home *** CD-ROM | disk | FTP | other *** search
/ kermit.columbia.edu / kermit.columbia.edu.tar / kermit.columbia.edu / test / tar / x30.tar.gz / x30.tar / ckutio.c < prev    next >
C/C++ Source or Header  |  2010-03-16  |  454KB  |  16,003 lines

  1. #define CKUTIO_C
  2.  
  3. #ifdef aegis
  4. char *ckxv = "Aegis Communications support, 9.0.320, 16 Mar 2010";
  5. #else
  6. #ifdef Plan9
  7. char *ckxv = "Plan 9 Communications support, 9.0.320, 16 Mar 2010";
  8. #else
  9. char *ckxv = "UNIX Communications support, 9.0.320, 16 Mar 2010";
  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, 2010,
  22.     Trustees of Columbia University in the City of New York.
  23.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  24.     copyright text in the ckcmai.c module for disclaimer and permissions.
  25. */
  26.  
  27. /*
  28.   NOTE TO CONTRIBUTORS: This file, and all the other C-Kermit files, must be
  29.   compatible with C preprocessors that support only #ifdef, #else, #endif,
  30.   #define, and #undef.  Please do not use #if, logical operators, or other
  31.   preprocessor features in any of the portable C-Kermit modules.  You can,
  32.   of course, use these constructions in platform-specific modules when they
  33.   are supported by all compilers/preprocessors that could be used on that
  34.   platform.
  35. */
  36.  
  37. extern int nettype;            /* Defined in ckcmai.c */
  38. extern int duplex;
  39.  
  40. /* Includes */
  41.  
  42. #include "ckcsym.h"            /* This must go first   */
  43. #include "ckcdeb.h"            /* This must go second  */
  44.  
  45. #ifdef OSF13
  46. #ifdef CK_ANSIC
  47. #ifdef _NO_PROTO
  48. #undef _NO_PROTO
  49. #endif /* _NO_PROTO */
  50. #endif /* CK_ANSIC */
  51. #endif /* OSF13 */
  52.  
  53. #include <errno.h>            /* System error numbers */
  54.  
  55. #ifdef __386BSD__
  56. #define ENOTCONN 57
  57. #else
  58. #ifdef __bsdi__
  59. #define ENOTCONN 57
  60. #else
  61. #ifdef __FreeBSD__
  62. #define ENOTCONN 57
  63. #endif /* __FreeBSD__ */
  64. #endif /* __bsdi__ */
  65. #endif /* __386BSD__ */
  66.  
  67. #ifdef SCO_OSR504
  68. #define NBBY 8
  69. #endif /* SCO_OSR504 */
  70.  
  71. #ifdef Plan9
  72. #define SELECT
  73. #include <sys/time.h>
  74. #include <select.h>
  75. #define FD_SETSIZE (3 * sizeof(long) * 8)
  76. static struct timeval tv;
  77. #endif /* Plan9 */
  78.  
  79. #ifdef CLIX
  80. #include <sys/time.h>
  81. #endif /* CLIX */
  82.  
  83. #include "ckcnet.h"            /* Symbols for network types. */
  84. #ifdef CK_SSL
  85. #include "ck_ssl.h"
  86. #endif /* CK_SSL */
  87.  
  88. /*
  89.   The directory-related includes are here because we need to test some
  90.   file-system-related symbols to find out which system we're being compiled
  91.   under.  For example, MAXNAMLEN is defined in BSD4.2 but not 4.1.
  92. */
  93. #ifdef SDIRENT                /* Directory bits... */
  94. #define DIRENT
  95. #endif /* SDIRENT */
  96.  
  97. #ifdef XNDIR
  98. #include <sys/ndir.h>
  99. #else /* !XNDIR */
  100. #ifdef NDIR
  101. #include <ndir.h>
  102. #else /* !NDIR, !XNDIR */
  103. #ifdef RTU
  104. #include "/usr/lib/ndir.h"
  105. #else /* !RTU, !NDIR, !XNDIR */
  106. #ifdef DIRENT
  107. #ifdef SDIRENT
  108. #include <sys/dirent.h>
  109. #else
  110. #include <dirent.h>
  111. #endif /* SDIRENT */
  112. #else /* !RTU, !NDIR, !XNDIR, !DIRENT, i.e. all others */
  113. #include <sys/dir.h>
  114. #endif /* DIRENT */
  115. #endif /* RTU */
  116. #endif /* NDIR */
  117. #endif /* XNDIR */
  118.  
  119. #ifdef QNX
  120. #include <sys/dev.h>
  121. #endif /* QNX */
  122.  
  123. #ifdef HPUX5
  124. #ifndef TCPSOCKET
  125. /* I don't know why this is needed here since we never reference bzero(). */
  126. /* But without it C-Kermit won't link in an HP-UX 5.xx non-TCP build. */
  127. void
  128. bzero(s,n) char *s; int n; {
  129.     extern char * memset();
  130.     memset(s,0,n);
  131. }
  132. #endif /* TCPSOCKET */
  133. #endif /* HPUX5 */
  134.  
  135. /* Definition of HZ, used in msleep() */
  136.  
  137. #ifdef MIPS
  138. #define HZ ( 1000 / CLOCK_TICK )
  139. #else  /* MIPS */
  140. #ifdef ATTSV
  141. #ifndef NAP
  142. #ifdef TRS16
  143. #define HZ ( 1000 / CLOCK_TICK )
  144. #endif /* TRS16 */
  145. #ifdef NAPHACK
  146. #define nap(x) (void)syscall(3112, (x))
  147. #define NAP
  148. #endif /* NAPHACK */
  149. #endif /* NAP */
  150. #endif /* ATTSV */
  151. #endif /* MIPS */
  152.  
  153. #ifdef M_UNIX
  154. #undef NGROUPS_MAX        /* Prevent multiple definition warnings */
  155. #endif /* M_UNIX */
  156.  
  157. /*
  158.   NOTE: HP-UX 8.0 has a <sys/poll.h>, but there is no corresponding
  159.   library routine, so _poll comes up undefined at link time.
  160. */
  161. #ifdef CK_POLL
  162. #ifndef AIXRS            /* IBM AIX needs special handling */
  163. #include <poll.h>        /* "standard" (SVID) i/o multiplexing, etc */
  164. #else /* AIXRS */
  165. #ifdef SVR4            /* AIX 3.2 is like SVID... */
  166. #include <poll.h>
  167. #else                /* But AIX 3.1 is not ... */
  168. #include <sys/poll.h>        /* The include file is in include/sys */
  169. #define events reqevents    /* And it does not map IBM-specific member */
  170. #define revents rtnevents    /* names to the System V equivalents */
  171. #endif /* SVR4 */
  172. #endif /* AIXRS */
  173. #endif /* CK_POLL */
  174.  
  175. #include <signal.h>                     /* Signals */
  176.  
  177. /* For setjmp and longjmp */
  178.  
  179. #ifndef ZILOG
  180. #include <setjmp.h>
  181. #else
  182. #include <setret.h>
  183. #endif /* ZILOG */
  184.  
  185. /*
  186.   The following test differentiates between 4.1 BSD and 4.2 & later.
  187.   If you have a 4.1BSD system with the DIRENT library, this test could
  188.   mistakenly diagnose 4.2BSD and then later enable the use of system calls
  189.   that aren't defined.  If indeed there are such systems, we can use some
  190.   other way of testing for 4.1BSD, or add yet another compile-time switch.
  191. */
  192. #ifdef BSD4
  193. #ifdef MAXNAMLEN
  194. #ifndef FT21                /* Except for Fortune. */
  195. #ifndef FT18
  196. #ifndef BELLV10                /* And Bell Labs Research UNIX V10 */
  197. #define BSD42
  198. #endif /* BELLV10 */
  199. #endif /* FT18 */
  200. #endif /* FT21 */
  201. #endif /* MAXNAMLEN */
  202. #endif /* BSD4 */
  203.  
  204. #ifdef SUNOS41                /* From Christian Corti */
  205. #define BSD44ORPOSIX            /* Uni Stuttgart */
  206. #define SVORPOSIX            /* February 2010 */
  207. #include <termios.h>
  208. #include <sys/ioctl.h>
  209. #include <unistd.h>
  210. #include <limits.h>
  211. #endif    /* SUNOS41 */
  212.  
  213. /*
  214.   Minix 2.0 support added by Terry McConnell,
  215.   Syracuse University <tmc@barnyard.syr.edu>
  216.   No more sgtty interface, posix compliant.
  217. */
  218. #ifdef MINIX2
  219. #define _MINIX   /* Needed for some Minix header files */
  220. #define BSD44ORPOSIX
  221. #define SVORPOSIX
  222. #ifndef MINIX3
  223. #define DCLTIMEVAL
  224. #endif    /* MINIX3 */
  225. #define NOFILEH
  226. #include <sys/types.h>
  227. #include <sys/ioctl.h>
  228. #include <termios.h>
  229. #include <limits.h>
  230. #undef TIOCGETC    /* defined in sys/ioctl.h, but not really supported */
  231. #define TANDEM 0
  232. #endif /* MINIX2 */
  233.  
  234. /*
  235.  MINIX 1.0 support added by Charles Hedrick,
  236.  Rutgers University <hedrick@aramis.rutgers.edu>.
  237.  MINIX also has V7 enabled.
  238. */
  239. #ifdef MINIX
  240. #define TANDEM 0
  241. #define MYREAD
  242. #define NOSYSIOCTLH
  243. #include <limits.h>
  244. #endif /* MINIX */
  245.  
  246. #ifdef CK_REDIR        /* <sys/wait.h> needed only for REDIRECT command. */
  247. /*
  248.   If anybody can figure out how to make this work with NeXTSTEP, be
  249.   my guest!  (NeXTBlah/NeXTBlah/bsd/sys/wait.h does not define WEXITSTATUS)
  250. */
  251. #ifndef CK_WAIT_H            /* If wait.h not already included... */
  252. #ifdef OSF                /* force OSF to select POSIX wait */
  253. #ifdef _BSD                /* instead of BSD (see ckcdeb.h) */
  254. #define CK_OSF_BSD
  255. #undef _BSD
  256. #endif /* _BSD */
  257. #endif /* OSF */
  258. #include <sys/wait.h>            /* Include it */
  259. #ifdef OSF
  260. #ifdef CK_OSF_BSD
  261. #define _BSD                /* Restore it */
  262. #undef CK_OSF_BSD
  263. #endif /* CK_OSF_BSD */
  264. #endif /* OSF */
  265. #endif /* CK_WAIT_H */
  266. #endif /* CK_REDIR */
  267.  
  268. #include "ckuver.h"            /* Version herald */
  269. char *ckxsys = HERALD;
  270.  
  271. #ifdef CK_UTSNAME
  272. #include <sys/utsname.h>
  273.  
  274. #ifdef TRU64                /* Tru64 UNIX 4.0 and later */
  275. /* Verified on Tru64 4.0F - might break on 4.0E or earlier */
  276. #include <sys/sysinfo.h>        /* (don't know about OSF/1 or DU) */
  277. #include <machine/hal_sysinfo.h>
  278. #endif /* TRU64 */
  279.  
  280. #ifdef SOLARIS25            /* Solaris 2.5 and later */
  281. #include <sys/systeminfo.h>        /* (don't know about earlier ones) */
  282. #endif /* SOLARIS25 */
  283.  
  284. #ifdef UW7
  285. #ifndef SYS_NMLN
  286. #define SYS_NMLN 257
  287. #endif /* NMLN */
  288. #endif /* UW7 */
  289. #ifdef HPUX9PLUS
  290. static int hpis800 = 0;
  291. #endif /* HPUX9PLUS */
  292. #ifdef SYS_NMLN
  293. #define CK_SYSNMLN SYS_NMLN
  294. #else
  295. #ifdef _SYS_NMLN
  296. #define CK_SYSNMLN _SYS_NMLN
  297. #else
  298. #ifdef UTSLEN
  299. #define CK_SYSNMLN UTSLEN
  300. #else
  301. #define CK_SYSNMLN 31
  302. #endif /* UTSLEN */
  303. #endif /* _SYS_NMLN */
  304. #endif /* SYS_NMLN */
  305. char unm_mch[CK_SYSNMLN+1] = { '\0', '\0' };
  306. char unm_mod[CK_SYSNMLN+1] = { '\0', '\0' };
  307. char unm_nam[CK_SYSNMLN+1] = { '\0', '\0' };
  308. char unm_rel[CK_SYSNMLN+1] = { '\0', '\0' };
  309. char unm_ver[CK_SYSNMLN+1] = { '\0', '\0' };
  310. #endif /* CK_UTSNAME */
  311.  
  312. #ifdef CIE
  313. #include <stat.h>            /* For chasing symlinks, etc. */
  314. #else
  315. #include <sys/stat.h>
  316. #endif /* CIE */
  317.  
  318. /* UUCP lockfile material... */
  319.  
  320. #ifndef NOUUCP
  321. #ifdef USETTYLOCK
  322. #ifdef HAVE_BAUDBOY            /* Red Hat baudboy/lockdev */
  323. /*
  324.   Watch out: baudboy.h references open() without making sure it has been
  325.   declared, resulting in warnings on at least Red Hat 7.3.  It's declared in
  326.   fcntl.h, but we don't include that until later.  In this case only, we
  327.   include it here, and then the second include is harmless because in Red Hat
  328.   Linux (the only place where you find baudboy.h) fcntl.h is protected from
  329.   multiple inclusion by _FCNTL_H.   - fdc, 10 May 2004.
  330.  
  331.   NOTE: Although Linux /usr/sbin/lockdev obviates the need for setuid or
  332.   setgid bits to access the lockfile, C-Kermit will still need them to access
  333.   the serial port itself unless the port is open for world read/write.
  334.   Normally setgid uucp does the trick.
  335.  
  336.  */
  337. #include <fcntl.h>            /* This has to come before baudboy */
  338. #include <baudboy.h>
  339. #define LOCK_DIR "/var/lock"        /* (even though we don't care) */
  340.  
  341. #else  /* !HAVE_BAUDBOY */
  342.  
  343. #ifdef USE_UU_LOCK
  344. #ifdef __FreeBSD__
  345. #include <libutil.h>            /* FreeBSD */
  346. #else
  347. #include <util.h>            /* OpenBSD */
  348. #endif /* HAVE_BAUDBOY */
  349. #endif /* __FreeBSD */
  350. #endif /* USE_UU_LOCK */
  351. #else  /* USETTYLOCK */
  352.  
  353. /* Name of UUCP tty device lockfile */
  354.  
  355. #ifdef LINUXFSSTND
  356. #ifndef HDBUUCP
  357. #define HDBUUCP
  358. #endif /* HDBUUCP */
  359. #endif /* LINUXFSSTND */
  360.  
  361. #ifdef ACUCNTRL
  362. #define LCKDIR
  363. #endif /* ACUCNTRL */
  364.  
  365. /*
  366.   PIDSTRING means use ASCII string to represent pid in lockfile.
  367. */
  368. #ifndef PIDSTRING
  369. #ifdef HDBUUCP
  370. #define PIDSTRING
  371. #else
  372. #ifdef BSD44
  373. #define PIDSTRING
  374. #else
  375. #ifdef RTAIX
  376. #define PIDSTRING
  377. #else
  378. #ifdef AIXRS
  379. #define PIDSTRING
  380. #else
  381. #ifdef COHERENT
  382. #define PIDSTRING
  383. #endif /* COHERENT */
  384. #endif /* AIXRS */
  385. #endif /* RTAIX */
  386. #endif /* BSD44 */
  387. #endif /* HDBUUCP */
  388. #endif /* PIDSTRING */
  389.  
  390. /* Now the PIDSTRING exceptions... */
  391.  
  392. #ifdef PIDSTRING
  393. #ifdef HPUX
  394. #undef PIDSTRING
  395. #endif /* HPUX */
  396. #endif /* PIDSTRING */
  397.  
  398. #ifdef __bsdi__                /* BSDI (at least thru 1.1) */
  399. #ifdef PIDSTRING
  400. #undef PIDSTRING
  401. #endif /* PIDSTRING */
  402. #endif /* __bsdi__ */
  403.  
  404. #ifdef OSF32                /* Digital UNIX (OSF/1) 3.2 */
  405. #ifdef PIDSTRING
  406. #undef PIDSTRING
  407. #endif /* PIDSTRING */
  408. #endif /* OSF32 */
  409.  
  410. /*
  411.   LOCK_DIR is the name of the lockfile directory.
  412.   If LOCK_DIR is already defined (e.g. on command line), we don't change it.
  413. */
  414.  
  415. #ifndef LOCK_DIR
  416. #ifdef MACOSX
  417. #define LOCK_DIR "/var/spool/lock"
  418. #endif /* MACOSX */
  419. #endif/* LOCK_DIR */
  420.  
  421. #ifndef LOCK_DIR
  422. #ifdef BSD44
  423. #ifdef __386BSD__
  424. #define LOCK_DIR "/var/spool/lock"
  425. #else
  426. #ifdef __FreeBSD__
  427. #define LOCK_DIR "/var/spool/lock"
  428. #else
  429. #ifdef __NetBSD__
  430. #define LOCK_DIR "/var/spool/lock"
  431. #else
  432. #ifdef __OpenBSD__
  433. #define LOCK_DIR "/var/spool/lock"
  434. #else
  435. /* So which ones is this for? */
  436. /* Probably original 4.4BSD on Vangogh */
  437. /* Plus who knows about Mac OS X... It doesn't even have a cu program */
  438. #define LOCK_DIR "/var/spool/uucp"
  439. #endif /* __OpenBSD__ */
  440. #endif /* __NetBSD__ */
  441. #endif /* __FreeBSD__ */
  442. #endif /* __386BSD__ */
  443. #else
  444. #ifdef DGUX430
  445. #define LOCK_DIR "/var/spool/locks"
  446. #else
  447. #ifdef HPUX10
  448. #define LOCK_DIR "/var/spool/locks"
  449. #else
  450. #ifdef RTAIX                /* IBM RT PC AIX 2.2.1 */
  451. #define LOCK_DIR "/etc/locks"
  452. #else
  453. #ifdef AIXRS
  454. #define LOCK_DIR "/etc/locks"
  455. #else
  456. #ifdef ISIII
  457. #define LOCK_DIR "/etc/locks"
  458. #else
  459. #ifdef HDBUUCP
  460. #ifdef M_SYS5
  461. #define LOCK_DIR "/usr/spool/uucp"
  462. #else
  463. #ifdef M_UNIX
  464. #define LOCK_DIR "/usr/spool/uucp"
  465. #else
  466. #ifdef SVR4
  467. #define LOCK_DIR "/var/spool/locks"
  468. #else
  469. #ifdef SUNOS4
  470. #define LOCK_DIR "/var/spool/locks"
  471. #else
  472. #ifdef LINUXFSSTND
  473. #define LOCK_DIR "/var/lock";
  474. #else
  475. #define LOCK_DIR "/usr/spool/locks"
  476. #endif /* LINUXFSSTND */
  477. #endif /* SUNOS4 */
  478. #endif /* SVR4 */
  479. #endif /* M_UNIX */
  480. #endif /* M_SYS5 */
  481. #else
  482. #ifdef LCKDIR
  483. #define LOCK_DIR "/usr/spool/uucp/LCK"
  484. #else
  485. #ifdef COHERENT
  486. #define LOCK_DIR "/usr/spool/uucp"
  487. #else
  488. #define LOCK_DIR "/usr/spool/uucp"
  489. #endif /* COHERENT */
  490. #endif /* LCKDIR */
  491. #endif /* HDBUUCP */
  492. #endif /* ISIII */
  493. #endif /* AIXRS */
  494. #endif /* RTAIX */
  495. #endif /* HPUX10 */
  496. #endif /* DGUX430 */
  497. #endif /* BSD44 */
  498. #endif /* !LOCK_DIR (outside ifndef) */
  499.  
  500. #ifdef OSF2                /* OSF/1 2.0 or later */
  501. #ifdef LOCK_DIR                /* (maybe 1.x too, who knows...) */
  502. #undef LOCK_DIR
  503. #define LOCK_DIR "/var/spool/locks"
  504. #endif /* LOCK_DIR */
  505. #endif /* OSF2 */
  506.  
  507. #ifdef COMMENT
  508. /* Sorry no more lockf() -- we lock first and THEN open the device. */
  509. #ifdef SVR4
  510. #ifndef BSD44
  511. #ifndef LOCKF
  512. #define LOCKF                /* Use lockf() on tty device in SVR4 */
  513. #endif /* LOCKF */
  514. #endif /* BSD44 */
  515. #endif /* SVR4 */
  516. #endif /* COMMENT */
  517.  
  518. #ifdef NOLOCKF                /* But NOLOCKF cancels LOCKF */
  519. #ifdef LOCKF
  520. #undef LOCKF
  521. #endif /* LOCKF */
  522. #endif /* NOLOCKF */
  523.  
  524. /* More about this below... */
  525.  
  526. #endif /* USETTYLOCK */
  527. #endif /* NOUUCP */
  528.  
  529. /*
  530.   MYREAD means use our internally defined nonblocking buffered read routine.
  531. */
  532. #ifdef ATTSV
  533. #define MYREAD
  534. #endif /* ATTSV */
  535.  
  536. #ifdef ATT7300
  537. #ifndef MYREAD
  538. #define MYREAD
  539. #endif /* MYREAD */
  540. /* bits for attmodem: internal modem in use, restart getty */
  541. #define ISMODEM 1
  542. #define DOGETY 512
  543. #endif  /* ATT7300 */
  544.  
  545. #ifdef BSD42
  546. #define MYREAD
  547. #endif /* BSD42 */
  548.  
  549. #ifdef POSIX
  550. #define MYREAD
  551. #endif /* POSIX */
  552. #ifdef __bsdi__
  553. #ifndef O_NDELAY
  554. #define O_NDELAY O_NONBLOCK
  555. #endif /* O_NDELAY */
  556. #endif /* __bsdi__ */
  557.  
  558. /*
  559.  Variables available to outside world:
  560.  
  561.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  562.    dfloc  -- 0 if dftty is console, 1 if external line.
  563.    dfprty -- Default parity
  564.    dfflow -- Default flow control
  565.    ckxech -- Flag for who echoes console typein:
  566.      1 - The program (system echo is turned off)
  567.      0 - The system (or front end, or terminal).
  568.    functions that want to do their own echoing should check this flag
  569.    before doing so.
  570.  
  571.    flfnam  -- Name of lock file, including its path, e.g.,
  572.                 "/usr/spool/uucp/LCK..cul0" or "/etc/locks/tty77"
  573.    lkflfn  -- Name of link to lock file, including its paths
  574.    haslock -- Flag set if this kermit established a uucp lock.
  575.    lockpid -- PID of other process that has desired line open, as string.
  576.    backgrd -- Flag indicating program executing in background ( & on
  577.                 end of shell command). Used to ignore INT and QUIT signals.
  578.    rtu_bug -- Set by stptrap().  RTU treats ^Z as EOF (but only when we handle
  579.                 SIGTSTP)
  580.  
  581.  Functions for assigned communication line (either external or console tty):
  582.  
  583.    sysinit()               -- System dependent program initialization
  584.    syscleanup()            -- System dependent program shutdown
  585.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  586.    ttclos()                -- Close & reset the tty, releasing any access lock.
  587.    ttsspd(cps)             -- Set the transmission speed of the tty.
  588.    ttgspd()                -- Get (read) the the transmission speed of the tty.
  589.    ttpkt(speed,flow,parity) -- Put the tty in packet mode and set the speed.
  590.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  591.                                 or in DIALING or CONNECTED modem control state.
  592.    ttres()                 -- Restore original tty modes.
  593.    ttscarr(carrier)        -- Set carrier control mode, on/off/auto.
  594.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  595.    ttinc(timo)             -- Timed read character from tty.
  596.    myread()                -- Raw mode bulk buffer read, gives subsequent
  597.                                 chars one at a time and simulates FIONREAD.
  598.    myunrd(c)               -- Places c back in buffer to be read (one only)
  599.    ttchk()                 -- See how many characters in tty input buffer.
  600.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  601.    ttol(string,length)     -- Write a string to the tty.
  602.    ttoc(c)                 -- Write a character to the tty.
  603.    ttflui()                -- Flush tty input buffer.
  604.    ttsndb()                -- Send BREAK signal.
  605.    ttsndlb()               -- Send Long BREAK signal.
  606.  
  607.    ttlock(ttname)          -- "Lock" tty device against uucp collisions.
  608.    ttunlck()               -- Unlock tty device.
  609.  
  610.                               For ATT7300/Unix PC, System V:
  611.    attdial(ttname,speed,telnbr) -- dials ATT7300/Unix PC internal modem
  612.    offgetty(ttname)        -- Turns off getty(1m) for comms line
  613.    ongetty(ttname)         -- Restores getty() to comms line
  614. */
  615.  
  616. /*
  617. Functions for console terminal:
  618.  
  619.    congm()   -- Get console terminal modes.
  620.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  621.    conbin(esc) -- Put the console in binary (raw) mode.
  622.    conres()  -- Restore the console to mode obtained by congm().
  623.    conoc(c)  -- Unbuffered output, one character to console.
  624.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  625.    conola(s) -- Unbuffered output, array of strings to the console.
  626.    conxo(n,s) -- Unbuffered output, n characters to the console.
  627.    conchk()  -- Check if characters available at console (bsd 4.2).
  628.                 Check if escape char (^\) typed at console (System III/V).
  629.    coninc(timo)  -- Timed get a character from the console.
  630.    congks(timo)  -- Timed get keyboard scan code.
  631.    conint()  -- Enable terminal interrupts on the console if not background.
  632.    connoi()  -- Disable terminal interrupts on the console if not background.
  633.  
  634. Time functions
  635.  
  636.    msleep(m) -- Millisecond sleep
  637.    ztime(&s) -- Return pointer to date/time string
  638.    rtimer() --  Reset timer
  639.    gtimer()  -- Get elapsed time since last call to rtimer()
  640. */
  641.  
  642. /* Conditional Includes */
  643.  
  644. /* Whether to include <sys/file.h> */
  645.  
  646. #ifdef RTU                /* RTU doesn't */
  647. #define NOFILEH
  648. #endif /* RTU */
  649.  
  650. #ifdef CIE                /* CIE does. */
  651. #undef NOFILEH
  652. #endif /* CIE */
  653.  
  654. #ifdef BSD41                /* 4.1 BSD doesn't */
  655. #define NOFILEH
  656. #endif /* BSD41 */
  657.  
  658. #ifdef is68k                /* Integrated Solutions 68000 UNIX  */
  659. #define NOFILEH                /* e.g. on Plexux P60 and Sun-1 */
  660. #endif /* is68k */
  661.  
  662. #ifdef MINIX                /* MINIX */
  663. #define NOFILEH
  664. #endif /* MINIX */
  665.  
  666. #ifdef COHERENT                /* Coherent */
  667. #define NOFILEH
  668. #endif /* COHERENT */
  669.  
  670. #ifndef NOFILEH                /* Now include if selected. */
  671. #include <sys/file.h>
  672. #endif /* NOFILEH */
  673.  
  674. /* POSIX */
  675.  
  676. #ifdef BSD44ORPOSIX            /* POSIX uses termios.h */
  677. #define TERMIOS
  678. #ifdef __bsdi__
  679. #ifdef POSIX
  680. #undef _POSIX_SOURCE            /* Get extra stuff from termios.h */
  681. #endif /* POSIX */
  682. #endif /* __bsdi__ */
  683. #include <termios.h>
  684. #ifdef LINUX
  685. #include <sys/ioctl.h>
  686. #endif /* LINUX */
  687. #ifdef QNX16
  688. #include <ioctl.h>
  689. #else
  690. #ifdef QNX6
  691. #include <ioctl.h>
  692. #endif /* QNX6 */
  693. #endif /* QNX16 */
  694. #ifdef __bsdi__
  695. #ifdef POSIX
  696. #define _POSIX_SOURCE
  697. #endif /* POSIX */
  698. #endif /* __bsdi__ */
  699. #ifndef BSD44                /* Really POSIX */
  700. #ifndef CK_QNX32            /* was CK_QNX32 */
  701. #define NOSYSIOCTLH            /* No ioctl's allowed. */
  702. #undef ultrix                /* Turn off any ultrix features. */
  703. #endif /* CK_QNX32 */
  704. #endif /* BSD44 */
  705. #endif /* POSIX */
  706.  
  707. /* System III, System V */
  708.  
  709. #ifdef ATTSV
  710. #ifndef BSD44
  711. #ifndef POSIX
  712. #include <termio.h>
  713. #endif /* POSIX */
  714. #endif /* BSD44 */
  715. #ifdef TERMIOX
  716. /* Need this for termiox structure, RTS/CTS and DTR/CD flow control */
  717. #include <termiox.h>
  718.   struct termiox rctsx;
  719. #else
  720. #ifdef STERMIOX
  721. #ifdef SCO_OSR504
  722. /* Sorry, this is truly disgusting but it's SCO's fault. */
  723. #ifndef _SVID3
  724. #define _CK_SVID3_X
  725. #define _SVID3
  726. #endif /* _SVID3 */
  727. #endif /* SCO_OSR504 */
  728. #include <sys/termiox.h>
  729.   struct termiox rctsx;
  730. #ifdef CK_SVID3_X
  731. #undef _SVID3
  732. #undef CK_SVID3_X
  733. #endif /* CK_SVID3_X */
  734. #endif /* STERMIOX */
  735. #endif /* TERMIOX */
  736. #endif /* ATTSV */
  737.  
  738. #ifdef COHERENT            /* Use termio.h, not sgtty.h for Coherent */
  739. #include <termio.h>
  740. #endif /* COHERENT */
  741.  
  742. #ifdef MINIX                /* MINIX uses ioctl's */
  743. #define NOSYSIOCTLH            /* but has no <sys/ioctl.h> */
  744. #endif /* MINIX */
  745.  
  746. /* Others */
  747.  
  748. #ifndef NOSYSIOCTLH            /* Others use ioctl() */
  749. #ifdef SUN4S5
  750. /*
  751.   This is to get rid of cpp warning messages that occur because all of
  752.   these symbols are defined by both termios.h and ioctl.h on the SUN.
  753. */
  754. #undef ECHO
  755. #undef NL0
  756. #undef NL1
  757. #undef TAB0
  758. #undef TAB1
  759. #undef TAB2
  760. #undef XTABS
  761. #undef CR0
  762. #undef CR1
  763. #undef CR2
  764. #undef CR3
  765. #undef FF0
  766. #undef FF1
  767. #undef BS0
  768. #undef BS1
  769. #undef TOSTOP
  770. #undef FLUSHO
  771. #undef PENDIN
  772. #undef NOFLSH
  773. #endif /* SUN4S5 */
  774. #include <sys/ioctl.h>
  775. #endif /* NOSYSIOCTLH */
  776. /*
  777.   We really, really, REALLY want FIONREAD, because it is the only way to find
  778.   out not just *if* stuff is waiting to be read, but how much, which is
  779.   critical to our sliding-window and streaming procedures, not to mention
  780.   efficiency of CONNECT, etc.
  781. */
  782. #ifdef BELLV10
  783. #include <sys/filio.h>            /* For FIONREAD */
  784. #ifdef FIONREAD
  785. #define MYREAD
  786. #endif /* MYREAD */
  787. #endif /* BELLV10 */
  788.  
  789. #ifndef FIONREAD
  790. /* It wasn't found in ioctl.h or term*.h - try these places: */
  791. #ifdef UNIXWARE
  792. #include <sys/filio.h>
  793. #else
  794. #ifdef SOLARIS
  795. #include <sys/filio.h>
  796. #endif /* SOLARIS */
  797. #endif /* UNIXWARE */
  798. #endif /* FIONREAD */
  799.  
  800. #ifdef XENIX /* Was M_UNIX but XENIX implies M_UNIX and applies to XENIX too */
  801. /*
  802.   <sys/socket.h> included above via "ckcnet.h" defines FIONREAD as
  803.   something.  Due to this, in_chk() uses the FIONREAD instead of RDCHK
  804.   and the hot keys during file transfer (X to cancel file etc) do not
  805.   work because FIONREAD doesn't work even though it is defined.
  806.  
  807.   NOTE: This might also be true elsewhere.
  808. */
  809. #ifdef FIONREAD
  810. #undef FIONREAD
  811. #endif /* FIONREAD */
  812. #endif /* XENIX */
  813.  
  814. #ifdef CK_SCOV5                /* Ditto for SCO OpenServer 5.0 */
  815. #ifdef FIONREAD
  816. #undef FIONREAD
  817. #endif /* FIONREAD */
  818. #endif /* XENIX */
  819.  
  820. /* Whether to include <fcntl.h> */
  821.  
  822. #ifndef is68k                /* Only a few don't have this one. */
  823. #ifndef BSD41
  824. #ifndef FT21
  825. #ifndef FT18
  826. #ifndef COHERENT
  827. #include <fcntl.h>
  828. #endif /* COHERENT */
  829. #endif /* FT18 */
  830. #endif /* FT21 */
  831. #endif /* BSD41 */
  832. #endif /* not is68k */
  833.  
  834. #ifdef COHERENT
  835. #ifdef _I386
  836. #include <fcntl.h>
  837. #else
  838. #include <sys/fcntl.h>
  839. #endif /* _I386 */
  840. #endif /* COHERENT */
  841.  
  842. #ifdef ATT7300                /* Unix PC, internal modem dialer */
  843. #include <sys/phone.h>
  844. #endif /* ATT7300 */
  845.  
  846. #ifdef HPUX                /* HP-UX variations. */
  847. #define HPUXJOBCTL
  848. #include <sys/modem.h>            /* HP-UX modem signals */
  849. #ifdef hp9000s500            /* Model 500 */
  850. #undef HPUXJOBCTL
  851. #endif /* hp9000s500 */
  852. #ifdef HPUXPRE65
  853. #undef HPUXJOBCTL
  854. typedef long mflag;
  855. #endif /* HPUXPRE65 */
  856. #ifdef HPUXJOBCTL
  857. #include <sys/bsdtty.h>            /* HP-UX Berkeley tty support */
  858. #endif /* HPUXJOBCTL */
  859. #endif /* HPUX */
  860.  
  861. /*
  862.   Which time.h files to include... See ckcdeb.h for defaults.
  863.   Note that 0, 1, 2, or all 3 of these can be included according to
  864.   the symbol definitions.
  865. */
  866. #ifndef NOTIMEH
  867. #ifdef TIMEH
  868. #include <time.h>
  869. #endif /* TIMEH */
  870. #endif /* NOTIMEH */
  871.  
  872. #ifndef NOSYSTIMEH
  873. #ifdef SYSTIMEH
  874. #include <sys/time.h>
  875. #endif /* SYSTIMEH */
  876. #endif /* NOSYSTIMEH */
  877.  
  878. #ifndef NOSYSTIMEBH
  879. #ifdef SYSTIMEBH
  880. #include <sys/timeb.h>
  881. #endif /* SYSTIMEBH */
  882. #endif /* NOSYSTIMEBH */
  883.  
  884. #ifndef NODCLTIMEVAL
  885. #ifdef DCLTIMEVAL
  886. /*
  887.   In certain POSIX builds (like Unixware 7), <[sys/]time.h> refuses to
  888.   define the structs we need to access the higher speeds, so we have to
  889.   do it ourselves.
  890. */
  891. struct timeval {
  892.     long tv_sec;
  893.     long tv_usec;
  894. };
  895. struct timezone {
  896.     int tz_minuteswest;
  897.     int tz_dsttime;
  898. };
  899. #endif /* DCLTIMEVAL */
  900. #endif /* NODCLTIMEVAL */
  901.  
  902. #ifdef __linux__
  903. /* THIS IS OBSOLETE since about Linux 0.92 */
  904. #ifdef OLINUXHISPEED
  905. #include <linux/serial.h>
  906. #endif /* OLINUXHISPEED */
  907. #ifdef __alpha__            /* Linux on DEC Alpha */
  908. #ifndef __GLIBC__            /* But not with glibc */
  909. #include <asm/termios.h>
  910. #endif /* __GLIBC__ */
  911. #endif /* __alpha__ */
  912. #endif /* __linux__ */
  913.  
  914. #ifdef NOIEXTEN                /* This is broken on some systems */
  915. #undef IEXTEN                /* like Convex/OS 9.1 */
  916. #endif /* NOIEXTEN */
  917. #ifndef IEXTEN                /* Turn off ^O/^V processing. */
  918. #define IEXTEN 0            /* Needed, at least, on BSDI. */
  919. #endif /* IEXTEN */
  920. /*
  921.   Pick up definitions needed for select() if we don't have them already.
  922.   Normally they come from <sys/types.h> but some systems get them from
  923.   <sys/select.h>...  Rather than hardwire all of them into the source, we
  924.   include it if SELECT_H is defined in compile-time CFLAGS.
  925. */
  926. #ifndef SCO_OSR504
  927. #ifdef SELECT_H
  928. #include <sys/select.h>
  929. #endif /* SELECT_H */
  930. #endif /* SCO_OSR504 */
  931.  
  932. #ifdef aegis
  933. #include "/sys/ins/base.ins.c"
  934. #include "/sys/ins/error.ins.c"
  935. #include "/sys/ins/ios.ins.c"
  936. #include "/sys/ins/sio.ins.c"
  937. #include "/sys/ins/pad.ins.c"
  938. #include "/sys/ins/time.ins.c"
  939. #include "/sys/ins/pfm.ins.c"
  940. #include "/sys/ins/pgm.ins.c"
  941. #include "/sys/ins/ec2.ins.c"
  942. #include "/sys/ins/type_uids.ins.c"
  943. #include <default_acl.h>
  944. #undef TIOCEXCL
  945. #undef FIONREAD
  946. #endif /* aegis */
  947.  
  948. #ifdef sxaE50                /* PFU Compact A SX/A TISP V10/L50 */
  949. #undef FIONREAD
  950. #endif /* sxaE50 */
  951.  
  952. /* The following #defines are catch-alls for those systems */
  953. /* that didn't have or couldn't find <file.h>... */
  954.  
  955. #ifndef FREAD
  956. #define FREAD 0x01
  957. #endif /* FREAD */
  958.  
  959. #ifndef FWRITE
  960. #define FWRITE 0x10
  961. #endif /* FWRITE */
  962.  
  963. #ifndef O_RDONLY
  964. #define O_RDONLY 000
  965. #endif /* O_RDONLY */
  966.  
  967. /* This is for ancient Unixes that don't have these tty symbols defined. */
  968.  
  969. #ifndef PENDIN
  970. #define PENDIN ICANON
  971. #endif /* PENDIN */
  972. #ifndef FLUSHO
  973. #define FLUSHO ICANON
  974. #endif /* FLUSHO */
  975. #ifndef EXTPROC
  976. #define EXTPROC ICANON
  977. #endif /* EXTPROC */
  978.  
  979. #ifdef SVORPOSIX
  980. /*
  981.   Modem signals are also forbidden in the POSIX world.  But some POSIX-based
  982.   platforms let us at them anyway if we know where to look.
  983. */
  984. #ifndef NEEDMDMDEFS
  985. /* Doesn't work for Linux */
  986. #ifdef UNIXWARE7
  987. #define NEEDMDMDEFS
  988. #endif /* UNIXWARE7 */
  989. #endif /* NEEDMDMDEFS */
  990.  
  991. #ifdef NEEDMDMDEFS
  992. #ifndef TIOCMGET
  993. #define TIOCMGET (('t'<<8)|29)
  994. #endif /* TIOCMGET */
  995.  
  996. #ifndef TIOCM_DTR
  997. #define TIOCM_DTR 0x0002
  998. #endif /* TIOCM_DTR */
  999. #ifndef TIOCM_RTS
  1000. #define TIOCM_RTS 0x0004
  1001. #endif /* TIOCM_RTS */
  1002. #ifndef TIOCM_CTS
  1003. #define TIOCM_CTS 0x0020
  1004. #endif /* TIOCM_CTS */
  1005. #ifndef TIOCM_CAR
  1006. #define TIOCM_CAR 0x0040
  1007. #endif /* TIOCM_CAR */
  1008. #ifndef TIOCM_RNG
  1009. #define TIOCM_RNG 0x0080
  1010. #endif /* TIOCM_RNG */
  1011. #ifndef TIOCM_DSR
  1012. #define TIOCM_DSR 0x0100
  1013. #endif /* TIOCM_DSR */
  1014. #endif /* NEEDMDMDEFS */
  1015. #endif /* SVORPOSIX */
  1016.  
  1017. /* Declarations */
  1018.  
  1019. #ifdef OXOS
  1020. #undef TCGETA
  1021. #undef TCSETA
  1022. #undef TCSETAW
  1023. #undef TCSETAF
  1024. #define TCGETA TCGETS
  1025. #define TCSETA TCSETS
  1026. #define TCSETAW TCSETSW
  1027. #define TCSETAF TCSETSF
  1028. #define termio termios
  1029. #endif /* OXOS */
  1030.  
  1031. #ifdef SVORPOSIX            /* AT&T Sys V or POSIX */
  1032. #ifdef UNIXWAREPOSIX            /* UnixWare 7 POSIX build */
  1033. /*
  1034.   In Unixware POSIX builds, <[sys/]time.h> refuses to define the
  1035.   structs we need to access the higher speeds, so we have to do it
  1036.   ourselves.
  1037. */
  1038. struct timeval {
  1039.     long tv_sec;
  1040.     long tv_usec;
  1041. };
  1042. struct timezone {
  1043.     int tz_minuteswest;
  1044.     int tz_dsttime;
  1045. };
  1046. #endif /* UNIXWAREPOSIX */
  1047. #endif /* SVORPOSIX */
  1048.  
  1049. #ifdef __GNUC__
  1050. #ifdef XENIX
  1051. /*
  1052.   Because Xenix <time.h> doesn't declare time() if we're using gcc.
  1053. */
  1054. time_t time();
  1055. #endif /* XENIX */
  1056. #endif /* __GNUC__ */
  1057.  
  1058. /* Special stuff for V7 input buffer peeking */
  1059.  
  1060. #ifdef  V7
  1061. int kmem[2] = { -1, -1};
  1062. char *initrawq(), *qaddr[2]={0,0};
  1063. #define CON 0
  1064. #define TTY 1
  1065. #endif /* V7 */
  1066.  
  1067. /* dftty is the device name of the default device for file transfer */
  1068. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  1069.  
  1070. #ifdef BEOS
  1071.     char * dftty = NULL;
  1072.     char * dfmdm = "none";
  1073.     int dfloc = 0;                  /* that goes in local mode by default */
  1074. #else
  1075. #ifndef DFTTY
  1076. #ifdef PROVX1
  1077.     char *dftty = "/dev/com1.dout"; /* Only example so far of a system */
  1078.     char *dfmdm = "none";
  1079.     int dfloc = 1;                  /* that goes in local mode by default */
  1080. #else
  1081.     char *dftty = CTTNAM;               /* Remote by default, use normal */
  1082.     char *dfmdm = "none";
  1083.     int dfloc = 0;                      /* controlling terminal name. */
  1084. #endif /* PROVX1 */
  1085. #else
  1086.     char *dftty = DFTTY;        /* Default location specified on */
  1087.     char *dfmdm = "none";        /* command line. */
  1088.     int dfloc = 1;                      /* controlling terminal name. */
  1089. #endif /* DFTTY */
  1090. #endif /* BEOS */
  1091.  
  1092. #define CON_RES 0            /* Console state is "reset" */
  1093. #define CON_CB  1            /* Console state is CBREAK */
  1094. #define CON_BIN 2            /* Console state is binary */
  1095.     static int constate = CON_RES;
  1096.  
  1097. #define CONI_RES 0            /* Console interrupts are "reset" */
  1098. #define CONI_INT 1            /* Console intterupts are set */
  1099. #define CONI_NOI 2            /* Console intterupts are disabled */
  1100.     static int conistate = CONI_RES;
  1101.  
  1102. #ifdef CK_SMALL
  1103. #define CONBUFSIZ 15
  1104. #else
  1105. #define CONBUFSIZ 255
  1106. #endif /* CK_SMALL */
  1107.     static char conbuf[CONBUFSIZ];    /* Console readahead buffer */
  1108.     static int  conbufn = 0;        /* Chars in readahead buffer */
  1109.     static char *conbufp = conbuf;    /* Next char in readahead buffer */
  1110.  
  1111.     char cttnam[DEVNAMLEN+1] = { '\0', '\0' }; /* Determined at runtime */
  1112.  
  1113. #ifdef RTU
  1114.     int rtu_bug = 0;            /* set to 1 when returning from SIGTSTP */
  1115. #endif /* RTU */
  1116.  
  1117.     int dfprty = DEFPAR;                /* Default parity (0 = none) */
  1118.     int ttprty = 0;                     /* The parity that is in use. */
  1119.     static int ttpmsk = 0xff;        /* Parity stripping mask. */
  1120.     int ttmdm = 0;                      /* Modem in use. */
  1121.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  1122.     int dfflow = FLO_NONE;        /* Default flow control is NONE */
  1123.     int backgrd = 0;                    /* Assume in foreground (no '&' ) */
  1124. #ifdef F_SETFL
  1125.     int iniflags = -1;            /* fcntl flags for ttyfd */
  1126. #endif /* F_SETFL */
  1127.     int fdflag = 0;            /* Flag for redirected stdio */
  1128.     int ttfdflg = 0;            /* Open File descriptor was given */
  1129.     int tvtflg = 0;            /* Flag that ttvt has been called */
  1130.     long ttspeed = -1L;            /* For saving speed */
  1131.     int ttflow = -9;            /* For saving flow */
  1132.     int ttld = -1;            /* Line discipline */
  1133.  
  1134. #ifdef sony_news
  1135.     static int km_con = -1;        /* Kanji mode for console tty */
  1136.     static int km_ext = -1;        /* Kanji mode for external device */
  1137. #endif /* sony_news */
  1138.  
  1139. #ifdef PARSENSE
  1140.     static int needpchk = 1;        /* Need parity check */
  1141. #else
  1142.     static int needpchk = 0;
  1143. #endif /* PARSENSE */
  1144.  
  1145.     extern int stopbits;        /* Stop bits */
  1146. #ifdef HWPARITY
  1147. /*
  1148.   Unfortunately we must do this with global variables rather than through the
  1149.   tt...() APIs to avoid changing the APIs and the many modules that use them.
  1150.   If hwparity != 0, this indicates 8 data bits + parity, rather than 7 data
  1151.   bits + parity or 8 data bits and no parity, and overrides the regular parity
  1152.   variable, which is communicated to this module thru ttpkt(), and represented
  1153.   locally by the ttprty variable.
  1154. */
  1155.     extern int hwparity;        /* Hardware parity */
  1156. #endif /* HWPARITY */
  1157.  
  1158. #ifdef TCPSOCKET
  1159. #ifdef TCP_NODELAY
  1160. static int nodelay_sav = -1;
  1161. #endif /* TCP_NODELAY */
  1162. #endif /* TCPSOCKET */
  1163.  
  1164. static int sigint_ign = 0;        /* SIGINT is ignored */
  1165.  
  1166. /*
  1167.   Having this module rely on external globals is bad, but fixing this
  1168.   requires overhaul of the ck*tio.c modules for all the different operating
  1169.   systems supported by C-Kermit.  Left for a future release.
  1170. */
  1171. extern int ttnproto;            /* Defined in ckcnet.c */
  1172. extern int ttnet;            /* Defined in ckcnet.c */
  1173. extern int nopush, xfrcan, xfrchr, xfrnum; /* Defined in ckcmai.c */
  1174. extern int xsuspend, wasclosed;
  1175. extern int inserver, local;
  1176.  
  1177. int ckxech = 0; /* 0 if system normally echoes console characters, else 1 */
  1178.  
  1179. int ckmaxfiles = 0;            /* Max number of open files */
  1180.  
  1181. #ifdef CK_ENCRYPTION            /* Kerberos */
  1182. #include "ckuath.h"
  1183. extern int me_encrypt, u_encrypt;
  1184. #endif /* CK_ENCRYPTION */
  1185.  
  1186. /* Declarations of variables global within this module */
  1187.  
  1188. #ifdef TTLEBUF                /* See ckcnet.h */
  1189. int ttpush = -1;
  1190. #define LEBUFSIZ 4096
  1191. static CHAR le_buf[LEBUFSIZ];
  1192. static int le_start = 0, le_end = 0, le_data = 0;
  1193. #endif /* TTLEBUF */
  1194.  
  1195. #define MSGBUF_SIZE 1024        /* For debugging */
  1196. static char msgbuf[MSGBUF_SIZE];
  1197.  
  1198. static int gotsigs = 0;
  1199.  
  1200. static time_t tcount = (time_t)0;    /* Elapsed time counter */
  1201.  
  1202. static SIGTYP (*saval)()     = NULL;    /* For saving alarm() handler */
  1203. static SIGTYP (*savquit)()   = NULL;    /* and other signal handlers */
  1204. #ifdef SIGUSR1
  1205. static SIGTYP (*savusr1)()   = NULL;
  1206. #endif /* SIGUSR1 */
  1207. #ifdef SIGUSR2
  1208. static SIGTYP (*savusr2)()   = NULL;
  1209. #endif /* SIGUSR2 */
  1210. #ifdef SIGPIPE
  1211. static SIGTYP (*savpipe)()   = NULL;
  1212. #endif /* SIGPIPE */
  1213. #ifdef SIGDANGER
  1214. static SIGTYP (*savdanger)() = NULL;
  1215. #endif /* SIGDANGER */
  1216.  
  1217. #ifndef NOJC
  1218. static SIGTYP (*jchdlr)()    = NULL;    /* For checking suspend handler */
  1219. #endif /* NOJC */
  1220. static int jcshell = -1;        /* And flag for result */
  1221.  
  1222. /*
  1223.   BREAKNULS is defined for systems that simulate sending a BREAK signal
  1224.   by sending a bunch of NUL characters at low speed.
  1225. */
  1226. #ifdef PROVX1
  1227. #ifndef BREAKNULS
  1228. #define BREAKNULS
  1229. #endif /* BREAKNULS */
  1230. #endif /* PROVX1 */
  1231.  
  1232. #ifdef V7
  1233. #ifndef BREAKNULS
  1234. #define BREAKNULS
  1235. #endif /* BREAKNULS */
  1236. #endif /* V7 */
  1237.  
  1238. #ifdef BREAKNULS
  1239. static char                /* A string of nulls */
  1240. *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";
  1241. #endif /* BREAKNULS */
  1242.  
  1243. #ifdef CK_POSIX_SIG            /* Longjump buffers */
  1244. static sigjmp_buf sjbuf;        /* POSIX signal handling */
  1245. #else
  1246. static jmp_buf sjbuf;
  1247. #endif /* CK_POSIX_SIG */
  1248.  
  1249. #ifdef V7
  1250. static jmp_buf jjbuf;
  1251. #endif /* V7 */
  1252.  
  1253. /* static */                /* (Not static any more) */
  1254. int ttyfd = -1;                /* TTY file descriptor */
  1255.  
  1256. int ttpipe = 0;                /* NETCMD: Use pipe instead of ttyfd */
  1257. int ttpty  = 0;                         /* NETPTY: Use pty instead of ttfyd */
  1258.  
  1259. #ifdef NETPTY                /* These are in ckupty.c */
  1260. extern PID_T pty_fork_pid;
  1261. extern int pty_master_fd, pty_slave_fd;
  1262. #endif    /* NETPTY */
  1263.  
  1264. #ifdef NETCMD
  1265. #ifdef NETCONN
  1266. static int pipe0[2], pipe1[2];        /* Pipes for net i/o */
  1267. #endif /* NETCONN */
  1268. static PID_T ttpid = 0;            /* Process ID for fork */
  1269. static int fdin, fdout;            /* File descriptors for pipe */
  1270. static FILE * ttout = NULL;        /* File pointer for output pipe */
  1271. #ifdef DCLFDOPEN
  1272. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  1273. _PROTOTYP( FILE * fdopen, (int, char *) );
  1274. #endif /* DCLFDOPEN */
  1275. #endif /* NETCMD */
  1276.  
  1277. extern int pexitstat, quiet;
  1278.  
  1279. #ifdef Plan9
  1280. int ttyctlfd  = -1;   /* TTY control channel - What? UNIX doesn't have one? */
  1281. int consctlfd = -1;            /* Console control channel */
  1282. int noisefd = -1;            /* tone channel */
  1283. static int ttylastspeed = -1;        /* So we can lie about the speed */
  1284. #endif /* Plan9 */
  1285.  
  1286. int telnetfd = 0;            /* File descriptor is for telnet */
  1287. #ifdef NETCONN
  1288. int x25fd = 0;                /* File descriptor is for X.25 */
  1289. #endif /* NETCONN */
  1290.  
  1291. char lockpid[16] = { '\0', '\0' };    /* PID stored in lockfile, as string */
  1292.  
  1293. static int lkf = 0,                     /* Line lock flag */
  1294.     cgmf = 0,                           /* Flag that console modes saved */
  1295.     xlocal = 0,                         /* Flag for tty local or remote */
  1296.     curcarr = 0;            /* Carrier mode: require/ignore. */
  1297.  
  1298. static int netconn = 0;            /* 1 if network connection active */
  1299.  
  1300. static char escchr;                     /* Escape or attn character */
  1301.  
  1302. #ifdef CK_SCO32V4
  1303. #include <sys/time.h>
  1304. #endif /* CK_SCO32V4 */
  1305.  
  1306. #ifdef HAVE_TV
  1307.     static struct timeval tv;        /* For getting time, from sys/time.h */
  1308. #endif /* HAVE_TV */
  1309. #ifdef HAVE_TZ
  1310.     static struct timezone tz;
  1311. #endif /* HAVE_TZ */
  1312.  
  1313. #ifdef OSF
  1314.     static struct timeb ftp;            /* And from sys/timeb.h */
  1315. #endif /* OSF */
  1316.  
  1317. #ifdef BSD29
  1318.     static long xclock;            /* For getting time from sys/time.h */
  1319.     static struct timeb ftp;            /* And from sys/timeb.h */
  1320. #endif /* BSD29 */
  1321.  
  1322. #ifdef BSD41
  1323.     static long xclock;            /* For getting time from sys/time.h */
  1324.     static struct timeb ftp;            /* And from sys/timeb.h */
  1325. #endif /* BSD41 */
  1326.  
  1327. #ifdef BELLV10
  1328.     static long xclock;            /* For getting time from sys/time.h */
  1329.     static struct timeb ftp;            /* And from sys/timeb.h */
  1330. #endif /* BELLV10 */
  1331.  
  1332. #ifdef FT21
  1333.     static long xclock;            /* For getting time from sys/time.h */
  1334.     static struct timeb ftp;            /* And from sys/timeb.h */
  1335. #endif /* FT21 */
  1336.  
  1337. #ifdef TOWER1
  1338.     static long xclock;            /* For getting time from sys/time.h */
  1339.     static struct timeb ftp;        /* And from sys/timeb.h */
  1340. #endif /* TOWER1 */
  1341.  
  1342. #ifdef COHERENT
  1343.     static long xclock;            /* For getting time from sys/time.h */
  1344.     static struct timeb ftp;        /* And from sys/timeb.h */
  1345. #endif /* COHERENT */
  1346.  
  1347. #ifdef V7
  1348.     static long xclock;
  1349. #endif /* V7 */
  1350.  
  1351. /* sgtty/termio information... */
  1352.  
  1353. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  1354.   static struct termios
  1355.     ttold, ttraw, tttvt, ttcur,
  1356.     ccold, ccraw, cccbrk;
  1357. #else                    /* BSD, V7, etc */
  1358.  
  1359. #ifdef COHERENT                /* Hack alert... */
  1360. #define ATTSV
  1361. #endif /* COHERENT */
  1362.  
  1363. #ifdef ATTSV
  1364.   static struct termio ttold = {0};    /* Init'd for word alignment, */
  1365.   static struct termio ttraw = {0};    /* which is important for some */
  1366.   static struct termio tttvt = {0};    /* systems, like Zilog... */
  1367.   static struct termio ttcur = {0};
  1368.   static struct termio ccold = {0};
  1369.   static struct termio ccraw = {0};
  1370.   static struct termio cccbrk = {0};
  1371. #else
  1372.   static struct sgttyb                  /* sgtty info... */
  1373.     ttold, ttraw, tttvt, ttcur,     /* for communication line */
  1374.     ccold, ccraw, cccbrk;        /* and for console */
  1375. #ifdef BELLV10
  1376.   static struct ttydevb            /* Device info... */
  1377.     tdold, tdcur;            /* for communication device */
  1378. #endif /* BELLV10 */
  1379. #ifdef TIOCGETC
  1380.   static struct tchars tchold, tchnoi;
  1381.  
  1382.   static int tcharf;
  1383. #endif /* TIOCGETC */
  1384. #ifdef TIOCGLTC
  1385.   static struct ltchars ltchold, ltchnoi;
  1386.   static int ltcharf;
  1387. #endif /* TIOCGLTC */
  1388.   int lmodef = 0;            /* Local modes */
  1389.   int lmode = 0;
  1390. #endif /* ATTSV */
  1391. #endif /* BSD44ORPOSIX */
  1392.  
  1393. #ifdef COMMENT
  1394. /* It picks up the speeds but they don't work */
  1395. #ifdef UNIXWARE                /* For higher serial speeds */
  1396. #ifdef UW7                /* in Unixware 7.0 */
  1397. #include <sys/asyc.h>            /* This picks up 57600 and 115200 */
  1398. #endif /* UW7 */
  1399. #endif /* UNIXWARE */
  1400. #endif /* COMMENT */
  1401.  
  1402. #ifdef PROVX1
  1403.   static struct sgttyb ttbuf;
  1404. #endif /* PROVX1 */
  1405.  
  1406. #ifdef ultrix
  1407. /* do we really need this? */
  1408.   static struct sgttyb vanilla;
  1409. #endif /* ultrix */
  1410.  
  1411. #ifdef ATT7300
  1412. static int attmodem = 0;                /* ATT7300 internal-modem status */
  1413. struct updata dialer = {0};        /* Condition dialer for data call */
  1414. #endif /* ATT7300 */
  1415.  
  1416. #ifndef NOUUCP
  1417. #define FLFNAML 128
  1418. #ifndef USETTYLOCK
  1419. #ifdef RTAIX
  1420. char lkflfn[FLFNAML] = { '\0', '\0' };    /* and possible link to it */
  1421. #endif /* RTAIX */
  1422. char lock2[FLFNAML] =  { '\0', '\0' };    /* Name of second lockfile */
  1423. #endif /* USETTYLOCK */
  1424. #else
  1425. #define FLFNAML 7
  1426. #endif /* NOUUCP */
  1427. char flfnam[FLFNAML+1] = { '\0', '\0' }; /* UUCP lock file path name */
  1428.  
  1429. int haslock = 0;            /* =1 if this kermit locked uucp */
  1430.  
  1431. #ifndef OXOS
  1432. #ifdef SVORPOSIX
  1433. static int conesc = 0;                  /* set to 1 if esc char (^\) typed */
  1434. #else
  1435. #ifdef V7
  1436. static int conesc = 0;
  1437. #else
  1438. #ifdef C70
  1439. static int conesc = 0;
  1440. #endif /* C70 */
  1441. #endif /* V7 */
  1442. #endif /* SVORPOSIX */
  1443. #endif /* OXOS */
  1444.  
  1445. /* Local copy of comm device name or network host */
  1446. static char ttnmsv[DEVNAMLEN+1] = { '\0', '\0' };
  1447. #ifdef USETTYLOCK
  1448. static char lockname[DEVNAMLEN+1];    /* Ditto, the part after "/dev/". */
  1449. #endif /* USETTYLOCK */
  1450.  
  1451. #ifdef aegis
  1452. static status_$t st;                    /* error status return value */
  1453. static short concrp = 0;                /* true if console is CRP pad */
  1454. static uid_$t ttyuid;                   /* tty type uid */
  1455. static uid_$t conuid;                   /* stdout type uid */
  1456.  
  1457. /* APOLLO Aegis main()
  1458.  * establish acl usage and cleanup handling
  1459.  *    this makes sure that CRP pads
  1460.  *    get restored to a usable mode
  1461.  */
  1462. main(argc,argv) int argc; char **argv; {
  1463.         status_$t status;
  1464.         pfm_$cleanup_rec dirty;
  1465.  
  1466.         PID_T pid = getpid();
  1467.  
  1468.         /* acl usage according to invoking environment */
  1469.         default_acl(USE_DEFENV);
  1470.  
  1471.         /* establish a cleanup continuation */
  1472.         status = pfm_$cleanup(dirty);
  1473.         if (status.all != pfm_$cleanup_set) {
  1474.                 /* only handle faults for the original process */
  1475.                 if (pid == getpid() && status.all > pgm_$max_severity) {
  1476.             /* blew up in main process */
  1477.             status_$t quo;
  1478.             pfm_$cleanup_rec clean;
  1479.  
  1480.             /* restore the console in any case */
  1481.             conres();
  1482.  
  1483.             /* attempt a clean exit */
  1484.             debug(F101, "cleanup fault status", "", status.all);
  1485.  
  1486.             /* doexit(), then send status to continuation */
  1487.             quo = pfm_$cleanup(clean);
  1488.             if (quo.all == pfm_$cleanup_set)
  1489.               doexit(pgm_$program_faulted,-1);
  1490.             else if (quo.all > pgm_$max_severity)
  1491.               pfm_$signal(quo); /* blew up in doexit() */
  1492.                 }
  1493.                 /* send to the original continuation */
  1494.                 pfm_$signal(status);
  1495.                 /*NOTREACHED*/
  1496.         }
  1497.         return(ckcmai(argc, argv));
  1498. }
  1499. #endif /* aegis */
  1500.  
  1501. /* ANSI-style prototypes for internal functions. */
  1502. /* Functions used outside this module are prototyped in ckcker.h. */
  1503.  
  1504. #ifdef apollo
  1505. _PROTOTYP( SIGTYP timerh, () );
  1506. _PROTOTYP( SIGTYP cctrap, () );
  1507. _PROTOTYP( SIGTYP esctrp, () );
  1508. _PROTOTYP( SIGTYP sig_ign, () );
  1509. #else
  1510. _PROTOTYP( SIGTYP timerh, (int) );
  1511. _PROTOTYP( SIGTYP cctrap, (int) );
  1512. _PROTOTYP( SIGTYP esctrp, (int) );
  1513. #endif /* apollo */
  1514. _PROTOTYP( int do_open, (char *) );
  1515. _PROTOTYP( static int in_chk, (int, int) );
  1516. _PROTOTYP( static int ttrpid, (char *) );
  1517. _PROTOTYP( static int ttchkpid, (char *) );
  1518. _PROTOTYP( static int ttlock, (char *) );
  1519. _PROTOTYP( static int ttunlck, (void) );
  1520. _PROTOTYP( static VOID sigchld_handler, (int) );
  1521. _PROTOTYP( int mygetbuf, (void) );
  1522. _PROTOTYP( int myfillbuf, (void) );
  1523. _PROTOTYP( VOID conbgt, (int) );
  1524. #ifdef ACUCNTRL
  1525. _PROTOTYP( VOID acucntrl, (char *, char *) );
  1526. #endif /* ACUCNTRL */
  1527.  
  1528. #ifdef BSD44ORPOSIX
  1529. _PROTOTYP( int carrctl, (struct termios *, int) );
  1530. #else
  1531. #ifdef ATTSV
  1532. _PROTOTYP( int carrctl, (struct termio *, int) );
  1533. #else
  1534. _PROTOTYP( int carrctl, (struct sgttyb *, int) );
  1535. #endif /* ATTSV */
  1536. #endif /* BSD44ORPOSIX */
  1537.  
  1538. #ifdef ATT7300
  1539. _PROTOTYP( int attdial, (char *, long, char *) );
  1540. _PROTOTYP( int offgetty, (char *) );
  1541. _PROTOTYP( int ongetty, (char *) );
  1542. #endif /* ATT7300 */
  1543.  
  1544. #ifdef BEOSORBEBOX
  1545. #ifdef SELECT
  1546.     /* BeOS is not capable of using SELECT on anything but sockets */
  1547. #undef SELECT
  1548. #endif /* SELECT */
  1549. #include <kernel/OS.h>
  1550. /* #ifdef BE_DR_7 */
  1551. static double time_started = 0.0;
  1552. struct ALARM_STRUCT {
  1553.     thread_id thread;
  1554.     int time;
  1555. };
  1556. static thread_id alarm_thread = -1;
  1557. static struct ALARM_STRUCT alarm_struct;
  1558. _PROTOTYP( long do_alarm, (void *) );
  1559. _PROTOTYP( unsigned int alarm, (unsigned int) );
  1560. _PROTOTYP( void alarm_expired, (void) );
  1561. /* #endif */ /* BE_DR_7 */
  1562. #endif /* BEOSORBEBOX */
  1563.  
  1564. #ifndef xunchar
  1565. #define xunchar(ch) (((ch) - 32 ) & 0xFF )    /* Character to number */
  1566. #endif /* xunchar */
  1567.  
  1568. #ifdef CK_ANSIC
  1569. static char *
  1570. xxlast(char *s, char c)
  1571. #else
  1572. static char *
  1573. xxlast(s,c) char *s; char c;
  1574. #endif /* CK_ANSIC */
  1575. /* xxlast */ {        /*  Last occurrence of character c in string s. */
  1576.     int i;
  1577.     for (i = (int)strlen(s); i > 0; i--)
  1578.       if (s[i-1] == c ) return(s + (i - 1));
  1579.     return(NULL);
  1580. }
  1581.  
  1582. /* Timeout handler for communication line input functions */
  1583.  
  1584. /*ARGSUSED*/
  1585. SIGTYP
  1586. timerh(foo) int foo; {
  1587.     ttimoff();
  1588. #ifdef BEOSORBEBOX
  1589. /* #ifdef BE_DR_7 */
  1590.     alarm_expired();
  1591. /* #endif */ /* BE_DR_7 */
  1592. #endif /* BEOSORBEBOX */
  1593. #ifdef CK_POSIX_SIG
  1594.     siglongjmp(sjbuf,1);
  1595. #else
  1596.     longjmp(sjbuf,1);
  1597. #endif /* CK_POSIX_SIG */
  1598. }
  1599.  
  1600. /*ARGSUSED*/
  1601. SIGTYP
  1602. xtimerh(foo) int foo; {            /* Like timerh() but does */
  1603. #ifdef BEOSORBEBOX            /* not reset the timer itself */
  1604. /* #ifdef BE_DR_7 */
  1605.     alarm_expired();
  1606. /* #endif */ /* BE_DR_7 */
  1607. #endif /* BEOSORBEBOX */
  1608. #ifdef CK_POSIX_SIG
  1609.     siglongjmp(sjbuf,1);
  1610. #else
  1611.     longjmp(sjbuf,1);
  1612. #endif /* CK_POSIX_SIG */
  1613. }
  1614.  
  1615.  
  1616. /* Control-C trap for communication line input functions */
  1617.  
  1618. int cc_int;                /* Flag */
  1619. SIGTYP (* occt)();            /* For saving old SIGINT handler */
  1620.  
  1621. /*ARGSUSED*/
  1622. SIGTYP
  1623. cctrap(foo) int foo; {            /* Needs arg for ANSI C */
  1624.   cc_int = 1;                /* signal() prototype. */
  1625.   return;
  1626. }
  1627.  
  1628. /*  S Y S I N I T  --  System-dependent program initialization.  */
  1629.  
  1630. /*
  1631.  * ttgwsiz() returns:
  1632.  *    1    tt_rows and tt_cols are known, both altered, both > 0
  1633.  *    0    tt_rows and/or tt_cols are known, both altered, one or both <= 0
  1634.  *    -1   tt_rows and tt_cols are unknown and unaltered
  1635.  */
  1636.  
  1637. extern int tt_rows, tt_cols;
  1638.  
  1639. static int
  1640. xttgwsiz() {
  1641.     char *p;
  1642.     int rows = 0, cols = 0;
  1643.     p = getenv("LINES");
  1644.     debug(F110,"xttgwsiz LINES",p,0);
  1645.     if (p) {
  1646.     rows = atol(p);
  1647.     if (rows > 0) {
  1648.         p = getenv("COLUMNS");
  1649.         debug(F110,"xttgwsiz COLUMNS",p,0);
  1650.         if (p) {
  1651.         cols = atol(p);
  1652.         if (cols > 0) {
  1653.             tt_rows = rows;
  1654.             tt_cols = cols;
  1655.             return(1);
  1656.         }
  1657.         return(0);
  1658.         }
  1659.     }
  1660.     }
  1661.     return(-1);
  1662. }
  1663.  
  1664. #ifdef TTLEBUF
  1665. VOID
  1666. le_init() {                /* LocalEchoInit() */
  1667.     int i;
  1668.     for (i = 0; i < LEBUFSIZ; i++)
  1669.       le_buf[i] = '\0';
  1670.     le_start = 0;
  1671.     le_end = 0;
  1672.     le_data = 0;
  1673. }
  1674.  
  1675. VOID
  1676. le_clean() {                /* LocalEchoCleanup() */
  1677.     le_init();
  1678.     return;
  1679. }
  1680.  
  1681. int
  1682. le_inbuf() {
  1683.     int rc = 0;
  1684.     if (le_start != le_end) {
  1685.     rc = (le_end -
  1686.           le_start +
  1687.           LEBUFSIZ) % LEBUFSIZ;
  1688.     }
  1689.     debug(F111,"le_inbuf","chars waiting",rc);
  1690.     return(rc);
  1691. }
  1692.  
  1693. int
  1694. #ifdef CK_ANSIC
  1695. le_putchar(CHAR ch)
  1696. #else
  1697. le_putchar(ch) CHAR ch;
  1698. #endif /* CK_ANSIC */
  1699. /* le_putchar */ {
  1700. #ifdef COMMENT
  1701.     /* In UNIX we do not have another thread taking chars out of the buffer */
  1702.     while ((le_start - le_end == 1) ||
  1703.             (le_start == 0 && le_end == LEBUFSIZ - 1)) {
  1704.     /* Buffer is full */
  1705.         debug(F111,"le_putchar","Buffer is Full",ch);
  1706.         ReleaseLocalEchoMutex() ;
  1707.         msleep(250);
  1708.         RequestLocalEchoMutex( SEM_INDEFINITE_WAIT ) ;
  1709.     }
  1710. #else
  1711.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  1712.         debug(F110,"le_putchar","buffer is full",0);
  1713.         return(-1);
  1714.     }
  1715. #endif /* COMMENT */
  1716.     le_buf[le_end++] = ch;
  1717.     if (le_end == LEBUFSIZ)
  1718.       le_end = 0;
  1719.     le_data = 1;
  1720.     return(0);
  1721. }
  1722.  
  1723. int
  1724. #ifdef CK_ANSIC
  1725. le_puts(CHAR * s, int n)
  1726. #else
  1727. le_puts(s,n) CHAR * s; int n;
  1728. #endif /* CK_ANSIC */
  1729. /* le_puts */ {
  1730.     int rc = 0;
  1731.     int i = 0;
  1732.     CHAR * p = (CHAR *)"le_puts";
  1733.     ckhexdump(p,s,n);
  1734.     for (i = 0; i < n; i++)
  1735.       rc = le_putchar((char)s[i]);
  1736.     debug(F101,"le_puts","",rc);
  1737.     return(rc);
  1738. }
  1739.  
  1740. int
  1741. #ifdef CK_ANSIC
  1742. le_putstr(CHAR * s)
  1743. #else
  1744. le_putstr(s) CHAR * s;
  1745. #endif /* CK_ANSIC */
  1746. /* le_puts */ {
  1747.     CHAR * p;
  1748.     int rc = 0;
  1749.     p = (CHAR *)"le_putstr";
  1750.     ckhexdump(p,s,(int)strlen((char *)s));
  1751.     for (p = s; *p && !rc; p++)
  1752.       rc = le_putchar(*p);
  1753.     return(rc);
  1754. }
  1755.  
  1756. int
  1757. #ifdef CK_ANSIC
  1758. le_getchar(CHAR * pch)
  1759. #else /* CK_ANSIC */
  1760. le_getchar(pch) CHAR * pch;
  1761. #endif /* CK_ANSIC */
  1762. /* le_gatchar */ {
  1763.     int rc = 0;
  1764.     if (le_start != le_end) {
  1765.         *pch = le_buf[le_start];
  1766.         le_buf[le_start] = 0;
  1767.         le_start++;
  1768.  
  1769.         if (le_start == LEBUFSIZ)
  1770.           le_start = 0;
  1771.  
  1772.         if (le_start == le_end) {
  1773.             le_data = 0;
  1774.         }
  1775.         rc++;
  1776.     } else {
  1777.         *pch = 0;
  1778.     }
  1779.     return(rc);
  1780. }
  1781. #endif /* TTLEBUF */
  1782.  
  1783. #ifdef COMMENT
  1784. /*
  1785.   Some systems like OSF/1 use TIOCGSIZE instead of TIOCGWINSZ.
  1786.   But as far as I know, whenever TIOCGSIZE is defined, it is
  1787.   equated to TIOCGWINSZ.  For cases where this is not done, try this:
  1788. */
  1789. #ifndef TIOCGWINSZ
  1790. #ifdef TIOCGSIZE
  1791. #define TIOCGWINSZ TIOCGSIZE
  1792. #endif /* TIOCGSIZE */
  1793. #endif /* TIOCGWINSZ */
  1794. #endif /* COMMENT */
  1795.  
  1796. static int tt_xpixel = 0, tt_ypixel = 0;
  1797.  
  1798. int
  1799. ttgwsiz() {
  1800.     int x = 0;
  1801. #ifndef NONAWS
  1802. #ifdef QNX
  1803. /*
  1804.   NOTE: TIOCGWSIZ works here too, but only in the 32-bit version.
  1805.   This code works for both the 16- and 32-bit versions.
  1806. */
  1807.     extern int dev_size(int, int, int, int *, int *);
  1808.     int r, c;
  1809.  
  1810.     if (dev_size(0, -1, -1, &r, &c) == 0) {
  1811.     debug(F101,"ttgwsiz QNX r","",r);
  1812.     debug(F101,"ttgwsiz QNX c","",c);
  1813.     tt_rows = r;
  1814.     tt_cols = c;
  1815.     return ((r > 0 && c > 0) ? 1 : 0);
  1816.     } else return(xttgwsiz());
  1817. #else /* QNX */
  1818. #ifdef TIOCGWINSZ
  1819.  
  1820. /* Note, this was M_UNIX, changed to XENIX to allow cross compilation... */
  1821. #ifdef XENIX                /* SCO UNIX 3.2v4.0 */
  1822. #include <sys/stream.h>            /* typedef mblk_t needed by ptem.h */
  1823. #include <sys/ptem.h>            /* for ttgwsiz() */
  1824. #endif /* XENIX */
  1825.  
  1826. #ifdef I386IX                /* Ditto for Interactive */
  1827. #include <sys/stream.h>
  1828. #include <sys/ptem.h>
  1829. #endif /* I386IX */
  1830.  
  1831. /* Note, the above might be needed for some other older SVR3 Intel makes... */
  1832.  
  1833.     struct winsize w;
  1834.     tt_xpixel = 0;
  1835.     tt_ypixel = 0;
  1836.  
  1837. #ifdef IKSD
  1838.     if (inserver)
  1839.       return(xttgwsiz());
  1840. #endif /* IKSD */
  1841.     x = ioctl(0, (int)TIOCGWINSZ, (char *)&w);
  1842.     debug(F101,"ttgwsiz TIOCGWINSZ","",x);
  1843.     if (x < 0) {
  1844.     return(xttgwsiz());
  1845.     } else if (w.ws_row > 0 && w.ws_col > 0) {
  1846.     tt_rows = w.ws_row;
  1847.     tt_cols = w.ws_col;
  1848.     tt_xpixel = w.ws_xpixel;
  1849.     tt_ypixel = w.ws_ypixel;
  1850.     debug(F101,"ttgwsiz tt_rows","",tt_rows);
  1851.     debug(F101,"ttgwsiz tt_cols","",tt_cols);
  1852.     return(1);
  1853.     } else {
  1854.     debug(F100,"ttgwsiz TIOCGWINSZ 00","",0);
  1855.     return(xttgwsiz());
  1856.     }
  1857. #else
  1858.     return(xttgwsiz());
  1859. #endif /* TIOCGWINSZ */
  1860. #endif /* QNX */
  1861. #endif /* NONAWS */
  1862. }
  1863.  
  1864.  
  1865. #ifdef RLOGCODE
  1866. _PROTOTYP( int rlog_naws, (void) );
  1867. #endif    /* RLOGCODE */
  1868.  
  1869. #ifndef NOSIGWINCH
  1870. #ifdef SIGWINCH
  1871. SIGTYP
  1872. winchh(foo) int foo; {            /* SIGWINCH handler */
  1873.     int x = 0;
  1874. #ifdef CK_TTYFD
  1875. #ifndef VMS
  1876.     extern int ttyfd;
  1877. #endif /* VMS */
  1878. #endif /* CK_TTYFD */
  1879.     extern int tt_rows, tt_cols, cmd_rows, cmd_cols;
  1880. #ifdef DEBUG
  1881.     if (deblog) {
  1882.     debug(F100,"***************","",0);
  1883.     debug(F100,"SIGWINCH caught","",0);
  1884.     debug(F100,"***************","",0);
  1885. #ifdef NETPTY
  1886.     debug(F101,"SIGWINCH pty_fork_pid","",pty_fork_pid);
  1887. #endif /* NETPTY */
  1888.     }
  1889. #endif /* DEUB */
  1890.     signal(SIGWINCH,winchh);            /* Re-arm the signal */
  1891.     x = ttgwsiz();                      /* Get new window size */
  1892.     cmd_rows = tt_rows;            /* Adjust command screen too */
  1893.     cmd_cols = tt_cols;
  1894.  
  1895. #ifdef CK_TTYFD
  1896.     if                    /* If we don't have a connection */
  1897. #ifdef VMS                /* we're done. */
  1898.       (vmsttyfd() == -1)
  1899. #else
  1900.       (ttyfd == -1)
  1901. #endif /* VMS */
  1902. #else
  1903.       (!local)
  1904. #endif /* CK_TTYFD */
  1905.         return;
  1906.  
  1907. #ifdef NETPTY
  1908.     if (pty_fork_pid > -1) {        /* "set host" to a PTY? */
  1909.     int x;
  1910.  
  1911. #ifdef TIOCSWINSZ
  1912.     struct winsize w;        /* Resize the PTY */
  1913.     errno = 0;
  1914.     w.ws_col = tt_cols;
  1915.     w.ws_row = tt_rows;
  1916.     w.ws_xpixel = tt_xpixel;
  1917.     w.ws_ypixel = tt_ypixel;
  1918.     x = ioctl(ttyfd,TIOCSWINSZ,&w);
  1919.     debug(F101,"winchh TIOCSWINSZ","",x);
  1920.     debug(F101,"winchh TIOCSWINSZ errno","",errno);
  1921. #endif /* TIOCSWINSZ */
  1922.  
  1923.     errno = 0;
  1924.     x = kill(pty_fork_pid,SIGWINCH);
  1925.     debug(F101,"winchh kill","",x);
  1926.     debug(F101,"winchh kill errno","",errno);
  1927.     }
  1928. #endif /* NETPTY */
  1929.  
  1930. /*
  1931.   This should be OK.  It might seem that sending this from
  1932.   interrupt level could interfere with another TELNET IAC string
  1933.   that was in the process of being sent.  But we always send
  1934.   TELNET strings with a single write(), which should prevent mixups.
  1935.   blah_snaws() should protect themselves from being called on the
  1936.   wrong kind of connection.
  1937. */
  1938. #ifdef TCPSOCKET
  1939. #ifndef NOTTGWSIZ
  1940.     if (x > 0 && tt_rows > 0 && tt_cols > 0) {
  1941.         tn_snaws();
  1942. #ifdef RLOGCODE
  1943.         rlog_naws();
  1944. #endif /* RLOGCODE */
  1945.     }
  1946. #endif /* NOTTGWSIZ */
  1947. #endif /* TCPSOCKET */
  1948.     SIGRETURN;
  1949. }
  1950. #endif /* SIGWINCH */
  1951. #endif /* NOSIGWINCH */
  1952.  
  1953. SIGTYP
  1954. sighup(foo) int foo; {            /* SIGHUP handler */
  1955.     backgrd = 1;
  1956.     debug(F100,"***************","",0);
  1957.     debug(F100,"SIGHUP received","",0);
  1958.     debug(F100,"***************","",0);
  1959.     doexit(BAD_EXIT,-1);
  1960.     /*NOTREACHED*/
  1961.     SIGRETURN;                /* Shut picky compilers up... */
  1962. }
  1963.  
  1964. #ifdef CK_SCO32V4
  1965. /* Exists but there is no prototype in the header files */
  1966. _PROTOTYP( char * ttyname, (int) );
  1967. #else
  1968. #ifdef SV68R3V6
  1969. _PROTOTYP( char * ttyname, (int) );
  1970. #else
  1971. #ifdef ultrix
  1972. _PROTOTYP( char * ttyname, (int) );
  1973. #else
  1974. #ifdef HPUX6
  1975. _PROTOTYP( char * ttyname, (int) );
  1976. #else
  1977. #ifdef HPUX5
  1978. _PROTOTYP( char * ttyname, (int) );
  1979. #else
  1980. #ifdef PS2AIX10
  1981. _PROTOTYP( char * ttyname, (int) );
  1982. #else
  1983. #ifdef BSD42
  1984. _PROTOTYP( char * ttyname, (int) );
  1985. #endif /* BSD42 */
  1986. #endif /* PS2AIX10 */
  1987. #endif /* HPUX5 */
  1988. #endif /* HPUX6 */
  1989. #endif /* ultrix */
  1990. #endif /* SV68R3V6 */
  1991. #endif /* CK_SCO32V4 */
  1992.  
  1993. #ifndef SIGUSR1                /* User-defined signals */
  1994. #define SIGUSR1 30
  1995. #endif /* SIGUSR1 */
  1996.  
  1997. #ifndef SIGUSR2
  1998. #define SIGUSR2 31
  1999. #endif /* SIGUSR2 */
  2000.  
  2001. /*
  2002.   ignorsigs() sets certain signals to SIG_IGN.  But when a signal is
  2003.   ignored, it remains ignored across exec(), so we have to restore these
  2004.   signals before exec(), which is the purpose of restorsigs().
  2005. */
  2006. static VOID
  2007. ignorsigs() {                /* Ignore these signals */
  2008.     savquit = signal(SIGQUIT,SIG_IGN);    /* Ignore Quit signal */
  2009.  
  2010. #ifdef SIGDANGER            /* Ignore danger signals */
  2011. /*
  2012.   This signal is sent when the system is low on swap space.  Processes
  2013.   that don't handle it are candidates for termination.  If swap space doesn't
  2014.   clear out enough, we still might be terminated via kill() -- nothing we can
  2015.   do about that!  Conceivably, this could be improved by installing a real
  2016.   signal handler that warns the user, but that would be pretty complicated,
  2017.   since we are not always in control of the screen -- e.g. during remote-mode
  2018.   file transfer.
  2019. */
  2020.     savdanger = signal(SIGDANGER,SIG_IGN); /* e.g. in AIX */
  2021. #endif /* SIGDANGER */
  2022. #ifdef SIGPIPE
  2023. /*
  2024.   This one comes when a TCP/IP connection is broken by the remote.
  2025.   We prefer to catch this situation by examining error codes from write().
  2026. */
  2027.     savpipe = signal(SIGPIPE,SIG_IGN);
  2028. #endif /* SIGPIPE */
  2029.     savusr1 = signal(SIGUSR1,SIG_IGN);    /* Ignore user-defined signals */
  2030.     savusr2 = signal(SIGUSR2,SIG_IGN);
  2031. }
  2032.  
  2033. VOID
  2034. restorsigs() {                /* Restore these signals */
  2035.     (VOID) signal(SIGQUIT,savquit);    /* (used in ckufio.c) */
  2036. #ifdef SIGDANGER
  2037.     (VOID) signal(SIGDANGER,savdanger);
  2038. #endif /* SIGDANGER */
  2039. #ifdef SIGPIPE
  2040.     (VOID) signal(SIGPIPE,savpipe);
  2041. #endif /* SIGPIPE */
  2042.     (VOID) signal(SIGUSR1,savusr1);
  2043.     (VOID) signal(SIGUSR2,savusr2);
  2044. }
  2045.  
  2046. int
  2047. sysinit() {
  2048.     int x;
  2049.     char * s;
  2050. #ifdef CK_UTSNAME
  2051.     struct utsname name;
  2052. #endif /* CK_UTSNAME */
  2053.  
  2054.     extern char startupdir[];
  2055. /*
  2056.   BEFORE ANYTHING ELSE: Initialize the setuid package.
  2057.   Change to the user's real user and group ID.
  2058.   If this can't be done, don't run at all.
  2059. */
  2060.     x = priv_ini();
  2061. #ifdef SUIDDEBUG
  2062.     fprintf(stderr,"PRIV_INI=%d\n",x);
  2063. #endif /* SUIDDEBUG */
  2064.     if (x) {
  2065.     if (x & 1) fprintf(stderr,"Fatal: setuid failure.\n");
  2066.     if (x & 2) fprintf(stderr,"Fatal: setgid failure.\n");
  2067.     if (x & 4) fprintf(stderr,"Fatal: C-Kermit setuid to root!\n");
  2068.     exit(1);
  2069.     }
  2070.     signal(SIGINT,SIG_IGN);        /* Ignore interrupts at first */
  2071.     signal(SIGFPE,SIG_IGN);        /* Ignore floating-point exceptions */
  2072.     signal(SIGHUP,sighup);        /* Catch SIGHUP */
  2073. #ifndef NOSIGWINCH
  2074. #ifdef SIGWINCH
  2075.     signal(SIGWINCH,winchh);        /* Catch window-size change */
  2076. #endif /* SIGWINCH */
  2077. #endif /* NOSIGWINCH */
  2078.  
  2079. #ifdef SIGXFSZ
  2080.     signal(SIGXFSZ,SIG_IGN);        /* Ignore writing past file limit */ 
  2081. #endif    /* SIGXFSZ */
  2082.  
  2083. #ifndef NOJC
  2084. /*
  2085.   Get the initial job control state.
  2086.   If it is SIG_IGN, that means the shell does not support job control,
  2087.   and so we'd better not suspend ourselves.
  2088. */
  2089. #ifdef SIGTSTP
  2090.     jchdlr = signal(SIGTSTP,SIG_IGN);
  2091.     if (jchdlr == SIG_IGN) {
  2092.     jcshell = 0;
  2093.     debug(F100,"sysinit jchdlr: SIG_IGN","",0);
  2094.     } else if (jchdlr == SIG_DFL) {
  2095.     debug(F100,"sysinit jchdlr: SIG_DFL","",0);
  2096.     jcshell = 1;
  2097.     } else {
  2098.     debug(F100,"sysinit jchdlr: other","",0);
  2099.     jcshell = 3;
  2100.     }
  2101.     (VOID) signal(SIGTSTP,jchdlr);    /* Put it back... */
  2102. #endif /* SIGTSTP */
  2103. #endif /* NOJC */
  2104.  
  2105.     conbgt(0);                /* See if we're in the background */
  2106.     congm();                /* Get console modes */
  2107.  
  2108.     (VOID) signal(SIGALRM,SIG_IGN);    /* Ignore alarms */
  2109.  
  2110.     ignorsigs();            /* Ignore some other signals */
  2111.  
  2112. #ifdef F_SETFL
  2113.     iniflags = fcntl(0,F_GETFL,0);    /* Get stdin flags */
  2114. #endif /* F_SETFL */
  2115.  
  2116. #ifdef ultrix
  2117.     gtty(0,&vanilla);            /* Get sgtty info */
  2118. #else
  2119. #ifdef AUX
  2120.     set42sig();                /* Don't ask! (hakanson@cs.orst.edu) */
  2121. #endif /* AUX */
  2122. #endif /* ultrix */
  2123. /*
  2124.   Warning: on some UNIX systems (SVR4?), ttyname() reportedly opens /dev but
  2125.   never closes it.  If it is called often enough, we run out of file
  2126.   descriptors and subsequent open()'s of other devices or files can fail.
  2127. */
  2128.     s = NULL;
  2129. #ifndef MINIX
  2130.     if (isatty(0))            /* Name of controlling terminal */
  2131.       s = ttyname(0);
  2132.     else if (isatty(1))
  2133.       s = ttyname(1);
  2134.     else if (isatty(2))
  2135.       s = ttyname(2);
  2136.     debug(F110,"sysinit ttyname(0)",s,0);
  2137. #endif /* MINIX */
  2138.  
  2139. #ifdef BEOS
  2140.     if (!dftty)
  2141.       makestr(&dftty,s);
  2142. #endif /* BEOS */
  2143.  
  2144.     if (s)
  2145.       ckstrncpy((char *)cttnam,s,DEVNAMLEN+1);
  2146. #ifdef SVORPOSIX
  2147.     if (!cttnam[0])
  2148.       ctermid(cttnam);
  2149. #endif /* SVORPOSIX */
  2150.     if (!cttnam[0])
  2151.       ckstrncpy((char *)cttnam,dftty,DEVNAMLEN+1);
  2152.     debug(F110,"sysinit CTTNAM",CTTNAM,0);
  2153.     debug(F110,"sysinit cttnam",cttnam,0);
  2154.  
  2155.     ttgwsiz();                /* Get window (screen) dimensions. */
  2156.  
  2157. #ifndef NOSYSCONF
  2158. #ifdef _SC_OPEN_MAX
  2159.     ckmaxfiles = sysconf(_SC_OPEN_MAX);
  2160. #endif /* _SC_OPEN_MAX */
  2161. #endif /* NOSYSCONF */
  2162.  
  2163. #ifdef Plan9
  2164.     if (!backgrd) {
  2165.         consctlfd = open("/dev/consctl", O_WRONLY);
  2166.         /*noisefd = open("/dev/noise", O_WRONLY)*/
  2167.     }
  2168.     ckxech = 1;
  2169. #endif /* Plan9 */
  2170.  
  2171. #ifdef CK_UTSNAME
  2172.     if (uname(&name) > -1) {
  2173.     ckstrncpy(unm_mch,name.machine,CK_SYSNMLN);
  2174.     ckstrncpy(unm_nam,name.sysname,CK_SYSNMLN);
  2175.     ckstrncpy(unm_rel,name.release,CK_SYSNMLN);
  2176.     ckstrncpy(unm_ver,name.version,CK_SYSNMLN);
  2177. #ifdef DEBUG
  2178.     if (deblog) {
  2179.         debug(F110,"sysinit uname machine",unm_mch,0);
  2180.         debug(F110,"sysinit uname sysname",unm_nam,0);
  2181.         debug(F110,"sysinit uname release",unm_rel,0);
  2182.         debug(F110,"sysinit uname version",unm_ver,0);
  2183.     }
  2184. #endif /* DEBUG */
  2185.  
  2186. #ifdef HPUX9PLUS
  2187.     if (name.machine[5] == '8')
  2188.       hpis800 = 1;
  2189.     else
  2190.       hpis800 = 0;
  2191.     debug(F101,"sysinit hpis800","",hpis800);
  2192. #endif /* HPUX9PLUS */
  2193. #ifdef TRU64
  2194.         getsysinfo(GSI_PLATFORM_NAME, unm_mod, CK_SYSNMLN, 0, 0);
  2195.         debug(F110,"sysinit getsysinfo model",unm_mod,0);
  2196. #endif /* TRU64 */
  2197. #ifdef SOLARIS25
  2198.         sysinfo(SI_PLATFORM, unm_mod, CK_SYSNMLN);
  2199.         debug(F110,"sysinit sysinfo model",unm_mod,0);
  2200. #endif /* SOLARIS25 */
  2201.     }
  2202. #endif /* CK_UTSNAME */
  2203.  
  2204. #ifdef CK_ENVIRONMENT
  2205.     {
  2206. #ifdef TNCODE
  2207.     extern char tn_env_acct[], tn_env_disp[], tn_env_job[],
  2208.     tn_env_prnt[], tn_env_sys[];
  2209. #endif /* TNCODE */
  2210.     extern char uidbuf[];
  2211.         extern char * whoami();
  2212.     char *p;
  2213. #ifdef CKSENDUID
  2214.         uidbuf[0] = '\0';
  2215. #ifdef IKSD
  2216.         if (!inserver) {
  2217. #endif /* IKSD */
  2218.             p = getenv("USER");
  2219.             debug(F110,"sysinit uidbuf from USER",uidbuf,0);
  2220.         if (!p) p = "";
  2221.             if (!*p) {
  2222.                 p = getenv("LOGNAME");
  2223.                 debug(F110,"sysinit uidbuf from LOGNAME",uidbuf,0);
  2224.             }
  2225.         if (!p) p = "";
  2226.             if (!*p) {
  2227.                 p = whoami();
  2228.                 debug(F110,"sysinit uidbuf from whoami()",uidbuf,0);
  2229.             }
  2230.         if (!p) p = "";
  2231.         ckstrncpy(uidbuf, *p ? p : "UNKNOWN", UIDBUFLEN);
  2232. #ifdef IKSD
  2233.         }
  2234. #endif /* IKSD */
  2235.     debug(F110,"sysinit final uidbuf",uidbuf,0);
  2236. #endif /* CKSENDUID */
  2237.  
  2238. #ifdef TNCODE
  2239.     if ((p = getenv("JOB"))) ckstrncpy(tn_env_job,p,63);
  2240.     if ((p = getenv("ACCT"))) ckstrncpy(tn_env_acct,p,63);
  2241.     if ((p = getenv("PRINTER"))) ckstrncpy(tn_env_prnt,p,63);
  2242.     if ((p = getenv("DISPLAY"))) ckstrncpy(tn_env_disp,p,63);
  2243. #ifdef aegis
  2244.     ckstrncpy(tn_env_sys,"Aegis",64);
  2245. #else
  2246. #ifdef Plan9
  2247.     ckstrncpy(tn_env_sys,"Plan9",64);
  2248. #else
  2249.     ckstrncpy(tn_env_sys,"UNIX",64);
  2250. #endif /* Plan9 */
  2251. #endif /* aegis */
  2252. #endif /* TNCODE */
  2253.     }
  2254. #endif /* CK_ENVIRONMENT */
  2255. #ifdef CK_SNDLOC
  2256.     {
  2257.     extern char * tn_loc;
  2258.     char *p;
  2259.     if (p = getenv("LOCATION"))
  2260.       if (tn_loc = (char *)malloc((int)strlen(p)+1))
  2261.         strcpy(tn_loc,p);        /* safe */
  2262.     }
  2263. #endif /* CK_SNDLOC */
  2264.  
  2265.     ckstrncpy(startupdir, zgtdir(), CKMAXPATH);
  2266.     startupdir[CKMAXPATH] = '\0';
  2267.     x = strlen(startupdir);
  2268.     if (x <= 0) {
  2269.     startupdir[0] = '/';
  2270.     startupdir[1] = '\0';
  2271.     } else if (startupdir[x-1] != '/') {
  2272.     startupdir[x] = '/';
  2273.     startupdir[x+1] = '\0';
  2274.     }
  2275.     debug(F110,"sysinit startupdir",startupdir,0);
  2276. #ifdef TTLEBUF
  2277.     le_init();
  2278. #endif /* TTLEBUF */
  2279. #ifdef BSD44ORPOSIX
  2280.     /* This should catch the ncurses platforms */
  2281.     /* Some platforms don't have putenv(), like NeXTSTEP */
  2282.     putenv("NCURSES_NO_SETBUF=1");
  2283. #endif /* BSD44ORPOSIX */
  2284.     return(0);
  2285. }
  2286.  
  2287. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  2288.  
  2289. int
  2290. syscleanup() {
  2291. #ifdef F_SETFL
  2292.     if (iniflags > -1)
  2293.       fcntl(0,F_SETFL,iniflags);    /* Restore stdin flags */
  2294. #endif /* F_SETFL */
  2295. #ifdef ultrix
  2296.     stty(0,&vanilla);                   /* Get sgtty info */
  2297. #endif /* ultrix */
  2298. #ifdef NETCMD
  2299.     if (ttpid) kill(ttpid,9);
  2300. #endif /* NETCMD */
  2301.     return(0);
  2302. }
  2303.  
  2304. /*  T T O P E N  --  Open a tty for exclusive access.  */
  2305.  
  2306. /*
  2307.   Call with:
  2308.     ttname: character string - device name or network host name.
  2309.     lcl:
  2310.   If called with lcl < 0, sets value of lcl as follows:
  2311.   0: the terminal named by ttname is the job's controlling terminal.
  2312.   1: the terminal named by ttname is not the job's controlling terminal.
  2313.   But watch out: if a line is already open, or if requested line can't
  2314.   be opened, then lcl remains (and is returned as) -1.
  2315.     modem:
  2316.   Less than zero: ttname is a network host name.
  2317.   Zero or greater: ttname is a terminal device name.
  2318.   Zero means a local connection (don't use modem signals).
  2319.   Positive means use modem signals.
  2320.    timo:
  2321.   0 = no timer.
  2322.   nonzero = number of seconds to wait for open() to return before timing out.
  2323.  
  2324.   Returns:
  2325.     0 on success
  2326.    -5 if device is in use
  2327.    -4 if access to device is denied
  2328.    -3 if access to lock directory denied
  2329.    -2 upon timeout waiting for device to open
  2330.    -1 on other error
  2331. */
  2332. static int ttotmo = 0;            /* Timeout flag */
  2333. /* Flag kept here to avoid being clobbered by longjmp.  */
  2334.  
  2335. int
  2336. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  2337.  
  2338. #ifdef BSD44
  2339. #define ctermid(x) strcpy(x,"")
  2340. #else
  2341. #ifdef SVORPOSIX
  2342. #ifndef CIE
  2343.     extern char *ctermid();        /* Wish they all had this! */
  2344. #else                    /* CIE Regulus */
  2345. #define ctermid(x) strcpy(x,"")
  2346. #endif /* CIE */
  2347. #endif /* SVORPOSIX */
  2348. #endif /* BSD44 */
  2349.  
  2350. #ifdef ultrix
  2351.     int temp = 0;
  2352. #endif /* ultrix */
  2353.  
  2354. #ifndef OPENFIRST
  2355.     char fullname[DEVNAMLEN+1];
  2356. #endif /* OPENFIRST */
  2357.  
  2358.     char * fnam;            /* Full name after expansion */
  2359.  
  2360.     int y;
  2361.  
  2362. #ifndef pdp11
  2363. #define NAMEFD     /* Feature to allow name to be an open file descriptor */
  2364. #endif /* pdp11 */
  2365.  
  2366. #ifdef NAMEFD
  2367.     char *p;
  2368.     debug(F101,"ttopen telnetfd","",telnetfd);
  2369. #endif /* NAMEFD */
  2370.  
  2371.     debug(F110,"ttopen ttname",ttname,0);
  2372.     debug(F110,"ttopen ttnmsv",ttnmsv,0);
  2373.     debug(F101,"ttopen modem","",modem);
  2374.     debug(F101,"ttopen netconn","",netconn);
  2375.     debug(F101,"ttopen ttyfd","",ttyfd);
  2376.     debug(F101,"ttopen *lcl","",*lcl);
  2377.     debug(F101,"ttopen ttmdm","",ttmdm);
  2378.     debug(F101,"ttopen ttnet","",ttnet);
  2379.  
  2380.     ttpmsk = 0xff;
  2381.     lockpid[0] = '\0';
  2382.  
  2383.     if (ttyfd > -1) {            /* If device already opened */
  2384.         if (!strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  2385.       return(0);            /* Yes, nothing to do - just return */
  2386.     ttnmsv[0] = '\0';        /* No, clear out old name */
  2387.     ttclos(ttyfd);            /* close old connection.  */
  2388.     }
  2389.     wasclosed = 0;            /* New connection, not closed yet. */
  2390.     ttpipe = 0;                /* Assume it's not a pipe */
  2391.     ttpty = 0;                /* or a pty... */
  2392.  
  2393. #ifdef NETCONN
  2394. /*
  2395.   This is a bit tricky...  Suppose that previously Kermit had dialed a telnet
  2396.   modem server ("set host xxx:2001, set modem type usr, dial ...").  Then the
  2397.   connection was closed (ttyfd = -1), and then a REDIAL command was given.  At
  2398.   this point we've obliterated the negative modem type hack, and so would
  2399.   treat the IP hostname as a device name, and would then fail because of "No
  2400.   such device or directory".  But the previous connection has left behind some
  2401.   clues, so let's use them...
  2402. */
  2403.     if (ttyfd < 0) {            /* Connection is not open */
  2404.     if (!strcmp(ttname,ttnmsv)) {    /* Old and new names the same? */
  2405.         if (((netconn > 0) && (ttmdm < 0)) ||
  2406.         ((ttnet > 0) &&
  2407.          (!ckstrchr(ttname,'/')) && (ckstrchr(ttname,':')))
  2408.         ) {
  2409.         int x, rc;
  2410.         x = (ttmdm < 0) ? -ttmdm : ttnet;
  2411.         rc = netopen(ttname, lcl, x);
  2412.         debug(F111,"ttopen REOPEN netopen",ttname,rc);
  2413.         if (rc > -1) {
  2414.             netconn = 1;
  2415.             xlocal = *lcl = 1;
  2416.         } else {
  2417.             netconn = 0;
  2418.         }
  2419.         gotsigs = 0;
  2420.         return(rc);
  2421.         }
  2422.     }
  2423.     }
  2424. #endif /* NETCONN */
  2425.  
  2426. #ifdef MAXNAMLEN
  2427.     debug(F100,"ttopen MAXNAMLEN defined","",0);
  2428. #else
  2429.     debug(F100,"ttopen MAXNAMLEN *NOT* defined","",0);
  2430. #endif
  2431.  
  2432. #ifdef BSD4
  2433.     debug(F100,"ttopen BSD4 defined","",0);
  2434. #else
  2435.     debug(F100,"ttopen BSD4 *NOT* defined","",0);
  2436. #endif /* BSD4 */
  2437.  
  2438. #ifdef BSD42
  2439.     debug(F100,"ttopen BSD42 defined","",0);
  2440. #else
  2441.     debug(F100,"ttopen BSD42 *NOT* defined","",0);
  2442. #endif /* BSD42 */
  2443.  
  2444. #ifdef MYREAD
  2445.     debug(F100,"ttopen MYREAD defined","",0);
  2446. #else
  2447.     debug(F100,"ttopen MYREAD *NOT* defined","",0);
  2448. #endif /* MYREAD */
  2449.  
  2450. #ifdef    NETCONN
  2451.     if (modem < 0) {            /* modem < 0 = code for network */
  2452.     int x;
  2453.     ttmdm = modem;
  2454.     modem = -modem;            /* Positive network type number */
  2455.     fdflag = 0;            /* Stdio not redirected. */
  2456.     netconn = 1;            /* And it's a network connection */
  2457.     debug(F111,"ttopen net",ttname,modem);
  2458. #ifdef NAMEFD
  2459.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2460.      if (*p == '\0' && (telnetfd || x25fd)) { /* Avoid X.121 addresses */
  2461.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2462.         ttfdflg = 1;        /* We got an open file descriptor */
  2463.         debug(F111,"ttopen net ttfdflg",ttname,ttfdflg);
  2464.         debug(F101,"ttopen net ttyfd","",ttyfd);
  2465.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2466.         x = 1;            /* Return code is "good". */
  2467.         if (telnetfd) {
  2468.         ttnet = NET_TCPB;
  2469.         if (ttnproto != NP_TCPRAW)
  2470.           ttnproto = NP_TELNET;
  2471. #ifdef SUNX25
  2472.         } else if (x25fd) {
  2473.         ttnet = NET_SX25;
  2474.         ttnproto = NP_NONE;
  2475. #endif /* SUNX25 */
  2476.         }
  2477.     } else {            /* Host name or address given */
  2478. #ifdef NETPTY
  2479.         if (modem == NET_PTY) {
  2480.         int x;
  2481.         if (nopush) {
  2482.             debug(F100,"ttopen PTY: nopush","",0);
  2483.             return(-1);
  2484.         }
  2485.                 ttnet = NET_PTY;
  2486.         ttnproto = NP_NONE;
  2487.                 netconn = 1;            /* but we don't use network i/o */
  2488.                 ttpty = 1;
  2489.                 debug(F110,"ttopen PTY",ttname,0);
  2490.         x = do_pty(&ttyfd,ttname,0);
  2491.         if (x > -1) {
  2492.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2493.             xlocal = *lcl = 1;    /* It's local */
  2494.         } else {
  2495.             ttpty = 0;
  2496.             netconn = 0;
  2497.         }
  2498.         gotsigs = 0;
  2499.         return(x);
  2500.         }
  2501. #endif /* NETPTY */
  2502. #ifdef NETCMD
  2503. /*
  2504.   dup2() is not available on older System V platforms like AT&T 3Bx.  For
  2505.   those systems we punt by not defining NETCMD, but we might be able to do
  2506.   better -- see workarounds for this problem in ckufio.c (search for dup2).
  2507. */
  2508.         if (modem == NET_CMD) {
  2509.         if (nopush) {
  2510.             debug(F100,"ttopen pipe: nopush","",0);
  2511.             return(-1);
  2512.         }
  2513.         if (pipe(pipe0) || pipe(pipe1)) {
  2514.             perror("Pipe error");
  2515.             return(-1);
  2516.         }
  2517.         ttpid = fork();        /* Make a fork */
  2518.  
  2519.         switch (ttpid) {
  2520.           case -1:        /* Error making fork */
  2521.             close(pipe0[0]);
  2522.             close(pipe0[1]);
  2523.             close(pipe1[0]);
  2524.             close(pipe1[1]);
  2525.             perror("Fork error");
  2526.             return(-1);
  2527.           case 0:        /* Child. */
  2528.             close(pipe0[0]);
  2529.             close(pipe1[1]);
  2530.             dup2(pipe0[1], 1);
  2531.             close(pipe0[1]);
  2532.             dup2(pipe1[0], 0);
  2533.             close(pipe1[0]);
  2534.             system(ttname);
  2535.             _exit(0);
  2536.           default:        /* Parent */
  2537.             close(pipe0[1]);
  2538.             close(pipe1[0]);
  2539.             fdin = pipe0[0];    /* Read from pipe */
  2540.             fdout = pipe1[1];    /* Write to pipe */
  2541.             ttout = fdopen(fdout,"w"); /* Get stream so we can */
  2542.             if (!ttout) {    /* make it unbuffered. */
  2543.             perror("fdopen failure");
  2544.             return(-1);
  2545.             }
  2546.             setbuf(ttout,NULL);
  2547.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2548.             xlocal = *lcl = 1;    /* It's local */
  2549.             netconn = 1;    /* Call it a network connection */
  2550.             ttmdm = modem;    /* Remember network type */
  2551.             ttyfd = fdin;
  2552.             ttpipe = 1;
  2553.             gotsigs = 0;
  2554.             return(0);
  2555.         }
  2556.         }
  2557. #endif /* NETCMD */
  2558. #endif /* NAMEFD */
  2559.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  2560.         if (x > -1) {
  2561.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2562.         } else netconn = 0;
  2563. #ifdef NAMEFD
  2564.     }
  2565. #endif /* NAMEFD */
  2566.  
  2567. #ifdef sony_news            /* Sony NEWS */
  2568.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get Kanji mode */
  2569.         perror("ttopen error getting Kanji mode (network)");
  2570.         debug(F111,"ttopen error getting Kanji mode","network",0);
  2571.         km_ext = -1;        /* Make sure this stays undefined. */
  2572.     }
  2573. #endif /* sony_news */
  2574.  
  2575.     xlocal = *lcl = 1;        /* Network connections are local. */
  2576.     debug(F101,"ttopen net x","",x);
  2577. #ifdef COMMENT
  2578. /* Let netopen() do this */
  2579.     if (x > -1 && !x25fd)
  2580.       x = tn_ini();            /* Initialize TELNET protocol */
  2581. #endif /* COMMENT */
  2582.     gotsigs = 0;
  2583.     return(x);
  2584.     } else {                /* Terminal device */
  2585. #endif    /* NETCONN */
  2586.  
  2587. #ifdef NAMEFD
  2588. /*
  2589.   This code lets you give Kermit an open file descriptor for a serial
  2590.   communication device, rather than a device name.  Kermit assumes that the
  2591.   line is already open, locked, conditioned with the right parameters, etc.
  2592. */
  2593.     for (p = ttname; isdigit(*p); p++) ; /* Check for all-digits */
  2594.     if (*p == '\0') {
  2595.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2596.         debug(F111,"ttopen got open fd",ttname,ttyfd);
  2597.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2598.         if (ttyfd >= 0 && ttyfd < 3) /* If it's stdio... */
  2599.           xlocal = *lcl = 0;    /* we're in remote mode */
  2600.         else            /* otherwise */
  2601.           xlocal = *lcl = 1;    /* local mode. */
  2602.         netconn = 0;        /* Assume it's not a network. */
  2603.         tvtflg = 0;            /* Might need to initialize modes. */
  2604.         ttmdm = modem;        /* Remember modem type. */
  2605.         fdflag = 0;            /* Stdio not redirected. */
  2606.         ttfdflg = 1;        /* Flag we were opened this way. */
  2607.         debug(F111,"ttopen non-net ttfdflg",ttname,ttfdflg);
  2608.         debug(F101,"ttopen non-net ttyfd","",ttyfd);
  2609.  
  2610. #ifdef sony_news            /* Sony NEWS */
  2611.         /* Get device Kanji mode */
  2612.         if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) {
  2613.         perror("ttopen error getting Kanji mode");
  2614.         debug(F101,"ttopen error getting Kanji mode","",0);
  2615.         km_ext = -1;        /* Make sure this stays undefined. */
  2616.         }
  2617. #endif /* sony_news */
  2618.         gotsigs = 0;
  2619.         return(0);            /* Return success */
  2620.     }
  2621. #endif /* NAMEFD */
  2622. #ifdef NETCONN
  2623.     }
  2624. #endif /* NETCONN */
  2625.  
  2626. /* Here we have to open a serial device of the given name. */
  2627.  
  2628.     netconn = 0;            /* So it's not a network connection */
  2629.     occt = signal(SIGINT, cctrap);    /* Set Control-C trap, save old one */
  2630.     sigint_ign = 0;
  2631.  
  2632.     tvtflg = 0;            /* Flag for use by ttvt(). */
  2633.                 /* 0 = ttvt not called yet for this device */
  2634.  
  2635.     fdflag = (!isatty(0) || !isatty(1)); /* Flag for stdio redirected */
  2636.     debug(F101,"ttopen fdflag","",fdflag);
  2637.  
  2638.     ttmdm = modem;                      /* Make this available to other fns */
  2639.     xlocal = *lcl;                      /* Make this available to other fns */
  2640.  
  2641. /* Code for handling bidirectional tty lines goes here. */
  2642. /* Use specified method for turning off logins and suppressing getty. */
  2643.  
  2644. #ifdef ACUCNTRL
  2645.     /* Should put call to priv_on() here, but that would be very risky! */
  2646.     acucntrl("disable",ttname);         /* acucntrl() program. */
  2647.     /* and priv_off() here... */
  2648. #else
  2649. #ifdef ATT7300
  2650.     if ((attmodem & DOGETY) == 0)       /* offgetty() program. */
  2651.       attmodem |= offgetty(ttname);    /* Remember response.  */
  2652. #endif /* ATT7300 */
  2653. #endif /* ACUCNTRL */
  2654.  
  2655. #ifdef OPENFIRST
  2656. /*
  2657.  1985-2001: opens device first then gets lock; reason:
  2658.  Kermit usually has to run setuid or setgid in order to create a lockfile.
  2659.  If you give a SET LINE command for a device that happens to be your job's
  2660.  controlling terminal, Kermit doesn't have to create a lockfile, and in fact
  2661.  should not create one, and would fail if it tried to if it did not have the
  2662.  required privileges.  But you can't find out if two tty device names are
  2663.  equivalent until you have a file descriptor that you can give to ttyname().
  2664.  But this can cause a race condition between Kermit and [m]getty.  So see
  2665.  the [#]else part...
  2666. */ 
  2667.  
  2668. /*
  2669.  In the following section, we open the tty device for read/write.
  2670.  If a modem has been specified via "set modem" prior to "set line"
  2671.  then the O_NDELAY parameter is used in the open, provided this symbol
  2672.  is defined (e.g. in fcntl.h), so that the program does not hang waiting
  2673.  for carrier (which in most cases won't be present because a connection
  2674.  has not been dialed yet).  O_NDELAY is removed later on in ttopen().  It
  2675.  would make more sense to first determine if the line is local before
  2676.  doing this, but because ttyname() requires a file descriptor, we have
  2677.  to open it first.  See do_open().
  2678.  
  2679.  Now open the device using the desired treatment of carrier.
  2680.  If carrier is REQUIRED, then open could hang forever, so an optional
  2681.  timer is provided.  If carrier is not required, the timer should never
  2682.  go off, and should do no harm...
  2683. */
  2684.     ttotmo = 0;                /* Flag no timeout */
  2685.     debug(F101,"ttopen timo","",timo);
  2686.     debug(F101,"ttopen xlocal","",xlocal);
  2687.     if (timo > 0) {
  2688.     int xx;
  2689.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2690.     xx = alarm(timo);        /* Timed open() */
  2691.     debug(F101,"ttopen alarm","",xx);
  2692.     if (
  2693. #ifdef CK_POSIX_SIG
  2694.         sigsetjmp(sjbuf,1)
  2695. #else
  2696.         setjmp(sjbuf)
  2697. #endif /* CK_POSIX_SIG */
  2698.         ) {
  2699.         ttotmo = 1;            /* Flag timeout. */
  2700.     } else ttyfd = do_open(ttname);
  2701.     ttimoff();
  2702.     debug(F111,"ttopen","modem",modem);
  2703.     debug(F101,"ttopen ttyfd","",ttyfd);
  2704.     debug(F101,"ttopen alarm return","",ttotmo);
  2705.     } else {
  2706.     errno = 0;
  2707.     ttyfd = do_open(ttname);
  2708.     }
  2709.     debug(F111,"ttopen ttyfd",ttname,ttyfd);
  2710.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2711.     debug(F101,"ttopen errno","",errno);
  2712.     if (errno > 0 && !quiet)
  2713.       perror(ttname);        /* Print message */
  2714.  
  2715. #ifdef ATT7300
  2716.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2717.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2718.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2719. #else
  2720. #ifdef ACUCNTRL
  2721.         /* Should put call to priv_on() here, but that would be risky! */
  2722.     acucntrl("enable",ttname);    /* acucntrl() program. */
  2723.     /* and priv_off() here... */
  2724. #endif /* ACUNTRL */
  2725. #endif /* ATT7300 */
  2726.  
  2727.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2728.     if (errno == EACCES) {        /* Device is protected against user */
  2729.         debug(F110,"ttopen EACCESS",ttname,0); /* Return -4 */
  2730.         return(-4);
  2731.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2732.     }
  2733.  
  2734. #ifdef QNX
  2735.     {
  2736.     extern int qnxportlock;
  2737.     x = qnxopencount();
  2738.     debug(F101,"ttopen qnxopencount","",x);
  2739.     debug(F101,"ttopen qnxportlock","",qnxportlock);
  2740.     if (x < 0 && qnxportlock) {
  2741.         ttclos(0);
  2742.         printf("?Can't get port open count\n");
  2743.         printf("(Try again with SET QNX-PORT-LOCK OFF)\n");
  2744.         return(-1);            /* Indicate device is in use */
  2745.     }
  2746.     if (x > 1) {            /* 1 == me */
  2747.         if (qnxportlock)
  2748.           ttclos(0);
  2749.           return(-2);        /* Indicate device is in use */
  2750.         else if (!quiet)
  2751.           printf("WARNING: \"%s\" looks busy...\n",ttdev);
  2752.     }
  2753.     }
  2754. #endif /* QNX */
  2755.  
  2756. #ifdef Plan9
  2757.     /* take this opportunity to open the control channel */
  2758.     if (p9openttyctl(ttname) < 0)
  2759. #else
  2760.     /* Make sure it's a real tty. */
  2761.     if (!ttfdflg && !isatty(ttyfd) && strcmp(ttname,"/dev/null"))
  2762. #endif /* Plan9 */
  2763.       {
  2764.     fprintf(stderr,"%s is not a terminal device\n",ttname);
  2765.     debug(F111,"ttopen not a tty",ttname,errno);
  2766.     close(ttyfd);
  2767.     ttyfd = -1;
  2768.     wasclosed = 1;
  2769.     signal(SIGINT,occt);
  2770.     return(-1);
  2771.     }
  2772.  
  2773. #ifdef aegis
  2774.     /* Apollo C runtime claims that console pads are tty devices, which
  2775.      * is reasonable, but they aren't any good for packet transfer. */
  2776.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2777.     if (st.all != status_$ok) {
  2778.         fprintf(stderr, "problem getting tty object type: ");
  2779.         error_$print(st);
  2780.     } else if (ttyuid != sio_$uid) { /* reject non-SIO lines */
  2781.         close(ttyfd); ttyfd = -1;
  2782.         wasclosed = 1;
  2783.         errno = ENOTTY; perror(ttname);
  2784.         signal(SIGINT,occt);
  2785.         return(-1);
  2786.     }
  2787. #endif /* aegis */
  2788.  
  2789.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2790.  
  2791.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2792.  
  2793. /* Caller wants us to figure out if line is controlling tty */
  2794.  
  2795.     if (*lcl < 0) {
  2796.         if (strcmp(ttname,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2797.             xlocal = 0;
  2798.         debug(F111,"ttopen ttname=CTTNAM",ttname,xlocal);
  2799.         } else if (strcmp(ttname,cttnam) == 0) {
  2800.             xlocal = 0;
  2801.         debug(F111,"ttopen ttname=cttnam",ttname,xlocal);
  2802.     } else if (cttnam[0]) {
  2803. #ifdef BEBOX_DR7
  2804.             x = ttnmsv;            /* ttyname() is broken */
  2805. #else
  2806.             x = ttyname(ttyfd);         /* Get real name of ttname. */
  2807. #endif /* BEBOX_DR7 */
  2808.         if (!x) x = "";
  2809.         if (*x)
  2810.           xlocal = ((strncmp(x,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  2811.         else
  2812.           xlocal = 1;
  2813.             debug(F111,"ttopen ttyname(ttyfd) xlocal",x,xlocal);
  2814.         }
  2815.     }
  2816.  
  2817. #ifndef NOFDZERO
  2818. /* Note, the following code was added so that Unix "idle-line" snoopers */
  2819. /* would not think Kermit was idle when it was transferring files, and */
  2820. /* maybe log people out. */
  2821.     if (xlocal == 0) {            /* Remote mode */
  2822.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  2823.         debug(F100,"ttopen setting ttyfd = 0","",0);
  2824. #ifdef LYNXOS
  2825.         /* On Lynx OS, fd 0 is open for read only. */
  2826.         dup2(ttyfd,0);
  2827. #endif /* LYNXOS */
  2828.         close(ttyfd);        /* Use file descriptor 0 */
  2829.         ttyfd = 0;
  2830.     } else {            /* Standard i/o is redirected */
  2831.         debug(F101,"ttopen stdio redirected","",ttyfd);
  2832.     }
  2833.     }
  2834. #endif /* NOFDZERO */
  2835.  
  2836. /* Now check if line is locked -- if so fail, else lock for ourselves */
  2837. /* Note: After having done this, don't forget to delete the lock if you */
  2838. /* leave ttopen() with an error condition. */
  2839.  
  2840.     lkf = 0;                            /* Check lock */
  2841.     if (xlocal > 0) {
  2842.     int xx; int xpid;
  2843.         if ((xx = ttlock(ttname)) < 0) { /* Can't lock it. */
  2844.             debug(F111,"ttopen ttlock fails",ttname,xx);
  2845.         /* WARNING - This close() can hang if tty is an empty socket... */
  2846.             close(ttyfd);        /* Close the device. */
  2847.         ttyfd = -1;            /* Erase its file descriptor. */
  2848.         wasclosed = 1;
  2849.         signal(SIGINT,occt);    /* Put old SIGINT back. */
  2850.         sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2851.         if (xx == -2) {        /* If lockfile says device in use, */
  2852. #ifndef NOUUCP
  2853.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2854.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2855.         if (xpid > -1) {    /* If we got a pid */
  2856.                     if (!quiet)
  2857.               printf("Locked by process %d\n",xpid); /* tell them. */
  2858.             sprintf(lockpid,"%d",xpid);    /* Record it too */
  2859.             debug(F110,"ttopen lockpid",lockpid,0);
  2860.         } else if (*flfnam) {
  2861.             extern char *DIRCMD;
  2862.             char *p = NULL;
  2863.             int x;
  2864.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2865.             p = malloc(x);    /* Print a directory listing. */
  2866. /*
  2867.   Note: priv_on() won't help here, because we do not pass privs along to
  2868.   to inferior processes, in this case ls.  So if the real user does not have
  2869.   directory-listing access to the lockfile directory, this will result in
  2870.   something like "not found".  That's why we try this only as a last resort.
  2871. */
  2872.             if (p) {        /* If we got the space... */
  2873.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2874.             zsyscmd(p);    /* Get listing. */
  2875.             if (p) {    /* free the space */
  2876.                 free(p);
  2877.                 p = NULL;
  2878.             }
  2879.             }
  2880.         }
  2881. #endif /* NOUUCP */
  2882.         return(-5);        /* Code for device in use */
  2883.         } else return(-3);        /* Access denied */
  2884.         } else lkf = 1;
  2885.     }
  2886. #else  /* OPENFIRST */
  2887.  
  2888. /*
  2889.   27 Oct 2001: New simpler code that gets the lock first and then opens the
  2890.   device, which eliminates the race condition.  The downside is you can no
  2891.   longer say "set line /dev/ttyp0" or whatever, where /dev/ttyp0 is your login
  2892.   terminal, without trying to create a lockfile, which fails if C-Kermit lacks
  2893.   privs, and if it succeeds, it has created a lockfile where it didn't create
  2894.   one before.
  2895. */
  2896.     xlocal = *lcl;            /* Is the device my login terminal? */
  2897.     debug(F111,"ttopen xlocal","A",xlocal);
  2898.     fnam = ttname;
  2899.     if (strcmp(ttname,CTTNAM) && netconn == 0) {
  2900.     if (zfnqfp(ttname,DEVNAMLEN+1,fullname)) {
  2901.         if ((int)strlen(fullname) > 0)
  2902.           fnam = fullname;
  2903.     }
  2904.     }
  2905.     debug(F110,"ttopen fnam",fnam,0);
  2906.     if (xlocal < 0) {
  2907.     xlocal = (strcmp(fnam,CTTNAM) != 0);
  2908.     }
  2909.     debug(F111,"ttopen xlocal","B",xlocal);
  2910.  
  2911.     lkf = 0;                            /* No lock yet */
  2912.     if (xlocal > 0) {            /* If not... */
  2913.     int xx; int xpid;
  2914.     xx = ttlock(fnam);        /* Try to lock it. */
  2915.     debug(F101,"ttopen ttlock","",xx);
  2916.         if (xx < 0) {            /* Can't lock it. */
  2917.             debug(F111,"ttopen ttlock fails",fnam,xx);
  2918.         if (xx == -2) {        /* If lockfile says device in use, */
  2919. #ifndef NOUUCP
  2920.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2921.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2922.         if (xpid > -1) {    /* If we got a pid */
  2923.                     if (!quiet)
  2924.               printf("Locked by process %d\n",xpid); /* tell them. */
  2925.             ckstrncpy(lockpid,ckitoa(xpid),16);
  2926.             debug(F110,"ttopen lockpid",lockpid,0);
  2927. #ifndef NOPUSH
  2928.         } else if (flfnam[0] && !nopush) {
  2929.             extern char *DIRCMD;
  2930.             char *p = NULL;
  2931.             int x;
  2932.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2933.             p = malloc(x);    /* Print a directory listing. */
  2934. /*
  2935.   Note: priv_on() won't help here, because we do not pass privs along to
  2936.   to inferior processes, in this case ls.  So if the real user does not have
  2937.   directory-listing access to the lockfile directory, this will result in
  2938.   something like "not found".  That's why we try this only as a last resort.
  2939. */
  2940.             if (p) {        /* If we got the space... */
  2941.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2942.             zsyscmd(p);    /* Get listing. */
  2943.             if (p) {    /* free the space */
  2944.                 free(p);
  2945.                 p = NULL;
  2946.             }
  2947.             }
  2948. #endif /* NOPUSH */
  2949.         }
  2950. #endif /* NOUUCP */
  2951.         return(-5);        /* Code for device in use */
  2952.         } else return(-3);        /* Access denied */
  2953.         } else lkf = 1;
  2954.     }
  2955.     /* Have lock -- now it's safe to open the device */
  2956.  
  2957.     debug(F101,"ttopen lkf","",lkf);
  2958.     debug(F101,"ttopen timo","",timo);
  2959.  
  2960.     ttotmo = 0;                /* Flag no timeout */
  2961.     if (timo > 0) {
  2962.     int xx;
  2963.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2964.     xx = alarm(timo);        /* Timed open() */
  2965.     debug(F101,"ttopen alarm","",xx);
  2966.     if (
  2967. #ifdef CK_POSIX_SIG
  2968.         sigsetjmp(sjbuf,1)
  2969. #else
  2970.         setjmp(sjbuf)
  2971. #endif /* CK_POSIX_SIG */
  2972.         ) {
  2973.         ttotmo = 1;            /* Flag timeout. */
  2974.     } else {
  2975.         ttyfd = do_open(fnam);
  2976.     }
  2977.     ttimoff();
  2978.     debug(F111,"ttopen timed ttyfd",fnam,ttyfd);
  2979.     } else {
  2980.     errno = 0;
  2981.     ttyfd = do_open(fnam);
  2982.     debug(F111,"ttopen untimed ttyfd",fnam,ttyfd);
  2983.     }
  2984.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2985.     debug(F111,"ttopen errno",fnam,errno);
  2986.     debug(F111,"ttopen xlocal","C",xlocal);
  2987.     if (xlocal == 0) {
  2988.         debug(F100,"ttopen substituting 0","",0);
  2989.         ttyfd = 0;
  2990.     } else {
  2991.         if (errno > 0 && !quiet) {
  2992.             debug(F111,"ttopen perror",fnam,errno);
  2993.         perror(fnam);        /* Print message */
  2994.         }
  2995.         if (ttunlck())                  /* Release the lock file */
  2996.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  2997.     }
  2998.     }
  2999.  
  3000.     if (ttyfd < 0) {            /* ttyfd is still < 0? */
  3001. #ifdef ATT7300
  3002.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  3003.       ongetty(ttnmsv);        /* yes, restart on tty line */
  3004.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  3005. #else
  3006. #ifdef ACUCNTRL
  3007.         /* Should put call to priv_on() here, but that would be risky! */
  3008.     acucntrl("enable",fnam);    /* acucntrl() program. */
  3009.     /* and priv_off() here... */
  3010. #endif /* ACUNTRL */
  3011. #endif /* ATT7300 */
  3012.  
  3013.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  3014.     if (errno == EACCES) {        /* Device is protected against user */
  3015.         debug(F110,"ttopen EACCESS",fnam,0); /* Return -4 */
  3016.         return(-4);
  3017.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  3018.     }
  3019.  
  3020. /* Make sure it's a real tty. */
  3021.  
  3022. #ifdef Plan9
  3023.     /* take this opportunity to open the control channel */
  3024.     if (p9openttyctl(fnam) < 0)       
  3025. #else
  3026.       if (!ttfdflg && !isatty(ttyfd) && strcmp(fnam,"/dev/null"))
  3027. #endif /* Plan9 */
  3028.     {
  3029.         fprintf(stderr,"%s is not a terminal device\n",fnam);
  3030.         debug(F111,"ttopen not a tty",fnam,errno);
  3031.         if (ttunlck())        /* Release the lock file */
  3032.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  3033.         close(ttyfd);
  3034.         ttyfd = -1;
  3035.         wasclosed = 1;
  3036.         signal(SIGINT,occt);
  3037.         return(-1);
  3038.     }
  3039.  
  3040. #ifdef aegis
  3041.     /*
  3042.       Apollo C runtime claims that console pads are tty devices, which
  3043.       is reasonable, but they aren't any good for packet transfer.
  3044.     */
  3045.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  3046.     if (st.all != status_$ok) {
  3047.     fprintf(stderr, "problem getting tty object type: ");
  3048.     error_$print(st);
  3049.     } else if (ttyuid != sio_$uid) {    /* Reject non-SIO lines */
  3050.     close(ttyfd); ttyfd = -1;
  3051.     wasclosed = 1;
  3052.     errno = ENOTTY; perror(fnam);
  3053.     signal(SIGINT,occt);
  3054.     return(-1);
  3055.     }
  3056. #endif /* aegis */
  3057.  
  3058.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3059.  
  3060.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  3061.  
  3062. /* Caller wants us to figure out if line is controlling tty */
  3063.  
  3064.     if (*lcl < 0) {
  3065.     char * s;
  3066.         if (strcmp(fnam,CTTNAM) == 0) { /* "/dev/tty" always remote */
  3067.             xlocal = 0;
  3068.         debug(F111,"ttopen fnam=CTTNAM",fnam,xlocal);
  3069.         } else if (strcmp(fnam,cttnam) == 0) {
  3070.             xlocal = 0;
  3071.         debug(F111,"ttopen fnam=cttnam",fnam,xlocal);
  3072.     } else if (cttnam[0]) {
  3073. #ifdef BEBOX_DR7
  3074.             s = ttnmsv;            /* ttyname() is broken */
  3075. #else
  3076.             s = ttyname(ttyfd);         /* Get real name of ttname. */
  3077. #endif /* BEBOX_DR7 */
  3078.         if (!s) s = "";
  3079.         if (*s)
  3080.           xlocal = ((strncmp(s,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  3081.         else
  3082.           xlocal = 1;
  3083.             debug(F111,"ttopen ttyname(ttyfd) xlocal",s,xlocal);
  3084.         }
  3085.     }
  3086.  
  3087. #ifndef NOFDZERO
  3088. /* Note, the following code was added so that Unix "idle-line" snoopers */
  3089. /* would not think Kermit was idle when it was transferring files, and */
  3090. /* maybe log people out. */
  3091.     if (xlocal == 0) {            /* Remote mode */
  3092.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  3093.         debug(F100,"ttopen setting ttyfd = 0","",0);
  3094. #ifdef LYNXOS
  3095.         /* On Lynx OS, fd 0 is open for read only. */
  3096.         dup2(ttyfd,0);
  3097. #endif /* LYNXOS */
  3098.         close(ttyfd);        /* Use file descriptor 0 */
  3099.         ttyfd = 0;
  3100.     } else {            /* Standard i/o is redirected */
  3101.         debug(F101,"ttopen stdio redirected","",ttyfd);
  3102.     }
  3103.     }
  3104. #endif /* NOFDZERO */
  3105. #endif /* OPENFIRST */
  3106.  
  3107. /* Got the line, now set the desired value for local. */
  3108.  
  3109.     if (*lcl != 0) *lcl = xlocal;
  3110.  
  3111. /* Some special stuff for v7... */
  3112.  
  3113. #ifdef  V7
  3114. #ifndef MINIX
  3115.     if (kmem[TTY] < 0) {        /*  If open, then skip this.  */
  3116.     qaddr[TTY] = initrawq(ttyfd);   /* Init the queue. */
  3117.     if ((kmem[TTY] = open("/dev/kmem", 0)) < 0) {
  3118.         fprintf(stderr, "Can't read /dev/kmem in ttopen.\n");
  3119.         perror("/dev/kmem");
  3120.         exit(1);
  3121.     }
  3122.     }
  3123. #endif /* !MINIX */
  3124. #endif /* V7 */
  3125.  
  3126. /* No failure returns after this point */
  3127.  
  3128. #ifdef ultrix
  3129.     ioctl(ttyfd, TIOCMODEM, &temp);
  3130. #ifdef TIOCSINUSE
  3131.     if (xlocal && ioctl(ttyfd, TIOCSINUSE, NULL) < 0) {
  3132.     if (!quiet)
  3133.       perror(fnam);
  3134.     }
  3135. #endif /* TIOCSINUSE */
  3136. #endif /* ultrix */
  3137.  
  3138. /* Get tty device settings  */
  3139.  
  3140. #ifdef BSD44ORPOSIX            /* POSIX */
  3141.     tcgetattr(ttyfd,&ttold);
  3142.     debug(F101,"ttopen tcgetattr ttold.c_lflag","",ttold.c_lflag);
  3143.     tcgetattr(ttyfd,&ttraw);
  3144.     debug(F101,"ttopen tcgetattr ttraw.c_lflag","",ttraw.c_lflag);
  3145.     tcgetattr(ttyfd,&tttvt);
  3146.     debug(F101,"ttopen tcgetattr tttvt.c_lflag","",tttvt.c_lflag);
  3147. #else                    /* BSD, V7, and all others */
  3148. #ifdef ATTSV                /* AT&T UNIX */
  3149.     ioctl(ttyfd,TCGETA,&ttold);
  3150.     debug(F101,"ttopen ioctl TCGETA ttold.c_lflag","",ttold.c_lflag);
  3151.     ioctl(ttyfd,TCGETA,&ttraw);
  3152.     ioctl(ttyfd,TCGETA,&tttvt);
  3153. #else
  3154. #ifdef BELLV10
  3155.     ioctl(ttyfd,TIOCGETP,&ttold);
  3156.     debug(F101,"ttopen BELLV10 ttold.sg_flags","",ttold.sg_flags);
  3157.     ioctl(ttyfd,TIOCGDEV,&tdold);
  3158.     debug(F101,"ttopen BELLV10 tdold.flags","",tdold.flags);
  3159. #else
  3160.     gtty(ttyfd,&ttold);
  3161.     debug(F101,"ttopen gtty ttold.sg_flags","",ttold.sg_flags);
  3162. #endif /* BELLV10 */
  3163.  
  3164. #ifdef sony_news            /* Sony NEWS */
  3165.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get console Kanji mode */
  3166.     perror("ttopen error getting Kanji mode");
  3167.     debug(F101,"ttopen error getting Kanji mode","",0);
  3168.     km_ext = -1;            /* Make sure this stays undefined. */
  3169.     }
  3170. #endif /* sony_news */
  3171.  
  3172. #ifdef TIOCGETC
  3173.     debug(F100,"ttopen TIOCGETC","",0);
  3174.     tcharf = 0;                /* In remote mode, also get */
  3175.     if (xlocal == 0) {            /* special characters */
  3176.     if (ioctl(ttyfd,TIOCGETC,&tchold) < 0) {
  3177.         debug(F100,"ttopen TIOCGETC failed","",0);
  3178.     } else {
  3179.         tcharf = 1;            /* It worked. */
  3180.         ioctl(ttyfd,TIOCGETC,&tchnoi); /* Get another copy */
  3181.         debug(F100,"ttopen TIOCGETC ok","",0);
  3182.     }
  3183.     }
  3184. #else
  3185.     debug(F100,"ttopen TIOCGETC not defined","",0);
  3186. #endif /* TIOCGETC */
  3187.  
  3188. #ifdef TIOCGLTC
  3189.     debug(F100,"ttopen TIOCGLTC","",0);
  3190.     ltcharf = 0;            /* In remote mode, also get */
  3191.     if (xlocal == 0) {            /* local special characters */
  3192.     if (ioctl(ttyfd,TIOCGLTC,<chold) < 0) {
  3193.         debug(F100,"ttopen TIOCGLTC failed","",0);
  3194.     } else {
  3195.         ltcharf = 1;        /* It worked. */
  3196.         ioctl(ttyfd,TIOCGLTC,<chnoi); /* Get another copy */
  3197.         debug(F100,"ttopen TIOCGLTC ok","",0);
  3198.     }
  3199.     }
  3200. #else
  3201.     debug(F100,"ttopen TIOCGLTC not defined","",0);
  3202. #endif /* TIOCGLTC */
  3203.  
  3204. #ifdef TIOCLGET
  3205.     debug(F100,"ttopen TIOCLGET","",0);
  3206.     lmodef = 0;
  3207.     if (ioctl(ttyfd,TIOCLGET,&lmode) < 0) {
  3208.     debug(F100,"ttopen TIOCLGET failed","",0);
  3209.     } else {
  3210.     lmodef = 1;
  3211.     debug(F100,"ttopen TIOCLGET ok","",0);
  3212.     }
  3213. #endif /* TIOCLGET */
  3214.  
  3215. #ifdef BELLV10
  3216.     ioctl(ttyfd,TIOCGETP,&ttraw);
  3217.     ioctl(ttyfd,TIOCGETP,&tttvt);
  3218. #else
  3219.     gtty(ttyfd,&ttraw);                 /* And a copy of it for packets*/
  3220.     gtty(ttyfd,&tttvt);                 /* And one for virtual tty service */
  3221. #endif /* BELLV10 */
  3222.  
  3223. #endif /* ATTSV */
  3224. #endif /* BSD44ORPOSIX */
  3225.  
  3226. /* Section for changing line discipline.  It's restored in ttres(). */
  3227.  
  3228. #ifdef AIXRS
  3229. #ifndef AIX41
  3230.     { union txname ld_name; int ld_idx = 0;
  3231.       ttld = 0;
  3232.         do {
  3233.         ld_name.tx_which = ld_idx++;
  3234.         ioctl(ttyfd, TXGETCD, &ld_name);
  3235.       if (!strncmp(ld_name.tx_name, "rts", 3))
  3236.           ttld |= 1;
  3237.         } while (*ld_name.tx_name);
  3238.         debug(F101,"AIX line discipline","",ttld);
  3239.       }
  3240. #endif /* AIX41 */
  3241. #endif /* AIXRS */
  3242.  
  3243. #ifdef BSD41
  3244. /* For 4.1BSD only, force "old" tty driver, new one botches TANDEM. */
  3245.     { int k;
  3246.       ioctl(ttyfd, TIOCGETD, &ttld);    /* Get and save line discipline */
  3247.       debug(F101,"4.1bsd line discipline","",ttld);
  3248.       k = OTTYDISC;            /* Switch to "old" discipline */
  3249.       k = ioctl(ttyfd, TIOCSETD, &k);
  3250.       debug(F101,"4.1bsd tiocsetd","",k);
  3251.     }
  3252. #endif /* BSD41 */
  3253.  
  3254. #ifdef aegis
  3255.     /* This was previously done before the last two TCGETA or gtty above,
  3256.      * in both the ATTSV and not-ATTSV case.  If it is not okay to have only
  3257.      * one copy if it here instead, give us a shout!
  3258.      */
  3259.     sio_$control((short)ttyfd, sio_$raw_nl, false, st);
  3260.     if (xlocal) {       /* ignore breaks from local line */
  3261.         sio_$control((short)ttyfd, sio_$int_enable, false, st);
  3262.         sio_$control((short)ttyfd, sio_$quit_enable, false, st);
  3263.     }
  3264. #endif /* aegis */
  3265.  
  3266. #ifdef VXVE
  3267.     ttraw.c_line = 0;                   /* STTY line 0 for VX/VE */
  3268.     tttvt.c_line = 0;                   /* STTY line 0 for VX/VE */
  3269.     ioctl(ttyfd,TCSETA,&ttraw);
  3270. #endif /* vxve */
  3271.  
  3272. /* If O_NDELAY was used during open(), then remove it now. */
  3273.  
  3274. #ifdef O_NDELAY
  3275.     debug(F100,"ttopen O_NDELAY","",0);
  3276.     if (xlocal > 0) {
  3277.       if (fcntl(ttyfd, F_GETFL, 0) & O_NDELAY) {
  3278.     debug(F100,"ttopen fcntl O_NDELAY","",0);
  3279. #ifndef aegis
  3280.     if (fcntl(ttyfd,F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY) < 0) {
  3281.         debug(F100,"ttopen fcntl failure to unset O_NDELAY","",0);
  3282.         perror("Can't unset O_NDELAY");
  3283.     }
  3284. #endif /* aegis */
  3285.     /* Some systems, notably Xenix (don't know how common this is in
  3286.      * other systems), need special treatment to get rid of the O_NDELAY
  3287.      * behaviour on read() with respect to carrier presence (i.e. read()
  3288.      * returning 0 when carrier absent), even though the above fcntl()
  3289.      * is enough to make read() wait for input when carrier is present.
  3290.      * This magic, in turn, requires CLOCAL for working when the carrier
  3291.      * is absent. But if xlocal == 0, presumably you already have CLOCAL
  3292.      * or you have a carrier, otherwise you wouldn't be running this.
  3293.      */
  3294.     debug(F101,"ttopen xlocal","",xlocal);
  3295. #ifdef ATTSV
  3296. #ifdef BSD44ORPOSIX
  3297. #ifdef COMMENT                /* 12 Aug 1997 */
  3298. #ifdef __bsdi__
  3299.     if (xlocal)
  3300.       ttraw.c_cflag |= CLOCAL;
  3301. #else
  3302. #ifdef __FreeBSD__
  3303.     if (xlocal)
  3304.       ttraw.c_cflag |= CLOCAL;
  3305. #endif /* __FreeBSD__ */
  3306. #endif /* __bsdi__ */
  3307. #else /* Not COMMENT */
  3308. #ifdef CLOCAL
  3309.     if (xlocal)            /* Unset this if it's defined. */
  3310.       ttraw.c_cflag |= CLOCAL;
  3311. #endif /* CLOCAL */
  3312. #endif /* COMMENT */
  3313.     debug(F101,"ttopen BSD44ORPOSIX calling tcsetattr","",TCSADRAIN);
  3314.     if (tcsetattr(ttyfd, TCSADRAIN, &ttraw) < 0) {
  3315.         debug(F100,"ttopen POSIX tcseattr fails","",0);
  3316.         perror("tcsetattr");
  3317.     }
  3318. #else /* !BSD44ORPOSIX */
  3319.     if (xlocal) {
  3320.         ttraw.c_cflag |= CLOCAL;
  3321.         debug(F100,"ttopen calling ioctl(TCSETA)","",0);
  3322.         errno = 0;
  3323.         if (ioctl(ttyfd, TCSETA, &ttraw) < 0) {
  3324.                 debug(F101,"ttopen ioctl(TCSETA) fails","",errno);
  3325.                 perror("ioctl(TCSETA)");
  3326.             }
  3327.     }
  3328. #endif /* BSD44ORPOSIX */
  3329. #endif /* ATTSV */
  3330. #ifndef NOCOTFMC /* = NO Close(Open()) To Force Mode Change */
  3331. /* Reportedly lets uugetty grab the device in SCO UNIX 3.2 / XENIX 2.3 */
  3332.     debug(F100,"ttopen executing close/open","",0);
  3333.     close( priv_opn(fnam, O_RDWR) ); /* Magic to force change. */
  3334. #endif /* NOCOTFMC */
  3335.       }
  3336.     }
  3337. #endif /* O_NDELAY */
  3338.  
  3339. /* Instruct the system how to treat the carrier, and set a few other tty
  3340.  * parameters.
  3341.  *
  3342.  * This also undoes the temporary setting of CLOCAL that may have been done
  3343.  * for the close(open()) above (except in Xenix).  Also throw in ~ECHO, to
  3344.  * prevent the other end of the line from sitting there talking to itself,
  3345.  * producing garbage when the user performs a connect.
  3346.  *
  3347.  * SCO Xenix unfortunately seems to ignore the actual state of CLOCAL.
  3348.  * Now it thinks CLOCAL is always on. It seems the only real solution for
  3349.  * Xenix is to switch between the lower and upper case device names.
  3350.  *
  3351.  * This section may at some future time expand into setting a complete
  3352.  * collection of tty parameters, or call a function shared with ttpkt()/
  3353.  * ttvt() that does so.  On the other hand, the initial parameters are not
  3354.  * that important, since ttpkt() or ttvt() should always fix that before
  3355.  * any communication is done.  Well, we'll see...
  3356.  */
  3357.     if (xlocal) {
  3358.         curcarr = -2;
  3359.     debug(F100,"ttopen calling carrctl","",0);
  3360.     carrctl(&ttraw, ttcarr == CAR_ON);
  3361.     debug(F100,"ttopen carrctl ok","",0);
  3362.  
  3363. #ifdef COHERENT
  3364. #define SVORPOSIX
  3365. #endif /* COHERENT */
  3366.  
  3367. #ifdef SVORPOSIX
  3368.     ttraw.c_lflag &= ~ECHO;
  3369.     ttold.c_lflag &= ~ECHO;
  3370. #ifdef BSD44ORPOSIX
  3371.     y = tcsetattr(ttyfd, TCSADRAIN, &ttraw);
  3372.     debug(F101,"ttopen tcsetattr","",y);
  3373. #else
  3374.     y = ioctl(ttyfd, TCSETA, &ttraw);
  3375.     debug(F100,"ttopen ioctl","",y);
  3376. #endif /* BSD44ORPOSIX */
  3377.  
  3378. #else /* BSD, etc */
  3379.     ttraw.sg_flags &= ~ECHO;
  3380.     ttold.sg_flags &= ~ECHO;
  3381. #ifdef BELLV10
  3382.     y = ioctl(ttyfd,TIOCSETP,&ttraw);
  3383.     debug(F100,"ttopen ioctl","",y);
  3384. #else
  3385.     y = stty(ttyfd,&ttraw);
  3386.     debug(F100,"ttopen stty","",y);
  3387. #endif /* BELLV10 */
  3388. #endif /* SVORPOSIX */
  3389.  
  3390. #ifdef COHERENT
  3391. #undef SVORPOSIX
  3392. #endif /* COHERENT */
  3393.  
  3394.     /* ttflui(); */  /*  This fails for some reason.  */
  3395.     }
  3396.  
  3397.     /* Get current speed */
  3398.  
  3399. #ifndef BEBOX
  3400.     ttspeed = ttgspd();
  3401. #else
  3402.     ttspeed = 19200;
  3403. #endif /* !BEBOX */
  3404.     debug(F101,"ttopen ttspeed","",ttspeed);
  3405.  
  3406.     /* Done, make entries in debug log, restore Ctrl-C trap, and return. */
  3407.  
  3408.     debug(F101,"ttopen ttyfd","",ttyfd);
  3409.     debug(F101,"ttopen *lcl","",*lcl);
  3410.     debug(F111,"ttopen lock file",flfnam,lkf);
  3411.     signal(SIGINT,occt);
  3412.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3413.     gotsigs = 0;
  3414.     return(0);
  3415. }
  3416.  
  3417.  
  3418. /*  D O _ O P E N  --  Do the right kind of open() call for the tty. */
  3419.  
  3420. int
  3421. do_open(ttname) char *ttname; {
  3422.     int flags;
  3423.  
  3424. #ifdef QNX6
  3425.     /* O_NONBLOCK on /dev/tty makes open() fail */
  3426.     return(priv_opn(ttname, O_RDWR |
  3427.             (
  3428.              ((int)strcmp(ttname,"/dev/tty") == 0) ?
  3429.              0 :
  3430.              (ttcarr != CAR_ON) ? O_NONBLOCK : 0)
  3431.             )
  3432.        ); 
  3433. #else  /* !QNX6 */
  3434.  
  3435. #ifndef    O_NDELAY            /* O_NDELAY not defined */
  3436.     return(priv_opn(ttname,2));
  3437. #else                    /* O_NDELAY defined */
  3438.  
  3439. #ifdef ATT7300
  3440. /*
  3441.  Open comms line without waiting for carrier so initial call does not hang
  3442.  because state of "modem" is likely unknown at the initial call  -jrd.
  3443.  If this is needed for the getty stuff to work, and the open would not work
  3444.  without O_NDELAY when getty is still on, then this special case is ok.
  3445.  Otherwise, get rid of it. -ske
  3446. */
  3447.     return(priv_opn(ttname, O_RDWR | O_NDELAY));
  3448.  
  3449. #else    /* !ATT7300 */
  3450.  
  3451.     /* Normal case. Use O_NDELAY according to SET CARRIER. See ttscarr(). */
  3452.     flags = O_RDWR;
  3453.     debug(F101,"do_open xlocal","",xlocal);
  3454.     debug(F111,"do_open flags A",ttname,flags);
  3455.     if (xlocal && (ttcarr != CAR_ON))
  3456.       flags |= O_NDELAY;
  3457.     debug(F111,"do_open flags B",ttname,flags);
  3458.     return(priv_opn(ttname, flags));
  3459. #endif /* !ATT7300 */
  3460. #endif /* O_NDELAY */
  3461. #endif /* QNX6 */
  3462. }
  3463.  
  3464. /*  T T C L O S  --  Close the TTY, releasing any lock.  */
  3465.  
  3466. static int ttc_state = 0;        /* ttclose() state */
  3467. static char * ttc_nam[] = { "setup", "hangup", "reset", "close" };
  3468.  
  3469. int
  3470. ttclos(foo) int foo; {            /* Arg req'd for signal() prototype */
  3471.     int xx, x = 0;
  3472.     extern int exithangup;
  3473.  
  3474.     debug(F101,"ttclos ttyfd","",ttyfd);
  3475.     debug(F101,"ttclos netconn","",netconn);
  3476.     debug(F101,"ttclos xlocal","",xlocal);
  3477. #ifdef NOFDZERO
  3478.     debug(F100,"ttclos NOFDZERO","",0);
  3479. #endif /* NOFDZERO */
  3480.  
  3481. #ifdef COMMENT
  3482. #ifdef TTLEBUF
  3483.     le_init();                /* No need for any of this */
  3484. #endif /* TTLEBUF */
  3485. #endif /* COMMENT */
  3486.  
  3487.     if (ttyfd < 0)            /* Wasn't open. */
  3488.       return(0);
  3489.  
  3490.     if (ttfdflg)            /* If we inherited ttyfd from */
  3491.       return(0);            /* another process, don't close it. */
  3492.  
  3493.     tvtflg = 0;                /* (some day get rid of this...) */
  3494.     gotsigs = 0;
  3495.  
  3496. #ifdef IKSD
  3497.     if (inserver) {
  3498. #ifdef TNCODE
  3499.           tn_push();                    /* Place any waiting data into input*/
  3500.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  3501.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  3502.           tn_reset();                   /* The Reset Telnet Option table.  */
  3503. #endif /* TNCODE */
  3504. #ifdef CK_SSL
  3505.       if (ssl_active_flag) {
  3506.           if (ssl_debug_flag)
  3507.         BIO_printf(bio_err,"calling SSL_shutdown(ssl)\n");
  3508.           SSL_shutdown(ssl_con);
  3509.           SSL_free(ssl_con);
  3510.           ssl_con = NULL;
  3511.           ssl_active_flag = 0;
  3512.       }
  3513.       if (tls_active_flag) {
  3514.           if (ssl_debug_flag)
  3515.         BIO_printf(bio_err,"calling SSL_shutdown(tls)\n");
  3516.           SSL_shutdown(tls_con);
  3517.           SSL_free(tls_con);
  3518.           tls_con = NULL;
  3519.           tls_active_flag = 0;
  3520.       }
  3521. #endif /* CK_SSL */
  3522.     }
  3523. #endif /* IKSD */
  3524. #ifdef NETCMD
  3525.     if (ttpipe) {            /* We've been using a pipe */
  3526.     /* ttpipe = 0; */
  3527.     if (ttpid > 0) {
  3528.         int wstat;
  3529.         int statusp;
  3530.         close(fdin);        /* Close these. */
  3531.         close(fdout);
  3532.         fdin = fdout = -1;
  3533.         kill(ttpid,1);        /* Kill fork with SIGHUP */
  3534.         while (1) {
  3535.         wstat = wait(&statusp);
  3536.         if (wstat == ttpid || wstat == -1)
  3537.           break;
  3538.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  3539.         }
  3540.         ttpid = 0;
  3541.     }
  3542.     netconn = 0;
  3543.     wasclosed = 1;
  3544.     ttyfd = -1;
  3545.     return(0);
  3546.     }
  3547. #endif /* NETCMD */
  3548. #ifdef NETPTY
  3549.     if (ttpty) {
  3550. #ifndef NODOPTY
  3551.         end_pty();
  3552. #endif /* NODOPTY */
  3553.         close(ttyfd);
  3554.     netconn = 0;
  3555.     wasclosed = 1;
  3556.         ttpty = 0;
  3557.         ttyfd = -1;
  3558.         return(0);
  3559.     }
  3560. #endif /* NETPTY */
  3561.  
  3562. #ifdef    NETCONN
  3563.     if (netconn) {            /* If it's a network connection. */
  3564.     debug(F100,"ttclos closing net","",0);
  3565.     netclos();            /* Let the network module close it. */
  3566.     netconn = 0;            /* No more network connection. */
  3567.     debug(F101,"ttclos ttyfd after netclos","",ttyfd); /* Should be -1 */
  3568.     return(0);
  3569.     }
  3570. #endif    /* NETCONN */
  3571.  
  3572.     if (xlocal) {            /* We're closing a SET LINE device */
  3573. #ifdef FT21                /* Fortune 2.1-specific items ... */
  3574.     ioctl(ttyfd,TIOCHPCL, NULL);
  3575. #endif /* FT21 */
  3576. #ifdef ultrix                /* Ultrix-specific items ... */
  3577. #ifdef TIOCSINUSE
  3578.     /* Unset the INUSE flag that we set in ttopen() */
  3579.     ioctl(ttyfd, TIOCSINUSE, NULL);
  3580. #endif /* TIOCSINUSE */
  3581.     ioctl(ttyfd, TIOCNMODEM, &x);
  3582. #ifdef COMMENT
  3583.     /* What was this? */
  3584.     ioctl(ttyfd, TIOCNCAR, NULL);
  3585. #endif /* COMMENT */
  3586. #endif /* ultrix */
  3587.     }
  3588.  
  3589.     /* This is to prevent us from sticking in tthang() or close(). */
  3590.  
  3591. #ifdef O_NDELAY
  3592. #ifndef aegis
  3593.     if (ttyfd > 0) {            /* But skip it on stdin. */
  3594.     debug(F100,"ttclos setting O_NDELAY","",0);
  3595.     x = fcntl(ttyfd,F_SETFL,fcntl(ttyfd,F_GETFL, 0)|O_NDELAY);
  3596. #ifdef DEBUG
  3597.     if (deblog && x == -1) {
  3598.         perror("Warning - Can't set O_NDELAY");
  3599.         debug(F101,"ttclos fcntl failure to set O_NDELAY","",x);
  3600.     }
  3601. #endif /* DEBUG */
  3602.     }
  3603. #endif /* aegis */
  3604. #endif /* O_NDELAY */
  3605.  
  3606.     x = 0;
  3607.     ttc_state = 0;
  3608.     if (xlocal
  3609. #ifdef NOFDZERO
  3610.     || ttyfd > 0
  3611. #endif /* NOFDZERO */
  3612.     ) {
  3613.     saval = signal(SIGALRM,xtimerh); /* Enable timer interrupt. */
  3614.     xx = alarm(8);            /* Allow 8 seconds. */
  3615.     debug(F101,"ttclos alarm","",xx);
  3616.     if (
  3617. #ifdef CK_POSIX_SIG
  3618.         sigsetjmp(sjbuf,1)
  3619. #else
  3620.         setjmp(sjbuf)
  3621. #endif /* CK_POSIX_SIG */
  3622.         ) {                /* Timer went off? */
  3623.         x = -1;
  3624. #ifdef DEBUG
  3625.         debug(F111,"ttclos ALARM TRAP errno",ckitoa(ttc_state),errno);
  3626.         printf("ttclos() timeout: %s\n", ttc_nam[ttc_state]);
  3627. #endif /* DEBUG */
  3628.     }
  3629.     /* Hang up the device (drop DTR) */
  3630.  
  3631.     errno = 0;
  3632.     debug(F111,"ttclos A",ckitoa(x),ttc_state);
  3633.     if (ttc_state < 1) {
  3634.         ttc_state = 1;
  3635.         debug(F101,"ttclos exithangup","",exithangup);
  3636.         if (exithangup) {
  3637.         alarm(8);        /* Re-arm the timer */
  3638.         debug(F101,"ttclos calling tthang()","",x);
  3639.         x = tthang();        /* Hang up first, then... */
  3640.         debug(F101,"ttclos tthang()","",x);
  3641.         }
  3642. #ifndef CK_NOHUPCL
  3643. /*
  3644.   Oct 2006 - Leave DTR on if SET EXIT HANGUP OFF.
  3645.   Suggested by Soewono Effendi.
  3646. */
  3647. #ifdef HUPCL
  3648.         else {
  3649.         ttold.c_cflag &= ~HUPCL; /* Let's see how this travels */
  3650. #ifdef BSD44ORPOSIX
  3651.         tcsetattr(ttyfd,TCSANOW,&ttold);
  3652. #else /* !BSD44ORPOSIX */
  3653. #ifdef ATTSV
  3654.         ioctl(ttyfd,TCSETAW,&ttold);        
  3655. #else  /* !ATTSV */
  3656.         stty(ttyfd,&ttold);
  3657. #endif    /* ATTSV */
  3658. #endif    /* BSD44ORPOSIX */
  3659.         }
  3660. #endif    /* HUPCL */
  3661. #endif    /* CK_NOHUPCL */
  3662.     }
  3663.     /* Put back device modes as we found them */
  3664.  
  3665.     errno = 0;
  3666.     debug(F111,"ttclos B",ckitoa(x),ttc_state);
  3667.     if (ttc_state < 2) {
  3668.         ttc_state = 2;
  3669.         /* Don't try to mess with tty modes if tthang failed() */
  3670.         /* since it probably won't work. */
  3671.         if (x > -1) {
  3672.         debug(F101,"ttclos calling ttres()","",x);
  3673.         signal(SIGALRM,xtimerh); /* Re-enable the alarm. */
  3674.         alarm(8);        /* Re-arm the timer */
  3675.         x = ttres();        /* Reset device modes. */
  3676.         debug(F101,"ttclos ttres()","",x);
  3677.         alarm(0);
  3678.         }
  3679.     }
  3680.     /* Close the device */
  3681.  
  3682.     errno = 0;
  3683.     debug(F101,"ttclos C","",ttc_state);
  3684.     if (ttc_state < 3) {
  3685.         ttc_state = 3;
  3686.         errno = 0;
  3687.         debug(F101,"ttclos calling close","",x);
  3688.         signal(SIGALRM,xtimerh);    /* Re-enable alarm. */
  3689.         alarm(8);            /* Re-arm the timer */
  3690.         x = close(ttyfd);        /* Close the device. */
  3691.         debug(F101,"ttclos close()","",x);
  3692.         if (x > -1)
  3693.           ttc_state = 3;
  3694.     }
  3695.     debug(F101,"ttclos D","",ttc_state);
  3696.     ttimoff();            /* Turn off timer. */
  3697.     if (x < 0) {
  3698.         printf("?WARNING - close failed: %s\n",ttnmsv);
  3699. #ifdef DEBUG
  3700.         if (deblog) {
  3701.         printf("errno = %d\n", errno);
  3702.         debug(F101,"ttclos failed","",errno);
  3703.         }
  3704. #endif /* DEBUG */
  3705.     }
  3706.     /* Unlock after closing but before any getty mumbo jumbo */
  3707.  
  3708.     debug(F100,"ttclos about to call ttunlck","",0);
  3709.         if (ttunlck())                  /* Release uucp-style lock */
  3710.       fprintf(stderr,"Warning, problem releasing lock\r\n");
  3711.     }
  3712.  
  3713. /* For bidirectional lines, restore getty if it was there before. */
  3714.  
  3715. #ifdef ACUCNTRL                /* 4.3BSD acucntrl() method. */
  3716.     if (xlocal) {
  3717.     debug(F100,"ttclos ACUCNTRL","",0);
  3718.     acucntrl("enable",ttnmsv);    /* Enable getty on the device. */
  3719.     }
  3720. #else
  3721. #ifdef ATT7300                /* ATT UNIX PC (3B1, 7300) method. */
  3722.     if (xlocal) {
  3723.     debug(F100,"ttclos ATT7300 ongetty","",0);
  3724.     if (attmodem & DOGETY)        /* Was getty(1m) running before us? */
  3725.       ongetty(ttnmsv);        /* Yes, restart getty on tty line */
  3726.     attmodem &= ~DOGETY;        /* No phone in use, getty restored */
  3727.     }
  3728. #endif /* ATT7300 */
  3729. #endif /* System-dependent getty-restoring methods */
  3730.  
  3731. #ifdef sony_news
  3732.     km_ext = -1;            /* Invalidate device's Kanji-mode */
  3733. #endif /* sony_news */
  3734.  
  3735.     ttyfd = -1;                         /* Invalidate the file descriptor. */
  3736.     wasclosed = 1;
  3737.     debug(F100,"ttclos done","",0);
  3738.     return(0);
  3739. }
  3740.  
  3741. /*  T T H A N G  --  Hangup phone line or network connection.  */
  3742. /*
  3743.   Returns:
  3744.   0 if it does nothing.
  3745.   1 if it believes that it hung up successfully.
  3746.  -1 if it believes that the hangup attempt failed.
  3747. */
  3748.  
  3749. #define HUPTIME 500            /* Milliseconds for hangup */
  3750.  
  3751. #ifdef COMMENT
  3752. /* The following didn't work but TIOCSDTR does work */
  3753. #ifdef UNIXWARE
  3754. /* Define HUP_POSIX to force non-POSIX builds to use the POSIX hangup method */
  3755. #ifndef POSIX                /* Such as Unixware 1.x, 2.x */
  3756. #ifndef HUP_POSIX
  3757. #define HUP_POSIX
  3758. #endif /* HUP_POSIX */
  3759. #endif /* POSIX */
  3760. #endif /* UNIXWARE */
  3761. #endif /* COMMENT */
  3762.  
  3763. #ifndef USE_TIOCSDTR
  3764. #ifdef __NetBSD__
  3765. /* Because the POSIX method (set output speed to 0) doesn't work in NetBSD */
  3766. #ifdef TIOCSDTR
  3767. #ifdef TIOCCDTR
  3768. #define USE_TIOCSDTR
  3769. #endif /* TIOCCDTR */
  3770. #endif /* TIOCSDTR */
  3771. #endif /* __NetBSD__ */
  3772. #endif /* USE_TIOCSDTR */
  3773.  
  3774. #ifndef HUP_CLOSE_POSIX
  3775. #ifdef OU8
  3776. #define HUP_CLOSE_POSIX
  3777. #else
  3778. #ifdef CK_SCOV5
  3779. #define HUP_CLOSE_POSIX
  3780. #endif /* CK_SCOV5 */
  3781. #endif /* OU8 */
  3782. #endif /* HUP_CLOSE_POSIX */
  3783.  
  3784. #ifdef NO_HUP_CLOSE_POSIX
  3785. #ifdef HUP_CLOSE_POSIX
  3786. #undef HUP_CLOSE_POSIX
  3787. #endif /* HUP_CLOSE_POSIX */
  3788. #endif /* NO_HUP_CLOSE_POSIX */
  3789.  
  3790. int
  3791. tthang() {
  3792. #ifdef NOLOCAL
  3793.     return(0);
  3794. #else
  3795.     int x = 0;                /* Sometimes used as return code. */
  3796. #ifndef POSIX
  3797.     int z;                /* worker */
  3798. #endif /* POSIX */
  3799.  
  3800. #ifdef COHERENT
  3801. #define SVORPOSIX
  3802. #endif /* COHERENT */
  3803.  
  3804. #ifdef SVORPOSIX            /* AT&T, POSIX, HPUX declarations. */
  3805.     int spdsav;                /* for saving speed */
  3806. #ifdef HUP_POSIX
  3807.     int spdsavi;
  3808. #else
  3809. #ifdef BSD44ORPOSIX
  3810.     int spdsavi;
  3811. #endif /* BSD44ORPOSIX */
  3812. #endif /* HUP_POSIX */
  3813. #ifdef HPUX
  3814. /*
  3815.   Early versions of HP-UX omitted the mflag typedef.  If you get complaints
  3816.   about it, just change it to long (or better still, unsigned long).
  3817. */
  3818.     mflag
  3819.       dtr_down = 00000000000,
  3820.       modem_rtn,
  3821.       modem_sav;
  3822.     char modem_state[64];
  3823. #endif /* HPUX */
  3824.     int flags;                /* fcntl flags */
  3825.     unsigned short ttc_save;
  3826. #endif /* SVORPOSIX */
  3827.  
  3828.     if (ttyfd < 0) return(0);           /* Don't do this if not open  */
  3829.     if (xlocal < 1) return(0);        /* Don't do this if not local */
  3830.  
  3831. #ifdef NETCMD
  3832.     if (ttpipe)
  3833.       return((ttclos(0) < 0) ? -1 : 1);
  3834. #endif /* NETCMD */
  3835. #ifdef NETPTY
  3836.     if (ttpty)
  3837.       return((ttclos(0) < 0) ? -1 : 1);
  3838. #endif /* NETPTY */
  3839. #ifdef NETCONN
  3840.     if (netconn) {            /* Network connection. */
  3841. #ifdef TN_COMPORT
  3842.         if (istncomport()) {
  3843.             int rc = tnc_set_dtr_state(0);
  3844.             if (rc >= 0) {
  3845.                 msleep(HUPTIME);
  3846.                 rc = tnc_set_dtr_state(1);
  3847.             }
  3848.             return(rc >= 0 ? 1 : -1);
  3849.         } else
  3850. #endif /* TN_COMPORT */
  3851.       return((netclos() < 0) ? -1 : 1); /* Just close it. */
  3852.   }
  3853. #endif /* NETCONN */
  3854.  
  3855. /* From here down, we handle real tty devices. */
  3856. #ifdef HUP_POSIX
  3857. /*
  3858.   e.g. for Unixware 2, where we don't have a full POSIX build, we
  3859.   still have to use POSIX-style hangup.  Thus the duplication of this
  3860.   and the next case, the only difference being we use a local termios
  3861.   struct here, since a different model is used elsewhere.
  3862.  
  3863.   NO LONGER USED as of C-Kermit 8.0 -- it turns out that this method,
  3864.   even though it compiles and executes without error, doesn't actually
  3865.   work (i.e. DTR does not drop), whereas the TIOCSDTR method works just fine,
  3866. */
  3867.     {
  3868.     struct termios ttcur;
  3869.     int x;
  3870.     debug(F100,"tthang HUP_POSIX style","",0);
  3871.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3872.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3873.     if (x < 0) return(-1);
  3874.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3875.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3876.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3877.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3878.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3879.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3880.     if (x < 0) return(-1);
  3881.     x = cfsetispeed(&ttcur,B0);
  3882.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3883.     if (x < 0) return(-1);
  3884.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3885.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3886.     if (x < 0) return(-1);
  3887.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3888.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3889.     if (x < 0) return(-1);
  3890.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3891.     x = cfsetispeed(&ttcur,spdsavi);
  3892.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3893.     if (x < 0) return(-1);
  3894.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3895.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3896.     if (x < 0) return(-1);
  3897.     return(1);
  3898.     }
  3899. #else
  3900. #ifdef BSD44ORPOSIX
  3901. #ifdef QNX
  3902.     {
  3903.     int x;
  3904.     x = tcdropline(ttyfd,500);
  3905.     debug(F101,"tthang QNX tcdropline","",x);
  3906.     ttcur.c_cflag |= CLOCAL;
  3907.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3908.     debug(F101,"tthang QNX tcsetattr restore","",x);
  3909.     if (x < 0) {
  3910.         debug(F101,"tthang QNX tcsetattr restore errno","",errno);
  3911.         return(-1);
  3912.     }
  3913.     /* Fix flags - ensure O_NONBLOCK is off */
  3914.  
  3915.     errno = 0;
  3916.     debug(F101,"tthang QNX iniflags","",iniflags);
  3917.     if (fcntl(ttyfd, F_SETFL, iniflags) == -1) {
  3918.         debug(F101,"tthang QNX F_SETFL errno","",errno);
  3919.         return(-1);
  3920.     }
  3921.     return(x);
  3922.     }
  3923. #else  /* QNX */
  3924.     {
  3925.     int x;
  3926. #ifdef USE_TIOCSDTR
  3927.     debug(F100,"tthang BSD44ORPOSIX USE_TIOCSDTR","",0);
  3928.     errno = 0;
  3929.     x = ioctl(ttyfd, TIOCCDTR, NULL);
  3930.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCCDTR",ckitoa(errno),x);
  3931.     if (x < 0) return(-1);
  3932.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3933.     errno = 0;
  3934.     x = ioctl(ttyfd, TIOCSDTR, NULL);
  3935.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCSDTR",ckitoa(errno),x);
  3936.     if (x < 0) return(-1);
  3937. #else  /* USE_TIOCSDTR */
  3938.  
  3939. #ifdef HUP_CLOSE_POSIX
  3940. /*
  3941.   In OSR5 versions where TIOCSDTR is not defined (up to and including at
  3942.   least 5.0.6a) the POSIX APIs in the "#else" part below are available but
  3943.   don't work, and no other APIs are available that do work.  In this case
  3944.   we have to drop DTR by brute force: close and reopen the port.  This
  3945.   code actually works, but all the steps are crucial: setting CLOCAL, the
  3946.   O_NDELAY manipulations, etc.
  3947. */
  3948.     debug(F100,"tthang HUP_CLOSE_POSIX close/open","",0);
  3949.     debug(F101,"tthang HUP_CLOSE_POSIX O_NONBLOCK","",O_NONBLOCK);
  3950.     debug(F101,"tthang HUP_CLOSE_POSIX O_NDELAY","",O_NDELAY);
  3951.     errno = 0;
  3952.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3953.     debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr","",x);
  3954.     if (x < 0) {
  3955.         debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr errno","",errno);
  3956.         return(-1);
  3957.     }
  3958.     errno = 0;
  3959.  
  3960.     x = close(ttyfd);        /* Close without releasing lock */
  3961.     if (x < 0) {
  3962.         debug(F101,"tthang HUP_CLOSE_POSIX close errno","",errno);
  3963.         return(-1);
  3964.     }
  3965.     errno = 0;
  3966.     x = msleep(500);        /* Pause half a second */
  3967.     if (x < 0) {            /* Or if that doesn't work, 1 sec */
  3968.         debug(F101,"tthang HUP_CLOSE_POSIX msleep errno","",errno);
  3969.         sleep(1);
  3970.     }
  3971.     errno = 0;
  3972.     ttyfd = priv_opn(ttnmsv, (O_RDWR|O_NDELAY)); /* Reopen the device */
  3973.     debug(F111,"tthang HUP_CLOSE_POSIX reopen",ttnmsv,ttyfd);
  3974.     if (ttyfd < 0) {
  3975.         debug(F101,"tthang HUP_CLOSE_POSIX reopen errno","",errno);
  3976.         return(-1);
  3977.     }
  3978.     debug(F101,"tthang HUP_CLOSE_POSIX re-ttopen ttyfd","",ttyfd);
  3979.  
  3980.     /* Restore previous attributes */
  3981.  
  3982.     errno = 0;
  3983.     tvtflg = 0;
  3984.     ttcur.c_cflag |= CLOCAL;
  3985.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3986.     debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore","",x);
  3987.     if (x < 0) {
  3988.         debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore errno",
  3989.           "",errno);
  3990.         return(-1);
  3991.     }
  3992.     /* Fix flags - ensure O_NDELAY and O_NONBLOCK are off */
  3993.  
  3994.     errno = 0;
  3995.         if ((x = fcntl(ttyfd, F_GETFL, 0)) == -1) {
  3996.         debug(F101,"tthang HUP_CLOSE_POSIX F_GETFL errno","",errno);
  3997.         return(-1);
  3998.     }
  3999.     debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  4000.     errno = 0;
  4001.         x &= ~(O_NONBLOCK|O_NDELAY);
  4002.     debug(F101,"tthang HUP_CLOSE_POSIX flags to set","",x);
  4003.     debug(F101,"tthang HUP_CLOSE_POSIX iniflags","",iniflags);
  4004.     if (fcntl(ttyfd, F_SETFL, x) == -1) {
  4005.         debug(F101,"tthang HUP_CLOSE_POSIX F_SETFL errno","",errno);
  4006.         return(-1);
  4007.     }
  4008. #ifdef DEBUG
  4009.     if (deblog) {
  4010.         if ((x = fcntl(ttyfd, F_GETFL, 0)) > -1) {
  4011.         debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  4012.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NONBLOCK",
  4013.               "",x&O_NONBLOCK);
  4014.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NDELAY",
  4015.               "",x&O_NDELAY);
  4016.         }
  4017.     }
  4018. #endif /* DEBUG */
  4019.  
  4020. #else  /* HUP_CLOSE_POSIX */
  4021.     
  4022.     /* General BSD44ORPOSIX case (Linux, BSDI, FreeBSD, etc) */
  4023.  
  4024.     debug(F100,"tthang BSD44ORPOSIX B0","",0);
  4025.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  4026.     debug(F111,"tthang BSD44ORPOSIX tcgetattr",ckitoa(errno),x);
  4027.     if (x < 0) return(-1);
  4028.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  4029.     debug(F111,"tthang BSD44ORPOSIX cfgetospeed",ckitoa(errno),spdsav);
  4030.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  4031.     debug(F111,"tthang BSD44ORPOSIX cfgetispeed",ckitoa(errno),spdsavi);
  4032.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  4033.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed",ckitoa(errno),x);
  4034.     if (x < 0) return(-1);
  4035.     x = cfsetispeed(&ttcur,B0);
  4036.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed",ckitoa(errno),x);
  4037.     if (x < 0) return(-1);
  4038.     /* This gets EINVAL on NetBSD 1.4.1 because of B0... */
  4039.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4040.     debug(F111,"tthang BSD44ORPOSIX tcsetattr B0",ckitoa(errno),x);
  4041.     if (x < 0) return(-1);
  4042.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  4043.     debug(F101,"tthang BSD44ORPOSIX restore output speed","",spdsav);
  4044.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  4045.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed prev",ckitoa(errno),x);
  4046.     if (x < 0) return(-1);
  4047.     debug(F101,"tthang BSD44ORPOSIX restore input speed","",spdsavi);
  4048.     x = cfsetispeed(&ttcur,spdsavi);
  4049.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed prev",ckitoa(errno),x);
  4050.     if (x < 0) return(-1);
  4051.     ttcur.c_cflag |= CLOCAL;    /* Don't expect CD after hangup */
  4052.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4053.     debug(F111,"tthang BSD44ORPOSIX tcsetattr restore",ckitoa(errno),x);
  4054.     if (x < 0) return(-1);
  4055.  
  4056. #endif /* HUP_CLOSE_POSIX */
  4057. #endif /* USE_TIOCSDTR */
  4058.  
  4059.     return(1);
  4060.     }
  4061.  
  4062. #endif /* QNX */
  4063. #else /* BSD44ORPOSIX */
  4064.  
  4065. #ifdef aegis                /* Apollo Aegis */
  4066.     sio_$control((short)ttyfd, sio_$dtr, false, st);    /* DTR down */
  4067.     msleep(HUPTIME);                    /* pause */
  4068.     sio_$control((short)ttyfd, sio_$dtr, true,  st);    /* DTR up */
  4069.     return(1);
  4070. #endif /* aegis */
  4071.  
  4072. #ifdef ANYBSD                /* Any BSD version. */
  4073. #ifdef TIOCCDTR                /* Except those that don't have this */
  4074.     debug(F100,"tthang BSD style","",0);
  4075.     if (ioctl(ttyfd,TIOCCDTR,0) < 0) {    /* Clear DTR. */
  4076.     debug(F101,"tthang TIOCCDTR fails","",errno);
  4077.     return(-1);
  4078.     }
  4079.     msleep(HUPTIME);            /* For about 1/2 sec */
  4080.     errno = 0;
  4081.     x = ioctl(ttyfd,TIOCSDTR,0);    /* Restore DTR */
  4082.     if (x < 0) {
  4083.     /*
  4084.       For some reason, this tends to fail with "no such device or address"
  4085.       but the operation still works, probably because of the close/open
  4086.       later on.  So let's not scare the user unnecessarily here.
  4087.     */
  4088.     debug(F101,"tthang TIOCSDTR errno","",errno); /* Log the error */
  4089.     x = 1;                /* Pretend we succeeded */
  4090.     } else if (x == 0) x = 1;        /* Success */
  4091. #ifdef COMMENT
  4092. #ifdef FT21
  4093.     ioctl(ttyfd, TIOCSAVEMODES, 0);
  4094.     ioctl(ttyfd, TIOCHPCL, 0);
  4095.     close(ttyfd);            /* Yes, must do this twice */
  4096.     if ((ttyfd = open(ttnmsv,2)) < 0)    /* on Fortune computers... */
  4097.       return(-1);            /* (but why?) */
  4098.     else x = 1;
  4099. #endif /* FT21 */
  4100. #endif /* COMMENT */
  4101. #endif /* TIOCCDTR */
  4102.     close(do_open(ttnmsv));        /* Clear i/o error condition */
  4103.     errno = 0;
  4104. #ifdef COMMENT
  4105. /* This is definitely dangerous.  Why was it here? */
  4106.     z = ttvt(ttspeed,ttflow);        /* Restore modes. */
  4107.     debug(F101,"tthang ttvt returns","",z);
  4108.     return(z < 0 ? -1 : 1);
  4109. #else
  4110.     return(x);
  4111. #endif /* COMMENT */
  4112. #endif /* ANYBSD */
  4113.  
  4114. #ifdef ATTSV
  4115. /* AT&T UNIX section, includes HP-UX and generic AT&T System III/V... */
  4116.  
  4117. #ifdef HPUX
  4118. /* Hewlett Packard allows explicit manipulation of modem signals. */
  4119.  
  4120. #ifdef COMMENT
  4121. /* Old way... */
  4122.     debug(F100,"tthang HP-UX style","",0);
  4123.     if (ioctl(ttyfd,MCSETAF,&dtr_down) < 0)        /* lower DTR */
  4124.       return(-1);                           /* oops, can't. */
  4125.     msleep(HUPTIME);                       /* Pause half a second. */
  4126.     x = 1;                           /* Set return code */
  4127.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) {     /* Get line status. */
  4128.     if ((modem_rtn & MDCD) != 0)             /* Check if CD is low. */
  4129.       x = -1;                                  /* CD didn't drop, fail. */
  4130.     } else x = -1;
  4131.  
  4132.     /* Even if above calls fail, RTS & DTR should be turned back on. */
  4133.     modem_rtn = MRTS | MDTR;
  4134.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) x = -1;
  4135.     return(x);
  4136. #else
  4137. /* New way, from Hellmuth Michaelis */
  4138.     debug(F100,"tthang HP-UX style, HPUXDEBUG","",0);
  4139.     if (ioctl(ttyfd,MCGETA,&modem_rtn) == -1) { /* Get current status. */
  4140.     debug(F100,"tthang HP-UX: can't get modem lines, NO HANGUP!","",0);
  4141.     return(-1);
  4142.     }
  4143.     sprintf(modem_state,"%#lx",modem_rtn);
  4144.     debug(F110,"tthang HP-UX: modem lines = ",modem_state,0);
  4145.     modem_sav = modem_rtn;        /* Save current modem signals */
  4146.     modem_rtn &= ~MDTR;            /* Turn DTR bit off */
  4147.     sprintf(modem_state,"%#lx",modem_rtn);
  4148.     debug(F110,"tthang HP-UX: DTR down = ",modem_state,0);
  4149.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) { /* lower DTR */
  4150.     debug(F100,"tthang HP-UX: can't lower DTR!","",0);
  4151.     return(-1);            /* oops, can't. */
  4152.     }
  4153.     msleep(HUPTIME);            /* Pause half a second. */
  4154.     x = 1;                /* Set return code */
  4155.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) { /* Get line status. */
  4156.     sprintf(modem_state,"%#lx",modem_rtn);
  4157.     debug(F110,"tthang HP-UX: modem lines got = ",modem_state,0);
  4158.     if ((modem_rtn & MDCD) != 0) {    /* Check if CD is low. */
  4159.         debug(F100,"tthang HP-UX: DCD not down","",0);
  4160.         x = -1;            /* CD didn't drop, fail. */
  4161.     } else {
  4162.         debug(F100,"tthang HP-UX: DCD down","",0);
  4163.     }
  4164.     } else {
  4165.     x = -1;
  4166.     debug(F100,"tthang HP-UX: can't get DCD status !","",0);
  4167.     }
  4168.  
  4169.     /* Even if above calls fail, DTR should be turned back on. */
  4170.  
  4171.     modem_sav |= MDTR;
  4172.     if (ioctl(ttyfd,MCSETAF,&modem_sav) < 0) {
  4173.     x = -1;
  4174.     debug(F100,"tthang HP-UX: can't set saved state","",0);
  4175.     } else {
  4176.     sprintf(modem_state,"%#lx",modem_sav);
  4177.     debug(F110,"tthang HP-UX: final modem lines = ",modem_state,0);
  4178.     }
  4179.     return(x);
  4180. #endif /* COMMENT */
  4181.  
  4182. #else /* AT&T but not HP-UX */
  4183.  
  4184. /* SVID for AT&T System V R3 defines ioctl's for handling modem signals. */
  4185. /* It is not known how many, if any, systems actually implement them, */
  4186. /* so we include them here in ifdef's. */
  4187.  
  4188. /*
  4189.   Unixware has the TIOCMxxx symbols defined, but calling ioctl() with them
  4190.   gives error 22 (invalid argument).
  4191. */
  4192. #ifndef _IBMR2
  4193. /*
  4194.   No modem-signal twiddling for IBM RT PC or RS/6000.
  4195.   In AIX 3.1 and earlier, the ioctl() call is broken.
  4196.   This code could be activated for AIX 3.1 with PTF 2006 or later
  4197.   (e.g. AIX 3.2), but close/open does the job too, so why bother.
  4198. */
  4199. #ifdef TIOCMBIS                /* Bit Set */
  4200. #ifdef TIOCMBIC                /* Bit Clear */
  4201. #ifdef TIOCM_DTR            /* DTR */
  4202.  
  4203. /* Clear DTR, sleep 300 msec, turn it back on. */
  4204. /* If any of the ioctl's return failure, go on to the next section. */
  4205.  
  4206.     z = TIOCM_DTR;            /* Code for DTR. */
  4207. #ifdef COMMENT
  4208. /*
  4209.   This was the cause of the troubles with the Solaris Port Monitor.
  4210.   The problem is: RTS never comes back on.  Moral: Don't do it!
  4211.   (But why doesn't it come back on?  See the TIOCMBIS call...)
  4212. */
  4213. #ifdef TIOCM_RTS            /* Lower RTS too if symbol is known. */
  4214.     z |= TIOCM_RTS;
  4215. #endif /* TIOCM_RTS */
  4216. #endif /* COMMENT */
  4217.  
  4218.     debug(F101,"tthang TIOCM signal mask","",z);
  4219.     if (ioctl(ttyfd,TIOCMBIC,&z) > -1) {   /* Try to lower DTR. */
  4220.     debug(F100,"tthang TIOCMBIC ok","",0);
  4221.     msleep(HUPTIME);           /* Pause half a second. */
  4222.     if (ioctl(ttyfd,TIOCMBIS,&z) > -1) { /* Try to turn it back on. */
  4223.         debug(F100,"tthang TIOCMBIS ok","",0);
  4224. #ifndef CLSOPN
  4225.         return(1);            /* Success, done. */
  4226. #endif /* CLSOPN */
  4227.     } else {            /* Couldn't raise, continue. */
  4228.         debug(F101,"tthang TIOCMBIS errno","",errno);
  4229.     }
  4230.     } else {                /* Couldn't lower, continue. */
  4231.      debug(F101,"tthang TIOCMBIC errno","",errno);
  4232.     }
  4233. #endif /* TIOCM_DTR */
  4234. #endif /* TIOCMBIC */
  4235. #endif /* TIOCMBIS */
  4236. #endif /* _IBMR2 */
  4237.  
  4238. /*
  4239.   General AT&T UNIX case, not HPUX.  The following code is highly suspect.  No
  4240.   two AT&T-based systems seem to do this the same way.  The object is simply
  4241.   to turn off DTR and then turn it back on.  SVID says the universal method
  4242.   for turning off DTR is to set the speed to zero, and this does seem to do
  4243.   the trick in all cases.  But neither SVID nor any known man pages say how to
  4244.   turn DTR back on again.  Some variants, like most Xenix implementations,
  4245.   raise DTR again when the speed is restored to a nonzero value.  Others
  4246.   require the device to be closed and opened again, but this is risky because
  4247.   getty could seize the device during the instant it is closed.
  4248. */
  4249.  
  4250. /* Return code for ioctl failures... */
  4251. #ifdef ATT6300
  4252.     x = 1;                /* ATT6300 doesn't want to fail... */
  4253. #else
  4254.     x = -1;
  4255. #endif /* ATT6300 */
  4256.  
  4257.     debug(F100,"tthang get settings","",0);
  4258.     if (ioctl(ttyfd,TCGETA,&ttcur) < 0) /* Get current settings. */
  4259.       return(x);            /* Fail if this doesn't work. */
  4260.     if ((flags = fcntl(ttyfd,F_GETFL,0)) < 0) /* Get device flags. */
  4261.       return(x);
  4262.     ttc_save = ttcur.c_cflag;        /* Remember current speed. */
  4263.     spdsav = ttc_save & CBAUD;
  4264.     debug(F101,"tthang speed","",spdsav);
  4265.  
  4266. #ifdef O_NDELAY
  4267.     debug(F100,"tthang turning O_NDELAY on","",0);
  4268.     fcntl(ttyfd, F_SETFL, flags | O_NDELAY); /* Activate O_NDELAY */
  4269. #endif /* O_NDELAY */
  4270.  
  4271. #ifdef ATT7300 /* This is the way it is SUPPOSED to work */
  4272.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4273. #else
  4274. #ifdef RTAIX
  4275.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4276. #else          /* This way really works but may be dangerous */
  4277. #ifdef u3b2
  4278.     ttcur.c_cflag = ~(CBAUD|CLOCAL);    /* Special for AT&T 3B2s */
  4279.                     /* (CLOCAL must be OFF) */
  4280. #else
  4281. #ifdef SCO3R2                /* SCO UNIX 3.2 */
  4282. /*
  4283.   This is complete nonsense, but an SCO user claimed this change made
  4284.   hanging up work.  Comments from other SCO UNIX 3.2 users would be
  4285.   appreciated.
  4286. */
  4287.     ttcur.c_cflag = CBAUD|B0;
  4288. #else
  4289. #ifdef AIXRS                /* AIX on RS/6000 */
  4290. /*
  4291.   Can't set speed to zero on AIX 3.1 on RS/6000 64-port adapter,
  4292.   even though you can do it on the built-in port and the 8- and 16-port
  4293.   adapters.  (Untested on 128-port adapter.)
  4294. */
  4295.     ttcur.c_cflag = CLOCAL|HUPCL|spdsav; /* Speed 0 causes EINVAL */
  4296. #else                    /* None of the above */
  4297. /*
  4298.   Set everything, including the speed, to zero, except for the CLOCAL
  4299.   and HUPCL bits.
  4300. */
  4301.     ttcur.c_cflag = CLOCAL|HUPCL;
  4302. #endif /* AIXRS */
  4303. #endif /* SCO3R2 */
  4304. #endif /* u3b2 */
  4305. #endif /* RTAIX */
  4306. #endif /* ATT7300 */
  4307.  
  4308. #ifdef COMMENT
  4309.     /* and if none of those work, try one of these... */
  4310.     ttcur.c_cflag = 0;
  4311.     ttcur.c_cflag = CLOCAL;
  4312.     ttcur.c_cflag &= ~(CBAUD|HUPCL);
  4313.     ttcur.c_cflag &= ~(CBAUD|CREAD);
  4314.     ttcur.c_cflag &= ~(CBAUD|CREAD|HUPCL);
  4315.     /* or other combinations */
  4316. #endif /* COMMENT */
  4317.  
  4318. #ifdef TCXONC
  4319.     debug(F100,"tthang TCXONC","",0);
  4320.     if (ioctl(ttyfd, TCXONC, 1) < 0) {
  4321.     debug(F101,"tthang TCXONC failed","",errno);
  4322.     }
  4323. #endif /* TCXONC */
  4324.  
  4325. #ifdef TIOCSTART
  4326.     debug(F100,"tthang TIOCSTART","",0);
  4327.     if (ioctl(ttyfd, TIOCSTART, 0) < 0) {
  4328.     debug(F101,"tthang TIOCSTART failed","",errno);
  4329.     }
  4330. #endif /* TIOCSTART */
  4331.  
  4332.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) { /* Fail if we can't. */
  4333.     debug(F101,"tthang TCSETAF failed","",errno);
  4334.     fcntl(ttyfd, F_SETFL, flags);    /* Restore flags */
  4335.     return(-1);            /* before returning. */
  4336.     }
  4337.     msleep(300);            /* Give modem time to notice. */
  4338.  
  4339. #ifndef NOCOTFMC
  4340.  
  4341. /* Now, even though it doesn't say this in SVID or any man page, we have */
  4342. /* to close and reopen the device.  This is not necessary for all systems, */
  4343. /* but it's impossible to predict which ones need it and which ones don't. */
  4344.  
  4345. #ifdef ATT7300
  4346. /*
  4347.   Special handling for ATT 7300 UNIX PC and 3B1, which have "phone"
  4348.   related ioctl's for their internal modems.  attmodem has getty status and
  4349.   modem-in-use bit.  Reportedly the ATT7300/3B1 PIOCDISC call is necessary,
  4350.   but also ruins the file descriptor, and no other phone(7) ioctl call can fix
  4351.   it.  Whatever it does, it seems to escape detection with PIOCGETA and TCGETA.
  4352.   The only way to undo the damage is to close the fd and then reopen it.
  4353. */
  4354.     if (attmodem & ISMODEM) {
  4355.     debug(F100,"tthang attmodem close/open","",0);
  4356.     ioctl(ttyfd,PIOCUNHOLD,&dialer); /* Return call to handset. */
  4357.     ioctl(ttyfd,PIOCDISC,&dialer);    /* Disconnect phone. */
  4358.     close(ttyfd);            /* Close and reopen the fd. */
  4359.     ttyfd = priv_opn(ttnmsv, O_RDWR | O_NDELAY);
  4360.     attmodem &= ~ISMODEM;        /* Phone no longer in use. */
  4361.     }
  4362. #else /* !ATT7300 */
  4363. /* It seems we have to close and open the device for other AT&T systems */
  4364. /* too, and this is the place to do it.  The following code does the */
  4365. /* famous close(open(...)) magic by default.  If that doesn't work for you, */
  4366. /* then try uncommenting the following statement or putting -DCLSOPN in */
  4367. /* the makefile CFLAGS. */
  4368.  
  4369. /* #define CLSOPN */
  4370.  
  4371. #ifndef SCO32 /* Not needed by, and harmful to, SCO UNIX 3.2 / Xenix 2.3 */
  4372.  
  4373. #ifdef O_NDELAY
  4374. #define OPENFLGS O_RDWR | O_NDELAY
  4375. #else
  4376. #define OPENFLGS O_RDWR
  4377. #endif
  4378.  
  4379. #ifndef CLSOPN
  4380. /* This method is used by default, i.e. unless CLSOPN is defined. */
  4381. /* It is thought to be safer because there is no window where getty */
  4382. /* can seize control of the device.  The drawback is that it might not work. */
  4383.  
  4384.     debug(F101,"tthang close(open()), OPENFLGS","",OPENFLGS);
  4385.     close(priv_opn(ttnmsv, OPENFLGS));
  4386.  
  4387. #else
  4388. /* This method is used if you #define CLSOPN.  It is more likely to work */
  4389. /* than the previous method, but it's also more dangerous. */
  4390.  
  4391.     debug(F101,"tthang close/open, OPENFLGS","",OPENFLGS);
  4392.     close(ttyfd);
  4393.     msleep(10);
  4394.     ttyfd = priv_opn(ttnmsv, OPENFLGS);    /* Open it again */
  4395. #endif /* CLSOPN */
  4396. #undef OPENFLGS
  4397.  
  4398. #endif /* SCO32 */
  4399. #endif /* ATT7300 */
  4400.  
  4401. #endif /* NOCOTFMC */
  4402.  
  4403. /* Now put all flags & modes back the way we found them. */
  4404. /* (Does the order of ioctl & fcntl matter ? ) */
  4405.  
  4406.     debug(F100,"tthang restore settings","",0);
  4407.     ttcur.c_cflag = ttc_save;        /* Get old speed back. */
  4408.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) /* ioctl parameters. */
  4409.       return(-1);
  4410. #ifdef O_NDELAY
  4411. /*
  4412.   This is required for IBM RT and RS/6000, probably helps elsewhere too (?).
  4413.   After closing a modem line, the modem will probably not be asserting
  4414.   carrier any more, so we should not require carrier any more.  If this
  4415.   causes trouble on non-IBM UNIXes, change the #ifdef to use _IBMR2 rather
  4416.   than O_NDELAY.
  4417. */
  4418.     flags &= ~O_NDELAY;            /* Don't require carrier on reopen */
  4419. #endif /* O_NDELAY */
  4420.     if (fcntl(ttyfd,F_SETFL,flags) < 0)    /* fcntl parameters */
  4421.       return(-1);
  4422.  
  4423.     return(1);
  4424. #endif /* not HPUX */
  4425. #endif /* ATTSV */
  4426. #endif /* BSD44ORPOSIX */
  4427. #endif /* HUP_POSIX */
  4428. #endif /* NOLOCAL */
  4429. }
  4430.  
  4431. /*
  4432.   Major change in 5A(174).  We used to use LPASS8, if it was defined, to
  4433.   allow 8-bit data and Xon/Xoff flow control at the same time.  But this
  4434.   LPASS8 business seems to have been causing trouble for everybody but me!
  4435.   For example, Annex terminal servers, commonly used with Encore computers,
  4436.   do not support LPASS8 even though the Encore itself does.  Ditto for many
  4437.   other terminal servers, TELNET connections, rlogin connections, etc etc.
  4438.   Now, reportedly, even vanilla 4.3 BSD systems can't do this right on their
  4439.   serial lines, even though LPASS8 is a feature of 4.3BSD.  So let's turn it
  4440.   off for everybody.  That means we goes back to using raw mode, with no
  4441.   flow control.  Phooey.
  4442.  
  4443.   NOTE: This must be done before the first reference to LPASS8 in this file,
  4444.   and after the last #include statment.
  4445. */
  4446. #ifdef LPASS8
  4447. #undef LPASS8
  4448. #endif /* LPASS8 */
  4449.  
  4450. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  4451.  
  4452. /* ske@pkmab.se: There are two choices for what this function should do.
  4453.  * (1) Restore the tty to current "normal" mode, with carrier treatment
  4454.  * according to ttcarr, to be used after every kermit command. (2) Restore
  4455.  * the tty to the state it was in before kermit opened it. These choices
  4456.  * conflict, since ttold can't hold both choices of tty parameters.  ttres()
  4457.  * is currently being called as in choice (1), but ttold basically holds
  4458.  * the initial parameters, as in (2), and the description at the beginning
  4459.  * of this file says (2).
  4460.  *
  4461.  * I don't think restoring tty parameters after all kermit commands makes
  4462.  * much of a difference.  Restoring them upon exit from kermit may be of
  4463.  * some use in some cases (when the line is not restored automatically on
  4464.  * close, by the operating system).
  4465.  *
  4466.  * I can't choose which one it should be, so I haven't changed it. It
  4467.  * probably works as it is, too. It would probably even work even with
  4468.  * ttres() entirely deleted...
  4469.  *
  4470.  * (from fdc: Actually, this function operates in remote mode too, so
  4471.  * it restores the console (command) terminal to whatever mode it was
  4472.  * in before packet operations began, so that commands work right again.)
  4473.  */
  4474. int
  4475. ttres() {                               /* Restore the tty to normal. */
  4476.     int x;
  4477.  
  4478.     if (ttyfd < 0) return(-1);          /* Not open. */
  4479.  
  4480.     if (ttfdflg) return(0);        /* Don't mess with terminal modes if */
  4481.                     /* we got ttyfd from another process */
  4482. #ifdef    NETCONN
  4483.     if (netconn) {            /* Network connection */
  4484.         tvtflg = 0;
  4485. #ifdef TCPSOCKET
  4486. #ifdef TCP_NODELAY
  4487.         {
  4488.         extern int tcp_nodelay;    /* Just put this back if necessary */
  4489.         if (ttnet == NET_TCPB) {
  4490.         if (nodelay_sav > -1) {
  4491.             no_delay(ttyfd,nodelay_sav);
  4492.             nodelay_sav = -1;
  4493.         }
  4494.         }
  4495.         }
  4496. #endif /* TCP_NODELAY */
  4497. #ifdef TN_COMPORT
  4498.         if (istncomport()) {
  4499.             int rc = -1;
  4500.             if ((rc = tnsetflow(ttflow)) < 0)
  4501.           return(rc);
  4502.             if (ttspeed <= 0) 
  4503.           ttspeed = tnc_get_baud();
  4504.             else if ((rc = tnc_set_baud(ttspeed)) < 0)
  4505.           return(rc);
  4506.             tnc_set_datasize(8);
  4507.         tnc_set_stopsize(stopbits);
  4508.  
  4509. #ifdef HWPARITY
  4510.             if (hwparity) {
  4511.                 switch (hwparity) {
  4512.           case 'e':            /* Even */
  4513.                     debug(F100,"ttres 8 bits + even parity","",0);
  4514.                     tnc_set_parity(3);
  4515.                     break;
  4516.           case 'o':            /* Odd */
  4517.                     debug(F100,"ttres 8 bits + odd parity","",0);
  4518.                     tnc_set_parity(2);
  4519.                     break;
  4520.           case 'm':            /* Mark */
  4521.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  4522.                     tnc_set_parity(4);
  4523.                     break;
  4524.           case 's':            /* Space */
  4525.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  4526.                     tnc_set_parity(5);
  4527.                     break;
  4528.                 }
  4529.             } else
  4530. #endif /* HWPARITY */
  4531.         {
  4532.                 tnc_set_parity(1);              /* None */
  4533.             }
  4534.             tvtflg = 0;
  4535.             return(0);
  4536.         }
  4537. #endif /* TN_COMPORT */
  4538. #endif /* TCPSOCKET */
  4539.     return(0);
  4540.     }
  4541. #endif    /* NETCONN */
  4542. #ifdef NETCMD
  4543.     if (ttpipe) return(0);
  4544. #endif /* NETCMD */
  4545. #ifdef NETPTY
  4546.     if (ttpty) return(0);
  4547. #endif /* NETPTY */
  4548.  
  4549. /* Real terminal device, so restore its original modes */
  4550.  
  4551. #ifdef BSD44ORPOSIX            /* For POSIX like this */
  4552.     debug(F100,"ttres BSD44ORPOSIX","",0);
  4553.     x = tcsetattr(ttyfd,TCSADRAIN,&ttold);
  4554. #else                    /* For all others... */
  4555. #ifdef ATTSV                            /* For AT&T versions... */
  4556.     debug(F100,"ttres ATTSV","",0);
  4557.     x = ioctl(ttyfd,TCSETAW,&ttold);    /* Restore tty modes this way. */
  4558. #else
  4559. /* Here we restore the modes for BSD */
  4560.  
  4561. #ifdef LPASS8                /* Undo "pass8" if it were done */
  4562.     if (lmodef) {
  4563.     if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4564.       debug(F100,"ttres TIOCLSET failed","",0);
  4565.     else
  4566.       debug(F100,"ttres TIOCLSET ok","",0);
  4567.     }
  4568. #endif /* LPASS8 */
  4569.  
  4570. #ifdef CK_DTRCTS           /* Undo hardware flow if it were done */
  4571.     if (lmodef) {
  4572.      if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4573.        debug(F100,"ttres TIOCLSET failed","",0);
  4574.      else
  4575.        debug(F100,"ttres TIOCLSET ok","",0);
  4576.     }
  4577. #endif /* CK_DTRCTS */
  4578.  
  4579. #ifdef TIOCGETC                /* Put back special characters */
  4580.     if (tcharf && (xlocal == 0)) {
  4581.     if (ioctl(ttyfd,TIOCSETC,&tchold) < 0)
  4582.       debug(F100,"ttres TIOCSETC failed","",0);
  4583.     else
  4584.       debug(F100,"ttres TIOCSETC ok","",0);
  4585.     }
  4586. #endif /* TIOCGETC */
  4587.  
  4588. #ifdef TIOCGLTC                /* Put back local special characters */
  4589.     if (ltcharf && (xlocal == 0)) {
  4590.     if (ioctl(ttyfd,TIOCSLTC,<chold) < 0)
  4591.       debug(F100,"ttres TIOCSLTC failed","",0);
  4592.     else
  4593.       debug(F100,"ttres TIOCSLTC ok","",0);
  4594.     }
  4595. #endif /* TIOCGLTC */
  4596.  
  4597. #ifdef BELLV10
  4598.     debug(F100,"ttres BELLV10","",0);
  4599.     x = ioctl(ttyfd,TIOCSETP,&ttold);    /* Restore both structs */
  4600.     x = ioctl(ttyfd,TIOCSDEV,&tdold);
  4601. #else
  4602.     debug(F100,"ttres stty","",0);
  4603.     x = stty(ttyfd,&ttold);             /* Restore tty modes the old way. */
  4604. #endif /* BELLV10 */
  4605.  
  4606.     if (!xlocal)
  4607.       msleep(100);            /* This replaces sleep(1)... */
  4608.                     /* Put back sleep(1) if tty is */
  4609.                     /* messed up after close. */
  4610. #endif /* ATTSV */
  4611. #endif /* BSD44ORPOSIX */
  4612.  
  4613.     debug(F101,"ttres result","",x);
  4614. #ifndef QNX
  4615.     if (x < 0) debug(F101,"ttres errno","",errno);
  4616. #endif /* QNX */
  4617.  
  4618. #ifdef AIXRS
  4619. #ifndef AIX41
  4620.     x = ioctl(ttyfd, ttld & 1 ? TXADDCD : TXDELCD, "rts");
  4621.     debug(F101,"ttres AIX line discipline rts restore","",x);
  4622. #endif /* AIX41 */
  4623. #endif /* AIXRS */
  4624.  
  4625. #ifdef BSD41
  4626.     if (ttld > -1) {            /* Put back line discipline */
  4627.     x = ioctl(ttyfd, TIOCSETD, &ttld);
  4628.     debug(F101,"ttres BSD41 line discipline restore","",x);
  4629.     if (x < 0) debug(F101,"...ioctl errno","",errno);
  4630.     ttld = -1;
  4631.     }
  4632. #endif /* BSD41 */
  4633.  
  4634. #ifdef sony_news
  4635.     x = xlocal ? km_ext : km_con;    /* Restore Kanji mode. */
  4636.     if (x != -1) {            /* Make sure we know original modes. */
  4637.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  4638.         perror("ttres can't set Kanji mode");
  4639.         debug(F101,"ttres error setting Kanji mode","",x);
  4640.         return(-1);
  4641.     }
  4642.     }
  4643.     debug(F100,"ttres set Kanji mode ok","",0);
  4644. #endif /* sony_news */
  4645.  
  4646.     tvtflg = 0;                /* Invalidate terminal mode settings */
  4647.     debug(F101,"ttres return code","",x);
  4648.     return(x);
  4649. }
  4650.  
  4651. #ifndef NOUUCP
  4652.  
  4653. /*  T T C H K P I D  --  Check lockfile pid  */
  4654. /*
  4655.   Read pid from lockfile named f, check that it's still valid.
  4656.   If so, return 1.
  4657.   On failure to read pid, return 1.
  4658.   Otherwise, try to delete lockfile f and return 0 if successful, else 1.
  4659. */
  4660. static int
  4661. ttchkpid(f) char *f; {
  4662.     int pid, mypid, x;
  4663.     pid = ttrpid(f);            /* Read pid from file. */
  4664.     if (pid > -1) {            /* If we were able to read the pid.. */
  4665.     debug(F101,"ttchkpid lock pid","",pid);
  4666.     errno = 0;            /* See if process still exists. */
  4667.     mypid = (int)getpid();        /* Get my own pid. */
  4668.     debug(F101,"ttchkpid my pid","",mypid);
  4669.     if (pid == mypid) {        /* It's me! */
  4670.         x = -1;            /* So I can delete it */
  4671.         errno = ESRCH;        /* pretend it's invalid */
  4672.     } else {            /* It's not me */
  4673.         x = kill((PID_T)pid, 0);    /* See if it's a live process */
  4674.         debug(F101,"ttchkpid kill errno","",errno);
  4675.     }
  4676.     debug(F101,"ttchkpid pid test","",x);
  4677.     if (x < 0 && errno == ESRCH) { /* pid is invalid */
  4678.         debug(F111,"removing stale lock",f,pid);
  4679.         if (!backgrd)
  4680.           printf("Removing stale lock %s (pid %d terminated)\n", f, pid);
  4681.         priv_on();
  4682.         x = unlink(f);        /* Remove the lockfile. */
  4683.         priv_off();
  4684.         debug(F111,"ttchkpid unlink",f,x);
  4685.         if (x > -1)
  4686.           return(0);        /* Device is not locked after all */
  4687.         else if (!backgrd)
  4688.           perror(f);
  4689.     }
  4690.     return(1);
  4691.     }
  4692.     return(1);                /* Failure to read pid */
  4693. }
  4694.  
  4695. #ifdef HPUX
  4696.  
  4697. /* Aliases (different drivers) for HP-UX dialout devices: */
  4698.  
  4699. static char *devprefix[] = { "tty", "ttyd", "cul", "cua", "cuad", "culd", "" };
  4700. static int ttydexists = 0;
  4701.  
  4702. #endif /* HPUX */
  4703.  
  4704. /*  T T R P I D  --  Read pid from lockfile "name" */
  4705.  
  4706. static int
  4707. ttrpid(name) char *name; {
  4708.     long len;
  4709.     int x, fd, pid;
  4710.     short spid;
  4711.     char buf[32];
  4712.  
  4713.     debug(F110,"ttrpid",name,0);
  4714.     if (!name) return(-1);
  4715.     if (!*name) return(-1);
  4716.     priv_on();
  4717.     len = zchki(name);            /* Get file length */
  4718.     priv_off();
  4719.     debug(F101,"ttrpid zchki","",len);
  4720.     if (len < 0)
  4721.       return(-1);
  4722.     if (len > 31)
  4723.       return(-1);
  4724.     priv_on();
  4725.     fd = open(name,O_RDONLY);        /* Try to open lockfile. */
  4726.     priv_off();
  4727.     debug(F101,"ttrpid fd","",fd);
  4728.     if (fd <= 0)
  4729.       return(-1);
  4730. /*
  4731.   Here we try to be flexible and allow for all different binary and string
  4732.   formats at runtime, rather than a specific format for each configuration
  4733.   hardwired at compile time.
  4734. */
  4735.     pid = -1;
  4736. #ifndef COHERENT
  4737. /*
  4738.   COHERENT uses a string PID but without leading spaces or 0's, so there is
  4739.   no way to tell from the file's length whether it contains a string or binary
  4740.   pid.  So for COHERENT only, we only allow string pids.  For all others, we
  4741.   decide based on the size of the lockfile.
  4742. */
  4743.     if (len > 4) {            /* If file > 4 bytes it's a string */
  4744. #endif /* COHERENT */
  4745.     x = read(fd,buf,(int)len);
  4746.     debug(F111,"ttrpid string read",buf,x);
  4747.     if (x < 0) {
  4748.         pid = -1;
  4749.     } else {
  4750.         buf[31] = '\0';
  4751.         x = sscanf(buf,"%d",&pid);    /* Get the integer pid from it. */
  4752.     }
  4753. #ifndef COHERENT
  4754.     } else if (len == 4) {        /* 4 bytes so binary */
  4755.     x = read(fd, (char *)&pid, 4);    /* Read the bytes into an int */
  4756.     debug(F101,"ttrpid integer read","",x);
  4757.     if (x < 4)
  4758.       pid = -1;
  4759.     } else if (len == 2) {        /* 2 bytes binary */
  4760.     x = read(fd, (char *)&spid, 2);    /* Read the bytes into a short */
  4761.     debug(F101,"ttrpid short read","",x);
  4762.     if (x < 2)
  4763.       pid = -1;
  4764.     else
  4765.       pid = spid;
  4766.     } else
  4767.       pid = -1;
  4768. #endif /* COHERENT */
  4769.     close(fd);                /* Close the lockfile */
  4770.     debug(F101,"ttrpid pid","",pid);
  4771.     return(pid);
  4772. }
  4773. #endif /* NOUUCP */
  4774.  
  4775. /*  T T L O C K  */
  4776.  
  4777. /*
  4778.   This function attempts to coordinate use of the communication device with
  4779.   other copies of Kermit and any other program that follows the UUCP
  4780.   device-locking conventions, which, unfortunately, vary among different UNIX
  4781.   implementations.  The idea is to look for a file of a certain name, the
  4782.   "lockfile", in a certain directory.  If such a file is found, then the line
  4783.   is presumed to be in use, and Kermit should not use it.  If no such file is
  4784.   found, Kermit attempts to create one so that other programs will not use the
  4785.   same line at the same time.  Because the lockfile and/or the directory it's
  4786.   in might lack write permission for the person running Kermit, Kermit could
  4787.   find itself running setuid to uucp or other user that does have the
  4788.   necessary permissions.  At startup, Kermit has changed its effective uid to
  4789.   the user's real uid, and so ttlock() must switch back to the original
  4790.   effective uid in order to create the lockfile, and then back again to the
  4791.   real uid to prevent unauthorized access to other directories or files owned
  4792.   by the user the program is setuid to.
  4793.  
  4794.   Totally rewritten for C-Kermit 5A to eliminate windows of vulnerability,
  4795.   based on suggestions from Warren Tucker.  Call with pointer to name of
  4796.   tty device.  Returns:
  4797.  
  4798.    0 on success
  4799.   -1 on failure
  4800.  
  4801.   Note: Once privileges are turned on using priv_on(), it is essential that
  4802.   they are turned off again before this function returns.
  4803. */
  4804. #ifdef SVR4                /* Lockfile uses device numbers. */
  4805. /*
  4806.   Although I can't find this in writing anywhere (e.g. in SVID for SVR4),
  4807.   it is the behavior of the "reference version" of SVR4, i.e. the Intel
  4808.   port from UNIX Systems Laboratories, then called Univel UnixWare,
  4809.   then called Novell UnixWare, then called SCO Unixware, then called Caldera
  4810.   Open UNIX...  It also makes much more sense than device-name-based lockfiles
  4811.   since there can be multiple names for the same device, symlinks, etc.
  4812. */
  4813. #ifndef NOLFDEVNO
  4814. #ifndef LFDEVNO                /* Define this for SVR4 */
  4815. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  4816. #ifndef BSD44                /* If anybody else needs it... */
  4817. #ifndef __386BSD__
  4818. #ifndef __FreeBSD__
  4819. #ifndef HPUX10
  4820. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  4821. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  4822. #define LFDEVNO
  4823. #endif /* CK_SCOV5 */
  4824. #endif /* IRIX51 */
  4825. #endif /* HPUX10 */
  4826. #endif /* __FreeBSD__ */
  4827. #endif /* __386BSD__ */
  4828. #endif /* BSD44 */
  4829. #endif /* AIXRS */
  4830. #endif /* LFDEVNO */            /* ... define it here or on CC */
  4831. #endif /* NOLFDEVNO */
  4832. #endif /* SVR4 */            /* command line. */
  4833.  
  4834. #ifdef COHERENT
  4835. #define LFDEVNO
  4836. #endif /* COHERENT */
  4837.  
  4838. /*
  4839.   For platforms where the lockfile name is made from device/major/minor
  4840.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4841.   by far the best format, since it eliminates all the confusion that stems
  4842.   from multiple names (or drivers) for the same port, not to mention
  4843.   symlinks.  It might even be a good idea to start using this form even
  4844.   on platforms where it's not supported, alongside the normal forms for those
  4845.   platforms, in order to get people used to it...
  4846. */
  4847. #ifdef LFDEVNO
  4848. #ifndef major                /* If we didn't find it */
  4849. #ifdef SVR4                /* then for Sys V R4 */
  4850. #include <sys/mkdev.h>            /* look here */
  4851. #else                    /* or for SunOS versions */
  4852. #ifdef SUNOS4                /* ... */
  4853. #include <sys/sysmacros.h>        /* look here */
  4854. #else                    /* Otherwise take a chance: */
  4855. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4856. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4857. #endif /* SUNOS4 */
  4858. #endif /* SVR4 */
  4859. #endif /* major */
  4860. #endif /* LFDEVNO */
  4861.  
  4862. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4863.  
  4864. #ifdef LOCKF
  4865. #ifndef F_TLOCK
  4866. #undef LOCKF
  4867. #ifndef NOLOCKF
  4868. #define NOLOCKF
  4869. #endif /* NOLOCKF */
  4870. #endif /* F_TLOCK */
  4871. #endif /* LOCKF */
  4872.  
  4873. #ifdef LOCKF
  4874. #ifndef F_ULOCK
  4875. #undef LOCKF
  4876. #ifndef NOLOCKF
  4877. #define NOLOCKF
  4878. #endif /* NOLOCKF */
  4879. #endif /* F_ULOCK */
  4880. #endif /* LOCKF */
  4881.  
  4882. static char linkto[DEVNAMLEN+1];
  4883. static char * linkdev = NULL;
  4884.  
  4885. #ifndef NOUUCP
  4886. #ifdef USETTYLOCK
  4887. #ifdef LOCK_DIR
  4888. char * uucplockdir = LOCK_DIR;
  4889. #else
  4890. char * uucplockdir = "";
  4891. #endif /* LOCK_DIR */
  4892. #else
  4893. #ifdef LOCK_DIR
  4894. char * uucplockdir = LOCK_DIR;
  4895. #else
  4896. char * uucplockdir = "";
  4897. #endif /* LOCK_DIR */
  4898. #endif /* USETTYLOCK */
  4899. #else
  4900. char * uucplockdir = "";
  4901. #endif /* NOUUCP */
  4902.  
  4903. #ifdef QNX                /* Only for QNX4 */
  4904. int                    /* Visible to outside world */
  4905. qnxopencount() {            /* Get QNX device open count */
  4906.     struct _dev_info_entry info;
  4907.     int x;
  4908.  
  4909.     x = -1;                /* Unknown */
  4910.     if (ttyfd > -1) {
  4911.     if (!dev_info(ttyfd, &info)) {
  4912.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4913.         x = info.open_count;
  4914.     }
  4915.     }
  4916.     return(x);
  4917. }
  4918. #endif /* QNX */
  4919.  
  4920. char *
  4921. ttglckdir() {                /* Get Lockfile directory name */
  4922. #ifdef __OpenBSD__
  4923.     return("/var/spool/lock");
  4924. #else /* __OpenBSD__ */
  4925. #ifdef __FreeBSD__
  4926.     return("/var/spool/lock");
  4927. #else  /* __FreeBSD__ */
  4928. #ifdef LOCK_DIR
  4929.     char * s = LOCK_DIR;
  4930. #endif /* LOCK_DIR */
  4931. #ifdef NOUUCP
  4932.     return("");
  4933. #else  /* NOUUCP */
  4934. #ifdef LOCK_DIR
  4935.     return(s);
  4936. #else  /* LOCK_DIR */
  4937.     return("");
  4938. #endif /* LOCK_DIR */
  4939. #endif /* NOUUCP */
  4940. #endif /* __FreeBSD__ */
  4941. #endif /* __OpenBSD__ */
  4942. }
  4943.  
  4944. static int
  4945. ttlock(ttdev) char *ttdev; {
  4946.  
  4947.     int x, n;
  4948.     int islink = 0;
  4949.  
  4950. #ifdef NOUUCP
  4951.     debug(F100,"ttlock NOUUCP","",0);
  4952.     ckstrncpy(flfnam,"NOLOCK",FLFNAML);
  4953.     haslock = 1;
  4954.     return(0);
  4955. #else /* !NOUUCP */
  4956.  
  4957. #ifdef USETTYLOCK
  4958.     haslock = 0;                        /* Not locked yet. */
  4959.     *flfnam = '\0';            /* Lockfile name is empty. */
  4960.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4961.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4962.     else
  4963.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4964. /*
  4965.   This might be overkill, but it's not clear from the man pages whether
  4966.   ttylock() can be called without calling ttylocked() first, since the doc
  4967.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4968.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4969.   case when it finds and removes a stale lockfile.  So one or both calls to
  4970.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  4971.   assuming that we have to do all the same ID swapping, etc, with these
  4972.   routines as we do without them.  Thus the priv_on/off() sandwich.
  4973. */
  4974. #ifdef USE_UU_LOCK
  4975.     priv_on();                /* Turn on privs */
  4976.     x = uu_lock(lockname);        /* Try to set the lock */
  4977.     priv_off();                /* Turn privs off */
  4978.     debug(F111,"ttlock uu_lock",lockname,x);
  4979.     switch (x) {
  4980.       case UU_LOCK_INUSE:
  4981.     return(-2);
  4982.       case UU_LOCK_OK:
  4983. #ifdef BSD44
  4984.     ckmakmsg(flfnam,FLFNAML,"/var/spool/lock/LCK..",lockname,NULL,NULL);
  4985. #endif /* BSD44 */
  4986.     haslock = 1;
  4987.     return(0);
  4988.       default:
  4989.     return(-1);
  4990.     }
  4991. #else  /* USE_UU_LOCK */
  4992.     priv_on();                /* Turn on privs */
  4993.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  4994.     if (ttylocked(lockname)) {    /* so check again. */
  4995.         priv_off();
  4996.         return(-5);            /* Still locked, fail. */
  4997.     }
  4998.     }
  4999.     x = ttylock(lockname);        /* Lock it. */
  5000.     priv_off();                /* Turn off privs */
  5001.  
  5002.     debug(F111,"ttlock lockname",lockname,x);
  5003.     if (x > -1) {
  5004.     /*
  5005.       We don't really know the name of the lockfile, but
  5006.       this is what the man page says it is.  In USETTYLOCK
  5007.           builds, it is used only for display by SHOW COMM.
  5008.     */
  5009.     ckmakmsg(flfnam,FLFNAML,"/etc/locks/LCK..",lockname,NULL,NULL);
  5010.     haslock = 1;
  5011.     }
  5012.     return(x);
  5013. #endif /* USE_UU_LOCK */
  5014. #else  /* Systems that don't have ttylock()... */
  5015.  
  5016. #ifndef HPUX
  5017.  
  5018.     int lockfd;                /* File descriptor for lock file. */
  5019.     PID_T pid;                /* Process id of this process. */
  5020.     int tries;                /* How many times we've tried... */
  5021.     struct stat devbuf;            /* For device numbers (SVR4). */
  5022.  
  5023. #ifdef PIDSTRING
  5024.     char pid_str[32];            /* My pid in string format. */
  5025. #endif /* PIDSTRING */
  5026.  
  5027.     char *device, *devname;
  5028.  
  5029. #define LFNAML 256            /* Max length for lock file name. */
  5030.     char lockfil[LFNAML];        /* Lock file name */
  5031. #ifdef RTAIX
  5032.     char lklockf[LFNAML];        /* Name for link to lock file  */
  5033. #endif /* RTAIX */
  5034. #ifdef CKSYMLINK
  5035.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  5036. #endif /* CKSYMLINK */
  5037.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  5038.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  5039.                     /* or on cc command line. */
  5040.     haslock = 0;                        /* Not locked yet. */
  5041.     *flfnam = '\0';            /* Lockfile name is empty. */
  5042.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  5043.     pid = getpid();            /* Get id of this process. */
  5044.  
  5045. /*  Construct name of lockfile and temporary file */
  5046.  
  5047. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  5048. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  5049.  
  5050.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5051.  
  5052.     if (stat(ttdev,&devbuf) < 0)
  5053.       return(-1);
  5054.  
  5055. #ifdef CKSYMLINK
  5056.     islink = 1;                /* Assume it's a symlink */
  5057.     linkto[0] = '\0';            /* But we don't know to what */
  5058. #ifdef COMMENT
  5059. /*
  5060.   This is undependable.  If it worked it would save the readlink call if
  5061.   we knew the device name was not a link.
  5062. */
  5063. #ifdef S_ISLNK
  5064.     islink = S_ISLNK(devbuf.st_mode);
  5065.     debug(F101,"ttlock stat S_ISLNK","",islink);
  5066. #endif /* S_ISLNK */
  5067. #endif /* COMMENT */
  5068.     if (islink) {
  5069.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  5070.     debug(F111,"ttlock readlink",ttdev,n);
  5071.     if (n > -1)            /* It is */
  5072.       linkto[n] = '\0';
  5073.     else                /* It's not */
  5074.       islink = 0;
  5075.     debug(F111,"ttlock link",linkto,islink);
  5076.     }
  5077.     if (islink) {
  5078.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5079.     debug(F110,"ttlock linkdev",linkdev,0);
  5080.     }
  5081. #endif /* CKSYMLINK */
  5082.  
  5083. /*
  5084.   On SCO platforms, if we don't have a symlink, then let's pretend the
  5085.   name given for the device is a symlink, because later we will change
  5086.   the name if it contains any uppercase characters.
  5087. */
  5088. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5089.     if (!islink) {
  5090.     islink = 1;
  5091.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5092.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5093.     debug(F110,"ttlock linkdev",linkdev,0);
  5094.     }
  5095. #else
  5096. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5097.     if (!islink) {
  5098.     islink = 1;
  5099.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5100.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5101.     debug(F110,"ttlock linkdev",linkdev,0);
  5102.     }
  5103. #endif /* M_XENIX */
  5104. #endif /* CK_SCOV5 */
  5105.  
  5106. #ifdef ISIII                /* Interactive System III, PC/IX */
  5107.     ckstrncpy(lockfil, device, DEVNAMLEN);
  5108. #else  /* not ISIII */
  5109. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  5110. #ifdef COHERENT
  5111.     sprintf(lockfil,"LCK..%d.%d",    /* SAFE */
  5112.         major(devbuf.st_rdev),       /* major device number */
  5113.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  5114. #else
  5115.     /* Note: %d changed to %u in 8.0 -- %u is part of SVID for SVR4 */
  5116.     /* Lockfile name format verified to agree with Solaris cu, Dec 2001 */
  5117.     sprintf(lockfil,"LK.%03u.%03u.%03u", /* SAFE */
  5118.         major(devbuf.st_dev),    /* device */
  5119.         major(devbuf.st_rdev),    /* major device number */
  5120.         minor(devbuf.st_rdev));    /* minor device number */
  5121. #endif /* COHERENT */
  5122. #else  /* Not LFDEVNO */
  5123. #ifdef PTX                /* Dynix PTX */
  5124.     if ((device != &ttdev[5]) && (strncmp(ttdev,"/dev/",5) == 0)) {
  5125.     if ((int)strlen(device) + 8 < LFNAML)
  5126.       sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  5127.     else
  5128.       ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5129.     } else
  5130. #endif /* PTX */
  5131.       if ((int)strlen(device) + 5 < LFNAML)
  5132.     sprintf(lockfil,"LCK..%s", device);
  5133.       else
  5134.     ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5135. #ifdef RTAIX
  5136.     ckstrncpy(lklockf,device,DEVNAMLEN);
  5137. #endif /* RTAIX */
  5138. #ifdef CKSYMLINK
  5139.     symlock[0] = '\0';
  5140.     if (islink)
  5141.       ckmakmsg(symlock,LFNAML, "LCK..", linkdev, NULL, NULL);
  5142. #endif /* CKSYMLINK */
  5143. #endif /* LFDEVNO */
  5144. #endif /* ISIII */
  5145.  
  5146. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5147.     {
  5148.     /* Lowercase the entire filename. */
  5149.         /* SCO says we must do this in V5.0 and later. */
  5150.     /* BUT... watch out for devices -- like Digiboard Portserver */
  5151.     /* That can have hundreds of ports... */
  5152.     char *p = (char *)(lockfil + 5);
  5153.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  5154.     }
  5155. #ifdef CKSYMLINK
  5156.     if (islink) {            /* If no change */
  5157.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  5158.         islink = 0;
  5159.         symlock[0] = '\0';
  5160.     }
  5161.     }
  5162. #endif /* CKSYMLINK */
  5163. #else
  5164. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5165.     {
  5166.     int x; char c;
  5167.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  5168.     if (x > 0) {            /* If it's uppercase, lower it. */
  5169.         c = lockfil[x];
  5170.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  5171.     }
  5172.     }
  5173. #ifdef CKSYMLINK
  5174.     if (islink) {
  5175.     if (!strcmp(lockfil,symlock)) {    /* No change */
  5176.         islink = 0;            /* so no second lockfile */
  5177.         symlock[0] = '\0';
  5178.     }
  5179.     }
  5180. #endif /* CKSYMLINK */
  5181. #endif /* M_XENIX */
  5182. #endif /* CK_SCOV5 */
  5183.  
  5184. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  5185. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  5186.  
  5187.     ckmakmsg(flfnam,LFNAML,lockdir,"/",lockfil,NULL);
  5188.  
  5189. #ifdef RTAIX
  5190.     ckmakmsg(lkflfn,FLFNAML,lockdir,"/",lklockf,NULL);
  5191. #endif /* RTAIX */
  5192.  
  5193. #ifndef LFDEVNO
  5194. #ifdef CKSYMLINK
  5195.     /* If it's a link then also make a lockfile for the real name */
  5196.     debug(F111,"ttlock link symlock",symlock,islink);
  5197.     if (islink && symlock[0]) {
  5198.     /* But only if the lockfile names would be different. */
  5199.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  5200.     ckmakmsg(lock2,FLFNAML,lockdir,"/",symlock,NULL);
  5201.     debug(F110,"ttlock lock2",lock2,0);
  5202.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  5203.         debug(F100,"ttlock lock2 cleared","",0);
  5204.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  5205.     }
  5206.     }
  5207. #endif /* CKSYMLINK */
  5208. #endif /* LFDEVNO */
  5209.  
  5210.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* safe */
  5211.     debug(F110,"ttlock flfnam",flfnam,0);
  5212.     debug(F110,"ttlock tmpnam",tmpnam,0);
  5213.  
  5214.     priv_on();                /* Turn on privileges if possible. */
  5215.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  5216.     if (lockfd < 0) {            /* Create failed. */
  5217.     debug(F111,"ttlock creat failed",tmpnam,errno);
  5218.     if (errno == ENOENT) {
  5219.         perror(lockdir);
  5220.         printf("UUCP not installed or Kermit misconfigured\n");
  5221.     } else {
  5222.         if (!quiet)
  5223.           perror(lockdir);
  5224.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5225.     }
  5226.     priv_off();            /* Turn off privileges!!! */
  5227.     return(-1);            /* Return failure code. */
  5228.     }
  5229. /* Now write the pid into the temp lockfile in the appropriate format */
  5230.  
  5231. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  5232.     sprintf(                /* write PID as decimal string */
  5233.         pid_str,
  5234. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  5235. #ifdef FSSTND10                /* Version 1.0 calls for */
  5236.         "%010d\n",            /* leading zeros */
  5237. #else                    /* while version 1.2 calls for */
  5238.         "%10d\n",            /* leading spaces */
  5239. #endif /* FSSTND10 */
  5240. #else
  5241. #ifdef COHERENT
  5242.         "%d\n",            /* with leading nothing */
  5243. #else
  5244.         "%10d\n",            /* with leading blanks */
  5245. #endif /* COHERENT */
  5246. #endif /* LINUXFSSTND */
  5247.         (int) pid
  5248.         );                /* safe */
  5249.     write(lockfd, pid_str, 11);
  5250.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  5251.  
  5252. #else /* Not PIDSTRING, use integer PID */
  5253.  
  5254.     write(lockfd, (char *)&pid, sizeof(pid) );
  5255.     debug(F101,"ttlock pid","",(int) pid);
  5256.  
  5257. #endif /* PIDSTRING */
  5258.  
  5259. /* Now try to rename the temp file to the real lock file name. */
  5260. /* This will fail if a lock file of that name already exists.  */
  5261.  
  5262.     close(lockfd);            /* Close the temp lockfile. */
  5263.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  5264.     tries = 0;
  5265.     while (!haslock && tries++ < 2) {
  5266.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5267.     if (haslock) {                  /* If we got the lockfile */
  5268. #ifdef RTAIX
  5269.         link(flfnam,lkflfn);
  5270. #endif /* RTAIX */
  5271. #ifdef CKSYMLINK
  5272. #ifndef LFDEVNO
  5273.         if (islink && lock2[0])
  5274.           link(flfnam,lock2);
  5275. #endif /* LFDEVNO */
  5276. #endif /* CKSYMLINK */
  5277.  
  5278. #ifdef COMMENT
  5279. /* Can't do this any more because device is not open yet so no ttyfd. */
  5280. #ifdef LOCKF
  5281. /*
  5282.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  5283.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  5284.   seem to prevent multiple users accessing the same device by different names.
  5285. */
  5286.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  5287.                 debug(F111, "ttlock lockf returns errno", "", errno);
  5288.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5289.                     x = unlink(flfnam); /* remove the lockfile */
  5290. #ifdef RTAIX
  5291.             unlink(lkflfn);    /* And any links to it... */
  5292. #endif /* RTAIX */
  5293. #ifdef CKSYMLINK
  5294. #ifndef LFDEVNO
  5295.             if (islink && lock2[0])
  5296.               unlink(lock2);    /* ditto... */
  5297. #endif /* LFDEVNO */
  5298. #endif /* CKSYMLINK */
  5299.                     debug(F111,"ttlock unlink",flfnam,x);
  5300.                     haslock = 0;
  5301.             break;
  5302.         }
  5303.                 sleep(2);
  5304.         }
  5305.         if (haslock)        /* If we got an advisory lock */
  5306. #endif /* LOCKF */
  5307. #endif /* COMMENT */
  5308.           break;            /* We're done. */
  5309.  
  5310.     } else {            /* We didn't create a new lockfile. */
  5311.         priv_off();
  5312.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  5313.         priv_on();        /* cause ttchkpid turns priv_off... */
  5314.         unlink(tmpnam);        /* Delete the tempfile */
  5315.         debug(F100,"ttlock found tty locked","",0);
  5316.         priv_off();        /* Turn off privs */
  5317.         return(-2);        /* Code for device is in use. */
  5318.         }
  5319.         priv_on();
  5320.     }
  5321.     }
  5322.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5323.     priv_off();                /* Turn off privs */
  5324.     return(haslock ? 0 : -1);        /* Return link's return code. */
  5325.  
  5326. #else /* HPUX */
  5327.  
  5328. /*
  5329.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  5330.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  5331.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  5332.   designator which is a string of digits, possibly containing an imbedded
  5333.   letter "p".  Examples (for base name "tty"):
  5334.  
  5335.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  5336.  
  5337.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  5338.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  5339.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  5340.   However, we make and enforce no such distinctions; either notation is
  5341.   accepted on any model or HP-UX version as a valid unit designator.
  5342.  
  5343.   If a valid unit is specified (as opposed to a designer name or symlink), we
  5344.   check for all aliases of the given unit according to the devprefix[] array.
  5345.   If no lockfiles are found for the given unit, we can have the device; we
  5346.   create a lockfile LCK..name in the lockfile directory appropriate for the
  5347.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  5348.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  5349.   created with the "ttyd" prefix.  This is exactly what cu does.
  5350.  
  5351.   If the "set line" device does not have a valid unit designator, then it is
  5352.   used literally and no synomyms are searched for and only one lockfile is
  5353.   created.
  5354.  
  5355.   -fdc, March 1998.
  5356. */
  5357. #define LFNAML 80            /* Max length for lock file name. */
  5358.  
  5359.     int lockfd;                /* File descriptor for lock file. */
  5360.     PID_T pid;                /* Process ID of this process. */
  5361.     int fpid;                /* pid found in existing lockfile. */
  5362.     int tries;                /* How many times we've tried... */
  5363.     int i, k;                /* Workers */
  5364.  
  5365.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  5366.     char *unit, *p;            /* <instance>p<port> part of xxx */
  5367.  
  5368.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  5369.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  5370.  
  5371. #ifdef HPUX10                /* Lockfile directory */
  5372.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  5373. #else  /* HP-UX 9.xx and below */
  5374. #ifdef LOCK_DIR
  5375.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  5376. #else
  5377.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  5378. #endif /* LOCK_DIR */
  5379. #endif /* HPUX10 */
  5380.  
  5381.     haslock = 0;                        /* Not locked yet. */
  5382.     *flfnam = '\0';            /* Lockfile name is empty. */
  5383.     lock2[0] = '\0';            /* Second one too. */
  5384.     pid = getpid();            /* Get my process ID */
  5385. /*
  5386.   Construct name of lockfile and temporary file...
  5387.   device  = name of tty device without the path, e.g. "tty0p0"
  5388.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  5389. */
  5390.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5391.     debug(F110,"TTLOCK device",device,0);
  5392.     ckmakmsg(lockfil,LFNAML,"LCK..",device,NULL,NULL);
  5393.  
  5394.     k = 0;                /* Assume device is not locked */
  5395.     n = 0;                /* Digit counter */
  5396.     unit = device;            /* Unit = <instance>p<port> */
  5397.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  5398.       unit++;
  5399.     p = unit;                /* Verify <num>p<num> format... */
  5400.     debug(F110,"TTLOCK unit 1",unit,0);
  5401. /*
  5402.   The unit number is recognized as:
  5403.   (a) any sequence of digits that runs to the end of the string.
  5404.   (b) any (a) that includes one and only one letter "p", with at least
  5405.       one digit before and after it.
  5406. */
  5407.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  5408.     if (*p && n > 0) {            /* Have a "p"? */
  5409.     if (*p == 'p' && isdigit(*(p+1))) {
  5410.         p++;
  5411.         n = 0;
  5412.         while (isdigit(*p)) p++, n++;
  5413.     }
  5414.     }
  5415.     if (n == 0 || *p) unit = "";
  5416.     debug(F110,"TTLOCK unit 2",unit,0);
  5417.  
  5418.     if (*unit) {            /* Device name has unit number. */
  5419.     /* The following loop not only searches for the various lockfile    */
  5420.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  5421.     /* for the device, should there be more than one.  See ttchkpid().  */
  5422.     ttydexists = 0;
  5423.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  5424.         /* Make device name */
  5425.         ckmakmsg(lock2,FLFNAML,"/dev/",devprefix[i],unit,NULL);
  5426.         priv_on();            /* Privs on */
  5427.         k = zchki(lock2) != -1;    /* See if device exists */
  5428.         priv_off();            /* Privs off */
  5429.         debug(F111,"TTLOCK exist",lock2,k);
  5430.             if (k) {
  5431.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  5432.           ttydexists = 1;
  5433.         /* Make lockfile name */
  5434.         ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",devprefix[i],unit);
  5435.         debug(F110,"TTLOCK checking",lock2,0);
  5436.         priv_on();        /* Privs on */
  5437.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  5438.         priv_off();        /* Privs off */
  5439.         debug(F111,"TTLOCK check for lock A",lock2,k);
  5440.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  5441.             ckstrncpy(flfnam,lock2,FLFNAML);
  5442.             return(-2);
  5443.         }
  5444.         }
  5445.     }
  5446.     } else {                /* Some other device-name format */
  5447.     /* This takes care of symbolic links, etc... */
  5448.     /* But does not chase them down! */
  5449.     ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",device,NULL);
  5450.     priv_on();
  5451.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  5452.     priv_off();
  5453.     debug(F111,"TTLOCK check for lock B",lock2,k);
  5454.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  5455.         ckstrncpy(flfnam,lock2,FLFNAML);
  5456.         debug(F110,"TTLOCK in use",device,0);
  5457.         debug(F101,"TTLOCK returns","",-2);
  5458.         return(-2);
  5459.     }
  5460.     }
  5461. /*
  5462.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  5463.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  5464.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  5465. */
  5466.     ckmakmsg(flfnam,FLFNAML,lockdir,"/",lockfil,NULL); /* SET LINE device */
  5467.  
  5468.     /* If dialout device, also make one for corresponding dialin device */
  5469.     lock2[0] = '\0';
  5470.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  5471.       ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..ttyd",unit,NULL);
  5472.  
  5473.     if ((int)strlen(lockdir)+12 < LFNAML)
  5474.       sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temp name */
  5475. #ifdef DEBUG
  5476.     if (deblog) {
  5477.     debug(F110,"TTLOCK flfnam",flfnam,0);
  5478.     debug(F110,"TTLOCK lock2",lock2,0);
  5479.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  5480.     }
  5481. #endif /* DEBUG */
  5482. /*
  5483.    Lockfile permissions...
  5484.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  5485.    Kermit uses 444; the difference lets us tell whether Kermit created
  5486.    the lock file.
  5487. */
  5488.     priv_on();                /* Turn on privileges. */
  5489.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  5490.     if (lockfd < 0) {            /* Create failed. */
  5491.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  5492.     if (errno == ENOENT) {
  5493.         perror(lockdir);
  5494.         printf("UUCP not installed or Kermit misconfigured\n");
  5495.     } else {
  5496.         if (!quiet)
  5497.           perror(lockdir);
  5498.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5499.     }
  5500.     priv_off();            /* Turn off privileges!!! */
  5501.     debug(F101,"TTLOCK returns","",-1);
  5502.     return(-1);            /* Return failure code. */
  5503.     }
  5504.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  5505.  
  5506. /* Now write our pid into the temp lockfile in integer format. */
  5507.  
  5508.     i = write(lockfd, (char *)&pid, sizeof(pid));
  5509.  
  5510. #ifdef DEBUG
  5511.     if (deblog) {
  5512.     debug(F101,"TTLOCK pid","",pid);
  5513.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  5514.     debug(F101,"TTLOCK write pid returns","",i);
  5515.     }
  5516. #endif /* DEBUG */
  5517.  
  5518. /*
  5519.   Now try to rename the temporary file to the real lockfile name.
  5520.   This will fail if a lock file of that name already exists, which
  5521.   will catch race conditions with other users.
  5522. */
  5523.     close(lockfd);            /* Close the temp lockfile. */
  5524.     chmod(tmpnam,0444);
  5525.  
  5526.     tries = 0;
  5527.     while (!haslock && tries++ < 2) {
  5528.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5529.     debug(F101,"TTLOCK link","",haslock);
  5530.     if (haslock) {            /* If we made the lockfile... */
  5531.  
  5532. #ifdef COMMENT
  5533. /* We can't do this any more because we don't have a file descriptor yet. */
  5534. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  5535. /*
  5536.   Create an advisory lock on the device through its file descriptor.
  5537.   This code actually seems to work.  If it is executed, and then another
  5538.   process tries to open the same device under a different name to circumvent
  5539.   the lockfile, they get a "device busy" error.
  5540. */
  5541.         debug(F100,"TTLOCK LOCKF code...","",0);
  5542.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  5543.                 debug(F111, "TTLOCK lockf error", "", errno);
  5544.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5545.                     x = unlink(flfnam); /* Remove the lockfile */
  5546.             if (errno == EACCES && !quiet)
  5547.               printf("Device already locked by another process\n");
  5548.                     haslock = 0;
  5549.             break;
  5550.         }
  5551.                 sleep(2);
  5552.         }
  5553. #endif /* LOCKF */
  5554. #endif /* COMMENT */
  5555.  
  5556.         if (haslock) {        /* If we made the lockfile ... */
  5557.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  5558.             lockfd = creat(lock2, 0444); /* Create it */
  5559.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  5560.             if (lockfd > -1) {    /* Created OK, write pid. */
  5561.             write(lockfd, (char *)&pid, sizeof(pid) );
  5562.             close(lockfd);    /* Close and */
  5563.             chmod(lock2, 0444); /* set permissions. */
  5564.             } else {         /* Not OK, but don't fail. */
  5565.             lock2[0] = '\0'; /* Just remember it's not there. */
  5566.             }
  5567.         }
  5568.         break;            /* and we're done. */
  5569.         }
  5570.     }
  5571.     }
  5572.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5573.     priv_off();                /* Turn off privs */
  5574.     i = haslock ? 0 : -1;        /* Our return value */
  5575.     debug(F101,"TTLOCK returns","",i);
  5576.     return(i);
  5577. #endif /* HPUX */
  5578. #endif /* USETTYLOCK */
  5579. #endif /* !NOUUCP */
  5580. }
  5581.  
  5582. /*  T T U N L O C K  */
  5583.  
  5584. static int
  5585. ttunlck() {                             /* Remove UUCP lockfile(s). */
  5586. #ifndef NOUUCP
  5587.     int x;
  5588.  
  5589.     debug(F111,"ttunlck",flfnam,haslock);
  5590.  
  5591. #ifdef USETTYLOCK
  5592.  
  5593.     if (haslock && *flfnam) {
  5594.     int x;
  5595.     priv_on();            /* Turn on privs */
  5596. #ifdef USE_UU_LOCK
  5597.     x = uu_unlock(lockname);
  5598. #else  /* USE_UU_LOCK */
  5599.     x = ttyunlock(lockname);    /* Try to unlock */
  5600. #endif /* USE_UU_LOCK */
  5601.     priv_off();            /* Turn off privs */
  5602.     if (x < 0 && !quiet)
  5603.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5604.  
  5605.     *flfnam = '\0';            /* Erase the name. */
  5606.     haslock = 0;
  5607.     return(0);
  5608.     }
  5609.  
  5610. #else  /* No ttylock()... */
  5611.  
  5612.     if (haslock && *flfnam) {
  5613.     /* Don't remove lockfile if we didn't make it ourselves */
  5614.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  5615.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  5616.         printf("Warning - Lockfile %s seized by pid %d\n",
  5617.            flfnam,
  5618.            x
  5619.            );
  5620.         return(0);
  5621.     }
  5622.     priv_on();            /* Turn privileges on.  */
  5623.     errno = 0;
  5624.     x = unlink(flfnam);        /* Remove the lockfile. */
  5625.     debug(F111,"ttunlck unlink",flfnam,x);
  5626.     if (x < 0) {
  5627.         if (errno && !quiet)
  5628.           perror(ttnmsv);
  5629.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5630.     }
  5631.     haslock = 0;
  5632.     *flfnam = '\0';            /* Erase the name. */
  5633.  
  5634. #ifdef RTAIX
  5635.     errno = 0;
  5636.     x = unlink(lkflfn);        /* Remove link to lockfile */
  5637.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  5638.     if (x < 0) {
  5639.         if (errno && !quiet)
  5640.           perror(ttnmsv);
  5641.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  5642.     }
  5643.     *lkflfn = '\0';
  5644. #else
  5645.     if (lock2[0]) {            /* If there is a second lockfile, */
  5646.         errno = 0;
  5647.         x = unlink(lock2);        /*  remove it too. */
  5648.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  5649.         if (x < 0) {
  5650.         if (errno && !quiet)
  5651.           perror(ttnmsv);
  5652.         printf("Warning - Can't remove secondary lockfile: %s\n",
  5653.                lock2
  5654.                );
  5655.         }
  5656.         lock2[0] = '\0';        /* Forget its name. */
  5657.     }
  5658. #endif /* RTAIX */
  5659.  
  5660. #ifdef COMMENT
  5661. #ifdef LOCKF
  5662.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  5663. #endif /* LOCKF */
  5664. #endif /* COMMENT */
  5665.  
  5666.     priv_off();            /* Turn privileges off. */
  5667.     }
  5668. #endif /* USETTYLOCK */
  5669. #endif /* !NOUUCP */
  5670.     return(0);
  5671. }
  5672.  
  5673. /*
  5674.   4.3BSD-style UUCP line direction control.
  5675.   (Stan Barber, Rice U, 1980-something...)
  5676. */
  5677. #ifndef NOUUCP
  5678. #ifdef ACUCNTRL
  5679. VOID
  5680. acucntrl(flag,ttname) char *flag, *ttname; {
  5681.     char x[DEVNAMLEN+32], *device, *devname;
  5682.  
  5683.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  5684.       return;                /* just return. */
  5685.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  5686.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  5687.     ckmakmsg(x,DEVNAMLEN+32,"/usr/lib/uucp/acucntrl ",flag," ",device);
  5688.     debug(F110,"called ",x,0);
  5689.     zsyscmd(x);
  5690. }
  5691. #endif /* ACUCNTRL */
  5692. #endif /* NOUUCP */
  5693.  
  5694. /*
  5695.   T T H F L O W  --  Set or Reset hardware flow control.
  5696.  
  5697.   This is an attempt to collect all hardware-flow-control related code
  5698.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  5699.   help here.  Overview:
  5700.  
  5701.   Hardware flow control is not supported in many UNIX implementions.  Even
  5702.   when it is supported, there is no (ha ha) "standard" for the programming
  5703.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  5704.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  5705.   relevant here, the programming interface often brings one only to a no-op
  5706.   in the device driver!)
  5707.  
  5708.   Among all these, we have two major types of APIs: those in which hardware
  5709.   flow control is determined by bits in the same termio/termios/sgtty mode
  5710.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  5711.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  5712.   for changing terminal modes.  And those that use entirely different
  5713.   mechanisms.
  5714.  
  5715.   In the first category, it is important that any change in the mode bits be
  5716.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  5717.   changes to that structure do not wipe out the effects of this routine.  That
  5718.   is why a pointer, attrs, to the appropriate structure is passed as a
  5719.   parameter to this routine.
  5720.  
  5721.   The second category should give us no worries, since any changes to hardware
  5722.   flow control accomplished by this routine should not affect the termio(s)/
  5723.   sgtty structures, and therefore will not be undone by later changes to them.
  5724.  
  5725.   The second argument, status, means to turn on hardware flow control if
  5726.   nonzero, and to turn it off if zero.
  5727.  
  5728.   Returns: 0 on apparent success, -1 on probable failure.
  5729. */
  5730.  
  5731. /*
  5732.   The following business is for BSDI, where it was discovered that two
  5733.   separate bits, CCTS_OFLOW and CRTS_IFLOW, are used in hardware flow control,
  5734.   but CTRSCTS is defined (in <termios.h>) to be just CCTS_OFLOW rather both
  5735.   bits, so hwfc only works in one direction if you use CRTSCTS to control it.
  5736.   Other 4.4BSD-based Unixes such as FreeBSD 4.1, which use these two bits,
  5737.   define CRTSCTS correctly.
  5738. */
  5739. #ifdef FIXCRTSCTS
  5740. #ifdef CRTSCTS
  5741. #ifdef CCTS_OFLOW
  5742. #ifdef CRTS_IFLOW
  5743. #undef CRTSCTS
  5744. #define CRTSCTS (CRTS_IFLOW|CCTS_OFLOW)
  5745. #endif /* CRTS_IFLOW */
  5746. #endif /* CCTS_OFLOW */
  5747. #endif /* CRTSCTS */
  5748. #endif /* FIXCRTSCTS */
  5749.  
  5750. static int
  5751. tthflow(flow, status, attrs)
  5752.     int flow,                /* Type of flow control (ckcdeb.h) */
  5753.     status;                /* Nonzero = turn it on */
  5754.                     /* Zero = turn it off */
  5755. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  5756.     struct termios *attrs;
  5757. #else                    /* System V */
  5758. #ifdef ATTSV
  5759. #ifdef ATT7300
  5760. #ifdef UNIX351M
  5761. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  5762. #define RTSFLOW CTSCD
  5763. #define CTSFLOW CTSCD
  5764. #endif /* ATT7300 */
  5765. #endif /* UNIX351M */
  5766.     struct termio *attrs;
  5767. #else                    /* BSD, V7, etc */
  5768.     struct sgttyb *attrs;        /* sgtty info... */
  5769. #endif /* ATTSV */
  5770. #endif /* BSD44ORPOSIX */
  5771. /* tthflow */ {
  5772.  
  5773.     int x = 0;                /* tthflow() return code */
  5774.  
  5775. #ifdef Plan9
  5776.     return p9tthflow(flow, status);
  5777. #else
  5778.  
  5779. #ifndef OXOS                /* NOT Olivetti X/OS... */
  5780. /*
  5781.   For SunOS 4.0 and later in the BSD environment ...
  5782.  
  5783.   The declarations are copied and interpreted from the System V header files,
  5784.   so we don't actually have to pull in all the System V junk when building
  5785.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  5786.   having those symbols defined would cause us to take the wrong paths through
  5787.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  5788.   versions.
  5789. */
  5790. #ifdef SUNOS41
  5791. /*
  5792.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  5793.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  5794.   the POSIX forms work for both.  But the POSIX calls are not available in
  5795.   SunOS 4.0.
  5796. */
  5797. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  5798. #define TCSANOW 0            /* Do it now */
  5799.  
  5800.     struct termios {
  5801.     unsigned long c_iflag;        /* Input modes */
  5802.     unsigned long c_oflag;        /* Output modes */
  5803.     unsigned long c_cflag;        /* Control modes */
  5804.     unsigned long c_lflag;        /* Line discipline modes */
  5805.     char c_line;
  5806.     CHAR c_cc[17];
  5807.     };
  5808.     struct termios temp;
  5809.  
  5810. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  5811. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  5812. /*
  5813.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  5814.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  5815.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  5816.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  5817. */
  5818.     int mflags;                /* Modem signal flags */
  5819.  
  5820. #ifdef NETCMD
  5821.     if (ttpipe) return(0);
  5822. #endif /* NETCMD */
  5823. #ifdef NETPTY
  5824.     if (ttpty) return(0);
  5825. #endif /* NETPTY */
  5826.  
  5827.     debug(F101,"tthflow SUNOS41 entry status","",status);
  5828.     if (!status) {            /* Turn hard flow off */
  5829.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5830.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5831.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5832.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5833.     }
  5834.     } else {                /* Turn hard flow on */
  5835.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  5836.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  5837.         debug(F100,"tthflow SunOS has CD","",0);
  5838.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5839.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5840.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  5841.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5842.         }
  5843.     } else {
  5844.         x = -1;
  5845.         debug(F100,"tthflow SunOS no CD","",0);
  5846.     }
  5847.     }
  5848. #else
  5849. #ifdef QNX
  5850.     struct termios temp;
  5851. #ifdef NETCMD
  5852.     if (ttpipe) return(0);
  5853. #endif /* NETCMD */
  5854. #ifdef NETPTY
  5855.     if (ttpty) return(0);
  5856. #endif /* NETPTY */
  5857.     debug(F101,"tthflow QNX entry status","",status);
  5858.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  5859.     if (!status) {            /* Turn hard flow off */
  5860.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  5861.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  5862.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  5863.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5864.         }
  5865.     } else {            /* Turn hard flow on */
  5866.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  5867.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  5868.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  5869.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  5870.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5871.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  5872.         attrs->c_iflag &= ~(IXON|IXOFF);
  5873.         }
  5874.     }
  5875.     } else {
  5876.     x = -1;
  5877.     debug(F100, "tthflow QNX getattr fails", "", 0);
  5878.     }
  5879. #else
  5880. #ifdef POSIX_CRTSCTS
  5881. /*
  5882.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  5883.   Note: Do not assume CRTSCTS is a one-bit field!
  5884. */
  5885.     struct termios temp;
  5886. #ifdef NETCMD
  5887.     if (ttpipe) return(0);
  5888. #endif /* NETCMD */
  5889. #ifdef NETPTY
  5890.     if (ttpty) return(0);
  5891. #endif /* NETPTY */
  5892.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  5893.     errno = 0;
  5894.     x = tcgetattr(ttyfd, &temp);
  5895.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  5896.     errno = 0;
  5897.     if (x < 0) {
  5898.     x = -1;
  5899.     } else {
  5900.     if (!status) {            /* Turn hard flow off */
  5901.         if (
  5902. #ifdef COMMENT
  5903.         /* This can fail because of sign extension */
  5904.         /* e.g. in Linux where it's Bit 31 */
  5905.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5906. #else
  5907.         (temp.c_cflag & CRTSCTS) != 0
  5908. #endif /* COMMENT */
  5909.         ) {
  5910.         temp.c_cflag &= ~CRTSCTS; /* It's there, remove it */
  5911.         attrs->c_cflag &= ~CRTSCTS;
  5912.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5913.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5914.               ckitoa(x),errno);
  5915.         } else {            /* John Dunlap 2010-01-26 */
  5916.         debug(F001,
  5917.               "tthflow before forcing off attrs CRTSCTS",
  5918.               "",
  5919.               attrs->c_cflag&CRTSCTS
  5920.               );
  5921.         attrs->c_cflag &= ~CRTSCTS; /* force it off if !status */
  5922.         debug(F001,
  5923.               "tthflow after forcing off attrs CRTSCTS",
  5924.               "",
  5925.               attrs->c_cflag&CRTSCTS
  5926.               );
  5927.         }
  5928.     } else {            /* Turn hard flow on */
  5929.         if (
  5930. #ifdef COMMENT
  5931.         /* This can fail because of sign extension */
  5932.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5933. #else
  5934.         (temp.c_cflag & CRTSCTS) == 0
  5935. #endif /* COMMENT */
  5936.         ) {
  5937.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5938.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5939.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5940.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5941.               ckitoa(x),errno);
  5942.         attrs->c_cflag |= CRTSCTS;
  5943.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5944.         }
  5945.     }
  5946.     }
  5947. #else
  5948. #ifdef SUNOS4
  5949. /*
  5950.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5951.   prevents compilation with GNU gcc, which uses different formats for the
  5952.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5953.   routines above, which work for both cc and gcc.
  5954. */
  5955. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5956. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5957. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5958.  
  5959.     struct termios {
  5960.     unsigned long c_iflag;        /* Input modes */
  5961.     unsigned long c_oflag;        /* Output modes */
  5962.     unsigned long c_cflag;        /* Control modes */
  5963.     unsigned long c_lflag;        /* Line discipline modes */
  5964.     char c_line;
  5965.     CHAR c_cc[17];
  5966.     };
  5967.     struct termios temp;
  5968. #ifdef NETCMD
  5969.     if (ttpipe) return(0);
  5970. #endif /* NETCMD */
  5971. #ifdef NETPTY
  5972.     if (ttpty) return(0);
  5973. #endif /* NETPTY */
  5974.     debug(F101,"tthflow entry status","",status);
  5975.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  5976.     if (status) {            /* Turn hard flow on */
  5977.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  5978.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  5979.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  5980.     } else {            /* Turn hard flow off */
  5981.         temp.c_cflag &= ~CRTSCTS;
  5982.         x = ioctl(ttyfd,TCSETS,&temp);
  5983.         attrs->c_cflag &= ~CRTSCTS;
  5984.     }
  5985.     }
  5986. #else                    /* Not SunOS 4.0 or later */
  5987. #ifdef AIXRS                /* IBM AIX RS/6000 */
  5988. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  5989. #ifdef NETCMD
  5990.     if (ttpipe) return(0);
  5991. #endif /* NETCMD */
  5992. #ifdef NETPTY
  5993.     if (ttpty) return(0);
  5994. #endif /* NETPTY */
  5995.     if (status) {
  5996.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  5997.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  5998.     } else {
  5999.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  6000.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  6001.     }
  6002. #endif /* AIX41 */
  6003. #else                    /* Not AIX RS/6000 */
  6004.  
  6005. #ifdef ATTSV                /* System V... */
  6006.  
  6007. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  6008. #define CK_SCOUNIX
  6009. #else
  6010. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  6011. #define CK_SCOUNIX
  6012. #endif /* M_UNIX */
  6013. #endif /* CK_SCOV5 */
  6014.  
  6015. #ifdef SCO_FORCE_RTSXOFF
  6016. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  6017. #ifdef SCO_OSR504            /* or later... */
  6018. #undef CK_SCOUNIX
  6019. #endif /* SCO_OSR504 */
  6020. #endif /* CK_SCOUNIX */
  6021. #endif /* SCO_FORCE_RTSXOFF */
  6022.  
  6023. #ifdef CK_SCOUNIX
  6024. #ifdef POSIX
  6025.     struct termios temp;
  6026. #ifdef NETCMD
  6027.     if (ttpipe) return(0);
  6028. #endif /* NETCMD */
  6029. #ifdef NETPTY
  6030.     if (ttpty) return(0);
  6031. #endif /* NETPTY */
  6032.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  6033.     errno = 0;
  6034.     x = tcgetattr(ttyfd, &temp);
  6035.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  6036. #else /* POSIX */
  6037.     struct termio temp;
  6038. #ifdef NETCMD
  6039.     if (ttpipe) return(0);
  6040. #endif /* NETCMD */
  6041. #ifdef NETPTY
  6042.     if (ttpty) return(0);
  6043. #endif /* NETPTY */
  6044.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  6045.     x = ioctl(ttyfd, TCGETA, &temp);
  6046.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  6047. #endif /* POSIX */
  6048. /*
  6049.   This is not really POSIX, since POSIX does not deal with hardware flow
  6050.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  6051.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  6052.   let's try forcing their definitions here.
  6053. */
  6054. #ifndef CTSFLOW
  6055. #define CTSFLOW 0020000
  6056.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  6057. #else
  6058.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  6059. #endif /* CTSFLOW */
  6060. #ifndef RTSFLOW
  6061. #define RTSFLOW 0040000
  6062.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  6063. #else
  6064.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  6065. #endif /* RTSFLOW */
  6066. #ifndef ORTSFL
  6067. #define ORTSFL 0100000
  6068.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  6069. #else
  6070.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  6071. #endif /* ORTSFL */
  6072.  
  6073.     if (x != -1) {
  6074.     if (status) {            /* Turn it ON */
  6075.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  6076.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  6077. #ifdef ORTSFL
  6078.         temp.c_cflag &= ~ORTSFL;
  6079.         attrs->c_cflag &= ~ORTSFL;
  6080. #endif /* ORTSFL */
  6081.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  6082.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  6083.     } else {            /* Turn it OFF */
  6084. #ifdef ORTSFL
  6085.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6086.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6087. #else  /* ORTSFL */
  6088.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  6089.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  6090. #endif /* ORTSFL */
  6091.     }
  6092. #ifdef POSIX
  6093.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  6094. #else
  6095.     x = ioctl(ttyfd, TCSETA, &temp);
  6096. #endif /* POSIX */
  6097.     debug(F101,"tthflow SCO set modes","",x);
  6098.     }
  6099. #else /* Not SCO UNIX */
  6100. #ifdef NETCMD
  6101.     if (ttpipe) return(0);
  6102. #endif /* NETCMD */
  6103. #ifdef NETPTY
  6104.     if (ttpty) return(0);
  6105. #endif /* NETPTY */
  6106.     if (!status) {            /* Turn it OFF */
  6107. #ifdef RTSXOFF
  6108.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  6109.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  6110. #ifdef TCSETX
  6111.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6112.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  6113. #else
  6114.     x = -1
  6115.     debug(F100,"tthflow TCSETX not defined","",0);
  6116. #endif /* TCSETX */
  6117. #else
  6118.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  6119. #endif /* RTSXOFF */
  6120. #ifdef DTRXOFF
  6121.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  6122.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6123.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6124.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  6125. #else
  6126.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6127. #endif /* DTRXOFF */
  6128.     } else {                /* Turn it ON. */
  6129.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  6130.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  6131. #ifdef RTSXOFF
  6132.         /* This is the preferred way, according to SVID3 */
  6133. #ifdef TCGETX
  6134.         x = ioctl(ttyfd,TCGETX,&rctsx);
  6135.         debug(F101,"tthflow TCGETX","",x);
  6136.         if (x > -1) {
  6137.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  6138.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6139.         debug(F100,"tthflow ATTSV ioctl","",x);
  6140.         }
  6141. #else
  6142.         debug(F100,"tthflow TCGETX not defined","",0);
  6143.         x = -1
  6144. #endif /* TCGETX */
  6145. #else
  6146.         debug(F100,"tthflow RTSXOFF not defined","",0);
  6147.         x = -1;
  6148. #endif /* RTSXOFF */
  6149.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  6150.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  6151. #ifdef DTRXOFF
  6152.         /* This is straight out of SVID R4 */
  6153.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  6154.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6155.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6156.         }
  6157. #else
  6158.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6159.         x = -1;
  6160. #endif /* DTRXOFF */
  6161.     }
  6162.     }
  6163. #endif /* CK_SCOUNIX */
  6164.  
  6165. #else /* not System V... */
  6166.  
  6167. #ifdef CK_DTRCTS
  6168. #ifdef LDODTR
  6169. #ifdef LDOCTS
  6170. #ifdef NETCMD
  6171.     if (ttpipe) return(0);
  6172. #endif /* NETCMD */
  6173. #ifdef NETPTY
  6174.     if (ttpty) return(0);
  6175. #endif /* NETPTY */
  6176.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  6177.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  6178.     if (lmodef) {
  6179.         x = ioctl(ttyfd,TIOCLBIS,&x);
  6180.         if (x < 0) {
  6181.             debug(F100,"hardflow TIOCLBIS error","",0);
  6182.         } else {
  6183.         lmodef++;
  6184.         debug(F100,"hardflow TIOCLBIS ok","",0);
  6185.         }
  6186.     }
  6187.     } else {
  6188.     if (lmodef) {
  6189.         x = ioctl(ttyfd,TIOCLBIC,&x);
  6190.         if (x < 0) {
  6191.             debug(F100,"hardflow TIOCLBIC error","",0);
  6192.         } else {
  6193.         lmodef++;
  6194.         debug(F100,"hardflow TIOCLBIC ok","",0);
  6195.         }
  6196.     }
  6197.     }
  6198. #endif /* LDODTR */
  6199. #endif /* LDOCTS */
  6200. #endif /* CK_DTRCTS */
  6201. #endif /* ATTSV */
  6202. #endif /* AIXRS */
  6203. #endif /* SUNOS4 */
  6204. #endif /* QNX */
  6205. #endif /* POSIX_CRTSCTS */
  6206. #endif /* SUNOS41 */
  6207.  
  6208. #else /* OXOS */
  6209.  
  6210.     struct termios temp;        /* Olivetti X/OS ... */
  6211.  
  6212. #ifdef NETCMD
  6213.     if (ttpipe) return(0);
  6214. #endif /* NETCMD */
  6215. #ifdef NETPTY
  6216.     if (ttpty) return(0);
  6217. #endif /* NETPTY */
  6218.     x = ioctl(ttyfd,TCGETS,&temp);
  6219.     if (x == 0) {
  6220.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  6221.     if (status) {
  6222.         switch (flow) {
  6223.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  6224.         break;
  6225.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  6226.         break;
  6227.         }
  6228.     }
  6229.     x = ioctl(ttyfd,TCSETS,&temp);
  6230.     }
  6231. #endif /* OXOS */
  6232.     return(x);
  6233.  
  6234. #endif /* Plan9 */
  6235. }
  6236.  
  6237. /*  T T P K T  --  Condition the communication line for packets */
  6238. /*                 or for modem dialing */
  6239.  
  6240. /*
  6241.   If called with speed > -1, also set the speed.
  6242.   Returns 0 on success, -1 on failure.
  6243.  
  6244.   NOTE: the "xflow" parameter is supposed to be the currently selected
  6245.   type of flow control, but for historical reasons, this parameter is also
  6246.   used to indicate that we are dialing.  Therefore, when the true flow
  6247.   control setting is needed, we access the external variable "flow", rather
  6248.   than trusting our "xflow" argument.
  6249. */
  6250. int
  6251. #ifdef CK_ANSIC
  6252. ttpkt(long speed, int xflow, int parity)
  6253. #else
  6254. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  6255. #endif /* CK_ANSIC */
  6256. /* ttpkt */ {
  6257. #ifndef NOLOCAL
  6258.     int s2;
  6259.     int s = -1;
  6260. #endif /* NOLOCAL */
  6261.     int x;
  6262.     extern int flow;            /* REAL flow-control setting */
  6263.  
  6264.     if (ttyfd < 0) return(-1);          /* Not open. */
  6265.  
  6266.     debug(F101,"ttpkt parity","",parity);
  6267.     debug(F101,"ttpkt xflow","",xflow);
  6268.     debug(F101,"ttpkt speed","",(int) speed);
  6269.  
  6270.     ttprty = parity;                    /* Let other tt functions see these. */
  6271.     ttspeed = speed;            /* Make global copy for this module */
  6272.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  6273. #ifdef PARSENSE
  6274.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  6275. #else
  6276.     needpchk = 0;
  6277. #endif /* PARSENSE */
  6278.  
  6279.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  6280.     debug(F101,"ttpkt netconn","",netconn);
  6281.  
  6282. #ifdef NETCONN                /* No mode-changing for telnet */
  6283.     if (netconn) {
  6284. #ifdef TCPSOCKET
  6285. #ifdef TCP_NODELAY
  6286.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  6287.             extern int tcp_nodelay;
  6288.             nodelay_sav = tcp_nodelay;
  6289.             no_delay(ttyfd,1);
  6290.         }
  6291. #endif /* TCP_NODELAY */
  6292. #ifdef TN_COMPORT
  6293.         if (istncomport()) {
  6294.             int rc = -1;
  6295.             if (tvtflg == 0 && speed == ttspeed && flow == ttflow
  6296.                  /* && ttcarr == curcarr */ ) {
  6297.                 debug(F100,"ttpkt modes already set, skipping...","",0);
  6298.                 return(0);        /* Already been called. */
  6299.             }
  6300.             if (flow != ttflow) {
  6301.                 if ((rc = tnsetflow(flow)) < 0)
  6302.           return(rc);
  6303.                 ttflow = flow;
  6304.             }
  6305.             if (speed != ttspeed) {
  6306.                 if (speed <= 0) 
  6307.           speed = tnc_get_baud();
  6308.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6309.           return(rc);
  6310.                 ttspeed = speed;
  6311.             }
  6312.             tnc_set_datasize(8);
  6313.         tnc_set_stopsize(stopbits);
  6314.  
  6315. #ifdef HWPARITY
  6316.             if (hwparity) {
  6317.                 switch (hwparity) {
  6318.           case 'e':            /* Even */
  6319.                     debug(F100,"ttres 8 bits + even parity","",0);
  6320.                     tnc_set_parity(3);
  6321.                     break;
  6322.           case 'o':            /* Odd */
  6323.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6324.                     tnc_set_parity(2);
  6325.                     break;
  6326.           case 'm':            /* Mark */
  6327.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6328.                     tnc_set_parity(4);
  6329.                     break;
  6330.           case 's':            /* Space */
  6331.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6332.                     tnc_set_parity(5);
  6333.                     break;
  6334.                 }
  6335.             } else 
  6336. #endif /* HWPARITY */
  6337.         {
  6338.                 tnc_set_parity(1);              /* None */
  6339.             }
  6340.             tvtflg = 0;
  6341.             return(0);
  6342.         }
  6343. #endif /* TN_COMPORT */
  6344. #endif /* TCPSOCKET */
  6345.         tvtflg = 0;
  6346.         return(0);
  6347.     }
  6348. #endif /* NETCONN */
  6349. #ifdef NETCMD
  6350.     if (ttpipe) return(0);
  6351. #endif /* NETCMD */
  6352. #ifdef NETPTY
  6353.     if (ttpty) return(0);
  6354. #endif /* NETPTY */
  6355.  
  6356. #ifndef Plan9
  6357.     if (ttfdflg && !isatty(ttyfd)) return(0);
  6358. #endif /* Plan9 */
  6359.  
  6360. #ifdef COHERENT
  6361. #define SVORPOSIX
  6362. #endif /* COHERENT */
  6363.  
  6364. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  6365. #ifdef LPASS8
  6366. /*
  6367.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  6368.  after having previously set it to NONE without closing and reopening the
  6369.  device.  Unless there's something I overlooked below...
  6370. */
  6371.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  6372.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  6373.     ttclos(0);            /* Close it */
  6374.     x = 0;
  6375.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  6376.     }
  6377. #endif /* LPASS8 */
  6378. #endif /* SVORPOSIX */
  6379.  
  6380. #ifdef COHERENT                /* This must be vestigial since we */
  6381. #undef SVORPOSIX            /* reverse it a few lines below... */
  6382. #endif /* COHERENT */
  6383.  
  6384.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  6385.       ttflow = xflow;            /* Now make this available too. */
  6386.  
  6387. #ifndef NOLOCAL
  6388.     if (xlocal) {
  6389.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  6390.     debug(F101,"ttpkt calling ttsspd","",s2);
  6391.     s = ttsspd(s2);            /* Check and set the speed */
  6392.     debug(F101,"ttpkt ttsspd result","",s);
  6393.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  6394.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6395.     tvtflg = 0;            /* So ttvt() will work next time */
  6396.     }
  6397. #endif /* NOLOCAL */
  6398.  
  6399. #ifdef COHERENT
  6400. #define SVORPOSIX
  6401. #endif /* COHERENT */
  6402.  
  6403. #ifndef SVORPOSIX            /* BSD section */
  6404.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6405.     flow == FLO_DTRC ||
  6406.     flow == FLO_DTRT) {
  6407.     tthflow(flow, 1, &ttraw);
  6408.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  6409.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6410.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6411.     } else if (flow == FLO_NONE) {    /* No flow control */
  6412.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  6413.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6414.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  6415.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6416.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6417.     debug(F100,"ttpkt keeping original TANDEM","",0);
  6418.     ttraw.sg_flags &= ~TANDEM;
  6419.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  6420.     /* NOTE: We should also handle hardware flow control here! */
  6421.     }
  6422.  
  6423. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  6424.  
  6425.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  6426.     debug(F100,"ttpkt turning on TANDEM","",0);
  6427.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  6428.  
  6429. #ifdef LPASS8                /* Can pass 8-bit data through? */
  6430. /* If the LPASS8 local mode is available, then flow control can always  */
  6431. /* be used, even if parity is none and we are transferring 8-bit data.  */
  6432. /* But we only need to do all this if Xon/Xoff is requested. */
  6433. /* BUT... this tends not to work through IP or LAT connections, terminal */
  6434. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  6435.     x = LPASS8;            /* If LPASS8 defined, then */
  6436.     debug(F100,"ttpkt executing LPASS8 code","",0);
  6437.     if (lmodef) {            /* TIOCLBIS must be too. */
  6438.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  6439.         if (x < 0) {
  6440.         debug(F100,"ttpkt TIOCLBIS error","",0);
  6441.         } else {
  6442.         lmodef++;
  6443.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  6444.         }
  6445.     }
  6446. /*
  6447.  But if we use LPASS8 mode, we must explicitly turn off
  6448.  terminal interrupts of all kinds.
  6449. */
  6450. #ifdef TIOCGETC                /* Not rawmode, */
  6451.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  6452.         tchnoi.t_intrc = -1;    /* interrupt character */
  6453.         tchnoi.t_quitc = -1;    /* and quit character. */
  6454.         tchnoi.t_startc = 17;    /* Make sure xon */
  6455.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6456. #ifndef NOBRKC
  6457.         tchnoi.t_eofc = -1;        /* eof character. */
  6458.         tchnoi.t_brkc = -1;        /* brk character. */
  6459. #endif /* NOBRKC */
  6460.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6461.         debug(F100,"ttpkt TIOCSETC failed","",0);
  6462.         } else {
  6463.         tcharf = 1;
  6464.         debug(F100,"ttpkt TIOCSETC ok","",0);
  6465.         }
  6466. #ifdef COMMENT
  6467. /* only for paranoid debugging */
  6468.         if (tcharf) {
  6469.         struct tchars foo;
  6470.         char tchbuf[100];
  6471.         ioctl(0,TIOCGETC,&foo);
  6472.         sprintf(tchbuf,
  6473.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  6474.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  6475.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  6476.         debug(F110,"ttpkt chars",tchbuf,0);
  6477.         }
  6478. #endif /* COMMENT */
  6479.     }
  6480.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  6481. #endif /* TIOCGETC */
  6482.  
  6483. /* Prevent suspend during packet mode */
  6484. #ifdef TIOCGLTC                /* Not rawmode, */
  6485.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  6486.         ltchnoi.t_suspc = -1;    /* suspend character */
  6487.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6488.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6489.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  6490.         } else {
  6491.         ltcharf = 1;
  6492.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  6493.         }
  6494.     }
  6495. #endif /* TIOCGLTC */
  6496.  
  6497. #else /* LPASS8 not defined */
  6498.  
  6499. /* Previously, BSD-based implementations always */
  6500. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  6501. /* This allows the flow control requested above to actually work, but only */
  6502. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  6503.  
  6504.     if (parity) {            /* If parity, */
  6505.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  6506. #ifdef COMMENT
  6507. /* WHY??? */
  6508.         if (xlocal)
  6509. #endif /* COMMENT */
  6510.           ttraw.sg_flags |= CBREAK;
  6511.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  6512. #ifdef TIOCGETC                /* Not rawmode, */
  6513.         if (tcharf && (xlocal == 0)) { /* must turn off */
  6514.         tchnoi.t_intrc = -1;    /* interrupt character */
  6515.         tchnoi.t_quitc = -1;    /* and quit character. */
  6516.         tchnoi.t_startc = 17;    /* Make sure xon */
  6517.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6518. #ifndef NOBRKC
  6519.         tchnoi.t_eofc = -1;    /* eof character. */
  6520.         tchnoi.t_brkc = -1;    /* brk character. */
  6521. #endif /* NOBRKC */
  6522.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6523.             debug(F100,"ttpkt TIOCSETC failed","",0);
  6524.         } else {
  6525.             tcharf = 1;
  6526.             debug(F100,"ttpkt TIOCSETC ok","",0);
  6527.         }
  6528.         }
  6529. #endif /* TIOCGETC */
  6530. #ifdef TIOCGLTC                /* Not rawmode, */
  6531. /* Prevent suspend during packet mode */
  6532.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  6533.         ltchnoi.t_suspc = -1;    /* suspend character */
  6534.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6535.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6536.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  6537.         } else {
  6538.             ltcharf = 1;
  6539.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  6540.         }
  6541.         }
  6542. #endif /* TIOCGLTC */
  6543.     } else {            /* If no parity, */
  6544.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  6545.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  6546.     }
  6547. #endif /* LPASS8 */
  6548.     } /* End of Xon/Xoff section */
  6549.  
  6550.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  6551. #ifdef LCASE
  6552.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  6553. #else
  6554.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  6555. #endif /* LCASE */
  6556.  
  6557. #ifdef TOWER1
  6558.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  6559. #endif /* TOWER1 */
  6560.  
  6561. #ifdef BELLV10
  6562.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  6563.       return(-1);
  6564. #else
  6565.     errno = 0;
  6566.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  6567.         debug(F101,"ttpkt stty failed","",errno);
  6568.         return(-1);
  6569.     }
  6570. #endif /* BELLV10 */
  6571.     debug(F100,"ttpkt stty ok","",0);
  6572.  
  6573. #ifdef sony_news
  6574.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  6575.     if (x != -1) {            /* Make sure we know original modes. */
  6576.     x &= ~KM_TTYPE;
  6577.     x |= KM_ASCII;
  6578.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  6579.         perror("ttpkt can't set ASCII mode");
  6580.         debug(F101,"ttpkt error setting ASCII mode","",x);
  6581.         return(-1);
  6582.     }
  6583.     }
  6584.     debug(F100,"ttpkt set ASCII mode ok","",0);
  6585. #endif /* sony_news */
  6586.  
  6587.     if (xlocal == 0) {            /* Turn this off so we can read */
  6588.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  6589.     sigint_ign = 1;
  6590.     }
  6591.     tvtflg = 0;                /* So ttvt() will work next time */
  6592.     debug(F100,"ttpkt success","",0);
  6593.     return(0);
  6594.  
  6595. #endif /* Not ATTSV or POSIX */
  6596.  
  6597. /* AT&T UNIX and POSIX */
  6598.  
  6599. #ifdef COHERENT
  6600. #define SVORPOSIX
  6601. #endif /* COHERENT */
  6602.  
  6603. #ifdef SVORPOSIX
  6604.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  6605.     ttraw.c_iflag |= (IXON|IXOFF);
  6606.     tthflow(flow, 0, &ttraw);
  6607.     } else if (flow == FLO_NONE) {    /* None */
  6608.     /* NOTE: We should also turn off hardware flow control here! */
  6609.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6610.     tthflow(flow, 0, &ttraw);
  6611.     } else if (flow == FLO_KEEP) {    /* Keep */
  6612.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6613.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6614.     /* NOTE: We should also handle hardware flow control here! */
  6615. #ifdef POSIX_CRTSCTS
  6616. /* In Linux case, we do this, which is unlikely to be portable */
  6617.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6618.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6619. #endif /* POSIX_CRTSCTS */
  6620.     } else if (flow == FLO_RTSC ||    /* Hardware */
  6621.            flow == FLO_DTRC ||
  6622.            flow == FLO_DTRT) {
  6623.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  6624.     tthflow(flow, 1, &ttraw);
  6625.     }
  6626.     ttraw.c_lflag &= ~(ICANON|ECHO);
  6627.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  6628.  
  6629. #ifndef OXOS
  6630. #ifdef QNX
  6631.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  6632. #endif /* QNX */
  6633. #ifndef COHERENT
  6634.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  6635. #endif /* COHERENT */
  6636. #else /* OXOS */
  6637.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  6638. #endif /* OXOS */
  6639.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  6640.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  6641. #ifdef ATTSV
  6642. #ifdef BSD44
  6643.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6644. #else
  6645.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6646. #endif /* BSD44 */
  6647. #else /* POSIX */
  6648.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6649. #endif /* ATTSV */
  6650.     ttraw.c_oflag &= ~OPOST;
  6651.     ttraw.c_cflag &= ~(CSIZE);
  6652.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  6653.  
  6654. #ifdef CSTOPB
  6655.     if (xlocal) {
  6656.     if (stopbits == 2) {
  6657.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6658.         debug(F100,"ttpkt 2 stopbits","",0);
  6659.     } else if (stopbits == 1) {
  6660.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6661.         debug(F100,"ttpkt 1 stopbit","",0);
  6662.     }
  6663.     }
  6664. #endif /* CSTOPB */
  6665.  
  6666. #ifdef HWPARITY
  6667.     if (hwparity && xlocal) {        /* Hardware parity */
  6668.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  6669. #ifdef COMMENT
  6670. /* Uncomment this only if needed -- I don't think it is */
  6671.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6672.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6673. #endif /* COMMENT */
  6674. #ifdef IGNPAR
  6675.     ttraw.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  6676.     debug(F100,"ttpkt IGNPAR","",0); /* that have parity errors */
  6677. #endif /* IGNPAR */
  6678.     switch (hwparity) {
  6679.       case 'e':            /* Even */
  6680.         ttraw.c_cflag &= ~(PARODD);
  6681.         debug(F100,"ttpkt 8 bits + even parity","",0);
  6682.         break;
  6683.       case 'o':            /* Odd */
  6684.         ttraw.c_cflag |= PARODD;
  6685.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  6686.         break;
  6687.       case 'm':            /* Mark */
  6688.       case 's':            /* Space */
  6689.         /* PAREXT is mentioned in SVID but the details are not given. */
  6690.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  6691.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  6692.         break;
  6693.     }
  6694.     } else {                /* We handle parity ourselves */
  6695. #endif /* HWPARITY */
  6696.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6697. #ifdef HWPARITY
  6698.     }
  6699. #endif /* HWPARITY */
  6700.  
  6701. #ifdef IX370
  6702.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  6703.     ttraw.c_cc[5] = 1;
  6704. #else
  6705. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  6706.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  6707. #else
  6708. #ifndef OXOS
  6709. #ifdef VMIN
  6710.     ttraw.c_cc[VMIN] = 1;
  6711. #endif /* VMIN */
  6712. #else /* OXOS */
  6713.     ttraw.c_min = 1;
  6714. #endif /* OXOS */
  6715. #endif /* VEOF */
  6716. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  6717.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  6718. #else
  6719. #ifndef OXOS
  6720. #ifdef VTIME
  6721.     ttraw.c_cc[VTIME] = 0;
  6722. #endif /* VTIME */
  6723. #else /* OXOS */
  6724.     ttraw.c_time = 0;
  6725. #endif /* OXOS */
  6726. #endif /* VEOL */
  6727. #endif /* IX370 */
  6728.  
  6729. #ifdef VINTR                /* Turn off interrupt character */
  6730.     if (xlocal == 0)            /* so ^C^C can break us out of */
  6731.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  6732. #endif /* VINTR */
  6733.  
  6734. #ifdef Plan9
  6735.     if (p9ttyparity('n') < 0)
  6736.     return -1;
  6737. #else
  6738. #ifdef BSD44ORPOSIX
  6739.     errno = 0;
  6740. #ifdef BEOSORBEBOX
  6741.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6742. #endif /* BEOSORBEBOX */
  6743.  
  6744. #define TESTING234
  6745. #ifdef TESTING234
  6746.     if (1) {
  6747.     debug(F100,"ttpkt TESTING234 rawmode","",0);
  6748.  
  6749.     /* iflags */
  6750.     ttraw.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  6751.     ttraw.c_iflag &= ~(INPCK|IGNPAR|IXON|IXOFF);
  6752.     ttraw.c_iflag |= IGNBRK;
  6753. #ifdef IMAXBEL
  6754.     ttraw.c_iflag &= ~IMAXBEL;
  6755. #endif    /* IMAXBEL */
  6756. #ifdef IXANY
  6757.     ttraw.c_iflag &= ~IXANY;
  6758. #endif    /* IXANY */
  6759. #ifdef IUCLC
  6760.     ttraw.c_iflag &= ~IUCLC;
  6761. #endif /* IUCLC */
  6762.  
  6763.     /* oflags */
  6764.     ttraw.c_oflag &= ~OPOST;
  6765. #ifdef OXTABS
  6766.     ttraw.c_oflag &= ~OXTABS;
  6767. #endif /* OXTABS */
  6768. #ifdef ONOCR
  6769.     ttraw.c_oflag &= ~ONOCR;
  6770. #endif /* ONOCR */
  6771. #ifdef ONLRET
  6772.     ttraw.c_oflag &= ~ONLRET;
  6773. #endif /* ONLRET */
  6774. #ifdef ONLCR
  6775.     ttraw.c_oflag &= ~ONLCR;
  6776. #endif /* ONLCR */
  6777.  
  6778.     /* lflags */
  6779.     ttraw.c_lflag &= ~ECHO;
  6780. #ifdef ECHOE
  6781.     ttraw.c_lflag &= ~ECHOE;
  6782. #endif /* ECHOE */
  6783. #ifdef ECHONL
  6784.     ttraw.c_lflag &= ~ECHONL;
  6785. #endif /* ECHONL */
  6786. #ifdef ECHOPRT
  6787.     ttraw.c_lflag &= ~ECHOPRT;
  6788. #endif /* ECHOPRT */
  6789. #ifdef ECHOKE
  6790.     ttraw.c_lflag &= ~ECHOKE;
  6791. #endif /* ECHOKE */
  6792. #ifdef ECHOCTL
  6793.     ttraw.c_lflag &= ~ECHOCTL;
  6794. #endif /* ECHOCTL */
  6795. #ifdef ALTWERASE
  6796.     ttraw.c_lflag &= ~ALTWERASE;
  6797. #endif /* ALTWERASE */
  6798. #ifdef EXTPROC
  6799.     ttraw.c_lflag &= ~EXTPROC;
  6800. #endif /* EXTPROC */
  6801.     ttraw.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  6802. #ifdef NOKERNINFO
  6803.     ttraw.c_lflag |= NOKERNINFO;
  6804. #endif    /* NOKERNINFO */
  6805.     /* ttraw.c_lflag |= NOFLSH; */
  6806.     ttraw.c_lflag &= ~NOFLSH;
  6807.  
  6808.     /* cflags */
  6809.     ttraw.c_cflag &= ~(CSIZE|PARENB|PARODD);
  6810.     ttraw.c_cflag |= CS8|CREAD;
  6811. #ifdef VMIN
  6812.     ttraw.c_cc[VMIN] = 1;        /* Supposedly needed for AIX */
  6813. #endif    /* VMIN */
  6814.  
  6815.     }
  6816. #endif /* TESTING234 */
  6817.  
  6818.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  6819.     x = tcsetattr(ttyfd,TCSADRAIN,&ttraw);
  6820.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr","",x);
  6821.     if (x < 0) {
  6822.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr errno","",errno);
  6823.         return(-1);
  6824.     }
  6825. #else /* BSD44ORPOSIX */
  6826.     x = ioctl(ttyfd,TCSETAW,&ttraw);
  6827.     debug(F101,"ttpkt ATTSV ioctl TCSETAW","",x);
  6828.     if (x < 0) {  /* set new modes . */
  6829.     debug(F101,"ttpkt ATTSV ioctl TCSETAW errno","",errno);
  6830.         return(-1);
  6831.     }
  6832. #endif /* BSD44ORPOSIX */
  6833. #endif /* Plan9 */
  6834.     tvtflg = 0;
  6835.     debug(F100,"ttpkt ok","",0);
  6836.     return(0);
  6837. #endif /* ATTSV */
  6838.  
  6839. #ifdef COHERENT
  6840. #undef SVORPOSIX
  6841. #endif /* COHERENT */
  6842.  
  6843. }
  6844.  
  6845. /*  T T S E T F L O W  --  Set flow control immediately.  */
  6846.  
  6847. #ifdef COHERENT
  6848. #define SVORPOSIX
  6849. #endif /* COHERENT */
  6850.  
  6851. int
  6852. ttsetflow(flow) int flow; {
  6853.     if (ttyfd < 0)            /* A channel must be open */
  6854.       return(-1);
  6855.  
  6856.     debug(F101,"ttsetflow flow","",flow);
  6857.  
  6858. #ifdef TN_COMPORT
  6859.     if (netconn && istncomport()) {
  6860.     debug(F101,"ttsetflow net modem","",ttmdm);
  6861.     return(tnsetflow(flow));
  6862.     }
  6863. #endif /* TN_COMPORT */
  6864. #ifdef NETCMD
  6865.     if (ttpipe) return(0);
  6866. #endif /* NETCMD */
  6867. #ifdef NETPTY
  6868.     if (ttpty) return(0);
  6869. #endif /* NETPTY */
  6870.  
  6871. #ifdef COMMENT
  6872.     /* This seems to hurt... */
  6873.     if (flow == FLO_KEEP)
  6874.       return(0);
  6875. #endif /* COMMENT */
  6876.  
  6877.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  6878.     flow == FLO_DTRC ||
  6879.     flow == FLO_DTRT) {
  6880.     tthflow(flow, 1, &ttraw);
  6881. #ifndef SVORPOSIX
  6882.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6883. #else
  6884.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6885. #endif /* SVORPOSIX */
  6886.  
  6887.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  6888.  
  6889. #ifndef SVORPOSIX
  6890.     ttraw.sg_flags |= TANDEM;
  6891. #else
  6892.     ttraw.c_iflag |= (IXON|IXOFF);
  6893. #endif /* SVORPOSIX */
  6894.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  6895.  
  6896.     } else if (flow == FLO_NONE) {    /* No flow control */
  6897.  
  6898. #ifndef SVORPOSIX
  6899.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6900. #else
  6901.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6902. #endif /* SVORPOSIX */
  6903.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  6904.     }
  6905.  
  6906. /* Set the new modes... */
  6907.  
  6908. #ifndef SVORPOSIX            /* BSD and friends */
  6909. #ifdef BELLV10
  6910.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  6911.       return(-1);
  6912. #else
  6913. #ifndef MINIX2
  6914.     if (stty(ttyfd,&ttraw) < 0)
  6915.       return(-1);
  6916. #endif /* MINIX2 */
  6917. #endif /* BELLV10 */
  6918. #else
  6919. #ifdef BSD44ORPOSIX            /* POSIX */
  6920.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  6921.       return(-1);
  6922. #else                    /* System V */
  6923.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  6924.       return(-1);
  6925. #endif /* BSD44ORPOSIX */
  6926. #endif /* SVORPOSIX */
  6927.     return(0);
  6928. }
  6929. #ifdef COHERENT
  6930. #undef SVORPOSIX
  6931. #endif /* COHERENT */
  6932.  
  6933. /*  T T V T -- Condition communication device for use as virtual terminal. */
  6934.  
  6935. int
  6936. #ifdef CK_ANSIC
  6937. ttvt(long speed, int flow)
  6938. #else
  6939. ttvt(speed,flow) long speed; int flow;
  6940. #endif /* CK_ANSIC */
  6941. /* ttvt */ {
  6942.     int s, s2, x;
  6943.  
  6944.     debug(F101,"ttvt ttyfd","",ttyfd);
  6945.     debug(F101,"ttvt tvtflg","",tvtflg);
  6946.     debug(F111,"ttvt speed",ckitoa(ttspeed),speed);
  6947.     debug(F111,"ttvt flow",ckitoa(ttflow),flow);
  6948.     debug(F111,"ttvt curcarr",ckitoa(ttcarr),curcarr);
  6949.  
  6950. /* Note: NetBSD and maybe other BSD44s have cfmakeraw() */
  6951. /* Maybe it would be simpler to use it... */
  6952.  
  6953.     ttpmsk = 0xff;
  6954. #ifdef NOLOCAL
  6955.     return(conbin((char)escchr));
  6956. #else
  6957.     if (ttyfd < 0) {            /* Not open. */
  6958.     if (ttchk() < 0)
  6959.       return(-1);
  6960.     else                /* But maybe something buffered. */
  6961.       return(0);
  6962.     }
  6963. #ifdef NETCMD
  6964.     if (ttpipe) return(0);
  6965. #endif /* NETCMD */
  6966. #ifdef NETPTY
  6967.     if (ttpty) return(0);
  6968. #endif /* NETPTY */
  6969. #ifdef NETCONN
  6970.     if (netconn) {
  6971. #ifdef TCPSOCKET
  6972. #ifdef TCP_NODELAY
  6973.         {
  6974.         extern int tcp_nodelay;
  6975.         if (ttnet == NET_TCPB) {
  6976.         if (nodelay_sav > -1) {
  6977.             no_delay(ttyfd,nodelay_sav);
  6978.             nodelay_sav = -1;
  6979.         }
  6980.         }
  6981.         }
  6982. #endif /* TCP_NODELAY */
  6983. #ifdef TN_COMPORT
  6984.         if (istncomport()) {
  6985.             int rc = -1;
  6986.             if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6987.                  /* && ttcarr == curcarr */ ) {
  6988.                 debug(F100,"ttvt modes already set, skipping...","",0);
  6989.                 return(0);            /* Already been called. */
  6990.             }
  6991.             if (flow != ttflow) {
  6992.                 if ((rc = tnsetflow(flow)) < 0)
  6993.           return(rc);
  6994.                 ttflow = flow;
  6995.             }
  6996.             if (speed != ttspeed) {
  6997.                 if (speed <= 0) 
  6998.           speed = tnc_get_baud();
  6999.                 else if ((rc = tnc_set_baud(speed)) < 0)
  7000.           return(rc);
  7001.                 ttspeed = speed;
  7002.             }
  7003.             tnc_set_datasize(8);
  7004.         tnc_set_stopsize(stopbits);
  7005.  
  7006. #ifdef HWPARITY
  7007.             if (hwparity) {
  7008.                 switch (hwparity) {
  7009.           case 'e':        /* Even */
  7010.                     debug(F100,"ttres 8 bits + even parity","",0);
  7011.                     tnc_set_parity(3);
  7012.                     break;
  7013.           case 'o':        /* Odd */
  7014.                     debug(F100,"ttres 8 bits + odd parity","",0);
  7015.                     tnc_set_parity(2);
  7016.                     break;
  7017.           case 'm':        /* Mark */
  7018.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  7019.                     tnc_set_parity(4);
  7020.                     break;
  7021.           case 's':        /* Space */
  7022.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  7023.                     tnc_set_parity(5);
  7024.                     break;
  7025.                 }
  7026.             } else
  7027. #endif /* HWPARITY */
  7028.             {
  7029.                 tnc_set_parity(1);    /* None */
  7030.             }
  7031.             tvtflg = 1;
  7032.             return(0);
  7033.         }
  7034. #endif /* TN_COMPORT */
  7035. #endif /* TCPSOCKET */
  7036.     tvtflg = 1;            /* Network connections... */
  7037.     debug(F100,"ttvt network connection, skipping...","",0);
  7038.     return(0);            /* ... require no special setup */
  7039.     }
  7040. #endif /* NETCONN */
  7041.  
  7042.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  7043.     /* && ttcarr == curcarr */ )
  7044.       {
  7045.       debug(F100,"ttvt modes already set, skipping...","",0);
  7046.       return(0);            /* Already been called. */
  7047.       }
  7048.  
  7049.     if (ttfdflg
  7050. #ifndef Plan9
  7051.     && !isatty(ttyfd)
  7052. #endif /* Plan9 */
  7053.     ) {
  7054.     debug(F100,"ttvt using external fd, skipping...","",0);
  7055.     return(0);
  7056.     }
  7057.  
  7058.     debug(F100,"ttvt setting modes...","",0);
  7059.  
  7060.     if (xlocal) {            /* For external lines... */
  7061.     s2 = (int) (speed / 10L);
  7062.     s = ttsspd(s2);            /* Check/set the speed */
  7063.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  7064.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  7065.     } else
  7066.       s = s2 = -1;
  7067.  
  7068. #ifdef COHERENT
  7069. #define SVORPOSIX
  7070. #endif /* COHERENT */
  7071.  
  7072. #ifndef SVORPOSIX
  7073.     /* Berkeley, V7, etc */
  7074.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  7075.     flow == FLO_DTRC ||
  7076.     flow == FLO_DTRT) {
  7077.     tthflow(flow, 1, &tttvt);
  7078.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  7079.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7080.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  7081.     debug(F100,"ttvt TANDEM on","",0);
  7082.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  7083.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7084.     } else if (flow == FLO_NONE) {
  7085.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  7086.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7087.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  7088.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  7089.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  7090.     debug(F100,"ttvt keeping original TANDEM","",0);
  7091.     tttvt.sg_flags &= ~TANDEM;
  7092.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  7093.     /* NOTE: We should also handle hardware flow control here! */
  7094.     }
  7095.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  7096. #ifdef TOWER1
  7097.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  7098. #else
  7099.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  7100. #endif /* TOWER1 */
  7101.  
  7102. #ifdef BELLV10
  7103.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  7104.       return(-1);
  7105. #else
  7106.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  7107.       return(-1);
  7108. #endif /* BELLV10 */
  7109.  
  7110. #else /* It is ATTSV or POSIX */
  7111.  
  7112.     if (flow == FLO_XONX) {        /* Software flow control */
  7113.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  7114.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7115.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  7116.     } else if (flow == FLO_NONE) {    /* NONE */
  7117.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  7118.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7119.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  7120.     } else if (flow == FLO_KEEP) {
  7121.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  7122.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  7123. #ifdef POSIX_CRTSCTS
  7124.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  7125.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  7126. #endif /* POSIX_CRTSCTS */
  7127.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  7128.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  7129.            flow == FLO_DTRC ||
  7130.            flow == FLO_DTRT) {
  7131.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  7132.     tthflow(flow, 1, &tttvt);
  7133.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  7134.     }
  7135. #ifndef OXOS
  7136. #ifdef COHERENT
  7137.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7138. #else
  7139.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  7140. #endif /* COHERENT */
  7141. #ifdef QNX
  7142.     /* Needed for hwfc */
  7143.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  7144.       tttvt.c_lflag |= IEXTEN;
  7145. #endif /* QNX */
  7146. #else /* OXOS */
  7147.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7148.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  7149. #endif /* OXOS */
  7150.  
  7151.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  7152.  
  7153. /* Stop bits */
  7154.  
  7155. #ifdef CSTOPB
  7156.     if (xlocal) {
  7157.     if (stopbits == 2) {
  7158.         tttvt.c_cflag |= CSTOPB;    /* 2 stop bits */
  7159.         debug(F100,"ttvt 2 stopbits","",0);
  7160.     } else if (stopbits == 1) {
  7161.         tttvt.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  7162.         debug(F100,"ttvt 1 stopbit","",0);
  7163.     }
  7164.     }
  7165. #endif /* CSTOPB */
  7166.  
  7167. /* Parity */
  7168.  
  7169. #ifdef HWPARITY
  7170.     if (hwparity && xlocal) {        /* Hardware parity */
  7171. #ifdef COMMENT
  7172. /* Uncomment this only if needed -- I don't think it is */
  7173.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  7174.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  7175. #endif /* COMMENT */
  7176. #ifdef IGNPAR
  7177.     debug(F101,"ttvt hwparity IGNPAR","",IGNPAR);
  7178.     tttvt.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  7179. #endif /* IGNPAR */
  7180.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  7181.  
  7182.     switch (hwparity) {
  7183.       case 'e':            /* Even */
  7184.         tttvt.c_cflag &= ~(PARODD);
  7185.         debug(F100,"ttvt 8 bits + even parity","",0);
  7186.         break;
  7187.       case 'o':            /* Odd */
  7188.         tttvt.c_cflag |= PARODD;
  7189.         debug(F100,"ttvt 8 bits + odd parity","",0);
  7190.         break;
  7191.       case 'm':            /* Mark */
  7192.       case 's':            /* Space */
  7193.         /* PAREXT is mentioned in SVID but the details are not given. */
  7194.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  7195.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  7196.         break;
  7197.     }
  7198.     } else {                /* We handle parity ourselves */
  7199. #endif /* HWPARITY */
  7200.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  7201. #ifdef HWPARITY
  7202.     }
  7203. #endif /* HWPARITY */
  7204.  
  7205. #ifdef ATTSV
  7206. #ifdef BSD44
  7207.     /* Things not to do... */
  7208.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  7209. #else
  7210.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  7211. #endif /* BSD44 */
  7212. #else /* POSIX */
  7213.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  7214. #endif /* ATTSV */
  7215.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  7216.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  7217.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  7218. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  7219.     tttvt.c_cc[4] = 1;
  7220. #else
  7221. #ifndef OXOS
  7222. #ifdef VMIN
  7223.     tttvt.c_cc[VMIN] = 1;
  7224. #endif /* VMIN */
  7225. #else /* OXOS */
  7226.     tttvt.c_min = 1;
  7227. #endif /* OXOS */
  7228. #endif /* VEOF */
  7229. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  7230.     tttvt.c_cc[5] = 0;
  7231. #else
  7232. #ifndef OXOS
  7233. #ifdef VTIME
  7234.     tttvt.c_cc[VTIME] = 0;
  7235. #endif /* VTIME */
  7236. #else /* OXOS */
  7237.     tttvt.c_time = 0;
  7238. #endif /* OXOS */
  7239. #endif /* VEOL */
  7240.  
  7241. #ifdef Plan9
  7242.     if (p9ttyparity('n') < 0)
  7243.       return -1;
  7244. #else
  7245. #ifdef BSD44ORPOSIX
  7246.     errno = 0;
  7247. #ifdef BEOSORBEBOX
  7248.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  7249. #endif /* BEOSORBEBOX */
  7250.  
  7251.     x = tcsetattr(ttyfd,TCSADRAIN,&tttvt);
  7252.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr","",x);
  7253.     if (x < 0) {
  7254.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr errno","",errno);
  7255.     return(-1);
  7256.     }
  7257. #else /* ATTSV */
  7258.     x = ioctl(ttyfd,TCSETAW,&tttvt);
  7259.     debug(F101,"ttvt ATTSV ioctl TCSETAW","",x);
  7260.     if (x < 0) {            /* set new modes . */
  7261.     debug(F101,"ttvt ATTSV ioctl TCSETAW errno","",errno);
  7262.     return(-1);    
  7263.     }
  7264. #endif /* BSD44ORPOSIX */
  7265. #endif /* Plan9 */
  7266. #endif /* ATTSV */
  7267.  
  7268.     ttspeed = speed;            /* Done, remember how we were */
  7269.     ttflow = flow;            /* called, so we can decide how to */
  7270.     tvtflg = 1;                /* respond next time. */
  7271.     debug(F100,"ttvt ok","",0);
  7272.     return(0);
  7273.  
  7274. #ifdef COHERENT
  7275. #undef SVORPOSIX
  7276. #endif /* COHERENT */
  7277.  
  7278. #endif /* NOLOCAL */
  7279. }
  7280.  
  7281. #ifndef NOLOCAL
  7282.  
  7283. /* Serial speed department . . . */
  7284.  
  7285. /*
  7286.   SCO OSR5.0.x might or might not support high speeds.  Sometimes they are not
  7287.   defined in the header files but they are supported (e.g. when building with
  7288.   UDK compiler rather than /bin/cc), sometimes vice versa.  Even though 5.0.4
  7289.   was the first release that came with high serial speeds standard, releases
  7290.   back to 5.0.0 could use them if certain patches (or "supplements") were
  7291.   applied to the SIO driver.  Plus a lot of SCO installations run third-party
  7292.   drivers.
  7293. */
  7294. #ifdef CK_SCOV5
  7295. #ifndef B38400
  7296. #define    B38400    0000017
  7297. #endif /* B38400 */
  7298. #ifndef B57600
  7299. #define    B57600    0000021
  7300. #endif /* B57600 */
  7301. #ifndef B76800
  7302. #define    B76800    0000022
  7303. #endif /* B76800 */
  7304. #ifndef B115200
  7305. #define    B115200    0000023
  7306. #endif /* B115200 */
  7307. #ifndef B230400
  7308. #define    B230400    0000024
  7309. #endif /* B230400 */
  7310. #ifndef B460800
  7311. #define    B460800    0000025
  7312. #endif /* B460800 */
  7313. #ifndef B921600
  7314. #define    B921600    0000026
  7315. #endif /* B921600 */
  7316. #endif /* CK_SCOV5 */
  7317. /*
  7318.   Plan 9's native speed setting interface lets you set anything you like,
  7319.   but will fail if the hardware doesn't like it, so we allow all the common
  7320.   speeds.
  7321. */
  7322. #ifdef Plan9
  7323. #ifndef B50
  7324. #define B50 50
  7325. #endif /* B50 */
  7326. #ifndef B75
  7327. #define B75 75
  7328. #endif /* B75 */
  7329. #ifndef B110
  7330. #define B110 110
  7331. #endif /* B110 */
  7332. #ifndef B134
  7333. #define B134 134
  7334. #endif /* B134 */
  7335. #ifndef B200
  7336. #define B200 200
  7337. #endif /* B200 */
  7338. #ifndef B300
  7339. #define B300 300
  7340. #endif /* B300 */
  7341. #ifndef B1200
  7342. #define B1200 1200
  7343. #endif /* B1200 */
  7344. #ifndef B1800
  7345. #define B1800 1800
  7346. #endif /* B1800 */
  7347. #ifndef B2400
  7348. #define B2400 2400
  7349. #endif /* B2400 */
  7350. #ifndef B4800
  7351. #define B4800 4800
  7352. #endif /* B4800 */
  7353. #ifndef B9600
  7354. #define B9600 9600
  7355. #endif /* B9600 */
  7356. #ifndef B14400
  7357. #define B14400 14400
  7358. #endif /* B14400 */
  7359. #ifndef B19200
  7360. #define B19200 19200
  7361. #endif /* B19200 */
  7362. #ifndef B28800
  7363. #define B28800 28800
  7364. #endif /* B28800 */
  7365. #ifndef B38400
  7366. #define B38400 38400
  7367. #endif /* B38400 */
  7368. #ifndef B57600
  7369. #define B57600 57600
  7370. #endif /* B57600 */
  7371. #ifndef B76800
  7372. #define B76800 76800
  7373. #endif /* B76800 */
  7374. #ifndef B115200
  7375. #define B115200 115200
  7376. #endif /* B115200 */
  7377. #ifndef B230400
  7378. #define B230400 230400
  7379. #endif /* B230400 */
  7380. #ifndef B460800
  7381. #define B460800 460800
  7382. #endif /* B460800 */
  7383. #ifndef B921600
  7384. #define B921600 921600
  7385. #endif /* B921600 */
  7386. #endif /* Plan9 */
  7387.  
  7388. /*  T T S S P D  --  Checks and sets transmission rate.  */
  7389.  
  7390. /*  Call with speed in characters (not bits!) per second. */
  7391. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  7392.  
  7393. #ifdef USETCSETSPEED
  7394. /*
  7395.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  7396.   to be used as a speed to be set, rather than forcing a choice from a
  7397.   predefined list.  It seems to be peculiar to UnixWare 7.
  7398.  
  7399.   These are the function codes to be passed to tc[gs]etspeed(),
  7400.   but for some reason they don't seem to be picked up from termios.h.
  7401. */
  7402. #ifndef TCS_ALL
  7403. #define TCS_ALL 0
  7404. #endif /* TCS_ALL */
  7405. #ifndef TCS_IN
  7406. #define TCS_IN 1
  7407. #endif /* TCS_IN */
  7408. #ifndef TCS_OUT
  7409. #define TCS_OUT 2
  7410. #endif /* TCS_OUT */
  7411. #endif /* USETCSETSPEED */
  7412.  
  7413. int
  7414. ttsspd(cps) int cps; {
  7415.     int x;
  7416. #ifdef POSIX
  7417. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  7418.     speed_t
  7419. #else
  7420.     int
  7421. #endif /* POSIX */
  7422.       s, s2;
  7423.     int ok = 1;                /* Speed check result, assume ok */
  7424.  
  7425. #ifdef OLINUXHISPEED
  7426.     unsigned int spd_flags = 0;
  7427.     struct serial_struct serinfo;
  7428. #endif /* OLINUXHISPEED */
  7429.  
  7430.     debug(F101,"ttsspd cps","",cps);
  7431.     debug(F101,"ttsspd ttyfd","",ttyfd);
  7432.     debug(F101,"ttsspd xlocal","",xlocal);
  7433.  
  7434.     if (ttyfd < 0 || xlocal == 0)    /* Don't set speed on console */
  7435.       return(0);
  7436.  
  7437. #ifdef    NETCONN
  7438.     if (netconn) {
  7439. #ifdef TN_COMPORT
  7440.         if (istncomport())
  7441.       return(tnc_set_baud(cps * 10));
  7442.         else
  7443. #endif /* TN_COMPORT */
  7444.     return(0);
  7445.   }
  7446. #endif    /* NETCONN */
  7447. #ifdef NETCMD
  7448.     if (ttpipe) return(0);
  7449. #endif /* NETCMD */
  7450. #ifdef NETPTY
  7451.     if (ttpty) return(0);
  7452. #endif /* NETPTY */
  7453.  
  7454.     if (cps < 0) return(-1);
  7455.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  7456.  
  7457. #ifdef USETCSETSPEED
  7458.  
  7459.     s = cps * 10L;
  7460.  
  7461.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7462.     debug(F101,"ttsspd tcgetattr","",x);
  7463.     if (x < 0)
  7464.       return(-1);
  7465.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  7466.  
  7467.     errno = 0;
  7468.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7469.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  7470.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  7471.     } else
  7472.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  7473. #ifdef DEBUG
  7474.     if (errno & deblog) {
  7475.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  7476.     }
  7477. #endif /* DEBUG */
  7478.  
  7479. #ifdef COMMENT
  7480.     tcsetspeed(TCS_ALL, &ttraw, s);
  7481.     tcsetspeed(TCS_ALL, &tttvt, s);
  7482.     tcsetspeed(TCS_ALL, &ttold, s);
  7483. #else
  7484.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7485.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  7486.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  7487.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  7488.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  7489.     tcsetspeed(TCS_IN, &ttold, 1200L);
  7490.     tcsetspeed(TCS_OUT, &ttold, 75L);
  7491.     } else {
  7492.     tcsetspeed(TCS_ALL, &ttraw, s);
  7493.     tcsetspeed(TCS_ALL, &tttvt, s);
  7494.     tcsetspeed(TCS_ALL, &ttold, s);
  7495.     }
  7496. #endif /* COMMENT */
  7497.  
  7498.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  7499.     debug(F101,"ttsspd tcsetattr","",x);
  7500.     if (x < 0)
  7501.       return(-1);
  7502.  
  7503. #else  /* Not USETCSETSPEED */
  7504.  
  7505.     /* First check that the given speed is valid. */
  7506.  
  7507.     switch (cps) {
  7508. #ifndef MINIX
  7509.       case 0:   s = B0;    break;
  7510.       case 5:   s = B50;   break;
  7511.       case 7:   s = B75;   break;
  7512. #endif /* MINIX */
  7513.       case 11:  s = B110;  break;
  7514. #ifndef MINIX
  7515.       case 13:  s = B134;  break;
  7516.       case 15:  s = B150;  break;
  7517.       case 20:  s = B200;  break;
  7518. #endif /* MINIX */
  7519.       case 30:  s = B300;  break;
  7520. #ifndef MINIX
  7521.       case 60:  s = B600;  break;
  7522. #endif /* MINIX */
  7523.       case 120: s = B1200; break;
  7524. #ifndef MINIX
  7525.       case 180: s = B1800; break;
  7526. #endif /* MINIX */
  7527.       case 240: s = B2400; break;
  7528.       case 480: s = B4800; break;
  7529. #ifndef MINIX
  7530.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  7531. #endif /* MINIX */
  7532. #ifdef B7200
  7533.       case 720: s = B7200; break;
  7534. #endif /* B7200 */
  7535.       case 960: s = B9600; break;
  7536. #ifdef B14400
  7537.       case 1440: s = B14400; break;
  7538. #endif /* B14400 */
  7539. #ifdef B19200
  7540.       case 1920: s = B19200; break;
  7541. #else
  7542. #ifdef EXTA
  7543.       case 1920: s = EXTA; break;
  7544. #endif /* EXTA */
  7545. #endif /* B19200 */
  7546. #ifdef B28800
  7547.       case 2880: s = B28800; break;
  7548. #endif /* B28800 */
  7549. #ifdef B38400
  7550.       case 3840: s = B38400;
  7551. #ifdef OLINUXHISPEED
  7552.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  7553. #endif /* OLINUXHISPEED */
  7554.     break;
  7555. #else /* B38400 not defined... */
  7556. #ifdef EXTB
  7557.       case 3840: s = EXTB; break;
  7558. #endif /* EXTB */
  7559. #endif /* B38400 */
  7560.  
  7561. #ifdef HPUX
  7562. #ifdef _B57600
  7563.       case 5760: s = _B57600; break;
  7564. #endif /* _B57600 */
  7565. #ifdef _B115200
  7566.       case 11520: s = _B115200; break;
  7567. #endif /* _B115200 */
  7568. #else
  7569. #ifdef OLINUXHISPEED
  7570. /*
  7571.   This bit from <carlo@sg.tn.tudelft.nl>:
  7572.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  7573.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  7574.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  7575.   want to mess up the speed flags when someone is doing sophisticated stuff
  7576.   like custom speeds..."
  7577. */
  7578.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  7579.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  7580. #else
  7581. #ifdef B57600
  7582.       case 5760: s = B57600; break;
  7583. #endif /* B57600 */
  7584. #ifdef B76800
  7585.       case 7680: s = B76800; break;
  7586. #endif /* B76800 */
  7587. #ifdef B115200
  7588.       case 11520: s = B115200; break;
  7589. #endif /* B115200 */
  7590. #endif /* OLINUXHISPEED */
  7591. #ifdef B153600
  7592.       case 15360: s = B153600; break;
  7593. #endif /* B153600 */
  7594. #ifdef B230400
  7595.       case 23040: s = B230400; break;
  7596. #endif /* B230400 */
  7597. #ifdef B307200
  7598.       case 30720: s = B307200; break;
  7599. #endif /* B307200 */
  7600. #ifdef B460800
  7601.       case 46080: s = B460800; break;
  7602. #endif /* 460800 */
  7603. #ifdef B921600
  7604.       case 92160: s = B921600; break;
  7605. #endif /* B921600 */
  7606. #endif /* HPUX */
  7607.       default:
  7608.     ok = 0;                /* Good speed not found, so not ok */
  7609.     break;
  7610.     }
  7611.     debug(F101,"ttsspd ok","",ok);
  7612.     debug(F101,"ttsspd s","",s);
  7613.  
  7614.     if (!ok) {
  7615.     debug(F100,"ttsspd fails","",0);
  7616.     return(-1);
  7617.     } else {
  7618.     if (!s2) s2 = s;        /* Set input speed */
  7619. #ifdef Plan9
  7620.     if (p9ttsspd(cps) < 0)
  7621.       return(-1);
  7622. #else
  7623. #ifdef BSD44ORPOSIX
  7624.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7625.     debug(F101,"ttsspd tcgetattr","",x);
  7626.     if (x < 0)
  7627.       return(-1);
  7628. #ifdef OLINUXHISPEED
  7629.     debug(F101,"ttsspd spd_flags","",spd_flags);
  7630.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  7631.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  7632.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  7633.         return(-1);
  7634.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  7635.         serinfo.flags &= ~ASYNC_SPD_MASK;
  7636.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  7637.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  7638.           return(-1);
  7639.     }
  7640. #endif /* OLINUXHISPEED */
  7641.     cfsetospeed(&ttcur,s);
  7642.     cfsetispeed(&ttcur,s2);
  7643.     cfsetospeed(&ttraw,s);
  7644.     cfsetispeed(&ttraw,s2);
  7645.     cfsetospeed(&tttvt,s);
  7646.     cfsetispeed(&tttvt,s2);
  7647.     cfsetospeed(&ttold,s);
  7648.     cfsetispeed(&ttold,s2);
  7649.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  7650.     debug(F101,"ttsspd tcsetattr","",x);
  7651.     if (x < 0) return(-1);
  7652. #else
  7653. #ifdef ATTSV
  7654.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  7655.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7656.     debug(F101,"ttsspd TCGETA ioctl","",x);
  7657.     if (x < 0) return(-1);
  7658.     ttcur.c_cflag &= ~CBAUD;
  7659.     ttcur.c_cflag |= s;
  7660.     tttvt.c_cflag &= ~CBAUD;
  7661.     tttvt.c_cflag |= s;
  7662.     ttraw.c_cflag &= ~CBAUD;
  7663.     ttraw.c_cflag |= s;
  7664.     ttold.c_cflag &= ~CBAUD;
  7665.     ttold.c_cflag |= s;
  7666.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  7667.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  7668.     if (x < 0) return(-1);
  7669. #else
  7670. #ifdef BELLV10
  7671.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7672.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  7673.     if (x < 0) return(-1);
  7674.     tdcur.ispeed = s2;
  7675.     tdcur.ospeed = s;
  7676.     errno = 0;
  7677.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  7678.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  7679.     if (ok < 0) {
  7680.         perror(ttnmsv);
  7681.         debug(F101,"ttsspd BELLV10 errno","",ok);
  7682.         return(-1);
  7683.     }
  7684. #else
  7685.     x = gtty(ttyfd,&ttcur);
  7686.     debug(F101,"ttsspd gtty","",x);
  7687.     if (x < 0) return(-1);
  7688.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  7689.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  7690.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  7691.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  7692.     x = stty(ttyfd,&ttcur);
  7693.     debug(F101,"ttsspd stty","",x);
  7694.     if (x < 0) return(-1);
  7695. #endif /* BELLV10 */
  7696. #endif /* ATTSV */
  7697. #endif /* BSD44ORPOSIX */
  7698. #endif /* Plan9 */
  7699.     }
  7700.     return(1);                /* Return 1 = success. */
  7701. #endif /* USETCSETSPEED */
  7702. }
  7703.  
  7704. #endif /* NOLOCAL */
  7705.  
  7706. /* C O N G S P D  -  Get speed of console terminal  */
  7707.  
  7708. long
  7709. congspd() {
  7710. /*
  7711.   This is a disgusting hack.  The right way to do this would be to pass an
  7712.   argument to ttgspd(), but then we'd need to change the Kermit API and
  7713.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  7714. */
  7715.     int t1;
  7716.     long spd;
  7717. #ifdef NETCONN
  7718.     int t2 = netconn;
  7719.     netconn = 0;
  7720. #endif /* NETCONN */
  7721.     t1 = ttyfd;
  7722.     ttyfd = -1;
  7723.     spd = ttgspd();
  7724.     debug(F101,"congspd","",spd);
  7725. #ifdef NETCONN
  7726.     netconn = t2;
  7727. #endif /* NETCONN */
  7728.     ttyfd = t1;
  7729.     return(spd);
  7730. }
  7731.  
  7732. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  7733.  
  7734. #define NSPDLIST 64
  7735. static long spdlist[NSPDLIST];
  7736. /*
  7737.   As written, this picks up the speeds known at compile time, and thus
  7738.   apply to the system where C-Kermit was built, rather than to the one where
  7739.   it is running.  Suggestions for improvement are always welcome.
  7740. */
  7741. long *
  7742. ttspdlist() {
  7743.     int i;
  7744.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  7745.       spdlist[i] = -1L;
  7746.     i = 1;
  7747.  
  7748. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  7749.     debug(F100,"ttspdlist USETCSETSPEED","",0);
  7750.     spdlist[i++] = 50L;
  7751. #ifndef UW7
  7752.     spdlist[i++] = 75L;
  7753. #endif /* UW7 */
  7754.     spdlist[i++] = 110L;
  7755. #ifndef UW7
  7756.     spdlist[i++] = 134L;
  7757. #endif /* UW7 */
  7758.     spdlist[i++] = 150L;
  7759.     spdlist[i++] = 200L;
  7760.     spdlist[i++] = 300L;
  7761.     spdlist[i++] = 600L;
  7762.     spdlist[i++] = 1200L;
  7763.     spdlist[i++] = 1800L;
  7764.     spdlist[i++] = 2400L;
  7765.     spdlist[i++] = 4800L;
  7766.     spdlist[i++] = 8880L;
  7767.     spdlist[i++] = 9600L;
  7768.     spdlist[i++] = 14400L;
  7769.     spdlist[i++] = 19200L;
  7770.     spdlist[i++] = 28800L;
  7771. #ifndef UW7
  7772.     spdlist[i++] = 33600L;
  7773. #endif /* UW7 */
  7774.     spdlist[i++] = 38400L;
  7775.     spdlist[i++] = 57600L;
  7776.     spdlist[i++] = 76800L;
  7777.     spdlist[i++] = 115200L;
  7778. #ifndef UW7
  7779.     spdlist[i++] = 153600L;
  7780.     spdlist[i++] = 230400L;
  7781.     spdlist[i++] = 307200L;
  7782.     spdlist[i++] = 460800L;
  7783.     spdlist[i++] = 921600L;
  7784. #endif /* UW7 */
  7785.  
  7786. #else  /* USETCSETSPEED */
  7787.  
  7788.     debug(F100,"ttspdlist no USETCSETSPEED","",0);
  7789.  
  7790. #ifdef B50
  7791.     debug(F101,"ttspdlist B50","",B50);
  7792.     spdlist[i++] = 50L;
  7793. #endif /* B50 */
  7794. #ifdef B75
  7795.     debug(F101,"ttspdlist B75","",B75);
  7796.     spdlist[i++] = 75L;
  7797. #endif /* B75 */
  7798. #ifdef B110
  7799.     debug(F101,"ttspdlist B110","",B110);
  7800.     spdlist[i++] = 110L;
  7801. #endif /* B110 */
  7802. #ifdef B134
  7803.     debug(F101,"ttspdlist B134","",B134);
  7804.     spdlist[i++] = 134L;
  7805. #endif /* B134 */
  7806. #ifdef B150
  7807.     debug(F101,"ttspdlist B150","",B150);
  7808.     spdlist[i++] = 150L;
  7809. #endif /* B150 */
  7810. #ifdef B200
  7811.     debug(F101,"ttspdlist B200","",B200);
  7812.     spdlist[i++] = 200L;
  7813. #endif /* B200 */
  7814. #ifdef B300
  7815.     debug(F101,"ttspdlist B300","",B300);
  7816.     spdlist[i++] = 300L;
  7817. #endif /* B300 */
  7818. #ifdef B600
  7819.     debug(F101,"ttspdlist B600","",B600);
  7820.     spdlist[i++] = 600L;
  7821. #endif /* B600 */
  7822. #ifdef B1200
  7823.     debug(F101,"ttspdlist B1200","",B1200);
  7824.     spdlist[i++] = 1200L;
  7825. #endif /* B1200 */
  7826. #ifdef B1800
  7827.     debug(F101,"ttspdlist B1800","",B1800);
  7828.     spdlist[i++] = 1800L;
  7829. #endif /* B1800 */
  7830. #ifdef B2400
  7831.     debug(F101,"ttspdlist B2400","",B2400);
  7832.     spdlist[i++] = 2400L;
  7833. #endif /* B2400 */
  7834. #ifdef B4800
  7835.     debug(F101,"ttspdlist B4800","",B4800);
  7836.     spdlist[i++] = 4800L;
  7837. #endif /* B4800 */
  7838. #ifdef B9600
  7839.     debug(F101,"ttspdlist B9600","",B9600);
  7840.     spdlist[i++] = 9600L;
  7841. #endif /* B9600 */
  7842. #ifdef B14400
  7843.     debug(F101,"ttspdlist B14400","",B14400);
  7844.     spdlist[i++] = 14400L;
  7845. #endif /* B14400 */
  7846. #ifdef B19200
  7847.     debug(F101,"ttspdlist B19200","",B19200);
  7848.     spdlist[i++] = 19200L;
  7849. #else
  7850. #ifdef EXTA
  7851.     debug(F101,"ttspdlist EXTA","",EXTA);
  7852.     spdlist[i++] = 19200L;
  7853. #endif /* EXTA */
  7854. #endif /* B19200 */
  7855. #ifdef B28800
  7856.     debug(F101,"ttspdlist B28800","",B28800);
  7857.     spdlist[i++] = 28800L;
  7858. #endif /* B28800 */
  7859. #ifdef B33600
  7860.     debug(F101,"ttspdlist B33600","",B33600);
  7861.     spdlist[i++] = 33600L;
  7862. #endif /* B33600 */
  7863. #ifdef B38400
  7864.     debug(F101,"ttspdlist B38400","",B38400);
  7865.     spdlist[i++] = 38400L;
  7866. #else
  7867. #ifdef EXTB
  7868.     debug(F101,"ttspdlist EXTB","",EXTB);
  7869.     spdlist[i++] = 38400L;
  7870. #endif /* EXTB */
  7871. #endif /* B38400 */
  7872. #ifdef _B57600
  7873.     debug(F101,"ttspdlist _B57600","",_B57600);
  7874.     spdlist[i++] = 57600L;
  7875. #else
  7876. #ifdef B57600
  7877.     debug(F101,"ttspdlist B57600","",B57600);
  7878.     spdlist[i++] = 57600L;
  7879. #endif /* B57600 */
  7880. #endif /* _B57600 */
  7881. #ifdef B76800
  7882.     debug(F101,"ttspdlist B76800","",B76800);
  7883.     spdlist[i++] = 76800L;
  7884. #endif /* B76800 */
  7885. #ifdef _B115200
  7886.     debug(F101,"ttspdlist _B115200","",_B115200);
  7887.     spdlist[i++] = 115200L;
  7888. #else
  7889. #ifdef B115200
  7890.     debug(F101,"ttspdlist B115200","",B115200);
  7891.     spdlist[i++] = 115200L;
  7892. #endif /* B115200 */
  7893. #endif /* _B115200 */
  7894. #ifdef B153600
  7895.     debug(F101,"ttspdlist B153600","",B153600);
  7896.     spdlist[i++] = 153600L;
  7897. #endif /* B153600 */
  7898. #ifdef B230400
  7899.     debug(F101,"ttspdlist B230400","",B230400);
  7900.     spdlist[i++] = 230400L;
  7901. #endif /* B230400 */
  7902. #ifdef B307200
  7903.     debug(F101,"ttspdlist B307200","",B307200);
  7904.     spdlist[i++] = 307200L;
  7905. #endif /* B307200 */
  7906. #ifdef B460800
  7907.     debug(F101,"ttspdlist B460800","",B460800);
  7908.     spdlist[i++] = 460800L;
  7909. #endif /* B460800 */
  7910. #ifdef B921600
  7911.     debug(F101,"ttspdlist B921600","",B921600);
  7912.     spdlist[i++] = 921600L;
  7913. #endif /* B921600 */
  7914. #endif /* USETCSETSPEED */
  7915.     spdlist[0] = i - 1;            /* Return count in 0th element */
  7916.     debug(F111,"ttspdlist spdlist","0",spdlist[0]);
  7917.     return((long *)spdlist);
  7918. }
  7919.  
  7920. /* T T G S P D  -  Get speed of currently selected tty line  */
  7921.  
  7922. /*
  7923.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  7924.   the real speed.  On some systems, it returns the line's nominal speed, from
  7925.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  7926.   not notice.
  7927. */
  7928. long
  7929. ttgspd() {                /* Get current serial device speed */
  7930. #ifdef NOLOCAL
  7931.     return(-1L);
  7932. #else
  7933. #ifdef POSIX
  7934.     speed_t                /* Should be unsigned */
  7935. #else
  7936.     int                    /* Isn't unsigned */
  7937. #endif /* POSIX */
  7938.       s;
  7939.     int x;
  7940.     long ss;
  7941. #ifdef OLINUXHISPEED
  7942.     unsigned int spd_flags = 0;
  7943.     struct serial_struct serinfo;
  7944. #endif /* OLINUXHISPEED */
  7945.  
  7946. #ifdef NETCONN
  7947.     if (netconn) {
  7948. #ifdef TN_COMPORT
  7949.     if (istncomport())
  7950.       return(tnc_get_baud());
  7951.     else
  7952. #endif /* TN_COMPORT */
  7953.       return(-1);            /* -1 if network connection */
  7954.     }
  7955. #endif /* NETCONN */
  7956. #ifdef NETCMD
  7957.     if (ttpipe) return(-1);
  7958. #endif /* NETCMD */
  7959. #ifdef NETPTY
  7960.     if (ttpty) return(-1);
  7961. #endif /* NETPTY */
  7962.  
  7963.     debug(F101,"ttgspd ttyfd","",ttyfd);
  7964.  
  7965. #ifdef USETCSETSPEED
  7966.  
  7967.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7968.     debug(F101,"ttgspd tcgetattr","",x);
  7969.     if (x < 0)
  7970.       return(-1);
  7971.     errno = 0;
  7972.     s = tcgetspeed(TCS_ALL, &ttcur);
  7973.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  7974.     if (s == 0) {
  7975.     long s1, s2;
  7976.     s1 = tcgetspeed(TCS_IN, &ttcur);
  7977.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  7978.     if (s1 == 1200L && s2 == 75L)
  7979.       return(8880L);
  7980.     }
  7981. #ifdef DEBUG
  7982.     if (errno & deblog) {
  7983.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  7984.     }
  7985. #endif /* DEBUG */
  7986.     return(s);
  7987.  
  7988. #else  /* Not USETCSETSPEED */
  7989.  
  7990. #ifdef Plan9
  7991.     if (ttyfd < 0)
  7992.       ss = -1;
  7993.     else
  7994.       ss = ttylastspeed;
  7995. #else
  7996. #ifdef OLINUXHISPEED
  7997.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  7998. #endif /* OLINUXHISPEED */
  7999.  
  8000.     if (ttyfd < 0) {
  8001. #ifdef BSD44ORPOSIX
  8002.     s = cfgetospeed(&ccold);
  8003.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  8004. #else
  8005. #ifdef ATTSV
  8006.     s = ccold.c_cflag & CBAUD;
  8007.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  8008. #else
  8009.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  8010.     debug(F101,"ttgspd sg_ospeed 1","",s);
  8011. #endif /* ATTSV */
  8012. #endif /* BSD44POSIX */
  8013.  
  8014.     } else {
  8015. #ifdef BSD44ORPOSIX
  8016.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  8017.     s = cfgetospeed(&ttcur);
  8018.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  8019. #ifdef OLINUXHISPEED
  8020.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  8021.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  8022.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8023. #endif /* OLINUXHISPEED */
  8024. #else
  8025. #ifdef ATTSV
  8026.     x = ioctl(ttyfd,TCGETA,&ttcur);
  8027.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  8028.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  8029.     if (x < 0) return(-1);
  8030.     s = ttcur.c_cflag & CBAUD;
  8031.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  8032. #else
  8033. #ifdef BELLV10
  8034.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  8035.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  8036.     if (x < 0) return(-1);
  8037.     s = tdcur.ospeed;
  8038.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  8039. #else
  8040.     x = gtty(ttyfd,&ttcur);
  8041.     debug(F101,"ttgspd gtty 2 x","",x);
  8042.     debug(F101,"ttgspd gtty 2 errno","",errno);
  8043.     if (x < 0) return(-1);
  8044.     s = ttcur.sg_ospeed;
  8045.     debug(F101,"ttgspd gtty 2 speed","",s);
  8046. #endif /* BELLV10 */
  8047. #endif /* ATTSV */
  8048. #endif /* BSD44ORPOSIX */
  8049.     }
  8050.     debug(F101,"ttgspd code","",s);
  8051. #ifdef OLINUXHISPEED
  8052.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8053. #endif /* OLINUXHISPEED */
  8054.     switch (s) {
  8055. #ifdef B0
  8056.       case B0:    ss = 0L; break;
  8057. #endif /* B0 */
  8058.  
  8059. #ifndef MINIX
  8060. /*
  8061.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  8062.  etc, making for many "duplicate case in switch" errors, which are fatal.
  8063. */
  8064. #ifdef B50
  8065.       case B50:   ss = 50L; break;
  8066. #endif /* B50 */
  8067. #ifdef B75
  8068.       case B75:   ss = 75L; break;
  8069. #endif /* B75 */
  8070. #endif /* MINIX */
  8071.  
  8072. #ifdef B110
  8073.       case B110:  ss = 110L; break;
  8074. #endif /* B110 */
  8075.  
  8076. #ifndef MINIX
  8077. #ifdef B134
  8078.       case B134:  ss = 134L; break;
  8079. #endif /* B134 */
  8080. #ifdef B150
  8081.       case B150:  ss = 150L; break;
  8082. #endif /* B150 */
  8083. #endif /* MINIX */
  8084.  
  8085. #ifdef B200
  8086.       case B200:  ss = 200L; break;
  8087. #endif /* B200 */
  8088.  
  8089. #ifdef B300
  8090.       case B300:  ss = 300L; break;
  8091. #endif /* B300 */
  8092.  
  8093. #ifdef B600
  8094.       case B600:  ss = 600L; break;
  8095. #endif /* B600 */
  8096.  
  8097. #ifdef B1200
  8098.       case B1200: ss = 1200L; break;
  8099. #endif /* B1200 */
  8100.  
  8101. #ifdef B1800
  8102.       case B1800: ss = 1800L; break;
  8103. #endif /* B1800 */
  8104.  
  8105. #ifdef B2400
  8106.       case B2400: ss = 2400L; break;
  8107. #endif /* B2400 */
  8108.  
  8109. #ifdef B4800
  8110.       case B4800: ss = 4800L; break;
  8111. #endif /* B4800 */
  8112.  
  8113. #ifdef B7200
  8114.       case B7200: ss = 7200L; break;
  8115. #endif /* B7200 */
  8116.  
  8117. #ifdef B9600
  8118.       case B9600: ss = 9600L; break;
  8119. #endif /* B9600 */
  8120.  
  8121. #ifdef B19200
  8122.       case B19200: ss = 19200L; break;
  8123. #else
  8124. #ifdef EXTA
  8125.       case EXTA: ss = 19200L; break;
  8126. #endif /* EXTA */
  8127. #endif /* B19200 */
  8128.  
  8129. #ifndef MINIX
  8130. #ifdef B38400
  8131.       case B38400:
  8132.         ss = 38400L;
  8133. #ifdef OLINUXHISPEED
  8134.         switch(spd_flags) {
  8135.           case ASYNC_SPD_HI:  ss =  57600L; break;
  8136.           case ASYNC_SPD_VHI: ss = 115200L; break;
  8137.     }
  8138. #endif /* OLINUXHISPEED */
  8139.         break;
  8140. #else
  8141. #ifdef EXTB
  8142.       case EXTB: ss = 38400L; break;
  8143. #endif /* EXTB */
  8144. #endif /* B38400 */
  8145. #endif /* MINIX */
  8146.  
  8147. #ifdef HPUX
  8148. #ifdef _B57600
  8149.       case _B57600: ss = 57600L; break;
  8150. #endif /* _B57600 */
  8151. #ifdef _B115200
  8152.       case _B115200: ss = 115200L; break;
  8153. #endif /* _B115200 */
  8154. #else
  8155. #ifdef B57600
  8156.       case B57600: ss = 57600L; break;
  8157. #endif /* B57600 */
  8158. #ifdef B76800
  8159.       case B76800: ss = 76800L; break;
  8160. #endif /* B76800 */
  8161. #ifdef B115200
  8162.       case B115200: ss = 115200L; break;
  8163. #endif /* B115200 */
  8164. #ifdef B153600
  8165.       case B153600: ss = 153600L; break;
  8166. #endif /* B153600 */
  8167. #ifdef B230400
  8168.       case B230400: ss = 230400L; break;
  8169. #endif /* B230400 */
  8170. #ifdef B307200
  8171.       case B307200: ss = 307200L; break;
  8172. #endif /* B307200 */
  8173. #ifdef B460800
  8174.       case B460800: ss = 460800L; break;
  8175. #endif /* B460800 */
  8176. #endif /* HPUX */
  8177. #ifdef B921600
  8178.       case B921600: ss = 921600L; break;
  8179. #endif /* B921600 */
  8180.       default:
  8181.     ss = -1; break;
  8182.     }
  8183. #endif /* Plan9 */
  8184.     debug(F101,"ttgspd speed","",ss);
  8185.     return(ss);
  8186.  
  8187. #endif /* USETCSETSPEED */
  8188. #endif /* NOLOCAL */
  8189. }
  8190. #ifdef MINIX2                /* Another hack alert */
  8191. #define MINIX
  8192. #endif /* MINIX2 */
  8193.  
  8194. /*
  8195.   FIONREAD data type...  This has been defined as "long" for many, many
  8196.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  8197.   int for 64-bit platforms, but keep long for the others.  If we changed
  8198.   the default PEEKTYPE to int, this would probably break 16-bit builds
  8199.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  8200.   of which we have no way of testing any more.  Therefore, do not change
  8201.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  8202. */
  8203. #ifdef COHERENT
  8204. #ifdef FIONREAD
  8205. #undef FIONREAD
  8206. #endif /* FIONREAD */
  8207. /* #define FIONREAD TIOCQUERY */
  8208. /* #define PEEKTYPE int */
  8209. #else  /* Not COHERENT... */
  8210.  
  8211. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  8212. #define PEEKTYPE int
  8213. #else
  8214. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  8215. #endif /* OSF32 */
  8216. #endif /* COHERENT */
  8217.  
  8218. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  8219.  
  8220. #ifdef MYREAD
  8221.  
  8222. /* Private buffer for myread() and its companions.  Not for use by anything
  8223.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  8224.  * allowed to read my_count.
  8225.  *
  8226.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  8227.  *
  8228.  * A global parity mask variable could be useful too.  We could use it to
  8229.  * let myread() strip the parity on its own, instead of stripping sign
  8230.  * bits as it does now.
  8231.  */
  8232. #ifdef BIGBUFOK
  8233. #define MYBUFLEN 32768
  8234. #else
  8235. #ifdef pdp11
  8236. #define MYBUFLEN 256
  8237. #else
  8238. #define MYBUFLEN 1024
  8239. #endif /* pdp11 */
  8240. #endif /* BIGBUFOK */
  8241.  
  8242. #ifdef ANYX25
  8243. #undef MYBUFLEN
  8244. #define MYBUFLEN 256
  8245. /*
  8246.   On X.25 connections, there is an extra control byte at the beginning.
  8247. */
  8248. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  8249. static CHAR  *mybuf = x25buf+1;
  8250. #else
  8251. static CHAR mybuf[MYBUFLEN];
  8252. #endif /* ANYX25 */
  8253.  
  8254. static int my_count = 0;        /* Number of chars still in mybuf */
  8255. static int my_item = -1;        /* Last index read from mybuf[]   */
  8256.  
  8257. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  8258.  
  8259. /*
  8260.   NOTE: This routine is peculiar to UNIX, and is used only by the
  8261.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  8262.   the ck?tio.c of other platforms.
  8263. */
  8264. int
  8265. ttpeek() {
  8266. #ifdef TTLEBUF
  8267.     int rc = 0;
  8268.     if (ttpush >= 0)
  8269.       rc++;
  8270.     rc += le_inbuf();
  8271.     if (rc > 0)
  8272.       return(rc);
  8273.     else
  8274. #endif /* TTLEBUF */
  8275.  
  8276. #ifdef MYREAD
  8277.     return(my_count);
  8278. #else
  8279.     return(0);
  8280. #endif /* MYREAD */
  8281. }
  8282.  
  8283. /* myread() -- Efficient read of one character from communications line.
  8284.  *
  8285.  * NOTE: myread() and its helpers mygetbuf() and myfillbuf() return raw
  8286.  * bytes from connection, so when the connection is encrypted, these bytes
  8287.  * must be decrypted.
  8288.  *
  8289.  * Uses a private buffer to minimize the number of expensive read() system
  8290.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  8291.  * is then returned.  By reading all available input from the system buffers
  8292.  * to the private buffer in one chunk, and then working from this buffer, the
  8293.  * number of system calls is reduced in any case where more than one character
  8294.  * arrives during the processing of the previous chunk, for instance high
  8295.  * baud rates or network type connections where input arrives in packets.
  8296.  * If the time needed for a read() system call approaches the time for more
  8297.  * than one character to arrive, then this mechanism automatically compensates
  8298.  * for that by performing bigger read()s less frequently.  If the system load
  8299.  * is high, the same mechanism compensates for that too.
  8300.  *
  8301.  * myread() is a macro that returns the next character from the buffer.  If the
  8302.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  8303.  * returns.
  8304.  *
  8305.  * This should be efficient enough for any one-character-at-a-time loops.
  8306.  * For even better efficiency you might use memcpy()/bcopy() or such between
  8307.  * buffers (since they are often better optimized for copying), but it may not
  8308.  * be worth it if you have to take an extra pass over the buffer to strip
  8309.  * parity and check for CTRL-C anyway.
  8310.  *
  8311.  * Note that if you have been using myread() from another program module, you
  8312.  * may have some trouble accessing this macro version and the private variables
  8313.  * it uses.  In that case, just add a function in this module, that invokes the
  8314.  * macro.
  8315.  */
  8316. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  8317.  
  8318. /* Specification: Push back up to one character onto myread()'s queue.
  8319.  *
  8320.  * This implementation: Push back characters into mybuf. At least one character
  8321.  * must have been read through myread() before myunrd() may be used.  After
  8322.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  8323.  * one character can be pushed back, but only one character is guaranteed.
  8324.  * Since a previous myread() must have read its character out of mybuf[],
  8325.  * that guarantees that there is space for at least one character.  If push
  8326.  * back was really needed after EOF, a small addition could provide that.
  8327.  *
  8328.  * As of 02/2007 myunrd() is used by ttinl().
  8329.  */
  8330. VOID
  8331. #ifdef CK_ANSIC
  8332. myunrd(CHAR ch)
  8333. #else
  8334. myunrd(ch) CHAR ch;
  8335. #endif    /* CK_ANSIC */
  8336. {
  8337.     if (my_item >= 0) {
  8338.     mybuf[my_item--] = ch;
  8339.     ++my_count;
  8340.     }
  8341. }
  8342.  
  8343. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  8344.  
  8345. static CHAR * pushbuf = NULL;
  8346. /* static int pushed = 0; */
  8347.  
  8348. int
  8349. ttpushback(s,n) CHAR * s; int n; {
  8350.     debug(F101,"ttpushback n","",n);
  8351.     if (pushbuf || n > MYBUFLEN || n < 1)
  8352.       return(-1);
  8353.     debug(F101,"ttpushback my_count","",my_count);
  8354.     if (my_count > 0) {
  8355.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  8356.       return(-1);
  8357.     memcpy(pushbuf,mybuf,my_count);
  8358.     /* pushed = my_count; */ /* (set but never used) */
  8359.     }
  8360.     memcpy(mybuf,s,n);
  8361.     my_count = n;
  8362.     my_item = -1;
  8363.     return(0);
  8364. }
  8365.  
  8366. /* mygetbuf() -- Fill buffer for myread() and return first character.
  8367.  *
  8368.  * This function is what myread() uses when it can't get the next character
  8369.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  8370.  * to read at least one new character into the buffer, and then it returns
  8371.  * the first character just as myread() would have done.  This function also
  8372.  * is responsible for all error conditions that myread() can indicate.
  8373.  *
  8374.  * Returns: When OK    => a positive character, 0 or greater.
  8375.  *        When EOF    => -2.
  8376.  *        When error    => -3, error code in errno.
  8377.  *
  8378.  * Older myread()s additionally returned -1 to indicate that there was nothing
  8379.  * to read, upon which the caller would call myread() again until it got
  8380.  * something.  The new myread()/mygetbuf() always gets something.  If it
  8381.  * doesn't, then make it do so!  Any program that actually depends on the old
  8382.  * behaviour will break.
  8383.  *
  8384.  * The older version also used to return -2 both for EOF and other errors,
  8385.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  8386.  * other errors now return different results, although Kermit currently never
  8387.  * checks to see which it was.  It just disconnects in both cases.
  8388.  *
  8389.  * Kermit lets the user use the quit key to perform some special commands
  8390.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  8391.  * finish without reading anything and return the EINTR error.  This should
  8392.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  8393.  * but if there is nothing to read, this could delay Kermit's reaction to
  8394.  * the command, and make Kermit appear unresponsive.
  8395.  *
  8396.  * The debug() call should be removed for optimum performance.
  8397.  */
  8398. int
  8399. mygetbuf() {
  8400.     int x;
  8401.     errno = 0;
  8402. #ifdef DEBUG
  8403.     if (deblog && my_count > 0)
  8404.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  8405. #endif /* DEBUG */
  8406.     if (my_count <= 0)
  8407.       my_count = myfillbuf();
  8408.  
  8409. #ifdef DEBUG
  8410. #ifdef COMMENT
  8411.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  8412. #else /* COMMENT */
  8413.     ckhexdump("mygetbuf read", mybuf, my_count);
  8414. #endif /* COMMENT */
  8415. #endif /* DEBUG */
  8416.     x = my_count;
  8417.     if (my_count <= 0) {
  8418.     my_count = 0;
  8419.     my_item = -1;
  8420.     debug(F101,"mygetbuf errno","",errno);
  8421. #ifdef TCPSOCKET
  8422.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  8423.         if (errno != EINTR) {
  8424.         debug(F101,"mygetbuf TCP error","",errno);
  8425.         ttclos(0);        /* Close the connection. */
  8426.         }
  8427.         return(-3);
  8428.     }
  8429. #endif /* TCPSOCKET */
  8430.     if (!netconn && xlocal && errno) {
  8431.         if (errno != EINTR) {
  8432.         debug(F101,"mygetbuf SERIAL error","",errno);
  8433.         x = -3;
  8434.         ttclos(0);        /* Close the connection. */
  8435.         }
  8436.     }
  8437.     return((x < 0) ? -3 : -2);
  8438.     }
  8439.     --my_count;
  8440.     return((unsigned)(0xff & mybuf[my_item = 0]));
  8441. }
  8442.  
  8443. /* myfillbuf():
  8444.  * System-dependent read() into mybuf[], as many characters as possible.
  8445.  *
  8446.  * Returns: OK => number of characters read, always more than zero.
  8447.  *          EOF => 0
  8448.  *          Error => -1, error code in errno.
  8449.  *
  8450.  * If there is input available in the system's buffers, all of it should be
  8451.  * read into mybuf[] and the function return immediately.  If no input is
  8452.  * available, it should wait for a character to arrive, and return with that
  8453.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  8454.  * character, but be aware that any such delay lengthens the packet turnaround
  8455.  * time during kermit file transfers.  Should never return with zero characters
  8456.  * unless EOF or irrecoverable read error.
  8457.  *
  8458.  * Correct functioning depends on the correct tty parameters being used.
  8459.  * Better control of current parameters is required than may have been the
  8460.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  8461.  * no longer be sometimes off and sometimes on like it used to, unless a
  8462.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  8463.  * myfillbuf()s may think they have come to EOF.
  8464.  *
  8465.  * If your system has a facility to directly perform the functioning of
  8466.  * myfillbuf(), then use it.  If the system can tell you how many characters
  8467.  * are available in its buffers, then read that amount (but not less than 1).
  8468.  * If the system can return a special indication when you try to read without
  8469.  * anything to read, while allowing you to read all there is when there is
  8470.  * something, you may loop until there is something to read, but probably that
  8471.  * is not good for the system load.
  8472.  */
  8473.  
  8474. #ifdef SVORPOSIX
  8475.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  8476.      * and CLOCAL set any way you like.  This way, read() will do exactly
  8477.      * what is required by myfillbuf(): If there is data in the buffers
  8478.      * of the O.S., all available data is read into mybuf, up to the size
  8479.      * of mybuf.  If there is none, the first character to arrive is
  8480.      * awaited and returned.
  8481.      */
  8482. int
  8483. myfillbuf() {
  8484.     int fd, n;
  8485. #ifdef NETCMD
  8486.     if (ttpipe)
  8487.       fd = fdin;
  8488.     else
  8489. #endif /* NETCMD */
  8490.       fd = ttyfd;
  8491.  
  8492. #ifdef sxaE50
  8493.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  8494.     /* necessary for the sxa E50, but it is. */
  8495.     return read(fd, mybuf, 255);
  8496. #else
  8497. #ifdef BEOSORBEBOX
  8498.     while (1) {
  8499. #ifdef NETCONN
  8500.         if (netconn) {
  8501.             n = netxin(sizeof(mybuf), (char *)mybuf);
  8502.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  8503.     }
  8504.         else
  8505. #endif /* NETCONN */
  8506.       n = read(fd, mybuf, sizeof(mybuf));
  8507.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  8508.         if (n > 0)
  8509.       return(n);
  8510.         snooze(1000.0);
  8511.     }
  8512. #else /* BEOSORBEBOX */
  8513.     errno = 0;
  8514.     /* debug(F101,"SVORPOSIX myfillbuf calling read() fd","",fd); */
  8515. #ifdef IBMX25
  8516.     if (netconn && (nettype == NET_IX25)) {
  8517.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  8518.     n = x25xin( MYBUFLEN, mybuf );
  8519.     } else
  8520. #endif /* IBMX25 */
  8521.  
  8522. #ifdef CK_SSL
  8523.       if (ssl_active_flag || tls_active_flag) {
  8524.       int error, n = 0;
  8525.       debug(F100,"myfillbuf calling SSL_read() fd","",0);
  8526.       while (n == 0) {
  8527.           if (ssl_active_flag)
  8528.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8529.           else if (tls_active_flag)
  8530.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8531.               else
  8532.         break;
  8533.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8534.         case SSL_ERROR_NONE:
  8535.           if (n > 0)
  8536.                     return(n);
  8537.           if (n < 0)
  8538.                     return(-2);
  8539.           msleep(50);
  8540.           break;
  8541.         case SSL_ERROR_WANT_WRITE:
  8542.         case SSL_ERROR_WANT_READ:
  8543.           return(-1);
  8544.         case SSL_ERROR_SYSCALL:
  8545.           if (n != 0)
  8546.             return(-1);
  8547.         case SSL_ERROR_WANT_X509_LOOKUP:
  8548.         case SSL_ERROR_SSL:
  8549.         case SSL_ERROR_ZERO_RETURN:
  8550.         default:
  8551.           ttclos(0);
  8552.           return(-3);
  8553.             }
  8554.         }
  8555.     }
  8556. #endif /* CK_SSL */
  8557. #ifdef CK_KERBEROS
  8558. #ifdef KRB4
  8559. #ifdef RLOGCODE
  8560.     if (ttnproto == NP_EK4LOGIN) {
  8561.     debug(F101,"myfillbuf calling krb4_des_read() fd","",ttyfd);
  8562.         if ((n = krb4_des_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8563.       return(-3);
  8564.         else
  8565.       return(n);
  8566.     }
  8567. #endif /* RLOGCODE */
  8568. #endif /* KRB4 */
  8569. #ifdef KRB5
  8570. #ifdef RLOGCODE
  8571.     if (ttnproto == NP_EK5LOGIN) {
  8572.     debug(F101,"myfillbuf calling krb5_des_read() fd","",ttyfd);
  8573.         if ((n = krb5_des_read(ttyfd,(char *)mybuf,sizeof(mybuf),0)) < 0)
  8574.       return(-3);
  8575.         else
  8576.       return(n);
  8577.     }
  8578. #endif /* RLOGCODE */
  8579. #ifdef KRB5_U2U
  8580.     if (ttnproto == NP_K5U2U) {
  8581.     debug(F101,"myfillbuf calling krb5_u2u_read() fd","",ttyfd);
  8582.         if ((n = krb5_u2u_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8583.       return(-3);
  8584.         else
  8585.       return(n);
  8586.     }
  8587. #endif /* KRB5_U2U */
  8588. #endif /* KRB5 */
  8589. #endif /* CK_KERBEROS */
  8590.  
  8591. #ifdef NETPTY
  8592. #ifdef HAVE_PTYTRAP
  8593.     /* Special handling for HP-UX pty i/o */
  8594.   ptyread:
  8595.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8596.     debug(F101,"myfillbuf calling pty_trap_handler() fd","",ttyfd);
  8597.         if (pty_trap_handler(ttyfd) > 0) {
  8598.             ttclos(0);
  8599.             return(-3);
  8600.         }
  8601.     }
  8602. #endif /* HAVE_PTYTRAP */
  8603. #endif /* NETPTY */
  8604.     debug(F101,"myfillbuf calling read() fd","",ttyfd);
  8605.     n = read(fd, mybuf, sizeof(mybuf));
  8606.     debug(F101,"SVORPOSIX myfillbuf read","",n);
  8607.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  8608.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  8609.     if (n < 1) {
  8610. #ifdef NETPTY
  8611. #ifdef HAVE_PTYTRAP
  8612.         /* When we have a PTY trap in place the connection cannot */
  8613.         /* be closed until the trap receives a close indication.  */
  8614.         if (n == 0 && ttpty)
  8615.             goto ptyread;
  8616. #endif /* HAVE_PTYTRAP */
  8617. #endif /* NETPTY */
  8618.         return(-3);
  8619.     }
  8620.     return(n);
  8621. #endif /* BEOSORBEBOX */
  8622. #endif /* sxaE50 */
  8623. }
  8624.  
  8625. #else /* not AT&T or POSIX */
  8626.  
  8627. #ifdef aegis
  8628.     /* This is quoted from the old myread().  The semantics seem to be
  8629.      * alright, but maybe errno would not need to be set even when
  8630.      * there is no error?  I don't know aegis.
  8631.      */
  8632. int
  8633. myfillbuf() {
  8634.     int count;
  8635. #ifdef NETCMD
  8636.     if (ttpipe)
  8637.       fd = fdin;
  8638.     else
  8639. #endif /* NETCMD */
  8640.       fd = ttyfd;
  8641.  
  8642.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  8643.     errno = EIO;
  8644.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  8645.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  8646.     if (st.all == ios_$end_of_file)
  8647.       return(-3);
  8648.     else if (st.all != status_$ok) {
  8649.     errno = EIO;
  8650.     return(-1);
  8651.     }
  8652.     return(count > 0 ? count : -3);
  8653. }
  8654. #else /* !aegis */
  8655.  
  8656. #ifdef FIONREAD
  8657.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  8658.      * of characters available for reading. If none are available, wait
  8659.      * until something arrives, otherwise return all there is.
  8660.      */
  8661. int
  8662. myfillbuf() {
  8663.     PEEKTYPE avail = 0;
  8664.     int x, fd;
  8665. #ifdef NETCMD
  8666.     if (ttpipe)
  8667.       fd = fdin;
  8668.     else
  8669. #endif /* NETCMD */
  8670.       fd = ttyfd;
  8671.  
  8672. #ifdef SUNX25
  8673. /*
  8674.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  8675.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  8676.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  8677.  
  8678.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  8679.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  8680.   transparently to the upper-level code.  This is a blocking read, and so
  8681.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  8682. */
  8683.     extern int nettype;
  8684.     if (netconn && nettype == NET_SX25) {
  8685.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  8686.     return(x - 1);            /* "-1" compensates for extra status byte */
  8687.     }
  8688. #endif /* SUNX25 */
  8689.  
  8690. #ifdef CK_SSL
  8691.     if (ssl_active_flag || tls_active_flag) {
  8692.         int error, n = 0;
  8693.         while (n == 0) {
  8694.             if (ssl_active_flag)
  8695.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8696.             else
  8697.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8698.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8699.           case SSL_ERROR_NONE:
  8700.                 if (n > 0)
  8701.           return(n);
  8702.                 if (n < 0)
  8703.           return(-2);
  8704.                 msleep(50);
  8705.                 break;
  8706.           case SSL_ERROR_WANT_WRITE:
  8707.           case SSL_ERROR_WANT_READ:
  8708.                 return(-1);
  8709.           case SSL_ERROR_SYSCALL:
  8710.         if (n != 0)
  8711.           return(-1);
  8712.           case SSL_ERROR_WANT_X509_LOOKUP:
  8713.           case SSL_ERROR_SSL:
  8714.           case SSL_ERROR_ZERO_RETURN:
  8715.           default:
  8716.                 ttclos(0);
  8717.                 return(-2);
  8718.             }
  8719.         }
  8720.     }
  8721. #endif /* CK_SSL */
  8722. #ifdef CK_KERBEROS
  8723. #ifdef KRB4
  8724. #ifdef RLOGCODE
  8725.     if (ttnproto == NP_EK4LOGIN) {
  8726.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8727.       return(-1);
  8728.         else
  8729.       return(x);
  8730.     }
  8731. #endif /* RLOGCODE */
  8732. #endif /* KRB4 */
  8733. #ifdef KRB5
  8734. #ifdef RLOGCODE
  8735.     if (ttnproto == NP_EK5LOGIN) {
  8736.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8737.       return(-1);
  8738.         else
  8739.       return(x);
  8740.     }
  8741. #endif /* RLOGCODE */
  8742. #ifdef KRB5_U2U
  8743.     if (ttnproto == NP_K5U2U) {
  8744.         if ((x = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8745.       return(-1);
  8746.         else
  8747.       return(x);
  8748.     }
  8749. #endif /* KRB5_U2U */
  8750. #endif /* KRB5 */
  8751. #endif /* CK_KERBEROS */
  8752.  
  8753.     errno = 0;
  8754.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  8755.     x = ioctl(fd, FIONREAD, &avail);
  8756. #ifdef DEBUG
  8757.     if (deblog) {
  8758.     debug(F101,"myfillbuf FIONREAD","",x);
  8759.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  8760.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  8761.     }
  8762. #endif /* DEBUG */
  8763.     if (x < 0 || avail == 0)
  8764.       avail = 1;
  8765.  
  8766.     if (avail > MYBUFLEN)
  8767.       avail = MYBUFLEN;
  8768.  
  8769.     errno = 0;
  8770.  
  8771.     x = read(fd, mybuf, (int) avail);
  8772. #ifdef DEBUG
  8773.     if (deblog) {
  8774.     debug(F101,"myfillbuf avail","",avail);
  8775.     debug(F101,"myfillbuf read","",x);
  8776.     debug(F101,"myfillbuf read errno","",errno);
  8777.         if (x > 0)
  8778.       ckhexdump("myfillbuf mybuf",mybuf,x);
  8779.     }
  8780. #endif /* DEBUG */
  8781.     if (x < 1) x = -3;            /* read 0 == connection loss */
  8782.     return(x);
  8783. }
  8784.  
  8785. #else /* !FIONREAD */
  8786. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  8787. /* When there is no other possibility, read 1 character at a time. */
  8788. int
  8789. myfillbuf() {
  8790.     int x;
  8791.  
  8792. #ifdef CK_SSL
  8793.     if (ssl_active_flag || tls_active_flag) {
  8794.         int error, n = 0;
  8795.         while (n == 0) {
  8796.             if (ssl_active_flag)
  8797.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8798.             else
  8799.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8800.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8801.           case SSL_ERROR_NONE:
  8802.                 if (n > 0)
  8803.           return(n);
  8804.                 if (n < 0)
  8805.           return(-2);
  8806.                 msleep(50);
  8807.                 break;
  8808.           case SSL_ERROR_WANT_WRITE:
  8809.           case SSL_ERROR_WANT_READ:
  8810.                 return(-1);
  8811.           case SSL_ERROR_SYSCALL:
  8812.         if (n != 0)
  8813.           return(-1);
  8814.           case SSL_ERROR_WANT_X509_LOOKUP:
  8815.           case SSL_ERROR_SSL:
  8816.           case SSL_ERROR_ZERO_RETURN:
  8817.           default:
  8818.                 ttclos(0);
  8819.                 return(-2);
  8820.             }
  8821.         }
  8822.     }
  8823. #endif /* CK_SSL */
  8824. #ifdef CK_KERBEROS
  8825. #ifdef KRB4
  8826. #ifdef RLOGCODE
  8827.     if (ttnproto == NP_EK4LOGIN) {
  8828.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8829.       return(-1);
  8830.         else
  8831.       return(len);
  8832.     }
  8833. #endif /* RLOGCODE */
  8834. #endif /* KRB4 */
  8835. #ifdef KRB5
  8836. #ifdef RLOGCODE
  8837.     if (ttnproto == NP_EK5LOGIN) {
  8838.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8839.       return(-1);
  8840.         else
  8841.       return(len);
  8842.     }
  8843. #endif /* RLOGCODE */
  8844. #ifdef KRB5_U2U
  8845.     if (ttnproto == NP_K5U2U) {
  8846.         if ((len = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8847.       return(-1);
  8848.         else
  8849.       return(len);
  8850.     }
  8851. #endif /* KRB5_U2U */
  8852. #endif /* KRB5 */
  8853. #endif /* CK_KERBEROS */
  8854.  
  8855. #ifdef NETCMD
  8856.     if (ttpipe)
  8857.       fd = fdin;
  8858.     else
  8859. #endif /* NETCMD */
  8860.       fd = ttyfd;
  8861.     x = read(fd, mybuf, 1);
  8862.     return(x > 0 ? x : -3);
  8863. }
  8864.  
  8865. #endif /* !FIONREAD */
  8866. #endif /* !aegis */
  8867. #endif /* !ATTSV */
  8868.  
  8869. #endif /* MYREAD */
  8870.  
  8871. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  8872. /*
  8873.   Call with the IAC that was encountered.
  8874.   Returns:
  8875.    -3: If connection has dropped or gone bad.
  8876.    -2: On Telnet protocol error resulting in inconsistent states.
  8877.     0: If negotiation OK and caller has nothing to do.
  8878.     1: If packet start character has changed (new value is in global stchr).
  8879.   255: If there was a quoted IAC as data.
  8880.    or: Not at all if we got a legitimate Telnet Logout request.
  8881. */
  8882. #ifdef TCPSOCKET
  8883. static int
  8884. tt_tnopt(n) int n; {            /* Handle Telnet options */
  8885.     /* In case caller did not already check these conditions...  */
  8886.     if (n == IAC &&
  8887.     ((xlocal && netconn && IS_TELNET()) ||
  8888.      (!xlocal && sstelnet))) {
  8889.     extern int server;
  8890.     int tx = 0;
  8891.     debug(F100,"ttinl calling tn_doop()","",0);
  8892.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  8893.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  8894.     switch (tx) {
  8895.       case 0:
  8896.         return(0);
  8897.       case -1:            /* I/O error */
  8898.         ttimoff();            /* Turn off timer */
  8899.         return(-3);
  8900.           case -2:            /* Connection failed. */
  8901.           case -3:
  8902.         ttimoff();            /* Turn off timer */
  8903.         ttclos(0);
  8904.         return(-3);
  8905.       case 1:            /* ECHO change */
  8906.         duplex = 1;
  8907.         return(0);
  8908.       case 2:            /* ECHO change */
  8909.         duplex = 0;
  8910.         return(0);
  8911.       case 3:            /* Quoted IAC */
  8912.         n = 255;
  8913.         return((unsigned)255);
  8914. #ifdef IKS_OPTION
  8915.       case 4: {
  8916.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  8917. #ifdef IKSD
  8918.           && !inserver
  8919. #endif /* IKSD */
  8920.           ) {            /* Remote in Server mode */
  8921.           ttimoff();        /* Turn off timer */
  8922.           debug(F100,"u_start and !inserver","",0);
  8923.           return(-2);        /* End server mode */
  8924.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  8925.              server
  8926.              ) {        /* I'm no longer in Server Mode */
  8927.           debug(F100,"me_start and server","",0);
  8928.           ttimoff();
  8929.           return(-2);
  8930.           }
  8931.           return(0);
  8932.       }
  8933.       case 5: {            /* Start character change */
  8934.           /* extern CHAR stchr; */
  8935.           /* start = stchr; */
  8936.           return(1);
  8937.       }
  8938. #endif /* IKS_OPTION */
  8939.       case 6:            /* Remote Logout */
  8940.         ttimoff();
  8941.         ttclos(0);
  8942. #ifdef IKSD
  8943.         if (inserver && !local)
  8944.           doexit(GOOD_EXIT,0);
  8945.         else
  8946. #endif /* IKSD */
  8947.           return(-2);
  8948.       default:
  8949.         return(0);
  8950.     }
  8951.     } else
  8952.       return(0);
  8953. }
  8954. #endif /* TCPSOCKET */
  8955.  
  8956. /*  T T F L U I  --  Flush tty input buffer */
  8957.  
  8958. void
  8959. ttflux() {                /* But first... */
  8960. #ifdef MYREAD
  8961. /*
  8962.   Flush internal MYREAD buffer.
  8963. */
  8964. #ifdef TCPSOCKET
  8965.     int dotnopts, x;
  8966.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8967.          (!xlocal && sstelnet)));
  8968. #endif /* TCPSOCKET */
  8969.     debug(F101,"ttflux my_count","",my_count);
  8970. #ifdef TCPSOCKET
  8971.     if (dotnopts) {
  8972.     CHAR ch = '\0';
  8973.         while (my_count > 0) {
  8974.         ch = myread();
  8975. #ifdef CK_ENCRYPTION
  8976.             if (TELOPT_U(TELOPT_ENCRYPTION))
  8977.           ck_tn_decrypt((char *)&ch,1);
  8978. #endif /* CK_ENCRYPTION */
  8979.             if (ch == IAC)
  8980.           x = tt_tnopt(ch);
  8981.         }
  8982.     } else
  8983. #endif /* TCPSOCKET */
  8984. #ifdef COMMENT
  8985. #ifdef CK_ENCRYPTION
  8986.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  8987.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  8988. #endif /* CK_ENCRYPTION */
  8989. #endif /* COMMENT */
  8990.     my_count = 0;            /* Reset count to zero */
  8991.     my_item = -1;            /* And buffer index to -1 */
  8992. #endif /* MYREAD */
  8993. }
  8994.  
  8995. int
  8996. ttflui() {
  8997.     int n, fd;
  8998. #ifdef TCPSOCKET
  8999.     int dotnopts;
  9000.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  9001.          (!xlocal && sstelnet)));
  9002. #endif /* TCPSOCKET */
  9003.  
  9004. #ifdef NETCMD
  9005.     if (ttpipe)
  9006.       fd = fdin;
  9007.     else
  9008. #endif /* NETCMD */
  9009.       fd = ttyfd;
  9010.  
  9011. #ifdef TTLEBUF
  9012.     ttpush = -1;            /* Clear the peek-ahead char */
  9013.     while (le_data && (le_inbuf() > 0)) {
  9014.         CHAR ch = '\0';
  9015.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  9016.             debug(F101,"ttflui le_inbuf ch","",ch);
  9017.         }
  9018.     }
  9019. #endif /* TTLEBUF */
  9020.     debug(F101,"ttflui ttpipe","",ttpipe);
  9021.  
  9022. #ifdef MYREAD
  9023. /*
  9024.   Flush internal MYREAD buffer *NEXT*, in all cases.
  9025. */
  9026.     ttflux();
  9027. #endif /* MYREAD */
  9028.  
  9029. #ifdef NETCONN
  9030. /* Network flush is done specially, in the network support module. */
  9031.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  9032.     debug(F100,"ttflui netflui","",0);
  9033. #ifdef COMMENT
  9034. #ifdef TN_COMPORT
  9035.     if (istncomport())
  9036.             tnc_send_purge_data(TNC_PURGE_RECEIVE);
  9037. #endif /* TN_COMPORT */
  9038. #endif /* COMMENT */
  9039.     return(netflui());
  9040.     }
  9041. #endif /* NETCONN */
  9042.  
  9043.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  9044.     if (ttyfd < 0)
  9045.       return(-1);
  9046.  
  9047. #ifdef aegis
  9048.     sio_$control((short)yfd, sio_$flush_in, true, st);
  9049.     if (st.all != status_$ok) {
  9050.     fprintf(stderr, "flush failed: "); error_$print(st);
  9051.     } else {      /* sometimes the flush doesn't work */
  9052.         for (;;) {
  9053.         char buf[256];
  9054.             /* eat all the characters that shouldn't be available */
  9055.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  9056.             if (st.all == ios_$get_conditional_failed) break;
  9057.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  9058.         }
  9059.     }
  9060. #else
  9061. #ifdef BSD44                /* 4.4 BSD */
  9062.     n = FREAD;                          /* Specify read queue */
  9063.     debug(F100,"ttflui BSD44","",0);
  9064.     ioctl(fd,TIOCFLUSH,&n);
  9065. #else
  9066. #ifdef Plan9
  9067. #undef POSIX                /* Uh oh... */
  9068. #endif /* Plan9 */
  9069. #ifdef POSIX                /* POSIX */
  9070.     debug(F100,"ttflui POSIX","",0);
  9071.     tcflush(fd,TCIFLUSH);
  9072. #else
  9073. #ifdef ATTSV                /* System V */
  9074. #ifndef VXVE
  9075.     debug(F100,"ttflui ATTSV","",0);
  9076.     ioctl(fd,TCFLSH,0);
  9077. #endif /* VXVE */
  9078. #else                    /* Not BSD44, POSIX, or Sys V */
  9079. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  9080. #ifdef ANYBSD                /* Berkeley */
  9081.     n = FREAD;                          /* Specify read queue */
  9082.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  9083.     ioctl(fd,TIOCFLUSH,&n);
  9084. #else                    /* Others (V7, etc) */
  9085.     debug(F100,"ttflui TIOCFLUSH","",0);
  9086.     ioctl(fd,TIOCFLUSH,0);
  9087. #endif /* ANYBSD */
  9088. #else                    /* All others... */
  9089. /*
  9090.   No system call (that we know about) for input buffer flushing.
  9091.   So see how many there are and read them in a loop, using ttinc().
  9092.   ttinc() is buffered, so we're not getting charged with a system call
  9093.   per character, just a function call.
  9094. */
  9095.     if ((n = ttchk()) > 0) {
  9096.     debug(F101,"ttflui read loop","",n);
  9097.     while ((n--) && ttinc(0) > 0) ;
  9098.     }
  9099. #endif /* TIOCFLUSH */
  9100. #endif /* ATTSV */
  9101. #endif /* POSIX */
  9102. #ifdef Plan9
  9103. #define POSIX
  9104. #endif /* Plan9 */
  9105. #endif /* BSD44 */
  9106. #endif /* aegis */
  9107.     return(0);
  9108. }
  9109.  
  9110. int
  9111. ttfluo() {                /* Flush output buffer */
  9112.     int fd;
  9113. #ifdef NETCMD
  9114.     if (ttpipe)
  9115.       fd = fdout;
  9116.     else
  9117. #endif /* NETCMD */
  9118.       fd = ttyfd;
  9119.  
  9120. #ifdef Plan9
  9121.     return 0;
  9122. #else
  9123. #ifdef POSIX
  9124.     return(tcflush(fd,TCOFLUSH));
  9125. #else
  9126. #ifdef OXOS
  9127.     return(ioctl(fd,TCFLSH,1));
  9128. #else
  9129.     return(0);                /* All others, nothing */
  9130. #endif /* OXOS */
  9131. #endif /* POSIX */
  9132. #endif /* Plan9 */
  9133. }
  9134.  
  9135. /* Interrupt Functions */
  9136.  
  9137. /* Set up terminal interrupts on console terminal */
  9138.  
  9139. #ifndef FIONREAD            /* We don't need esctrp() */
  9140. #ifndef SELECT                /* if we have any of these... */
  9141. #ifndef CK_POLL
  9142. #ifndef RDCHK
  9143.  
  9144. #ifndef OXOS
  9145. #ifdef SVORPOSIX
  9146. SIGTYP
  9147. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9148.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9149.     conesc = 1;
  9150.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9151. }
  9152. #endif /* SVORPOSIX */
  9153. #endif /* OXOS */
  9154.  
  9155. #ifdef V7
  9156. #ifndef MINIX2
  9157. SIGTYP
  9158. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9159.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9160.     conesc = 1;
  9161.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9162. }
  9163. #endif /* MINIX2 */
  9164. #endif /* V7 */
  9165.  
  9166. #ifdef C70
  9167. SIGTYP
  9168. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9169.     conesc = 1;
  9170.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9171. }
  9172. #endif /* C70 */
  9173.  
  9174. #endif /* RDCHK */
  9175. #endif /* CK_POLL */
  9176. #endif /* SELECT */
  9177. #endif /* FIONREAD */
  9178.  
  9179. /*  C O N B G T  --  Background Test  */
  9180.  
  9181. static int jc = 0;            /* 0 = no job control */
  9182.  
  9183. /*
  9184.   Call with flag == 1 to prevent signal test, which can not be expected
  9185.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  9186.  
  9187.   Call with flag == 0 to use the signal test, but only if the process-group
  9188.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  9189.   requires an argument when the man page says it doesn't, or vice versa.
  9190.  
  9191.   If flag == 0 and the process-group test fails, then we determine background
  9192.   status simply (but not necessarily reliably) from isatty().
  9193.  
  9194.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  9195.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  9196.   misbehavior.
  9197. */
  9198. VOID
  9199. conbgt(flag) int flag; {
  9200.     int x = -1,                /* process group or SIGINT test */
  9201.         y = 0;                /* isatty() test */
  9202. /*
  9203.   Check for background operation, even if not running on real tty, so that
  9204.   background flag can be set correctly.  If background status is detected,
  9205.   then Kermit will not issue its interactive prompt or most messages.
  9206.   If your prompt goes away, you can blame (and fix?) this function.
  9207. */
  9208.  
  9209. /* Use process-group test if possible. */
  9210.  
  9211. #ifdef POSIX                /* We can do it in POSIX */
  9212. #define PGROUP_T
  9213. #else
  9214. #ifdef BSD4                /* and in BSD 4.x. */
  9215. #define PGROUP_T
  9216. #else
  9217. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  9218. #define PGROUP_T
  9219. #else
  9220. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  9221. #define PGROUP_T
  9222. #endif /* TIOCGPGRP */
  9223. #endif /* HPUXJOBCTL */
  9224. #endif /* BSD4 */
  9225. #endif /* POSIX */
  9226.  
  9227. #ifdef MIPS                /* Except if it doesn't work... */
  9228. #undef PGROUP_T
  9229. #endif /* MIPS */
  9230.  
  9231. #ifdef MINIX
  9232. #undef PGROUP_T
  9233. #endif    /* MINIX */
  9234.  
  9235. #ifdef PGROUP_T
  9236. /*
  9237.   Semi-reliable process-group test.  Check whether this process's group is
  9238.   the same as the controlling terminal's process group.  This works if the
  9239.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  9240. */
  9241.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  9242.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  9243. #ifndef _POSIX_SOURCE
  9244. /*
  9245.   The getpgrp() prototype is obtained from system header files for POSIX
  9246.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  9247.   a duplicate declaration here, others don't, so it's safer to leave it in
  9248.   if we don't know for certain.
  9249. */
  9250. #ifndef SVR4
  9251. #ifndef PS2AIX10
  9252. #ifndef HPUX9
  9253.     extern PID_T getpgrp();
  9254. #endif /* HPUX9 */
  9255. #endif /* PS2AIX10 */
  9256. #endif /* SVR4 */
  9257. #endif /* _POSIX_SOURCE */
  9258.  
  9259. /* Get my process group. */
  9260.  
  9261. #ifdef SVR3 /* Maybe this should be ATTSV? */
  9262. /* This function is not described in SVID R2 */
  9263.     mypgrp = getpgrp();
  9264.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  9265. #else
  9266. #ifdef POSIX
  9267.     mypgrp = getpgrp();
  9268.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  9269. #else
  9270. #ifdef OSFPC
  9271.     mypgrp = getpgrp();
  9272.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  9273. #else
  9274. #ifdef QNX
  9275.     mypgrp = getpgrp();
  9276.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  9277. #else
  9278. #ifdef OSF32                /* (was OSF40) */
  9279.     mypgrp = getpgrp();
  9280.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  9281. #else /* BSD, V7, etc */
  9282. #ifdef MINIX2
  9283.     mypgrp = getpgrp();
  9284. #else
  9285.     mypgrp = getpgrp(0);
  9286. #endif /* MINIX2 */
  9287.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  9288. #endif /* OSF32 */
  9289. #endif /* QNX */
  9290. #endif /* OSFPC */
  9291. #endif /* POSIX */
  9292. #endif /* SVR3 */
  9293.  
  9294. #ifdef MINIX
  9295.     /* MINIX does not support job control so Kermit is always in foreground */
  9296.     x = 0;
  9297.  
  9298. #else  /* Not MINIX */
  9299.  
  9300. /* Now get controlling tty's process group */
  9301. #ifdef BSD44ORPOSIX
  9302.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  9303.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  9304. #else
  9305.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  9306.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  9307. #endif /* BSD44ORPOSIX */
  9308.  
  9309.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  9310.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  9311.     else x = -1;            /* If error, remember. */
  9312.     debug(F101,"conbgt process group test","",x);
  9313. #endif /* PGROUP_T */
  9314. #endif    /* MINIX */
  9315.  
  9316. /* Try to see if job control is available */
  9317.  
  9318. #ifdef NOJC                /* User override */
  9319.     jc = 0;                /* No job control allowed */
  9320.     debug(F111,"NOJC","jc",jc);
  9321. #else
  9322. #ifdef BSD44
  9323.     jc = 1;
  9324. #else
  9325. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  9326.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  9327. #ifdef _SC_JOB_CONTROL
  9328. #ifdef __bsdi__
  9329.     jc = 1;
  9330. #else
  9331. #ifdef __386BSD__
  9332.     jc = 1;
  9333. #else
  9334.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  9335.     if (jc < 0) {
  9336.     debug(F101,"sysconf fails, jcshell","",jcshell);
  9337.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  9338.     } else
  9339.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  9340. #endif /* __386BSD__ */
  9341. #endif /* __bsdi__ */
  9342. #else
  9343. #ifdef _POSIX_JOB_CONTROL
  9344.     jc = 1;                /* By definition */
  9345.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  9346. #else
  9347.     jc = 0;                /* Assume job control not allowed */
  9348.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  9349. #endif /* _POSIX_JOB_CONTROL */
  9350. #endif /* _SC_JOB_CONTROL */
  9351. #else
  9352. #ifdef BSD4
  9353.     jc = 1;                /* Job control allowed */
  9354.     debug(F111,"BSD job control","jc",jc);
  9355. #else
  9356. #ifdef SVR3JC
  9357.     jc = 1;                /* JC allowed */
  9358.     debug(F111,"SVR3 job control","jc",jc);
  9359. #else
  9360. #ifdef OXOS
  9361.     jc = 1;                /* JC allowed */
  9362.     debug(F111,"X/OS job control","jc",jc);
  9363. #else
  9364. #ifdef HPUX9
  9365.     jc = 1;                /* JC allowed */
  9366.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  9367. #else
  9368. #ifdef HPUX10
  9369.     jc = 1;                /* JC allowed */
  9370.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  9371. #else
  9372.     jc = 0;                /* JC not allowed */
  9373.     debug(F111,"job control catch-all","jc",jc);
  9374. #endif /* HPUX10 */
  9375. #endif /* HPUX9 */
  9376. #endif /* OXOS */
  9377. #endif /* SVR3JC */
  9378. #endif /* BSD4 */
  9379. #endif /* SVR4ORPOSIX */
  9380. #endif /* BSD44 */
  9381. #endif /* NOJC */
  9382.     debug(F101,"conbgt jc","",jc);
  9383. #ifndef NOJC
  9384.     debug(F101,"conbgt jcshell","",jcshell);
  9385. /*
  9386.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  9387.   job control, but the shell or other process we are running under does not
  9388.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  9389.   will come of it.  So...
  9390. */
  9391.     if (jc < 0) jc = 0;
  9392.     if (jc > 0 && jcshell == 0) jc = 0;
  9393. #endif /* NOJC */
  9394.  
  9395. /*
  9396.   Another background test.
  9397.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  9398.   which is done by the shell (sh) if the program is started with '&'.
  9399.   Unfortunately, this is NOT done by csh or ksh so watch out!
  9400.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  9401.   we always set it to something else.
  9402.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  9403.   SIG_IGN ourselves.
  9404. */
  9405.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  9406.  
  9407.     SIGTYP (*osigint)();
  9408.  
  9409.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  9410.     sigint_ign = 1;
  9411.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  9412.     /* debug(F101,"conbgt osigint","",osigint); */
  9413.     /* debug(F101,"conbgt signal test","",x); */
  9414.     }
  9415.  
  9416. /* Also check to see if we're running with redirected stdio. */
  9417. /* This is not really background operation, but we want to act as though */
  9418. /* it were. */
  9419.  
  9420. #ifdef IKSD
  9421.     if (inserver) {            /* Internet Kermit Server */
  9422.     backgrd = 0;            /* is not in the background */
  9423.     return;
  9424.     }
  9425. #endif /* IKSD */
  9426.  
  9427.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  9428.     debug(F101,"conbgt isatty test","",y);
  9429.  
  9430. #ifdef BSD29
  9431. /* The process group and/or signal test doesn't work under these... */
  9432.     backgrd = !y;
  9433. #else
  9434. #ifdef sxaE50
  9435.     backgrd = !y;
  9436. #else
  9437. #ifdef MINIX
  9438.     backgrd = !y;
  9439. #else
  9440. #ifdef MINIX2
  9441.     backgrd = !y;
  9442. #else
  9443.     if (x > -1)
  9444.       backgrd = (x || !y) ? 1 : 0;
  9445.     else backgrd = !y;
  9446. #endif /* BSD29 */
  9447. #endif /* sxaE50 */
  9448. #endif /* MINIX */
  9449. #endif /* MINIX2 */
  9450.     debug(F101,"conbgt backgrd","",backgrd);
  9451. }
  9452.  
  9453. /*  C O N I N T  --  Console Interrupt setter  */
  9454.  
  9455. /*
  9456.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  9457.   Second arg is pointer to function to handle SIGTSTP (suspend).
  9458. */
  9459.  
  9460. VOID                    /* Set terminal interrupt traps. */
  9461. #ifdef CK_ANSIC
  9462. #ifdef apollo
  9463. conint(f,s) SIGTYP (*f)(), (*s)();
  9464. #else
  9465. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  9466. #endif /* apollo */
  9467. #else
  9468. conint(f,s) SIGTYP (*f)(), (*s)();
  9469. #endif /* CK_ANSIC */
  9470. /* conint */ {
  9471.  
  9472.     debug(F101,"conint conistate","",conistate);
  9473.  
  9474.     conbgt(0);                /* Do background test. */
  9475.  
  9476. /* Set the desired handlers for hangup and software termination. */
  9477.  
  9478. #ifdef SIGTERM
  9479.     signal(SIGTERM,f);                  /* Software termination */
  9480. #endif /* SIGTERM */
  9481.  
  9482. /*
  9483.   Prior to July 1999 we used to call sighup() here but now it's called in
  9484.   sysinit() so SIGHUP can be caught during execution of the init file or
  9485.   a kerbang script.
  9486. */
  9487.  
  9488. /* Now handle keyboard stop, quit, and interrupt signals. */
  9489. /* Check if invoked in background -- if so signals set to be ignored. */
  9490. /* However, if running under a job control shell, don't ignore them. */
  9491. /* We won't be getting any, as we aren't in the terminal's process group. */
  9492.  
  9493.     debug(F101,"conint backgrd","",backgrd);
  9494.     debug(F101,"conint jc","",jc);
  9495.  
  9496.     if (backgrd && !jc) {        /* In background, ignore signals */
  9497.     debug(F101,"conint background ignoring signals, jc","",jc);
  9498. #ifdef SIGTSTP
  9499.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  9500. #endif /* SIGTSTP */
  9501.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  9502.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  9503.     sigint_ign = 1;
  9504.     conistate = CONI_NOI;
  9505.     } else {                /* Else in foreground or suspended */
  9506.     debug(F101,"conint foreground catching signals, jc","",jc);
  9507.         signal(SIGINT,f);               /* Catch terminal interrupt */
  9508.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  9509.  
  9510. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  9511.     /* debug(F101,"conint SIGSTSTP","",s); */
  9512.     if (s == NULL) s = SIG_DFL;
  9513. #ifdef NOJC                /* No job control allowed. */
  9514.     signal(SIGTSTP,SIG_IGN);
  9515. #else                    /* Job control allowed */
  9516.     if (jc)                /* if available. */
  9517.       signal(SIGTSTP,s);
  9518.     else
  9519.       signal(SIGTSTP,SIG_IGN);
  9520. #endif /* NOJC */
  9521. #endif /* SIGTSTP */
  9522.  
  9523. #ifndef OXOS
  9524. #ifdef SVORPOSIX
  9525. #ifndef FIONREAD            /* Watch out, we don't know this... */
  9526. #ifndef SELECT
  9527. #ifndef CK_POLL
  9528. #ifndef RDCHK
  9529.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  9530. #endif /* RDCHK */
  9531. #endif /* CK_POLL */
  9532. #endif /* SELECT */
  9533. #endif /* FIONREAD */
  9534.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  9535. #else
  9536. #ifdef V7
  9537.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  9538.         if (conesc) conesc = 0;
  9539. #else
  9540. #ifdef aegis
  9541.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  9542. #else
  9543.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  9544. #endif /* aegis */
  9545. #endif /* V7 */
  9546. #endif /* SVORPOSIX */
  9547. #endif /* OXOS */
  9548.     conistate = CONI_INT;
  9549.     }
  9550. }
  9551.  
  9552.  
  9553. /*  C O N N O I  --  Reset console terminal interrupts */
  9554.  
  9555. VOID
  9556. connoi() {                              /* Console-no-interrupts */
  9557.  
  9558.     debug(F101,"connoi conistate","",conistate);
  9559. #ifdef SIGTSTP
  9560.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  9561. #endif /* SIGTSTP */
  9562.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  9563.     sigint_ign = 1;            /* Remember we did this ourselves */
  9564. #ifdef SIGQUIT
  9565.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  9566. #endif /* SIGQUIT */
  9567. #ifdef SIGTERM
  9568.     signal(SIGTERM,SIG_IGN);        /* Term */
  9569. #endif /* SIGTERM */
  9570.     conistate = CONI_NOI;
  9571. }
  9572.  
  9573. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  9574.  
  9575. #ifdef  V7
  9576. /*
  9577.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  9578.  eliminates blocking on a read, because we can read /dev/kmem to get the
  9579.  number of characters available for raw input.  If your system can't
  9580.  or you won't let the world read /dev/kmem then you must figure out a
  9581.  different way to do the counting of characters available, or else replace
  9582.  this by a dummy function that always returns 0.
  9583. */
  9584. /*
  9585.  * Call this routine as: initrawq(tty)
  9586.  * where tty is the file descriptor of a terminal.  It will return
  9587.  * (as a char *) the kernel-mode memory address of the rawq character
  9588.  * count, which may then be read.  It has the side-effect of flushing
  9589.  * input on the terminal.
  9590.  */
  9591. /*
  9592.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  9593.  * ...!decvax!mulga!physiol.su.oz!john
  9594.  *
  9595.  * Permission is hereby granted to do anything with this code, as
  9596.  * long as this comment is retained unmodified and no commercial
  9597.  * advantage is gained.
  9598.  */
  9599. #ifndef MINIX
  9600. #ifndef MINIX2
  9601. #ifndef COHERENT
  9602. #include <a.out.h>
  9603. #include <sys/proc.h>
  9604. #endif /* COHERENT */
  9605. #endif /* MINIX2 */
  9606. #endif /* MINIX */
  9607.  
  9608. #ifdef COHERENT
  9609. #include <l.out.h>
  9610. #include <sys/proc.h>
  9611. #endif /* COHERENT */
  9612.  
  9613. char *
  9614. initrawq(tty) int tty; {
  9615. #ifdef MINIX
  9616.     return(0);
  9617. #else
  9618. #ifdef MINIX2
  9619.     return(0);
  9620. #else
  9621. #ifdef UTS24
  9622.     return(0);
  9623. #else
  9624. #ifdef BSD29
  9625.     return(0);
  9626. #else
  9627.     long lseek();
  9628.     static struct nlist nl[] = {
  9629.         {PROCNAME},
  9630.         {NPROCNAME},
  9631.         {""}
  9632.     };
  9633.     static struct proc *pp;
  9634.     char *qaddr, *p, c;
  9635.     int m;
  9636.     PID_T pid, me;
  9637.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  9638.     int catch();
  9639.  
  9640.     me = getpid();
  9641.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  9642.     nlist(BOOTNAME, nl);
  9643.     if (nl[0].n_type == 0) err("proc array");
  9644.  
  9645.     if (nl[1].n_type == 0) err("nproc");
  9646.  
  9647.     lseek(m, (long)(nl[1].n_value), 0);
  9648.     read (m, &xproc, sizeof(xproc));
  9649.     saval = signal(SIGALRM, catch);
  9650.     if ((pid = fork()) == 0) {
  9651.         while(1)
  9652.             read(tty, &c, 1);
  9653.     }
  9654.     alarm(2);
  9655.  
  9656.     if(setjmp(jjbuf) == 0) {
  9657.         while(1)
  9658.       read(tty, &c, 1);
  9659.     }
  9660.     signal(SIGALRM, SIG_DFL);
  9661.  
  9662. #ifdef DIRECT
  9663.     pp = (struct proc *) nl[0].n_value;
  9664. #else
  9665.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  9666.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  9667. #endif
  9668.     lseek(m, (long)(nl[1].n_value), 0);
  9669.     read(m, &xproc, sizeof(xproc));
  9670.  
  9671.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  9672.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  9673.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  9674.         err("read proc table");
  9675.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  9676.         if (pp -> p_pid == (short) pid) goto iout;
  9677.     }
  9678.     err("no such proc");
  9679.  
  9680. iout:
  9681.     close(m);
  9682.     qaddr = (char *)(pp -> p_wchan);
  9683.     free (p);
  9684.     kill(pid, SIGKILL);
  9685.     wait((WAIT_T *)0);
  9686.     return (qaddr);
  9687. #endif
  9688. #endif
  9689. #endif
  9690. #endif
  9691. }
  9692.  
  9693. /*  More V7-support functions...  */
  9694.  
  9695. static VOID
  9696. err(s) char *s; {
  9697.     char buf[200];
  9698.  
  9699.     ckmakmsg(buf,200,"fatal error in initrawq: ", s, NULL, NULL);
  9700.     perror(buf);
  9701.     doexit(1,-1);
  9702. }
  9703.  
  9704. static VOID
  9705. catch(foo) int foo; {
  9706.     longjmp(jjbuf, -1);
  9707. }
  9708.  
  9709.  
  9710. /*  G E N B R K  --  Simulate a modem break.  */
  9711.  
  9712. #ifdef MINIX
  9713. #define BSPEED B110
  9714. #else
  9715. #ifdef MINIX2
  9716. #define BSPEED B110
  9717. #else
  9718. #define BSPEED B150
  9719. #endif /* MINIX2 */
  9720. #endif /* MINIX */
  9721.  
  9722. #ifndef MINIX2
  9723. VOID
  9724. genbrk(fn,msec) int fn, msec; {
  9725.     struct sgttyb ttbuf;
  9726.     int ret, sospeed, x, y;
  9727.  
  9728.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  9729.     sospeed = ttbuf.sg_ospeed;
  9730.     ttbuf.sg_ospeed = BSPEED;
  9731.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9732.     y = (int)strlen(brnuls);
  9733.     x = ( BSPEED * 100 ) / msec;
  9734.     if (x > y) x = y;
  9735.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9736.     ttbuf.sg_ospeed = sospeed;
  9737.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9738.     ret = write(fn, "@", 1);
  9739.     return;
  9740. }
  9741. #endif /* MINIX2 */
  9742.  
  9743. #ifdef MINIX2
  9744. int
  9745. genbrk(fn,msec) int fn, msec; {
  9746.     struct termios ttbuf;
  9747.     int ret, x, y;
  9748.     speed_t sospeed;
  9749.  
  9750.     ret = tcgetattr(fn, &ttbuf);
  9751.     sospeed = ttbuf.c_ospeed;
  9752.     ttbuf.c_ospeed = BSPEED;
  9753.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  9754.     y = (int)strlen(brnuls);
  9755.     x = ( BSPEED * 100 ) / msec;
  9756.     if (x > y) x = y;
  9757.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9758.     ttbuf.c_ospeed = sospeed;
  9759.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  9760.     ret = write(fn, "@", 1);
  9761.     return ret;
  9762. }
  9763. #endif /* MINIX2 */
  9764. #endif /* V7 */
  9765.  
  9766. /*
  9767.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  9768.  
  9769.   This routine is a merger of ttchk() and conchk().
  9770.   Call with:
  9771.     channel == 0 to check console.
  9772.     channel == 1 to check communications connection.
  9773.   and:
  9774.     fd = file descriptor.
  9775.   Returns:
  9776.    >= 0: number of characters waiting, 0 or greater,
  9777.      -1: on any kind of error,
  9778.      -2: if there is (definitely) no connection.
  9779.   Note: In UNIX we don't have to call nettchk() because a socket
  9780.   file descriptor works just like in serial i/o, ioctls and all.
  9781.   (But this will change if we add non-file-descriptor channels,
  9782.   such as IBM X.25 for AIX...)
  9783. */
  9784. static int
  9785. in_chk(channel, fd) int channel, fd; {
  9786.     int x, n = 0;            /* Workers, n = return value */
  9787.     extern int clsondisc;        /* Close on disconnect */
  9788. /*
  9789.   The first section checks to make sure we have a connection,
  9790.   but only if we're in local mode.
  9791. */
  9792. #ifdef DEBUG
  9793.     if (deblog) {
  9794.     debug(F111,"in_chk entry",ckitoa(fd),channel);
  9795.     debug(F101,"in_chk ttyfd","",ttyfd);
  9796.     debug(F101,"in_chk ttpty","",ttpty);
  9797.     }
  9798. #endif /* DEBUG */
  9799. /*
  9800.   But don't say connection is gone if we have any buffered-stuff.
  9801. */
  9802. #ifdef TTLEBUF
  9803.     debug(F101,"in_chk ttpush","",ttpush);
  9804.     if (channel == 1) {
  9805.     if (ttpush >= 0)
  9806.       n++;
  9807.     n += le_inbuf();
  9808.     if (n > 0)
  9809.       return(n);
  9810.     }
  9811. #endif /* TTLEBUF */
  9812.  
  9813. #ifdef NETPTY
  9814. #ifdef HAVE_PTYTRAP
  9815.     /* Special handling for HP-UX pty i/o */
  9816.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  9817.         if (pty_trap_handler(ttyfd) > 0) {
  9818.             ttclos(0);
  9819.             return(-2);
  9820.         }
  9821.     }
  9822. #endif /* HAVE_PTYTRAP */
  9823. #endif /* NETPTY */
  9824.  
  9825.     if (channel) {            /* Checking communications channel */
  9826.     if (ttyfd < 0) {        /* No connection */
  9827.       return(-2);            /* That's what this means */
  9828.     } else if (xlocal &&        /* In local mode */
  9829.            (!netconn        /* Serial connection or */
  9830. #ifdef TN_COMPORT
  9831.             || istncomport()    /* Telnet Com Port */
  9832. #endif /* TN_COMPORT */
  9833.            ) && ttcarr != CAR_OFF /* with CARRIER WATCH ON (or AUTO) */
  9834. #ifdef COMMENT
  9835. #ifdef MYREAD
  9836. /*
  9837.   Seems like this would be a good idea but it prevents C-Kermit from
  9838.   popping back to the prompt automatically when carrier drops.  However,
  9839.   commenting this out prevents us from seeing the NO CARRIER message.
  9840.   Needs more work...
  9841. */
  9842.            && my_count < 1    /* Nothing in our internal buffer */
  9843. #endif /* MYREAD */
  9844. #endif /* COMMENT */
  9845.            ) {
  9846.         int x;
  9847.         x = ttgmdm();        /* So get modem signals */
  9848.         debug(F101,"in_chk close-on-disconnect","",clsondisc);
  9849.         if (x > -1) {        /* Check for carrier */
  9850.         if (!(x & BM_DCD)) {    /* No carrier */
  9851.             debug(F101,"in_chk carrier lost","",x);
  9852.             if (clsondisc)    /* If "close-on-disconnect" */
  9853.               ttclos(0);    /* close device & release lock. */
  9854.             return(-2);        /* This means "disconnected" */
  9855.         }
  9856.         /* In case I/O to device after CD dropped always fails */
  9857.         /* as in Debian Linux 2.1 and Unixware 2.1... */
  9858.         } else {
  9859.             debug(F101,"in_chk ttgmdm I/O error","",errno);
  9860.             debug(F101,"in_chk ttgmdm gotsigs","",gotsigs);
  9861.             if (gotsigs) {        /* If we got signals before... */
  9862.             if (errno == 5 || errno == 6) { /* I/O error etc */
  9863.                 if (clsondisc)    /* like when modem hangs up */
  9864.               ttclos(0);
  9865.             return(-2);
  9866.             }
  9867.         }
  9868.         /* If we never got modem signals successfully on this */
  9869.         /* connection before, we can't conclude that THIS failure */
  9870.         /* means the connection was lost. */
  9871.         return(0);
  9872.         }
  9873.     }
  9874.     }
  9875.  
  9876. /* We seem to have a connection so now see if any bytes are waiting on it */
  9877.  
  9878. #ifdef CK_SSL
  9879.     if (ssl_active_flag || tls_active_flag) {
  9880.         n += SSL_pending(ssl_active_flag?ssl_con:tls_con);
  9881.         debug(F101,"in_chk SSL_pending","",n);
  9882.         if (n < 0) {
  9883.             ttclos(0);
  9884.             return(-1);
  9885.         } else if (n > 0) {
  9886.             return(n);
  9887.         }
  9888.     }
  9889. #endif /* CK_SSL */
  9890. #ifdef RLOGCODE
  9891. #ifdef CK_KERBEROS
  9892.     /* It is not safe to read any data when using encrypted Klogin */
  9893.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  9894. #ifdef KRB4
  9895.         if (ttnproto == NP_EK4LOGIN) {
  9896.             n += krb4_des_avail(ttyfd);
  9897.             debug(F101,"in_chk krb4_des_avail","",n);
  9898.         }
  9899. #endif /* KRB4 */
  9900. #ifdef KRB5
  9901.         if (ttnproto == NP_EK5LOGIN) {
  9902.             n += krb5_des_avail(ttyfd);
  9903.             debug(F101,"in_chk krb5_des_avail","",n);
  9904.         }
  9905. #ifdef KRB5_U2U
  9906.         if (ttnproto == NP_K5U2U) {
  9907.             n += krb5_u2u_avail(ttyfd);
  9908.             debug(F101,"in_chk krb5_des_avail","",n);
  9909.         }
  9910. #endif /* KRB5_U2U */
  9911. #endif /* KRB5 */
  9912.         if (n < 0)            /* Is this right? */
  9913.       return(-1);
  9914.         else
  9915.       return(n);
  9916.     }
  9917. #endif /* CK_KERBEROS */
  9918. #endif /* RLOGCODE */
  9919.  
  9920.     errno = 0;                /* Reset this so we log good info */
  9921. #ifdef FIONREAD
  9922.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  9923. #ifdef DEBUG                /* (the more the better) */
  9924.     if (deblog) {
  9925.     debug(F101,"in_chk FIONREAD return code","",x);
  9926.     debug(F101,"in_chk FIONREAD count","",n);
  9927.     debug(F101,"in_chk FIONREAD errno","",errno);
  9928.     }
  9929. #endif /* DEBUG */
  9930. #else /* FIONREAD not defined */
  9931. /*
  9932.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  9933.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  9934.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  9935.   that I looked at, but it is needed to prevent the call from blocking), and
  9936.   the msghdr struct differs from place to place, so we would need another
  9937.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  9938.   only other known method of asking the OS for the *number* of characters
  9939.   available for reading.
  9940. */
  9941. #ifdef V7                /* UNIX V7: look in kernel memory */
  9942. #ifdef MINIX
  9943.     n = 0;                /* But not in MINIX */
  9944. #else
  9945. #ifdef MINIX2
  9946.     n = 0;
  9947. #else
  9948.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  9949.     x = read(kmem[TTY], &n, sizeof(int));
  9950.     if (x != sizeof(int))
  9951.       n = 0;
  9952. #endif /* MINIX2 */
  9953. #endif /* MINIX */
  9954. #else /* Not V7 */
  9955. #ifdef PROVX1
  9956.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  9957.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  9958.     if (x < 0) n = 0;
  9959. #else
  9960. #ifdef MYREAD
  9961. /*
  9962.   Here we skip all the undependable and expensive calls below if we
  9963.   already have something in our internal buffer.  This tends to work quite
  9964.   nicely, so the only really bad case remaining is the one in which neither
  9965.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  9966. */
  9967.     if (channel != 0 && my_count > 0) {
  9968.     debug(F101,"in_chk buf my_count","",my_count);
  9969.     n = my_count;            /* n was 0 before we got here */
  9970.     return(n);
  9971.     }
  9972. #endif /* MYREAD */
  9973. /*
  9974.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  9975.   not how much, so these should be used only as a final resort.  Especially
  9976.   since these calls tend to add a lot overhead.
  9977. */
  9978. #ifdef RDCHK                /* This mostly SCO-specific */
  9979.     n = rdchk(fd);
  9980.     debug(F101,"in_chk rdchk","",n);
  9981. #else /* No RDCHK */
  9982. #ifdef SELECT
  9983. #ifdef Plan9
  9984.     /* Only allows select on the console ... don't ask */
  9985.     if (channel == 0)
  9986. #endif /* Plan9 */
  9987.       {
  9988.     fd_set rfds;            /* Read file descriptors */
  9989. #ifdef BELLV10
  9990.     FD_ZERO(rfds);            /* Initialize them */
  9991.     FD_SET(fd,rfds);        /* We want to look at this fd */
  9992. #else
  9993.     FD_ZERO(&rfds);            /* Initialize them */
  9994.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  9995.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  9996. #endif /* BELLV10 */
  9997. #ifdef Plan9
  9998.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9999.     debug(F101,"in_chk Plan 9 select","",n);
  10000. #else
  10001. #ifdef BELLV10
  10002.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  10003.     debug(F101,"in_chk BELLV10 select","",n);
  10004. #else
  10005. #ifdef BSD44
  10006.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10007.     debug(F101,"in_chk BSD44 select","",n);
  10008. #else
  10009. #ifdef BSD43
  10010.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10011.     debug(F101,"in_chk BSD43 select","",n);
  10012. #else
  10013. #ifdef SOLARIS
  10014.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10015.     debug(F101,"in_chk SOLARIS select","",n);
  10016. #else
  10017. #ifdef QNX6
  10018.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10019.     debug(F101,"in_chk QNX6 select","",n);
  10020. #else
  10021. #ifdef QNX
  10022.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10023.     debug(F101,"in_chk QNX select","",n);
  10024. #else
  10025. #ifdef COHERENT
  10026.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10027.     debug(F101,"in_chk COHERENT select","",n);
  10028. #else
  10029. #ifdef SVR4
  10030.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10031.     debug(F101,"in_chk SVR4 select","",n);
  10032. #else
  10033. #ifdef __linux__
  10034.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10035.     debug(F101,"in_chk LINUX select","",n);
  10036. #ifdef OSF
  10037.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10038.     debug(F101,"in_chk OSF select","",n);
  10039. #else
  10040.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  10041.     debug(F101,"in_chk catchall select","",n);
  10042. #endif /* OSF */
  10043. #endif /* __linux__ */
  10044. #endif /* SVR4 */
  10045. #endif /* COHERENT */
  10046. #endif /* QNX */
  10047. #endif /* QNX6 */
  10048. #endif /* SOLARIS */
  10049. #endif /* BSD43 */
  10050. #endif /* BSD44 */
  10051. #endif /* BELLV10 */
  10052. #endif /* Plan9 */
  10053.     }
  10054. #else  /* Not SELECT */
  10055. #ifdef CK_POLL
  10056.     {
  10057.       struct pollfd pfd;
  10058.  
  10059.       pfd.fd = fd;
  10060.       pfd.events = POLLIN;
  10061.       pfd.revents = 0;
  10062.       n = poll(&pfd, 1, 0);
  10063.       debug(F101,"in_chk poll","",n);
  10064.       if ((n > 0) && (pfd.revents & POLLIN))
  10065.     n = 1;
  10066.     }
  10067. #endif /* CK_POLL */
  10068. #endif /* SELECT */
  10069. #endif /* RDCHK */
  10070. #endif /* PROVX1 */
  10071. #endif /* V7 */
  10072. #endif /* FIONREAD */
  10073.  
  10074. /* From here down, treat console and communication device differently... */
  10075.  
  10076.     if (channel == 0) {            /* Console */
  10077.  
  10078. #ifdef SVORPOSIX
  10079. #ifndef FIONREAD
  10080. #ifndef SELECT
  10081. #ifndef CK_POLL
  10082. #ifndef RDCHK
  10083. /*
  10084.   This is the hideous hack used in System V and POSIX systems that don't
  10085.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  10086.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  10087.   only on the console.
  10088. */
  10089.     if (conesc) {            /* Escape character typed == SIGQUIT */
  10090.         debug(F100,"in_chk conesc","",conesc);
  10091.         conesc = 0;
  10092.         signal(SIGQUIT,esctrp);    /* Restore signal */
  10093.         n += 1;
  10094.     }
  10095. #endif /* RDCHK */
  10096. #endif /* CK_POLL */
  10097. #endif /* SELECT */
  10098. #endif /* FIONREAD */
  10099. #endif /* SVORPOSIX */
  10100.  
  10101.     return(n);            /* Done with console */
  10102.     }
  10103.  
  10104.     if (channel != 0) {            /* Communications connection */
  10105.  
  10106. #ifdef MYREAD
  10107. #ifndef FIONREAD
  10108. /*
  10109.   select() or rdchk(), etc, has told us that something is waiting, but we
  10110.   don't know how much.  So we do a read to get it and then we know.  Note:
  10111.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  10112.   it should be safe in this case since the OS tells us at least one byte is
  10113.   waiting to be read, and MYREAD reads return as much as is there without
  10114.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  10115.   FIONREAD deliberately undefined) show this to be true.
  10116. */
  10117.     debug(F101,"in_chk read my_count","",my_count);
  10118.     debug(F101,"in_chk read n","",n);
  10119.     if (n > 0 && my_count == 0) {
  10120.         /* This also catches disconnects etc */
  10121.         /* Do what mygetbuf does except don't grab a character */
  10122.         my_count = myfillbuf();
  10123.         my_item = -1;        /* ^^^ */
  10124.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  10125.         if (my_count < 0)
  10126.           return(-1);
  10127.         else
  10128.           n = 0;            /* NB: n is replaced by my_count */
  10129.     }
  10130. #endif /* FIONREAD */
  10131. /*
  10132.   Here we add whatever we think is unread to what is still in our
  10133.   our internal buffer.  Thus the importance of setting n to 0 just above.
  10134. */
  10135.     debug(F101,"in_chk my_count","",my_count);
  10136.     debug(F101,"in_chk n","",n);
  10137.     if (my_count > 0)
  10138.       n += my_count;
  10139. #endif /* MYREAD */
  10140.     }
  10141.     debug(F101,"in_chk result","",n);
  10142.  
  10143.     /* Errors here don't prove the connection has dropped so just say 0 */
  10144.  
  10145.     return(n < 0 ? 0 : n);
  10146. }
  10147.  
  10148.  
  10149. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  10150.  
  10151. int
  10152. ttchk() {
  10153.     int fd;
  10154. #ifdef NETCMD
  10155.     if (ttpipe)
  10156.       fd = fdin;
  10157.     else
  10158. #endif /* NETCMD */
  10159.       fd = ttyfd;
  10160.     return(in_chk(1,fd));
  10161. }
  10162.  
  10163. /*  T T X I N  --  Get n characters from tty input buffer  */
  10164.  
  10165. /*  Returns number of characters actually gotten, or -1 on failure  */
  10166.  
  10167. /*  Intended for use only when it is known that n characters are actually */
  10168. /*  Available in the input buffer.  */
  10169.  
  10170. int
  10171. ttxin(n,buf) int n; CHAR *buf; {
  10172.     register int x = 0, c = -2;
  10173. #ifdef TTLEBUF
  10174.     register int i = 0;
  10175. #endif /* TTLEBUF */
  10176.     int fd;
  10177.  
  10178.     if (n < 1)                /* Nothing to do */
  10179.       return(0);
  10180.  
  10181. #ifdef TTLEBUF
  10182.     if (ttpush >= 0) {
  10183.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  10184.         ttpush = -1;            /* Clear the push buffer */
  10185.         if (ttchk() > 0)
  10186.       return(ttxin(n-1, &buf[1]) + 1);
  10187.         else
  10188.       return(1);
  10189.     }
  10190.     if (le_data) {
  10191.         while (le_inbuf() > 0) {
  10192.         if (le_getchar(&buf[i])) {
  10193.                 i++;
  10194.                 n--;
  10195.             }
  10196.         }
  10197.         if (ttchk() > 0)
  10198.       return(ttxin(n,&buf[i])+i);
  10199.         else
  10200.       return(i);
  10201.     }
  10202. #endif /* TTLEBUF */
  10203.  
  10204. #ifdef NETCMD
  10205.     if (ttpipe)
  10206.       fd = fdin;
  10207.     else
  10208. #endif /* NETCMD */
  10209.       fd = ttyfd;
  10210.  
  10211. #ifdef SUNX25
  10212.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  10213.       return(x25xin(n,buf));
  10214. #endif /* SUNX25 */
  10215.  
  10216. #ifdef IBMX25
  10217.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  10218.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  10219.     x = x25xin(n,buf);
  10220.     if (x > 0) buf[x] = '\0';
  10221.     return(x);
  10222.     }
  10223. #endif /* IBMX25 */
  10224.  
  10225. #ifdef MYREAD
  10226.     debug(F101,"ttxin MYREAD","",n);
  10227.     while (x < n) {
  10228.     c = myread();
  10229.     if (c < 0) {
  10230.         debug(F101,"ttxin myread returns","",c);
  10231.         if (c == -3) x = -1;
  10232.         break;
  10233.         }
  10234.     buf[x++] = c & ttpmsk;
  10235. #ifdef RLOGCODE
  10236. #ifdef CK_KERBEROS
  10237.         /* It is impossible to know how many characters are waiting */
  10238.         /* to be read when you are using Encrypted Rlogin or SSL    */
  10239.         /* as the transport since the number of real data bytes     */
  10240.         /* can be greater or less than the number of bytes on the   */
  10241.         /* wire which is what ttchk() returns.                      */
  10242.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  10243.       if (ttchk() <= 0)
  10244.         break;
  10245. #endif /* CK_KERBEROS */
  10246. #endif /* RLOGCODE */
  10247. #ifdef CK_SSL
  10248.         if (ssl_active_flag || tls_active_flag)
  10249.       if (ttchk() <= 0)
  10250.         break;
  10251. #endif /* CK_SSL */
  10252.     }
  10253. #else
  10254.     debug(F101,"ttxin READ","",n);
  10255.     x = read(fd,buf,n);
  10256.     for (c = 0; c < n; c++)        /* Strip any parity */
  10257.       buf[c] &= ttpmsk;
  10258. #endif /* MYREAD */
  10259.  
  10260.     debug(F101,"ttxin x","",x);        /* Done */
  10261.     if (x > 0) buf[x] = '\0';
  10262.     if (x < 0) x = -1;
  10263.     return(x);
  10264. }
  10265.  
  10266. /*  T T O L  --  Write string s, length n, to communication device.  */
  10267. /*
  10268.   Returns:
  10269.    >= 0 on success, number of characters actually written.
  10270.    -1 on failure.
  10271. */
  10272. #ifdef CK_ENCRYPTION
  10273. CHAR * xpacket = NULL;
  10274. int nxpacket = 0;
  10275. #endif /* CK_ENCRYPTION */
  10276.  
  10277. #define TTOLMAXT 5
  10278. int
  10279. ttol(s,n) int n; CHAR *s; {
  10280.     int x, len, tries, fd;
  10281. #ifdef CKXXCHAR
  10282.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  10283.     extern short dblt[];
  10284.     CHAR *p = NULL, *p2, *s2, c;
  10285.     int n2 = 0;
  10286. #endif /* CKXXCHAR */
  10287.  
  10288.     if (ttyfd < 0)            /* Not open? */
  10289.       return(-3);
  10290. #ifdef DEBUG
  10291.     if (deblog) {
  10292.     /* debug(F101,"ttol ttyfd","",ttyfd); */
  10293.     ckhexdump("ttol s",s,n);
  10294.     }
  10295. #endif /* DEBUG */
  10296.  
  10297. #ifdef NETCMD
  10298.     if (ttpipe)
  10299.       fd = fdout;
  10300.     else
  10301. #endif /* NETCMD */
  10302.       fd = ttyfd;
  10303.  
  10304. #ifdef CKXXCHAR
  10305. /*  Double any characters that must be doubled.  */
  10306.     debug(F101,"ttol dblflag","",dblflag);
  10307.     if (dblflag) {
  10308.     p = (CHAR *) malloc(n + n + 1);
  10309.     if (p) {
  10310.         s2 = s;
  10311.         p2 = p;
  10312.         n2 = 0;
  10313.         while (*s2) {
  10314.         c = *s2++;
  10315.         *p2++ = c;
  10316.         n2++;
  10317.         if (dblt[(unsigned) c] & 2) {
  10318.             *p2++ = c;
  10319.             n2++;
  10320.         }
  10321.         }
  10322.         s = p;
  10323.         n = n2;
  10324.         s[n] = '\0';
  10325.     }
  10326. #ifdef DEBUG
  10327.         ckhexdump("ttol doubled s",s,n);
  10328. #endif /* DEBUG */
  10329.     }
  10330. #endif /* CKXXCHAR */
  10331.  
  10332.     tries = TTOLMAXT;            /* Allow up to this many tries */
  10333.     len = n;                /* Remember original length */
  10334.  
  10335. #ifdef CK_ENCRYPTION
  10336. /*
  10337.   This is to avoid encrypting a packet that is already encrypted, e.g.
  10338.   when we resend a packet directly out of the packet buffer, and also to
  10339.   avoid encrypting a constant (literal) string, which can cause a memory
  10340.   fault.
  10341. */
  10342.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  10343.     int x;
  10344.     if (nxpacket < n) {
  10345.         if (xpacket) {
  10346.         free(xpacket);
  10347.         xpacket = NULL;
  10348.         nxpacket = 0;
  10349.         }
  10350.         x = n > 10240 ? n : 10240;
  10351.         xpacket = (CHAR *)malloc(x);
  10352.         if (!xpacket) {
  10353.         fprintf(stderr,"ttol malloc failure\n");
  10354.         return(-1);
  10355.         } else
  10356.           nxpacket = x;
  10357.     }
  10358.     memcpy((char *)xpacket,(char *)s,n);
  10359.     s = xpacket;
  10360.     ck_tn_encrypt((char *)s,n);
  10361.     }
  10362. #endif /* CK_ENCRYPTION */
  10363.  
  10364.     while (n > 0 &&
  10365.        (tries-- > 0
  10366. #ifdef CK_ENCRYPTION
  10367.         /* keep trying if we are encrypting */
  10368.         || TELOPT_ME(TELOPT_ENCRYPTION)
  10369. #endif /* CK_ENCRYPTION */
  10370.             )) {            /* Be persistent */
  10371.     debug(F101,"ttol try","",TTOLMAXT - tries);
  10372. #ifdef BEOSORBEBOX
  10373.         if (netconn && !ttpipe && !ttpty)
  10374.       x = nettol((char *)s,n);    /* Write string to device */
  10375.         else
  10376. #endif /* BEOSORBEBOX */
  10377. #ifdef IBMX25
  10378.       if (ttnet == NET_IX25)
  10379.         /*
  10380.          * this is a more controlled way of writing to X25
  10381.          * STREAMS, however write should also work!
  10382.          */
  10383.         x = x25write(ttyfd, s, n);
  10384.       else
  10385. #endif /* IBMX25 */
  10386. #ifdef CK_SSL
  10387.         if (ssl_active_flag || tls_active_flag) {
  10388.         int error;
  10389.         /* Write using SSL */
  10390.                 ssl_retry:
  10391.         if (ssl_active_flag)
  10392.                   x = SSL_write(ssl_con, s, n);
  10393.         else
  10394.                   x = SSL_write(tls_con, s, n);
  10395.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  10396.                 case SSL_ERROR_NONE:
  10397.                     if (x == n)
  10398.               return(len);
  10399.                     s += x;
  10400.                     n -= x;
  10401.                     goto ssl_retry;
  10402.           case SSL_ERROR_WANT_WRITE:
  10403.           case SSL_ERROR_WANT_READ:
  10404.             x = 0;
  10405.             break;
  10406.           case SSL_ERROR_SYSCALL:
  10407.                     if (x != 0)
  10408.               return(-1);
  10409.           case SSL_ERROR_WANT_X509_LOOKUP:
  10410.           case SSL_ERROR_SSL:
  10411.           case SSL_ERROR_ZERO_RETURN:
  10412.           default:
  10413.             ttclos(0);
  10414.             return(-3);
  10415.         }
  10416.         } else
  10417. #endif /* CK_SSL */
  10418. #ifdef CK_KERBEROS
  10419. #ifdef KRB4
  10420. #ifdef RLOGCODE
  10421.         if (ttnproto == NP_EK4LOGIN) {
  10422.         return(krb4_des_write(ttyfd,s,n));
  10423.         } else
  10424. #endif /* RLOGCODE */
  10425. #endif /* KRB4 */
  10426. #ifdef KRB5
  10427. #ifdef RLOGCODE
  10428.             if (ttnproto == NP_EK5LOGIN) {
  10429.                 return(krb5_des_write(ttyfd,(char *)s,n,0));
  10430.             } else
  10431. #endif /* RLOGCODE */
  10432. #ifdef KRB5_U2U
  10433.             if (ttnproto == NP_K5U2U) {
  10434.                 return(krb5_u2u_write(ttyfd,(char *)s,n));
  10435.             } else
  10436. #endif /* KRB5_U2U */
  10437. #endif /* KRB5 */
  10438. #endif /* CK_KERBEROS */
  10439.           x = write(fd,s,n);    /* Write string to device */
  10440.  
  10441.     if (x == n) {            /* Worked? */
  10442.         debug(F101,"ttol ok","",x);    /* OK */
  10443. #ifdef CKXXCHAR
  10444.         if (p) free(p);
  10445. #endif /* CKXXCHAR */
  10446.         return(len);        /* Done */
  10447.     } else if (x < 0) {        /* No, got error? */
  10448.         debug(F101,"ttol write error","",errno);
  10449. #ifdef EWOULDBLOCK
  10450.         if (errno == EWOULDBLOCK) {
  10451.         msleep(10);
  10452.         continue;
  10453.         } else
  10454. #endif /* EWOULDBLOCK */
  10455. #ifdef TCPSOCKET
  10456.         if (netconn && ttnet == NET_TCPB) {
  10457.         debug(F101,"ttol TCP error","",errno);
  10458.         ttclos(0);        /* Close the connection. */
  10459.         x = -3;
  10460.         }
  10461. #endif /* TCPSOCKET */
  10462. #ifdef CKXXCHAR
  10463.         if (p) free(p);
  10464. #endif /* CKXXCHAR */
  10465.         return(x);
  10466.     } else {            /* No error, so partial success */
  10467.         debug(F101,"ttol partial","",x); /* This never happens */
  10468.         s += x;            /* Point to part not written yet */
  10469.         n -= x;            /* Adjust length */
  10470.         if (x > 0) msleep(10);    /* Wait 10 msec */
  10471.     }                /* Go back and try again */
  10472.     }
  10473. #ifdef CKXXCHAR
  10474.     if (p) free(p);
  10475. #endif /* CKXXCHAR */
  10476.     return(n < 1 ? len : -1);        /* Return the results */
  10477. }
  10478.  
  10479. /*  T T O C  --  Output a character to the communication line  */
  10480.  
  10481. /*
  10482.  This function should only be used for interactive, character-mode operations,
  10483.  like terminal connection, script execution, dialer i/o, where the overhead
  10484.  of the signals and alarms does not create a bottleneck.
  10485. */
  10486. int
  10487. #ifdef CK_ANSIC
  10488. ttoc(char c)
  10489. #else
  10490. ttoc(c) char c;
  10491. #endif /* CK_ANSIC */
  10492. /* ttoc */ {
  10493. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  10494.     int xx, fd;
  10495.  
  10496.     if (ttyfd < 0)            /* Check for not open. */
  10497.       return(-1);
  10498.  
  10499. #ifdef NETCMD
  10500.     if (ttpipe)
  10501.       fd = fdout;
  10502.     else
  10503. #endif /* NETCMD */
  10504.       fd = ttyfd;
  10505.  
  10506.     c &= 0xff;
  10507.     /* debug(F101,"ttoc","",(CHAR) c); */
  10508.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10509.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  10510.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  10511.     /* debug(F101,"ttoc alarm","",xx); */
  10512.     if (
  10513. #ifdef CK_POSIX_SIG
  10514.     sigsetjmp(sjbuf,1)
  10515. #else
  10516.     setjmp(sjbuf)
  10517. #endif /* CK_POSIX_SIG */
  10518.     ) {        /* Timer went off? */
  10519.     ttimoff();            /* Yes, cancel this alarm. */
  10520.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  10521.         /* debug(F100,"ttoc timeout","",0); */
  10522. #ifdef NETCONN
  10523.     if (!netconn) {
  10524. #endif /* NETCONN */
  10525.         debug(F101,"ttoc timeout","",c);
  10526.         if (ttflow == FLO_XONX) {
  10527.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  10528. #ifndef Plan9
  10529. #ifdef POSIX
  10530.         /* POSIX way to unstick. */
  10531.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  10532. #else
  10533. #ifdef BSD4                /* Berkeley way to do it. */
  10534. #ifdef TIOCSTART
  10535. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  10536.         {
  10537.           int x = 0;
  10538.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  10539.         }
  10540. #endif /* TIOCSTART */
  10541. #endif /* BSD4 */
  10542.                     /* Is there a Sys V way to do this? */
  10543. #endif /* POSIX */
  10544. #endif /* Plan9 */
  10545.         }
  10546. #ifdef NETCONN
  10547.         }
  10548. #endif /* NETCONN */
  10549.     return(-1);            /* Return failure code. */
  10550.     } else {
  10551.         int rc;
  10552. #ifdef BEOSORBEBOX
  10553. #ifdef NETCONN
  10554.         if (netconn && !ttpipe && !ttpty)
  10555.       rc = nettoc(c);
  10556.         else
  10557. #endif /*  BEOSORBEBOX */
  10558. #endif /* NETCONN */
  10559. #ifdef CK_ENCRYPTION
  10560.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  10561.         ck_tn_encrypt(&c,1);
  10562. #endif /* CK_ENCRYPTION */
  10563. #ifdef IBMX25
  10564.     /* riehm: maybe this isn't necessary after all. Test program
  10565.      * worked fine with data being sent and retrieved with normal
  10566.      * read's and writes!
  10567.      */
  10568.     if (ttnet == NET_IX25)
  10569.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  10570.     else
  10571. #endif /* IBMX25 */
  10572. #ifdef CK_SSL
  10573.       if (ssl_active_flag || tls_active_flag) {
  10574.           int error;
  10575.           /* Write using SSL */
  10576.           if (ssl_active_flag)
  10577.                 rc = SSL_write(ssl_con, &c, 1);
  10578.           else
  10579.                 rc = SSL_write(tls_con, &c, 1);
  10580.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  10581.         case SSL_ERROR_NONE:
  10582.           break;
  10583.         case SSL_ERROR_WANT_WRITE:
  10584.         case SSL_ERROR_WANT_READ:
  10585.           rc = 0;
  10586.           break;
  10587.         case SSL_ERROR_SYSCALL:
  10588.           if (rc != 0)
  10589.             return(-1);
  10590.         case SSL_ERROR_WANT_X509_LOOKUP:
  10591.         case SSL_ERROR_SSL:
  10592.         case SSL_ERROR_ZERO_RETURN:
  10593.         default:
  10594.           ttclos(0);
  10595.           return(-1);
  10596.           }
  10597.       } else
  10598. #endif /* CK_SSL */
  10599. #ifdef CK_KERBEROS
  10600. #ifdef KRB4
  10601. #ifdef RLOGCODE
  10602.       if (ttnproto == NP_EK4LOGIN) {
  10603.           rc = (krb4_des_write(ttyfd,(char *)&c,1) == 1);
  10604.       } else
  10605. #endif /* RLOGCODE */
  10606. #endif /* KRB4 */
  10607. #ifdef KRB5
  10608. #ifdef RLOGCODE
  10609.           if (ttnproto == NP_EK5LOGIN) {
  10610.               rc = (krb5_des_write(ttyfd,&c,1,0) == 1);
  10611.           } else
  10612. #endif /* RLOGCODE */
  10613. #ifdef KRB5_U2U
  10614.           if (ttnproto == NP_K5U2U) {
  10615.               rc = (krb5_u2u_write(ttyfd,&c,1) == 1);
  10616.           } else
  10617. #endif /* KRB5_U2U */
  10618. #endif /* KRB5 */
  10619. #endif /* CK_KERBEROS */
  10620.         rc = write(fd,&c,1);    /* Try to write the character. */
  10621.     if (rc < 1) {            /* Failed */
  10622.         ttimoff();            /* Turn off the alarm. */
  10623.         alarm(xx);            /* Restore previous alarm. */
  10624.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  10625.         return(-1);            /* and return the error code. */
  10626.     }
  10627.     }
  10628.     ttimoff();                /* Success, turn off the alarm. */
  10629.     alarm(xx);                /* Restore previous alarm. */
  10630.     return(0);                /* Return good code. */
  10631. }
  10632.  
  10633. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  10634. /*
  10635.   Reads up to "max" characters from the connection, terminating on:
  10636.     (a) the packet length field if the "turn" argument is zero, or
  10637.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  10638.     (c) a certain number of Ctrl-C's in a row
  10639.  
  10640.   Returns:
  10641.     >= 0, the number of characters read upon success;
  10642.     -1 if "max" exceeded, timeout, or other correctable error;
  10643.     -2 on user interruption (c);
  10644.     -3 on fatal error like connection lost.
  10645.  
  10646.   The name of this routine dates from the early days when Kermit packets
  10647.   were, indeed, always lines of text.  That was before control-character
  10648.   unprefixing and length-driven packet framing were introduced, which this
  10649.   version handle.  NB: this routine is ONLY for reading incoming Kermit
  10650.   packets, nothing else.  To read other kinds of incoming material, use
  10651.   ttinc() or ttxin().
  10652.  
  10653.   The bytes that were input are copied into "dest" with their parity bits
  10654.   stripped if parity was selected.  Returns the number of bytes read.
  10655.   Bytes after the eol are available upon the next call to this function.
  10656.  
  10657.   The idea is to minimize the number of system calls per packet, and also to
  10658.   minimize timeouts.  This function is the inner loop of the protocol and must
  10659.   be as efficient as possible.  The current strategy is to use myread(), a
  10660.   macro to manage buffered (and generally nonblocking) reads.
  10661.  
  10662.   WARNING: This function calls parchk(), which is defined in another module.
  10663.   Normally, ckutio.c does not depend on code from any other module, but there
  10664.   is an exception in this case because all the other ck?tio.c modules also
  10665.   need to call parchk(), so it's better to have it defined in a common place.
  10666. */
  10667. #ifdef CTRLC
  10668. #undef CTRLC
  10669. #endif /* CTRLC */
  10670. #define CTRLC '\03'
  10671. /*
  10672.   We have four different declarations here because:
  10673.   (a) to allow Kermit to be built without the automatic parity sensing feature
  10674.   (b) one of each type for ANSI C, one for non-ANSI.
  10675. */
  10676. #ifndef NOXFER
  10677.  
  10678. static int pushedback = 0;
  10679.  
  10680. int
  10681. #ifdef PARSENSE
  10682. #ifdef CK_ANSIC
  10683. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  10684. #else
  10685. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  10686. #endif /* CK_ANSIC */
  10687. #else /* not PARSENSE */
  10688. #ifdef CK_ANSIC
  10689. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  10690. #else
  10691. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  10692. #endif /* CK_ANSIC */
  10693. #endif /* PARSENSE */
  10694. /* ttinl */ {
  10695.  
  10696. #ifndef MYREAD
  10697.     CHAR ch, dum;
  10698. #endif /* MYREAD */
  10699. #ifdef PARSENSE
  10700.     int pktlen = -1;
  10701.     int lplen = 0;
  10702.     int havelen = 0;
  10703. #endif /* PARSENSE */
  10704.     int fd;
  10705.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  10706. #ifdef CKXXCHAR
  10707.     extern short dblt[];        /* Ignore-character table */
  10708.     extern int ignflag;
  10709. #endif /* CKXXCHAR */
  10710. #ifdef TCPSOCKET
  10711.     extern CHAR stchr;
  10712. #endif /* TCPSOCKET */
  10713.     int x;
  10714. #ifdef STREAMING
  10715.     extern int streaming;
  10716.     extern int sndtyp;
  10717. #endif /* STREAMING */
  10718.  
  10719.     if (ttyfd < 0) return(-3);          /* Not open. */
  10720. /*
  10721.   In February 2007 I fixed ttinl() to work better under the truly awful
  10722.   conditions encountered by the AM-APEX oceanographic floats that gather
  10723.   hurricane data and phone home using Iridium satellite modems, which under
  10724.   certain conditions, can send two packets back to back after a long pause.
  10725.   In this case the second packet would be ignored because the SOH was skipped
  10726.   due to the ttflui() call.  But the reworked lookahead/pushback logic broke
  10727.   Kermit transfers on encrypted connections.  This was fixed 12-13 August
  10728.   2007.  All of this happened after 8.0.212 Dev.27 was released and before
  10729.   Dev.28, so no harm done other than the delay.
  10730. */
  10731.     debug(F101,"ttinl max","",max);
  10732.     debug(F101,"ttinl timo","",timo);
  10733.  
  10734. #ifdef NETCMD
  10735.     if (ttpipe)
  10736.       fd = fdin;
  10737.     else
  10738. #endif /* NETCMD */
  10739.       fd = ttyfd;
  10740.  
  10741. #ifdef COMMENT
  10742.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  10743.       return(-1);
  10744. #endif /* COMMENT */
  10745.  
  10746.     *dest = '\0';                       /* Clear destination buffer */
  10747.     if (timo < 0) timo = 0;        /* Safety */
  10748.     if (timo) {                /* Don't time out if timo == 0 */
  10749.     int xx;
  10750.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10751.     xx = alarm(timo);        /* Set it. */
  10752.     debug(F101,"ttinl alarm","",xx);
  10753.     }
  10754.     if (
  10755. #ifdef CK_POSIX_SIG
  10756.     sigsetjmp(sjbuf,1)
  10757. #else
  10758.     setjmp(sjbuf)
  10759. #endif /* CK_POSIX_SIG */
  10760.     ) {                /* Timer went off? */
  10761.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  10762.     /* debug(F110," with",(char *) dest,0); */
  10763.     ttimoff();            /* Turn off timer */
  10764.     return(-1);            /* and return error code. */
  10765.     } else {
  10766.     register int i, n = -1;        /* local variables */
  10767.     int ccn = 0;
  10768. #ifdef PARSENSE
  10769.     register int flag = 0;
  10770.     debug(F000,"ttinl start","",start);
  10771. #endif /* PARSENSE */
  10772.  
  10773.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  10774.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  10775.  
  10776. /* Now read into destination, stripping parity and looking for the */
  10777. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  10778.  
  10779.     i = 0;                /* Destination index */
  10780.     debug(F101,"ttinl eol","",eol);
  10781.  
  10782.     while (i < max-1) {
  10783. #ifdef MYREAD
  10784.         errno = 0;
  10785.         /* On encrypted connections myread returns encrypted bytes */
  10786.         n = myread();
  10787.         debug(F000,"TTINL myread char","",n);
  10788.         if (n < 0) {    /* Timeout or i/o error? */
  10789. #ifdef DEBUG
  10790.         if (deblog) {
  10791.             debug(F101,"ttinl myread failure, n","",n);
  10792.             debug(F101,"ttinl myread errno","",errno);
  10793.         }
  10794. #endif /* DEBUG */
  10795.         /* Don't let EINTR break packets. */
  10796.         if (n == -3) {
  10797.             if (errno == EINTR && i > 0) {
  10798.             debug(F111,"ttinl EINTR myread i","continuing",i);
  10799.             continue;
  10800.             } else {
  10801.             debug(F110,"ttinl non-EINTR -3","closing",0);
  10802.             wasclosed = 1;
  10803.             ttimoff();    /* Turn off timer */
  10804.             ttclos(0);
  10805.             return(n);
  10806.             }
  10807.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  10808.             /* Here we try to catch broken network connections */
  10809.             /* even when ioctl() and read() do not catch them */
  10810.             debug(F111,"ttinl network myread failure","closing",n);
  10811.             wasclosed = 1;
  10812.             ttimoff();
  10813.             ttclos(0);
  10814.             return(-3);
  10815.         }
  10816. #ifdef STREAMING
  10817.         /* Streaming and no data to read */
  10818.         else if (n == 0 && streaming && sndtyp == 'D')
  10819.           return(0);
  10820. #endif /* STREAMING */
  10821.         break;            /* Break out of while loop */
  10822.         }
  10823.  
  10824. #else /* not MYREAD (is this code used anywhere any more?) */
  10825. /*
  10826.   The non-MYREAD code dates from the 1980s and was needed on certain platforms
  10827.   where there were no nonblocking reads.  -fdc, 2007/02/22.
  10828. */
  10829.         if ((n = read(fd, &n, 1)) < 1)
  10830.           break;            /* Error - break out of while loop */
  10831.  
  10832. #endif /* MYREAD */
  10833.  
  10834.         /* Get here with char in n */
  10835.  
  10836. #ifdef CK_ENCRYPTION
  10837.         if (TELOPT_U(TELOPT_ENCRYPTION) && !pushedback) {
  10838.         CHAR ch = n;
  10839.         ck_tn_decrypt((char *)&ch,1);
  10840.         n = ch;
  10841.         debug(F000,"TTINL decryp char","",n);
  10842.         }
  10843.         pushedback = 0;
  10844. #endif /* CK_ENCRYPTION */
  10845.  
  10846. #ifdef TCPSOCKET
  10847.         if (n == IAC &&        /* Handle Telnet options */
  10848.         ((xlocal && netconn && IS_TELNET()) ||
  10849.         (!xlocal && sstelnet))) {
  10850.         n = tt_tnopt(n);
  10851.         if (n < 0)
  10852.           return(n);
  10853. #ifndef NOPARSEN
  10854.         else if (n == 1)
  10855.           start = stchr;
  10856. #endif /* NOPARSEN */
  10857.         if (n != 255)        /* No data - go back for next char */
  10858.           continue;
  10859.         }                /* Quoted IAC - keep going */
  10860. #endif /* TCPSOCKET */
  10861.  
  10862. #ifdef CKXXCHAR
  10863.         if (ignflag)
  10864.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  10865.         continue;
  10866. #endif /* CKXXCHAR */
  10867. /*
  10868.   Use parity mask, rather than always stripping parity, to check for
  10869.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  10870.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  10871.   unlikely due to run-length encoding.)
  10872. */
  10873.         /* Check cancellation */
  10874.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  10875.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  10876.             if (timo) {        /* Clear timer. */
  10877.             ttimoff();
  10878.             }
  10879.             if (xfrchr < 32)
  10880.               printf("^%c...\r\n",(char)(xfrchr+64));
  10881.             else
  10882.               printf("Canceled...\r\n");
  10883.             return(-2);
  10884.         }
  10885.         } else ccn = 0;        /* No cancellation, reset counter, */
  10886.  
  10887. #ifdef PARSENSE
  10888. /*
  10889.   Restructured code allows for a new packet to appear somewhere in the
  10890.   middle of a previous one.  -fdc, 24 Feb 2007.
  10891. */
  10892.         if ((n & sopmask) == start) { /* Start of Packet */
  10893.         debug(F101,"ttinl SOP i","",i);
  10894.         flag = 1;        /* Flag that we are in a packet */
  10895.         havelen = 0;        /* Invalidate previous length */
  10896.         pktlen = -1;        /* (if any) in case we were */
  10897.         lplen = 0;        /* alread processand a packet */
  10898.         i = 0;            /* and reset the dest buffer pointer */
  10899.         }
  10900.         if (flag == 0) {        /* No SOP yet... */
  10901.         debug(F000,"ttinl skipping","",n);
  10902.         continue;
  10903.         }
  10904.         dest[i++] = n & ttpmsk;
  10905. /*
  10906.   If we have not been instructed to wait for a turnaround character, we
  10907.   can go by the packet length field.  If turn != 0, we must wait for the
  10908.   end of line (eol) character before returning.  This is an egregious
  10909.   violation of all principles of layering...
  10910. */
  10911.         if (!havelen) {
  10912.         if (i == 2) {
  10913.             pktlen = xunchar(dest[1] & 0x7f);
  10914.             if (pktlen > 1) {
  10915.             havelen = 1;
  10916.             debug(F101,"ttinl pktlen value","",pktlen);
  10917.             }
  10918.         } else if (i == 5 && pktlen == 0) {
  10919.             lplen = xunchar(dest[4] & 0x7f);
  10920.         } else if (i == 6 && pktlen == 0) {
  10921.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  10922.             havelen = 1;
  10923.             debug(F101,"ttinl extended length","",pktlen);
  10924.         }
  10925.         }
  10926.  
  10927. /*
  10928.   Suppose we looked at the sequence number here and found it was out of
  10929.   range?  This would mean either (a) incoming packets had SOP unprefixed
  10930.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  10931.   practice, let's ignore it.  So what should we do here if we know the
  10932.   packet is damaged?
  10933.  
  10934.    1. Nothing -- keep trying to read the packet till we find what we think
  10935.       is the end, or we time out, and let the upper layer decide what to
  10936.       do.  But since either the packet is corrupt or we are out of sync,
  10937.       our criterion for finding the end does not apply and we are likely
  10938.       to time out (or swallow a piece of the next packet) if our assumed
  10939.       length is too long.  (This was the behavior prior to version 7.0.)
  10940.  
  10941.    2. set flag = 0 and continue?  This would force us to wait for the
  10942.       next packet to come in, and therefore (in the nonwindowing case),
  10943.       would force a timeout in the other Kermit.
  10944.  
  10945.    3. set flag = 0 and continue, but only if the window size is > 1 and
  10946.       the window is not blocked?  Talk about cheating!
  10947.  
  10948.    4. Return a failure code and let the upper layer decide what to do.
  10949.       This should be equivalent to 3, but without the cheating.  So let's
  10950.       do it that way...  But note that we must ignore the parity bit
  10951.       in case this is the first packet and we have not yet run parchk().
  10952. */
  10953.         if (i == 3) {        /* Peek at sequence number */
  10954.         x = xunchar((dest[i-1] & 0x7f)); /* If it's not in range... */
  10955.         if (x < 0 || x > 63) {
  10956.             debug(F111,"ttinl bad seq",dest,x);
  10957.             if (timo) ttimoff();
  10958.             return(-1);        /* return a nonfatal error */
  10959.         }
  10960.         }
  10961.  
  10962. #else /* PARSENSE */
  10963.         dest[i++] = n & ttpmsk;
  10964. #endif /* PARSENSE */
  10965.  
  10966.     /* Check for end of packet */
  10967.  
  10968.         if (
  10969. #ifdef PARSENSE
  10970. /*
  10971.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  10972.   This allows packet terminators and handshake characters to appear
  10973.   literally inside a packet data field.
  10974. */
  10975.         (havelen && (i > pktlen+1) &&
  10976.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  10977. #else /* !PARSENSE */
  10978. /*
  10979.   Built without PARSENSE, so just look for packet terminator.
  10980. */
  10981.         ((n & 0x7f) == eol)
  10982. #endif /* PARSENSE */
  10983.         ) {
  10984. /*
  10985.   Here we have either read the last byte of the packet based on its length
  10986.   field, or else we have read the packet terminator (eol) or the half-duplex
  10987.   line-turnaround char (turn).
  10988. */
  10989. #ifndef PARSENSE
  10990.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10991.         dest[i] = '\0';        /* Yes, terminate the string, */
  10992.         /* debug(F101,"ttinl i","",i); */
  10993.  
  10994. #else  /* PARSENSE */
  10995.  
  10996. #ifdef DEBUG
  10997.         if (deblog) {
  10998.             if ((n & 0x7f) != eol) {
  10999.             debug(F101,"ttinl EOP length","",pktlen);
  11000.             debug(F000,"ttinl EOP current char","",n);
  11001.             debug(F101,"ttinl EOP packet buf index","",i);
  11002.             } else debug(F101,"ttinl got eol","",eol);
  11003.         }
  11004. #endif /* DEBUG */
  11005.  
  11006. #ifdef MYREAD
  11007. /*
  11008.   The packet was read based on its length.  This leaves the packet terminator
  11009.   unread, and so ttchk() will always return at least 1 because of this,
  11010.   possibly giving a false positive to the "is there another packet waiting?"
  11011.   test.  But if we know the terminator (or any other interpacket junk) is
  11012.   there, we can safely get rid of it.
  11013.  
  11014.   NOTE: This code reworked to (a) execute even if the debug log isn't active;
  11015.   and (b) actually work.  -fdc, 2007/02/22.  And again 2007/08/12-13 to also
  11016.   work on encrypted connections.
  11017. */    
  11018.         debug(F101,"TTINL my_count","",my_count);
  11019.         if ((n & ttpmsk) != eol) { /* Not the packet terminator */
  11020.             int x;
  11021.             while (my_count > 0) {
  11022.             x = myread();       /* (was ttinc(0) */
  11023.             debug(F000,"TTINL lkread char","",x);
  11024. #ifdef CK_ENCRYPTION
  11025.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11026.                 CHAR ch = x;
  11027.                 ck_tn_decrypt((char *)&ch,1);
  11028.                 x = ch;
  11029.                 debug(F000,"TTINL lkdecr char","",x); 
  11030.             }
  11031. #endif    /* CK_ENCRYPTION */
  11032.             /*
  11033.               Note: while it might seem more elegant to simply
  11034.               push back the encrypted byte, that desynchronizes
  11035.               the decryption stream; the flag is necessary so we
  11036.               don't try to decrypt the same byte twice.
  11037.             */
  11038.             if ((x & ttpmsk) == start) { /* Start of next packet */
  11039.                 myunrd(x);    /* Push back the decrypted byte */
  11040.                 pushedback = 1; /* And set flag */
  11041.                 debug(F000,"TTINL lkpush char","",x);
  11042.                 break;
  11043.             }
  11044.             }
  11045.         }
  11046. #endif /* MYREAD */
  11047.  
  11048.         dest[i] = '\0';        /* Terminate the string, */
  11049.             if (needpchk) {        /* Parity checked yet? */
  11050.             if (ttprty == 0) {    /* No, check. */
  11051.             if ((ttprty = parchk(dest,start,i)) > 0) {
  11052.                 int j;
  11053.                 debug(F101,"ttinl senses parity","",ttprty);
  11054.                 debug(F110,"ttinl packet before",dest,0);
  11055.                 ttpmsk = 0x7f;
  11056.                 for (j = 0; j < i; j++)
  11057.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  11058.                 debug(F110,"ttinl packet after ",dest,0);
  11059.             } else ttprty = 0; /* Restore if parchk error */
  11060.             }
  11061.             sopmask = ttpmsk;
  11062.             needpchk = 0;
  11063.         }
  11064. #endif /* PARSENSE */
  11065.  
  11066.         if (timo)        /* Turn off timer if it was on */
  11067.           ttimoff();
  11068.                 ckhexdump("ttinl got",dest,i);
  11069.  
  11070. #ifdef STREAMING
  11071.         /* ttinl() was called because there was non-packet */
  11072.         /* data sitting in the back channel.  Ignore it.   */
  11073.         if (streaming && sndtyp == 'D')
  11074.           return(-1);
  11075. #endif /* STREAMING */
  11076.         return(i);
  11077.         }
  11078.     } /* End of while() */
  11079.     ttimoff();
  11080.     return(n);
  11081.     }
  11082. }
  11083. #endif /* NOXFER */
  11084.  
  11085. /*  T T I N C --  Read a character from the communication line  */
  11086. /*
  11087.  On success, returns the character that was read, >= 0.
  11088.  On failure, returns -1 or other negative myread error code,
  11089.    or -2 if connection is broken or ttyfd < 0.
  11090.    or -3 if session limit has expired,
  11091.    or -4 if something or other...
  11092.  NOTE: The API does not provide for ttinc() returning a special code
  11093.  upon timeout, but we need it.  So for this we have a global variable,
  11094.  ttinctimo.
  11095. */
  11096. static int ttinctimo = 0;        /* Yuk */
  11097.  
  11098. int
  11099. ttinc(timo) int timo; {
  11100.  
  11101.     int n = 0, fd;
  11102.     int is_tn = 0;
  11103.     CHAR ch = 0;
  11104.  
  11105.     ttinctimo = 0;
  11106.  
  11107.     if (ttyfd < 0) return(-2);          /* Not open. */
  11108.  
  11109.     is_tn = (xlocal && netconn && IS_TELNET()) ||
  11110.         (!xlocal && sstelnet);
  11111.  
  11112. #ifdef TTLEBUF
  11113.     if (ttpush >= 0) {
  11114.         debug(F111,"ttinc","ttpush",ttpush);
  11115.         ch = ttpush;
  11116.         ttpush = -1;
  11117.         return(ch);
  11118.     }
  11119.     if (le_data) {
  11120.         if (le_getchar(&ch) > 0) {
  11121.             debug(F111,"ttinc le_getchar","ch",ch);
  11122.             return(ch);
  11123.         }
  11124.     }
  11125. #endif /* TTLEBUF */
  11126.  
  11127. #ifdef NETCMD
  11128.     if (ttpipe)
  11129.       fd = fdin;
  11130.     else
  11131. #endif /* NETCMD */
  11132.       fd = ttyfd;
  11133.  
  11134.     if ((timo <= 0)            /* Untimed. */
  11135. #ifdef MYREAD
  11136.     || (my_count > 0)        /* Buffered char already waiting. */
  11137. #endif /* MYREAD */
  11138.     ) {
  11139. #ifdef MYREAD
  11140.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  11141.     n = myread();            /* Wait for a character... */
  11142.     /* debug(F000,"ttinc MYREAD n","",n); */
  11143. #ifdef CK_ENCRYPTION
  11144.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  11145.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11146.         ch = n;
  11147.         ck_tn_decrypt((char *)&ch,1);
  11148.         n = ch;
  11149.     }
  11150. #endif /* CK_ENCRYPTION */
  11151.  
  11152. #ifdef NETPTY
  11153.     if (ttpty && n < 0) {
  11154.         debug(F101,"ttinc error on pty","",n);
  11155.         ttclos(0);
  11156.         return(n);
  11157.     }
  11158. #endif /* NETPTY */
  11159.  
  11160. #ifdef TNCODE
  11161.     if ((n > -1) && is_tn)
  11162.       return((unsigned)(n & 0xff));
  11163.     else
  11164. #endif /* TNCODE */
  11165.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  11166.  
  11167. #else  /* MYREAD */
  11168.  
  11169.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  11170.         /* Shouldn't have to loop in ver 5A. */
  11171. #ifdef NETCONN
  11172.       if (netconn) {        /* Special handling for net */
  11173.           netclos();        /* If read() returns 0 it means */
  11174.           netconn = 0;        /* the connection has dropped. */
  11175.           errno = ENOTCONN;
  11176.           return(-2);
  11177.       }
  11178. #endif /* NETCONN */
  11179.       ;
  11180.     /* debug(F101,"ttinc","",ch); */
  11181. #ifdef TNCODE
  11182.     if ((n > 0) && is_tn) {
  11183. #ifdef CK_ENCRYPTION
  11184.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11185.         ck_tn_decrypt(&ch,1);
  11186.         n = ch;
  11187.         }
  11188. #endif /* CK_ENCRYPTION */
  11189.         return((unsigned)(ch & 0xff));
  11190.     } else
  11191. #endif /* TNCODE */
  11192.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  11193. #endif /* MYREAD */
  11194.  
  11195.     } else {                /* Timed read */
  11196.  
  11197.     int oldalarm;
  11198.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  11199.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  11200.     if (
  11201. #ifdef CK_POSIX_SIG
  11202.         sigsetjmp(sjbuf,1)
  11203. #else
  11204.         setjmp(sjbuf)
  11205. #endif /* CK_POSIX_SIG */
  11206.         ) {                /* Timer expired */
  11207.         ttinctimo = 1;
  11208.         n = -1;            /* set flag */
  11209.     } else {
  11210. #ifdef MYREAD
  11211.         n = myread();        /* If managing own buffer... */
  11212.         debug(F101,"ttinc myread","",n);
  11213.         ch = n;
  11214. #else
  11215.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  11216.         if (n == 0) n = -1;
  11217.         debug(F101,"ttinc read","",n);
  11218. #endif /* MYREAD */
  11219.  
  11220. #ifdef CK_ENCRYPTION
  11221.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11222.         ck_tn_decrypt((char *)&ch,1);
  11223.         }
  11224. #endif /* CK_ENCRYPTION */
  11225.         if (n >= 0)
  11226.           n = (unsigned) (ch & 0xff);
  11227.         else
  11228.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  11229.     }
  11230.     ttimoff();            /* Turn off the timer */
  11231.     if (oldalarm > 0) {
  11232.         if (n == -1)        /* and restore any previous alarm */
  11233.           oldalarm -= timo;
  11234.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  11235.           oldalarm = 0;
  11236.         if (oldalarm) {
  11237.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  11238.         alarm(oldalarm);
  11239.         }
  11240.     }
  11241. #ifdef NETCONN
  11242.     if (netconn) {
  11243.         if (n == -2) {        /* read() returns 0 */
  11244.         netclos();        /* on network read failure */
  11245.         netconn = 0;
  11246.         errno = ENOTCONN;
  11247.         }
  11248.     }
  11249. #endif    /* NETCONN */
  11250. #ifdef TNCODE
  11251.     if ((n > -1) && is_tn)
  11252.       return((unsigned)(n & 0xff));
  11253.     else
  11254. #endif /* TNCODE */
  11255.       /* Return masked char or neg. */
  11256.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  11257.     }
  11258. }
  11259.  
  11260. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  11261.  
  11262. static int
  11263. #ifdef CK_ANSIC
  11264. sndbrk(int msec) {            /* Argument is milliseconds */
  11265. #else
  11266. sndbrk(msec) int msec; {
  11267. #endif /* CK_ANSIC */
  11268. #ifndef POSIX
  11269.     int x, n;
  11270. #endif /* POSIX */
  11271.  
  11272. #ifdef OXOS
  11273. #define BSDBREAK
  11274. #endif /* OXOS */
  11275.  
  11276. #ifdef ANYBSD
  11277. #define BSDBREAK
  11278. #endif /* ANYBSD */
  11279.  
  11280. #ifdef BSD44
  11281. #define BSDBREAK
  11282. #endif /* BSD44 */
  11283.  
  11284. #ifdef COHERENT
  11285. #ifdef BSDBREAK
  11286. #undef BSDBREAK
  11287. #endif /* BSDBREAK */
  11288. #endif /* COHERENT */
  11289.  
  11290. #ifdef BELLV10
  11291. #ifdef BSDBREAK
  11292. #undef BSDBREAK
  11293. #endif /* BSDBREAK */
  11294. #endif /* BELLV10 */
  11295.  
  11296. #ifdef PROVX1
  11297.     char spd;
  11298. #endif /* PROVX1 */
  11299.  
  11300.     debug(F101,"ttsndb ttyfd","",ttyfd);
  11301.     if (ttyfd < 0) return(-1);          /* Not open. */
  11302.  
  11303. #ifdef Plan9
  11304.     return p9sndbrk(msec);
  11305. #else
  11306. #ifdef NETCONN
  11307. #ifdef NETCMD
  11308.     if (ttpipe)                /* Pipe */
  11309.       return(ttoc('\0'));
  11310. #endif /* NETCMD */
  11311. #ifdef NETPTY
  11312.     if (ttpty)
  11313.       return(ttoc('\0'));
  11314. #endif /* NETPTY */
  11315.     if (netconn)             /* Send network BREAK */
  11316.       return(netbreak());
  11317. #endif /* NETCONN */
  11318.  
  11319.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  11320.  
  11321. #ifdef POSIX                /* Easy in POSIX */
  11322.     {
  11323.     int x;
  11324.     debug(F111,"sndbrk POSIX",ckitoa(msec),(msec/375));
  11325.     errno = 0;
  11326.     x = tcsendbreak(ttyfd,msec / 375);
  11327.     debug(F111,"sndbrk tcsendbreak",ckitoa(errno),x);
  11328.     return(x);
  11329.     }
  11330. #else
  11331. #ifdef PROVX1
  11332.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  11333.     spd = ttbuf.sg_ospeed;              /* Save speed */
  11334.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  11335.     stty(ttyfd,&ttbuf);                 /*  ... */
  11336.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  11337.     x = msec / 91;
  11338.     if (x > n) x = n;
  11339.     write(ttyfd,brnuls,n);
  11340.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  11341.     stty(ttyfd,&ttbuf);                 /*  ... */
  11342.     return(0);
  11343. #else
  11344. #ifdef aegis
  11345.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  11346.     return(0);
  11347. #else
  11348. #ifdef BSDBREAK
  11349.     n = FWRITE;                         /* Flush output queue. */
  11350. /* Watch out for int vs long problems in &n arg! */
  11351.     debug(F101,"sndbrk BSDBREAK","",msec);
  11352.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  11353.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  11354.         perror("Can't send BREAK");
  11355.         return(-1);
  11356.     }
  11357.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  11358.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  11359.         perror("BREAK stuck!!!");
  11360.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  11361.                                         /*   with bad exit status */
  11362.     }
  11363.     return(x);
  11364. #else
  11365. #ifdef ATTSV
  11366. /*
  11367.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  11368.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  11369.   but there's no way for this code to know for sure.)
  11370. */
  11371.     debug(F101,"sndbrk ATTSV","",msec);
  11372.     x = msec / 275;
  11373.     for (n = 0; n < x; n++) {
  11374.     /* Reportedly the cast breaks this function on some systems */
  11375.     /* But then why was it here in the first place? */
  11376.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  11377.         perror("Can't send BREAK");
  11378.         return(-1);
  11379.     }
  11380.     }
  11381.     return(0);
  11382. #else
  11383. #ifdef  V7
  11384.     debug(F101,"sndbrk V7","",msec);
  11385.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  11386. #else
  11387.     debug(F101,"sndbrk catchall","",msec);
  11388.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  11389.     return(0);
  11390. #endif /* V7 */
  11391. #endif /* BSDBREAK */
  11392. #endif /* ATTSV */
  11393. #endif /* aegis */
  11394. #endif /* PROVX1 */
  11395. #endif /* POSIX */
  11396. #endif /* Plan9 */
  11397. }
  11398.  
  11399. /*  T T S N D B  --  Send a BREAK signal  */
  11400.  
  11401. int
  11402. ttsndb() {
  11403. #ifdef TN_COMPORT
  11404.     if (netconn && istncomport())
  11405.       return((tnsndb(275L) >= 0) ? 0 : -1);
  11406.     else
  11407. #endif /* TN_COMPORT */
  11408.       return(sndbrk(275));
  11409. }
  11410.  
  11411. /*  T T S N D L B  --  Send a Long BREAK signal  */
  11412.  
  11413. int
  11414. ttsndlb() {
  11415. #ifdef TN_COMPORT
  11416.     if (netconn && istncomport())
  11417.       return((tnsndb(1800L) >= 0) ? 0 : -1);
  11418.     else
  11419. #endif /* TN_COMPORT */
  11420.     return(sndbrk(1500));
  11421. }
  11422.  
  11423. /*  M S L E E P  --  Millisecond version of sleep().  */
  11424.  
  11425. /*
  11426.   Call with number of milliseconds (thousandths of seconds) to sleep.
  11427.   Intended only for small intervals.  For big ones, just use sleep().
  11428.   Highly system-dependent.
  11429.   Returns 0 always, even if it didn't work.
  11430. */
  11431.  
  11432. /* Define MSLFTIME for systems that must use an ftime() loop. */
  11433. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  11434. #ifndef BSD4
  11435. #define MSLFTIME
  11436. #endif /* BSD4 */
  11437. #endif /* ANYBSD */
  11438.  
  11439. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  11440. #define MSLFTIME
  11441. #endif /* TOWER1 */
  11442.  
  11443. #ifdef COHERENT         /* Coherent... */
  11444. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  11445. #define MSLFTIME        /* Opinions are divided */
  11446. #endif /* _I386 */
  11447. #endif /* COHERENT */
  11448.  
  11449. #ifdef COMMENT
  11450. #ifdef GETMSEC
  11451.  
  11452. /* Millisecond timer */
  11453.  
  11454. static long msecbase = 0L;        /* Unsigned long not portable */
  11455.  
  11456. long
  11457. getmsec() {                /* Milliseconds since base time */
  11458.     struct timeval xv;
  11459.     struct timezone xz;
  11460.     long secs, msecs;
  11461.     if (
  11462. #ifdef GTODONEARG
  11463.     gettimeofday(&tv)
  11464. #else
  11465. #ifdef PTX
  11466.     gettimeofday(&tv, NULL)
  11467. #else
  11468.     gettimeofday(&tv, &tz)
  11469. #endif /* PTX */
  11470. #endif /* GTODONEARG */
  11471.     < 0)
  11472.       return(-1);
  11473.     if (msecbase == 0L) {        /* First call, set base time. */
  11474.     msecbase = tv.tv_sec;
  11475.     debug(F101,"getmsec base","",msecbase);
  11476.     }
  11477.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  11478. }
  11479. #endif /* GETMSEC */
  11480. #endif /* COMMENT */
  11481.  
  11482. #ifdef SELECT
  11483. int
  11484. ttwait(fd, secs) int fd, secs; {
  11485.     int x;
  11486.     fd_set rfds;
  11487.     FD_ZERO(&rfds);
  11488.     FD_SET(fd,&rfds);
  11489.     tv.tv_sec = secs;
  11490.     tv.tv_usec = 0L;
  11491.     errno = 0;
  11492.     if ((x = select(FD_SETSIZE,
  11493. #ifdef HPUX9
  11494.             (int *)
  11495. #else
  11496. #ifdef HPUX1000
  11497.             (int *)
  11498. #endif /* HPUX1000 */
  11499. #endif /* HPUX9 */
  11500.             &rfds,
  11501.             0, 0, &tv)) < 0) {
  11502.     debug(F101,"ttwait select errno","",errno);
  11503.     return(0);
  11504.     } else {
  11505.     debug(F101,"ttwait OK","",errno);
  11506.     x = FD_ISSET(fd, &rfds);
  11507.     debug(F101,"ttwait select x","",x);
  11508.     return(x ? 1 : 0);
  11509.     }
  11510. }
  11511. #endif /* SELECT */
  11512.  
  11513. int
  11514. msleep(m) int m; {
  11515. /*
  11516.   Other possibilities here are:
  11517.    nanosleep(), reportedly defined in POSIX.4.
  11518.    sginap(), IRIX only (back to what IRIX version I don't know).
  11519. */
  11520. #ifdef Plan9
  11521.     return _SLEEP(m);
  11522. #else
  11523. #ifdef BEOSORBEBOX
  11524.     snooze(m*1000);
  11525. #else /* BEOSORBEBOX */
  11526. #ifdef SELECT
  11527.     int t1, x;
  11528.     debug(F101,"msleep SELECT 1","",m);
  11529.     if (m <= 0) return(0);
  11530.     if (m >= 1000) {            /* Catch big arguments. */
  11531.     sleep(m/1000);
  11532.     m = m % 1000;
  11533.     if (m < 10) return(0);
  11534.     }
  11535.     debug(F101,"msleep SELECT 2","",m);
  11536. #ifdef BELLV10
  11537.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  11538.     debug(F101,"msleep BELLV10 select","",x);
  11539. #else /* BELLV10 */
  11540. #ifdef HPUX9
  11541.     gettimeofday(&tv, &tz);
  11542. #else
  11543.  
  11544. #ifndef COHERENT
  11545. #ifdef GTODONEARG
  11546.     if (gettimeofday(&tv) < 0)
  11547. #else
  11548. #ifdef PTX
  11549.     if (gettimeofday(&tv,NULL) < 0)
  11550. #else
  11551. #ifdef NOTIMEZONE
  11552.     if (gettimeofday(&tv, NULL) < 0)    /* wonder what this does... */
  11553. #else
  11554.     if (gettimeofday(&tv, &tz) < 0)
  11555. #endif /* NOTIMEZONE */
  11556. #endif /* PTX */
  11557. #endif /* GTODONEARG */
  11558.       return(-1);
  11559.     t1 = tv.tv_sec;                     /* Seconds */
  11560. #endif /* COHERENT */
  11561. #endif /* HPUX9 */
  11562.     tv.tv_sec = 0;                      /* Use select() */
  11563.     tv.tv_usec = m * 1000L;
  11564. #ifdef BSD44
  11565.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11566.     debug(F101,"msleep BSD44 select","",x);
  11567. #else /* BSD44 */
  11568. #ifdef __linux__
  11569.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11570.     debug(F101,"msleep __linux__ select","",x);
  11571. #else /* __linux__ */
  11572. #ifdef BSD43
  11573.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11574.     debug(F101,"msleep BSD43 select","",x);
  11575. #else /* BSD43 */
  11576. #ifdef QNX6
  11577.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11578.     debug(F101,"msleep QNX6 select","",x);
  11579. #else /* QNX6 */
  11580. #ifdef QNX
  11581.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11582.     debug(F101,"msleep QNX select","",x);
  11583. #else /* QNX */
  11584. #ifdef COHERENT
  11585.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11586.     debug(F101,"msleep COHERENT select","",x);
  11587. #else /* COHERENT */
  11588. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  11589.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11590.     debug(F101,"msleep HP-UX 10.00 select","",x);
  11591. #else /* HPUX1000 */
  11592. #ifdef SVR4
  11593.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11594.     debug(F101,"msleep SVR4 select","",x);
  11595. #else /* SVR4 */
  11596. #ifdef OSF40
  11597.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11598.     debug(F101,"msleep OSF40 select","",x);
  11599. #else /* OSF40 */
  11600. #ifdef PTX
  11601.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11602.     debug(F101,"msleep OSF40 select","",x);
  11603. #else
  11604.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11605.     debug(F101,"msleep catch-all select","",x);
  11606. #endif /* PTX */
  11607. #endif /* OSF40 */
  11608. #endif /* HP1000 */
  11609. #endif /* SVR4 */
  11610. #endif /* COHERENT */
  11611. #endif /* QNX */
  11612. #endif /* QNX6 */
  11613. #endif /* BSD43 */
  11614. #endif /* __linux__ */
  11615. #endif /* BSD44 */
  11616. #endif /* BELLV10 */
  11617.     return(0);
  11618.  
  11619. #else                    /* Not SELECT */
  11620. #ifdef CK_POLL                /* We have poll() */
  11621.     struct pollfd pfd;            /* Supply a valid address for poll() */
  11622.  
  11623. #ifdef ODT30                /* But in SCO ODT 3.0 */
  11624. #ifdef NAP                /* we should use nap() instead */
  11625.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  11626.     nap((long)m);               /* seems to break dialing. */
  11627.     return(0);
  11628. #else
  11629.     debug(F101,"msleep ODT 3.0 POLL","",m);
  11630.     poll(&pfd, 0, m);
  11631.     return(0);
  11632. #endif /* NAP */
  11633. #else
  11634.     debug(F101,"msleep POLL","",m);
  11635.     poll(&pfd, 0, m);
  11636.     return(0);
  11637. #endif /* ODT30 */
  11638.  
  11639. /*
  11640.   We could handle the above more cleanly by just letting nap() always
  11641.   take precedence over poll() in this routine, but there is no way to know
  11642.   whether that would break something else.
  11643. */
  11644.  
  11645. #else                    /* Not POLL */
  11646. #ifdef USLEEP
  11647. /*
  11648.   "This routine is implemented using setitimer(2); it requires eight
  11649.   system calls...".  In other words, it might take 5 minutes to sleep
  11650.   10 milliseconds...
  11651. */
  11652.     debug(F101,"msleep USLEEP","",m);
  11653.     if (m >= 1000) {            /* Catch big arguments. */
  11654.     sleep(m/1000);
  11655.     m = m % 1000;
  11656.     if (m < 10) return(0);
  11657.     }
  11658.     usleep((unsigned int)(m * 1000));
  11659.     return(0);
  11660. #else
  11661. #ifdef aegis
  11662.     time_$clock_t dur;
  11663.     debug(F101,"msleep aegis","",m);
  11664.     dur.c2.high16 = 0;
  11665.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  11666.     time_$wait(time_$relative, dur, st);
  11667.     return(0);
  11668. #else
  11669. #ifdef PROVX1
  11670.     debug(F101,"msleep Venix","",m);
  11671.     if (m <= 0) return(0);
  11672.     sleep(-((m * 60 + 500) / 1000));
  11673.     return(0);
  11674. #else
  11675. #ifdef NAP
  11676.     debug(F101,"msleep NAP","",m);
  11677.     nap((long)m);
  11678.     return(0);
  11679. #else
  11680. #ifdef ATTSV
  11681. #ifndef BSD44
  11682.     extern long times();        /* Or #include <times.h> ? */
  11683. #endif /* BSD44 */
  11684.     long t1, t2, tarray[4];
  11685.     int t3;
  11686.     char *cp = getenv("HZ");
  11687.     int CLOCK_TICK;
  11688.     int hertz;
  11689.  
  11690.     if (cp && (hertz = atoi(cp))) {
  11691.         CLOCK_TICK  = 1000 / hertz;
  11692.     } else {                /* probably single user mode */
  11693. #ifdef HZ
  11694.         CLOCK_TICK  = 1000 / HZ;
  11695. #else
  11696.     static warned = 0;
  11697.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  11698.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  11699.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  11700.      * in the makefile. Most systems have HZ.
  11701.      */
  11702.     CLOCK_TICK = 17;        /* 1/60 sec */
  11703.     if (!warned) {
  11704.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  11705.          1000 / CLOCK_TICK);
  11706.           warned = 1;
  11707.     }
  11708. #endif /* !HZ */
  11709.     }
  11710.     debug(F101,"msleep ATTSV","",m);
  11711.     if (m <= 0) return(0);
  11712.     if (m >= 1000) {            /* Catch big arguments. */
  11713.     sleep(m/1000);
  11714.     m = m % 1000;
  11715.     if (m < 10) return(0);
  11716.     }
  11717.     if ((t1 = times(tarray)) < 0) return(-1);
  11718.     while (1) {
  11719.         if ((t2 = times(tarray)) < 0) return(-1);
  11720.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  11721.         if (t3 > m) return(t3);
  11722.     }
  11723. #else /* Not ATTSV */
  11724. #ifdef MSLFTIME                /* Use ftime() loop... */
  11725.     int t1, t3 = 0;
  11726.     debug(F101,"msleep MSLFTIME","",m);
  11727.     if (m <= 0) return(0);
  11728.     if (m >= 1000) {            /* Catch big arguments. */
  11729.     sleep(m/1000);
  11730.     m = m % 1000;
  11731.     if (m < 10) return(0);
  11732.     }
  11733. #ifdef QNX
  11734.     ftime(&ftp);            /* void ftime() in QNX */
  11735. #else
  11736.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  11737. #endif /* QNX */
  11738.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  11739.     while (1) {
  11740.         ftime(&ftp);            /* Get current time and compare. */
  11741.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  11742.         if (t3 > m) return(0);
  11743.     }
  11744. #else
  11745. /* This includes true POSIX, which has no way to do this. */
  11746.     debug(F101,"msleep busy loop","",m);
  11747.     if (m >= 1000) {            /* Catch big arguments. */
  11748.     sleep(m/1000);
  11749.     m = m % 1000;
  11750.     if (m < 10) return(0);
  11751.     }
  11752.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  11753.     return(0);
  11754. #endif /* MSLFTIME */
  11755. #endif /* ATTSV */
  11756. #endif /* NAP */
  11757. #endif /* PROVX1 */
  11758. #endif /* aegis */
  11759. #endif /* CK_POLL */
  11760. #endif /* SELECT */
  11761. #endif /* BEOSORBEBOX */
  11762. #endif /* USLEEP */
  11763. #endif /* Plan9 */
  11764. }
  11765.  
  11766. /*  R T I M E R --  Reset elapsed time counter  */
  11767.  
  11768. VOID
  11769. rtimer() {
  11770.     tcount = time( (time_t *) 0 );
  11771. }
  11772.  
  11773.  
  11774. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  11775.  
  11776. int
  11777. gtimer() {
  11778.     int x;
  11779.     x = (int) (time( (time_t *) 0 ) - tcount);
  11780.     debug(F101,"gtimer","",x);
  11781.     return( (x < 0) ? 0 : x );
  11782. }
  11783.  
  11784. #ifdef GFTIMER
  11785. /*
  11786.   Floating-point timers.  Require not only floating point support, but
  11787.   also gettimeofday().
  11788. */
  11789. static struct timeval tzero;
  11790.  
  11791. VOID
  11792. rftimer() {
  11793. #ifdef GTODONEARG            /* Account for Mot's definition */
  11794.     (VOID) gettimeofday(&tzero);
  11795. #else
  11796.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  11797. #endif /* GTODONEARG */
  11798. }
  11799.  
  11800. CKFLOAT
  11801. gftimer() {
  11802.     struct timeval tnow, tdelta;
  11803.     CKFLOAT s;
  11804. #ifdef DEBUG
  11805.     char fpbuf[64];
  11806. #endif /* DEBUG */
  11807. #ifdef GTODONEARG            /* Account for Mot's definition */
  11808.     (VOID) gettimeofday(&tnow);
  11809. #else
  11810.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  11811. #endif /* GTODONEARG */
  11812.  
  11813.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  11814.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  11815.  
  11816.     if (tdelta.tv_usec < 0) {
  11817.     tdelta.tv_sec--;
  11818.     tdelta.tv_usec += 1000000;
  11819.     }
  11820.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  11821.     if (s < GFMINTIME)
  11822.       s = GFMINTIME;
  11823. #ifdef DEBUG
  11824.     if (deblog) {
  11825.     sprintf(fpbuf,"%f",s);
  11826.     debug(F110,"gftimer",fpbuf,0);
  11827.     }
  11828. #endif /* DEBUG */
  11829.     return(s);
  11830. }
  11831. #endif /* GFTIMER */
  11832.  
  11833. /*  Z T I M E  --  Return asctime()-format date/time string  */
  11834. /*
  11835.   NOTE: as a side effect of calling this routine, we can also set the
  11836.   following two variables, giving the micro- and milliseconds (fractions of
  11837.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  11838.   that use gettimeofday().  When these variables are not filled in, they are
  11839.   left with a value of -1L.
  11840. */
  11841. static char asctmbuf[64];
  11842.  
  11843. VOID
  11844. ztime(s) char **s; {
  11845.  
  11846. #ifdef GFTIMER
  11847. /*
  11848.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  11849.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  11850.   and extern declarations for them are in ckcdeb.h; thus they are
  11851.   declared in this file by inclusion of ckcdeb.h.
  11852. */
  11853.     char *asctime();
  11854.     struct tm *localtime();
  11855.     struct tm *tp;
  11856.     ztmsec = -1L;
  11857.     ztusec = -1L;
  11858.  
  11859.     if (!s)
  11860.       debug(F100,"ztime s==NULL","",0);
  11861.  
  11862. #ifdef GTODONEARG
  11863.     /* No 2nd arg in Motorola SV88 and some others */
  11864.     if (gettimeofday(&tv) > -1)
  11865. #else
  11866. #ifndef COHERENT
  11867. #ifdef PTX
  11868.     if (gettimeofday(&tv,NULL) > -1)
  11869. #else
  11870. #ifdef NOTIMEZONE
  11871.     if (gettimeofday(&tv, NULL) > -1)    /* wonder what this does... */
  11872. #else
  11873.     if (gettimeofday(&tv, &tz) > -1)
  11874. #endif /* NOTIMEZONE */
  11875. #endif /* PTX */
  11876. #endif /* COHERENT */
  11877. #endif /* GTODONEARG */
  11878.       {                    /* Fill in tm struct */
  11879.     ztusec = tv.tv_usec;        /* Microseconds */
  11880.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  11881. #ifdef HPUX9
  11882.     {
  11883.         time_t zz;
  11884.         zz = tv.tv_sec;
  11885.         tp = localtime(&zz);    /* Convert to local time */
  11886.     }
  11887. #else
  11888. #ifdef HPUX1000
  11889.     {
  11890.         time_t zz;
  11891.         zz = tv.tv_sec;
  11892.         tp = localtime(&zz);
  11893.     }
  11894. #else
  11895. #ifdef LINUX
  11896.     {   /* avoid unaligned access trap on 64-bit platforms */
  11897.         time_t zz;
  11898.         zz = tv.tv_sec;
  11899.         tp = localtime(&zz);
  11900.     }
  11901. #else
  11902. #ifdef MACOSX
  11903.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  11904. #else
  11905.     tp = localtime(&tv.tv_sec);
  11906. #endif /* MACOSX */
  11907. #endif /* LINUX */
  11908. #endif /* HPUX1000 */
  11909. #endif /* HPUX9 */
  11910.     if (s) {
  11911.         char * s2;
  11912.         s2 = asctime(tp);        /* Convert result to ASCII string */
  11913.         asctmbuf[0] = '\0';
  11914.         if (s2) ckstrncpy(asctmbuf,s2,64);
  11915.         *s = asctmbuf;
  11916.         debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  11917.     }
  11918.     }
  11919. #else  /* Not GFTIMER */
  11920.  
  11921. #undef ZTIMEV7                /* Which systems need to use */
  11922. #ifdef COHERENT                /* old UNIX Version 7 way... */
  11923. #define ZTIMEV7
  11924. #endif /* COHERENT */
  11925. #ifdef TOWER1
  11926. #define ZTIMEV7
  11927. #endif /* TOWER1 */
  11928. #ifdef ANYBSD
  11929. #ifndef BSD42
  11930. #define ZTIMEV7
  11931. #endif /* BSD42 */
  11932. #endif /* ANYBSD */
  11933. #ifdef V7
  11934. #ifndef MINIX
  11935. #define ZTIMEV7
  11936. #endif /* MINIX */
  11937. #endif /* V7 */
  11938. #ifdef POSIX
  11939. #define ZTIMEV7
  11940. #endif /* POSIX */
  11941.  
  11942. #ifdef HPUX1020
  11943. /*
  11944.   Prototypes are in <time.h>, included above.
  11945. */
  11946.     time_t clock_storage;
  11947.     clock_storage = time((void *) 0);
  11948.     if (s) {
  11949.     *s = ctime(&clock_storage);
  11950.     debug(F110,"ztime: HPUX 10.20",*s,0);
  11951.     }
  11952. #else
  11953. #ifdef ATTSV                /* AT&T way */
  11954. /*  extern long time(); */        /* Theoretically these should */
  11955.     char *ctime();            /* already been dcl'd in <time.h> */
  11956.     time_t clock_storage;
  11957.     clock_storage = time(
  11958. #ifdef IRIX60
  11959.              (time_t *)
  11960. #else
  11961. #ifdef BSD44
  11962.              (time_t *)
  11963. #else
  11964.              (long *)
  11965. #endif /* BSD44 */
  11966. #endif /* IRIX60 */
  11967.              0 );
  11968.     if (s) {
  11969.     *s = ctime( &clock_storage );
  11970.     debug(F110,"ztime: ATTSV",*s,0);
  11971.     }
  11972. #else
  11973. #ifdef PROVX1                /* Venix 1.0 way */
  11974.     int utime[2];
  11975.     time(utime);
  11976.     if (s) {
  11977.     *s = ctime(utime);
  11978.     debug(F110,"ztime: PROVX1",*s,0);
  11979.     }
  11980. #else
  11981. #ifdef BSD42                /* 4.2BSD way */
  11982.     char *asctime();
  11983.     struct tm *localtime();
  11984.     struct tm *tp;
  11985.     gettimeofday(&tv, &tz);
  11986.     ztusec = tv.tv_usec;
  11987.     ztmsec = tv.tv_usec / 1000L;
  11988.     tp = localtime(&tv.tv_sec);
  11989.     if (s) {
  11990.     *s = asctime(tp);
  11991.     debug(F111,"ztime: BSD42",*s,ztusec);
  11992.     }
  11993. #else
  11994. #ifdef MINIX                /* MINIX way */
  11995. #ifdef COMMENT
  11996.     extern long time();            /* Already got these from <time.h> */
  11997.     extern char *ctime();
  11998. #endif /* COMMENT */
  11999.     time_t utime[2];
  12000.     time(utime);
  12001.     if (s) {
  12002.     *s = ctime(utime);
  12003.     debug(F110,"ztime: MINIX",*s,0);
  12004.     }
  12005. #else
  12006. #ifdef ZTIMEV7                /* The regular way */
  12007.     char *asctime();
  12008.     struct tm *localtime();
  12009.     struct tm *tp;
  12010.     long xclock;            /* or unsigned long for BeBox? */
  12011.     time(&xclock);
  12012.     tp = localtime(&xclock);
  12013.     if (s) {
  12014.     *s = asctime(tp);
  12015.     debug(F110,"ztime: ZTIMEV7",*s,0);
  12016.     }
  12017. #else                    /* Catch-all for others... */
  12018.     if (s) {
  12019.     *s = "Day Mon 00 00:00:00 0000\n"; /* Dummy in asctime() format */
  12020.     debug(F110,"ztime: catch-all",*s,0);
  12021.     }
  12022. #endif /* ZTIMEV7 */
  12023. #endif /* MINIX */
  12024. #endif /* BSD42 */
  12025. #endif /* PROVX1 */
  12026. #endif /* ATTSV */
  12027. #endif /* HPUX1020 */
  12028. #endif /* GFTIMER */
  12029. }
  12030.  
  12031. /*  C O N G M  --  Get console terminal modes.  */
  12032.  
  12033. /*
  12034.   Saves initial console mode, and establishes variables for switching
  12035.   between current (presumably normal) mode and other modes.
  12036.   Should be called when program starts, but only after establishing
  12037.   whether program is in the foreground or background.
  12038.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  12039. */
  12040. int
  12041. congm() {
  12042.     int fd;
  12043.     if (backgrd || !isatty(0)) {    /* If in background. */
  12044.     cgmf = -1;            /* Don't bother, modes are garbage. */
  12045.     return(-1);
  12046.     }
  12047.     if (cgmf > 0) return(0);        /* Already did this. */
  12048.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  12049. #ifdef aegis
  12050.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  12051.     if (st.all != status_$ok) {
  12052.     fprintf(stderr, "problem getting stdin objtype: ");
  12053.     error_$print(st);
  12054.     }
  12055.     concrp = (conuid == mbx_$uid);
  12056.     conbufn = 0;
  12057. #endif /* aegis */
  12058.  
  12059. #ifndef BEBOX
  12060.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  12061. #ifdef COMMENT
  12062.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  12063.     perror("congm");
  12064.     return(-1);
  12065. #else
  12066.     fd = 0;
  12067. #endif /* COMMENT */
  12068.     }
  12069. #else
  12070.     fd = 0;
  12071. #endif /* !BEBOX */
  12072. #ifdef BSD44ORPOSIX
  12073.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  12074.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  12075.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  12076. #else
  12077. #ifdef ATTSV
  12078.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  12079.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  12080.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  12081. #ifdef VXVE
  12082.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12083.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  12084.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12085.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  12086. #endif /* VXVE */
  12087. #else
  12088. #ifdef BELLV10
  12089.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  12090.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  12091.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  12092.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  12093. #else
  12094.     if (gtty(fd,&ccold) < 0) return(-1);
  12095.     if (gtty(fd,&cccbrk) < 0) return(-1);
  12096.     if (gtty(fd,&ccraw) < 0) return(-1);
  12097. #endif /* BELLV10 */
  12098. #endif /* ATTSV */
  12099. #endif /* BSD44ORPOSIX */
  12100. #ifdef sony_news            /* Sony NEWS */
  12101.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  12102.     perror("congm error getting Kanji mode");
  12103.     debug(F101,"congm error getting Kanji mode","",0);
  12104.     km_con = -1;            /* Make sure this stays undefined. */
  12105.     return(-1);
  12106.     }
  12107. #endif /* sony_news */
  12108.     if (fd > 0)
  12109.       close(fd);
  12110.     cgmf = 1;                /* Flag that we got them. */
  12111.     return(1);
  12112. }
  12113.  
  12114.  
  12115. static VOID
  12116. congetbuf(x) int x; {
  12117.     int n;
  12118.     n = CONBUFSIZ - (conbufp - conbuf);    /* How much room left in buffer? */
  12119.     if (x > n) {
  12120.     debug(F101,"congetbuf char loss","",x-n);
  12121.     x = n;
  12122.     }
  12123.     x = read(0,conbufp,x);
  12124.     conbufn += x;
  12125.     debug(F111,"congetbuf readahead",conbuf,x);
  12126. }
  12127.  
  12128.  
  12129. /*  C O N C B --  Put console in cbreak mode.  */
  12130.  
  12131. /*  Returns 0 if ok, -1 if not  */
  12132.  
  12133. int
  12134. #ifdef CK_ANSIC
  12135. concb(char esc)
  12136. #else
  12137. concb(esc) char esc;
  12138. #endif /* CK_ANSIC */
  12139. /* concb */ {
  12140.     int x, y = 0;
  12141.     debug(F101,"concb constate","",constate);
  12142.     debug(F101,"concb cgmf","",cgmf);
  12143.     debug(F101,"concb backgrd","",backgrd);
  12144.  
  12145.     if (constate == CON_CB)
  12146.       return(0);
  12147.  
  12148.     if (cgmf < 1)            /* Did we get console modes yet? */
  12149.       if (!backgrd)            /* No, in background? */
  12150.     congm();            /* No, try to get them now. */
  12151.     if (cgmf < 1)            /* Still don't have them? */
  12152.       return(0);            /* Give up. */
  12153.     debug(F101,"concb ttyfd","",ttyfd);
  12154.     debug(F101,"concb ttfdflg","",ttfdflg);
  12155. #ifdef COMMENT
  12156.     /* This breaks returning to prompt after protocol with "-l 0" */
  12157.     /* Commented out July 1998 */
  12158.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  12159.       return(0);
  12160. #endif /* COMMENT */
  12161.     x = isatty(0);
  12162.     debug(F101,"concb isatty","",x);
  12163.     if (!x) return(0);            /* Only when running on real ttys */
  12164.     debug(F101,"concb xsuspend","",xsuspend);
  12165.     if (backgrd)            /* Do nothing if in background. */
  12166.       return(0);
  12167.     escchr = esc;                       /* Make this available to other fns */
  12168.     ckxech = 1;                         /* Program can echo characters */
  12169. #ifdef aegis
  12170.     conbufn = 0;
  12171.     if (concrp) return(write(1, "\035\002", 2));
  12172.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  12173. #endif /* aegis */
  12174.  
  12175. #ifdef COHERENT
  12176. #define SVORPOSIX
  12177. #endif /* COHERENT */
  12178.  
  12179. #ifdef Plan9
  12180.     x = p9concb();
  12181. #else
  12182. #ifndef SVORPOSIX            /* BSD, V7, etc */
  12183.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  12184.     debug(F101,"concb stty CBREAK","",0);
  12185.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  12186.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  12187.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  12188.     errno = 0;
  12189. /*
  12190.   BSD stty() clears the console buffer.  So if anything is waiting in it,
  12191.   we have to read it now to avoid losing it.
  12192. */
  12193.     x = conchk();
  12194.     if (x > 0)
  12195.       congetbuf(x);
  12196.  
  12197. #ifdef BELLV10
  12198.     x = ioctl(0,TIOCSETP,&cccbrk);
  12199. #else
  12200.     x = stty(0,&cccbrk);
  12201.     debug(F101,"cccbrk.sg_flags concb x","", x);
  12202. #endif /* BELLV10 */
  12203. #else                    /* Sys V and POSIX */
  12204. #ifndef OXOS
  12205.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  12206. #ifdef QNX
  12207.     /* Don't mess with IEXTEN */
  12208.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12209. #else
  12210. #ifdef COHERENT
  12211.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12212. #else
  12213.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  12214. #endif /* COHERENT */
  12215. #endif /* QNX */
  12216.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  12217.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  12218.     cccbrk.c_iflag &= ~BRKINT;
  12219.  
  12220. #else /* OXOS */
  12221.     debug(F100,"concb OXOS is defined","",0);
  12222.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12223.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  12224. #endif /* OXOS */
  12225. #ifdef COMMENT
  12226. /*
  12227.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  12228.   array reference is out of bounds.  It's only a debug() call so who needs it.
  12229. */
  12230. #ifdef VSUSP
  12231.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  12232. #endif /* VSUSP */
  12233. #endif /* COMMENT */
  12234. #ifndef VINTR
  12235.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  12236.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  12237. #else
  12238.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  12239.     cccbrk.c_cc[VINTR] = 003;
  12240. #endif /* VINTR */
  12241. #ifndef VQUIT
  12242.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  12243. #else
  12244.     cccbrk.c_cc[VQUIT] = escchr;
  12245. #endif /* VQUIT */
  12246. #ifndef VEOF
  12247.     cccbrk.c_cc[4] = 1;
  12248. #else
  12249. #ifndef OXOS
  12250. #ifdef VMIN
  12251.     cccbrk.c_cc[VMIN] = 1;
  12252. #endif /* VMIN */
  12253. #else /* OXOS */
  12254.     cccbrk.c_min = 1;
  12255. #endif /* OXOS */
  12256. #endif /* VEOF */
  12257. #ifdef ZILOG
  12258.     cccbrk.c_cc[5] = 0;
  12259. #else
  12260. #ifndef VEOL
  12261.     cccbrk.c_cc[5] = 1;
  12262. #else
  12263. #ifndef OXOS
  12264. #ifdef VTIME
  12265.     cccbrk.c_cc[VTIME] = 1;
  12266. #endif /* VTIME */
  12267. #else /* OXOS */
  12268.     cccbrk.c_time = 1;
  12269. #endif /* OXOS */
  12270. #endif /* VEOL */
  12271. #endif /* ZILOG */
  12272.     errno = 0;
  12273. #ifdef BSD44ORPOSIX            /* Set new modes */
  12274.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  12275. #else /* ATTSV */                  /* or the POSIX way */
  12276.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  12277. #endif /* BSD44ORPOSIX */
  12278. #endif /* SVORPOSIX */
  12279.  
  12280. #ifdef COHERENT
  12281. #undef SVORPOSIX
  12282. #endif /* COHERENT */
  12283.  
  12284.     debug(F101,"concb x","",x);
  12285.     debug(F101,"concb errno","",errno);
  12286.  
  12287. #ifdef  V7
  12288. #ifndef MINIX
  12289.     if (kmem[CON] < 0) {
  12290.         qaddr[CON] = initrawq(0);
  12291.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  12292.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  12293.             perror("/dev/kmem");
  12294.             exit(1);
  12295.         }
  12296.     }
  12297. #endif /* MINIX */
  12298. #endif /* V7 */
  12299. #endif /* Plan9 */
  12300.  
  12301.     if (x > -1)
  12302.       constate = CON_CB;
  12303.  
  12304.     debug(F101,"concb returns","",x);
  12305.     return(x);
  12306. }
  12307.  
  12308. /*  C O N B I N  --  Put console in binary mode  */
  12309.  
  12310. /*  Returns 0 if ok, -1 if not  */
  12311.  
  12312. int
  12313. #ifdef CK_ANSIC
  12314. conbin(char esc)
  12315. #else
  12316. conbin(esc) char esc;
  12317. #endif /* CK_ANSIC */
  12318. /* conbin */  {
  12319.  
  12320.     int x;
  12321.  
  12322.     debug(F101,"conbin constate","",constate);
  12323.  
  12324.     if (constate == CON_BIN)
  12325.       return(0);
  12326.  
  12327.     if (!isatty(0)) return(0);          /* only for real ttys */
  12328.     congm();                /* Get modes if necessary. */
  12329.     debug(F100,"conbin","",0);
  12330.     escchr = esc;                       /* Make this available to other fns */
  12331.     ckxech = 1;                         /* Program can echo characters */
  12332. #ifdef aegis
  12333.     conbufn = 0;
  12334.     if (concrp) return(write(1, "\035\002", 2));
  12335.     if (conuid == input_pad_$uid) {
  12336.     pad_$raw(ios_$stdin, st);
  12337.     return(0);
  12338.       }
  12339. #endif /* aegis */
  12340.  
  12341. #ifdef COHERENT
  12342. #define SVORPOSIX
  12343. #endif /* COHERENT */
  12344.  
  12345. #ifdef Plan9
  12346.     return p9conbin();
  12347. #else
  12348. #ifdef SVORPOSIX
  12349. #ifndef OXOS
  12350. #ifdef QNX
  12351.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12352. #else
  12353. #ifdef COHERENT
  12354.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12355. #else
  12356.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  12357. #endif /* COHERENT */
  12358. #endif /* QNX */
  12359. #else /* OXOS */
  12360.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12361.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  12362. #endif /* OXOS */
  12363.     ccraw.c_iflag |= IGNPAR;
  12364. /*
  12365.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  12366.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  12367.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  12368.   control, if in use, is not affected.
  12369. */
  12370. #ifdef ATTSV
  12371. #ifdef BSD44
  12372.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  12373.                         |INPCK|ISTRIP);
  12374. #else
  12375.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  12376.                         |INPCK|ISTRIP);
  12377. #endif /* BSD44 */
  12378. #else /* POSIX */
  12379.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  12380. #endif /* ATTSV */
  12381.     ccraw.c_oflag &= ~OPOST;
  12382. #ifdef COMMENT
  12383. /*
  12384.   WHAT THE HECK WAS THIS FOR?
  12385.   The B9600 setting (obviously) prevents CONNECT from working at any
  12386.   speed other than 9600 when you are logged in to the 7300 on a serial
  12387.   line.  Maybe some of the other flags are necessary -- if so, put back
  12388.   the ones that are needed.  This code is supposed to work the same, no
  12389.   matter whether you are logged in to the 7300 on the real console device,
  12390.   or through a serial port.
  12391. */
  12392. #ifdef ATT7300
  12393.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  12394. #endif /* ATT7300 */
  12395. #endif /* COMMENT */
  12396.  
  12397. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  12398.  *** pointed out that this should not be done, since some sites actually
  12399.  *** use terminals with parity settings on their Unix systems, and if we
  12400.  *** override the current settings and stop doing parity, then their terminals
  12401.  *** will display blotches for characters whose parity is wrong.  Therefore,
  12402.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  12403.  ***
  12404.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  12405.  ***   ccraw.c_cflag |= (CS8|CREAD);
  12406.  ***
  12407.  *** Sys III/V sites that have trouble with this can restore these lines.
  12408.  ***/
  12409. #ifndef VINTR
  12410.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  12411. #else
  12412.     ccraw.c_cc[VINTR] = 003;
  12413. #endif /* VINTR */
  12414. #ifndef VQUIT
  12415.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  12416. #else
  12417.     ccraw.c_cc[VQUIT] = escchr;
  12418. #endif /* VQUIT */
  12419. #ifndef VEOF
  12420.     ccraw.c_cc[4] = 1;
  12421. #else
  12422. #ifndef OXOS
  12423. #ifdef VMIN
  12424.     ccraw.c_cc[VMIN] = 1;
  12425. #endif /* VMIN */
  12426. #else /* OXOS */
  12427.     ccraw.c_min = 1;
  12428. #endif /* OXOS */
  12429. #endif /* VEOF */
  12430.  
  12431. #ifdef ZILOG
  12432.     ccraw.c_cc[5] = 0;
  12433. #else
  12434. #ifndef VEOL
  12435.     ccraw.c_cc[5] = 1;
  12436. #else
  12437. #ifndef OXOS
  12438. #ifdef VTIME
  12439.     ccraw.c_cc[VTIME] = 1;
  12440. #endif /* VTIME */
  12441. #else /* OXOS */
  12442.     ccraw.c_time = 1;
  12443. #endif /* OXOS */
  12444. #endif /* VEOL */
  12445. #endif /* ZILOG */
  12446.  
  12447. #ifdef BSD44ORPOSIX
  12448.     x = tcsetattr(0,TCSADRAIN,&ccraw);    /* Set new modes. */
  12449. #else
  12450.     x = ioctl(0,TCSETAW,&ccraw);
  12451. #endif /* BSD44ORPOSIX */
  12452. #else /* Berkeley, etc. */
  12453.     x = conchk();            /* Because stty() is destructive */
  12454.     if (x > 0)
  12455.       congetbuf(x);
  12456.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  12457.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  12458. #ifdef BELLV10
  12459.     x = ioctl(0,TIOCSETP,&ccraw);
  12460. #else
  12461.     x = stty(0,&ccraw);
  12462. #endif /* BELLV10 */
  12463. #endif /* SVORPOSIX */
  12464. #endif /* Plan9 */
  12465.  
  12466.     if (x > -1)
  12467.       constate = CON_BIN;
  12468.  
  12469.     debug(F101,"conbin returns","",x);
  12470.     return(x);
  12471.  
  12472. #ifdef COHERENT
  12473. #undef SVORPOSIX
  12474. #endif /* COHERENT */
  12475.  
  12476. }
  12477.  
  12478.  
  12479. /*  C O N R E S  --  Restore the console terminal  */
  12480.  
  12481. int
  12482. conres() {
  12483.     int x;
  12484.     debug(F101,"conres cgmf","",cgmf);
  12485.     debug(F101,"conres constate","",constate);
  12486.  
  12487.     if (cgmf < 1)            /* Do nothing if modes unchanged */
  12488.       return(0);
  12489.     if (constate == CON_RES)
  12490.       return(0);
  12491.  
  12492.     if (!isatty(0)) return(0);          /* only for real ttys */
  12493.     debug(F100,"conres isatty ok","",0);
  12494.     ckxech = 0;                         /* System should echo chars */
  12495.  
  12496. #ifdef aegis
  12497.     conbufn = 0;
  12498.     if (concrp) return(write(1, "\035\001", 2));
  12499.     if (conuid == input_pad_$uid) {
  12500.     pad_$cooked(ios_$stdin, st);
  12501.     constate = CON_RES;
  12502.     return(0);
  12503.     }
  12504. #endif /* aegis */
  12505.  
  12506. #ifdef Plan9
  12507.     p9conres();
  12508. #else
  12509. #ifdef BSD44ORPOSIX
  12510.     debug(F100,"conres restoring tcsetattr","",0);
  12511.     x = tcsetattr(0,TCSADRAIN,&ccold);
  12512. #else
  12513. #ifdef ATTSV
  12514.     debug(F100,"conres restoring ioctl","",0);
  12515.     x = ioctl(0,TCSETAW,&ccold);
  12516. #else /* BSD, V7, and friends */
  12517. #ifdef sony_news            /* Sony NEWS */
  12518.     if (km_con != -1)
  12519.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  12520. #endif /* sony_news */
  12521.     msleep(100);
  12522.     debug(F100,"conres restoring stty","",0);
  12523.     x = conchk();            /* Because stty() is destructive */
  12524.     if (x > 0)
  12525.       congetbuf(x);
  12526. #ifdef BELLV10
  12527.     x = ioctl(0,TIOCSETP,&ccold);
  12528. #else
  12529.     x = stty(0,&ccold);
  12530. #endif /* BELLV10 */
  12531. #endif /* ATTSV */
  12532. #endif /* BSD44ORPOSIX */
  12533. #endif /* Plan9 */
  12534.     if (x > -1)
  12535.       constate = CON_RES;
  12536.  
  12537.     debug(F101,"conres returns","",x);
  12538.     return(x);
  12539. }
  12540.  
  12541. /*  C O N O C  --  Output a character to the console terminal  */
  12542.  
  12543. int
  12544. #ifdef CK_ANSIC
  12545. conoc(char c)
  12546. #else
  12547. conoc(c) char c;
  12548. #endif /* CK_ANSIC */
  12549. /* conoc */ {
  12550.  
  12551. #ifdef IKSD
  12552.     if (inserver && !local)
  12553.       return(ttoc(c));
  12554.  
  12555. #ifdef CK_ENCRYPTION
  12556.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12557.         ck_tn_encrypt(&c,1);
  12558. #endif /* CK_ENCRYPTION */
  12559. #endif /* IKSD */
  12560.  
  12561. #ifdef Plan9
  12562.     return conwrite(&c,1);
  12563. #else
  12564.     return(write(1,&c,1));
  12565. #endif /* Plan9 */
  12566. }
  12567.  
  12568. /*  C O N X O  --  Write x characters to the console terminal  */
  12569.  
  12570. int
  12571. conxo(x,s) int x; char *s; {
  12572.  
  12573. #ifdef IKSD
  12574.     if (inserver && !local)
  12575.       return(ttol((CHAR *)s,x));
  12576.  
  12577. #ifdef CK_ENCRYPTION
  12578.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12579.         ck_tn_encrypt(s,x);
  12580. #endif /* CK_ENCRYPTION */
  12581. #endif /* IKSD */
  12582.  
  12583. #ifdef Plan9
  12584.     return(conwrite(s,x));
  12585. #else
  12586.     return(write(1,s,x));
  12587. #endif /* Plan9 */
  12588. }
  12589.  
  12590. /*  C O N O L  --  Write a line to the console terminal  */
  12591.  
  12592. int
  12593. conol(s) char *s; {
  12594.     int len;
  12595.     if (!s) s = "";            /* Always do this! */
  12596.     len = strlen(s);
  12597.     if (len == 0)
  12598.       return(0);
  12599.  
  12600. #ifdef IKSD
  12601.     if (inserver && !local)
  12602.       return(ttol((CHAR *)s,len));
  12603.  
  12604. #ifdef CK_ENCRYPTION
  12605.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  12606.     if (nxpacket < len) {
  12607.         if (xpacket) {
  12608.         free(xpacket);
  12609.         xpacket = NULL;
  12610.         nxpacket = 0;
  12611.         }
  12612.         len = len > 10240 ? len : 10240;
  12613.         xpacket = (CHAR *)malloc(len);
  12614.         if (!xpacket) {
  12615.         fprintf(stderr,"ttol malloc failure\n");
  12616.         return(-1);
  12617.         } else
  12618.           nxpacket = len;
  12619.     }
  12620.     memcpy(xpacket,s,len);
  12621.     s = (char *)xpacket;
  12622.     ck_tn_encrypt(s,len);
  12623.     }
  12624. #endif /* CK_ENCRYPTION */
  12625. #endif /* IKSD */
  12626.  
  12627. #ifdef Plan9
  12628.     return(conwrite(s,len));
  12629. #else
  12630.     return(write(1,s,len));
  12631. #endif /* Plan9 */
  12632. }
  12633.  
  12634. /*  C O N O L A  --  Write an array of lines to the console terminal */
  12635.  
  12636. int
  12637. conola(s) char *s[]; {
  12638.     char * p;
  12639.     int i, x;
  12640.  
  12641.  
  12642.     if (!s) return(0);
  12643.     for (i = 0; ; i++) {
  12644.     p = s[i];
  12645.     if (!p) p = "";            /* Let's not dump core shall we? */
  12646.     if (!*p)
  12647.       break;
  12648. #ifdef IKSD
  12649.     if (inserver && !local)
  12650.       x = ttol((CHAR *)p,(int)strlen(p));
  12651.     else
  12652. #endif /* IKSD */
  12653.       x = conol(p);
  12654.     if (x < 0)
  12655.       return(-1);
  12656.     }
  12657.     return(0);
  12658. }
  12659.  
  12660. /*  C O N O L L  --  Output a string followed by CRLF  */
  12661.  
  12662. int
  12663. conoll(s) char *s; {
  12664.     CHAR buf[3];
  12665.     buf[0] = '\r';
  12666.     buf[1] = '\n';
  12667.     buf[2] = '\0';
  12668.     if (!s) s = "";
  12669.  
  12670. #ifdef IKSD
  12671.     if (inserver && !local) {
  12672.     if (*s) ttol((CHAR *)s,(int)strlen(s));
  12673.     return(ttol(buf,2));
  12674.     }
  12675. #endif /* IKSD */
  12676.  
  12677.     if (*s) conol(s);
  12678. #ifdef IKSD
  12679. #ifdef CK_ENCRYPTION
  12680.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12681.       ck_tn_encrypt((char *)buf,2);
  12682. #endif /* CK_ENCRYPTION */
  12683. #endif /* IKSD */
  12684.  
  12685. #ifdef Plan9
  12686.     return(conwrite(buf, 2));
  12687. #else
  12688.     return(write(1,buf,2));
  12689. #endif /* Plan9 */
  12690. }
  12691.  
  12692. /*  C O N C H K  --  Return how many characters available at console  */
  12693. /*
  12694.   We could also use select() here to cover a few more systems that are not
  12695.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  12696. */
  12697. int
  12698. conchk() {
  12699.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  12700.  
  12701.     if (contyp == 0)            /* This prevents unnecessary */
  12702.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  12703.     debug(F101,"conchk contyp","",contyp);
  12704.     if (backgrd || (contyp < 0))
  12705.       return(0);
  12706.  
  12707. #ifdef aegis
  12708.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  12709.  
  12710.     /* read in more characters */
  12711.     conbufn = ios_$get(ios_$stdin,
  12712.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  12713.     if (st.all != status_$ok) conbufn = 0;
  12714.     conbufp = conbuf;
  12715.     return(conbufn);
  12716. #else
  12717. #ifdef IKSD
  12718.     if (inserver && !local)
  12719.       return(in_chk(1,ttyfd));
  12720.     else
  12721. #endif /* IKSD */
  12722.       return(in_chk(0,0));
  12723. #endif /* aegis */
  12724. }
  12725.  
  12726. /*  C O N I N C  --  Get a character from the console  */
  12727. /*
  12728.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  12729.   read.  Upon success, returns the character.  Upon failure, returns -1.
  12730.   A timed read that does not complete within the timeout period returns -2.
  12731. */
  12732. int
  12733. coninc(timo) int timo; {
  12734.     int n = 0; CHAR ch;
  12735.     int xx;
  12736.  
  12737.     if (conbufn > 0) {            /* If something already buffered */
  12738.     --conbufn;
  12739.     return((unsigned)(*conbufp++ & 0xff));
  12740.     }
  12741.  
  12742.     errno = 0;                /* Clear this */
  12743. #ifdef IKSD
  12744.     if (inserver && !local) {
  12745.     xx = ttinc(timo);
  12746.     if (xx < 0)
  12747.       return(ttinctimo ? -2 : -1);
  12748.     else
  12749.       return(xx);
  12750.     }
  12751. #endif /* IKSD */
  12752.  
  12753. #ifdef aegis                /* Apollo Aegis only... */
  12754.     debug(F101,"coninc timo","",timo);
  12755.     fflush(stdout);
  12756.     if (conchk() > 0) {
  12757.     --conbufn;
  12758.     return((unsigned)(*conbufp++ & 0xff));
  12759.     }
  12760. #endif /* aegis */
  12761.  
  12762. #ifdef TTLEBUF
  12763.     if (
  12764. #ifdef IKSD
  12765.     inserver &&
  12766. #endif /* IKSD */
  12767.     !xlocal
  12768.     ) {
  12769.     if (ttpush >= 0) {
  12770.         debug(F111,"ttinc","ttpush",ttpush);
  12771.         ch = ttpush;
  12772.         ttpush = -1;
  12773.         return(ch);
  12774.     }
  12775.     if (le_data) {
  12776.         if (le_getchar(&ch) > 0) {
  12777.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  12778.         return(ch);
  12779.         }
  12780.     }
  12781.     }
  12782. #endif /* TTLEBUF */
  12783.  
  12784.     if (timo <= 0) {            /* Untimed, blocking read. */
  12785.     while (1) {            /* Keep trying till we get one. */
  12786.         n = read(0, &ch, 1);    /* Read a character. */
  12787.         if (n == 0) continue;    /* Shouldn't happen. */
  12788.         if (n > 0) {        /* If read was successful, */
  12789. #ifdef IKSD
  12790. #ifdef CK_ENCRYPTION
  12791.                 debug(F100,"coninc decrypt 1","",0);
  12792.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12793.           ck_tn_decrypt((char *)&ch,1);
  12794. #endif /* CK_ENCRYPTION */
  12795. #endif /* IKSD */
  12796.         return((unsigned)(ch & 0xff)); /* return the character. */
  12797.             }
  12798.  
  12799. /* Come here if read() returned an error. */
  12800.  
  12801.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  12802. #ifndef OXOS
  12803. #ifdef SVORPOSIX
  12804. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  12805. #ifndef EINTR
  12806. #define EINTR 4
  12807. #endif /* EINTR */
  12808. #endif /* CIE */
  12809. /*
  12810.   This routine is used for several different purposes.  In CONNECT mode, it is
  12811.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  12812.   fork.  During local-mode file transfer, it reads a character from the
  12813.   console to interrupt the file transfer (like A for a status report, X to
  12814.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  12815.   to be blocking, or the file transfer would stop until the user typed
  12816.   something.  Unfortunately, System V does not allow the console device input
  12817.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  12818.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  12819.   and trapped by esctrp(), and this routine pretends to have read the quit
  12820.   character from the keyboard normally.  But, kludge or no kludge, the read()
  12821.   issued by this command, under System V only, can fail if a signal -- ANY
  12822.   signal -- is caught while the read is pending.  This can occur not only when
  12823.   the user types the quit character, but also during telnet negotiations, when
  12824.   the lower CONNECT fork signals the upper one about an echoing mode change.
  12825.   When this happens, we have to post the read() again.  This is apparently not
  12826.   a problem in BSD-based UNIX versions.
  12827. */
  12828.         if (errno == EINTR)        /* Read interrupted. */
  12829.           if (conesc)  {        /* If by SIGQUIT, */
  12830.           conesc = 0;        /* the conesc variable is set, */
  12831.           return(escchr);    /* so return the escape character. */
  12832.          } else continue;        /* By other signal, try again. */
  12833. #else
  12834. /*
  12835.   This might be dangerous, but let's do this on non-System V versions too,
  12836.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  12837.   upon first making a TELNET connection.
  12838. */
  12839.         if (errno == EINTR)        /* Read interrupted. */
  12840.           continue;
  12841. #endif /* SVORPOSIX */
  12842. #else /* OXOS */
  12843.         if (errno == EINTR)        /* Read interrupted. */
  12844.           continue;
  12845. #endif /* OXOS */
  12846.         return(-1);            /* Error */
  12847.     }
  12848.     }
  12849. #ifdef DEBUG
  12850.     if (deblog && timo <= 0) {
  12851.     debug(F100,"coninc timeout logic error","",0);
  12852.     timo = 1;
  12853.     }
  12854. #endif /* DEBUG */
  12855.  
  12856. /* Timed read... */
  12857.  
  12858.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  12859.     xx = alarm(timo);            /* Set the alarm. */
  12860.     debug(F101,"coninc alarm set","",timo);
  12861.     if (
  12862. #ifdef CK_POSIX_SIG
  12863.     sigsetjmp(sjbuf,1)
  12864. #else
  12865.     setjmp(sjbuf)
  12866. #endif /* CK_POSIX_SIG */
  12867.     )                /* The read() timed out. */
  12868.       n = -2;                /* Code for timeout. */
  12869.     else
  12870.       n = read(0, &ch, 1);
  12871.     ttimoff();                /* Turn off timer */
  12872.     if (n > 0) {            /* Got character OK. */
  12873. #ifdef IKSD
  12874. #ifdef CK_ENCRYPTION
  12875.         debug(F100,"coninc decrypt 2","",0);
  12876.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12877.       ck_tn_decrypt((char *)&ch,1);
  12878. #endif /* CK_ENCRYPTION */
  12879. #endif /* IKSD */
  12880.     return((unsigned)(ch & 0xff));    /* Return it. */
  12881.     }
  12882. /*
  12883.   read() returned an error.  Same deal as above, but without the loop.
  12884. */
  12885.     debug(F101, "coninc(timo) n","",n);
  12886.     debug(F101, "coninc(timo) errno","",errno);
  12887. #ifndef OXOS
  12888. #ifdef SVORPOSIX
  12889.     if (n == -1 && errno == EINTR && conesc != 0) {
  12890.     conesc = 0;
  12891.     return(escchr);            /* User entered escape character. */
  12892.     }
  12893. #endif /* SVORPOSIX */
  12894.     if (n == 0 && errno > 0) {        /* It's an error */
  12895.     return(-1);
  12896.     }
  12897. #endif /* ! OXOS */
  12898.     return(n);
  12899. }
  12900.  
  12901. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  12902.  
  12903. #ifndef congks
  12904. /*
  12905.   This function needs to be filled in with the various system-dependent
  12906.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  12907.   keyboard scan code.  Unfortunately there aren't any.
  12908. */
  12909. int
  12910. congks(timo) int timo; {
  12911.  
  12912. #ifdef IKSD
  12913.     if (inserver && !local)
  12914.       return(ttinc(timo));
  12915. #endif /* IKSD */
  12916.  
  12917.     return(coninc(timo));
  12918. }
  12919. #endif /* congks */
  12920.  
  12921. #ifdef ATT7300
  12922.  
  12923. /*  A T T D I A L  --  Dial up the remote system using internal modem
  12924.  * Purpose: to open and dial a number on the internal modem available on the
  12925.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  12926.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  12927.  * Uses information in <sys/phone.h> and our status int attmodem.
  12928.  */
  12929. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  12930.     char *telnum;
  12931.  
  12932.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  12933.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  12934.                     /* We turn this flag off once the dial is complete */
  12935.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  12936.  
  12937.     /* Condition line, check availability & DATA mode, turn on speaker */
  12938.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  12939.         printf("cannot access phone\n");
  12940.         ttclos(0);
  12941.         return (-2);
  12942.     }
  12943.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  12944.  
  12945.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  12946.         printf(" Should not dial with modem in VOICE mode.\n");
  12947.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  12948.         ttclos(0);
  12949.         return (-2);
  12950.     }
  12951. #ifdef ATTTONED                /* Old way, tone dialing only. */
  12952.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  12953.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  12954. #else
  12955.     /* Leave current pulse/tone state alone. */
  12956.     /* But what about DATA?  Add it back if you have trouble. */
  12957.     /* sys/phone says you get DATA automatically by opening device RDWR */
  12958. #endif
  12959.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  12960. #ifdef COMMENT
  12961.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  12962. #else
  12963.     /* sys/phone says RINGON used only for incoming voice calls */
  12964.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  12965.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  12966. #endif
  12967.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  12968.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  12969.         printf("Cannot set modem characteristics\n");
  12970.         ttclos(0);
  12971.         return (-2);
  12972.     }
  12973.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  12974.  
  12975. #ifdef COMMENT
  12976.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  12977. line_status:%o feedback:%o\n",
  12978.     dialer.c_lineparam, dialer.c_waitdialtone,
  12979.     dialer.c_linestatus, dialer.c_feedback);
  12980. #endif
  12981.  
  12982.     attmodem |= ISMODEM;                        /* modem is now in-use */
  12983.     sleep(1);
  12984.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  12985. #ifdef ATTTONED
  12986.       /* Tone dialing only */
  12987.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12988.       perror("Error in dialing");
  12989.       ttclos(0);
  12990.       return(-2);
  12991.       }
  12992. #else /* Allow Pulse or Tone dialing */
  12993.     switch (*telnum) {
  12994.       case 't': case 'T': case '%':    /* Tone dialing requested */
  12995.     dialer.c_lineparam |= DTMF;
  12996.     dialer.c_lineparam &= ~PULSE;
  12997.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12998.         printf("Cannot set modem to tone dialing\n");
  12999.         ttclos(0);
  13000.         return(-2);
  13001.     }
  13002.     break;
  13003.       case 'd': case 'D': case 'p': case 'P': case '^':
  13004.     dialer.c_lineparam |= PULSE;
  13005.     dialer.c_lineparam &= ~DTMF;
  13006.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  13007.         printf("Cannot set modem to pulse dialing\n");
  13008.         ttclos(0);
  13009.         return(-2);
  13010.     }
  13011.     break;
  13012.       default:
  13013.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  13014.         perror("Dialing error");
  13015.         ttclos(0);
  13016.         return(-2);
  13017.     }
  13018.     break;
  13019.     }
  13020. #endif
  13021.  
  13022.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  13023.     do {                /* wait for modems to Connect */
  13024.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  13025.         perror("Cannot get modems to connect");
  13026.         ttclos(0);
  13027.         return(-2);
  13028.     }
  13029.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  13030.     /* Turn off O_NDELAY flag now. */
  13031.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  13032.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  13033.     return(0);                          /* return success */
  13034. }
  13035.  
  13036. /*
  13037.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  13038.   and restore it to the indicated line.  Shell's return codes are:
  13039.     0: Can't do it.  Probably a user logged on.
  13040.     1: No need.  No getty on that line.
  13041.     2: Done, you should restore the getty when you're done.
  13042.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  13043.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  13044.  
  13045.    getoff.sh looks like:   geton.sh looks like:
  13046.      setgetty $1 0           setgetty $1 1
  13047.      err=$?                  exit $?
  13048.      sleep 2
  13049.      exit $err
  13050. */
  13051.  
  13052. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  13053.  * and get status so it can be restarted after the line is hung up.
  13054.  */
  13055. int
  13056. offgetty(ttname) char *ttname; {
  13057.     char temp[30];
  13058.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  13059.     ttname -= 3;                            /* get last 3 chars of name */
  13060.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  13061.     return(zsyscmd(temp));
  13062. }
  13063.  
  13064. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  13065.  
  13066. int
  13067. ongetty(ttname) char *ttname; {
  13068.     char temp[30];
  13069.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  13070.     ttname -= 3;
  13071.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  13072.     return(zsyscmd(temp));
  13073. }
  13074. #endif /* ATT7300 */
  13075.  
  13076. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  13077.  *
  13078.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  13079.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  13080.  *  2 = Auto: For "modem direct": The same as "Off".
  13081.  *            For real modem types: Heed carrier during connect, but ignore
  13082.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  13083.  *
  13084.  * As you can see, this setting does not affect dialing, which always ignores
  13085.  * carrier (unless there is some special exception for some modem type).  It
  13086.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  13087.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  13088.  * (or should be) always called before any communications is tried, which
  13089.  * means that, practically speaking, the effect is immediate.
  13090.  *
  13091.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  13092.  *
  13093.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  13094.  * environment (or any non-termio using environment).  Until that time, this
  13095.  * will simply be a no-op for BSD.
  13096.  *
  13097.  * Note that in previous versions, the carrier was most often left unchanged
  13098.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  13099.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  13100.  * modes.
  13101.  */
  13102. int
  13103. ttscarr(carrier) int carrier; {
  13104.     ttcarr = carrier;
  13105.     debug(F101, "ttscarr","",ttcarr);
  13106.     return(ttcarr);
  13107. }
  13108.  
  13109. /* C A R R C T L  --  Set tty modes for carrier treatment.
  13110.  *
  13111.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  13112.  * (actually, there are no bits in sgttyb for that), or performs any other
  13113.  * operations needed to control this on the current system.  The function does
  13114.  * not do the actual TCSETA or stty, since often we want to set other bits too
  13115.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  13116.  *
  13117.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  13118.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  13119.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  13120.  * forth between the upper and lower case device files.  Maybe later.
  13121.  * Presently, Xenix will stick to the mode it was opened with.
  13122.  *
  13123.  * carrier: 0 = ignore carrier, 1 = require carrier.
  13124.  * The current state is saved in curcarr, and checked to save labour.
  13125.  */
  13126. #ifdef SVORPOSIX
  13127. int
  13128. #ifdef BSD44ORPOSIX
  13129. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  13130. #else /* ATTSV */
  13131. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  13132. #endif /* BSD44ORPOSIX */
  13133. /* carrctl */ {
  13134.     debug(F101, "carrctl","",carrier);
  13135.     if (carrier)
  13136.       ttpar->c_cflag &= ~CLOCAL;
  13137.     else
  13138.       ttpar->c_cflag |= CLOCAL;
  13139.     return(0);
  13140. }
  13141. #else /* Berkeley, V7, et al... */
  13142. int
  13143. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  13144.     debug(F101, "carrctl","",carrier);
  13145.     if (carrier == curcarr)
  13146.       return(0);
  13147.     curcarr = carrier;
  13148. #ifdef ultrix
  13149. #ifdef COMMENT
  13150. /*
  13151.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  13152. */
  13153.     if (carrier) {
  13154.     ioctl(ttyfd, TIOCMODEM, &temp);
  13155.     ioctl(ttyfd, TIOCHPCL, 0);
  13156.     } else {
  13157.     /* (According to the manuals, TIOCNCAR should be preferred */
  13158.     /* over TIOCNMODEM...) */
  13159.     ioctl(ttyfd, TIOCNMODEM, &temp);
  13160.     }
  13161. #else
  13162. /*
  13163.   New code from Jamie Watson that, he says, eliminates the problems.
  13164. */
  13165.     if (carrier) {
  13166.     ioctl(ttyfd, TIOCCAR);
  13167.     ioctl(ttyfd, TIOCHPCL);
  13168.     } else {
  13169.     ioctl(ttyfd, TIOCNCAR);
  13170.     }
  13171. #endif /* COMMENT */
  13172. #endif /* ultrix */
  13173.     return(0);
  13174. }
  13175. #endif /* SVORPOSIX */
  13176.  
  13177.  
  13178. /*  T T G M D M  --  Get modem signals  */
  13179. /*
  13180.  Looks for RS-232 modem signals, and returns those that are on in as its
  13181.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  13182.  Returns:
  13183.  -3 Not implemented
  13184.  -2 if the communication device does not have modem control (e.g. telnet)
  13185.  -1 on error.
  13186.  >= 0 on success, with a bit mask containing the modem signals that are on.
  13187. */
  13188.  
  13189. /*
  13190.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  13191.   modem control, namely the TIOCMGET ioctl.
  13192. */
  13193.  
  13194. #ifdef BSD43
  13195. #define K_MDMCTL
  13196. #endif /* BSD43 */
  13197.  
  13198. #ifdef SUNOS4
  13199. #define K_MDMCTL
  13200. #endif /* SUNOS4 */
  13201.  
  13202. /*
  13203.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  13204.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  13205.   must be defined in order to get the high serial speeds that are new to
  13206.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  13207.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  13208.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  13209.   driven by those drivers.
  13210. */
  13211. #ifdef SCO_OSR504
  13212. #ifndef TIOCMGET
  13213. #define TIOCMGET (('t'<<8)|29)
  13214. #endif /* TIOCMGET */
  13215. #endif /* SCO_OSR504 */
  13216.  
  13217. #ifdef CK_SCOV5
  13218. /* Because POSIX strictness in <sys/termio.h> won't let us see these. */
  13219. #ifndef TIOCM_DTR
  13220. #define TIOCM_DTR    0x0002        /* data terminal ready */
  13221. #define TIOCM_RTS    0x0004        /* request to send */
  13222. #define TIOCM_CTS    0x0020        /* clear to send */
  13223. #define TIOCM_CAR    0x0040        /* carrier detect */
  13224. #define TIOCM_RNG    0x0080        /* ring */
  13225. #define TIOCM_DSR    0x0100        /* data set ready */
  13226. #define TIOCM_CD    TIOCM_CAR
  13227. #define TIOCM_RI    TIOCM_RNG
  13228. #endif /* TIOCM_DTR */
  13229. #endif /* CK_SCOV5 */
  13230.  
  13231. #ifdef QNX
  13232. #define K_MDMCTL
  13233. #else
  13234. #ifdef TIOCMGET
  13235. #define K_MDMCTL
  13236. #endif /* TIOCMGET */
  13237. #endif /* QNX */
  13238. /*
  13239.   "A serial communication program that can't read modem signals
  13240.    is like a car without windows."
  13241. */
  13242. int
  13243. ttgmdm() {
  13244.  
  13245. #ifdef QNX
  13246. #include <sys/qioctl.h>
  13247.  
  13248.     unsigned long y, mdmbits[2];
  13249.     int x, z = 0;
  13250.  
  13251.     if (xlocal && ttyfd < 0)
  13252.       return(-1);
  13253.  
  13254. #ifdef NETCONN
  13255.     if (netconn) {            /* Network connection */
  13256. #ifdef TN_COMPORT
  13257.         if (istncomport()) {
  13258.         gotsigs = 1;
  13259.         return(tngmdm());
  13260.     } else
  13261. #endif /* TN_COMPORT */
  13262.       return(-2);            /* No modem signals */
  13263.     }
  13264. #endif /* NETCONN */
  13265.  
  13266. #ifdef NETCMD
  13267.     if (ttpipe) return(-2);
  13268. #endif /* NETCMD */
  13269. #ifdef NETPTY
  13270.     if (ttpty) return(-2);
  13271. #endif /* NETPTY */
  13272.  
  13273.     mdmbits[0] = 0L;
  13274.     mdmbits[1] = 0L;
  13275. /*
  13276.  * From <sys/qioctl.h>:
  13277.  *
  13278.  * SERIAL devices   (all Dev.ser versions)
  13279.  * 0 : DTR           8 = Data Bits 0  16 - reserved     24 - reserved
  13280.  * 1 : RTS           9 = Data Bits 1  17 - reserved     25 - reserved
  13281.  * 2 = Out 1        10 = Stop Bits    18 - reserved     26 - reserved
  13282.  * 3 = Int Enable   11 = Par Enable   19 - reserved     27 - reserved
  13283.  * 4 = Loop         12 = Par Even     20 = CTS          28 - reserved
  13284.  * 5 - reserved     13 = Par Stick    21 = DSR          29 - reserved
  13285.  * 6 - reserved     14 : Break        22 = RI           30 - reserved
  13286.  * 7 - reserved     15 = 0            23 = CD           31 - reserved
  13287.  */
  13288.     errno = 0;
  13289.     x = qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4);
  13290.     debug(F101,"ttgmdm qnx_ioctl","",x);
  13291.     debug(F101,"ttgmdm qnx_ioctl errno","",errno);
  13292.     if (!x) {
  13293.     debug(F101,"ttgmdm qnx_ioctl mdmbits[0]","",mdmbits[0]);
  13294.     debug(F101,"ttgmdm qnx_ioctl mdmbits[1]","",mdmbits[1]);
  13295.     y = mdmbits[0];
  13296.     if (y & 0x000001L) z |= BM_DTR;    /* Bit  0 */
  13297.     if (y & 0x000002L) z |= BM_RTS;    /* Bit  1 */
  13298.     if (y & 0x100000L) z |= BM_CTS;    /* Bit 20 */
  13299.     if (y & 0x200000L) z |= BM_DSR;    /* Bit 21 */
  13300.     if (y & 0x400000L) z |= BM_RNG;    /* Bit 22 */
  13301.     if (y & 0x800000L) z |= BM_DCD;    /* Bit 23 */
  13302.     debug(F101,"ttgmdm qnx result","",z);
  13303.     debug(F110,"ttgmdm qnx CD = ",(z & BM_DCD) ? "On" : "Off", 0);
  13304.     gotsigs = 1;
  13305.     return(z);
  13306.     } else return(-1);
  13307. #else /* QNX */
  13308. #ifdef HPUX                /* HPUX has its own way */
  13309.     int x, z;
  13310.  
  13311. #ifdef HPUX10                /* Modem flag word */
  13312.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  13313. #else
  13314. #ifdef HPUX9
  13315.     mflag y;
  13316. #else
  13317. #ifdef HPUX8
  13318.     mflag y;
  13319. #else
  13320.     unsigned long y;            /* Not sure about pre-8.0... */
  13321. #endif /* HPUX8 */
  13322. #endif /* HPUX9 */
  13323. #endif /* HPUX10 */
  13324.  
  13325.     if (xlocal && ttyfd < 0)
  13326.       return(-1);
  13327.  
  13328. #ifdef NETCONN
  13329.     if (netconn) {            /* Network connection */
  13330. #ifdef TN_COMPORT
  13331.         if (istncomport()) {
  13332.         gotsigs = 1;
  13333.         return(tngmdm());
  13334.     } else
  13335. #endif /* TN_COMPORT */
  13336.       return(-2);            /* No modem signals */
  13337.     }
  13338. #endif /* NETCONN */
  13339.  
  13340. #ifdef NETCMD
  13341.     if (ttpipe) return(-2);
  13342. #endif /* NETCMD */
  13343. #ifdef NETPTY
  13344.     if (ttpty) return(-2);
  13345. #endif /* NETPTY */
  13346.  
  13347.     if (xlocal)                /* Get modem signals */
  13348.       x = ioctl(ttyfd,MCGETA,&y);
  13349.     else
  13350.       x = ioctl(0,MCGETA,&y);
  13351.     if (x < 0) return(-1);
  13352.     debug(F101,"ttgmdm","",y);
  13353.  
  13354.     z = 0;                /* Initialize return value */
  13355.  
  13356. /* Now set bits for each modem signal that is reported to be on. */
  13357.  
  13358. #ifdef MCTS
  13359.     /* Clear To Send */
  13360.     debug(F101,"ttgmdm HPUX CTS","",y & MCTS);
  13361.     if (y & MCTS) z |= BM_CTS;
  13362. #endif
  13363. #ifdef MDSR
  13364.     /* Data Set Ready */
  13365.     debug(F101,"ttgmdm HPUX DSR","",y & MDSR);
  13366.     if (y & MDSR) z |= BM_DSR;
  13367. #endif
  13368. #ifdef MDCD
  13369.     /* Carrier */
  13370.     debug(F101,"ttgmdm HPUX DCD","",y & MDCD);
  13371.     if (y & MDCD) z |= BM_DCD;
  13372. #endif
  13373. #ifdef MRI
  13374.     /* Ring Indicate */
  13375.     debug(F101,"ttgmdm HPUX RI","",y & MRI);
  13376.     if (y & MRI) z |= BM_RNG;
  13377. #endif
  13378. #ifdef MDTR
  13379.     /* Data Terminal Ready */
  13380.     debug(F101,"ttgmdm HPUX DTR","",y & MDTR);
  13381.     if (y & MDTR) z |= BM_DTR;
  13382. #endif
  13383. #ifdef MRTS
  13384.     /* Request To Send */
  13385.     debug(F101,"ttgmdm HPUX RTS","",y & MRTS);
  13386.     if (y & MRTS) z |= BM_RTS;
  13387. #endif
  13388.     gotsigs = 1;
  13389.     return(z);
  13390.  
  13391. #else /* ! HPUX */
  13392.  
  13393. #ifdef K_MDMCTL
  13394. /*
  13395.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  13396.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  13397.   are needed.
  13398. */
  13399. #ifndef TIOCMGET
  13400. #include <sys/ttycom.h>
  13401. #endif /* TIOCMGET */
  13402.  
  13403.     int x, y, z;
  13404.  
  13405.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  13406.  
  13407. #ifdef NETCONN
  13408.     if (netconn) {            /* Network connection */
  13409. #ifdef TN_COMPORT
  13410.         if (istncomport()) {
  13411.         gotsigs = 1;
  13412.         return(tngmdm());
  13413.     } else
  13414. #endif /* TN_COMPORT */
  13415.       return(-2);            /* No modem signals */
  13416.     }
  13417. #endif /* NETCONN */
  13418.  
  13419. #ifdef NETCMD
  13420.     if (ttpipe) return(-2);
  13421. #endif /* NETCMD */
  13422. #ifdef NETPTY
  13423.     if (ttpty) return(-2);
  13424. #endif /* NETPTY */
  13425.  
  13426.     if (xlocal && ttyfd < 0)
  13427.       return(-1);
  13428.  
  13429.     if (xlocal)
  13430.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  13431.     else
  13432.       x = ioctl(0,TIOCMGET,&y);
  13433.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  13434.     if (x < 0) {
  13435.     debug(F101,"ttgmdm errno","",errno);
  13436.     return(-1);
  13437.     }
  13438.     debug(F101,"ttgmdm bits","",y);
  13439.  
  13440.     z = 0;                /* Initialize return value. */
  13441. #ifdef TIOCM_CTS
  13442.     /* Clear To Send */
  13443.     if (y & TIOCM_CTS) z |= BM_CTS;
  13444.     debug(F101,"ttgmdm TIOCM_CTS defined","",TIOCM_CTS); 
  13445. #else
  13446.     debug(F100,"ttgmdm TIOCM_CTS not defined","",0);
  13447. #endif
  13448. #ifdef TIOCM_DSR
  13449.     /* Data Set Ready */
  13450.     if (y & TIOCM_DSR) z |= BM_DSR;
  13451.     debug(F101,"ttgmdm TIOCM_DSR defined","",TIOCM_DSR); 
  13452. #else
  13453.     debug(F100,"ttgmdm TIOCM_DSR not defined","",0);
  13454. #endif
  13455. #ifdef TIOCM_CAR
  13456.     /* Carrier */
  13457.     if (y & TIOCM_CAR) z |= BM_DCD;
  13458.     debug(F101,"ttgmdm TIOCM_CAR defined","",TIOCM_CAR); 
  13459. #else
  13460.     debug(F100,"ttgmdm TIOCM_CAR not defined","",0);
  13461. #endif
  13462. #ifdef TIOCM_RNG
  13463.     /* Ring Indicate */
  13464.     if (y & TIOCM_RNG) z |= BM_RNG;
  13465.     debug(F101,"ttgmdm TIOCM_RNG defined","",TIOCM_RNG); 
  13466. #else
  13467.     debug(F100,"ttgmdm TIOCM_RNG not defined","",0);
  13468. #endif
  13469. #ifdef TIOCM_DTR
  13470.     /* Data Terminal Ready */
  13471.     if (y & TIOCM_DTR) z |= BM_DTR;
  13472.     debug(F101,"ttgmdm TIOCM_DTR defined","",TIOCM_DTR); 
  13473. #else
  13474.     debug(F100,"ttgmdm TIOCM_DTR not defined","",0);
  13475. #endif
  13476. #ifdef TIOCM_RTS
  13477.     /* Request To Send */
  13478.     if (y & TIOCM_RTS) z |= BM_RTS;
  13479.     debug(F101,"ttgmdm TIOCM_RTS defined","",TIOCM_RTS); 
  13480. #else
  13481.     debug(F100,"ttgmdm TIOCM_RTS not defined","",0);
  13482. #endif
  13483.     gotsigs = 1;
  13484.     return(z);
  13485.  
  13486. #else /* !K_MDMCTL catch-All */
  13487.  
  13488.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  13489. #ifdef TIOCMGET
  13490.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  13491. #else
  13492.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  13493. #endif /* TIOCMGET */
  13494. #ifdef _SVID3
  13495.     debug(F100,"ttgmdm _SVID3 defined","",0);
  13496. #else
  13497.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  13498. #endif /* _SVID3 */
  13499.  
  13500. #ifdef NETCONN
  13501.     if (netconn) {            /* Network connection */
  13502. #ifdef TN_COMPORT
  13503.         if (istncomport()) {
  13504.         gotsigs = 1;
  13505.         return(tngmdm());
  13506.     } else
  13507. #endif /* TN_COMPORT */
  13508.       return(-2);            /* No modem signals */
  13509.     }
  13510. #endif /* NETCONN */
  13511.  
  13512. #ifdef NETCMD
  13513.     if (ttpipe) return(-2);
  13514. #endif /* NETCMD */
  13515. #ifdef NETPTY
  13516.     if (ttpty) return(-2);
  13517. #endif /* NETPTY */
  13518.  
  13519.     return(-3);                /* Sorry, I don't know how... */
  13520.  
  13521. #endif /* K_MDMCTL */
  13522. #endif /* HPUX */
  13523. #endif /* QNX */
  13524. }
  13525.  
  13526. /*  P S U S P E N D  --  Put this process in the background.  */
  13527.  
  13528. /*
  13529.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  13530.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  13531.   kill() returned an error code.
  13532. */
  13533. int
  13534. psuspend(flag) int flag; {
  13535.  
  13536. #ifdef RTU
  13537.     extern int rtu_bug;
  13538. #endif /* RTU */
  13539.  
  13540.     if (flag == 0) return(-1);
  13541.  
  13542. #ifdef NOJC
  13543.     return(-1);
  13544. #else
  13545. #ifdef SIGTSTP
  13546. /*
  13547.   The big question here is whether job control is *really* supported.
  13548.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  13549.   defined does not guarantee the Unix kernel supports it, and the fact
  13550.   that the Unix kernel supports it doesn't guarantee that the user's
  13551.   shell (or other process that invoked Kermit) supports it.
  13552. */
  13553. #ifdef RTU
  13554.     rtu_bug = 1;
  13555. #endif /* RTU */
  13556.     if (kill(0,SIGSTOP) < 0
  13557. #ifdef MIPS
  13558. /* Let's try this for MIPS too. */
  13559.     && kill(getpid(),SIGSTOP) < 0
  13560. #endif /* MIPS */
  13561.     ) {                /* If job control, suspend the job */
  13562.     perror("suspend");
  13563.     debug(F101,"psuspend error","",errno);
  13564.     return(-1);
  13565.     }
  13566.     debug(F100,"psuspend ok","",0);
  13567.     return(0);
  13568. #else
  13569.     return(-1);
  13570. #endif /* SIGTSTP */
  13571. #endif /* NOJC */
  13572. }
  13573.  
  13574. /*
  13575.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  13576.   Long and fdc.
  13577. */
  13578.  
  13579. /* The following is for SCO when CK_ANSILIBS is defined... */
  13580. #ifdef M_UNIX
  13581. #ifdef CK_ANSILIBS
  13582. #ifndef NOGETID_PROTOS
  13583. #define NOGETID_PROTOS
  13584. #endif /* NOGETID_PROTOS */
  13585. #endif /* CK_ANSILIBS */
  13586. #endif /* M_UNIX */
  13587.  
  13588. #ifndef _POSIX_SOURCE
  13589. #ifndef SUNOS4
  13590. #ifndef NEXT
  13591. #ifndef PS2AIX10
  13592. #ifndef sequent
  13593. #ifndef HPUX9
  13594. #ifndef HPUX10
  13595. #ifndef COHERENT
  13596. #ifndef NOGETID_PROTOS
  13597. _PROTOTYP( UID_T getuid, (void) );
  13598. _PROTOTYP( UID_T geteuid, (void) );
  13599. _PROTOTYP( UID_T getreuid, (void) );
  13600. _PROTOTYP( UID_T getgid, (void) );
  13601. _PROTOTYP( UID_T getegid, (void) );
  13602. _PROTOTYP( UID_T getregid, (void) );
  13603. #endif /* NOGETID_PROTOS */
  13604. #else
  13605. _PROTOTYP( UID_T getreuid, (void) );
  13606. _PROTOTYP( UID_T getregid, (void) );
  13607. #endif /* COHERENT */
  13608. #endif /* HPUX10 */
  13609. #endif /* HPUX9 */
  13610. #endif /* sequent */
  13611. #endif /* PS2AIX10 */
  13612. #endif /* NEXT */
  13613. #endif /* SUNOS4 */
  13614. #endif /* _POSIX_SOURCE */
  13615.  
  13616. /*
  13617. Subject: Set-user-id
  13618. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  13619. Date: Sat, 21 Apr 90 4:48:25 MES
  13620. From: Kristoffer Eriksson <ske@pkmab.se>
  13621.  
  13622. This is a set of functions to be used in programs that may be run set-user-id
  13623. and/or set-group-id. They handle both the case where the program is not run
  13624. with such privileges (nothing special happens then), and the case where one
  13625. or both of these set-id modes are used.  The program is made to run with the
  13626. user's real user and group ids most of the time, except for when more
  13627. privileges are needed.  Don't set-user-id to "root".
  13628.  
  13629. This works on System V and POSIX.  In BSD, it depends on the
  13630. "saved-set-user-id" feature.
  13631. */
  13632.  
  13633. #define UID_ROOT 0            /* Root user and group ids */
  13634. #define GID_ROOT 0
  13635.  
  13636. /*
  13637.   The following code defines the symbol SETEUID for UNIX systems based
  13638.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  13639.   seteuid() and setegid() instead of setuid() and setgid(), which still
  13640.   don't allow arbitrary switching.  It also avoids setreuid() and
  13641.   setregid(), which are included in BSD4.4 for compatibility only, are
  13642.   insecure, and print warnings to stderr under at least one system (NetBSD
  13643.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  13644.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  13645.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  13646. */
  13647. #ifdef BSD44
  13648. #define SETEUID
  13649. #endif /* BSD44 */
  13650.  
  13651. /*
  13652.   The following construction automatically defines the symbol SETREUID for
  13653.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  13654.   defined, then this program will use getreuid() and getregid() calls in
  13655.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  13656.   not allow arbitrary switching back and forth of real & effective uid.
  13657.   This construction also allows -DSETREUID to be put on the cc command line
  13658.   for any system that has and wants to use setre[ug]id().  It also prevents
  13659.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  13660.   command line (or otherwise defined).
  13661. */
  13662. #ifdef FT18                /* None of this for Fortune. */
  13663. #define NOSETREU
  13664. #endif /* FT18 */
  13665.  
  13666. #ifdef ANYBSD
  13667. #ifndef BSD29
  13668. #ifndef BSD41
  13669. #ifndef SETREUID
  13670. #ifndef NOSETREU
  13671. #ifndef SETEUID
  13672. #define SETREUID
  13673. #endif /* SETEUID */
  13674. #endif /* NOSETREU */
  13675. #endif /* SETREUID */
  13676. #endif /* !BSD41 */
  13677. #endif /* !BSD29 */
  13678. #endif /* ANYBSD */
  13679.  
  13680. /* Variables for user and group IDs. */
  13681.  
  13682. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  13683. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  13684.  
  13685.  
  13686. /* P R I V _ I N I  --  Initialize privileges package  */
  13687.  
  13688. /* Called as early as possible in a set-uid or set-gid program to store the
  13689.  * set-to uid and/or gid and step down to the users real uid and gid. The
  13690.  * stored id's can be temporarily restored (allowed in System V) during
  13691.  * operations that require the privilege.  Most of the time, the program
  13692.  * should execute in unpriviliged state, to not impose any security threat.
  13693.  *
  13694.  * Note: Don't forget that access() always uses the real id:s to determine
  13695.  * file access, even with privileges restored.
  13696.  *
  13697.  * Returns an error mask, with error values or:ed together:
  13698.  *   1 if setuid() fails,
  13699.  *   2 if setgid() fails, and
  13700.  *   4 if the program is set-user-id to "root", which can't be handled.
  13701.  *
  13702.  * Only the return value 0 indicates real success. In case of failure,
  13703.  * those privileges that could be reduced have been, at least, but the
  13704.  * program should be aborted none-the-less.
  13705.  *
  13706.  * Also note that these functions do not expect the uid or gid to change
  13707.  * without their knowing. It may work if it is only done temporarily, but
  13708.  * you're on your own.
  13709.  */
  13710. int
  13711. priv_ini() {
  13712.     int err = 0;
  13713.  
  13714. #ifndef HAVE_BAUDBOY
  13715.  
  13716.     /* Save real ID:s. */
  13717.     realuid = getuid();
  13718.     realgid = getgid();
  13719.  
  13720.     /* Save current effective ID:s, those set to at program exec. */
  13721.     privuid = geteuid();
  13722.     privgid = getegid();
  13723.  
  13724.     /* If running set-uid, go down to real uid, otherwise remember that
  13725.      * no privileged uid is available.
  13726.      *
  13727.      * Exceptions:
  13728.      *
  13729.      * 1) If the real uid is already "root" and the set-uid uid (the
  13730.      * initial effective uid) is not "root", then we would have trouble
  13731.      * if we went "down" to "root" here, and then temporarily back to the
  13732.      * set-uid uid (not "root") and then again tried to become "root". I
  13733.      * think the "saved set-uid" is lost when changing uid from effective
  13734.      * uid "root", which changes all uid, not only the effective uid. But
  13735.      * in this situation, we can simply go to "root" and stay there all
  13736.      * the time. That should give sufficient privilege (understatement!),
  13737.      * and give the right uids for subprocesses.
  13738.      *
  13739.      * 2) If the set-uid (the initial effective uid) is "root", and we
  13740.      * change uid to the real uid, we can't change it back to "root" when
  13741.      * we need the privilege, for the same reason as in 1). Thus, we can't
  13742.      * handle programs that are set-user-id to "root" at all. The program
  13743.      * should be stopped.  Use some other uid.  "root" is probably too
  13744.      * privileged for such things, anyway. (The uid is reverted to the
  13745.      * real uid until termination.)
  13746.      *
  13747.      * These two exceptions have the effect that the "root" uid will never
  13748.      * be one of the two uids that are being switched between, which also
  13749.      * means we don't have to check for such cases in the switching
  13750.      * functions.
  13751.      *
  13752.      * Note that exception 1) is handled by these routines (by constantly
  13753.      * running with uid "root", while exception 2) is a serious error, and
  13754.      * is not provided for at all in the switching functions.
  13755.      */
  13756.     if (realuid == privuid)
  13757.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  13758.  
  13759.     /* If running set-gid, go down to real gid, otherwise remember that
  13760.      * no privileged gid is available.
  13761.      *
  13762.      * There are no exception like there is for the user id, since there
  13763.      * is no group id that is privileged in the manner of uid "root".
  13764.      * There could be equivalent problems for group changing if the
  13765.      * program sometimes ran with uid "root" and sometimes not, but
  13766.      * that is already avoided as explained above.
  13767.      *
  13768.      * Thus we can expect always to be able to switch to the "saved set-
  13769.      * gid" when we want, and back to the real gid again. You may also
  13770.      * draw the conclusion that set-gid provides for fewer hassles than
  13771.      * set-uid.
  13772.      */
  13773.  
  13774. #ifdef SUIDDEBUG
  13775.     fprintf(stderr,"UID_ROOT=%d\n",UID_ROOT);
  13776.     fprintf(stderr,"realuid=%d\n",realuid);
  13777.     fprintf(stderr,"privuid=%d\n",privuid);
  13778. #endif /* SUIDDEBUG */
  13779.  
  13780.     if (realgid == privgid)        /* If not running set-user-id, */
  13781.       privgid = (GID_T) -1;        /*  remember it this way. */
  13782.  
  13783.     err = priv_off();            /* Turn off setuid privilege. */
  13784.  
  13785.     if (privuid == UID_ROOT)        /* If setuid to root, */
  13786.       err |= 4;                /* return this error. */
  13787.  
  13788.     if (realuid == UID_ROOT) {        /* If real id is root, */
  13789.     privuid = (UID_T) -1;        /* stay root at all times. */
  13790. #ifdef ATT7300
  13791.     /* If Kermit installed SUID uucp and user is running as root */
  13792.     err &= ~1;            /* System V R0 does not save UID */
  13793. #endif /* ATT7300 */
  13794.     }
  13795. #endif /* HAVE_BAUDBOY */
  13796.     return(err);
  13797. }
  13798.  
  13799.  
  13800. /* Macros for hiding the differences in UID/GID setting between various Unix
  13801.  * systems. These macros should always be called with both the privileged ID
  13802.  * and the non-privileged ID. The one in the second argument, will become the
  13803.  * effective ID. The one in the first argument will be retained for later
  13804.  * retrieval.
  13805.  */
  13806. #ifdef SETREUID
  13807. #ifdef SAVEDUID
  13808. /* On BSD systems with the saved-UID feature, we just juggle the effective
  13809.  * UID back and forth, and leave the real UID at its true value.  The kernel
  13810.  * allows switching to both the current real UID, the effective UID, and the
  13811.  * UID which the program is set-UID to.  The saved set-UID always holds the
  13812.  * privileged UID for us, and the real UID will always be the non-privileged,
  13813.  * and we can freely choose one of them for the effective UID at any time.
  13814.  */
  13815. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  13816. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  13817.  
  13818. #else   /* SETREUID,!SAVEDUID */
  13819.  
  13820. /* On systems with setreXid() but without the saved-UID feature, notably
  13821.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  13822.  * the effective UID that we are interested in, but we have to retain the
  13823.  * unused UID somewhere to enable us to restore it later, and we do this
  13824.  * in the real UID.  The kernel only allows switching to either the current
  13825.  * real or the effective UID, unless you're "root".
  13826.  */
  13827. #define switchuid(hidden,active)    setreuid(hidden,active)
  13828. #define switchgid(hidden,active)    setregid(hidden,active)
  13829. #endif
  13830.  
  13831. #else /* !SETREUID, !SAVEDUID */
  13832.  
  13833. #ifdef SETEUID
  13834. /*
  13835.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  13836.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  13837.   seteXid() functions work the same for "root" as for other users.
  13838. */
  13839. #define switchuid(hidden,active)    seteuid(active)
  13840. #define switchgid(hidden,active)    setegid(active)
  13841.  
  13842. #else /* !SETEUID */
  13843.  
  13844. /* On System V and POSIX, the only thing we can change is the effective UID
  13845.  * (unless the current effective UID is "root", but initsuid() avoids that for
  13846.  * us).  The kernel allows switching to the current real UID or to the saved
  13847.  * set-UID.  These are always set to the non-privileged UID and the privileged
  13848.  * UID, respectively, and we only change the effective UID.  This breaks if
  13849.  * the current effective UID is "root", though, because for "root" setuid/gid
  13850.  * becomes more powerful, which is why initsuid() treats "root" specially.
  13851.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  13852.  * systems that don't fit any of these four cases, we simply can't support
  13853.  * set-UID.
  13854.  */
  13855. #define switchuid(hidden,active)    setuid(active)
  13856. #define switchgid(hidden,active)    setgid(active)
  13857.  
  13858. #endif /* SETEUID */
  13859. #endif /* SETREUID */
  13860.  
  13861.  
  13862. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  13863.  
  13864. /* Go to the privileged uid (gid) that the program is set-user-id
  13865.  * (set-group-id) to, unless the program is running unprivileged.
  13866.  * If setuid() fails, return value will be 1. If getuid() fails it
  13867.  * will be 2.  Return immediately after first failure, and the function
  13868.  * tries to restore any partial work done.  Returns 0 on success.
  13869.  * Group id is changed first, since it is less serious than user id.
  13870.  */
  13871. int
  13872. priv_on() {
  13873. #ifndef HAVE_BAUDBOY
  13874.     if (privgid != (GID_T) -1)
  13875.       if (switchgid(realgid,privgid))
  13876.         return(2);
  13877.  
  13878.     if (privuid != (UID_T) -1)
  13879.       if (switchuid(realuid,privuid)) {
  13880.       if (privgid != (GID_T) -1)
  13881.         switchgid(privgid,realgid);
  13882.       return(1);
  13883.       }
  13884. #endif /* HAVE_BAUDBOY */
  13885.     return(0);
  13886. }
  13887.  
  13888. /* P R I V _ O F F  --  Turn on the real uid and gid */
  13889.  
  13890. /* Return to the unprivileged uid (gid) after an temporary visit to
  13891.  * privileged status, unless the program is running without set-user-id
  13892.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  13893.  * in setgid() or:ed together. The functions tries to return both uid
  13894.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  13895.  * success.
  13896.  */
  13897. int
  13898. priv_off() {
  13899.     int err = 0;
  13900. #ifndef HAVE_BAUDBOY
  13901.     if (privuid != (UID_T) -1)
  13902.        if (switchuid(privuid,realuid))
  13903.       err |= 1;
  13904.  
  13905.     if (privgid != (GID_T) -1)
  13906.        if (switchgid(privgid,realgid))
  13907.     err |= 2;
  13908. #endif /* HAVE_BAUDBOY */
  13909.     return(err);
  13910. }
  13911.  
  13912. /* Turn off privilege permanently.  No going back.  This is necessary before
  13913.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  13914.  * we swap the real and effective ids, and we don't want to let the forked
  13915.  * process swap them again and get the privilege back. It will work on other
  13916.  * machines too, such that you can rely on its effect always being the same,
  13917.  * for instance, even when you're in priv_on() state when this is called.
  13918.  * (Well, that part about "permanent" is on System V only true if you follow
  13919.  * this with a call to exec(), but that's what we want it for anyway.)
  13920.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  13921.  */
  13922. int
  13923. priv_can() {
  13924. #ifndef HAVE_BAUDBOY
  13925. #ifdef SETREUID
  13926.     int err = 0;
  13927.     if (privuid != (UID_T) -1)
  13928.        if (setreuid(realuid,realuid))
  13929.       err |= 1;
  13930.  
  13931.     if (privgid != (GID_T) -1)
  13932.         if (setregid(realgid,realgid))
  13933.        err |= 2;
  13934.  
  13935.     return(err);
  13936.  
  13937. #else
  13938. #ifdef SETEUID
  13939.     int err = 0;
  13940.     if (privuid != (UID_T) -1)
  13941.     if (setuid(realuid)) {
  13942.         debug(F101,"setuid failed","",errno);
  13943.         err |= 1;
  13944.         debug(F101,"ruid","",getuid());
  13945.         debug(F101,"euid","",geteuid());
  13946.     }
  13947.     debug(F101,"setuid","",realuid);
  13948.     if (privgid != (GID_T) -1)
  13949.         if (setgid(realgid)) {
  13950.         debug(F101,"setgid failed","",errno);
  13951.         err |= 2;
  13952.         debug(F101,"rgid","",getgid());
  13953.         debug(F101,"egid","",getegid());
  13954.     }
  13955.     debug(F101,"setgid","",realgid);
  13956.     return(err);
  13957. #else
  13958.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  13959.     return(priv_off());
  13960. #endif /* SETEUID */
  13961. #endif /* SETREUID */
  13962. #else
  13963.     return(0);
  13964. #endif /* HAVE_BAUDBOY */
  13965. }
  13966.  
  13967. /* P R I V _ O P N  --  For opening protected files or devices. */
  13968.  
  13969. int
  13970. priv_opn(name, modes) char *name; int modes; {
  13971.     int x;
  13972.     priv_on();                /* Turn privileges on */
  13973.     debug(F111,"priv_opn",name,modes);
  13974.     errno = 0;
  13975.     x = open(name, modes);        /* Try to open the device */
  13976.     debug(F101,"priv_opn result","",x);
  13977.     debug(F101,"priv_opn errno","",errno);
  13978.     priv_off();                /* Turn privileges off */
  13979.     return(x);                /* Return open's return code */
  13980. }
  13981.  
  13982. /*  P R I V _ C H K  --  Check privileges.  */
  13983.  
  13984. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  13985.  
  13986. int
  13987. priv_chk() {
  13988.     int x, y = 0;
  13989.     x = priv_off();            /* Turn off privs. */
  13990.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  13991.       y = priv_can();
  13992.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  13993.       y = y | priv_can();
  13994.     return(y);
  13995. }
  13996.  
  13997. UID_T
  13998. real_uid() {
  13999.     return(realuid);
  14000. }
  14001.  
  14002. VOID
  14003. ttimoff() {                /* Turn off any timer interrupts */
  14004.     /* int xx; */
  14005. /*
  14006.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  14007.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  14008.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  14009.   systems, possibly having to do with sleep(), that caused core dumps.  It
  14010.   should be OK to do this, because no code in this module uses nested alarms.
  14011.   (But we still have to watch out for SCRIPT and DIAL...)
  14012. */
  14013.     /* xx = */ alarm(0);
  14014.     /* debug(F101,"ttimoff alarm","",xx); */
  14015.     if (saval) {            /* Restore any previous */
  14016.     signal(SIGALRM,saval);        /* alarm handler. */
  14017.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  14018.     saval = NULL;
  14019.     } else {
  14020.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  14021.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  14022.     }
  14023. }
  14024.  
  14025.  
  14026. int
  14027. tt_is_secure() {      /* Tells whether the current connection is secure */
  14028.  
  14029.     if (ttyfd == -1)
  14030.       return(0);
  14031.  
  14032.     if (0
  14033. #ifdef SSHBUILTIN
  14034.     || IS_SSH()
  14035. #endif /* SSHBUILTIN */
  14036. #ifdef CK_ENCRYPTION
  14037.     || ck_tn_encrypting() && ck_tn_decrypting()
  14038. #endif /* CK_ENCRYPTION */
  14039. #ifdef CK_SSL
  14040.     || tls_active_flag || ssl_active_flag
  14041. #endif /* CK_SSL */
  14042. #ifdef RLOGCODE
  14043. #ifdef CK_KERBEROS
  14044. #ifdef CK_ENCRYPTION
  14045.     || ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN
  14046. #endif /* CK_ENCRYPTION */
  14047. #endif /* CK_KERBEROS */
  14048. #endif /* RLOGCODE */
  14049.     )
  14050.       return(1);
  14051.     return(0);
  14052. }
  14053.  
  14054. #ifdef CK_REDIR
  14055.   
  14056. /* External protocol handler parameters from ckuus3.c */
  14057. extern int exp_handler, exp_stderr, exp_timo;
  14058.  
  14059. #ifdef SELECT
  14060. #ifdef NETPTY
  14061.  
  14062. /* The right size is 24576 */
  14063.  
  14064. #ifndef PTY_PBUF_SIZE            /* Size of buffer to read from pty */
  14065. #define PTY_PBUF_SIZE 24576        /* and write to net. */
  14066. #endif    /* PTY_PBUF_SIZE */
  14067.  
  14068. #ifndef PTY_TBUF_SIZE            /* Size of buffer to read from net */
  14069. #define PTY_TBUF_SIZE 24576        /* and write to pty. */
  14070. #endif    /* PTY_TBUF_SIZE */
  14071.  
  14072. #ifdef O_NDELAY                /* Whether to use nonblocking */
  14073. #ifndef PTY_NO_NDELAY            /* reads on the pseudoterminal */
  14074. #ifndef PTY_USE_NDELAY
  14075. #define PTY_USE_NDELAY
  14076. #endif    /* PTY_USE_NDELAY */
  14077. #endif    /* PTY_NO_NDELAY */
  14078. #endif    /* O_NDELAY */
  14079.  
  14080. #ifndef HAVE_OPENPTY
  14081. #ifndef USE_CKUPTY_C
  14082. #define USE_CKUPTY_C
  14083. #endif /* USE_CKUPTY_C */
  14084. #endif /* HAVE_OPENPTY */
  14085.  
  14086. VOID
  14087. pty_make_raw(fd) int fd; {
  14088.     int x = -23, i;
  14089.  
  14090. #ifdef BSD44ORPOSIX            /* POSIX */
  14091.     struct termios tp;
  14092. #else
  14093. #ifdef ATTSV                /* AT&T UNIX */
  14094. #ifdef CK_ANSIC
  14095.     struct termio tp = {0};
  14096. #else
  14097.     struct termio tp;
  14098. #endif    /* CK_ANSIC */
  14099. #else
  14100.     struct sgttyb tp;            /* Traditional */
  14101. #endif /* ATTSV */
  14102. #endif /* BSD44ORPOSIX */
  14103.  
  14104.     debug(F101,"pty_make_raw fd","",fd);
  14105.     errno = 0;
  14106.  
  14107. #ifdef BSD44ORPOSIX            /* POSIX */
  14108.     x = tcgetattr(fd,&tp);
  14109.     debug(F101,"pty_make_raw tcgetattr","",x);
  14110. #else
  14111. #ifdef ATTSV                /* AT&T UNIX */
  14112.     x = ioctl(fd,TCGETA,&tp);
  14113.     debug(F101,"pty_make_raw TCGETA ioctl","",x);
  14114. #else
  14115.     x = gtty(fd,&tp);
  14116.     debug(F101,"pty_make_raw ttty","",x);
  14117. #endif /* ATTSV */
  14118. #endif /* BSD44ORPOSIX */
  14119.     debug(F101,"pty_make_raw GET errno","",errno);
  14120.  
  14121. #ifdef USE_CFMAKERAW
  14122.     errno = 0;
  14123.     cfmakeraw(&tp);
  14124.     debug(F101,"pty_make_raw cfmakeraw errno","",errno);
  14125. #else  /* USE_CFMAKERAW */
  14126.  
  14127. #ifdef COMMENT
  14128.  
  14129. /* This very simple version recommended by Serg Iakolev doesn't work */
  14130.  
  14131.     tp.c_lflag &= ~(ECHO|ICANON|IEXTEN|ISIG);
  14132.     tp.c_iflag &= ~(BRKINT|ICRNL|INPCK|ISTRIP|IXON);
  14133.     tp.c_cflag &= ~(CSIZE|PARENB);
  14134.     tp.c_cflag |= CS8;
  14135.     tp.c_oflag &= ~(OPOST);
  14136.     tp.c_cc[VMIN] = 1;
  14137.     tp.c_cc[VTIME] = 0;
  14138.  
  14139.     debug(F101,"pty_make_raw 1 c_cc[] NCCS","",NCCS);
  14140.     debug(F101,"pty_make_raw 1 iflags","",tp.c_iflag);
  14141.     debug(F101,"pty_make_raw 1 oflags","",tp.c_oflag);
  14142.     debug(F101,"pty_make_raw 1 lflags","",tp.c_lflag);
  14143.     debug(F101,"pty_make_raw 1 cflags","",tp.c_cflag);
  14144.  
  14145. #else
  14146. #ifdef COMMENT
  14147. /*
  14148.   In this version we unset everything and then set only the
  14149.   bits we know we need.
  14150. */
  14151.     /* iflags */
  14152.     tp.c_iflag = 0L;
  14153.     tp.c_iflag |= IGNBRK;
  14154. #ifdef IMAXBEL
  14155.     tp.c_iflag |= IMAXBEL;
  14156. #endif /* IMAXBEL */
  14157.  
  14158.     /* oflags */
  14159.     tp.c_oflag = 0L;
  14160.  
  14161.     /* lflags */
  14162.     tp.c_lflag = 0L;
  14163. #ifdef NOKERNINFO
  14164.     tp.c_lflag |= NOKERNINFO;
  14165. #endif    /* NOKERNINFO */
  14166.  
  14167.     /* cflags */
  14168.     tp.c_cflag = 0L;
  14169.     tp.c_cflag |= CS8|CREAD;
  14170.  
  14171.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14172.     tp.c_cc[i] = 0;
  14173.     }
  14174. #ifdef VMIN
  14175.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14176. #endif    /* VMIN */
  14177.     debug(F101,"pty_make_raw 2 c_cc[] NCCS","",NCCS);
  14178.     debug(F101,"pty_make_raw 2 iflags","",tp.c_iflag);
  14179.     debug(F101,"pty_make_raw 2 oflags","",tp.c_oflag);
  14180.     debug(F101,"pty_make_raw 2 lflags","",tp.c_lflag);
  14181.     debug(F101,"pty_make_raw 2 cflags","",tp.c_cflag);
  14182.  
  14183. #else  /* COMMENT */
  14184. /*
  14185.   In this version we set or unset every single flag explicitly.  It works a
  14186.   bit better than the simple version just above, but it's still far from
  14187.   adequate.
  14188. */
  14189.     /* iflags */
  14190.     tp.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  14191.     tp.c_iflag &= ~(INPCK|IGNPAR|IXANY|IXON|IXOFF);
  14192.     tp.c_iflag |= IGNBRK;
  14193. #ifdef IMAXBEL
  14194. #ifdef COMMENT
  14195.     tp.c_iflag |= IMAXBEL;
  14196. #else
  14197.     tp.c_iflag &= ~IMAXBEL;
  14198. #endif /* COMMENT */
  14199. #endif /* IMAXBEL */
  14200. #ifdef IUCLC
  14201.     tp.c_iflag &= ~IUCLC;
  14202. #endif /* IUCLC */
  14203.  
  14204.     /* oflags */
  14205. #ifdef BSDLY
  14206.     tp.c_oflag &= ~BSDLY;
  14207. #endif /* BSDLY */
  14208. #ifdef CRDLY
  14209.     tp.c_oflag &= ~CRDLY;
  14210. #endif /* CRDLY */
  14211. #ifdef FFDLY
  14212.     tp.c_oflag &= ~FFDLY;
  14213. #endif /* FFDLY */
  14214. #ifdef NLDLY
  14215.     tp.c_oflag &= ~NLDLY;
  14216. #endif /* NLDLY */
  14217. #ifdef TABDLY
  14218.     tp.c_oflag &= ~TABDLY;
  14219. #endif /* TABDLY */
  14220. #ifdef VTDLY
  14221.     tp.c_oflag &= ~VTDLY;
  14222. #endif /* VTDLY */
  14223. #ifdef OFDEL
  14224.     tp.c_oflag &= ~OFDEL;
  14225. #endif /* OFDEL */
  14226. #ifdef OFILL
  14227.     tp.c_oflag &= ~OFILL;
  14228. #endif /* OFILL */
  14229. #ifdef OLCUC
  14230.     tp.c_oflag &= ~OLCUC;
  14231. #endif /* OLCUC */
  14232. #ifdef CMSPAR
  14233.     tp.c_oflag &= ~CMSPAR;
  14234. #endif /* CMSPAR */
  14235.     tp.c_oflag &= ~OPOST;
  14236. #ifdef OXTABS
  14237.     tp.c_oflag &= ~OXTABS;
  14238. #endif /* OXTABS */
  14239. #ifdef COMMENT
  14240. #ifdef ONOCR
  14241.     tp.c_oflag &= ~ONOCR;        /* Maybe should be |=? */
  14242.     tp.c_oflag |= ONOCR;        /* makes no difference either way */
  14243. #endif /* ONOCR */
  14244. #endif /* COMMENT */
  14245. #ifdef ONOEOT
  14246.     tp.c_oflag &= ~ONOEOT;
  14247. #endif /* ONOEOT */
  14248. #ifdef ONLRET
  14249.     tp.c_oflag &= ~ONLRET;
  14250. #endif /* ONLRET */
  14251. #ifdef ONLCR
  14252.     tp.c_oflag &= ~ONLCR;
  14253. #endif /* ONLCR */
  14254. #ifdef OCRNL
  14255.     tp.c_oflag &= ~OCRNL;
  14256. #endif /* OCRNL */
  14257.  
  14258.     /* lflags */
  14259.     tp.c_lflag &= ~ECHO;
  14260. #ifdef ECHOE
  14261.     tp.c_lflag &= ~ECHOE;
  14262. #endif /* ECHOE */
  14263. #ifdef ECHONL
  14264.     tp.c_lflag &= ~ECHONL;
  14265. #endif /* ECHONL */
  14266. #ifdef ECHOPRT
  14267.     tp.c_lflag &= ~ECHOPRT;
  14268. #endif /* ECHOPRT */
  14269. #ifdef ECHOKE
  14270.     tp.c_lflag &= ~ECHOKE;
  14271. #endif /* ECHOKE */
  14272. #ifdef ECHOCTL
  14273.     tp.c_lflag &= ~ECHOCTL;
  14274. #endif /* ECHOCTL */
  14275. #ifdef XCASE
  14276.     tp.c_lflag &= ~XCASE;
  14277. #endif /* XCASE */
  14278. #ifdef ALTWERASE
  14279.     tp.c_lflag &= ~ALTWERASE;
  14280. #endif /* ALTWERASE */
  14281. #ifdef EXTPROC
  14282.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN|EXTPROC);
  14283. #else
  14284.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  14285. #endif    /* EXTPROC */
  14286. #ifdef NOKERNINFO
  14287.     tp.c_lflag |= NOKERNINFO;
  14288. #endif    /* NOKERNINFO */
  14289. #ifndef COMMENT
  14290.     tp.c_lflag &= ~NOFLSH;        /* TRY IT THE OTHER WAY? */
  14291. #else
  14292.     tp.c_lflag |= NOFLSH;        /* No, this way is worse */
  14293. #endif /* COMMENT */
  14294.  
  14295.     /* cflags */
  14296.     tp.c_cflag &= ~(CSIZE|PARENB|PARODD);
  14297.     tp.c_cflag |= CS8|CREAD;
  14298.  
  14299. #ifdef MDMBUF
  14300.     tp.c_cflag &= ~(MDMBUF);
  14301. #else
  14302. #ifdef CCAR_OFLOW
  14303.     tp.c_cflag &= ~(CCAR_OFLOW);    /* two names for the same thing */
  14304. #endif /* CCAR_OFLOW */
  14305. #endif /* MDMBUF */
  14306.  
  14307. #ifdef CCTS_OFLOW
  14308.     tp.c_cflag &= ~(CCTS_OFLOW);
  14309. #endif /* CCTS_OFLOW */
  14310. #ifdef CDSR_OFLOW
  14311.     tp.c_cflag &= ~(CDSR_OFLOW);
  14312. #endif /* CDSR_OFLOW */
  14313. #ifdef CDTR_IFLOW
  14314.     tp.c_cflag &= ~(CDTR_IFLOW);
  14315. #endif /* CDTR_IFLOW */
  14316. #ifdef CRTS_IFLOW
  14317.     tp.c_cflag &= ~(CRTS_IFLOW);
  14318. #endif /* CRTS_IFLOW */
  14319. #ifdef CRTSXOFF
  14320.     tp.c_cflag &= ~(CRTSXOFF);
  14321. #endif /* CRTSXOFF */
  14322. #ifdef CRTSCTS
  14323.     tp.c_cflag &= ~(CRTSCTS);
  14324. #endif /* CRTSCTS */
  14325. #ifdef CLOCAL
  14326.     tp.c_cflag &= ~(CLOCAL);
  14327. #endif /* CLOCAL */
  14328. #ifdef CSTOPB
  14329.     tp.c_cflag &= ~(CSTOPB);
  14330. #endif /* CSTOPB */
  14331. #ifdef HUPCL
  14332.     tp.c_cflag &= ~(HUPCL);
  14333. #endif /* HUPCL */
  14334.  
  14335.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14336.     tp.c_cc[i] = 0;
  14337.     }
  14338. #ifdef VMIN
  14339.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14340. #endif    /* VMIN */
  14341.     debug(F101,"pty_make_raw 3 c_cc[] NCCS","",NCCS);
  14342.     debug(F101,"pty_make_raw 3 iflags","",tp.c_iflag);
  14343.     debug(F101,"pty_make_raw 3 oflags","",tp.c_oflag);
  14344.     debug(F101,"pty_make_raw 3 lflags","",tp.c_lflag);
  14345.     debug(F101,"pty_make_raw 3 cflags","",tp.c_cflag);
  14346. #endif /* COMMENT */
  14347. #endif /* COMMENT */
  14348.  
  14349.     errno = 0;
  14350. #ifdef BSD44ORPOSIX            /* POSIX */
  14351.     x = tcsetattr(fd,TCSANOW,&tp);
  14352.     debug(F101,"pty_make_raw tcsetattr","",x);
  14353. #else
  14354. #ifdef ATTSV                /* AT&T UNIX */
  14355.     x = ioctl(fd,TCSETA,&tp);
  14356.     debug(F101,"pty_make_raw ioctl","",x);
  14357. #else
  14358.     x = stty(fd,&tp);            /* Traditional */
  14359.     debug(F101,"pty_make_raw stty","",x);
  14360. #endif /* ATTSV */
  14361. #endif /* BSD44ORPOSIX */
  14362.     debug(F101,"pty_make_raw errno","",errno);
  14363.  
  14364. #endif /* __NetBSD__ */
  14365. }
  14366.  
  14367. static int
  14368. pty_chk(fd) int fd; {
  14369.     int x, n = 0;
  14370.     errno = 0;
  14371. #ifdef FIONREAD
  14372.     x = ioctl(fd, FIONREAD, &n);    /* BSD and most others */
  14373.     ckmakmsg(msgbuf,500,
  14374.          "pty_chk ioctl FIONREAD errno=",
  14375.          ckitoa(errno),
  14376.          " count=",
  14377.          ckitoa(n));
  14378.     debug(F100,msgbuf,"",0);
  14379. #else
  14380.     n = rdchk(fd);
  14381.     debug(F101,"pty_chk rdchk","",n);
  14382. #ifdef RDCHK
  14383. #endif    /* RDCHK */
  14384. #endif    /* FIONREAD */
  14385.     return((n > -1) ? n : 0);
  14386. }
  14387.  
  14388. static int
  14389. pty_get_status(fd,pid) int fd; PID_T pid; {
  14390.     int x, status = -1;
  14391.     PID_T w;
  14392.  
  14393.     debug(F101,"pty_get_status fd","",fd);
  14394.     debug(F101,"pty_get_status pid","",pid);
  14395.  
  14396.     if (pexitstat > -1)
  14397.       return(pexitstat);
  14398.  
  14399. #ifdef COMMENT
  14400.     /* Not only unnecessary but harmful */
  14401.     errno = 0;
  14402.     x = kill(pty_fork_pid,0);
  14403.     debug(F101,"pty_get_status kill value","",x);
  14404.     debug(F101,"pty_get_status kill errno","",errno);
  14405.     if (x > -1 && errno != ESRCH)
  14406.       return(-1);            /* Fork still there */
  14407.     /* Fork seems to be gone */
  14408. #endif    /* COMMENT */
  14409.  
  14410.     errno = 0;
  14411.     x = waitpid(pty_fork_pid,&status,WNOHANG);
  14412.     debug(F111,"pty_get_status waitpid",ckitoa(errno),x);
  14413.     if (x <= 0 && errno == 0) {
  14414.     debug(F101,"pty_get_status waitpid return","",-1);
  14415.     return(-1);
  14416.     }
  14417.     if (x > 0) {
  14418.     if (x != pty_fork_pid)
  14419.       debug(F101,
  14420.         "pty_get_status waitpid pid doesn't match","",pty_fork_pid); 
  14421.     debug(F101,"pty_get_status waitpid status","",status);
  14422.     debug(F101,"pty_get_status waitpid errno","",errno);
  14423.     if (WIFEXITED(status)) {
  14424.         debug(F100,"pty_get_status WIFEXITED","",0);
  14425.         status = WEXITSTATUS(status);
  14426.         debug(F101,"pty_get_status fork exit status","",status);
  14427. #ifdef COMMENT
  14428.         end_pty();
  14429. #endif    /* COMMENT */
  14430.         close(fd);
  14431.         pexitstat = status;
  14432.     } else {
  14433.         debug(F100,"pty_get_status waitpid unexpected status","",0);
  14434.     }
  14435.     }
  14436.     debug(F101,"pty_get_status return status","",status);
  14437.     return(status);
  14438. }
  14439.  
  14440. /* t t p t y c m d  --  Run command on pty and forward to net */
  14441.  
  14442. /*
  14443.   Needed for running external protocols on secure connections.
  14444.   For example, if C-Kermit has made an SSL/TLS or Kerberos Telnet
  14445.   connection, and then needs to transfer a file with Zmodem, which is
  14446.   an external program, this routine reads Zmodem's output, encrypts it,
  14447.   and then forwards it out the connection, and reads the encrypted data
  14448.   stream coming in from the connection, decrypts it, and forwards it to
  14449.   Zmodem.
  14450.  
  14451.   Works like a TCP/IP port forwarder except one end is a pty rather
  14452.   than a socket, which introduces some complications:
  14453.  
  14454.    . On most platforms, select() always indicates the output side of
  14455.      the pty has characters waiting to be read, even when it doesn't,
  14456.      even when the pty process has already exited.
  14457.  
  14458.    . Nonblocking reads must be used on the pty, because there is no
  14459.      way on certain platforms (e.g. NetBSD) to find out how many characters
  14460.      are available to be read (the FIONREAD ioctl always says 0).  The code
  14461.      also allows for blocking reads (if O_NDELAY and O_NONBLOCK are not
  14462.      defined, or if PTY_NO_NDELAY is defined), but on some platforms this can
  14463.      result in single-byte reads and writes (NetBSD again).
  14464.  
  14465.    . Testing for "EOF" on the pty is problematic.  select() never gives
  14466.      any indication.  After the pty process has exited and the fork has
  14467.      disappeared, read() can still return with 0 bytes read but without an
  14468.      error (NetBSD); no known test on the pty file descriptor will indicate
  14469.      that it is no longer valid.  The process ID of the pty fork can be
  14470.      tested on some platforms (NetBSD, luckily) but not others (Solaris,
  14471.      Linux).
  14472.  
  14473.   On the network side, we use ttinc() and ttoc(), which, for network 
  14474.   connections, handle any active security methods.
  14475.  
  14476.   Call with s = command.
  14477.   Returns 0 on failure, 1 on success.
  14478.   fdc - December 2006 - August 2007.
  14479.  
  14480.   NOTE: This code defaults to nonblocking reads if O_NDELAY or O_NONBLOCK are
  14481.   defined in the header files, which should be true of every recent Unix
  14482.   platform.  If this causes trouble somewhere, define PTY_NO_NDELAY, e.g. when
  14483.   building C-Kermit:
  14484.  
  14485.     touch ckutio.c
  14486.     make platformname KFLAGS=-DPTY_NO_NODELAY
  14487. */
  14488. static int have_pty = 0;        /* Do we have a pty? */
  14489.  
  14490. static SIGTYP (*save_sigchld)() = NULL;    /* For catching SIGCHLD */
  14491.  
  14492. static VOID
  14493. sigchld_handler(sig) int sig; {
  14494.     have_pty = 0;            /* We don't have a pty */
  14495. #ifdef DEBUG
  14496.     if (save_sigchld) {
  14497.     (VOID) signal(SIGCHLD,save_sigchld);
  14498.     save_sigchld = NULL;
  14499.     }
  14500.     if (deblog) {
  14501.     debug(F100,"**************","",0);
  14502.     debug(F100,"SIGCHLD caught","",0);
  14503.     debug(F100,"**************","",0);
  14504.     }
  14505. #endif    /* DEBUG */
  14506. }
  14507. #define HAVE_IAC 1
  14508. #define HAVE_CR  2
  14509.  
  14510. int
  14511. ttptycmd(s) char *s; {
  14512.     CHAR tbuf[PTY_TBUF_SIZE];        /* Read from net, write to pty */
  14513.     int tbuf_avail = 0;            /* Pointers for tbuf */
  14514.     int tbuf_written = 0;
  14515.     static int in_state = 0;        /* For TELNET IAC and NVT in */
  14516.     static int out_prev = 0;        /* Simpler scheme for out */
  14517.  
  14518.     CHAR pbuf[PTY_PBUF_SIZE];        /* Read from pty, write to net */
  14519.     CHAR dbuf[PTY_PBUF_SIZE + PTY_PBUF_SIZE + 1]; /* Double-size buffer */
  14520.     int pbuf_avail = 0;            /* Pointers for pbuf */
  14521.     int pbuf_written = 0;
  14522.  
  14523.     int ptyfd = -1;            /* Pty file descriptor */
  14524.     int have_net = 0;            /* We have a network connection */
  14525.     int pty_err = 0;            /* Got error on pty */
  14526.     int net_err = 0;            /* Got error on net */
  14527.     int status = -1;            /* Pty process exit status */
  14528.     int rc = 0;                /* Our return code */
  14529.  
  14530.     int x1 = 0, x2 = 0;            /* Workers... */
  14531.     int c, n, m, t, x;            /* Workers */
  14532.  
  14533.     long seconds_to_wait = 0L;        /* select() timeout */
  14534.     struct timeval tv, *tv2;        /* For select() */
  14535. #ifdef INTSELECT
  14536.     int in, out, err;            /* For select() */
  14537. #else
  14538.     fd_set in, out, err;
  14539. #endif /* INTSELECT */
  14540.     int nfds = 0;            /* For select() */
  14541.  
  14542.     int pset = 0, tset = 0, pnotset = 0, tnotset = 0; /* stats/debuggin only */
  14543.     int read_net_bytes = 0;        /* Stats */
  14544.     int write_net_bytes = 0;        /* Stats */
  14545.     int read_pty_bytes = 0;        /* Stats */
  14546.     int write_pty_bytes = 0;        /* Stats */
  14547.     int is_tn = 0;            /* TELNET protocol is active */
  14548.  
  14549.     int masterfd = -1;
  14550.     int slavefd = -1;
  14551. #ifndef USE_CKUPTY_C
  14552.     struct termios term;
  14553.     struct winsize twin;
  14554.     struct stringarray * q;
  14555.     char ** args = NULL;
  14556. #endif /* USE_CKUPTY_C */
  14557.  
  14558.     in_state = 0;            /* No previous character yet */
  14559.  
  14560.     if (ttyfd == -1) {
  14561.     printf("?Sorry, communication channel is not open\n");
  14562.     return(0);
  14563.     } else {
  14564.     have_net = 1;
  14565.     }
  14566.     if (nopush) {
  14567.     debug(F100,"ttptycmd fail: nopush","",0);
  14568.     return(0);
  14569.     }
  14570.     if (!s) s = "";            /* Defense de bogus arguments */
  14571.     if (!*s) return(0);
  14572.     pexitstat = -1;            /* Fork process exit status */
  14573.  
  14574. #ifdef TNCODE
  14575.     is_tn = (xlocal && netconn && IS_TELNET()) || /* Telnet protocol active */
  14576.         (!xlocal && sstelnet);
  14577. #endif /* TNCODE */
  14578.  
  14579.     debug(F110,"ttptycmd command",s,0);
  14580.     debug(F101,"ttptycmd ttyfd","",ttyfd);
  14581.     debug(F101,"ttptycmd is_tn","",is_tn);
  14582.     debug(F101,"ttptycmd ckermit pid","",getpid());
  14583.  
  14584. #ifdef USE_CKUPTY_C
  14585.     /* Call ckupty.c module to get and set up the pty fork */
  14586.     /* fc 1 == "run an external protocol" */
  14587.     debug(F100,"ttptycmd using ckupty.c","",0);
  14588.     if (do_pty(&ptyfd,s,1) < 0) {    /* Start the command on a pty */
  14589.     debug(F100,"ttptycmd do_pty fails","",0);
  14590.     return(0);
  14591.     }
  14592.     masterfd = ptyfd;
  14593.     pty_master_fd = ptyfd;
  14594. #ifdef COMMENT
  14595.     slavefd = pty_slave_fd;        /* This is not visible to us */
  14596. #endif /* COMMENT */
  14597.     debug(F111,"ttptycmd ptyfd","USE_CKUPTY_C",ptyfd);
  14598.     debug(F111,"ttptycmd masterfd","USE_CKUPTY_C",masterfd);
  14599.     debug(F111,"ttptycmd fork pid","USE_CKUPTY_C",pty_fork_pid);
  14600. #ifndef SOLARIS
  14601.     /* "ioctl inappropriate on device" for pty master */
  14602.     pty_make_raw(masterfd);
  14603. #endif /* SOLARIS */
  14604.  
  14605. #else /* USE_CKUPTY_C */
  14606.  
  14607.     debug(F100,"ttptycmd OPENPTY","",0);
  14608.     if (tcgetattr(0, &term) == -1) {    /* Get controlling terminal's modes */
  14609.     perror("tcgetattr");
  14610.     return(0);
  14611.     }
  14612.     if (ioctl(0, TIOCGWINSZ, (char *) &twin) == -1) { /* and window size */
  14613.     perror("ioctl TIOCGWINSZ");
  14614.     return(0);
  14615.     }
  14616.     if (openpty(&masterfd, &slavefd, NULL, NULL, NULL) == -1) {
  14617.     debug(F101,"ttptycmd openpty failed errno","",errno);
  14618.     perror("opentpy");
  14619.     return(0);
  14620.     }
  14621.     debug(F101,"ttptycmd openpty masterfd","",masterfd);
  14622.     debug(F101,"ttptycmd openpty slavefd","",slavefd);
  14623.     pty_master_fd = masterfd;
  14624.     pty_slave_fd = slavefd;
  14625.     debug(F101,"ttptycmd openpty pty_master_fd","",pty_master_fd);
  14626.  
  14627.     /* Put pty master in raw mode but let forked app control the slave */
  14628.     pty_make_raw(masterfd);
  14629.  
  14630. #ifdef COMMENT
  14631. #ifdef TIOCREMOTE
  14632.     /* TIOCREMOTE,0 = disable all termio processing */
  14633.     x = ioctl(masterfd, TIOCREMOTE, 1);
  14634.     debug(F111,"ttptycmd ioctl TIOCREMOTE",ckitoa(x),errno);
  14635. #endif    /* TIOCREMOTE */
  14636. #ifdef TIOCTTY
  14637.     /* TIOCTTY,0 = disable all termio processing */
  14638.     x = ioctl(masterfd, TIOCTTY, 0);
  14639.     debug(F111,"ttptycmd ioctl TIOCTTY",ckitoa(x),errno);
  14640. #endif    /* TIOCTTY */
  14641. #endif /* COMMENT */
  14642.  
  14643.     have_pty = 1;            /* We have an open pty */
  14644.     save_sigchld = signal(SIGCHLD, sigchld_handler); /* Catch fork quit */
  14645.  
  14646.     pty_fork_pid = fork();        /* Make fork for external protocol */
  14647.     debug(F101,"ttptycmd pty_fork_pid","",pty_fork_pid);
  14648.     if (pty_fork_pid == -1) {
  14649.     perror("fork");
  14650.     return(0);
  14651.     } else if (pty_fork_pid == 0) {    /* In new fork */
  14652.     int x;
  14653.     debug(F101,"ttptycmd new fork pid","",getpid());
  14654.     close(masterfd);        /* Slave quarters no masters allowed */
  14655.     x = setsid();
  14656.     debug(F101,"ttptycmd new fork setsid","",x);
  14657.     if (x == -1) {
  14658.         perror("ttptycmd setsid");
  14659.         exit(1);
  14660.     }
  14661.     signal(SIGINT,SIG_IGN);        /* Let upper fork catch this */
  14662.     
  14663. #ifdef COMMENT
  14664. #ifdef TIOCSCTTY
  14665.     /* Make pty the controlling terminal for the process */
  14666.     /* THIS CAUSES AN INFINITE SIGWINCH INTERRUPT LOOP */
  14667.     x = ioctl(slavefd, TIOCSCTTY, NULL);
  14668.     debug(F101,"ttptycmd TIOCSCTTY","",x);
  14669. #endif    /* TIOCSCTTY */
  14670. #endif    /* COMMENT */
  14671.  
  14672.     /* Initialize slave pty modes and size to those of our terminal */
  14673.     if (tcsetattr(slavefd, TCSANOW, &term) == -1) {
  14674.         perror("ttptycmd tcsetattr");
  14675.         exit(1);
  14676.     }
  14677.     if (ioctl(slavefd, TIOCSWINSZ, &twin) == -1) {
  14678.         perror("ttptycmd ioctl");
  14679.         exit(1);
  14680.     }
  14681. #ifdef COMMENT
  14682. #ifdef TIOCNOTTY
  14683.     /* Disassociate this process from its terminal */
  14684.     /* THIS HAS NO EFFECT */
  14685.     x = ioctl(slavefd, TIOCNOTTY, NULL);
  14686.     debug(F101,"ttptycmd TIOCNOTTY","",x);
  14687. #endif    /* TIOCNOTTY */
  14688. #endif    /* COMMENT */
  14689.  
  14690. #ifdef COMMENT
  14691. #ifdef SIGTTOU    
  14692.     /* Ignore terminal output interrupts */
  14693.     /* THIS HAS NO EFFECT */
  14694.     debug(F100,"ttptycmd ignoring SIGTTOU","",0);
  14695.     signal(SIGTTOU, SIG_IGN);
  14696. #endif    /* SIGTTOU */
  14697. #ifdef SIGTSTP    
  14698.     /* Ignore terminal output interrupts */
  14699.     /* THIS HAS NO EFFECT */
  14700.     debug(F100,"ttptycmd ignoring SIGTSTP","",0);
  14701.     signal(SIGTSTP, SIG_IGN);
  14702. #endif    /* SIGTSTP */
  14703. #endif    /* COMMENT */
  14704.  
  14705.     pty_make_raw(slavefd);        /* Put it in rawmode */
  14706.  
  14707.     errno = 0;
  14708.     if (dup2(slavefd, STDIN_FILENO) != STDIN_FILENO ||
  14709.         dup2(slavefd, STDOUT_FILENO) != STDOUT_FILENO) {
  14710.         debug(F101,"ttptycmd new fork dup2 error","",errno);
  14711.         perror("ttptycmd dup2");
  14712.         exit(1);
  14713.     }
  14714.     debug(F100,"ttptycmd new fork dup2 ok","",0);
  14715.  
  14716.     /* Parse external protocol command line */
  14717.     q = cksplit(1,0,s,NULL,"\\%[]&$+-/=*^_@!{}/<>|.#~'`:;?",7,0,0);
  14718.     if (!q) {
  14719.         debug(F100,"ttptycmd cksplit failed","",0);
  14720.         exit(1);
  14721.     } else {
  14722.         int i, n;
  14723.         debug(F100,"ttptycmd cksplit ok","",0);
  14724.         n = q->a_size;
  14725.         args = q->a_head + 1;
  14726.         for (i = 0; i <= n; i++) {
  14727.         if (!args[i]) {
  14728.             break;
  14729.         } else {
  14730.             /* sometimes cksplit() doesn't terminate the list */
  14731.             if ((i == n) && args[i]) {
  14732.             if ((int)strlen(args[i]) == 0)
  14733.               makestr(&(args[i]),NULL);
  14734.             }
  14735.         }
  14736.         }        
  14737.     }
  14738. #ifdef COMMENT
  14739. /*
  14740.   Putting the slave pty in rawmode should not be necessary because the
  14741.   external protocol program is supposed to do that itself.  Yet doing this
  14742.   here cuts down on Zmodem binary-file transmission errors by 30-50% but
  14743.   still doesn't eliminate them.
  14744. */
  14745.     pty_make_raw(STDIN_FILENO);
  14746.     pty_make_raw(STDOUT_FILENO);
  14747. #endif /* COMMENT */
  14748.  
  14749.     debug(F100,"ttptycmd execvp'ing external protocol","",0);
  14750.     execvp(args[0],args);
  14751.     perror("execvp failed");
  14752.     debug(F101,"ttptycmd execvp failed","",errno);
  14753.     close(slavefd);
  14754.     exit(1);
  14755.     } 
  14756.     /* (there are better ways to do this...) */
  14757.     msleep(1000);          /* Make parent wait for child to be ready */
  14758.     ptyfd = masterfd;            /* We talk to the master */
  14759.  
  14760. #endif /* USE_CKUPTY_C */
  14761.  
  14762.     debug(F101,"ttptycmd ptyfd","",ptyfd);
  14763.     if (ptyfd < 0) {
  14764.     printf("?Failure to get pty\n");
  14765.     return(-9);
  14766.     }
  14767.     have_pty = 1;          /* We have an open pty or we wouldn't he here */
  14768.  
  14769.     debug(F101,"ttptycmd PTY_PBUF_SIZE","",PTY_PBUF_SIZE);
  14770.     debug(F101,"ttptycmd PTY_TBUF_SIZE","",PTY_TBUF_SIZE);
  14771.  
  14772. #ifdef PTY_USE_NDELAY
  14773.     /* 
  14774.        NOTE: If select() and ioctl(ptyfd,FIONREAD,&n) return true indications
  14775.        on the pty, we don't need nonblocking reads.  Performance of either
  14776.        method seems to be about the same, so use whatever works.
  14777.     */
  14778.     errno = 0;
  14779.     x = fcntl(ptyfd,F_SETFL,fcntl(ptyfd,F_GETFL, 0)|O_NDELAY);
  14780.     ckmakmsg(msgbuf,500,
  14781.          "ttptycmd set O_NDELAY errno=",
  14782.          ckitoa(errno),
  14783.          " fcntl=",
  14784.          ckitoa(x));
  14785.     debug(F100,msgbuf,"",0);
  14786. #endif /* PTY_USE_NDELAY */
  14787.  
  14788. #ifdef COMMENT
  14789. /* Not necessary, the protocol module already did this */
  14790.  
  14791. #ifdef USE_CFMAKERAW
  14792.     if (tcgetattr(ttyfd, &term) > -1) {
  14793.     cfmakeraw(&term);
  14794.     debug(F101,"ttptycmd net cfmakeraw errno","",errno);
  14795.     x tcsetattr(ttyfd, TCSANOW, &term);
  14796.     debug(F101,"ttptycmd net tcsetattr","",x);
  14797.     debug(F101,"ttptycmd net tcsetattr","",errno);
  14798.     }
  14799. #else
  14800.     if (local)                /* Put network connection in */
  14801.       ttpkt(ttspeed,ttflow,ttprty);    /* "packet mode". */
  14802.     else
  14803.       conbin((char)escchr);        /* OR... pty_make_raw(0) */
  14804. #endif /* USE_CFMAKERAW */
  14805. #endif /* COMMENT */
  14806.  
  14807. #ifdef TNCODE
  14808.     if (is_tn) {
  14809.       debug(F101,"<<< ttptycmd TELOPT_ME_BINARY","",TELOPT_ME(TELOPT_BINARY));
  14810.       debug(F101,"<<< ttptycmd TELOPT_U_BINARY","",TELOPT_U(TELOPT_BINARY));
  14811.     }
  14812. #endif /* TNCODE */
  14813.  
  14814.     debug(F101,"ttptycmd entering loop - seconds_to_wait","",seconds_to_wait);
  14815.  
  14816.     while (have_pty || have_net) {
  14817.     FD_ZERO(&in);            /* Initialize select() structs */
  14818.     FD_ZERO(&out);
  14819.     FD_ZERO(&err);            /* (not used because useless) */
  14820.     nfds = -1;
  14821.  
  14822.     debug(F101,"ttptycmd loop top have_pty","",have_pty);
  14823.     debug(F101,"ttptycmd loop top have_net","",have_net);
  14824.  
  14825.     /* Pty is open and we have room to read from it? */
  14826.     if (have_pty && pbuf_avail < PTY_PBUF_SIZE) {
  14827.         debug(F100,"ttptycmd FD_SET ptyfd in","",0);
  14828.             FD_SET(ptyfd, &in);
  14829.         nfds = ptyfd;
  14830.         }
  14831.     /* Network is open and we have room to read from it? */
  14832.         if (have_net && have_pty && tbuf_avail < PTY_TBUF_SIZE) {
  14833.         debug(F100,"ttptycmd FD_SET ttyfd in","",0);
  14834.             FD_SET(ttyfd, &in);
  14835.         if (ttyfd > nfds) nfds = ttyfd;
  14836.         }
  14837.     /* Pty is open and we have stuff to write to it? */
  14838.         if (have_pty && tbuf_avail - tbuf_written > 0) {
  14839.         debug(F100,"ttptycmd FD_SET ptyfd out","",0);
  14840.             FD_SET (ptyfd, &out);
  14841.         if (ptyfd > nfds) nfds = ptyfd;
  14842.         }
  14843.     /* Net is open and we have stuff to write to it? */
  14844.     debug(F101,"ttptycmd pbuf_avail-pbuf_written","",
  14845.           pbuf_avail - pbuf_written);
  14846.         if (have_net && pbuf_avail - pbuf_written > 0) {
  14847.         debug(F100,"ttptycmd FD_SET ttyfd out","",0);
  14848.             FD_SET (ttyfd, &out);
  14849.         if (ttyfd > nfds) nfds = ttyfd;
  14850.         }
  14851.     /* We don't use err because it's not really for errors, */
  14852.     /* but for out of band data on the TCP socket, which, if it is */
  14853.     /* to be handled at all, is handled in the tt*() routines */
  14854.  
  14855.     nfds++;                /* 0-based to 1-based */
  14856.     debug(F101,"ttptycmd nfds","",nfds);
  14857.     if (!nfds) {
  14858.         debug(F100,"ttptycmd NO FDs set for select","",0);
  14859.         if (have_pty) {
  14860.         /* This is not right -- sleeping won't accomplish anything */
  14861.         debug(F101,"ttptycmd msleep","",100);
  14862.         msleep(100);        
  14863.         } else {
  14864.         debug(F100,"ttptycmd no pty - quitting loop","",0);
  14865.         break;
  14866.         }
  14867.     }
  14868.     errno = 0;
  14869.  
  14870.     if (seconds_to_wait > 0L) {    /* Timeout in case nothing happens */
  14871.         tv.tv_sec = seconds_to_wait; /* for a long time */
  14872.         tv.tv_usec = 0L;        
  14873.         tv2 = &tv;
  14874.         } else {
  14875.             tv2 = NULL;
  14876.     }
  14877.     x = select(nfds, &in, &out, NULL, tv2);
  14878.     debug(F101,"ttptycmd select","",x);
  14879.     if (x < 0) {
  14880.         if (errno == EINTR)
  14881.           continue;
  14882.         debug(F101,"ttptycmd select error","",errno);
  14883.         break;
  14884.     }
  14885.     if (x == 0) {
  14886.         debug(F101,"ttptycmd +++ select timeout","",seconds_to_wait); 
  14887.         if (have_pty) {
  14888.         status = pty_get_status(ptyfd,pty_fork_pid);
  14889.         debug(F101,"ttptycmd pty_get_status A","",status);
  14890.         if (status > -1) pexitstat = status;
  14891.         have_pty = 0;
  14892.         }
  14893.         break;
  14894.     }
  14895.     /* We want to handle any pending writes first to make room */
  14896.     /* for new incoming. */
  14897.  
  14898.     if (FD_ISSET(ttyfd, &out)) {    /* Can write to net? */
  14899.         CHAR * s;
  14900.         s = pbuf + pbuf_written;    /* Current spot for sending */
  14901. #ifdef TNCODE
  14902.         if (is_tn) {        /* ttol() doesn't double IACs */
  14903.         CHAR c;            /* Rewrite string with IACs doubled */
  14904.         int i;
  14905.         s = pbuf + pbuf_written; /* Source */
  14906.         x = 0;              /* Count */
  14907.         for (i = 0; i < pbuf_avail - pbuf_written; i++) {
  14908.             c = s[i];        /* Next character */
  14909.             if (c == IAC) {    /* If it's IAC */
  14910.             dbuf[x++] = c;    /* put another one */
  14911.             debug(F000,">>> QUOTED IAC","",c);
  14912.             } else if (c != 0x0a && out_prev == 0x0d) {    /* Bare CR */
  14913.             if (!TELOPT_ME(TELOPT_BINARY)) { /* NVT rule */
  14914.                 c = 0x00;
  14915.                 dbuf[x++] = c;
  14916.                 debug(F000,">>> CR-NUL","",c);
  14917.             }            
  14918.             }
  14919.             dbuf[x++] = c;    /* Copy and count it */
  14920.             debug(F000,">>> char",ckitoa(in_state),c);
  14921.             out_prev = c;
  14922.         }
  14923.         s = dbuf;        /* New source */
  14924.         } else
  14925. #endif /* TNCODE */
  14926.           x = pbuf_avail - pbuf_written; /* How much to send */
  14927.  
  14928.         debug(F101,"ttptycmd bytes to send","",x);
  14929.         x = ttol(s, x);
  14930.         debug(F101,">>> ttol","",x);
  14931.         if (x < 0) {
  14932.         net_err++;
  14933.         debug(F111,"ttptycmd ttol error",ckitoa(x),errno);
  14934.         x = 0;
  14935.         }
  14936.         write_net_bytes += x;
  14937.         pbuf_written += x;
  14938.     }
  14939.     if (FD_ISSET(ptyfd, &out)) {    /* Can write to pty? */
  14940.         debug(F100,"ttptycmd FD_ISSET ptyfd out","",0);
  14941.         errno = 0;
  14942. #ifndef COMMENT
  14943.         x = write(ptyfd,tbuf + tbuf_written,tbuf_avail - tbuf_written);
  14944. #else
  14945.         /* Byte loop to rule out data overruns in the pty */
  14946.         /* (it makes no difference) */
  14947.         {
  14948.         char *p = tbuf+tbuf_written;
  14949.         int n = tbuf_avail - tbuf_written;
  14950.         for (x = 0; x < n; x++) {
  14951.             msleep(10);
  14952.             if (write(ptyfd,&(p[x]),1) < 0)
  14953.               break;
  14954.         }
  14955.         }
  14956. #endif /* COMMENT */
  14957.         debug(F111,"ttptycmd ptyfd write",ckitoa(errno),x);
  14958.         if (x > 0) {
  14959.         tbuf_written += x;
  14960.         write_pty_bytes += x;
  14961.         } else {
  14962.         x = 0;
  14963.         pty_err++;
  14964.         if (pexitstat < 0) {
  14965.             status = pty_get_status(ptyfd,pty_fork_pid);
  14966.             debug(F101,"ttptycmd pty_get_status B","",status);
  14967.             if (status > -1) pexitstat = status;
  14968.             have_pty = 0;
  14969.         }
  14970.         debug(F100,"ttptycmd +++ ptyfd write error","",0);
  14971.         }
  14972.     }
  14973.     if (FD_ISSET(ttyfd, &in)) {    /* Can read from net? */
  14974.         tset++;
  14975.         debug(F100,"ttptycmd FD_ISSET ttyfd in","",0);
  14976.         n = in_chk(1,ttyfd);
  14977.         debug(F101,"ttptycmd in_chk(ttyfd)","",n); 
  14978.         if (n < 0 || ttyfd == -1) {
  14979.         debug(F101,"ttptycmd +++ ttyfd errno","",errno);
  14980.         net_err++;
  14981.         } else if (n > 0) {
  14982.         if (n > PTY_TBUF_SIZE - tbuf_avail)
  14983.           n = PTY_TBUF_SIZE - tbuf_avail;
  14984.         debug(F101,"ttptycmd net read size adjusted","",n); 
  14985.         if (xlocal && netconn) {
  14986.             /*
  14987.               We have to use a byte loop here because ttxin()
  14988.               does not decrypt or, for that matter, handle Telnet.
  14989.             */
  14990.             int c;
  14991.             CHAR * p;
  14992.             p = tbuf + tbuf_avail;
  14993.             for (x = 0; x < n; x++) {
  14994.             if ((c = ttinc(0)) < 0)
  14995.               break;
  14996.             if (!is_tn) {    /* Not Telnet - keep all bytes */
  14997.                 *p++ = (CHAR)c;
  14998.                 debug(F000,"<<< char","",c);
  14999. #ifdef TNCODE
  15000.             } else {    /* Telnet - must handle IAC and NVT */
  15001.                 debug(F000,"<<< char",ckitoa(in_state),c);
  15002.                 switch (c) {
  15003.                   case 0x00: /* NUL */
  15004.                 if (in_state == HAVE_CR) {
  15005.                     debug(F000,"<<< SKIP","",c);
  15006.                 } else {
  15007.                     *p++ = c;
  15008.                     debug(F000,"<<< Keep","",c);
  15009.                 }
  15010.                 in_state = 0;
  15011.                 break;
  15012.                   case 0x0d: /* CR */
  15013.                 if (!TELOPT_U(TELOPT_BINARY))
  15014.                   in_state = HAVE_CR;
  15015.                 *p++ = c;
  15016.                 debug(F000,"<<< Keep","",c);
  15017.                 break;
  15018. #ifdef COMMENT
  15019.                   case 0x0f: /* Ctrl-O */
  15020.                   case 0x16: /* Ctrl-V */
  15021.                 *p++ = 0x16;
  15022.                 *p++ = c;
  15023.                 debug(F000,"<<< QUOT","",c);
  15024.                 break;
  15025. #endif /* COMMENT */
  15026.                   case 0xff: /* IAC */
  15027.                 if (in_state == HAVE_IAC) {
  15028.                     debug(F000,"<<< KEEP","",c);
  15029.                     *p++ = c;
  15030.                     in_state = 0;
  15031.                 } else {
  15032.                     debug(F000,"<<< SKIP","",c);
  15033.                     in_state = HAVE_IAC;
  15034.                 }
  15035.                 break;
  15036.                   default:    /* All others */
  15037.                 if (in_state == HAVE_IAC) {
  15038. #ifdef COMMENT
  15039. /*
  15040.   tn_doop() will consume an unknown number of bytes and we'll overshoot
  15041.   the for-loop.  The only Telnet command I've ever seen arrive here is
  15042.   a Data Mark, which comes when the remote protocol exits and the remote
  15043.   job returns to its shell prompt.  On the assumption it's a 1-byte command,
  15044.   we don't write out the IAC or the command, and we clear the state.  If
  15045.   we called tn_doop() we'd have no way of knowing how many bytes it took
  15046.   from the input stream.
  15047. */
  15048.                     int xx;
  15049.                     xx = tn_doop((CHAR)c,duplex,ttinc);
  15050.                     debug(F111,"<<< DOOP",ckctoa(c),xx);
  15051. #else
  15052.                     debug(F101,"<<< DOOP","",c);
  15053. #endif    /* COMMENT */
  15054.                     in_state = 0;
  15055.                 } else {
  15056.                     *p++ = c;
  15057.                     debug(F000,"<<< keep","",c);
  15058.                     in_state = 0;
  15059.                 }
  15060.                 }
  15061. #endif    /* TNCODE */
  15062.             }
  15063.             }
  15064.             ckmakmsg(msgbuf,500,
  15065.                  "ttptycmd read net [ttinc loop] errno=",
  15066.                  ckitoa(errno),
  15067.                  " count=",
  15068.                  ckitoa(x));
  15069.             debug(F100,msgbuf,"",0);
  15070.         } else {
  15071.             x = ttxin(n,tbuf+tbuf_avail);
  15072.             debug(F101,"ttptycmd ttxin x","",x); 
  15073.         }
  15074.  
  15075.         if (x < 0) {
  15076.             debug(F101,"ttptycmd read net error","",x);
  15077.             net_err++;
  15078.         }
  15079.         tbuf_avail += x;
  15080.         read_net_bytes += x;
  15081.         }
  15082.  
  15083.     } else
  15084.       tnotset++;
  15085.  
  15086.     if (FD_ISSET(ptyfd, &in)) {    /* Read from pty? */
  15087.         pset++;
  15088.         debug(F100,"ttptycmd FD_ISSET ptyfd in","",0);
  15089. #ifdef PTY_USE_NDELAY
  15090.         n = PTY_PBUF_SIZE;
  15091. #else
  15092.         /*
  15093.           This does not work on nonblocking channels
  15094.           on certain platforms such as NetBSD.
  15095.         */
  15096.         n = pty_chk(ptyfd);
  15097. #endif /* PTY_USE_NDELAY */
  15098.         debug(F101,"ttptycmd pty_chk() n","",n); 
  15099.  
  15100.         if (n < 0)
  15101.           n = 0;
  15102.         if (n > 0) {
  15103.         if (n > PTY_PBUF_SIZE - pbuf_avail)
  15104.           n = PTY_PBUF_SIZE - pbuf_avail;
  15105.         debug(F101,"ttptycmd pty read size adjusted","",n); 
  15106.         errno = 0;
  15107.         x = read(ptyfd,pbuf+pbuf_avail,n);
  15108. #ifdef DEBUG
  15109.         if (deblog) {
  15110.             ckmakmsg(msgbuf,500,
  15111.                  "ttptycmd read pty errno=",
  15112.                  ckitoa(errno),
  15113.                  " count=",
  15114.                  ckitoa(x));
  15115.             debug(F100,msgbuf,"",0);
  15116.         }
  15117. #endif    /* DEBUG */
  15118.  
  15119.         if (x < 0 && errno == EAGAIN)
  15120.           x = 0;
  15121.  
  15122.         if (x < 0) {        /* This works on Solaris and Linux */
  15123.             pty_err++;        /* but not NetBSD */
  15124.             debug(F100,"TERMINATION TEST A","",0);
  15125. #ifdef COMMENT
  15126.             if (errno == EIO)
  15127.               rc = 1;
  15128. #endif    /* COMMENT */
  15129.             if (pexitstat < 0) {
  15130.             status = pty_get_status(ptyfd,pty_fork_pid);
  15131.             debug(F101,"ttptycmd pty_get_status C","",status);
  15132.             if (status > -1) pexitstat = status;
  15133.             }
  15134.             have_pty = 0;
  15135.             x = 0;
  15136.         }
  15137.         if (x == 0 && !pty_err) { /* This works on NetBSD but */
  15138.             debug(F100,"TERMINATION TEST B","",0);
  15139.             status = pexitstat > -1 ? pexitstat :
  15140.             pty_get_status(ptyfd,pty_fork_pid);
  15141.             debug(F101,"ttptycmd pty_get_status D","",status);
  15142.             if (status > -1) {
  15143.             pexitstat = status;
  15144.             pty_err++;
  15145.             have_pty = 0;
  15146.             } else {        /* Select() lied */
  15147.             pty_err = 0;    /* pty still there but has nothing */
  15148.             msleep(100);    /* sleep a bit */
  15149.             }
  15150.             x = 0;
  15151.         } 
  15152.         /* Hopefully the next two are no longer needed... */
  15153.         if (!pty_err && (
  15154. #ifndef PTY_USE_NDELAY
  15155.             x < 1 || errno
  15156. #else
  15157.             errno != 0 && errno != EAGAIN
  15158. #endif /* PTY_USE_NDELAY */
  15159.             )) {
  15160.             debug(F100,"TERMINATION TEST C","",0);
  15161.             pty_err++;
  15162.             debug(F101,"ttptycmd SET pty_err","",pty_err);
  15163.             if (errno == EIO)    /* errno == EIO is like EOF */
  15164.               rc = 1;
  15165.             if (x < 0)
  15166.               x = 0;
  15167.         }
  15168. #ifdef COMMENT
  15169. #ifdef DEBUG
  15170.         if (deblog) {
  15171.             pbuf[pbuf_avail + x] = '\0';
  15172.             debug(F111,"ttptycmd added to pty buffer",
  15173.               pbuf+pbuf_avail,x);
  15174.         }
  15175. #endif    /* DEBUG */
  15176. #endif    /* COMMENT */
  15177.         pbuf_avail += x;
  15178.         read_pty_bytes += x;
  15179.         } else {            /* n == 0 with blocking reads */
  15180.         debug(F100,
  15181.               "PTY READ RETURNED ZERO BYTES - SHOULD NOT HAPPEN",
  15182.               "",0);
  15183.         }
  15184.     } else
  15185.       pnotset++;
  15186.  
  15187.     /* If writes have caught up to reads, reset the buffers */
  15188.  
  15189.     if (pbuf_written == pbuf_avail)
  15190.       pbuf_written = pbuf_avail = 0;
  15191.     if (tbuf_written == tbuf_avail)
  15192.       tbuf_written = tbuf_avail = 0;
  15193.  
  15194.     /* See if we can exit */
  15195.  
  15196.     x1 = pbuf_avail - pbuf_written; 
  15197.     x2 = tbuf_avail - tbuf_written;
  15198.  
  15199.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pty_err","",pty_err);
  15200.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x1 [write to net]","",x1);
  15201.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x2 [write to pty]","",x2);
  15202.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc","",rc);
  15203.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST status","",status);
  15204.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pexitstat","",pexitstat);
  15205.  
  15206.     if (net_err) {            /* Net error? */
  15207.         debug(F101,"ttptycmd net_err LOOP EXIT TEST net_err","",net_err);
  15208.         if (have_net) {
  15209.         if (local) {
  15210.             ttclos(0);
  15211.             printf("?Connection closed\n");
  15212.         }
  15213.         have_net = 0;
  15214.         }
  15215.         debug(F101,"ttptycmd net_err LOOP EXIT TEST x1","",x1);
  15216.         if (x1 == 0)
  15217.           break;
  15218.     }
  15219.     if (pty_err) {            /* Pty error? */
  15220.         if (have_pty) {
  15221.         if (pexitstat < 0) {        
  15222.             status = pty_get_status(ptyfd,pty_fork_pid);
  15223.             debug(F101,"ttptycmd pty_get_status E","",status);
  15224.             if (status > -1) pexitstat = status;
  15225.         }
  15226.         have_pty = 0;
  15227.         }
  15228.         if (x1 == 0 && x2 == 0) {    /* If buffers are caught up */
  15229.         rc = 1;            /* set preliminary return to success */
  15230.         debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc 2","",rc);
  15231.         break;            /* and exit the loop */
  15232.         }
  15233.     }
  15234.     }
  15235.     debug(F101,"ttptycmd +++ have_pty","",have_pty);
  15236.     if (have_pty) {            /* In case select() failed */
  15237. #ifdef USE_CKUPTY_C
  15238.     end_pty();
  15239.     close(ptyfd);
  15240. #else
  15241.     close(slavefd);
  15242.     close(masterfd);
  15243. #endif /* USE_CKUPTY_C */
  15244.     }
  15245.     pty_master_fd = -1;
  15246.     debug(F101,"ttptycmd +++ pexitstat","",pexitstat);
  15247.     if (pexitstat < 0) {        /* Try one last time to get status */
  15248.     status = pty_get_status(ptyfd,pty_fork_pid);
  15249.     debug(F101,"ttptycmd pty_get_status F","",status);
  15250.     if (status > -1) pexitstat = status;
  15251.     }
  15252.     debug(F101,"ttptycmd +++ final pexitstat","",pexitstat);
  15253.     if (deblog) {            /* Stats for debug log */
  15254.     debug(F101,"ttptycmd +++ pset    ","",pset);
  15255.     debug(F101,"ttptycmd +++ pnotset","",pnotset);
  15256.     debug(F101,"ttptycmd +++ tset    ","",tset);
  15257.     debug(F101,"ttptycmd +++ tnotset","",tnotset);
  15258.  
  15259.     debug(F101,"ttptycmd +++  read_pty_bytes","",read_pty_bytes);
  15260.     debug(F101,"ttptycmd +++ write_net_bytes","",write_net_bytes);
  15261.     debug(F101,"ttptycmd +++  read_net_bytes","",read_net_bytes);
  15262.     debug(F101,"ttptycmd +++ write_pty_bytes","",write_pty_bytes);
  15263.     }
  15264. /*
  15265.   If we got the external protocol's exit status from waitpid(), we use that
  15266.   to set our return code.  If not, we fall back on whatever rc was previously
  15267.   set to, namely 1 (success) if the pty fork seemed to terminate, 0 otherwise.
  15268. */
  15269.     if (save_sigchld) {            /* Restore this if we changed it */
  15270.     (VOID) signal(SIGCHLD,save_sigchld);
  15271.     save_sigchld = NULL;
  15272.     }
  15273.     msleep(500);
  15274.     x = kill(pty_fork_pid,SIGHUP);    /* In case it's still there */
  15275.     pty_fork_pid = -1;
  15276.     debug(F101,"ttptycmd fork kill SIGHUP","",x);
  15277.     if (pexitstat > -1)
  15278.       rc = (pexitstat == 0 ? 1 : 0);
  15279.     debug(F101,"ttptycmd +++ rc","",rc);
  15280.     if (!local) {            /* If in remote mode */
  15281.     conres();            /* restore console to CBREAK mode */
  15282.     concb((char)escchr);
  15283.     }
  15284.     return(rc);
  15285. }
  15286. #endif    /* NETPTY */
  15287. #endif    /* SELECT */
  15288.  
  15289. /* T T R U N C M D  --  Redirect an external command over the connection. */
  15290.  
  15291. /*
  15292.   TTRUNCMD is the routine that was originally used for running external
  15293.   protocols.  It is very simple and works fine provided (a) the connection
  15294.   is not encrypted, and (b) the external protocol uses standard i/o
  15295.   (file descriptors 0 and 1) for file transfer.
  15296. */
  15297.  
  15298. int
  15299. ttruncmd(s) char *s; {
  15300.     PID_T pid;                /* pid of lower fork */
  15301.     int wstat;                /* for wait() */
  15302.     int x;
  15303.     int statusp;
  15304.  
  15305.     if (ttyfd == -1) {
  15306.     printf("?Sorry, device is not open\n");
  15307.     return(0);
  15308.     }
  15309.     if (nopush) {
  15310.     debug(F100,"ttruncmd fail: nopush","",0);
  15311.     return(0);
  15312.     }
  15313.  
  15314. #ifdef NETPTY
  15315. /***************
  15316.   It might also be necessary to use the pty routine for other reasons,
  15317.   e.g. because the external program does not use stdio.
  15318. */
  15319. #ifdef NETCONN
  15320. /*
  15321.   If we have a network connection we use a different routine because
  15322.   (a) if the connection is encrypted, the mechanism used here can't deal
  15323.   with it; and (b) it won't handle any network protocols either, e.g.
  15324.   Telnet, Rlogin, K5 U-to-U, etc.  However, this routine works much
  15325.   better (faster, more transparent) on serial connections and when
  15326.   C-Kermit is in remote mode (i.e. is on the far end).
  15327. */
  15328.     /* For testing always use this */
  15329.     if (netconn)
  15330.       return(ttptycmd(s));
  15331. #endif /* NETCONN */
  15332.  
  15333. /***************/
  15334. #else  /* NETPTY */
  15335.     if (tt_is_secure()) {
  15336.     printf("?Sorry, \
  15337. external protocols over secure connections not supported in this OS.\n"
  15338.               );
  15339.         return(0);
  15340.     }
  15341. #endif    /* NETPTY */
  15342.  
  15343.     conres();                /* Make console normal  */
  15344.     pexitstat = -4;
  15345.     if ((pid = fork()) == 0) {        /* Make a child fork */
  15346.     if (priv_can())            /* Child: turn off privs. */
  15347.       exit(1);
  15348.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  15349.     dup2(ttyfd, 1);
  15350.     x = system(s);
  15351.     debug(F101,"ttruncmd system",s,x);
  15352.     _exit(x ? BAD_EXIT : 0);
  15353.     } else {
  15354.     SIGTYP (*istat)(), (*qstat)();
  15355.     if (pid == (PID_T) -1)        /* fork() failed? */
  15356.       return(0);
  15357.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  15358.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  15359.  
  15360. #ifdef COMMENT
  15361.         while (((wstat = wait(&statusp)) != pid) && (wstat != -1)) ;
  15362. #else  /* Not COMMENT */
  15363.         while (1) {
  15364.         wstat = wait(&statusp);
  15365.         debug(F101,"ttruncmd wait","",wstat);
  15366.         if (wstat == pid || wstat == -1)
  15367.           break;
  15368.     }
  15369. #endif /* COMMENT */
  15370.  
  15371.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  15372.     debug(F101,"ttruncmd wait statusp","",statusp);
  15373.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  15374.     signal(SIGINT,istat);        /* Restore interrupts */
  15375.     signal(SIGQUIT,qstat);
  15376.     }
  15377.     concb((char)escchr);        /* Restore console to CBREAK mode */
  15378.     return(statusp == 0 ? 1 : 0);
  15379. }
  15380. #endif    /* CK_REDIR */
  15381.  
  15382. struct tm *
  15383. #ifdef CK_ANSIC
  15384. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  15385. #else
  15386. cmdate2tm(date,gmt) char * date; int gmt;
  15387. #endif
  15388. {
  15389.     /* date as "yyyymmdd hh:mm:ss" */
  15390.     static struct tm _tm;
  15391.     time_t now;
  15392.  
  15393.     if (strlen(date) != 17 ||
  15394.     date[8] != ' ' ||
  15395.     date[11] != ':' ||
  15396.     date[14] != ':')
  15397.       return(NULL);
  15398.  
  15399.     time(&now);
  15400.     if (gmt)
  15401.       _tm = *gmtime(&now);
  15402.     else
  15403.       _tm = *localtime(&now);
  15404.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  15405.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  15406.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  15407.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  15408.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  15409.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  15410.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  15411.  
  15412.     /* Should we set _tm.tm_isdst to -1 here? */
  15413.  
  15414.     _tm.tm_wday = 0;
  15415.     _tm.tm_yday = 0;
  15416.  
  15417.     return(&_tm);
  15418. }
  15419.  
  15420. #ifdef OXOS
  15421. #undef kill
  15422. #endif /* OXOS */
  15423.  
  15424. #ifdef OXOS
  15425. int
  15426. priv_kill(pid, sig) int pid, sig; {
  15427.     int    i;
  15428.  
  15429.     if (priv_on())
  15430.     debug(F100,"priv_kill priv_on failed","",0);
  15431.     i = kill(pid, sig);
  15432.     if (priv_off())
  15433.     debug(F100,"priv_kill priv_off failed","",0);
  15434.     return(i);
  15435. }
  15436. #endif /* OXOS */
  15437.  
  15438. #ifdef BEOSORBEBOX
  15439. /* #ifdef BE_DR_7 */
  15440. /*
  15441.   alarm() function not supplied with Be OS DR7 - this one contributed by
  15442.   Neal P. Murphy.
  15443. */
  15444.  
  15445. /*
  15446.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  15447.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  15448.   and wait for the alarm thread to finish.
  15449. */
  15450. unsigned int
  15451. alarm(unsigned int seconds) {
  15452.     long time_left = 0;
  15453.  
  15454. /* If an alarm is active, turn it off, saving the unused time */
  15455.     if (alarm_thread != -1) {
  15456.         /* We'll be generous and count partial seconds as whole seconds. */
  15457.         time_left = alarm_struct.time -
  15458.       ((system_time() - time_started) / 1000000.0);
  15459.  
  15460.         /* Kill the alarm thread */
  15461.         kill_thread (alarm_thread);
  15462.  
  15463.         /* We need to clean up as though the alarm occured. */
  15464.         time_started = 0;
  15465.         alarm_struct.thread = -1;
  15466.         alarm_struct.time = 0;
  15467.         alarm_expired();
  15468.     }
  15469.  
  15470. /* Set a new alarm clock, if requested. */
  15471.     if (seconds > 0) {
  15472.         alarm_struct.thread = find_thread(NULL);
  15473.         alarm_struct.time = seconds;
  15474.         time_started = system_time();
  15475.         alarm_thread = spawn_thread (do_alarm,
  15476.                                      "alarm_thread",
  15477.                                      B_NORMAL_PRIORITY,
  15478.                                      (void *) &alarm_struct
  15479.                      );
  15480.         resume_thread (alarm_thread);
  15481.     }
  15482.  
  15483. /* Now return [unused time | 0] */
  15484.     return ((unsigned int) time_left);
  15485. }
  15486.  
  15487. /*
  15488.   This function is the departure from UNIX/POSIX alarm handling. In the case
  15489.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  15490.   handler. When Be implements alarm(), this function call can be eliminated
  15491.   from user's SIGALRM signal handlers.
  15492. */
  15493.  
  15494. void
  15495. alarm_expired(void) {
  15496.     long ret_val;
  15497.  
  15498.     if (alarm_thread != -1) {
  15499.         wait_for_thread (alarm_thread, &ret_val);
  15500.         alarm_thread = -1;
  15501.     }
  15502. }
  15503.  
  15504. /*
  15505.   This is the function that snoozes the requisite number of seconds and then
  15506.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  15507.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  15508.   cast anyway. This function is run in a separate thread.
  15509. */
  15510.  
  15511. long
  15512. do_alarm (void *alarm_struct) {
  15513.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  15514.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  15515.     time_started = 0;
  15516.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  15517.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  15518. }
  15519. /* #endif */ /* BE_DR_7 */
  15520. #endif /* BEOSORBEBOX */
  15521.  
  15522. #ifdef Plan9
  15523.  
  15524. int
  15525. p9ttyctl(char letter, int num, int param) {
  15526.     char cmd[20];
  15527.     int len;
  15528.  
  15529.     if (ttyctlfd < 0)
  15530.       return -1;
  15531.  
  15532.     cmd[0] = letter;
  15533.     if (num)
  15534.       len = sprintf(cmd + 1, "%d", param) + 1;
  15535.     else {
  15536.     cmd[1] = param;
  15537.     len = 2;
  15538.     }
  15539.     if (write(ttyctlfd, cmd, len) == len) {
  15540.     cmd[len] = 0;
  15541.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  15542.     return 0;
  15543.     }
  15544.     return -1;
  15545. }
  15546.  
  15547. int
  15548. p9ttyparity(char l) {
  15549.     return p9ttyctl('p', 0, l);
  15550. }
  15551.  
  15552. int
  15553. p9tthflow(int flow, int status) {
  15554.     return p9ttyctl('m', 1, status);
  15555. }
  15556.  
  15557. int
  15558. p9ttsspd(int cps) {
  15559.     if (p9ttyctl('b', 1, cps * 10) < 0)
  15560.       return -1;
  15561.     ttylastspeed = cps * 10;
  15562.     return 0;
  15563. }
  15564.  
  15565. int
  15566. p9openttyctl(char *ttname) {
  15567.     char name[100];
  15568.  
  15569.     if (ttyctlfd >= 0) {
  15570.     close(ttyctlfd);
  15571.     ttyctlfd = -1;
  15572.     ttylastspeed = -1;
  15573.     }
  15574.     sprintf(name, "%sctl", ttname);
  15575.     ttyctlfd = open(name, 1);
  15576.     return ttyctlfd;
  15577. }
  15578.  
  15579. int
  15580. p9concb() {
  15581.     if (consctlfd >= 0) {
  15582.     if (write(consctlfd, "rawon", 5) == 5)
  15583.       return 0;
  15584.     }
  15585.     return -1;
  15586. }
  15587.  
  15588. int
  15589. p9conbin() {
  15590.     return p9concb();
  15591. }
  15592.  
  15593. int
  15594. p9conres() {
  15595.     if (consctlfd >= 0) {
  15596.     if (write(consctlfd, "rawoff", 6) == 6)
  15597.       return 0;
  15598.     }
  15599.     return -1;
  15600. }
  15601.  
  15602. int
  15603. p9sndbrk(int msec) {
  15604.     if (ttyctlfd >= 0) {
  15605.     char cmd[20];
  15606.     int i = sprintf(cmd, "k%d", msec);
  15607.     if (write(ttyctlfd, cmd, i) == i)
  15608.       return 0;
  15609.     }
  15610.     return -1;
  15611. }
  15612.  
  15613. int
  15614. conwrite(char *buf, int n) {
  15615.     int x;
  15616.     static int length = 0;
  15617.     static int holdingcr = 0;
  15618.     int normal = 0;
  15619.     for (x = 0; x < n; x++) {
  15620.     char c = buf[x];
  15621.     if (c == 007) {
  15622.         if (normal) {
  15623.         write(1, buf + (x - normal), normal);
  15624.         length += normal;
  15625.         normal = 0;
  15626.         }
  15627.         /* write(noisefd, "1000 300", 8); */
  15628.         holdingcr = 0;
  15629.     } else if (c == '\r') {
  15630.         if (normal) {
  15631.         write(1, buf + (x - normal), normal);
  15632.         length += normal;
  15633.         normal = 0;
  15634.         }
  15635.         holdingcr = 1;
  15636.     } else if (c == '\n') {
  15637.         write(1, buf + (x - normal), normal + 1);
  15638.         normal = 0;
  15639.         length = 0;
  15640.         holdingcr = 0;
  15641.     } else if (c == '\b') {
  15642.         if (normal) {
  15643.         write(1, buf + (x - normal), normal);
  15644.         length += normal;
  15645.         normal = 0;
  15646.         }
  15647.         if (length) {
  15648.         write(1, &c, 1);
  15649.         length--;
  15650.         }
  15651.         holdingcr = 0;
  15652.     } else {
  15653.         if (holdingcr) {
  15654.         char b = '\b';
  15655.         while (length-- > 0)
  15656.           write(1, &b, 1);
  15657.         length = 0;    /* compiler bug */
  15658.         }
  15659.         holdingcr = 0;
  15660.         normal++;
  15661.     }
  15662.     }
  15663.     if (normal) {
  15664.     write(1, buf + (x - normal), normal);
  15665.     length += normal;
  15666.     }
  15667.     return n;
  15668. }
  15669.  
  15670. void
  15671. conprint(char *fmt, ...) {
  15672.     static char buf[1000];        /* not safe if on the stack */
  15673.  
  15674.     va_list ap;
  15675.     int i;
  15676.  
  15677.     va_start(ap, fmt);
  15678.     i = vsprintf(buf, fmt, ap);
  15679.     conwrite(buf, i);
  15680. }
  15681. #endif /* Plan9 */
  15682.  
  15683. /* fprintf, printf, perror replacements... */
  15684.  
  15685. /* f p r i n t f */
  15686.  
  15687. #ifdef UNIX
  15688. #ifdef CK_ANSIC
  15689. #include <stdarg.h>
  15690. #else /* CK_ANSIC */
  15691. #ifdef __GNUC__
  15692. #include <stdarg.h>
  15693. #else
  15694. #include <varargs.h>
  15695. #endif    /* __GNUC__ */
  15696. #endif /* CK_ANSIC */
  15697. #ifdef fprintf
  15698. #undef fprintf
  15699. static char str1[4096];
  15700. static char str2[4096];
  15701. int
  15702. #ifdef CK_ANSIC
  15703. ckxfprintf(FILE * file, const char * format, ...)
  15704. #else /* CK_ANSIC */
  15705. ckxfprintf(va_alist) va_dcl
  15706. #endif /* CK_ANSIC */
  15707. /* ckxfprintf */ {
  15708.     int i, j, len, got_cr;
  15709.     va_list args;
  15710.     int rc = 0;
  15711.  
  15712. #ifdef CK_ANSIC
  15713.     va_start(args, format);
  15714. #else /* CK_ANSIC */
  15715.     char * format;
  15716.     FILE * file;
  15717.     va_start(args);
  15718.     file = va_arg(args,FILE *);
  15719.     format = va_arg(args,char *);
  15720. #endif /* CK_ANSIC */
  15721.  
  15722.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  15723.     rc = vfprintf(file,format,args);
  15724.     } else {
  15725.     unsigned int c;
  15726.         rc = vsprintf(str1, format, args);
  15727.         len = strlen(str1);
  15728.         if (len >= sizeof(str1)) {
  15729.             debug(F101,"ckxfprintf() buffer overflow","",len);
  15730.             doexit(BAD_EXIT,1);
  15731.         }
  15732.         for (i = 0, j = 0, got_cr = 0;
  15733.          i < len && j < sizeof(str1)-2;
  15734.          i++, j++ ) {
  15735.         /* We can't use 255 as a case label because of signed chars */
  15736.         c = (unsigned)(str1[i] & 0xff);
  15737. #ifdef TNCODE
  15738.         if (c == 255) {
  15739.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15740.           str2[j++] = '\0';
  15741.         str2[j++] = IAC;
  15742.         str2[j] = IAC;
  15743.         got_cr = 0;
  15744.         } else
  15745. #endif /* TNCODE */
  15746.         switch (c) {
  15747.           case '\r':
  15748.                 if (got_cr
  15749. #ifdef TNCODE
  15750.             && !TELOPT_ME(TELOPT_BINARY)
  15751. #endif /* TNCODE */
  15752.             )
  15753.           str2[j++] = '\0';
  15754.                 str2[j] = str1[i];
  15755.                 got_cr = 1;
  15756.                 break;
  15757.           case '\n':
  15758.                 if (!got_cr)
  15759.           str2[j++] = '\r';
  15760.                 str2[j] = str1[i];
  15761.                 got_cr = 0;
  15762.                 break;
  15763.           default:
  15764.                 if (got_cr
  15765. #ifdef TNCODE
  15766.             && !TELOPT_ME(TELOPT_BINARY)
  15767. #endif /* TNCODE */
  15768.             )
  15769.           str2[j++] = '\0';
  15770.                 str2[j] = str1[i];
  15771.                 got_cr = 0;
  15772.             }
  15773.         }
  15774.         if (got_cr
  15775. #ifdef TNCODE
  15776.              && !TELOPT_ME(TELOPT_BINARY)
  15777. #endif /* TNCODE */
  15778.              )
  15779.             str2[j++] = '\0';
  15780. #ifdef CK_ENCRYPTION
  15781. #ifdef TNCODE
  15782.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15783.       ck_tn_encrypt(str2,j);
  15784. #endif /* TNCODE */
  15785. #endif /* CK_ENCRYPTION */
  15786. #ifdef CK_SSL
  15787.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15788.         /* Write using SSL */
  15789.             char * p = str2;
  15790.           ssl_retry:
  15791.             if (ssl_active_flag)
  15792.           rc = SSL_write(ssl_con, p, j);
  15793.             else
  15794.           rc = SSL_write(tls_con, p, j);
  15795.         debug(F111,"ckxfprintf","SSL_write",rc);
  15796.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15797.           case SSL_ERROR_NONE:
  15798.                 if (rc == j)
  15799.           break;
  15800.                 p += rc;
  15801.                 j -= rc;
  15802.                 goto ssl_retry;
  15803.           case SSL_ERROR_WANT_WRITE:
  15804.           case SSL_ERROR_WANT_READ:
  15805.           case SSL_ERROR_SYSCALL:
  15806.                 if (rc != 0)
  15807.           return(-1);
  15808.           case SSL_ERROR_WANT_X509_LOOKUP:
  15809.           case SSL_ERROR_SSL:
  15810.           case SSL_ERROR_ZERO_RETURN:
  15811.           default:
  15812.                 rc = 0;
  15813.             }
  15814.     } else
  15815. #endif /* CK_SSL */
  15816.         fwrite(str2,sizeof(char),j,stdout);
  15817.     }
  15818.     va_end(args);
  15819.     return(rc);
  15820. }
  15821. #endif /* fprintf */
  15822.  
  15823. /* p r i n t f */
  15824.  
  15825. #ifdef printf
  15826. #undef printf
  15827. int
  15828. #ifdef CK_ANSIC
  15829. ckxprintf(const char * format, ...)
  15830. #else /* CK_ANSIC */
  15831. ckxprintf(va_alist) va_dcl
  15832. #endif /* CK_ANSIC */
  15833. /* ckxprintf */ {
  15834.     int i, j, len, got_cr;
  15835.     va_list args;
  15836.     int rc = 0;
  15837.  
  15838. #ifdef CK_ANSIC
  15839.     va_start(args, format);
  15840. #else /* CK_ANSIC */
  15841.     char * format;
  15842.     va_start(args);
  15843.     format = va_arg(args,char *);
  15844. #endif /* CK_ANSIC */
  15845.  
  15846.     if (!inserver) {
  15847.     rc = vprintf(format, args);
  15848.     } else {
  15849.     unsigned int c;
  15850.         rc = vsprintf(str1, format, args);
  15851.         len = strlen(str1);
  15852.         if (len >= sizeof(str1)) {
  15853.             debug(F101,"ckxprintf() buffer overflow","",len);
  15854.             doexit(BAD_EXIT,1);
  15855.         }
  15856.         for (i = 0, j = 0, got_cr=0;
  15857.          i < len && j < sizeof(str1)-2;
  15858.          i++, j++ ) {
  15859.         c = (unsigned)(str1[i] & 0xff);
  15860. #ifdef TNCODE
  15861.         if (c == 255) {
  15862.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15863.           str2[j++] = '\0';
  15864.         str2[j++] = IAC;
  15865.         str2[j] = IAC;
  15866.         got_cr = 0;
  15867.         } else
  15868. #endif /* TNCODE */
  15869.         switch (c) {
  15870.           case '\r':
  15871.                 if (got_cr
  15872. #ifdef TNCODE
  15873.             && !TELOPT_ME(TELOPT_BINARY)
  15874. #endif /* TNCODE */
  15875.             )
  15876.           str2[j++] = '\0';
  15877.                 str2[j] = str1[i];
  15878.                 got_cr = 1;
  15879.                 break;
  15880.           case '\n':
  15881.                 if (!got_cr)
  15882.           str2[j++] = '\r';
  15883.                 str2[j] = str1[i];
  15884.                 got_cr = 0;
  15885.                 break;
  15886.           default:
  15887.                 if (got_cr
  15888. #ifdef TNCODE
  15889.             && !TELOPT_ME(TELOPT_BINARY)
  15890. #endif /* TNCODE */
  15891.             )
  15892.           str2[j++] = '\0';
  15893.                 str2[j] = str1[i];
  15894.                 got_cr = 0;
  15895.                 break;
  15896.         }
  15897.         }
  15898.         if (got_cr
  15899. #ifdef TNCODE
  15900.              && !TELOPT_ME(TELOPT_BINARY)
  15901. #endif /* TNCODE */
  15902.              )
  15903.             str2[j++] = '\0';
  15904. #ifdef CK_ENCRYPTION
  15905. #ifdef TNCODE
  15906.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15907.       ck_tn_encrypt(str2,j);
  15908. #endif /* TNCODE */
  15909. #endif /* CK_ENCRYPTION */
  15910. #ifdef CK_SSL
  15911.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15912.             char * p = str2;
  15913.         /* Write using SSL */
  15914.           ssl_retry:
  15915.             if (ssl_active_flag)
  15916.           rc = SSL_write(ssl_con, p, j);
  15917.             else
  15918.           rc = SSL_write(tls_con, p, j);
  15919.         debug(F111,"ckxprintf","SSL_write",rc);
  15920.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15921.           case SSL_ERROR_NONE:
  15922.                 if (rc == j)
  15923.           break;
  15924.                 p += rc;
  15925.                 j -= rc;
  15926.                 goto ssl_retry;
  15927.           case SSL_ERROR_WANT_WRITE:
  15928.           case SSL_ERROR_WANT_READ:
  15929.           case SSL_ERROR_SYSCALL:
  15930.                 if (rc != 0)
  15931.           return(-1);
  15932.           case SSL_ERROR_WANT_X509_LOOKUP:
  15933.           case SSL_ERROR_SSL:
  15934.           case SSL_ERROR_ZERO_RETURN:
  15935.           default:
  15936.                 rc = 0;
  15937.             }
  15938.     } else
  15939. #endif /* CK_SSL */
  15940.       rc = fwrite(str2,sizeof(char),j,stdout);
  15941.     }
  15942.     va_end(args);
  15943.     return(rc);
  15944. }
  15945. #endif /* printf */
  15946.  
  15947. /*  p e r r o r  */
  15948.  
  15949. #ifdef perror
  15950. #undef perror
  15951. _PROTOTYP(char * ck_errstr,(VOID));
  15952. #ifdef NEXT
  15953. void
  15954. #else
  15955. #ifdef CK_SCOV5
  15956. void
  15957. #else
  15958. int
  15959. #endif /* CK_SCOV5 */
  15960. #endif /* NEXT */
  15961. #ifdef CK_ANSIC
  15962. ckxperror(const char * str)
  15963. #else /* CK_ANSIC */
  15964. ckxperror(str) char * str;
  15965. #endif /* CK_ANSIC */
  15966. /* ckxperror */ {
  15967.     char * errstr = ck_errstr();
  15968. #ifndef NEXT
  15969. #ifndef CK_SCOV5
  15970.     return
  15971. #endif /* CK_SCOV5 */
  15972. #endif /* NEXT */
  15973.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  15974. }
  15975. #endif /* perror */
  15976. #endif /* UNIX */
  15977.  
  15978. #ifdef MINIX2
  15979.  
  15980. /* Minix doesn't have a gettimeofday call (but MINIX3 does).
  15981.  * We fake one here using time(2)
  15982.  */
  15983.  
  15984. #ifndef MINIX3
  15985. int
  15986. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  15987.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  15988.     if(time(&(tp->tv_sec))==-1)
  15989.       return(-1);
  15990.     return(0);
  15991. }
  15992. #endif    /* MINIX3 */
  15993.  
  15994. #ifndef MINIX3
  15995. int
  15996. readlink(const char *path, void *buf, size_t bufsiz) {
  15997.     errno = ENOSYS;
  15998.     return(-1);
  15999. }
  16000. #endif    /* MINIX3 */
  16001.  
  16002. #endif /* MINIX2 */
  16003.