home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ck9196.zip / ckcnet.c < prev    next >
C/C++ Source or Header  |  2000-01-06  |  342KB  |  10,585 lines

  1. char *cknetv = "Network support, 7.0.194, 30 Dec 1999";
  2.  
  3. /*  C K C N E T  --  Network support  */
  4.  
  5. /*
  6.   Copyright (C) 1985, 1999,
  7.     Trustees of Columbia University in the City of New York.
  8.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  9.     copyright text in the ckcmai.c module for disclaimer and permissions.
  10. */
  11.  
  12. /*
  13.   REMINDER: Any changes made to this file that other modules depend must
  14.   also be made to cklnet.c (for VOS) until such time as cklnet.c and this
  15.   module are merged back together.
  16.  
  17.   NOTE TO CONTRIBUTORS: This file, and all the other shared (ckc and cku)
  18.   C-Kermit source files, must be compatible with C preprocessors that support
  19.   only #ifdef, #else, #endif, #define, and #undef.  Please do not use #if,
  20.   logical operators, or other preprocessor features in this module.  Also,
  21.   don't use any ANSI C constructs except within #ifdef CK_ANSIC..#endif.
  22.  
  23.   Authors:
  24.  
  25.   Frank da Cruz (fdc@columbia.edu),
  26.     Columbia University Academic Information Systems, New York City.
  27.   Jeffrey E Altman (jaltman@columbia.edu) -- OS/2 & Windows and a lot more.
  28.     netopen() routine for TCP/IP originally by Ken Yap, Rochester University
  29.     (ken@cs.rochester.edu) (no longer at that address).
  30.   Missing pieces for Excelan sockets library from William Bader.
  31.   Telnet protocol by Frank da Cruz and Jeffrey Altman.
  32.   Rlogin protocol by Jeffrey Altman.
  33.   SSL support adapted by Jeffrey Altman from work done by
  34.     Tim Hudson <tjh@cryptosoft.com> +61 7 32781581
  35.   TLS support by Jeffrey Altman.
  36.   HTTP support by Jeffrey Altman.
  37.   TGV MultiNet code by Frank da Cruz.
  38.   MultiNet code adapted to WIN/TCP by Ray Hunter of TWG.
  39.   MultiNet code adapted to DEC TCP/IP by Lee Tibbert of DEC and Frank da Cruz.
  40.   TCP/IP support adapted to IBM TCP/IP 1.2.1,2.0 for OS/2 by Kai Uwe Rommel.
  41.   CMU-OpenVMS/IP modifications by Mike O'Malley, Digital (DEC).
  42.   X.25 support by Marcello Frutig, Catholic University,
  43.     Rio de Janeiro, Brazil (frutig@rnp.impa.br) with fixes from
  44.     Stefaan Eeckels, Eurokom, Luxembourg.
  45.     David Lane added support for Stratus X.25 1996.
  46.     Stephen Riehm added support for IBM AIX X.25 in April 1998.
  47.   Other contributions as indicated in the code.
  48. */
  49. #define CKCNET_C
  50. #include "ckcsym.h"
  51. #include "ckcdeb.h"
  52. #include "ckcker.h"
  53. #ifdef I386IX                           /* Has to come before ckcnet.h in */
  54. #include <errno.h>                      /* this version, but after in others */
  55. #endif /* I386IX */
  56. #include "ckcnet.h"                     /* which includes ckctel.h */
  57. #ifdef CK_SSL
  58. #include "ck_ssl.h"
  59. #endif /* CK_SSL */
  60.  
  61. #ifdef CK_DNS_SRV
  62. #ifdef OS2
  63. #ifdef NT
  64. #include <wshelper.h>
  65. #else /* NT */
  66. /* !Error OS/2 does not support DNS Service Records. */
  67. #endif /* NT */
  68. #else /* OS2 */
  69. #include <arpa/inet.h>
  70. #include <arpa/nameser.h>
  71. #include <resolv.h>
  72. #ifndef PS2AIX10
  73. #include <netdb.h>
  74. #endif /* PS2AIX10 */
  75. #endif /* OS2 */
  76. #ifndef T_SRV
  77. #define T_SRV 33
  78. #endif /* T_SRV */
  79.  
  80. /* for old Unixes and friends ... */
  81. #ifndef MAXHOSTNAMELEN
  82. #define MAXHOSTNAMELEN 64
  83. #endif /* MAXHOSTNAMELEN */
  84.  
  85. #define MAX_DNS_NAMELEN (15*(MAXHOSTNAMELEN + 1)+1)
  86. #endif /* CK_DNS_SRV */
  87.  
  88. #ifdef NOLOCAL
  89. #ifdef TCPIPLIB
  90. #undef TCPIPLIB
  91. #endif /* TCPIPLIB */
  92. #endif /* NOLOCAL */
  93.  
  94. #ifndef NOMHHOST
  95. #ifdef datageneral
  96. #define NOMHHOST
  97. #else
  98. #ifdef HPUX5WINTCP
  99. #define NOMHHOST
  100. #endif /* HPUX5WINTCP */
  101. #endif /* datageneral */
  102. #endif /* NOMHHOST */
  103.  
  104. #ifdef INADDRX
  105.   struct in_addr inaddrx;
  106. #endif /* INADDRX */
  107.  
  108. int ttnet = NET_NONE;                   /* Network type */
  109. int ttnproto = NP_DEFAULT;              /* Network virtual terminal protocol */
  110.  
  111. /* 0 = don't lowercase username for Rlogin/Telnet protocol */
  112. /* nonzero = do lowercase it.  Add a SET command if necessary... */
  113. #ifdef VMS
  114. int ck_lcname = 1;
  115. #else
  116. int ck_lcname = 0;
  117. #endif /* VMS */
  118.  
  119. extern int                              /* External variables */
  120.   duplex, debses, seslog, sessft, wasclosed,
  121.   ttyfd, quiet, msgflg, what, nettype, ttmdm;
  122.  
  123. #ifdef NETCONN
  124. /* Don't need any of this if there is no network support. */
  125.  
  126. /*
  127.   NETLEBUF is (must be) defined for those platforms that call this
  128.   module to do network i/o (e.g. netinc(), nettchk(), etc) rather
  129.   than doing it themselves (ttinc(), ttchk(), etc).  In this case
  130.   the Telnet local-echo buffers and routines are defined and referenced
  131.   here, rather than in the ck?tio.c module.
  132. */
  133. #ifdef NETLEBUF
  134. #define LEBUFSIZ 4096
  135. int ttpush = -1, le_data = 0;           /* These are seen from outside */
  136. static CHAR le_buf[LEBUFSIZ];           /* These are used internally */
  137. static int le_start = 0, le_end = 0;
  138. int tt_push_inited = 0;
  139. #endif /* NETLEBUF */
  140.  
  141. #ifdef CK_SOCKS                         /* SOCKS Internet relay package */
  142. #ifdef CK_SOCKS5                        /* SOCKS 5 */
  143. #define accept  SOCKSaccept
  144. #define bind    SOCKSbind
  145. #define connect SOCKSconnect
  146. #define getsockname SOCKSgetsockname
  147. #define listen SOCKSlisten
  148. #else  /* Not SOCKS 5 */
  149. #define accept  Raccept
  150. #define bind    Rbind
  151. #define connect Rconnect
  152. #define getsockname Rgetsockname
  153. #define listen Rlisten
  154. #endif /* CK_SOCKS5 */
  155. #endif /* CK_SOCKS */
  156.  
  157. #ifdef DEC_TCPIP
  158. #include <time.h>
  159. #include <inet.h>
  160. #endif /* DEC_TCPIP */
  161.  
  162. /* Also see ckcnet.h -- hmmm, why don't we always include inet.h? */
  163.  
  164. #ifdef HPUX
  165. #ifndef HPUX7                           /* HPUX 7.00 doesn't have it */
  166. #include <arpa/inet.h>                  /* For inet_ntoa() prototype */
  167. #endif /* HPUX7 */
  168. #endif /* HPUX */
  169.  
  170. #ifdef CMU_TCPIP
  171. #include <time.h>
  172. #endif /* CMU_TCPIP */
  173.  
  174. #ifdef DCLTIMEVAL                       /* UnixWare 7 */
  175. struct timeval {                        /* And define these ourselves. */
  176.     long tv_sec;                        /* (see comments in ckutio.c) */
  177.     long tv_usec;
  178. };
  179. struct timezone {
  180.     int tz_minuteswest;
  181.     int tz_dsttime;
  182. };
  183. #endif /* DCLTIMEVAL */
  184.  
  185. #ifdef WINTCP
  186.  
  187. #include <setjmp.h>
  188. #include <signal.h>
  189. #include <sys/time.h>
  190. /*
  191.   The WIN/TCP code path is the same as that for MultiNet.
  192.   Only the routine names have changed ...
  193. */
  194. #define socket_read     netread
  195. #define socket_ioctl    ioctl
  196. #define socket_write    netwrite
  197. #define socket_close    netclose
  198.  
  199. #ifdef OLD_TWG                         /* some routines have evolved */
  200.         extern int vmserrno, uerrno;
  201. #define socket_errno    uerrno
  202. #define socket_perror   perror         /* which uses errno, not uerrno! */
  203. #else
  204. #define socket_errno    errno
  205. #define socket_perror   win$perror
  206. #endif /* OLD_TWG */
  207.  
  208. #else /* Not WINTCP */
  209.  
  210. #ifndef I386IX
  211. #include <errno.h>                      /* Already included above */
  212. #endif /* I386IX */
  213.  
  214. #include <signal.h>                     /* Everybody needs this */
  215.  
  216. #ifdef ZILOG                            /* Zilog has different name for this */
  217. #include <setret.h>
  218. #else
  219. #include <setjmp.h>
  220. #endif /* ZILOG */
  221.  
  222. #endif /* WINTCP */
  223.  
  224. #ifdef datageneral                      /* Data General AOS/VS */
  225. #include <:usr:include:vs_tcp_errno.h>
  226. #include <:usr:include:sys:vs_tcp_types.h>
  227. #ifdef SELECT
  228. /*
  229.   NOTE: This can be compiled and linked OK with SELECT defined
  230.   but it doesn't work at all.  Anybody who cares and knows how
  231.   to fix it, feel free.
  232. */
  233. #include <:usr:include:sys:vs_tcp_time.h>
  234. #endif /* SELECT */
  235. #include <:usr:include:sys:socket.h>
  236. #include <:usr:include:netinet:in.h>
  237. #include <:usr:include:netdb.h>
  238. #endif /* datageneral */
  239.  
  240. #ifndef socket_errno
  241. #define socket_errno errno
  242. #endif /* socket_errno */
  243.  
  244. #ifdef TNCODE
  245. extern int tn_deb;
  246. #endif /* TNCODE */
  247.  
  248. int tcp_rdns =                          /* Reverse DNS lookup */
  249. #ifdef DEC_TCPIP_OLD
  250.     SET_OFF                             /* Doesn't seem to work in UCX */
  251. #else
  252.      SET_AUTO
  253. #endif /* DEC_TCPIP */
  254.       ;
  255. #ifdef CK_DNS_SRV
  256. int tcp_dns_srv = SET_OFF;
  257. #endif /* CK_DNS_SRV */
  258.  
  259. #ifdef RLOGCODE
  260. #ifdef TCPIPLIB
  261. _PROTOTYP( static VOID rlog_oob, (CHAR *, int) );
  262. #else
  263. _PROTOTYP( static SIGTYP rlogoobh, ( int ) );
  264. #endif /* TCPIPLIB */
  265. _PROTOTYP( static int rlog_ini, (CHAR *, int,
  266.                                  struct sockaddr_in *,
  267.                                  struct sockaddr_in *) );
  268. int rlog_mode = RL_COOKED;
  269. int rlog_stopped = 0;
  270. #endif /* RLOGCODE */
  271.  
  272. #ifndef NOICP
  273. extern int doconx;                      /* CONNECT-class command active */
  274. #endif /* NOICP */
  275.  
  276. #ifdef IBMX25
  277. /* This variable should probably be generalised for true client/server
  278.  * support - ie: the fd of the listening server, accepted calls should
  279.  * be forked or at least handled via a second fd (for IBM's X.25 -
  280.  * ttyfd always holds the active fd - ie the server becomes inactive
  281.  * as long as a client is connected, and becomes active again when the
  282.  * connection is closed)
  283.  */
  284. int x25serverfd = 0;            /* extern in ckcnet.h */
  285. int x25seqno = 0;               /* Connection sequence number */
  286. int x25lastmsg = -1;            /* A cheapskate's state table */
  287.  
  288. #define X25_CLOSED      0       /* Default state: no connection, no STREAM */
  289. #define X25_SETUP       1       /* X.25 has been set up (no connection) */
  290. #define X25_CONNECTED   2       /* X.25 connection has been established */
  291. int x25_state = X25_CLOSED;     /* Default state */
  292. #endif /* IBMX25 */
  293.  
  294. #ifndef DEBUG
  295. #define deblog 0
  296. #endif /* DEBUG */
  297.  
  298. #ifdef CK_NAWS                          /* Negotiate About Window Size */
  299. #ifdef RLOGCODE
  300. _PROTOTYP( int rlog_naws, (void) );
  301. #endif /* RLOGCODE */
  302. #endif /* CK_NAWS */
  303.  
  304. #ifdef OS2                              /* For terminal type name string */
  305. #include "ckuusr.h"
  306. #ifndef NT
  307. #include <os2.h>
  308. #undef COMMENT
  309. #endif /* NT */
  310. #include "ckocon.h"
  311. extern int tt_type, max_tt;
  312. extern struct tt_info_rec tt_info[];
  313. extern char ttname[];
  314. #else
  315. #ifdef CK_AUTHENTICATION
  316. #include "ckuusr.h"
  317. #endif /* CK_AUTHENTICATION */
  318. #endif /* OS2 */
  319.  
  320. #ifdef CK_AUTHENTICATION
  321. #include "ckuath.h"
  322. #endif /* CK_AUTHENTICATION */
  323.  
  324. #include "ckcsig.h"
  325.  
  326. #ifndef OS2                             /* For timeout longjumps */
  327. static ckjmpbuf njbuf;
  328. #endif /* OS2 */
  329.  
  330. #define NAMECPYL 100                    /* Local copy of hostname */
  331. char namecopy[NAMECPYL];                /* Referenced by ckctel.c */
  332.  
  333. char ipaddr[20] = { '\0' };             /* Global copy of IP address */
  334. char myipaddr[20] = { '\0' };           /* Global copy of my IP address */
  335. unsigned long myxipaddr = 0L;           /* Ditto as a number */
  336. #endif /* NETCONN */
  337.  
  338. char *tcp_address = NULL;               /* Preferred IP Address */
  339. extern char uidbuf[];                   /* User ID buffer */
  340. extern char pwbuf[];                    /* Password buffer */
  341.  
  342. #ifdef OS2
  343. extern int tt_rows[], tt_cols[];
  344. extern int tt_status;
  345. #else /* OS2 */
  346. extern int tt_rows, tt_cols;            /* Everybody has this */
  347. #endif /* OS2 */
  348.  
  349. extern int cmd_cols, cmd_rows;
  350.  
  351. #ifdef STREAMING                        /* Use blocking writes for streaming */
  352. extern int streaming;
  353. #endif /* STREAMING */
  354.  
  355. #ifdef NT
  356. extern int WSASafeToCancel;
  357. int win95selectbug = 0;                 /* For TCP/IP stacks whose select() */
  358. /* always fails on write requests such as Cisco and Quarterdeck */
  359. #define stricmp _stricmp
  360. #endif /* NT */
  361.  
  362. #ifndef NOTCPOPTS
  363.  
  364. /* Skip all this if NOTCPOPTS specified. */
  365.  
  366. #ifdef SOL_SOCKET
  367.  
  368. #ifdef TCP_NODELAY
  369. int tcp_nodelay = 0;                    /* Nagle algorithm TCP_NODELAY */
  370. #endif /* TCP_NODELAY */
  371.  
  372. #ifdef SO_DONTROUTE
  373. int tcp_dontroute = 0;
  374. #endif /* SO_DONTROUTE */
  375.  
  376. #ifdef SO_LINGER
  377. int tcp_linger  = 0;                    /* SO_LINGER */
  378. int tcp_linger_tmo = 0;                 /* SO_LINGER timeout */
  379. #endif /* SO_LINGER */
  380.  
  381. #ifdef HPUX                             /* But the data structures */
  382. #ifndef HPUX8                           /* needed for linger are not */
  383. #ifndef HPUX9                           /* defined in HP-UX versions */
  384. #ifndef HPUX10                          /* prior to 8.00. */
  385. #ifdef SO_LINGER
  386. #undef SO_LINGER
  387. #endif /* SO_LINGER */
  388. #endif /* HPUX10 */
  389. #endif /* HPUX9 */
  390. #endif /* HPUX8 */
  391. #endif /* HPUX */
  392.  
  393. #ifndef SO_OOBINLINE                    /* Hopefully only HP-UX 7.0 */
  394. #define SO_OOBINLINE 0x0100
  395. #endif /* SO_OOBINLINE */
  396.  
  397. #ifndef TCPSNDBUFSIZ
  398. #ifdef VMS
  399. #ifdef __alpha
  400. #define TCPSNDBUFSIZ 16384
  401. #endif /* __alpha */
  402. #endif /* VMS */
  403. #endif /* TCPSNDBUFSIZ */
  404.  
  405. #ifndef TCPSNDBUFSIZ
  406. #define TCPSNDBUFSIZ -1
  407. #endif /* TCPSNDBUFSIZ */
  408.  
  409. #ifdef SO_SNDBUF
  410. int tcp_sendbuf = TCPSNDBUFSIZ;
  411. #endif /* SO_SNDBUF */
  412.  
  413. #ifdef SO_RCVBUF
  414. int tcp_recvbuf = -1;
  415. #endif /* SO_RCVBUF */
  416.  
  417. #ifdef SO_KEEPALIVE
  418. int tcp_keepalive = 1;
  419. #endif /* SO_KEEPALIVE */
  420.  
  421. #endif /* SOL_SOCKET */
  422. #endif /* NOTCPOPTS */
  423.  
  424. #ifndef NETCONN
  425. /*
  426.   Network support not defined.
  427.   Dummy functions here in case #ifdef's forgotten elsewhere.
  428. */
  429. int                                     /* Open network connection */
  430. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  431.     return(-1);
  432. }
  433. int                                     /* Close network connection */
  434. netclos() {
  435.     return(-1);
  436. }
  437. int                                     /* Check network input buffer */
  438. nettchk() {
  439.     return(-1);
  440. }
  441. int                                     /* Flush network input buffer */
  442. netflui() {
  443.     return(-1);
  444. }
  445. int                                     /* Send network BREAK */
  446. netbreak() {
  447.     return(-1);
  448. }
  449. int                                     /* Input character from network */
  450. netinc(timo) int timo; {
  451.     return(-1);
  452. }
  453. int                                     /* Output character to network */
  454. #ifdef CK_ANSIC
  455. nettoc(CHAR c)
  456. #else
  457. nettoc(c) CHAR c;
  458. #endif /* CK_ANSIC */
  459. /* nettoc */ {
  460.     return(-1);
  461. }
  462. int
  463. nettol(s,n) CHAR *s; int n; {
  464.     return(-1);
  465. }
  466.  
  467. #else /* NETCONN is defined (much of this module...) */
  468.  
  469. #ifdef NETLEBUF
  470. VOID
  471. le_init() {                             /* LocalEchoInit() */
  472.     int i;
  473.     for (i = 0; i < LEBUFSIZ; i++)
  474.       le_buf[i] = '\0';
  475.     le_start = 0;
  476.     le_end = 0;
  477.     le_data = 0;
  478.     tt_push_inited = 1;
  479. }
  480.  
  481. VOID
  482. le_clean() {                            /* LocalEchoCleanup() */
  483.     le_init();
  484.     return;
  485. }
  486.  
  487. int
  488. le_inbuf() {
  489.     int rc = 0;
  490.     if (le_start != le_end) {
  491.         rc = (le_end -
  492.               le_start +
  493.               LEBUFSIZ) % LEBUFSIZ;
  494.     }
  495.     return(rc);
  496. }
  497.  
  498. int
  499. #ifdef CK_ANSIC
  500. le_putchar(CHAR ch)
  501. #else
  502. le_putchar(ch) CHAR ch;
  503. #endif /* CK_ANSIC */
  504. /* le_putchar */ {
  505.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  506.         debug(F110,"le_putchar","buffer is full",0);
  507.         return(-1);
  508.     }
  509.     le_buf[le_end++] = ch;
  510.     if (le_end == LEBUFSIZ)
  511.       le_end = 0;
  512.     le_data = 1;
  513.     return(0);
  514. }
  515.  
  516. int
  517. #ifdef CK_ANSIC
  518. le_puts(CHAR * s, int n)
  519. #else
  520. le_puts(s,n) CHAR * s; int n;
  521. #endif /* CK_ANSIC */
  522. /* le_puts */ {
  523.     int rc = 0;
  524.     int i = 0;
  525.     CHAR * p = (CHAR *)"le_puts";
  526.     hexdump(p,s,n);
  527.     for (i = 0; i < n; i++)
  528.       rc = le_putchar((char)s[i]);
  529.     debug(F101,"le_puts","",rc);
  530.     return(rc);
  531. }
  532.  
  533. int
  534. #ifdef CK_ANSIC
  535. le_putstr(CHAR * s)
  536. #else
  537. le_putstr(s) CHAR * s;
  538. #endif /* CK_ANSIC */
  539. /* le_puts */ {
  540.     CHAR * p;
  541.     int rc = 0;
  542.     p = (CHAR *)"le_putstr";
  543.     hexdump(p,s,(int)strlen((char *)s));
  544.     for (p = s; *p && !rc; p++)
  545.       rc = le_putchar(*p);
  546.     return(rc);
  547. }
  548.  
  549. int
  550. #ifdef CK_ANSIC
  551. le_getchar(CHAR * pch)
  552. #else /* CK_ANSIC */
  553. le_getchar(pch) CHAR * pch;
  554. #endif /* CK_ANSIC */
  555. /* le_gatchar */ {
  556.     int rc = 0;
  557.     if (le_start != le_end) {
  558.         *pch = le_buf[le_start];
  559.         le_buf[le_start] = 0;
  560.         le_start++;
  561.  
  562.         if (le_start == LEBUFSIZ)
  563.           le_start = 0;
  564.  
  565.         if (le_start == le_end) {
  566.             le_data = 0;
  567.         }
  568.         rc++;
  569.     } else {
  570.         *pch = 0;
  571.     }
  572.     return(rc);
  573. }
  574. #endif /* NETLEBUF */
  575.  
  576. #ifdef VMS
  577. /*
  578.   In edit 190, we moved tn_ini() to be called from within netopen().
  579.   But tn_ini() calls ttol(), and ttol() checks to see if it's a net
  580.   connection, but the flag for that isn't set until after netopen()
  581.   is finished.  Since, in this module, we are always doing network
  582.   output anyway, we just call nettol() directly, instead of going thru
  583.   ttol().  Only needed for VMS, since UNIX, AOS/VS, and VOS can handle
  584.   net connections just like regular connections in ttol(), and OS/2
  585.   has a special routine for this.
  586. */
  587. #define ttol nettol
  588. #endif /* VMS */
  589.  
  590. int tcpsrfd = -1;
  591.  
  592. #ifdef CK_KERBEROS
  593.  
  594. char * krb5_d_principal = NULL;         /* Default principal */
  595. char * krb5_d_instance = NULL;          /* Default instance */
  596. char * krb5_d_realm = NULL;             /* Default realm */
  597. char * krb5_d_cc = NULL;                /* Default credentials cache */
  598. char * krb5_d_srv   = NULL;             /* Default Service */
  599. int    krb5_d_lifetime = 600;           /* Default lifetime (10 hours) */
  600. int    krb5_d_forwardable = 0;          /* creds not forwardable */
  601. int    krb5_d_proxiable = 0;            /* creds not proxiable */
  602. int    krb5_d_renewable = 0;            /* creds not renewable (0 min) */
  603. int    krb5_autoget = 1;                /* Autoget TGTs */
  604. int    krb5_autodel = 0;                /* Auto delete TGTs */
  605. int    krb5_d_getk4 = 0;                /* K5 Kinit gets K4 TGTs */
  606. int    krb5_checkaddrs = 1;             /* Check TGT Addrs */
  607.  
  608. int    krb5_errno = 0;                  /* Last K5 errno */
  609. char * krb5_errmsg = NULL;              /* Last K5 errmsg */
  610.  
  611. char * krb4_d_principal = NULL;         /* Default principal */
  612. char * krb4_d_realm = NULL;             /* Default realm */
  613. char * krb4_d_srv   = NULL;             /* Default Service */
  614. int    krb4_d_lifetime = 600;           /* Default lifetime (10 hours) */
  615. int    krb4_d_preauth = 1;              /* Use preauth requests */
  616. char * krb4_d_instance = NULL;          /* Default instance */
  617. int    krb4_autoget = 1;                /* Autoget TGTs */
  618. int    krb4_autodel = 0;                /* Auto delete TGTs */
  619. int    krb4_checkaddrs = 1;             /* Check TGT Addrs */
  620.  
  621. int    krb4_errno = 0;                  /* Last K4 errno */
  622. char * krb4_errmsg = NULL;              /* Last K4 errmsg */
  623.  
  624. struct krb_op_data krb_op = {           /* Operational data structure */
  625.     0, NULL                             /* (version, cachefile) */
  626. };
  627.  
  628. struct krb4_init_data krb4_init = {     /* Kerberos 4 INIT data structure */
  629.     0, NULL, NULL, NULL, NULL
  630. };
  631.  
  632. struct krb5_init_data krb5_init = {     /* Kerberos 5 INIT data structure */
  633.     0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0,
  634.     { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  635.       NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
  636. };
  637.  
  638. struct krb5_list_cred_data krb5_lc = {  /* List Credentials data structure */
  639.     0, 0, 0
  640. };
  641.  
  642. int krb_action = -1;                    /* Kerberos action to perform */
  643.  
  644. #ifndef CK_AUTHENTICATION
  645. char *
  646. ck_krb4_getrealm() {
  647.     return("");
  648. }
  649. char *
  650. ck_krb5_getrealm(cc) char * cc; {
  651.     return("");
  652. }
  653. char *
  654. ck_krb4_getprincipal() {
  655.     return("");
  656. }
  657. char *
  658. ck_krb5_getprincipal(cc) char * cc; {
  659.     return("");
  660. }
  661. #endif /* CK_AUTHENTICATION */
  662.  
  663. /*  I N I _ K E R B  --  Initialize Kerberos data  */
  664.  
  665. VOID
  666. ini_kerb() {
  667.     int i;
  668.  
  669.     krb_action = -1;                    /* No action specified */
  670.  
  671.     krb_op.version = 0;                 /* Kerberos version (none) */
  672.     krb_op.cache = NULL;                /* Cache file (none) */
  673.  
  674. /* Kerberos 5 */
  675.  
  676.     krb5_init.forwardable = krb5_d_forwardable; /* Init switch values... */
  677.     krb5_init.proxiable   = krb5_d_proxiable;
  678.     krb5_init.lifetime    = krb5_d_lifetime;
  679.     krb5_init.renew       = 0;
  680.     krb5_init.renewable   = krb5_d_renewable;
  681.     krb5_init.validate    = 0;
  682.     if (krb5_init.postdate) {
  683.         free(krb5_init.postdate);
  684.         krb5_init.postdate = NULL;
  685.     }
  686.     if (krb5_init.service) {
  687.         free(krb5_init.service);
  688.         krb5_init.service = NULL;
  689.     }
  690.     if (!krb5_d_cc || !krb5_d_cc[0]) {  /* Set default cache */
  691.         char * p;
  692.         p = ck_krb5_get_cc_name();
  693.         makestr(&krb5_d_cc,p);
  694.     }
  695.     if (!krb5_d_realm || !krb5_d_realm[0]) { /* Set default realm */
  696.         char * p;
  697.         p = ck_krb5_getrealm(krb5_d_cc);
  698.         makestr(&krb5_d_realm,p);
  699.     }
  700.     makestr(&krb5_init.instance,krb5_d_instance);
  701.     makestr(&krb5_init.realm,krb5_d_realm); /* Set realm from default */
  702.     if (krb5_init.password) {
  703.         memset(krb5_init.password,0xFF,strlen(krb5_init.password));
  704.         free(krb5_init.password);
  705.         krb5_init.password = NULL;
  706.     }
  707.     if (!krb5_d_principal) {            /* Default principal */
  708.         /* a Null principal indicates the user should be prompted */
  709.         char * p = ck_krb5_getprincipal(krb5_d_cc);
  710.         if (!p || !(*p))
  711.           p = (char *)uidbuf;           /* Principal = user */
  712.         makestr(&(krb5_d_principal),p);
  713.     }
  714.     makestr(&(krb5_init.principal),krb5_d_principal);
  715.     for (i = 0; i <= KRB5_NUM_OF_ADDRS; i++) {
  716.         if (krb5_init.addrs[i])
  717.           free(krb5_init.addrs[i]);
  718.         krb5_init.addrs[i] = NULL;
  719.     }
  720.  
  721. /* Kerberos 4 */
  722.  
  723.     krb4_init.lifetime = krb4_d_lifetime;
  724.     krb4_init.preauth  = krb4_d_preauth;
  725.     makestr(&krb4_init.instance,krb4_d_instance);
  726.     if (!krb4_d_realm || !krb4_d_realm[0]) {/* Set default realm */
  727.         char * p;
  728.         p = ck_krb4_getrealm();
  729.         makestr(&krb4_d_realm,p);
  730.     }
  731.     makestr(&krb4_init.realm,krb4_d_realm);
  732.     if (krb4_init.password) {
  733.         memset(krb4_init.password,0xFF,strlen(krb4_init.password));
  734.         free(krb4_init.password);
  735.         krb4_init.password = NULL;
  736.     }
  737.     if (!krb4_d_principal) {            /* Default principal */
  738.         /* a Null principal indicates the user should be prompted */
  739.         char * p = ck_krb4_getprincipal();
  740.         if (!p || !(*p))
  741.           p = (char *)uidbuf;           /* Principal = user */
  742.         makestr(&(krb4_d_principal),p);
  743.     }
  744.     makestr(&(krb4_init.principal),krb4_d_principal);
  745. }
  746.  
  747. /*  D O A U T H  --  AUTHENTICATE action routine  */
  748.  
  749. int
  750. doauth(cx) int cx; {                    /* AUTHENTICATE action routine */
  751.     int rc = 0;                         /* Return code */
  752.  
  753. #ifdef CK_AUTHENTICATION
  754. #ifdef OS2
  755.     if (!ck_auth_loaddll())             /* Load Kerberos DLL */
  756.       return(rc);
  757. #endif /* OS2 */
  758.     if (krb_op.version == 4) {          /* Version = 4 */
  759. #ifdef COMMENT
  760.         sho_auth(AUTHTYPE_KERBEROS_V4);
  761. #endif /* COMMENT */
  762.         if (!ck_krb4_is_installed()) {
  763.             printf("?Kerberos 4 is not installed\n");
  764.             return(0);
  765.         }
  766.         switch (krb_action) {           /* Perform V4 functions */
  767.           case KRB_A_IN:                /* INIT */
  768.             rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
  769.             break;
  770.           case KRB_A_DE:                /* DESTROY */
  771.             rc |= !(ck_krb4_destroy(&krb_op) < 0);
  772.             break;
  773.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  774.             rc |= !(ck_krb4_list_creds(&krb_op) < 0);
  775.             break;
  776.         }
  777.     }
  778.     if (krb_op.version == 5) {          /* V5 functions */
  779. #ifdef COMMENT
  780.         sho_auth(AUTHTYPE_KERBEROS_V5);
  781. #endif /* COMMENT */
  782.         if (!ck_krb5_is_installed()) {
  783.             printf("?Kerberos 5 is not installed\n");
  784.             return(0);
  785.         }
  786.         switch (krb_action) {
  787.           case KRB_A_IN:                /* INIT */
  788.             rc |= !(ck_krb5_initTGT(&krb_op,&krb5_init) < 0);
  789.             if ( krb5_init.getk4 )
  790.                 rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
  791.             break;
  792.           case KRB_A_DE:                /* DESTROY */
  793.             rc |= !(ck_krb5_destroy(&krb_op) < 0);
  794.             break;
  795.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  796.             if (krb_op.version == 0)
  797.               printf("\n");
  798.             rc |= !(ck_krb5_list_creds(&krb_op,&krb5_lc) < 0);
  799.             break;
  800.         }
  801.     }
  802. #else
  803. #ifndef NOICP
  804. #ifndef NOSHOW
  805.     rc = sho_auth(0);                   /* Show all */
  806. #endif /* NOSHOW */
  807. #endif /* NOICP */
  808. #endif /* CK_AUTHENTICATION */
  809.     return(rc);
  810. }
  811. #endif /* CK_KERBEROS */
  812.  
  813. #ifdef TCPSOCKET
  814. #ifndef OS2
  815. #ifndef NOLISTEN                        /* For incoming connections */
  816.  
  817. #ifndef INADDR_ANY
  818. #define INADDR_ANY 0
  819. #endif /* INADDR_ANY */
  820.  
  821. _PROTOTYP( int ttbufr, ( VOID ) );
  822. _PROTOTYP( int tcpsrv_open, (char *, int *, int, int ) );
  823.  
  824. static unsigned short tcpsrv_port = 0;
  825.  
  826. #endif /* NOLISTEN */
  827. #endif /* OS2 */
  828.  
  829. static char svcbuf[80];                 /* TCP service string */
  830. static int svcnum = 0;                  /* TCP port number */
  831.  
  832. #endif /* TCPSOCKET */
  833.  
  834. /*
  835.   TCPIPLIB means use separate socket calls for i/o, while on UNIX the
  836.   normal file system calls are used for TCP/IP sockets too.
  837.   Means "DEC_TCPIP or MULTINET or WINTCP or OS2 or BEBOX" (see ckcnet.h),
  838. */
  839.  
  840. #ifdef TCPIPLIB
  841.  
  842. /* For buffered network reads... */
  843. /*
  844.   If the buffering code is written right, it shouldn't matter
  845.   how long this buffer is.
  846. */
  847. #ifdef OS2
  848. #ifdef NT
  849. #define TTIBUFL 64240                   /* 44 * 1460 (MSS) */
  850. #else
  851. #define TTIBUFL 32120                   /* 22 * 1460 (MSS) */
  852. #endif /* NT */
  853. #else /* OS2 */
  854. #define TTIBUFL 8191                    /* Let's use 8K. */
  855. #endif /* OS2 */
  856.  
  857. CHAR ttibuf[TTIBUFL+1];
  858.  
  859. /*
  860.   select() is used in preference to alarm()/signal(), but different systems
  861.   use different forms of select()...
  862. */
  863. #ifndef NOSELECT         /* Option to override BSDSELECT */
  864. #ifdef BELLV10
  865. /*
  866.   Note: Although BELLV10 does have TCP/IP support, and does use the unique
  867.   form of select() that is evident in this module (and in ckutio.c), it does
  868.   not have a sockets library and so we can't build Kermit TCP/IP support for
  869.   it.  For this, somebody would have to write TCP/IP streams code.
  870. */
  871. #define BELLSELECT
  872. #ifndef FD_SETSIZE
  873. #define FD_SETSIZE 128
  874. #endif /* FD_SETSIZE */
  875. #else
  876. #ifdef WINTCP                           /* VMS with Wollongong WIN/TCP */
  877. #ifndef OLD_TWG                         /* TWG 3.2 has only select(read) */
  878. #define BSDSELECT
  879. #endif /* OLD_TWG */
  880. #else
  881. #ifdef CMU_TCPIP                        /* LIBCMU can do select */
  882. #define BSDSELECT
  883. #else
  884. #ifdef DEC_TCPIP
  885. #define BSDSELECT
  886. #else
  887. #ifdef OS2                              /* OS/2 with TCP/IP */
  888. #ifdef NT
  889. #define BSDSELECT
  890. #else /* NT */
  891. #define IBMSELECT
  892. #endif /* NT */
  893. #endif /* OS2 */
  894. #endif /* DEC_TCPIP */
  895. #endif /* CMU_TCPIP */
  896. #endif /* WINTCP */
  897. #endif /* BELLV10 */
  898. #endif /* NOSELECT */
  899. /*
  900.   Others (TGV, TCPware, ...) use alarm()/signal().  The BSDSELECT case does not
  901.   compile at all; the IBMSELECT case compiles and links but crashes at runtime.
  902.   NOTE: If any of these can be converted to select(), they should be for two
  903.   reasons: (1) It's a lot faster; (2) certain sockets libraries do not like
  904.   their socket_read() calls to be interrupted; subsequent socket_read()'s tend
  905.   to fail with EBUSY.  This happened in the UCX case before it was converted
  906.   to use select().
  907. */
  908. #ifndef OS2
  909. #ifndef VMS
  910. static                                  /* These are used in CKVTIO.C */
  911. #endif /* VMS */                        /* And in CKONET.C            */
  912. #endif /* OS2 */
  913. int
  914.   ttibp = 0,
  915.   ttibn = 0;
  916. /*
  917.   Read bytes from network into internal buffer ttibuf[].
  918.   To be called when input buffer is empty, i.e. when ttibn == 0.
  919.  
  920.   Other network reading routines, like ttinc, ttinl, ttxin, should check the
  921.   internal buffer first, and call this routine for a refill if necessary.
  922.  
  923.   Returns -1 on error, 0 if nothing happens.  When data is read successfully,
  924.   returns number of bytes read, and sets global ttibn to that number and
  925.   ttibp (the buffer pointer) to zero.
  926. */
  927. _PROTOTYP( int ttbufr, ( VOID ) );
  928. int
  929. ttbufr() {                              /* TT Buffer Read */
  930.     int count;
  931.  
  932.     if (ttnet != NET_TCPB)              /* First make sure current net is */
  933.       return(-1);                       /* TCP/IP; if not, do nothing. */
  934.  
  935.     if (ttibn > 0)                      /* Our internal buffer is not empty, */
  936.       return(ttibn);                    /* so keep using it. */
  937.  
  938.     ttibp = 0;                          /* Else reset pointer to beginning */
  939.  
  940.     if (ttyfd == -1)                    /* No connection, error */
  941.         return(-2);
  942.  
  943. #ifdef WINTCP
  944.     count = 512;                        /* This works for WIN/TCP */
  945. #else
  946. #ifdef DEC_TCPIP
  947.     count = 512;                        /* UCX */
  948. #else
  949. #ifdef OS2
  950.     count = TTIBUFL;
  951. #else                                   /* Multinet, etc. */
  952.     count = ttchk();                    /* Check network input buffer, */
  953.     if (ttibn > 0) {                    /* which can put a char there! */
  954.         debug(F111,"ttbufr","ttchk() returns",count);
  955.         return(ttibn);
  956.     }
  957.     if (count < 0)                      /* Read error - connection closed */
  958.       return(-2);
  959.     else if (count > TTIBUFL)           /* Too many to read */
  960.       count = TTIBUFL;
  961.     else if (count == 0)                /* None, so force blocking read */
  962.       count = 1;
  963. #endif /* OS2 */
  964. #endif /* DEC_TCPIP */
  965. #endif /* WINTCP */
  966.     debug(F101,"ttbufr count 1","",count);
  967.  
  968. #ifdef CK_SSL
  969.     if (ssl_active_flag || tls_active_flag) {
  970.         int error;
  971.         if (ssl_active_flag)
  972.           count = SSL_read(ssl_con, ttibuf, count);
  973.         else
  974.           count = SSL_read(tls_con, ttibuf, count);
  975.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,count)) {
  976.           case SSL_ERROR_NONE:
  977.             debug(F111,"ttbufr SSL_ERROR_NONE","count",count);
  978.             if (count > 0) {
  979.                 ttibp = 0;              /* Reset buffer pointer. */
  980.                 ttibn = count;
  981.                 return(ttibn);          /* Return buffer count. */
  982.             } else if (count < 0) {
  983.                 return(-1);
  984.             } else {
  985.                 netclos();
  986.                 return(-2);
  987.             }
  988.           case SSL_ERROR_WANT_WRITE:
  989.             debug(F100,"ttbufr SSL_ERROR_WANT_WRITE","",0);
  990.             return(-1);
  991.           case SSL_ERROR_WANT_READ:
  992.             debug(F100,"ttbufr SSL_ERROR_WANT_READ","",0);
  993.             return(-1);
  994.           case SSL_ERROR_SYSCALL:
  995. #ifdef NT
  996.             debug(F111,"ttbufr SSL_ERROR_SYSCALL",
  997.                   "GetLastError()",GetLastError());
  998. #endif /* NT */
  999.             netclos();
  1000.             return(-2);
  1001.           case SSL_ERROR_WANT_X509_LOOKUP:
  1002.             debug(F100,"ttbufr SSL_ERROR_WANT_X509_LOOKUP","",0);
  1003.             netclos();
  1004.             return(-2);
  1005.           case SSL_ERROR_SSL:
  1006.             debug(F100,"ttbufr SSL_ERROR_SSL","",0);
  1007.             netclos();
  1008.             return(-2);
  1009.           case SSL_ERROR_ZERO_RETURN:
  1010.             debug(F100,"ttbufr SSL_ERROR_ZERO_RETURN","",0);
  1011.             netclos();
  1012.             return(-2);
  1013.           default:
  1014.             debug(F100,"ttbufr SSL_ERROR_?????","",0);
  1015.             netclos();
  1016.             return(-2);
  1017.         }
  1018.     }
  1019. #endif /* CK_SSL */
  1020.  
  1021. #ifdef COMMENT
  1022. /*
  1023.  This is for nonblocking reads, which we don't do any more.  This code didn't
  1024.  work anyway, in the sense that a broken connection was never sensed.
  1025. */
  1026.     if ((count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count)) < 1) {
  1027.         if (count == -1 && socket_errno == EWOULDBLOCK) {
  1028.             debug(F100,"ttbufr finds nothing","",0);
  1029.             return(0);
  1030.         } else {
  1031.             debug(F101,"ttbufr socket_read error","",socket_errno);
  1032.             return(-1);
  1033.         }
  1034.  
  1035.     } else if (count == 0) {
  1036.         debug(F100,"ttbufr socket eof","",0);
  1037.         return(-1);
  1038.     }
  1039. #else /* COMMENT */
  1040.  
  1041. /* This is for blocking reads */
  1042.  
  1043. #ifndef VMS
  1044. #ifdef SO_OOBINLINE
  1045.     {
  1046.         int outofband = 0;
  1047. #ifdef BELLSELECT
  1048.         if (select(128, NULL, NULL, efds, 0) > 0 && FD_ISSET(ttyfd, efds))
  1049.           outofband = 1;
  1050. #else
  1051. #ifdef BSDSELECT
  1052.         fd_set efds;
  1053.         struct timeval tv;
  1054.         FD_ZERO(&efds);
  1055.         FD_SET(ttyfd, &efds);
  1056.         tv.tv_sec  = tv.tv_usec = 0L;
  1057.         debug(F100,"Out-of-Band BSDSELECT","",0);
  1058. #ifdef NT
  1059.         WSASafeToCancel = 1;
  1060. #endif /* NT */
  1061.         if (select(FD_SETSIZE, NULL, NULL, &efds, &tv) > 0 &&
  1062.             FD_ISSET(ttyfd, &efds))
  1063.           outofband = 1;
  1064. #ifdef NT
  1065.         WSASafeToCancel = 0;
  1066. #endif /* NT */
  1067. #else /* !BSDSELECT */
  1068. #ifdef IBMSELECT
  1069. /* Was used by OS/2, currently not used, but might come in handy some day... */
  1070. /* ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set */
  1071. /* and timeval stuff since this is the only place where it is used. */
  1072.         int socket = ttyfd;
  1073.         debug(F100,"Out-of-Band IBMSELECT","",0);
  1074.         if ((select(&socket, 0, 0, 1, 0L) == 1) && (socket == ttyfd))
  1075.           outofband = 1;
  1076. #else /* !IBMSELECT */
  1077. /*
  1078.   If we can't use select(), then we use the regular alarm()/signal()
  1079.   timeout mechanism.
  1080. */
  1081.       debug(F101,"Out-of-Band data not supported","",0);
  1082.       outofband = 0;
  1083.  
  1084. #endif /* IBMSELECT */
  1085. #endif /* BSDSELECT */
  1086. #endif /* BELLSELECT */
  1087.       if (outofband) {
  1088.          /* Get the Urgent Data */
  1089.          /* if OOBINLINE is disabled this should be only a single byte      */
  1090.          /* MS Winsock has a bug in Windows 95.  Extra bytes are delivered  */
  1091.          /* That were never sent.                                           */
  1092. #ifdef OS2
  1093.           RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1094. #endif /* OS2 */
  1095.           count = socket_recv(ttyfd,&ttibuf[ttibp+ttibn],count,MSG_OOB);
  1096. #ifdef OS2
  1097.           ReleaseTCPIPMutex();
  1098. #endif /* OS2 */
  1099.           if (count <= 0) {
  1100.               int s_errno = socket_errno;
  1101.               debug(F101, "ttbufr socket_recv MSG_OOB","",count);
  1102.               debug(F101, "ttbufr socket_errno","",s_errno);
  1103. #ifdef OS2ONLY
  1104.               if (count < 0 && (s_errno == 0 || s_errno == 23)) {
  1105.                   /* These appear in OS/2 - don't know why   */
  1106.                   /* ignore it and read as normal data       */
  1107.                   /* and break, then we will attempt to read */
  1108.                   /* the port using normal read() techniques */
  1109.                   debug(F100,"ttbufr handing as in-band data","",0);
  1110.                   count = 1;
  1111.               } else {
  1112.                   netclos();                    /* *** *** */
  1113.                   return(-2);
  1114.               }
  1115. #else /* OS2ONLY */
  1116.               netclos();                        /* *** *** */
  1117.               return(-2);
  1118. #endif /* OS2ONLY */
  1119.           } else {                      /* we got out-of-band data */
  1120.               hexdump("ttbufr out-of-band chars",&ttibuf[ttibp+ttibn],count);
  1121. #ifdef BETATEST
  1122.               bleep(BP_NOTE);
  1123. #endif /* BETATEST */
  1124. #ifdef RLOGCODE                         /* blah */
  1125.               if (ttnproto == NP_RLOGIN  ||
  1126.                   ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  1127.                   ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  1128.                    ) {
  1129.                   /*
  1130.                     When urgent data is read with MSG_OOB and not OOBINLINE
  1131.                     then urgent data and normal data are not mixed.  So
  1132.                     treat the entire buffer as urgent data.
  1133.                   */
  1134.                   rlog_oob(&ttibuf[ttibp+ttibn], count);
  1135.                   return ttbufr();
  1136.               } else
  1137. #endif /* RLOGCODE */ /* blah */
  1138. #ifdef COMMENT
  1139.             /*
  1140.                I haven't written this yet, nor do I know what it should do
  1141.              */
  1142.                 if (ttnproto == NP_TELNET) {
  1143.                     tn_oob();
  1144.                     return 0;
  1145.                 } else
  1146. #endif /* COMMENT */
  1147.                   {
  1148.                    /* For any protocols we don't have a special out-of-band  */
  1149.                    /* handler for, just put the bytes in the normal buffer   */
  1150.                    /* and return                                             */
  1151.  
  1152. #ifdef OS2
  1153.                       RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1154. #endif /* OS2 */
  1155.                       ttibp += 0;       /* Reset buffer pointer. */
  1156.                       ttibn += count;
  1157. #ifdef OS2
  1158.                       ReleaseTCPIPMutex();
  1159. #endif /* OS2 */
  1160. #ifdef DEBUG
  1161.                       /* Got some bytes. */
  1162.                       debug(F101,"ttbufr count 2","",count);
  1163.                       if (count > 0)
  1164.                         ttibuf[ttibp+ttibn] = '\0';
  1165.                       debug(F111,"ttbufr ttibuf",ttibuf,ttibp);
  1166. #endif /* DEBUG */
  1167.                       return(ttibn);    /* Return buffer count. */
  1168.                   }
  1169.           }
  1170.       }
  1171.     }
  1172. #endif /* SO_OOBINLINE */
  1173. #endif /* VMS */
  1174.  
  1175. #ifdef OS2
  1176.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1177. #endif /* OS2 */
  1178.     count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count);
  1179. #ifdef OS2
  1180.     ReleaseTCPIPMutex();
  1181. #endif /* OS2 */
  1182.     if (count <= 0) {
  1183.         int s_errno = socket_errno;
  1184.         debug(F101,"ttbufr socket_read","",count);
  1185.         debug(F101,"ttbufr socket_errno","",s_errno);
  1186. #ifdef OS2
  1187.         if (count == 0 || os2socketerror(s_errno) < 0) {
  1188.             netclos();
  1189.             return(-2);
  1190.         }
  1191.         return(-1);
  1192. #else /* OS2 */
  1193.         netclos();                      /* *** *** */
  1194.         return(-2);
  1195. #endif /* OS2 */
  1196.     }
  1197. #endif /* COMMENT */ /* (blocking vs nonblock reads...) */
  1198.     else {
  1199. #ifdef OS2
  1200.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1201. #endif /* OS2 */
  1202.         ttibp = 0;                      /* Reset buffer pointer. */
  1203.         ttibn += count;
  1204. #ifdef OS2
  1205.     ReleaseTCPIPMutex();
  1206. #endif /* OS2 */
  1207. #ifdef DEBUG
  1208.         debug(F101,"ttbufr count 2","",count); /* Got some bytes. */
  1209.         if (count > 0)
  1210.           ttibuf[ttibp+ttibn] = '\0';
  1211.         debug(F111,"ttbufr ttibuf",&ttibuf[ttibp],ttibn);
  1212. #endif /* DEBUG */
  1213.         return(ttibn);                  /* Return buffer count. */
  1214.     }
  1215. }
  1216. #endif /* TCPIPLIB */
  1217.  
  1218. #ifndef IBMSELECT
  1219. #ifndef BELLSELECT
  1220. #ifndef BSDSELECT               /* Non-TCPIPLIB case */
  1221. #ifdef SELECT
  1222. #define BSDSELECT
  1223. #endif /* SELECT */
  1224. #endif /* BSDSELECT */
  1225. #endif /* BELLSELECT */
  1226. #endif /* IBMSELECT */
  1227.  
  1228. #define TELNET_PORT 23          /* Should do lookup, but it won't change */
  1229. #define RLOGIN_PORT 513
  1230. #define KERMIT_PORT 1649
  1231. #define KLOGIN_PORT 543
  1232. #define EKLOGIN_PORT 2105
  1233.  
  1234. /* Type needed as 5th argument (length) to get/setsockopt() */
  1235.  
  1236. #ifndef SOCKOPT_T
  1237. #define SOCKOPT_T int
  1238. #ifdef AIX42
  1239. #undef SOCKOPT_T
  1240. #define SOCKOPT_T unsigned long
  1241. #else
  1242. #ifdef PTX
  1243. #undef SOCKOPT_T
  1244. #define SOCKOPT_T size_t
  1245. #else
  1246. #ifdef NT
  1247. #undef SOCKOPT_T
  1248. #define SOCKOPT_T int
  1249. #else /* NT */
  1250. #ifdef UNIXWARE
  1251. #undef SOCKOPT_T
  1252. #define SOCKOPT_T size_t
  1253. #else /* UNIXWARE */
  1254. #ifdef VMS
  1255. #ifdef DEC_TCPIP
  1256. #ifdef __DECC_VER
  1257. #undef SOCKOPT_T
  1258. #define SOCKOPT_T size_t
  1259. #endif /* __DECC_VER */
  1260. #endif /* DEC_TCPIP */
  1261. #endif /* VMS */
  1262. #endif /* UNIXWARE */
  1263. #endif /* NT */
  1264. #endif /* PTX */
  1265. #endif /* AIX42 */
  1266. #endif /* SOCKOPT_T */
  1267.  
  1268. /* Ditto for getsockname() */
  1269.  
  1270. #ifndef GSOCKNAME_T
  1271. #define GSOCKNAME_T int
  1272. #ifdef PTX
  1273. #undef GSOCKNAME_T
  1274. #define GSOCKNAME_T size_t
  1275. #else
  1276. #ifdef AIX42                            /* size_t in 4.2++, int in 4.1-- */
  1277. #undef GSOCKNAME_T
  1278. #define GSOCKNAME_T size_t
  1279. #else
  1280. #ifdef UNIXWARE
  1281. #undef GSOCKNAME_T
  1282. #define GSOCKNAME_T size_t
  1283. #else
  1284. #ifdef VMS
  1285. #ifdef DEC_TCPIP
  1286. #ifdef __DECC_VER
  1287. #undef GSOCKNAME_T
  1288. #define GSOCKNAME_T size_t
  1289. #endif /* __DECC_VER */
  1290. #endif /* DEC_TCPIP */
  1291. #endif /* VMS */
  1292. #endif /* UNIXWARE */
  1293. #endif /* AIX41 */
  1294. #endif /* PTX */
  1295. #endif /* GSOCKNAME_T */
  1296.  
  1297. #ifndef NOLOCAL
  1298. /*
  1299.   C-Kermit network open/close functions for BSD-sockets.
  1300.   Much of this code shared by SunLink X.25, which also uses the socket library.
  1301. */
  1302.  
  1303. /*  N E T O P N  --  Open a network connection.  */
  1304. /*
  1305.   Call with:
  1306.     name of host (or host:service),
  1307.     lcl - local-mode flag to be set if this function succeeds,
  1308.     network type - value defined in ckunet.h.
  1309. */
  1310. #ifdef TCPSOCKET
  1311. #ifdef EXCELAN
  1312. /*
  1313.   Most other BSD sockets implementations define these in header files
  1314.   and libraries.
  1315. */
  1316. struct servent {
  1317.     unsigned short s_port;
  1318. };
  1319.  
  1320. struct hostent {
  1321.     short h_addrtype;
  1322.     struct in_addr h_addr;
  1323.     int h_length;
  1324. };
  1325.  
  1326. struct servent *
  1327. getservbyname(service, connection) char *service,*connection; {
  1328.     static struct servent servrec;
  1329.     int port;
  1330.  
  1331.     port = 0;
  1332.     if (strcmp(service, "telnet") == 0) port = 23;
  1333.     else if (strcmp(service, "smtp") == 0) port = 25;
  1334.     else port = atoi(service);
  1335.  
  1336.     debug(F101,"getservbyname return port ","",port);
  1337.  
  1338.     if (port > 0) {
  1339.         servrec.s_port = htons(port);
  1340.         return(&servrec);
  1341.     }
  1342.     return((struct servent *) NULL);
  1343. }
  1344.  
  1345. struct hostent *
  1346. gethostbyname(hostname) char *hostname; {
  1347.     return((struct hostent *) NULL);
  1348. }
  1349.  
  1350. unsigned long
  1351. inet_addr(name) char *name; {
  1352.     unsigned long addr;
  1353.  
  1354.     addr = rhost(&name);
  1355.     debug(F111,"inet_addr ",name,(int)addr);
  1356.     return(addr);
  1357. }
  1358.  
  1359. char *
  1360. inet_ntoa(in) struct in_addr in; {
  1361.     static char name[80];
  1362.     sprintf(name, "%d.%d.%d.%d", in.s_net, in.s_host, in.s_lh, in.s_impno);
  1363.     return(name);
  1364. }
  1365. #else
  1366. #ifdef DEC_TCPIP                        /* UCX */
  1367.  
  1368. int ucx_port_bug = 0;                   /* Explained below */
  1369.  
  1370. #ifndef __DECC                          /* VAXC or GCC */
  1371.  
  1372. #define getservbyname my_getservbyname
  1373.  
  1374. #ifdef CK_ANSIC
  1375. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1376. extern void C$$TRANSLATE();
  1377. extern void C$$SOCK_TRANSLATE();
  1378. #else
  1379. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1380. extern VOID C$$TRANSLATE();
  1381. extern VOID C$$SOCK_TRANSLATE();
  1382. #endif /* CK_ANSIC */
  1383.  
  1384. struct servent *
  1385. my_getservbyname (service, proto) char *service, *proto; {
  1386.     static struct servent sent;
  1387.     struct iosb {
  1388.         union {
  1389.             unsigned long status;
  1390.             unsigned short st[2];
  1391.         } sb;
  1392.         unsigned long spare;
  1393.     } s;
  1394.     struct {
  1395.         struct iosb *s;
  1396.         char *serv;
  1397.         char *prot;
  1398.     } par;
  1399.     unsigned long e;
  1400.     char sbuf[30], pbuf[30];
  1401.     char *p;
  1402.  
  1403.     debug(F111,"UCX getservbyname",service,(int)C$$GA_UCX_GETSERVBYNAME);
  1404.  
  1405.     p = sbuf;
  1406.     ckstrncpy(p, service, 29);
  1407.     while (*p = toupper(*p), *p++) {}
  1408.     p = pbuf;
  1409.     ckstrncpy(p, proto, 29);
  1410.     while (*p = toupper(*p), *p++) {}
  1411.  
  1412.     par.s = &s;
  1413.  
  1414.     par.serv = "";
  1415.     par.prot = "";
  1416.     /* reset file pointer or something like that!?!? */
  1417.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1418.     par.serv = sbuf;
  1419.     par.prot = pbuf;            /* that is don't care */
  1420.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1421.     if ((long)e == -1L)
  1422.       return NULL;
  1423.     if ((e & 1) == 0L) {
  1424.         C$$TRANSLATE(e);
  1425.         return NULL;
  1426.     }
  1427.     if ((s.sb.st[0] & 1) == 0) {
  1428.         C$$SOCK_TRANSLATE(&s.sb.st[0]);
  1429.         return NULL;
  1430.     }
  1431. /*
  1432.   sent.s_port is supposed to be returned by UCX in network byte order.
  1433.   However, UCX 2.0 through 2.0C did not do this; 2.0D and later do it.
  1434.   But there is no way of knowing which UCX version, so we have a user-settable
  1435.   runtime variable.  Note: UCX 2.0 was only for the VAX.
  1436. */
  1437.     debug(F101,"UCX getservbyname port","",sent.s_port);
  1438.     debug(F101,"UCX getservbyname ntohs(port)","",ntohs(sent.s_port));
  1439.     if (ucx_port_bug) {
  1440.         sent.s_port = htons(sent.s_port);
  1441.         debug(F100,"UCX-PORT-BUG ON: swapping bytes","",0);
  1442.         debug(F101,"UCX swapped port","",sent.s_port);
  1443.         debug(F101,"UCX swapped ntohs(port)","",ntohs(sent.s_port));
  1444.     }
  1445.     return &sent;
  1446. }
  1447. #endif /* __DECC */
  1448. #endif /* DEC_TCPIP */
  1449. #endif /* EXCELAN */
  1450. #endif /* TCPSOCKET */
  1451.  
  1452. #ifndef NOTCPOPTS
  1453. #ifndef datageneral
  1454. int
  1455. ck_linger(onoff, timo) int onoff; int timo; {
  1456. /*
  1457.   The following, from William Bader, turns off the socket linger parameter,
  1458.   which makes a close() block until all data is sent.  "I don't think that
  1459.   disabling linger can ever cause kermit to lose data, but you telnet to a
  1460.   flaky server (or to our modem server when the modem is in use), disabling
  1461.   linger prevents kermit from hanging on the close if you try to exit."
  1462.  
  1463.   Modified by Jeff Altman to be generally useful.
  1464. */
  1465. #ifdef SOL_SOCKET
  1466. #ifdef SO_LINGER
  1467.     struct linger set_linger_opt;
  1468.     struct linger get_linger_opt;
  1469.     SOCKOPT_T x;
  1470.  
  1471.     if (ttyfd == -1 ||
  1472.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1473.         tcp_linger = onoff;
  1474.         tcp_linger_tmo = timo;
  1475.         return(1);
  1476.     }
  1477.     x = sizeof(get_linger_opt);
  1478.     if (getsockopt(ttyfd, SOL_SOCKET, SO_LINGER,
  1479.                     (char *)&get_linger_opt, &x)) {
  1480.         debug(F111,"TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1481.     } else if (x != sizeof(get_linger_opt)) {
  1482. #ifdef OS2
  1483.         struct _linger16 {
  1484.             short s_linger;
  1485.             short s_onoff;
  1486.         } get_linger_opt16, set_linger_opt16;
  1487.         if ( x == sizeof(get_linger_opt16) ) {
  1488.             debug(F111,"TCP setlinger warning: SO_LINGER","len is 16-bit",x);
  1489.             if (getsockopt(ttyfd,
  1490.                            SOL_SOCKET, SO_LINGER,
  1491.                            (char *)&get_linger_opt16, &x)
  1492.                 ) {
  1493.                 debug(F111,
  1494.                       "TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1495.             } else if (get_linger_opt16.s_onoff != onoff ||
  1496.                        get_linger_opt16.s_linger != timo)
  1497.             {
  1498.                 set_linger_opt16.s_onoff  = onoff;
  1499.                 set_linger_opt16.s_linger = timo;
  1500.                 if (setsockopt(ttyfd,
  1501.                                SOL_SOCKET,
  1502.                                SO_LINGER,
  1503.                                (char *)&set_linger_opt16,
  1504.                                sizeof(set_linger_opt16))
  1505.                     ) {
  1506.                     debug(F111,
  1507.                           "TCP ck_linger can't set SO_LINGER",
  1508.                           ck_errstr(),
  1509.                           errno
  1510.                           );
  1511.                     tcp_linger = get_linger_opt16.s_onoff;
  1512.                     tcp_linger_tmo = get_linger_opt16.s_linger;
  1513.                 } else {
  1514.                     debug(F101,
  1515.                           "TCP ck_linger new SO_LINGER","",
  1516.                           set_linger_opt16.s_onoff);
  1517.                     tcp_linger = set_linger_opt16.s_onoff;
  1518.                     tcp_linger_tmo = set_linger_opt16.s_linger;
  1519.                     return 1;
  1520.                 }
  1521.             } else {
  1522.                 debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1523.                        get_linger_opt16.s_onoff);
  1524.                 tcp_linger = get_linger_opt16.s_onoff;
  1525.                 tcp_linger_tmo = get_linger_opt16.s_linger;
  1526.                 return 1;
  1527.             }
  1528.             return(0);
  1529.         }
  1530. #endif /* OS2 */
  1531.         debug(F111,"TCP ck_linger error: SO_LINGER","len",x);
  1532.         debug(F111,"TCP ck_linger SO_LINGER",
  1533.               "expected len",sizeof(get_linger_opt));
  1534.         debug(F111,"TCP ck_linger SO_LINGER","linger_opt.l_onoff",
  1535.               get_linger_opt.l_onoff);
  1536.         debug(F111,"TCP linger SO_LINGER","linger_opt.l_linger",
  1537.                get_linger_opt.l_linger);
  1538.     } else if (get_linger_opt.l_onoff != onoff ||
  1539.                get_linger_opt.l_linger != timo) {
  1540.         set_linger_opt.l_onoff  = onoff;
  1541.         set_linger_opt.l_linger = timo;
  1542.         if (setsockopt(ttyfd,
  1543.                        SOL_SOCKET,
  1544.                        SO_LINGER,
  1545.                        (char *)&set_linger_opt,
  1546.                        sizeof(set_linger_opt))) {
  1547.             debug(F111,"TCP ck_linger can't set SO_LINGER",ck_errstr(),errno);
  1548.             tcp_linger = get_linger_opt.l_onoff;
  1549.             tcp_linger_tmo = get_linger_opt.l_linger;
  1550.          } else {
  1551.              debug(F101,
  1552.                    "TCP ck_linger new SO_LINGER",
  1553.                    "",
  1554.                    set_linger_opt.l_onoff
  1555.                    );
  1556.              tcp_linger = set_linger_opt.l_onoff;
  1557.              tcp_linger_tmo = set_linger_opt.l_linger;
  1558.              return 1;
  1559.          }
  1560.     } else {
  1561.         debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1562.               get_linger_opt.l_onoff);
  1563.         tcp_linger = get_linger_opt.l_onoff;
  1564.         tcp_linger_tmo = get_linger_opt.l_linger;
  1565.         return 1;
  1566.     }
  1567. #else
  1568.     debug(F100,"TCP ck_linger SO_LINGER not defined","",0);
  1569. #endif /* SO_LINGER */
  1570. #else
  1571.     debug(F100,"TCP ck_linger SO_SOCKET not defined","",0);
  1572. #endif /* SOL_SOCKET */
  1573.     return(0);
  1574. }
  1575.  
  1576. int
  1577. sendbuf(size) int size; {
  1578. /*
  1579.   The following, from William Bader, allows changing of socket buffer sizes,
  1580.   in case that might affect performance.
  1581.  
  1582.   Modified by Jeff Altman to be generally useful.
  1583. */
  1584. #ifdef SOL_SOCKET
  1585. #ifdef SO_SNDBUF
  1586.     int i, j, rc = 0;
  1587.     SOCKOPT_T x;
  1588.  
  1589.     if (ttyfd == -1 ||
  1590.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1591.         tcp_sendbuf = size;
  1592.         return 1;
  1593.     }
  1594.     x = sizeof(i);
  1595.     if (getsockopt(ttyfd, SOL_SOCKET, SO_SNDBUF, (char *)&i, &x)) {
  1596.         debug(F111,"TCP sendbuf can't get SO_SNDBUF",ck_errstr(),errno);
  1597.     } else if (x != sizeof(i)) {
  1598. #ifdef OS2
  1599.         short i16,j16;
  1600.         if (x == sizeof(i16)) {
  1601.             debug(F111,"TCP sendbuf warning: SO_SNDBUF","len is 16-bit",x);
  1602.             if (getsockopt(ttyfd,
  1603.                            SOL_SOCKET, SO_SNDBUF,
  1604.                            (char *)&i16, &x)
  1605.                 ) {
  1606.                 debug(F111,"TCP sendbuf can't get SO_SNDBUF",
  1607.                       ck_errstr(),errno);
  1608.             } else if (size <= 0) {
  1609.                 tcp_sendbuf = i16;
  1610.                 debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i16);
  1611.                 return 1;
  1612.             } else if (i16 != size) {
  1613.                 j16 = size;
  1614.                 if (setsockopt(ttyfd,
  1615.                                SOL_SOCKET,
  1616.                                SO_SNDBUF,
  1617.                                (char *)&j16,
  1618.                                sizeof(j16))
  1619.                     ) {
  1620.                     debug(F111,"TCP sendbuf can't set SO_SNDBUF",
  1621.                           ck_errstr(),errno);
  1622.                 } else {
  1623.                     debug(F101,"TCP sendbuf old SO_SNDBUF","",i16);
  1624.                     debug(F101,"TCP sendbuf new SO_SNDBUF","",j16);
  1625.                     tcp_sendbuf = size;
  1626.                     return 1;
  1627.                 }
  1628.             } else {
  1629.                 debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i16);
  1630.                 tcp_sendbuf = size;
  1631.                 return 1;
  1632.             }
  1633.             return(0);
  1634.         }
  1635. #endif /* OS2 */
  1636.         debug(F111,"TCP sendbuf error: SO_SNDBUF","len",x);
  1637.         debug(F111,"TCP sendbuf SO_SNDBUF","expected len",sizeof(i));
  1638.         debug(F111,"TCP sendbuf SO_SNDBUF","i",i);
  1639.     } else if (size <= 0) {
  1640.         tcp_sendbuf = i;
  1641.         debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i);
  1642.         return 1;
  1643.     } else if (i != size) {
  1644.         j = size;
  1645.         if (setsockopt(ttyfd, SOL_SOCKET, SO_SNDBUF, (char *)&j, sizeof(j))) {
  1646.             debug(F111,"TCP sendbuf can't set SO_SNDBUF",ck_errstr(),errno);
  1647.             tcp_sendbuf = i;
  1648.         } else {
  1649.             debug(F101,"TCP sendbuf old SO_SNDBUF","",i);
  1650.             debug(F101,"TCP sendbuf new SO_SNDBUF","",j);
  1651.             tcp_sendbuf = size;
  1652.             return 1;
  1653.         }
  1654.     } else {
  1655.         debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i);
  1656.         tcp_sendbuf = size;
  1657.         return 1;
  1658.     }
  1659. #else
  1660.     debug(F100,"TCP sendbuf SO_SNDBUF not defined","",0);
  1661. #endif /* SO_SNDBUF */
  1662. #else
  1663.     debug(F100,"TCP sendbuf SO_SOCKET not defined","",0);
  1664. #endif /* SOL_SOCKET */
  1665.     return(0);
  1666. }
  1667.  
  1668. int
  1669. recvbuf(size) int size; {
  1670. /*
  1671.   The following, from William Bader, allows changing of socket buffer sizes,
  1672.   in case that might affect performance.
  1673.  
  1674.   Modified by Jeff Altman to be generally useful.
  1675. */
  1676. #ifdef SOL_SOCKET
  1677. #ifdef SO_RCVBUF
  1678.     int i, j, rc = 0;
  1679.     SOCKOPT_T x;
  1680.  
  1681.     if (ttyfd == -1 ||
  1682.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1683.         tcp_recvbuf = size;
  1684.         return(1);
  1685.     }
  1686.     x = sizeof(i);
  1687.     if (getsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&i, &x)) {
  1688.         debug(F111,"TCP recvbuf can't get SO_RCVBUF",ck_errstr(),errno);
  1689.     } else if (x != sizeof(i)) {
  1690. #ifdef OS2
  1691.         short i16,j16;
  1692.         if ( x == sizeof(i16) ) {
  1693.             debug(F111,"TCP recvbuf warning: SO_RCVBUF","len is 16-bit",x);
  1694.             if (getsockopt(ttyfd,
  1695.                            SOL_SOCKET, SO_RCVBUF,
  1696.                            (char *)&i16, &x)
  1697.                 ) {
  1698.                 debug(F111,"TCP recvbuf can't get SO_RCVBUF",
  1699.                       ck_errstr(),errno);
  1700.             } else if (size <= 0) {
  1701.                 tcp_recvbuf = i16;
  1702.                 debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i16);
  1703.                 return 1;
  1704.             } else if (i16 != size) {
  1705.                 j16 = size;
  1706.                 if (setsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&j16,
  1707.                                sizeof(j16))) {
  1708.                     debug(F111,"TCP recvbuf can' set SO_RCVBUF",
  1709.                           ck_errstr(),errno);
  1710.                 } else {
  1711.                     debug(F101,"TCP recvbuf old SO_RCVBUF","",i16);
  1712.                     debug(F101,"TCP recvbuf new SO_RCVBUF","",j16);
  1713.                     tcp_recvbuf = size;
  1714.                     return 1;
  1715.                 }
  1716.             } else {
  1717.                 debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i16);
  1718.                 tcp_recvbuf = size;
  1719.                 return 1;
  1720.             }
  1721.             return(0);
  1722.         }
  1723. #endif /* OS2 */
  1724.         debug(F111,"TCP recvbuf error: SO_RCVBUF","len",x);
  1725.         debug(F111,"TCP recvbuf SO_RCVBUF","expected len",sizeof(i));
  1726.         debug(F111,"TCP recvbuf SO_RCVBUF","i",i);
  1727.     } else if (size <= 0) {
  1728.         tcp_recvbuf = i;
  1729.         debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i);
  1730.         return 1;
  1731.     } else if (i != size) {
  1732.         j = size;
  1733.         if (setsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&j, sizeof(j))) {
  1734.             debug(F111,"TCP recvbuf can't set SO_RCVBUF",ck_errstr(),errno);
  1735.             tcp_recvbuf = i;
  1736.         } else {
  1737.             debug(F101,"TCP recvbuf old SO_RCVBUF","",i);
  1738.             debug(F101,"TCP recvbuf new SO_RCVBUF","",j);
  1739.             tcp_recvbuf = size;
  1740.             return 1;
  1741.         }
  1742.     } else {
  1743.         debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i);
  1744.         tcp_recvbuf = size;
  1745.         return 1;
  1746.     }
  1747. #else
  1748.     debug(F100,"TCP recvbuf SO_RCVBUF not defined","",0);
  1749. #endif /* SO_RCVBUF */
  1750. #else
  1751.     debug(F100,"TCP recvbuf SO_SOCKET not defined","",0);
  1752. #endif /* SOL_SOCKET */
  1753.     return 0;
  1754. }
  1755.  
  1756. int
  1757. keepalive(onoff) int onoff; {
  1758. #ifdef SOL_SOCKET
  1759. #ifdef SO_KEEPALIVE
  1760.     int get_keepalive_opt;
  1761.     int set_keepalive_opt;
  1762.     SOCKOPT_T x;
  1763.  
  1764.     if (ttyfd == -1 ||
  1765.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1766.         tcp_keepalive = onoff;
  1767.         return 1;
  1768.     }
  1769.     x = sizeof(get_keepalive_opt);
  1770.     if (getsockopt(ttyfd,
  1771.                    SOL_SOCKET, SO_KEEPALIVE, (char *)&get_keepalive_opt, &x)) {
  1772.         debug(F111,"TCP keepalive can't get SO_KEEPALIVE",ck_errstr(),errno);
  1773.     } else if (x != sizeof(get_keepalive_opt)) {
  1774. #ifdef OS2
  1775.         short get_keepalive_opt16;
  1776.         short set_keepalive_opt16;
  1777.         if (x == sizeof(get_keepalive_opt16)) {
  1778.             debug(F111,"TCP keepalive warning: SO_KEEPALIVE",
  1779.                   "len is 16-bit",x);
  1780.             if (getsockopt(ttyfd,
  1781.                            SOL_SOCKET, SO_KEEPALIVE,
  1782.                            (char *)&get_keepalive_opt16, &x)
  1783.                 ) {
  1784.                 debug(F111,
  1785.                       "TCP keepalive can't get SO_KEEPALIVE",
  1786.                       ck_errstr(),
  1787.                       errno
  1788.                       );
  1789.             } else if (get_keepalive_opt16 != onoff) {
  1790.                 set_keepalive_opt16 = onoff;
  1791.                 if (setsockopt(ttyfd,
  1792.                                SOL_SOCKET,
  1793.                                SO_KEEPALIVE,
  1794.                                (char *)&set_keepalive_opt16,
  1795.                                sizeof(set_keepalive_opt16))
  1796.                     ) {
  1797.                     debug(F111,
  1798.                           "TCP keepalive can't clear SO_KEEPALIVE",
  1799.                           ck_errstr(),
  1800.                           errno
  1801.                           );
  1802.                     tcp_keepalive = get_keepalive_opt16;
  1803.                 } else {
  1804.                     debug(F101,
  1805.                           "TCP keepalive new SO_KEEPALIVE","",
  1806.                           set_keepalive_opt16);
  1807.                     tcp_keepalive = set_keepalive_opt16;
  1808.                     return 1;
  1809.                 }
  1810.             } else {
  1811.                 debug(F101,"TCP keepalive SO_KEEPALIVE unchanged","",
  1812.                       get_keepalive_opt16);
  1813.                 tcp_keepalive = onoff;
  1814.                 return 1;
  1815.             }
  1816.             return(0);
  1817.         }
  1818. #endif /* OS2 */
  1819.         debug(F111,"TCP keepalive error: SO_KEEPALIVE","len",x);
  1820.         debug(F111,
  1821.               "TCP keepalive SO_KEEPALIVE",
  1822.               "expected len",
  1823.               sizeof(get_keepalive_opt)
  1824.               );
  1825.         debug(F111,
  1826.               "TCP keepalive SO_KEEPALIVE",
  1827.               "keepalive_opt",
  1828.               get_keepalive_opt
  1829.               );
  1830.     } else if (get_keepalive_opt != onoff) {
  1831.             set_keepalive_opt = onoff;
  1832.             if (setsockopt(ttyfd,
  1833.                             SOL_SOCKET,
  1834.                             SO_KEEPALIVE,
  1835.                             (char *)&set_keepalive_opt,
  1836.                             sizeof(set_keepalive_opt))
  1837.                 ) {
  1838.                 debug(F111,
  1839.                       "TCP keepalive can't clear SO_KEEPALIVE",
  1840.                       ck_errstr(),
  1841.                       errno
  1842.                       );
  1843.                 tcp_keepalive = get_keepalive_opt;
  1844.             } else {
  1845.                 debug(F101,
  1846.                       "TCP keepalive new SO_KEEPALIVE",
  1847.                       "",
  1848.                       set_keepalive_opt
  1849.                       );
  1850.                 tcp_keepalive = onoff;
  1851.                 return 1;
  1852.             }
  1853.         } else {
  1854.             debug(F101,"TCP keepalive SO_KEEPALIVE unchanged",
  1855.                   "",
  1856.                   get_keepalive_opt
  1857.                   );
  1858.             tcp_keepalive = onoff;
  1859.             return 1;
  1860.     }
  1861. #else
  1862.     debug(F100,"TCP keepalive SO_KEEPALIVE not defined","",0);
  1863. #endif /* SO_KEEPALIVE */
  1864. #else
  1865.     debug(F100,"TCP keepalive SO_SOCKET not defined","",0);
  1866. #endif /* SOL_SOCKET */
  1867.     return(0);
  1868. }
  1869.  
  1870. int
  1871. dontroute(onoff) int onoff; {
  1872. #ifdef SOL_SOCKET
  1873. #ifdef SO_DONTROUTE
  1874.     int get_dontroute_opt;
  1875.     int set_dontroute_opt;
  1876.     SOCKOPT_T x;
  1877.  
  1878.     if (ttyfd == -1 ||
  1879.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1880.         tcp_dontroute = onoff;
  1881.         return 1;
  1882.     }
  1883.     x = sizeof(get_dontroute_opt);
  1884.     if (getsockopt(ttyfd,
  1885.                    SOL_SOCKET, SO_DONTROUTE, (char *)&get_dontroute_opt, &x)) {
  1886.         debug(F111,"TCP dontroute can't get SO_DONTROUTE",ck_errstr(),errno);
  1887.     } else if (x != sizeof(get_dontroute_opt)) {
  1888. #ifdef OS2
  1889.         short get_dontroute_opt16;
  1890.         short set_dontroute_opt16;
  1891.         if (x == sizeof(get_dontroute_opt16)) {
  1892.             debug(F111,"TCP dontroute warning: SO_DONTROUTE",
  1893.                   "len is 16-bit",x);
  1894.             if (getsockopt(ttyfd,
  1895.                            SOL_SOCKET, SO_DONTROUTE,
  1896.                            (char *)&get_dontroute_opt16, &x)
  1897.                 ) {
  1898.                 debug(F111,
  1899.                       "TCP dontroute can't get SO_DONTROUTE",
  1900.                       ck_errstr(),
  1901.                       errno
  1902.                       );
  1903.             } else if (get_dontroute_opt16 != onoff) {
  1904.                 set_dontroute_opt16 = onoff;
  1905.                 if (setsockopt(ttyfd,
  1906.                                SOL_SOCKET,
  1907.                                SO_DONTROUTE,
  1908.                                (char *)&set_dontroute_opt16,
  1909.                                sizeof(set_dontroute_opt16))
  1910.                     ) {
  1911.                     debug(F111,
  1912.                           "TCP dontroute can't clear SO_DONTROUTE",
  1913.                           ck_errstr(),
  1914.                           errno
  1915.                           );
  1916.                     tcp_dontroute = get_dontroute_opt16;
  1917.                 } else {
  1918.                     debug(F101,
  1919.                           "TCP dontroute new SO_DONTROUTE","",
  1920.                           set_dontroute_opt16);
  1921.                     tcp_dontroute = set_dontroute_opt16;
  1922.                     return 1;
  1923.                 }
  1924.             } else {
  1925.                 debug(F101,"TCP dontroute SO_DONTROUTE unchanged","",
  1926.                       get_dontroute_opt16);
  1927.                 tcp_dontroute = onoff;
  1928.                 return 1;
  1929.             }
  1930.             return(0);
  1931.         }
  1932. #endif /* OS2 */
  1933.         debug(F111,"TCP dontroute error: SO_DONTROUTE","len",x);
  1934.         debug(F111,
  1935.               "TCP dontroute SO_DONTROUTE",
  1936.               "expected len",
  1937.               sizeof(get_dontroute_opt)
  1938.               );
  1939.         debug(F111,
  1940.               "TCP dontroute SO_DONTROUTE",
  1941.               "dontroute_opt",
  1942.               get_dontroute_opt
  1943.               );
  1944.     } else if (get_dontroute_opt != onoff) {
  1945.             set_dontroute_opt = onoff;
  1946.             if (setsockopt(ttyfd,
  1947.                             SOL_SOCKET,
  1948.                             SO_DONTROUTE,
  1949.                             (char *)&set_dontroute_opt,
  1950.                             sizeof(set_dontroute_opt))
  1951.                 ) {
  1952.                 debug(F111,
  1953.                       "TCP dontroute can't clear SO_DONTROUTE",
  1954.                       ck_errstr(),
  1955.                       errno
  1956.                       );
  1957.                 tcp_dontroute = get_dontroute_opt;
  1958.             } else {
  1959.                 debug(F101,
  1960.                       "TCP dontroute new SO_DONTROUTE",
  1961.                       "",
  1962.                       set_dontroute_opt
  1963.                       );
  1964.                 tcp_dontroute = onoff;
  1965.                 return 1;
  1966.             }
  1967.         } else {
  1968.             debug(F101,"TCP dontroute SO_DONTROUTE unchanged",
  1969.                   "",
  1970.                   get_dontroute_opt
  1971.                   );
  1972.             tcp_dontroute = onoff;
  1973.             return 1;
  1974.     }
  1975. #else
  1976.     debug(F100,"TCP dontroute SO_DONTROUTE not defined","",0);
  1977. #endif /* SO_DONTROUTE */
  1978. #else
  1979.     debug(F100,"TCP dontroute SO_SOCKET not defined","",0);
  1980. #endif /* SOL_SOCKET */
  1981.     return(0);
  1982. }
  1983.  
  1984. int
  1985. no_delay(onoff)  int onoff; {
  1986. #ifdef SOL_SOCKET
  1987. #ifdef TCP_NODELAY
  1988.     int get_nodelay_opt;
  1989.     int set_nodelay_opt;
  1990.     SOCKOPT_T x;
  1991.  
  1992.     if (ttyfd == -1 ||
  1993.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1994.         tcp_nodelay = onoff;
  1995.         return(1);
  1996.     }
  1997.     x = sizeof(get_nodelay_opt);
  1998.     if (getsockopt(ttyfd,IPPROTO_TCP,TCP_NODELAY,
  1999.                    (char *)&get_nodelay_opt,&x)) {
  2000.         debug(F111,
  2001.               "TCP no_delay can't get TCP_NODELAY",
  2002.               ck_errstr(),
  2003.               errno);
  2004.     } else if (x != sizeof(get_nodelay_opt)) {
  2005. #ifdef OS2
  2006.         short get_nodelay_opt16;
  2007.         short set_nodelay_opt16;
  2008.         if (x == sizeof(get_nodelay_opt16)) {
  2009.             debug(F111,"TCP no_delay warning: TCP_NODELAY","len is 16-bit",x);
  2010.             if (getsockopt(ttyfd,
  2011.                            IPPROTO_TCP, TCP_NODELAY,
  2012.                            (char *)&get_nodelay_opt16, &x)
  2013.                 ) {
  2014.                 debug(F111,
  2015.                       "TCP no_delay can't get TCP_NODELAY",
  2016.                       ck_errstr(),
  2017.                       errno);
  2018.             } else if (get_nodelay_opt16 != onoff) {
  2019.                 set_nodelay_opt16 = onoff;
  2020.                 if (setsockopt(ttyfd,
  2021.                                IPPROTO_TCP,
  2022.                                TCP_NODELAY,
  2023.                                (char *)&set_nodelay_opt16,
  2024.                                sizeof(set_nodelay_opt16))
  2025.                     ) {
  2026.                     debug(F111,
  2027.                           "TCP no_delay can't clear TCP_NODELAY",
  2028.                           ck_errstr(),
  2029.                           errno);
  2030.                     tcp_nodelay = get_nodelay_opt16;
  2031.                 } else {
  2032.                     debug(F101,
  2033.                           "TCP no_delay new TCP_NODELAY",
  2034.                           "",
  2035.                           set_nodelay_opt16);
  2036.                     tcp_nodelay = onoff;
  2037.                     return 1;
  2038.                 }
  2039.             } else {
  2040.                 debug(F101,"TCP no_delay TCP_NODELAY unchanged","",
  2041.                       get_nodelay_opt16);
  2042.                 tcp_nodelay = onoff;
  2043.                 return 1;
  2044.             }
  2045.             return(0);
  2046.         }
  2047. #endif /* OS2 */
  2048.         debug(F111,"TCP no_delay error: TCP_NODELAY","len",x);
  2049.         debug(F111,"TCP no_delay TCP_NODELAY","expected len",
  2050.               sizeof(get_nodelay_opt));
  2051.         debug(F111,"TCP no_delay TCP_NODELAY","nodelay_opt",get_nodelay_opt);
  2052.     } else if (get_nodelay_opt != onoff) {
  2053.         set_nodelay_opt = onoff;
  2054.         if (setsockopt(ttyfd,
  2055.                        IPPROTO_TCP,
  2056.                        TCP_NODELAY,
  2057.                        (char *)&set_nodelay_opt,
  2058.                        sizeof(set_nodelay_opt))) {
  2059.             debug(F111,
  2060.                   "TCP no_delay can't clear TCP_NODELAY",
  2061.                   ck_errstr(),
  2062.                   errno
  2063.                   );
  2064.             tcp_nodelay = get_nodelay_opt;
  2065.         } else {
  2066.             debug(F101,"TCP no_delay new TCP_NODELAY","",set_nodelay_opt);
  2067.             tcp_nodelay = onoff;
  2068.             return 1;
  2069.         }
  2070.     } else {
  2071.         debug(F101,"TCP no_delay TCP_NODELAY unchanged","",get_nodelay_opt);
  2072.         tcp_nodelay = onoff;
  2073.         return(1);
  2074.     }
  2075. #else
  2076.     debug(F100,"TCP no_delay TCP_NODELAY not defined","",0);
  2077. #endif /* TCP_NODELAY */
  2078. #else
  2079.     debug(F100,"TCP no_delay SO_SOCKET not defined","",0);
  2080. #endif /* SOL_SOCKET */
  2081.     return 0;
  2082. }
  2083. #endif /* datageneral */
  2084. #endif /* NOTCPOPTS */
  2085.  
  2086. #ifdef SUNX25
  2087. #ifndef X25_WR_FACILITY
  2088. /* For Solaris 2.3 / SunLink 8.x - see comments in ckcnet.h */
  2089. void
  2090. bzero(s,n) char *s; int n; {
  2091.     memset(s,0,n);
  2092. }
  2093. #endif /* X25_WR_FACILITY */
  2094. #endif /* SUNX25 */
  2095.  
  2096. #ifdef TCPSOCKET
  2097. #ifndef OS2
  2098. #ifndef NOLISTEN
  2099.  
  2100. #ifdef BSDSELECT
  2101. #ifndef VMS
  2102. #ifndef BELLV10
  2103. #ifndef datageneral
  2104. #ifdef hp9000s500                       /* HP-9000/500 HP-U 5.21 */
  2105. #include <time.h>
  2106. #else
  2107.  
  2108. /****** THIS SECTION ADDED BY STEVE RANCE - OS9 NETWORK SERVER
  2109. *       ------------------------------------------------------
  2110. *
  2111. *       Due to OS9's Lack of a select() call, the following seems to be
  2112. *       enough to fool the rest of the code into compiling. The only
  2113. *       effect that I can see is using control L to refresh the status
  2114. *       display gets qued up until some network packets arrive.
  2115. *
  2116. *       This solution is by no means elegant but works enough to be
  2117. *       a (the) solution.
  2118. *
  2119. *       Also with the defines I had specified in my makefile I had to
  2120. *       have an #endif right at the end of the file when compiling.
  2121. *       I did not bother speding time to find out why.
  2122. *
  2123. *       COPTS   = -to=osk -d=OSK -d=TCPSOCKET -d=SELECT -d=VOID=void -d=SIG_V \
  2124. *          -d=DYNAMIC -d=PARSENSE -d=KANJI -d=MYCURSES -d=ZFCDAT \
  2125. *          -d=CK_APC -d=CK_REDIR -d=RENAME -d=CK_TTYFD -d=NOOLDMODEMS \
  2126. *          -d=CK_ANSIC -d=CK_XYZ -tp=68040d -l=netdb.l -l=socklib.l \
  2127. *          -l=termlib.l -l=math.l -l=sys_clib.l
  2128. *
  2129. *       stever@ozemail.com.au
  2130. */
  2131.  
  2132. #ifdef  OSK
  2133. #define BSDSELECT                       /* switch on BSD select code */
  2134. #define FD_SETSIZE 32                   /* Max # of paths in OS9 */
  2135. #define FD_ZERO(p)                      ((*p)=0)
  2136. #define FD_SET(n,b)                     ((*b)|=(1<<(n)))
  2137. #define FD_ISSET(n,b)           1       /* always say data is ready */
  2138. #define select(a,b,c,d,e)       1       /* always say 1 path has data */
  2139. typedef int     fd_set;                 /* keep BSD Code Happy */
  2140. struct timeval {int tv_sec,tv_usec;};   /* keep BSD Code Happy */
  2141.  
  2142. /****** END OF OS9 MODS FROM STEVE RANCE **************************/
  2143. #endif /* OSK */
  2144.  
  2145. #include <sys/time.h>
  2146. #endif /* hp9000s500 */
  2147. #endif /* datageneral */
  2148. #endif /* BELLV10 */
  2149. #endif /* VMS */
  2150. #ifdef SELECT_H
  2151. #include <sys/select.h>
  2152. #endif /* SELECT_H */
  2153. #endif /* BSDSELECT */
  2154.  
  2155. #ifdef SELECT
  2156. #ifdef CK_SCOV5
  2157. #include <sys/select.h>
  2158. #endif /* CK_SCOV5 */
  2159. #endif /* SELECT */
  2160. #ifdef NOTUSED
  2161.  
  2162. /* T C P S O C K E T _ O P E N -- Open a preexisting socket number */
  2163.  
  2164. int
  2165. tcpsocket_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo {
  2166.     int on = 1;
  2167.     static struct servent *service, servrec;
  2168.     static struct hostent *host;
  2169.     static struct sockaddr_in saddr;
  2170.     static
  2171. #ifdef UCX50
  2172.       unsigned
  2173. #endif /* UCX50 */
  2174.       int saddrlen;
  2175. #ifdef BSDSELECT
  2176.     fd_set rfds;
  2177.     struct timeval tv;
  2178. #else
  2179. #ifdef BELLSELECT
  2180.     fd_set rfds;
  2181. #else
  2182.     fd_set rfds;
  2183.     fd_set rfds;
  2184.     struct timeval {
  2185.         long tv_sec;
  2186.         long tv_usec;
  2187.     } tv;
  2188. #endif /* BELLSELECT */
  2189. #endif /* BSDSELECT */
  2190.  
  2191.     debug(F101,"tcpsocket_open nett","",nett);
  2192.     *ipaddr = '\0';
  2193.  
  2194.     if (nett != NET_TCPB)
  2195.       return(-1);                       /* BSD socket support */
  2196.  
  2197.     netclos();                          /* Close any previous connection. */
  2198.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2199.     if (ttnproto != NP_TCPRAW)
  2200.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2201.     debug(F110,"tcpsocket_open namecopy",namecopy,0);
  2202.  
  2203.     /* Assign the socket number to ttyfd and then fill in tcp structures */
  2204.     ttyfd = atoi(&name[1]);
  2205.     debug(F111,"tcpsocket_open","ttyfd",ttyfd);
  2206.  
  2207. #ifndef NOTCPOPTS
  2208. #ifdef SOL_SOCKET
  2209.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2210.  
  2211. #ifndef datageneral
  2212. #ifdef TCP_NODELAY
  2213.     no_delay(tcp_nodelay);
  2214. #endif /* TCP_NODELAY */
  2215. #ifdef SO_KEEPALIVE
  2216.     keepalive(tcp_keepalive);
  2217. #endif /* SO_KEEPALIVE */
  2218. #ifdef SO_LINGER
  2219.     ck_linger(tcp_linger, tcp_linger_tmo);
  2220. #endif /* SO_LINGER */
  2221. #ifdef SO_SNDBUF
  2222.     sendbuf(tcp_sendbuf);
  2223. #endif /* SO_SNDBUF */
  2224. #ifdef SO_RCVBUF
  2225.     recvbuf(tcp_recvbuf);
  2226. #endif /* SO_RCVBUF */
  2227. #endif /* datageneral */
  2228. #endif /* SOL_SOCKET */
  2229. #endif /* NOTCPOPTS */
  2230.  
  2231. #ifdef NT_TCP_OVERLAPPED
  2232.     OverlappedWriteInit();
  2233.     OverlappedReadInit();
  2234. #endif /* NT_TCP_OVERLAPPED */
  2235.  
  2236.  
  2237.     /* Get the name of the host we are connected to */
  2238.  
  2239.     saddrlen = sizeof(saddr);
  2240.     getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen);
  2241.  
  2242.     ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2243.  
  2244.     if (tcp_rdns == SET_ON
  2245. #ifdef CK_KERBEROS
  2246.         || tcp_rdns == SET_AUTO &&
  2247.          (ck_krb5_is_installed() || ck_krb4_is_installed())
  2248. #endif /* CK_KERBEROS */
  2249.          ) {                            /* Reverse DNS */
  2250.         if (!quiet) {
  2251.             printf(" Reverse DNS Lookup... ");
  2252.             fflush(stdout);
  2253.         }
  2254.         host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET);
  2255.         debug(F110,"tcpsocket_open gethostbyaddr",host ? "OK" : "FAILED",0);
  2256.         if (host) {
  2257.             debug(F100,"tcpsocket_open gethostbyaddr != NULL","",0);
  2258.             if (!quiet) {
  2259.                 printf("(OK)\n");
  2260.                 fflush(stdout);
  2261.             }
  2262.             ckstrncpy(name, host->h_name, 79);
  2263.             strncat(name, ":", 80 - strlen(name));
  2264. #ifdef COMMENT
  2265.             itoa(ntohs(saddr.sin_port), name + strlen(name), 10);
  2266. #else
  2267.             sprintf(name + strlen(name),"%d",ntohs(saddr.sin_port));
  2268. #endif /* COMMENT */
  2269.             if (!quiet
  2270. #ifndef NOICP
  2271.                 && !doconx
  2272. #endif /* NOICP */
  2273.                 )
  2274.               printf("%s connected on port %d\n",
  2275.                    host->h_name,
  2276.                    ntohs(saddr.sin_port)
  2277.                    );
  2278.         } else if (!quiet)
  2279.           printf("Failed\n");
  2280.     } else if (!quiet)
  2281.       printf("(OK)\n");
  2282.  
  2283.     if (tcp_rdns != SET_ON || !host) {
  2284.         ckstrncpy(name,ipaddr,79);
  2285.         strncat(name,":",80-strlen(name));
  2286. #ifdef COMMENT
  2287.         itoa(ntohs(saddr.sin_port), name + strlen(name), 10);
  2288. #else
  2289.         sprintf(name + strlen(name),"%d",ntohs(saddr.sin_port));
  2290. #endif /* COMMENT */
  2291.         if (!quiet
  2292. #ifdef NOICP
  2293.             && !doconx
  2294. #endif /* NOICP */
  2295.             )
  2296.           printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2297.     }
  2298.     if (!quiet) fflush(stdout);
  2299.     ttnet = nett;                       /* TCP/IP (sockets) network */
  2300.  
  2301. #ifdef RLOGCODE
  2302.     if (ntohs(saddr.sin_port) == 513)
  2303.         ttnproto = NP_LOGIN;
  2304.     else
  2305. #endif /* RLOGCODE */
  2306.     /* Assume the service is TELNET. */
  2307.     if (ttnproto != NP_TCPRAW)
  2308.         ttnproto = NP_TELNET;           /* Yes, set global flag. */
  2309. #ifdef CK_AUTHENTICATION
  2310.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2311.     ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2312.                 host->h_name : ipaddr,
  2313.                 ipaddr,
  2314.                 uidbuf,
  2315.                 ttyfd
  2316.                 );
  2317. #endif /* CK_AUTHENTICATION */
  2318.     if (tn_ini() < 0)                   /* Start/Reset TELNET negotiations */
  2319.       if (ttchk() < 0)                  /* Did it fail due to connect loss? */
  2320.         return(-1);
  2321.  
  2322.     if (*lcl < 0) *lcl = 1;             /* Local mode. */
  2323.  
  2324.     return(0);                          /* Done. */
  2325. }
  2326. #endif /* NOTUSED */
  2327.  
  2328. /*  T C P S R V _ O P E N  --  Open a TCP/IP Server connection  */
  2329. /*
  2330.   Calling conventions same as ttopen(), except third argument is network
  2331.   type rather than modem type.
  2332. */
  2333. int
  2334. tcpsrv_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo; {
  2335.     char *p;
  2336.     int i, x;
  2337.     SOCKOPT_T on = 1;
  2338.     int ready_to_accept = 0;
  2339.     static struct servent *service, servrec;
  2340.     static struct hostent *host;
  2341.     static struct sockaddr_in saddr;
  2342.     struct sockaddr_in l_addr;
  2343.     GSOCKNAME_T l_slen;
  2344. #ifdef UCX50
  2345.     static u_int saddrlen;
  2346. #else
  2347.     static SOCKOPT_T saddrlen;
  2348. #endif /* UCX50 */
  2349.  
  2350. #ifdef BSDSELECT
  2351.     fd_set rfds;
  2352.     struct timeval tv;
  2353. #else
  2354. #ifdef BELLSELCT
  2355.     fd_set rfds;
  2356. #else
  2357.     fd_set rfds;
  2358.     struct timeval {
  2359.         long tv_sec;
  2360.         long tv_usec;
  2361.     } tv;
  2362. #endif /* BELLSELECT */
  2363. #endif /* BSDSELECT */
  2364. #ifdef CK_SSL
  2365.     int ssl_failed = 0;
  2366. #endif /* CK_SSL */
  2367.  
  2368.     debug(F101,"tcpsrv_open nett","",nett);
  2369.     *ipaddr = '\0';
  2370.  
  2371.     if (nett != NET_TCPB)
  2372.       return(-1);                       /* BSD socket support */
  2373.  
  2374.     netclos();                          /* Close any previous connection. */
  2375.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2376. #ifdef COMMENT
  2377.     /* Don't do this. */
  2378.     if (ttnproto != NP_TCPRAW)
  2379.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2380. #endif /* COMMENT */
  2381.     debug(F110,"tcpsrv_open namecopy",namecopy,0);
  2382.  
  2383.     p = namecopy;                       /* Was a service requested? */
  2384.     while (*p != '\0' && *p != ':')
  2385.       p++; /* Look for colon */
  2386.     if (*p == ':') {                    /* Have a colon */
  2387.         *p++ = '\0';                    /* Get service name or number */
  2388.     } else {                            /* Otherwise use kermit */
  2389.         p = "kermit";
  2390.     }
  2391.     debug(F110,"tcpsrv_open service requested",p,0);
  2392.     if (isdigit(*p)) {                  /* Use socket number without lookup */
  2393.         service = &servrec;
  2394.         service->s_port = htons((unsigned short)atoi(p));
  2395.     } else {                            /* Otherwise lookup the service name */
  2396.         service = getservbyname(p, "tcp");
  2397.     }
  2398.     if (!service && !strcmp("kermit",p)) { /* Use Kermit service port */
  2399.         service = &servrec;
  2400.         service->s_port = htons(1649);
  2401.     }
  2402. #ifdef RLOGCODE
  2403.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  2404.         fprintf(stderr,
  2405.                 "  Warning: login service on port %d instead of port 513\n",
  2406.                  ntohs(service->s_port));
  2407.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  2408.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  2409.     }
  2410. #endif /* RLOGCODE */
  2411.     if (!service) {
  2412.         fprintf(stderr, "Cannot find port for service: %s\n", p);
  2413.         debug(F111,"tcpsrv_open can't get service",p,errno);
  2414.         errno = 0;                      /* rather than mislead */
  2415.         return(-1);
  2416.     }
  2417.  
  2418.     /* If we currently have a listen active but port has changed then close */
  2419.  
  2420.     debug(F101,"tcpsrv_open checking previous connection","",tcpsrfd);
  2421.     debug(F101,"tcpsrv_open previous tcpsrv_port","",tcpsrv_port);
  2422.     if (tcpsrfd != -1 &&
  2423.         tcpsrv_port != ntohs((unsigned short)service->s_port)) {
  2424.         debug(F100,"tcpsrv_open closing previous connection","",0);
  2425. #ifdef TCPIPLIB
  2426.         socket_close(tcpsrfd);
  2427. #else
  2428.         close(tcpsrfd);
  2429. #endif /* TCPIPLIB */
  2430.         tcpsrfd = -1;
  2431.     }
  2432.     debug(F100,"tcpsrv_open tcpsrfd","",tcpsrfd);
  2433.     if (tcpsrfd == -1) {
  2434.  
  2435.         /* Set up socket structure and get host address */
  2436.  
  2437.         bzero((char *)&saddr, sizeof(saddr));
  2438.         debug(F100,"tcpsrv_open bzero ok","",0);
  2439.         saddr.sin_family = AF_INET;
  2440.         if (tcp_address) {
  2441. #ifdef INADDRX
  2442.             inaddrx = inet_addr(tcp_address);
  2443.             saddr.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  2444. #else
  2445.             saddr.sin_addr.s_addr = inet_addr(tcp_address);
  2446. #endif /* INADDRX */
  2447.         } else
  2448.           saddr.sin_addr.s_addr = INADDR_ANY;
  2449.  
  2450.         /* Get a file descriptor for the connection. */
  2451.  
  2452.         saddr.sin_port = service->s_port;
  2453.         ipaddr[0] = '\0';
  2454.  
  2455.         debug(F100,"tcpsrv_open calling socket","",0);
  2456.         if ((tcpsrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  2457.             perror("TCP socket error");
  2458.             debug(F101,"tcpsrv_open socket error","",errno);
  2459.             return (-1);
  2460.         }
  2461.         errno = 0;
  2462.  
  2463.         /* Specify the Port may be reused */
  2464.  
  2465.         debug(F100,"tcpsrv_open calling setsockopt","",0);
  2466.         x = setsockopt(tcpsrfd,
  2467.                        SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof on);
  2468.         debug(F101,"tcpsrv_open setsockopt","",x);
  2469.  
  2470.        /* Now bind to the socket */
  2471.         printf("\nBinding socket to port %d ...\n",
  2472.                ntohs((unsigned short)service->s_port));
  2473.         if (bind(tcpsrfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  2474.             i = errno;                  /* Save error code */
  2475. #ifdef TCPIPLIB
  2476.             socket_close(tcpsrfd);
  2477. #else /* TCPIPLIB */
  2478.             close(tcpsrfd);
  2479. #endif /* TCPIPLIB */
  2480.             tcpsrfd = -1;
  2481.             tcpsrv_port = 0;
  2482.             ttyfd = -1;
  2483.             wasclosed = 1;
  2484.             errno = i;                  /* and report this error */
  2485.             debug(F101,"tcpsrv_open bind errno","",errno);
  2486.             printf("?Unable to bind to socket (errno = %d)\n",errno);
  2487.             return(-1);
  2488.         }
  2489.         debug(F100,"tcpsrv_open bind OK","",0);
  2490.         printf("Listening ...\n");
  2491.         if (listen(tcpsrfd, 15) < 0) {
  2492.             i = errno;                  /* Save error code */
  2493. #ifdef TCPIPLIB
  2494.             socket_close(tcpsrfd);
  2495. #else /* TCPIPLIB */
  2496.             close(tcpsrfd);
  2497. #endif /* TCPIPLIB */
  2498.             tcpsrfd = -1;
  2499.             tcpsrv_port = 0;
  2500.             ttyfd = -1;
  2501.             wasclosed = 1;
  2502.             errno = i;                  /* And report this error */
  2503.             debug(F101,"tcpsrv_open listen errno","",errno);
  2504.             return(-1);
  2505.         }
  2506.         debug(F100,"tcpsrv_open listen OK","",0);
  2507.         tcpsrv_port = ntohs((unsigned short)service->s_port);
  2508.     }
  2509.  
  2510. #ifdef CK_SSL
  2511.     if (ck_ssleay_is_installed()) {
  2512.         if (!ssl_do_init(1)) {
  2513.             ssl_failed = 1;
  2514.             if (bio_err!=NULL) {
  2515.                 BIO_printf(bio_err,"do_ssleay_init() failed\n");
  2516.                 ERR_print_errors(bio_err);
  2517.             } else {
  2518.                 fflush(stderr);
  2519.                 fprintf(stderr,"do_ssleay_init() failed\n");
  2520.                 ERR_print_errors_fp(stderr);
  2521.             }
  2522.             /* we will continue to accept the connection */
  2523.             /* without SSL or TLS support.               */
  2524.             TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2525.             TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2526.             TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2527.             TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2528.         }
  2529.     }
  2530. #endif /* CK_SSL */
  2531.  
  2532.     printf("\nWaiting to Accept a TCP/IP connection on port %d ...\n",
  2533.            ntohs((unsigned short)service->s_port));
  2534.     saddrlen = sizeof(saddr);
  2535.  
  2536. #ifdef BSDSELECT
  2537.     tv.tv_sec  = tv.tv_usec = 0L;
  2538.     if (timo < 0)
  2539.       tv.tv_usec = (long) -timo * 10000L;
  2540.     else
  2541.       tv.tv_sec = timo;
  2542.     debug(F101,"tcpsrv_open BSDSELECT","",timo);
  2543. #else
  2544.     debug(F101,"tcpsrv_open not BSDSELECT","",timo);
  2545. #endif /* BSDSELECT */
  2546.  
  2547.     if (timo) {
  2548.         while (!ready_to_accept) {
  2549. #ifdef BSDSELECT
  2550.             FD_ZERO(&rfds);
  2551.             FD_SET(tcpsrfd, &rfds);
  2552.             ready_to_accept =
  2553.               ((select(FD_SETSIZE,
  2554. #ifdef HPUX
  2555. #ifdef HPUX1010
  2556.                        (fd_set *)
  2557. #else
  2558.  
  2559.                        (int *)
  2560. #endif /* HPUX1010 */
  2561. #else
  2562. #ifdef __DECC
  2563.                        (fd_set *)
  2564. #endif /* __DECC */
  2565. #endif /* HPUX */
  2566.                        &rfds, NULL, NULL, &tv) > 0) &&
  2567.                FD_ISSET(tcpsrfd, &rfds));
  2568. #else /* BSDSELECT */
  2569. #ifdef IBMSELECT
  2570. #define ck_sleepint 250
  2571.             ready_to_accept =
  2572.               (select(&tcpsrfd, 1, 0, 0,
  2573.                       timo < 0 ? -timo :
  2574.                       (timo > 0 ? timo * 1000L : ck_sleepint)) == 1
  2575.                );
  2576. #else
  2577. #ifdef BELLSELECT
  2578.             FD_ZERO(rfds);
  2579.             FD_SET(tcpsrfd, rfds);
  2580.             ready_to_accept =
  2581.               ((select(128, rfds, NULL, NULL, timo < 0 ? -timo :
  2582.                       (timo > 0 ? timo * 1000L)) > 0) &&
  2583.                FD_ISSET(tcpsrfd, rfds));
  2584. #else
  2585. /* Try this - what's the worst that can happen... */
  2586.  
  2587.             FD_ZERO(&rfds);
  2588.             FD_SET(tcpsrfd, &rfds);
  2589.             ready_to_accept =
  2590.               ((select(FD_SETSIZE,
  2591.                        (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  2592.                FD_ISSET(tcpsrfd, &rfds));
  2593.  
  2594. #endif /* BELLSELECT */
  2595. #endif /* IBMSELECT */
  2596. #endif /* BSDSELECT */
  2597.         }
  2598.     }
  2599.     if (ready_to_accept || timo == 0) {
  2600.         if ((ttyfd = accept(tcpsrfd,
  2601.                             (struct sockaddr *)&saddr,&saddrlen)) < 0) {
  2602.             i = errno;                  /* save error code */
  2603. #ifdef TCPIPLIB
  2604.             socket_close(tcpsrfd);
  2605. #else /* TCPIPLIB */
  2606.             close(tcpsrfd);
  2607. #endif /* TCPIPLIB */
  2608.             ttyfd = -1;
  2609.             wasclosed = 1;
  2610.             tcpsrfd = -1;
  2611.             tcpsrv_port = 0;
  2612.             errno = i;                  /* and report this error */
  2613.             debug(F101,"tcpsrv_open accept errno","",errno);
  2614.             return(-1);
  2615.         }
  2616.         setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2617.  
  2618. #ifndef NOTCPOPTS
  2619. #ifndef datageneral
  2620. #ifdef SOL_SOCKET
  2621. #ifdef TCP_NODELAY
  2622.         no_delay(tcp_nodelay);
  2623.         debug(F101,"tcpsrv_open no_delay","",tcp_nodelay);
  2624. #endif /* TCP_NODELAY */
  2625. #ifdef SO_KEEPALIVE
  2626.         keepalive(tcp_keepalive);
  2627.         debug(F101,"tcpsrv_open keepalive","",tcp_keepalive);
  2628. #endif /* SO_KEEPALIVE */
  2629. #ifdef SO_LINGER
  2630.         ck_linger(tcp_linger, tcp_linger_tmo);
  2631.         debug(F101,"tcpsrv_open linger","",tcp_linger_tmo);
  2632. #endif /* SO_LINGER */
  2633. #ifdef SO_SNDBUF
  2634.         sendbuf(tcp_sendbuf);
  2635. #endif /* SO_SNDBUF */
  2636. #ifdef SO_RCVBUF
  2637.         recvbuf(tcp_recvbuf);
  2638. #endif /* SO_RCVBUF */
  2639. #endif /* SOL_SOCKET */
  2640. #endif /* datageneral */
  2641. #endif /* NOTCPOPTS */
  2642.  
  2643.         ttnet = nett;                   /* TCP/IP (sockets) network */
  2644.         tcp_incoming = 1;               /* This is an incoming connection */
  2645.         sstelnet = 1;                   /* Do server-side Telnet protocol */
  2646.  
  2647.         /* See if the service is TELNET. */
  2648.         if ((x = (unsigned short)service->s_port) ==
  2649.             getservbyname("telnet", "tcp")->s_port) {
  2650.             if (ttnproto != NP_TCPRAW)  /* Yes and if raw port not requested */
  2651.               ttnproto = NP_TELNET;     /* Set protocol to TELNET. */
  2652.         }
  2653. #ifdef CK_AUTHENTICATION
  2654.         /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2655.         ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2656.                      (char *)host->h_name : ipaddr,
  2657.                      ipaddr,
  2658.                      uidbuf,
  2659.                      ttyfd
  2660.                      );
  2661. #endif /* CK_AUTHENTICATION */
  2662.  
  2663. #ifdef CK_SSL
  2664.         if (ck_ssleay_is_installed() && !ssl_failed) {
  2665.             if (ck_ssl_incoming(ttyfd) < 0) {
  2666. #ifdef TCPIPLIB
  2667.                     socket_close(ttyfd);
  2668.                     socket_close(tcpsrfd);
  2669. #else /* TCPIPLIB */
  2670.                     close(ttyfd);
  2671.                     close(tcpsrfd);
  2672. #endif /* TCPIPLIB */
  2673.                     ttyfd = -1;
  2674.                     wasclosed = 1;
  2675.                     tcpsrfd = -1;
  2676.                     tcpsrv_port = 0;
  2677.                     return(-1);
  2678.             }
  2679.         }
  2680. #endif /* CK_SSL */
  2681.  
  2682. #ifndef datageneral
  2683.         /* Find out our own IP address. */
  2684.         l_slen = sizeof(l_addr);
  2685.         bzero((char *)&l_addr, l_slen);
  2686. #ifndef EXCELAN
  2687.         if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  2688.             char * s = (char *)inet_ntoa(l_addr.sin_addr);
  2689.             ckstrncpy(myipaddr, s,20);
  2690.             debug(F110,"getsockname",myipaddr,0);
  2691.         }
  2692. #endif /* EXCELAN */
  2693. #endif /* datageneral */
  2694.  
  2695.         if (tn_ini() < 0)               /* Start TELNET negotiations. */
  2696.           if (ttchk() < 0) {            /* Disconnected? */
  2697.               i = errno;                /* save error code */
  2698. #ifdef TCPIPLIB
  2699.               socket_close(tcpsrfd);
  2700. #else /* TCPIPLIB */
  2701.               close(tcpsrfd);
  2702. #endif /* TCPIPLIB */
  2703.               ttyfd = -1;
  2704.               wasclosed = 1;
  2705.               tcpsrfd = -1;
  2706.               tcpsrv_port = 0;
  2707.               errno = i;                /* and report this error */
  2708.               debug(F101,"tcpsrv_open accept errno","",errno);
  2709.               return(-1);
  2710.           }
  2711.         debug(F101,"tcpsrv_open service","",x);
  2712.         if (*lcl < 0)                   /* Set local mode. */
  2713.           *lcl = 1;
  2714.  
  2715. #ifdef COMMENT
  2716. #ifdef TCPIPLIB
  2717.         socket_close(tcpsrfd);
  2718. #else /* TCPIPLIB */
  2719.         close(tcpsrfd);
  2720. #endif /* TCPIPLIB */
  2721.         tcpsrfd = -1;
  2722.         tcpsrv_port = 0;
  2723. #endif /* COMMENT */
  2724.  
  2725.         ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2726.         if (tcp_rdns) {
  2727.             if (!quiet) {
  2728.                 printf(" Reverse DNS Lookup... ");
  2729.                 fflush(stdout);
  2730.             }
  2731.             if (host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET)) {
  2732.                 debug(F100,"tcpsrv_open gethostbyaddr != NULL","",0);
  2733.                 if (!quiet) {
  2734.                     printf("(OK)\n");
  2735.                     fflush(stdout);
  2736.                 }
  2737.                 name[0] = '*';
  2738.                 ckstrncpy(&name[1],host->h_name,78);
  2739.                 strncat(name,":",80-strlen(name));
  2740.                 strncat(name,p,80-strlen(name));
  2741.                 if (!quiet
  2742. #ifndef NOICP
  2743.                     && !doconx
  2744. #endif /* NOICP */
  2745.                     )
  2746.                   printf("%s connected on port %s\n",host->h_name,p);
  2747.             } else {
  2748.                 if (!quiet) printf("Failed.\n");
  2749.             }
  2750.         } else if (!quiet) printf("(OK)\n");
  2751.  
  2752.         if (!tcp_rdns || !host) {
  2753.             ckstrncpy(name,ipaddr,79);
  2754.             strncat(name,":",80-strlen(name));
  2755. #ifdef COMMENT
  2756.             itoa(ntohs(saddr.sin_port), name + strlen(name), 10);
  2757. #else
  2758.             sprintf(name + strlen(name),"%d",ntohs(saddr.sin_port));
  2759. #endif /* COMMENT */
  2760.             if (!quiet
  2761. #ifndef NOICP
  2762.                 && !doconx
  2763. #endif /* NOICP */
  2764.                 )
  2765.               printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2766.         }
  2767.         if (!quiet) fflush(stdout);
  2768.         return(0);                      /* Done. */
  2769.     } else {
  2770.         i = errno;                      /* save error code */
  2771. #ifdef TCPIPLIB
  2772.         socket_close(tcpsrfd);
  2773. #else /* TCPIPLIB */
  2774.         close(tcpsrfd);
  2775. #endif /* TCPIPLIB */
  2776.         ttyfd = -1;
  2777.         wasclosed = 1;
  2778.         tcpsrfd = -1;
  2779.         tcpsrv_port = 0;
  2780.         errno = i;                      /* and report this error */
  2781.         debug(F101,"tcpsrv_open accept errno","",errno);
  2782.         return(-1);
  2783.     }
  2784. }
  2785. #endif /* NOLISTEN */
  2786. #endif /* OS2 */
  2787. #endif /* TCPSOCKET */
  2788.  
  2789. #endif /* NOLOCAL */
  2790.  
  2791. unsigned long peerxipaddr = 0L;
  2792.  
  2793. char *
  2794. ckgetpeer() {
  2795. #ifdef TCPSOCKET
  2796.     static char namebuf[256];
  2797.     static struct hostent *host;
  2798.     static struct sockaddr_in saddr;
  2799. #ifdef PTX
  2800.     static size_t saddrlen;
  2801. #else
  2802. #ifdef AIX42
  2803.     /* It's size_t in 4.2 but int in 4.1 and earlier. */
  2804.     /* Note: the 4.2 man page lies; believe socket.h. */
  2805.     static size_t saddrlen;
  2806. #else
  2807. #ifdef UNIXWARE
  2808.     static size_t saddrlen;
  2809. #else  /* UNIXWARE */
  2810. #ifdef DEC_TCPIP
  2811.     static unsigned int saddrlen;
  2812. #else
  2813.     static int saddrlen;
  2814. #endif /* VMS */
  2815. #endif /* UNIXWARE */
  2816. #endif /* AIX42 */
  2817. #endif /* PTX */
  2818.     saddrlen = sizeof(saddr);
  2819.     if (getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen) < 0) {
  2820.         debug(F111,"ckgetpeer failure",ckitoa(ttyfd),errno);
  2821.         return(NULL);
  2822.     }
  2823.     host = gethostbyaddr((char *)&saddr.sin_addr,4,AF_INET);
  2824.     if (host) {
  2825.         ckstrncpy(namebuf,(char *)host->h_name,80);
  2826.     } else {
  2827.         ckstrncpy(namebuf,(char *)inet_ntoa(saddr.sin_addr),80);
  2828.     }
  2829.     peerxipaddr = ntohl(saddr.sin_addr.s_addr);
  2830.     debug(F111,"ckgetpeer",namebuf,peerxipaddr);
  2831.     return(namebuf);
  2832. #else
  2833.     return(NULL);
  2834. #endif /* TCPSOCKET */
  2835. }
  2836.  
  2837. #ifndef NOLOCAL
  2838.  
  2839. char *
  2840. #ifdef CK_ANSIC
  2841. ckgetfqhostname(char * name)
  2842. #else
  2843. ckgetfqhostname(name) char * name;
  2844. #endif /* CK_ANSIC */
  2845. {
  2846.     static char namebuf[256];
  2847.     struct hostent *host=NULL;
  2848.     struct sockaddr_in r_addr;
  2849.     int i;
  2850.  
  2851.     debug(F110,"ckgetfqhn()",name,0);
  2852.  
  2853.     ckstrncpy(namebuf,name,256);
  2854.     namebuf[255] = '\0';
  2855.     i = ckindex(":",namebuf,0,0,0);
  2856.     if (i)
  2857.       namebuf[i-1] = '\0';
  2858.  
  2859.     bzero((char *)&r_addr, sizeof(r_addr));
  2860.  
  2861.     host = gethostbyname(namebuf);
  2862.     if (host) {
  2863.         debug(F100,"ckgetfqhn() gethostbyname != NULL","",0);
  2864.         r_addr.sin_family = host->h_addrtype;
  2865. #ifdef HADDRLIST
  2866. #ifdef h_addr
  2867.         /* This is for trying multiple IP addresses - see <netdb.h> */
  2868.         if (!(host->h_addr_list))
  2869.           goto exit_func;
  2870.         bcopy(host->h_addr_list[0],
  2871.               (caddr_t)&r_addr.sin_addr,
  2872.               host->h_length
  2873.               );
  2874. #else
  2875.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  2876. #endif /* h_addr */
  2877. #else  /* HADDRLIST */
  2878.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  2879. #endif /* HADDRLIST */
  2880. #ifndef EXCELAN
  2881.         debug(F111,"BCOPY","host->h_addr",host->h_addr);
  2882. #endif /* EXCELAN */
  2883.         debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  2884.               (caddr_t)&r_addr.sin_addr);
  2885.         debug(F111,"BCOPY","host->h_length",host->h_length);
  2886.  
  2887. #ifdef NT
  2888.         /* Windows 95/98 requires a 1 second wait between calls to Microsoft */
  2889.         /* provided DNS functions.  Otherwise, the TTL of the DNS response */
  2890.         /* is ignored. */
  2891.         if (isWin95())
  2892.           sleep(1);
  2893. #endif /* NT */
  2894.         host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET);
  2895.         if (host) {
  2896.             debug(F100,"ckgetfqhn() gethostbyaddr != NULL","",0);
  2897.             ckstrncpy(namebuf, host->h_name, 256);
  2898.         }
  2899.     }
  2900.  
  2901. #ifdef HADDRLIST
  2902. #ifdef h_addr
  2903.   exit_func:
  2904. #endif /* h_addr */
  2905. #endif /* HADDRLIST */
  2906.  
  2907.     if (i > 0)
  2908.       strncat(namebuf,&name[i-1],256-strlen(namebuf)-strlen(&name[i-1]));
  2909.     debug(F110,"ckgetfqhn()",namebuf,0);
  2910.     return(namebuf);
  2911. }
  2912.  
  2913. VOID
  2914. #ifdef CK_ANSIC
  2915. setnproto(char * p)
  2916. #else
  2917. setnproto(p) char * p;
  2918. #endif /* CK_ANSIC */
  2919. {
  2920.     if (!isdigit(*p)) {
  2921.         if (!strcmp("kermit",p))
  2922.           ttnproto = NP_KERMIT;
  2923.         else if (!strcmp("telnet",p))
  2924.           ttnproto = NP_TELNET;
  2925.         else if (!strcmp("http",p))
  2926.           ttnproto = NP_TCPRAW;
  2927. #ifdef RLOGCODE
  2928.         else if (!strcmp("login",p))
  2929.           ttnproto = NP_RLOGIN;
  2930. #endif /* RLOGCODE */
  2931. #ifdef CK_SSL
  2932.         /* Commonly used SSL ports (might not be in services file) */
  2933.         else if (!strcmp("https",p))
  2934.           ttnproto = NP_SSL;
  2935.         else if (!strcmp("ssl-telnet",p))
  2936.           ttnproto = NP_SSL;
  2937.         else if (!strcmp("telnets",p))
  2938.           ttnproto = NP_SSL;
  2939. #endif /* CK_SSL */
  2940. #ifdef CK_KERBEROS
  2941. #ifdef RLOGCODE
  2942.         else if (!strcmp("klogin",p)) {
  2943.             if (ck_krb5_is_installed())
  2944.               ttnproto = NP_K5LOGIN;
  2945.             else if (ck_krb4_is_installed())
  2946.               ttnproto = NP_K4LOGIN;
  2947.             else
  2948.               ttnproto = NP_RLOGIN;
  2949.         } else if (!strcmp("eklogin",p)) {
  2950.             if (ck_krb5_is_installed())
  2951.               ttnproto = NP_EK5LOGIN;
  2952.             else if (ck_krb4_is_installed())
  2953.               ttnproto = NP_EK4LOGIN;
  2954.             else
  2955.               ttnproto = NP_RLOGIN;
  2956.         }
  2957. #endif /* RLOGCODE */
  2958. #endif /* CK_KERBEROS */
  2959.         else
  2960.           ttnproto = NP_NONE;
  2961.     } else {
  2962.         switch (atoi(p)) {
  2963.           case 23:                      /* Telnet */
  2964.             ttnproto = NP_TELNET;
  2965.             break;
  2966.           case 513:
  2967.             ttnproto = NP_RLOGIN;
  2968.             break;
  2969.           case 1649:
  2970.             ttnproto = NP_KERMIT;
  2971.             break;
  2972. #ifdef CK_SSL
  2973.           case 443:
  2974.             ttnproto = NP_SSL;
  2975.             ssl_only_flag = 1;
  2976.             break;
  2977.           case 151:
  2978.           case 992:
  2979.             ttnproto = NP_TELNET;
  2980.             break;
  2981. #endif /* CK_SSL */
  2982. #ifdef CK_KERBEROS
  2983.           case 543:
  2984.             if (ck_krb5_is_installed())
  2985.               ttnproto = NP_K5LOGIN;
  2986.             else if (ck_krb4_is_installed())
  2987.               ttnproto = NP_K4LOGIN;
  2988.             else
  2989.               ttnproto = NP_RLOGIN;
  2990.             break;
  2991.           case 2105:
  2992.             if (ck_krb5_is_installed())
  2993.               ttnproto = NP_EK5LOGIN;
  2994.             else if (ck_krb4_is_installed())
  2995.               ttnproto = NP_EK4LOGIN;
  2996.             else
  2997.               ttnproto = NP_RLOGIN;
  2998.             break;
  2999. #endif /* CK_KERBEROS */
  3000.           case 80:                      /* HTTP */
  3001.             ttnproto = NP_TCPRAW;
  3002.             break;
  3003.           default:
  3004.             ttnproto = NP_NONE;
  3005.             break;
  3006.         }
  3007.     }
  3008. }
  3009.  
  3010.  
  3011. /*  N E T O P E N  --  Open a network connection  */
  3012. /*
  3013.   Calling conventions same as ttopen(), except third argument is network
  3014.   type rather than modem type.  Designed to be called from within ttopen.
  3015. */
  3016. int
  3017. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  3018.     char *p;
  3019.     int i, x, dns = 0;
  3020. #ifdef TCPSOCKET
  3021.     int isconnect = 0;
  3022. #ifdef SO_OOBINLINE
  3023.     int on = 1;
  3024. #endif /* SO_OOBINLINE */
  3025.     struct servent *service=NULL, servrec;
  3026.     struct hostent *host=NULL;
  3027.     struct sockaddr_in r_addr;
  3028.     struct sockaddr_in sin;
  3029.     struct sockaddr_in l_addr;
  3030.     GSOCKNAME_T l_slen;
  3031. #ifdef CK_DNS_SRV
  3032.     struct sockaddr * dns_addrs = NULL;
  3033.     int dns_naddrs = 0;
  3034. #endif /* CK_DNS_SRV */
  3035. #ifdef EXCELAN
  3036.     struct sockaddr_in send_socket;
  3037. #endif /* EXCELAN */
  3038.  
  3039. #ifdef INADDRX
  3040. /* inet_addr() is of type struct in_addr */
  3041. #ifdef datageneral
  3042.     extern struct in_addr inet_addr();
  3043. #else
  3044. #ifdef HPUX5WINTCP
  3045.     extern struct in_addr inet_addr();
  3046. #endif /* HPUX5WINTCP */
  3047. #endif /* datageneral */
  3048.     struct in_addr iax;
  3049. #else
  3050. #ifdef INADDR_NONE
  3051.     struct in_addr iax;
  3052. #else /* INADDR_NONE */
  3053.     long iax;
  3054. #endif /* INADDR_NONE */
  3055. #endif /* INADDRX */
  3056. #endif /* TCPSOCKET */
  3057.  
  3058. #ifdef COMMENT
  3059. /* This causes big trouble */
  3060. #ifndef INADDR_NONE
  3061. #define INADDR_NONE 0xffffffff
  3062. #endif /* INADDR_NONE */
  3063. #endif /* COMMENT */
  3064.  
  3065. #ifdef SUNX25                           /* Code for SunLink X.25 support */
  3066. #define X29PID 1                        /* X.29 Protocol ID */
  3067. _PROTOTYP(SIGTYP x25oobh, (int) );
  3068.     CONN_DB x25host;
  3069. #ifndef X25_WR_FACILITY
  3070.     FACILITY x25facil;
  3071. #else
  3072.     FACILITY_DB x25facil;
  3073. #endif /* X25_WR_FACILITY */
  3074.     static int needh = 1;
  3075.     PID_T pid;
  3076.     extern int linkid, lcn, x25ver;
  3077. #endif /* SUNX25 */
  3078. #ifdef ANYX25
  3079.     extern int revcall, closgr, cudata;
  3080.     extern char udata[];
  3081. #endif /* ANYX25 */
  3082.  
  3083. #ifdef IBMX25                           /* Variables for IBM X25 */
  3084.     extern int x25port;                 /* Logical port to use */
  3085.     extern x25addr_t local_nua;         /* Local X.25 address */
  3086.     extern x25addr_t remote_nua;        /* Remote X.25 address */
  3087.     extern char x25name[];              /* X25 device name (sx25a0) */
  3088.     extern char x25dev[];               /* X25 device file /dev/x25pkt */
  3089.     ulong bind_flags = 0;               /* Flags for binding the X25 stream */
  3090.     ulong token = 0;                    /* Temporary return code */
  3091. #endif /* IBMX25 */
  3092.  
  3093.     debug(F101,"netopen nett","",nett);
  3094.     *ipaddr = '\0';                     /* Initialize IP address string */
  3095.  
  3096. #ifdef SUNX25
  3097.     if (nett == NET_SX25) {             /* If network type is X.25 */
  3098.         netclos();                      /* Close any previous net connection */
  3099.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3100.  
  3101.         /* Set up host structure */
  3102.         bzero((char *)&x25host,sizeof(x25host));
  3103.         if ((x25host.hostlen = pkx121(name,x25host.host)) < 0) {
  3104.             fprintf (stderr,"Invalid X.121 host address %s\n",name);
  3105.             errno = 0;
  3106.             return (-1);
  3107.         }
  3108.         x25host.datalen = X29PIDLEN;
  3109.         x25host.data[0] = X29PID;
  3110.  
  3111.         /* Set call user data if specified */
  3112.         if (cudata) {
  3113.             ckstrncpy((char *)x25host.data+X29PIDLEN,udata,(int)strlen(udata));
  3114.             x25host.datalen += (int)strlen(udata);
  3115.         }
  3116.  
  3117.         /* Open SunLink X.25 socket */
  3118.         if (!quiet && *name) {
  3119.             printf(" Trying %s... ", name);
  3120.             fflush(stdout);
  3121.         }
  3122.         if ((ttyfd = socket(AF_X25, SOCK_STREAM, 0)) < 0) {
  3123.             debug(F101,"netopen socket error","",errno);
  3124.             perror ("X.25 socket error");
  3125.             return (-1);
  3126.         }
  3127.  
  3128.         /* Setting X.25 out-of-band data handler */
  3129.         pid = getpid();
  3130.         if (ioctl(ttyfd,SIOCSPGRP,&pid)) {
  3131.             perror("X.25 set process group id error");
  3132.             return(-1);
  3133.         }
  3134.         (VOID) signal(SIGURG,x25oobh);
  3135.  
  3136.         /* Set reverse charge call and closed user group if requested */
  3137.         bzero ((char *)&x25facil,sizeof(x25facil));
  3138.  
  3139. #ifndef X25_WR_FACILITY
  3140. /*  New SunLink (7.0 or 8.0, not sure which)... */
  3141.         x25facil.type = T_REVERSE_CHARGE; /* Reverse Charge */
  3142.         x25facil.f_reverse_charge = revcall ? 1 : 0;
  3143.         if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3144.             perror ("Setting X.25 reverse charge");
  3145.             return (-1);
  3146.         }
  3147.         if (closgr > -1) {              /* Closed User Group (Outgoing) */
  3148.             bzero ((char *)&x25facil,sizeof(x25facil));
  3149.             x25facil.type = T_CUG;
  3150.             x25facil.f_cug_req = CUG_REQ_ACS;
  3151.             x25facil.f_cug_index = closgr;
  3152.             if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3153.                 perror ("Setting X.25 closed user group");
  3154.                 return (-1);
  3155.             }
  3156.         }
  3157. #else
  3158. /*  Old SunLink 6.0 (or 7.0?)... */
  3159.         if (revcall) x25facil.reverse_charge = revcall;
  3160.         if (closgr > -1) {
  3161.             x25facil.cug_req = 1;
  3162.             x25facil.cug_index = closgr;
  3163.         }
  3164.         if (ioctl(ttyfd,X25_WR_FACILITY,&x25facil) < 0) {
  3165.             perror ("Setting X.25 facilities");
  3166.             return (-1);
  3167.         }
  3168. #endif /* X25_WR_FACILITY */
  3169.  
  3170.         /*  Need X.25 header with bits Q and M */
  3171.         if (ioctl (ttyfd,X25_HEADER,&needh) < 0) {
  3172.             perror ("Setting X.25 header");
  3173.             return (-1);
  3174.         }
  3175.  
  3176.         /* Connects to remote host via SunLink X.25 */
  3177.         if (connect(ttyfd,(struct sockaddr *)&x25host,sizeof(x25host)) < 0) {
  3178.             i = errno;
  3179.             debug(F101,"netopen connect errno","",i);
  3180.             if (i) {
  3181.                 perror("netopen x25 connect");
  3182.                 x25diag();
  3183.             }
  3184.             (VOID) netclos();
  3185.             ttyfd = -1;
  3186.             wasclosed = 1;
  3187.             ttnproto = NP_NONE;
  3188.             errno = i;
  3189.             return (-1);
  3190.         }
  3191.  
  3192.         /* Get X.25 link identification used for the connection */
  3193.         if (ioctl(ttyfd,X25_GET_LINK,&linkid) < 0) {
  3194.             perror ("Getting X.25 link id");
  3195.             return (-1);
  3196.         }
  3197.  
  3198.         /* Get X.25 logical channel number used for the connection */
  3199.         if (ioctl(ttyfd,X25_RD_LCGN,&lcn) < 0) {
  3200.             perror ("Getting X.25 lcn");
  3201.             return (-1);
  3202.         }
  3203.  
  3204.         /* Get SunLink X.25 version */
  3205.         if (ioctl(ttyfd,X25_VERSION,&x25ver) < 0) {
  3206.             perror ("Getting SunLink X.25 version");
  3207.             return (-1);
  3208.         }
  3209.         ttnet = nett;                   /* Sunlink X.25 network */
  3210.         ttnproto = NP_X3;               /* PAD X.3, X.28, X.29 protocol */
  3211.         if (*lcl < 0) *lcl = 1;         /* Local mode */
  3212.         return(0);
  3213.     } else /* Note that SUNX25 support can coexist with TCP/IP support. */
  3214. #endif /* SUNX25 */
  3215.  
  3216. #ifdef IBMX25
  3217.     /* riehm */
  3218.     if (nett == NET_IX25) {             /* IBM AIX X.25 */
  3219.         netclos();                      /* Close any previous net connection */
  3220.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3221.  
  3222.         /* find out who we are - this is not so easy on AIX */
  3223.         /* riehm: need to write the code that finds this out
  3224.          * automatically, or at least allow it to be configured
  3225.          * somehow
  3226.          */
  3227.         if (!local_nua[0] && !x25local_nua(local_nua)) {
  3228.             return(-1);
  3229.         }
  3230.  
  3231.         /* Initialise the X25 API (once per process? once per connection?) */
  3232.  
  3233.         debug(F110, "Opening ", x25dev, 0 );
  3234.         /* set O_NDELAY to allow polling? */
  3235.         if ((ttyfd = open(x25dev, O_RDWR)) < 0) {
  3236.             perror ("X.25 device open error");
  3237.             debug(F101,"netopen: device open error","",errno);
  3238.             return (-1);
  3239.         }
  3240.  
  3241.         /* push the NPI onto the STREAM */
  3242.         if (ioctl(ttyfd,I_PUSH,"npi") < 0 ) {
  3243.             close(ttyfd);
  3244.             ttyfd = -1;
  3245.             wasclosed = 1;
  3246.             perror( "kermit: netopen(): couldn't push npi on the X25 stream" );
  3247.             debug(F101,"netopen: can't push npi on the X25 stream","",errno);
  3248.             return (-1);
  3249.         }
  3250.  
  3251.         /* set up server mode - bind the x25 port and wait for
  3252.          * incoming connections
  3253.          */
  3254.         if (name[0] == '*') {           /* Server */
  3255.             /* set up a server - see the warning in x25bind() */
  3256.             bind_flags |= TOKEN_REQUEST;
  3257.  
  3258.             /* bind kermit to the local X25 address */
  3259.             token = x25bind(ttyfd,
  3260.                             local_nua,
  3261.                             udata,
  3262.                             (int)strlen( udata ),
  3263.                             1,
  3264.                             x25port,
  3265.                             bind_flags
  3266.                             );
  3267.             if (token < 0) {
  3268.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3269.                 netclos();
  3270.                 return(-1);
  3271.             }
  3272.             /* Currently not connected to a remote host */
  3273.  
  3274.             remote_nua[0] = '\0';
  3275.  
  3276.             /* store the fd so that incoming calls can have their own fd
  3277.              * This is almost support for a true server (ie: a'la ftpd)
  3278.              * but we're not quite there yet.
  3279.              * used in netclos()
  3280.              */
  3281.             x25serverfd = ttyfd;
  3282.             /*
  3283.              * wait for an incoming call
  3284.              * this should happen in the "server" command and not in
  3285.              * the "set host *" command.
  3286.              */
  3287.             if ((ttyfd = x25getcall(ttyfd)) < 0) {
  3288.                 netclos();
  3289.                 return(-1);
  3290.             }
  3291.         } else {                        /* Client */
  3292.             /* Bind kermit to the local X25 address */
  3293.             token = x25bind(
  3294.                             ttyfd,
  3295.                             local_nua,
  3296.                             (char *)NULL,
  3297.                             0,
  3298.                             0,
  3299.                             x25port,
  3300.                             bind_flags
  3301.                             );
  3302.             if (token < 0) {
  3303.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3304.                 netclos();
  3305.                 return(-1);
  3306.             }
  3307. /* riehm: this should be done via the CONNECT command, not HOST! */
  3308.             {
  3309.                 x25serverfd = 0;
  3310.                 /* call the remote host */
  3311.                 /* name == address of remote host as char* */
  3312.                 if (x25call(ttyfd, name, udata) < 0 ) {
  3313.                     debug(F100,
  3314.                           "netopen: couldn't connect to remote X25 address",
  3315.                           "", 0);
  3316.                     netclos();
  3317.                     return(-1);
  3318.                 }
  3319.                 strcpy(remote_nua, name);
  3320.             }
  3321.         }
  3322.         ttnet = nett;                   /* AIX X.25 network */
  3323.         if (*lcl < 0)
  3324.           *lcl = 1;                     /* Local mode */
  3325.         return(0);
  3326.  
  3327.     } else /* Note that IBMX25 support can coexist with TCP/IP support. */
  3328. #endif /* IBMX25 */
  3329.  
  3330. /*   Add support for other networks here. */
  3331.  
  3332.       if (nett != NET_TCPB) return(-1); /* BSD socket support */
  3333.  
  3334. #ifdef TCPSOCKET
  3335.     netclos();                          /* Close any previous connection. */
  3336.     ckstrncpy(namecopy, name, NAMECPYL);        /* Copy the hostname. */
  3337.     debug(F110,"netopen namecopy",namecopy,0);
  3338.  
  3339. #ifndef NOLISTEN
  3340.     if (name[0] == '*')
  3341.       return(tcpsrv_open(name, lcl, nett, 0));
  3342. #endif /* NOLISTEN */
  3343.  
  3344.     p = namecopy;                       /* Was a service requested? */
  3345.     while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3346.     if (*p == ':') {                    /* Have a colon */
  3347.         debug(F110,"netopen name has colon",namecopy,0);
  3348.         *p++ = '\0';                    /* Get service name or number */
  3349. #ifdef CK_URL
  3350.         /*
  3351.            Here we have to check for various popular syntaxes:
  3352.            host:port (our original syntax)
  3353.            URL such as telnet:host or telnet://host/
  3354.            Or even telnet://user:password@host:port/
  3355.            Or a malformed URL such as generated by Netscape 4.0 like:
  3356.            telnet:telnet or telnet::host.
  3357.         */
  3358.         if (*p == ':')                  /* a second colon */
  3359.           *p++ = '\0';                  /* get rid of that one too */
  3360.         while (*p == '/') *p++ = '\0';  /* and slashes */
  3361.         x = strlen(p);                  /* Length of remainder */
  3362.         if (p[x-1] == '/')              /* If there is a trailing slash */
  3363.           p[x-1] = '\0';                /* remove it. */
  3364.         debug(F110,"netopen namecopy after stripping",namecopy,0);
  3365.         debug(F110,"netopen p after stripping",p,0);
  3366.         service = getservbyname(namecopy,"tcp");
  3367.         if (service || !ckstrcmp("rlogin",namecopy,NAMECPYL,0)) {
  3368.             char temphost[80], tempservice[80];
  3369.             char * q = p, *r = p, *w = p;
  3370.             /* Check for userid and possibly password */
  3371.             while (*p != '\0' && *p != '@') p++; /* look for @ */
  3372.             if (*p == '@') {
  3373.                 /* found username and perhaps password */
  3374.                 debug(F110,"netopen namecopy found @","",0);
  3375.                 *p = '\0'; p++;
  3376.                 while (*w != '\0' && *w != ':')
  3377.                   w++;
  3378.                 if (*w == ':')
  3379.                   *w++ = '\0';
  3380.                 /* r now points to username, save it and discard password */
  3381.                 debug(F110,"netopen namecopy username",r,0);
  3382.                 debug(F110,"netopen namecopy password",w,0);
  3383.                 ckstrncpy(uidbuf,r,UIDBUFLEN);
  3384.                 q = p;                  /* Host after user and pwd */
  3385.             } else {
  3386.                 p = q;                  /* No username or password */
  3387.             }
  3388.             /* Now we must look for the optional port. */
  3389.             debug(F110,"netopen x p",p,0);
  3390.             debug(F110,"netopen x q",q,0);
  3391.             while (*p != '\0' && *p != ':') /* Look for another colon */
  3392.               p++;
  3393.             if (*p == ':') {
  3394.                 debug(F110,"netopen found port",q,0);
  3395.                 *p++ = '\0';            /* Found a port name or number */
  3396.                 debug(F110,"netopen port",p,0);
  3397.                 ckstrncpy(tempservice,p,79);
  3398.                 ckstrncpy(temphost,q,79);
  3399.                 ckstrncpy(namecopy,temphost,NAMECPYL);
  3400.                 debug(F110,"netopen tempservice",tempservice,0);
  3401.                 debug(F110,"netopen temphost",temphost,0);
  3402.                 x = strlen(namecopy);
  3403.                 p = namecopy + x + 1;
  3404.                 ckstrncpy(p, tempservice, NAMECPYL - x);
  3405.             } else {
  3406.                 /* We didn't find another port, but if q is a service */
  3407.                 /* then assume that namecopy is actually a host.      */
  3408.                 if (getservbyname(q,"tcp")) {
  3409.                     p = q;
  3410.                 } else {
  3411. #ifdef RLOGCODE
  3412.                     /* rlogin is not a valid service */
  3413.                     if (!ckstrcmp("rlogin",namecopy,6,0)) {
  3414.                         ckstrncpy(namecopy,"login",NAMECPYL);
  3415.                     }
  3416. #endif /* RLOGCODE */
  3417.                     /* Reconstruct namecopy */
  3418.                     ckstrncpy(tempservice,namecopy,79);
  3419.                     ckstrncpy(temphost,q,79);
  3420.                     ckstrncpy(namecopy,temphost,NAMECPYL);
  3421.                     debug(F110,"netopen tempservice",tempservice,0);
  3422.                     debug(F110,"netopen temphost",temphost,0);
  3423.                     x = strlen(namecopy);
  3424.                     p = namecopy + x + 1;
  3425.                     ckstrncpy(p, tempservice, NAMECPYL - x - 1);
  3426.                 }
  3427.             }
  3428.             debug(F110,"netopen URL result",namecopy,0);
  3429.         }
  3430. #endif /* CK_URL */
  3431.     } else {                            /* Otherwise use telnet */
  3432.         p = "telnet";
  3433.     }
  3434. /*
  3435.   By the time we get here, namecopy[] should hold the null-terminated
  3436.   hostname or address, and p should point to the service name or number.
  3437. */
  3438.     debug(F110,"netopen host",namecopy,0);
  3439.     debug(F110,"netopen service requested",p,0);
  3440.     if (isdigit(*p)) {                  /* Use socket number without lookup */
  3441.         service = &servrec;
  3442.         service->s_port = htons((unsigned short)atoi(p));
  3443.     } else {                            /* Otherwise lookup the service name */
  3444. #ifdef CK_DNS_SRV
  3445.         if (tcp_dns_srv && !quiet) {
  3446.             printf(" DNS SRV Lookup... ");
  3447.             fflush(stdout);
  3448.         }
  3449.         if (tcp_dns_srv &&
  3450.             locate_srv_dns(namecopy,p,"tcp",&dns_addrs,&dns_naddrs)) {
  3451.             /* Use the first one.  Eventually we should cycle through all */
  3452.             /* the returned IP addresses and port numbers. */
  3453.             struct sockaddr_in *sin = NULL;
  3454. #ifdef BETATEST
  3455.             int i;
  3456.             printf("\r\n");
  3457.             for ( i=0;i<dns_naddrs;i++ ) {
  3458.                 sin = (struct sockaddr_in *) &dns_addrs[i];
  3459.                 printf("dns_addrs[%d] = %s %d\r\n", i,
  3460.                         (char *)inet_ntoa(sin->sin_addr),
  3461.                         ntohs(sin->sin_port));
  3462.             }
  3463. #endif /* BETATEST */
  3464.             /* Since the DNS SRV record will replace the service name with */
  3465.             /* a numeric port number we need to set the protocol before we */
  3466.             /* replace the service name */
  3467.             if (ttnproto == NP_DEFAULT)
  3468.               setnproto(p);
  3469.  
  3470.             sin = (struct sockaddr_in *) &dns_addrs[0];
  3471.             ckstrncpy(namecopy,(char *)inet_ntoa(sin->sin_addr),NAMECPYL);
  3472.             p = namecopy+strlen(namecopy)+1;
  3473.             sprintf(p,"%d",ntohs(sin->sin_port));
  3474.             service = &servrec;
  3475.             service->s_port = sin->sin_port;
  3476.  
  3477.             free(dns_addrs);
  3478.             dns_addrs = NULL;
  3479.             dns_naddrs = 0;
  3480.         } else
  3481. #endif /* CK_DNS_SRV */
  3482.             service = getservbyname(p, "tcp");
  3483.     }
  3484.     if (!service) {
  3485.         if (!strcmp("kermit",p)) {      /* Use Kermit service port */
  3486.             service = &servrec;
  3487.             service->s_port = htons(1649);
  3488.         } else if (!strcmp("telnet",p)) { /* Use Telnet port */
  3489.             service = &servrec;
  3490.             service->s_port = htons(23);
  3491.         } else if (!strcmp("http",p)) {
  3492.             service = &servrec;
  3493.             service->s_port = htons(80);
  3494.         }
  3495. #ifdef RLOGCODE
  3496.         else if (!strcmp("login",p)) {
  3497.             service = &servrec;
  3498.             service->s_port = htons(513);
  3499.         }
  3500. #endif /* RLOGCODE */
  3501. #ifdef CK_SSL
  3502.         /* Commonly used SSL ports (might not be in services file) */
  3503.         else if (!strcmp("https",p)) {
  3504.             service = &servrec;
  3505.             service->s_port = htons(443);
  3506.         } else if (!strcmp("ssl-telnet",p)) {
  3507.             service = &servrec;
  3508.             service->s_port = htons(151);
  3509.         } else if (!strcmp("telnets",p)) {
  3510.             service = &servrec;
  3511.             service->s_port = htons(992);
  3512.         }
  3513. #endif /* CK_SSL */
  3514. #ifdef CK_KERBEROS
  3515. #ifdef RLOGCODE
  3516.         else if (!strcmp("klogin",p)) {
  3517.             service = &servrec;
  3518.             service->s_port = htons(543);
  3519.         } else if (!strcmp("eklogin",p)) {
  3520.             service = &servrec;
  3521.             service->s_port = htons(2105);
  3522.         }
  3523. #endif /* RLOGCODE */
  3524. #endif /* CK_KERBEROS */
  3525.  
  3526.         if (!service) {
  3527.             fprintf(stderr, "Can't find port for service %s\n", p);
  3528. #ifdef TGVORWIN
  3529.             debug(F101,"netopen can't get service","",socket_errno);
  3530. #else
  3531.             debug(F101,"netopen can't get service","",errno);
  3532. #endif /* TGVORWIN */
  3533.             errno = 0;                  /* (rather than mislead) */
  3534.             return(-1);
  3535.         }
  3536.     }
  3537.     ckstrncpy(svcbuf,p,79);
  3538.     debug(F110,"netopen service ok",svcbuf,0);
  3539.  
  3540.     /* Use the service port to set the default protocol type if necessary */
  3541.     if (ttnproto == NP_DEFAULT)
  3542.       setnproto(p);
  3543.  
  3544. #ifdef RLOGCODE
  3545.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  3546.         fprintf(stderr,
  3547.                 "  Warning: login service on port %d instead of port 513\n",
  3548.                  ntohs(service->s_port)
  3549.                 );
  3550.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  3551.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  3552.     }
  3553. #endif /* RLOGCODE */
  3554.  
  3555.     /* Set up socket structure and get host address */
  3556.  
  3557.     bzero((char *)&r_addr, sizeof(r_addr));
  3558.     debug(F100,"netopen bzero ok","",0);
  3559. /*
  3560.    NOTE: Originally the inet_addr() check was #ifdef NT, but is enabled for
  3561.    all as of 20 Sep 97, to allow people to "set host" to a specific numeric IP
  3562.    address without going through the multihomed host sequence and winding up
  3563.    at a different place than the one requested.
  3564. */
  3565. #ifdef INADDR_NONE
  3566.     debug(F101,"netopen INADDR_NONE defined","",INADDR_NONE);
  3567. #else /* INADDR_NONE */
  3568.     debug(F100,"netopen INADDR_NONE not defined","",0);
  3569. #endif /* INADDR_NONE */
  3570. #ifdef INADDRX
  3571.     debug(F100,"netopen INADDRX defined","",0);
  3572. #else /* INADDRX */
  3573.     debug(F100,"netopen INADDRX not defined","",0);
  3574. #endif /* INADDRX */
  3575.  
  3576. #ifndef NOMHHOST
  3577. #ifdef INADDRX
  3578.     iax = inet_addr(namecopy);
  3579.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  3580. #else /* INADDRX */
  3581. #ifdef INADDR_NONE
  3582.     iax.s_addr = inet_addr(namecopy);
  3583.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  3584. #else /* INADDR_NONE */
  3585. #ifndef datageneral
  3586.     iax = (unsigned int) inet_addr(namecopy);
  3587. #else
  3588.     iax = -1L;
  3589. #endif /* datageneral */
  3590.     debug(F111,"netopen inet_addr",namecopy,iax);
  3591. #endif /* INADDR_NONE */
  3592. #endif /* INADDRX */
  3593.  
  3594.     dns = 0;
  3595.     if (
  3596. #ifdef INADDR_NONE
  3597.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  3598. #else /* INADDR_NONE */
  3599.         iax < 0
  3600. #endif /* INADDR_NONE */
  3601.         ) {
  3602.         if (!quiet) {
  3603.             printf(" DNS Lookup... ");
  3604.             fflush(stdout);
  3605.         }
  3606.         if ((host = gethostbyname(namecopy)) != NULL) {
  3607.             debug(F100,"netopen gethostbyname != NULL","",0);
  3608.             dns = 1;                    /* Remember we performed dns lookup */
  3609. #ifdef OS2
  3610.             ckstrncpy(name,host->h_name,80);
  3611.             strncat(name,":",80-strlen(name));
  3612.             strncat(name,p,80-strlen(name));
  3613. #endif /* OS2 */
  3614.             r_addr.sin_family = host->h_addrtype;
  3615. #ifdef HADDRLIST
  3616. #ifdef h_addr
  3617.             /* This is for trying multiple IP addresses - see <netdb.h> */
  3618.             if (!(host->h_addr_list))
  3619.               return(-1);
  3620.             bcopy(host->h_addr_list[0],
  3621.                   (caddr_t)&r_addr.sin_addr,
  3622.                   host->h_length
  3623.                   );
  3624. #else
  3625.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3626. #endif /* h_addr */
  3627. #else  /* HADDRLIST */
  3628.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3629. #endif /* HADDRLIST */
  3630. #ifndef EXCELAN
  3631.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  3632. #endif /* EXCELAN */
  3633.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  3634.                   (caddr_t)&r_addr.sin_addr);
  3635.             debug(F111,"BCOPY","host->h_length",host->h_length);
  3636.         }
  3637.     }
  3638. #endif /* NOMHHOST */
  3639.  
  3640.     if (!dns) {
  3641. #ifdef INADDRX
  3642. /* inet_addr() is of type struct in_addr */
  3643.         struct in_addr ina;
  3644.         unsigned long uu;
  3645.         debug(F100,"netopen gethostbyname == NULL: INADDRX","",0);
  3646.         ina = inet_addr(namecopy);
  3647.         uu = *(unsigned int *)&ina;
  3648. #else /* Not INADDRX */
  3649. /* inet_addr() is unsigned long */
  3650.         unsigned long uu;
  3651.         debug(F100,"netopen gethostbyname == NULL: Not INADDRX","",0);
  3652.         uu = inet_addr(namecopy);
  3653. #endif /* INADDRX */
  3654.         debug(F101,"netopen uu","",uu);
  3655.         if (
  3656. #ifdef INADDR_NONE
  3657.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  3658. #else   /* INADDR_NONE */
  3659.             uu != ((unsigned long)-1)
  3660. #endif /* INADDR_NONE */
  3661.             ) {
  3662.             r_addr.sin_addr.s_addr = uu;
  3663.             r_addr.sin_family = AF_INET;
  3664.         } else {
  3665.             fprintf(stderr, "Can't get address for %s\n", namecopy);
  3666. #ifdef TGVORWIN
  3667.             debug(F101,"netopen can't get address","",socket_errno);
  3668. #else
  3669.             debug(F101,"netopen can't get address","",errno);
  3670. #endif /* TGVORWIN */
  3671.             errno = 0;                  /* Rather than mislead */
  3672.             return(-1);
  3673.         }
  3674.     }
  3675.  
  3676.     /* Get a file descriptor for the connection. */
  3677.  
  3678.     r_addr.sin_port = service->s_port;
  3679.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  3680.     debug(F110,"netopen trying",ipaddr,0);
  3681.     if (!quiet && *ipaddr) {
  3682.         printf(" Trying %s... ", ipaddr);
  3683.         fflush(stdout);
  3684.     }
  3685.  
  3686.     /* Loop to try additional IP addresses, if any. */
  3687.  
  3688.     do {
  3689. #ifdef EXCELAN
  3690.         send_socket.sin_family = AF_INET;
  3691.         send_socket.sin_addr.s_addr = 0;
  3692.         send_socket.sin_port = 0;
  3693.         if ((ttyfd = socket(SOCK_STREAM, (struct sockproto *)0,
  3694.                             &send_socket, SO_REUSEADDR)) < 0)
  3695. #else  /* EXCELAN */
  3696. #ifdef NT
  3697. #ifdef COMMENT_X
  3698.        /*
  3699.          Must make sure that all sockets are opened in
  3700.          Non-overlapped mode since we use the standard
  3701.          C RTL functions to read and write data.
  3702.          But it doesn't seem to work as planned.
  3703.        */
  3704.           {
  3705.               int optionValue = SO_SYNCHRONOUS_NONALERT;
  3706.               if (setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
  3707.                              (char *) &optionValue, sizeof(optionValue))
  3708.                   != NO_ERROR)
  3709.                 return(-1);
  3710.           }
  3711. #endif /* COMMENT */
  3712. #endif /* NT */
  3713.  
  3714.         if ((ttyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  3715. #endif /* EXCELAN */
  3716.             {
  3717. #ifdef EXCELAN
  3718.                 experror("TCP socket error");
  3719. #else
  3720. #ifdef TGVORWIN
  3721. #ifdef OLD_TWG
  3722.                 errno = socket_errno;
  3723. #endif /* OLD_TWG */
  3724.                 socket_perror("TCP socket error");
  3725.                 debug(F101,"netopen socket error","",socket_errno);
  3726. #else
  3727.                 perror("TCP socket error");
  3728.                 debug(F101,"netopen socket error","",errno);
  3729. #endif /* TGVORWIN */
  3730. #endif /* EXCELAN */
  3731.                 return (-1);
  3732.             }
  3733.         errno = 0;
  3734.  
  3735. #ifdef RLOGCODE
  3736.        /* Not part of the RLOGIN RFC, but the BSD implementation     */
  3737.        /* requires that the client port be a priviliged port (<1024) */
  3738.        /* on a Unix system this would require SuperUser permissions  */
  3739.        /* thereby saying that the root of the Unix system has given  */
  3740.        /* permission for this connection to be created               */
  3741.        if (service->s_port == htons((unsigned short)RLOGIN_PORT)) {
  3742.            static unsigned short lport = 1024;  /* max reserved port */
  3743.            int s_errno;
  3744.  
  3745.            lport--;                     /* Make sure we do not reuse a port */
  3746.            if (lport == 512)
  3747.              lport = 1023;
  3748.  
  3749.            sin.sin_family = AF_INET;
  3750.            if (tcp_address) {
  3751. #ifdef INADDRX
  3752.                inaddrx = inet_addr(tcp_address);
  3753.                sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  3754. #else
  3755.                sin.sin_addr.s_addr = inet_addr(tcp_address);
  3756. #endif /* INADDRX */
  3757.            } else
  3758.              sin.sin_addr.s_addr = INADDR_ANY;
  3759.            while (1) {
  3760.                sin.sin_port = htons(lport);
  3761.                if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
  3762.                  break;
  3763. #ifdef OS2
  3764.                s_errno = socket_errno;
  3765.                if (s_errno && /* OS2 bind fails with 0, if already in use */
  3766. #ifdef NT
  3767.                    s_errno != WSAEADDRINUSE
  3768. #else
  3769.                    s_errno != SOCEADDRINUSE &&
  3770.                    s_errno != (SOCEADDRINUSE - SOCBASEERR)
  3771. #endif /* NT */
  3772.                    )
  3773. #else /* OS2 */
  3774. #ifdef TGVORWIN
  3775.                  if (socket_errno != EADDRINUSE)
  3776. #else
  3777.                  if (errno != EADDRINUSE)
  3778. #endif /* TGVORWIN */
  3779. #endif /* OS2 */
  3780.                    {
  3781.                        printf("\nBind failed with errno %d  for port %d.\n",
  3782. #ifdef OS2
  3783.                               s_errno
  3784. #else
  3785. #ifdef TGVORWIN
  3786.                               socket_errno
  3787. #else
  3788.                               errno
  3789. #endif /* TGVORWIN */
  3790. #endif /* OS2 */
  3791.                               , lport
  3792.                               );
  3793. #ifdef OS2
  3794.                        debug(F101,"rlogin bind failed","",s_errno);
  3795. #else
  3796. #ifdef TGVORWIN
  3797.                        debug(F101,"rlogin bind failed","",socket_errno);
  3798. #ifdef OLD_TWG
  3799.                        errno = socket_errno;
  3800. #endif /* OLD_TWG */
  3801.                        socket_perror("rlogin bind");
  3802. #else
  3803.                        debug(F101,"rlogin bind failed","",errno);
  3804.                        perror("rlogin bind");
  3805. #endif /* TGVORWIN */
  3806. #endif /* OS2 */
  3807.                        netclos();
  3808.                        return -1;
  3809.                    }
  3810.                lport--;
  3811.                if (lport == 512 /* lowest reserved port to use */ ) {
  3812.                    printf("\nNo reserved ports available.\n");
  3813.                    netclos();
  3814.                    return -1;
  3815.                }
  3816.            }
  3817.            debug(F101,"rlogin lport","",lport);
  3818.            ttnproto = NP_RLOGIN;
  3819.        } else
  3820. #endif /* RLOGCODE  */
  3821.  
  3822.        /* If a specific TCP address on the local host is desired we */
  3823.        /* must bind it to the socket.                               */
  3824. #ifndef datageneral
  3825.          if (tcp_address) {
  3826.              int s_errno;
  3827.  
  3828.              debug(F110,"netopen binding socket to",tcp_address,0);
  3829.              bzero((char *)&sin,sizeof(sin));
  3830.              sin.sin_family = AF_INET;
  3831. #ifdef INADDRX
  3832.              inaddrx = inet_addr(tcp_address);
  3833.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  3834. #else
  3835.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  3836. #endif /* INADDRX */
  3837.              sin.sin_port = 0;
  3838.              if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  3839.                  s_errno = socket_errno; /* Save error code */
  3840. #ifdef TCPIPLIB
  3841.                  socket_close(ttyfd);
  3842. #else /* TCPIPLIB */
  3843.                  close(ttyfd);
  3844. #endif /* TCPIPLIB */
  3845.                  ttyfd = -1;
  3846.                  wasclosed = 1;
  3847.                  errno = s_errno;       /* and report this error */
  3848.                  debug(F101,"netopen bind errno","",errno);
  3849.                  return(-1);
  3850.              }
  3851.          }
  3852. #endif /* datageneral */
  3853.  
  3854. /* Now connect to the socket on the other end. */
  3855.  
  3856. #ifdef EXCELAN
  3857.         if (connect(ttyfd, &r_addr) < 0)
  3858. #else
  3859. #ifdef NT
  3860.           WSASafeToCancel = 1;
  3861. #endif /* NT */
  3862.         if (connect(ttyfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  3863. #endif /* EXCELAN */
  3864.           {
  3865. #ifdef NT
  3866.               WSASafeToCancel = 0;
  3867. #endif /* NT */
  3868. #ifdef OS2
  3869.               i = socket_errno;
  3870. #else /* OS2 */
  3871. #ifdef TGVORWIN
  3872.               i = socket_errno;
  3873. #else
  3874.               i = errno;                /* Save error code */
  3875. #endif /* TGVORWIN */
  3876. #endif /* OS2 */
  3877. #ifdef RLOGCODE
  3878.               if (
  3879. #ifdef OS2
  3880.                  i && /* OS2 bind fails with 0, if already in use */
  3881. #ifdef NT
  3882.                  i == WSAEADDRINUSE
  3883. #else
  3884.                  (i == SOCEADDRINUSE ||
  3885.                  i == (SOCEADDRINUSE - SOCBASEERR))
  3886. #endif /* NT */
  3887. #else /* OS2 */
  3888. #ifdef TGVORWIN
  3889.                   socket_errno == EADDRINUSE
  3890. #else
  3891.                   errno == EADDRINUSE
  3892. #endif /* TGVORWIN */
  3893. #endif /* OS2 */
  3894.                   && ttnproto == NP_RLOGIN) {
  3895. #ifdef TCPIPLIB
  3896.                    socket_close(ttyfd); /* Close it. */
  3897. #else
  3898.                    close(ttyfd);
  3899. #endif /* TCPIPLIB */
  3900.                    continue;            /* Try a different lport */
  3901.                }
  3902. #endif /* RLOGCODE */
  3903. #ifdef HADDRLIST
  3904. #ifdef h_addr
  3905.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  3906.                   perror("");
  3907.                   host->h_addr_list++;
  3908.                   bcopy(host->h_addr_list[0],
  3909.                         (caddr_t)&r_addr.sin_addr,
  3910.                         host->h_length);
  3911.  
  3912.                   ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  3913.                   debug(F110,"netopen h_addr_list",ipaddr,0);
  3914.                   if (!quiet && *ipaddr) {
  3915.                       printf(" Trying %s... ", ipaddr);
  3916.                       fflush(stdout);
  3917.                   }
  3918. #ifdef TCPIPLIB
  3919.                   socket_close(ttyfd); /* Close it. */
  3920. #else
  3921.                   close(ttyfd);
  3922. #endif /* TCPIPLIB */
  3923.                   continue;
  3924.               }
  3925. #endif /* h_addr */
  3926. #endif  /* HADDRLIST */
  3927.               netclos();
  3928.               ttyfd = -1;
  3929.               wasclosed = 1;
  3930.               ttnproto = NP_NONE;
  3931.               errno = i;                /* And report this error */
  3932. #ifdef EXCELAN
  3933.               if (errno) experror("netopen connect");
  3934. #else
  3935. #ifdef TGVORWIN
  3936.               debug(F101,"netopen connect error","",socket_errno);
  3937.               /* if (errno) socket_perror("netopen connect"); */
  3938. #ifdef OLD_TWG
  3939.               errno = socket_errno;
  3940. #endif /* OLD_TWG */
  3941.               socket_perror("netopen connect");
  3942. #else /* TGVORWIN */
  3943.               debug(F101,"netopen connect errno","",errno);
  3944. #ifdef VMS
  3945.               perror("\r\nFailed");
  3946. #else
  3947.               perror("Failed");
  3948. #endif /* VMS */
  3949. #ifdef DEC_TCPIP
  3950.               perror("netopen connect");
  3951. #endif /* DEC_TCPIP */
  3952. #ifdef CMU_TCPIP
  3953.               perror("netopen connect");
  3954. #endif /* CMU_TCPIP */
  3955. #endif /* TGVORWIN */
  3956. #endif /* EXCELAN */
  3957.               return(-1);
  3958.           }
  3959. #ifdef NT
  3960.         WSASafeToCancel = 0;
  3961. #endif /* NT */
  3962.         isconnect = 1;
  3963.     } while (!isconnect);
  3964.  
  3965.  
  3966.     /* There are certain magic port numbers that when used require */
  3967.     /* the use of specific protocols.  Check this now before we    */
  3968.     /* set the SO_OOBINLINE state or we might get it wrong.        */
  3969.     x = ntohs((unsigned short)service->s_port);
  3970.     svcnum = x;
  3971.     /* See if the service is TELNET. */
  3972.     if (x == TELNET_PORT) {
  3973.         if (ttnproto != NP_TCPRAW)      /* Yes, so if raw port not requested */
  3974.           ttnproto = NP_TELNET;         /* select TELNET protocol. */
  3975.     }
  3976. #ifdef RLOGCODE
  3977.     else if (x == RLOGIN_PORT) {
  3978.         ttnproto = NP_RLOGIN;
  3979.     }
  3980. #ifdef CK_KERBEROS
  3981.     /* There is no good way to do this.  If the user didn't tell    */
  3982.     /* which one to use up front.  We may guess wrong if the user   */
  3983.     /* has both Kerberos versions installed and valid TGTs for each */
  3984.     else if (x == KLOGIN_PORT &&
  3985.              ttnproto != NP_K4LOGIN &&
  3986.              ttnproto != NP_K5LOGIN) {
  3987.         if (ck_krb5_is_installed() &&
  3988.             ck_krb5_is_tgt_valid())
  3989.           ttnproto = NP_K5LOGIN;
  3990.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  3991.           ttnproto = NP_K4LOGIN;
  3992.         else
  3993.           ttnproto = NP_K4LOGIN;
  3994.     } else if (x == EKLOGIN_PORT &&
  3995.                ttnproto != NP_EK4LOGIN &&
  3996.                ttnproto != NP_EK5LOGIN) {
  3997.         if (ck_krb5_is_installed() && ck_krb5_is_tgt_valid())
  3998.           ttnproto = NP_EK5LOGIN;
  3999.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4000.           ttnproto = NP_EK4LOGIN;
  4001.         else
  4002.           ttnproto = NP_EK4LOGIN;
  4003.     }
  4004. #endif /* CK_KERBEROS */
  4005. #endif /* RLOGCODE */
  4006. #ifdef IKS_OPTION
  4007.     else if (x == KERMIT_PORT) {        /* IKS uses Telnet protocol */
  4008.         if (ttnproto == NP_NONE)
  4009.           ttnproto = NP_KERMIT;
  4010.     }
  4011. #endif /* IKS_OPTION */
  4012.  
  4013. #ifdef SO_OOBINLINE
  4014. /*
  4015.   The symbol SO_OOBINLINE is not known to Ultrix 2.0.
  4016.   It means "leave out of band data inline".  The normal value is 0x0100,
  4017.   but don't try this on systems where the symbol is undefined.
  4018. */
  4019. /*
  4020.   Note from Jeff Altman: 12/13/95
  4021.   In implementing rlogin protocol I have come to the conclusion that it is
  4022.   a really bad idea to read out-of-band data inline.
  4023.   At least Windows and OS/2 does not handle this well.
  4024.   And if you need to know that data is out-of-band, then it becomes
  4025.   absolutely pointless.
  4026.  
  4027.   Therefore, at least on OS2 and Windows (NT) I have changed the value of
  4028.   on to 0, so that out-of-band data stays out-of-band.
  4029.  
  4030.   12/18/95
  4031.   Actually, OOB data should be read inline when possible.  Especially with
  4032.   protocols that don't care about the Urgent flag.  This is true with Telnet.
  4033.   With Rlogin, you need to be able to catch OOB data.  However, the best
  4034.   way to do this is to set a signal handler on SIGURG.  This isn't possible
  4035.   on OS/2 and Windows.  But it is in UNIX.  We will also need OOB data for
  4036.   FTP so better create a general mechanism.
  4037.  
  4038.   The reason for making OOB data be inline is that the standard ttinc/ttoc
  4039.   calls can be used for reading that data on UNIX systems.  If we didn't
  4040.   have the OOBINLINE option set then we would have to use recv(,MSG_OOB)
  4041.   to read it.
  4042. */
  4043. #ifdef RLOGCODE
  4044. #ifdef TCPIPLIB
  4045.     if (ttnproto == NP_RLOGIN  ||
  4046. #ifdef CK_KERBEROS
  4047.         ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  4048.         ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN ||
  4049. #endif /* CK_KERBEROS */
  4050.         ttnproto == NP_FTP)
  4051.       on = 0;
  4052. #else /* TCPIPLIB */
  4053.     if (ttnproto == NP_RLOGIN
  4054. #ifdef CK_KERBEROS
  4055.          || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4056.          || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4057. #endif /* CK_KERBEROS */
  4058.          ) {
  4059.         debug(F100,"Installing rlogoobh on SIGURG","",0);
  4060.         signal(SIGURG, rlogoobh);
  4061.         on = 0;
  4062.     } else
  4063. #ifdef FTPCODE
  4064.       if (ttnproto == NP_FTP) {
  4065.           debug(F100,"Installing ftpoobh on SIGURG","",0);
  4066.           signal(SIGURG, ftpoobh);
  4067.           on = 0;
  4068.       } else
  4069. #endif /* FTPCODE */
  4070.         {
  4071.             debug(F100,"Ignoring SIGURG","",0);
  4072.             signal(SIGURG, SIG_DFL);
  4073.         }
  4074. #endif /* TCPIPLIB */
  4075. #endif /* RLOGCODE */
  4076.  
  4077. #ifdef datageneral
  4078.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4079. #else
  4080. #ifdef BSD43
  4081.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4082. #else
  4083. #ifdef OSF1
  4084.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4085. #else
  4086. #ifdef POSIX
  4087.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4088. #else
  4089. #ifdef MOTSV88R4
  4090.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4091. #else
  4092. #ifdef SOLARIS
  4093. /*
  4094.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  4095.   compiling and working fine on all the others, so best not to change it.
  4096. */
  4097.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4098. #else
  4099. #ifdef OSK
  4100.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4101. #else
  4102. #ifdef OS2
  4103.     {
  4104.         int rc;
  4105.         rc = setsockopt(ttyfd,
  4106.                         SOL_SOCKET,
  4107.                         SO_OOBINLINE,
  4108.                         (char *) &on,
  4109.                         sizeof on
  4110.                         );
  4111.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  4112.     }
  4113. #else
  4114. #ifdef VMS /* or, at least, VMS with gcc */
  4115.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4116. #else
  4117.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  4118. #endif /* VMS */
  4119. #endif /* OS2 */
  4120. #endif /* OSK */
  4121. #endif /* SOLARIS */
  4122. #endif /* MOTSV88R4 */
  4123. #endif /* POSIX */
  4124. #endif /* BSD43 */
  4125. #endif /* OSF1 */
  4126. #endif /* datageneral */
  4127. #endif /* SO_OOBINLINE */
  4128.  
  4129. #ifndef NOTCPOPTS
  4130. #ifndef datageneral
  4131. #ifdef SOL_SOCKET
  4132. #ifdef TCP_NODELAY
  4133.     no_delay(tcp_nodelay);
  4134. #endif /* TCP_NODELAY */
  4135. #ifdef SO_KEEPALIVE
  4136.     keepalive(tcp_keepalive);
  4137. #endif /* SO_KEEPALIVE */
  4138. #ifdef SO_LINGER
  4139.     ck_linger(tcp_linger, tcp_linger_tmo);
  4140. #endif /* SO_LINGER */
  4141. #ifdef SO_SNDBUF
  4142.     sendbuf(tcp_sendbuf);
  4143. #endif /* SO_SNDBUF */
  4144. #ifdef SO_RCVBUF
  4145.     recvbuf(tcp_recvbuf);
  4146. #endif /* SO_RCVBUF */
  4147. #endif /* SOL_SOCKET */
  4148. #endif /* datageneral */
  4149. #endif /* NOTCPOPTS */
  4150.  
  4151. #ifdef NON_BLOCK_IO
  4152.     on = 1;
  4153.     x = socket_ioctl(ttyfd,FIONBIO,&on);
  4154.     debug(F101,"netopen FIONBIO","",x);
  4155. #endif /* NON_BLOCK_IO */
  4156.  
  4157. #ifdef NT_TCP_OVERLAPPED
  4158.     OverlappedWriteInit();
  4159.     OverlappedReadInit();
  4160. #endif /* NT_TCP_OVERLAPPED */
  4161.  
  4162.     ttnet = nett;                       /* TCP/IP (sockets) network */
  4163.  
  4164. #ifndef datageneral
  4165.     /* Find out our own IP address. */
  4166.     /* We need the l_addr structure for [E]KLOGIN. */
  4167.     l_slen = sizeof(l_addr);
  4168.     bzero((char *)&l_addr, l_slen);
  4169. #ifndef EXCELAN
  4170.     if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  4171.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  4172.         ckstrncpy(myipaddr, s, 20);
  4173.         debug(F110,"getsockname",myipaddr,0);
  4174.     }
  4175. #endif /* EXCELAN */
  4176. #endif /* datageneral */
  4177.  
  4178. /*
  4179.   This is really only needed for Kerberos IV but is useful information in any
  4180.   case.  If we connect to a name that is really a pool, we need to get the
  4181.   name of the machine we are actually connecting to for K4 to authenticate
  4182.   properly.  This way we also update the names properly.
  4183.  
  4184.   Note: This does not work on Windows 95 or Windows NT 3.5x.  This is because
  4185.   of the Microsoft implementation of gethostbyaddr() in both Winsock 1.1
  4186.   and Winsock 2.0 on those platforms.  Their algorithm is:
  4187.  
  4188.   1. Check the HOSTENT cache.
  4189.   2. Check the HOSTS file at %SystemRoot%\System32\DRIVERS\ETC.
  4190.   3. Do a DNS query if the DNS server is configured for name resolution.
  4191.   4. Do an additional NetBIOS remote adapter status to an IP address for its
  4192.      NetBIOS name table. This step is specific only to the Windows NT version
  4193.      3.51 implementation.
  4194.  
  4195.   The problem is the use of the HOSTENT cache.  It means that gethostbyaddr()
  4196.   can not be used to resolve the real name of machine if it was originally
  4197.   accessed by an alias used to represent a cluster.
  4198. */
  4199.      if (tcp_rdns && dns || tcp_rdns == SET_ON
  4200. #ifdef CK_KERBEROS
  4201.          || tcp_rdns == SET_AUTO &&
  4202.           (ck_krb5_is_installed() || ck_krb4_is_installed())
  4203. #endif /* CK_KERBEROS */
  4204.          ) {
  4205. #ifdef NT
  4206.         if (isWin95())
  4207.           sleep(1);
  4208. #endif /* NT */
  4209.         if (!quiet) {
  4210.             printf(" Reverse DNS Lookup... ");
  4211.             fflush(stdout);
  4212.         }
  4213.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  4214.             char * s;
  4215.             debug(F100,"netopen gethostbyname != NULL","",0);
  4216.             if (!quiet) {
  4217.                 printf("(OK)\n");
  4218.                 fflush(stdout);
  4219.             }
  4220.             s = host->h_name;
  4221.             if (!s) {                   /* This can happen... */
  4222.                 debug(F100,"netopen host->h_name is NULL","",0);
  4223.                 s = "";
  4224.             }
  4225.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  4226.             /* The compiler says "Integral value implicitly converted to */
  4227.             /* pointer in assignment."  The prototype is right there */
  4228.             /* in <arpa/inet.h> so what's the problem? */
  4229.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  4230.             if (!*s) {                  /* No name so substitute the address */
  4231.                 debug(F100,"netopen host->h_name is empty","",0);
  4232.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  4233.                 if (!s)                 /* Trust No 1 */
  4234.                   s = "";
  4235.                 if (*s) {               /* If it worked, use this string */
  4236.                     ckstrncpy(ipaddr,s,20);
  4237.                 }
  4238.                 s = ipaddr;             /* Otherwise stick with the IP */
  4239.                 if (!*s)                /* or failing that */
  4240.                   s = namecopy;         /* the name we were called with. */
  4241.             }
  4242.             if (*s) {                   /* Copying into our argument? */
  4243.                 ckstrncpy(name,s,80);   /* Bad Bad Bad */
  4244.                 strncat(name,":",80-strlen(name));
  4245.                 strncat(name,p,80-strlen(name));
  4246.             }
  4247.             if (!quiet && *s
  4248. #ifndef NOICP
  4249.                 && !doconx
  4250. #endif /* NOICP */
  4251.                 ) {
  4252.                 printf(" %s connected on port %s\n",s,p);
  4253. #ifdef BETATEST
  4254.                 /* This is simply for testing the DNS entries */
  4255.                 if (host->h_aliases) {
  4256.                     char ** a = host->h_aliases;
  4257.                     while (*a) {
  4258.                         printf(" alias => %s\n",*a);
  4259.                         a++;
  4260.                     }
  4261.                 }
  4262. #endif /* BETATEST */
  4263.             }
  4264.         } else {
  4265.             if (!quiet) printf("Failed.\n");
  4266.         }
  4267.     } else if (!quiet) printf("(OK)\n");
  4268.     if (!quiet) fflush(stdout);
  4269.  
  4270.     /* This should already have been done but just in case */
  4271.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4272.  
  4273. #ifdef CK_AUTHENTICATION
  4274.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  4275.     ck_auth_init((host && host->h_name && host->h_name[0]) ?
  4276.                 (char *)host->h_name : ipaddr,
  4277.                 ipaddr,
  4278.                 uidbuf,
  4279.                 ttyfd
  4280.                 );
  4281. #endif /* CK_AUTHENTICATION */
  4282. #ifdef CK_SSL
  4283.     if (ck_ssleay_is_installed()) {
  4284.         if ( ck_ssl_outgoing(ttyfd) < 0 ) {
  4285.             netclos();
  4286.             return(-1);
  4287.         }
  4288.     }
  4289. #endif /* CK_SSL */
  4290.  
  4291. #ifdef RLOGCODE
  4292.     if (ttnproto == NP_RLOGIN
  4293. #ifdef CK_KERBEROS
  4294.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4295.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4296. #endif /* CK_KERBEROS */
  4297.         ) {                             /* Similar deal for rlogin */
  4298.         if (rlog_ini(((host && host->h_name && host->h_name[0]) ?
  4299.                       (CHAR *)host->h_name : (CHAR *)ipaddr),
  4300.                      service->s_port,
  4301.                      &l_addr,&r_addr
  4302.                      ) < 0) {
  4303.             debug(F100,"rlogin initialization failed","",0);
  4304.             netclos();
  4305.             return(-1);
  4306.         }
  4307.     } else
  4308. #endif /* RLOGCODE */
  4309.     if (tn_ini() < 0)                   /* Start Telnet negotiations. */
  4310. #ifdef OS2
  4311.       if (ttchk() < 0)                  /* Failed - check connection. */
  4312. #endif /* OS2 */
  4313.         return(-1);                     /* Gone, so open failed.  */
  4314.  
  4315.     debug(F101,"netopen service","",svcnum);
  4316.     debug(F110,"netopen name",name,0);
  4317.  
  4318.     if (*lcl < 0)                       /* Local mode. */
  4319.       *lcl = 1;
  4320. #endif /* TCPSOCKET */
  4321.     return(0);                          /* Done. */
  4322. }
  4323.  
  4324. /*  N E T C L O S  --  Close current network connection.  */
  4325.  
  4326. #ifndef NOICP
  4327. _PROTOTYP(VOID slrestor,(VOID));
  4328. #ifdef CK_SSL
  4329. int tls_norestore = 0;
  4330. #endif /* CK_SSL */
  4331. #endif /* NOICP */
  4332.  
  4333. int
  4334. netclos() {
  4335.     static int close_in_progress = 0;
  4336.     int x = 0;
  4337.     debug(F101,"netclos","",ttyfd);
  4338.  
  4339. #ifdef NETLEBUF
  4340.     if (!tt_push_inited)
  4341.       le_init();
  4342. #endif /* NETLEBUF */
  4343.  
  4344.     if (ttyfd == -1)                    /* Was open? */
  4345.       return(0);                        /* Wasn't. */
  4346.  
  4347.     if (close_in_progress)
  4348.       return(0);
  4349.     close_in_progress = 1;              /* Remember */
  4350.  
  4351. #ifndef NOICP
  4352.     /* This function call should not be here since this is a direct call */
  4353.     /* from an I/O routine to a user interface level function.  However, */
  4354.     /* the reality is that we do not have pure interfaces.  If we ever   */
  4355.     /* decide to clean this up the UI level should assign this function  */
  4356.     /* via a pointer assignment.  - Jeff 9/10/1999                       */
  4357. #ifdef CK_SSL
  4358.     if (!tls_norestore)
  4359. #endif /* CK_SSL */
  4360.       slrestor();
  4361. #endif /* NOICP */
  4362. #ifndef OS2
  4363.     if (ttyfd > -1)                     /* Was. */
  4364. #endif /* OS2 */
  4365.       {
  4366. #ifdef TNCODE
  4367.           tn_push();                    /* Place any waiting data into input*/
  4368.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  4369.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  4370.           tn_reset();                   /* The Reset Telnet Option table.  */
  4371. #endif /* TNCODE */
  4372. #ifdef CK_SSL
  4373.           if (ssl_active_flag) {
  4374.               if (ssl_debug_flag)
  4375.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4376.               SSL_shutdown(ssl_con);
  4377.               SSL_free(ssl_con);
  4378.               ssl_con = NULL;
  4379.               ssl_active_flag = 0;
  4380.           }
  4381.           if (tls_active_flag) {
  4382.               if (ssl_debug_flag)
  4383.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4384.               SSL_shutdown(tls_con);
  4385.               SSL_free(tls_con);
  4386.               tls_con = NULL;
  4387.               tls_active_flag = 0;
  4388.           }
  4389. #endif /* CK_SSL */
  4390. #ifdef VMS
  4391.           ck_cancio();                  /* Cancel any outstanding reads. */
  4392. #endif /* VMS */
  4393. #ifdef TCPIPLIB
  4394.           x = socket_close(ttyfd);      /* Close it. */
  4395. #else
  4396. #ifndef OS2
  4397. #ifdef IBMX25
  4398.         if (ttnet == NET_IX25) {
  4399.             /* riehm: should send a disc_req - but only if link is still OK */
  4400.             x = x25clear();
  4401.             close(ttyfd);
  4402.             if (x25serverfd) {
  4403.                   /* we were the passive client of a server, now we
  4404.                    * go back to being the normal client.
  4405.                    * I hope that kermit can cope with the logic that
  4406.                    * there can still be a connection after netclos
  4407.                    * has been called.
  4408.                    */
  4409.                   ttyfd = x25serverfd;
  4410.                   x25serverfd = 0;
  4411.                   /*
  4412.                    * need to close the server connection too - because
  4413.                    * all file descriptors connected to the NPI have the
  4414.                    * same status.
  4415.                    *
  4416.                    * The problem is that any waiting connections get
  4417.                    * lost, the client doesn't realise, and hangs.
  4418.                    */
  4419.                   netclos();
  4420.               }
  4421.             x25_state = X25_CLOSED;     /* riehm: dead code? */
  4422.         } else
  4423. #endif /* IBMX25 */
  4424.           x = close(ttyfd);
  4425. #endif /* OS2 */
  4426. #endif /* TCPIPLIB */
  4427.       }
  4428.     ttyfd = -1;                         /* Mark it as closed. */
  4429.     wasclosed = 1;
  4430. #ifdef TNCODE
  4431.     debug(F100,"netclose setting tn_init = 0","",0);
  4432.     tn_init = 0;                        /* Remember about telnet protocol... */
  4433.     sstelnet = 0;                       /* Client-side Telnet */
  4434. #ifdef CK_FORWARD_X
  4435.     fwdx_close_all();                   /* Shut down any Forward X sockets */
  4436. #endif /* CK_FORWARD_X */
  4437. #endif /* TNCODE */
  4438.     *ipaddr = '\0';                     /* Zero the IP address string */
  4439.     tcp_incoming = 0;                   /* No longer incoming */
  4440.     /* Don't reset ttnproto so that we can remember which protocol is in use */
  4441.  
  4442. #ifdef TCPIPLIB
  4443. /*
  4444.   Empty the internal buffers so they won't be used as invalid input on
  4445.   the next connect attempt (rlogin).
  4446. */
  4447.     ttibp = 0;
  4448.     ttibn = 0;
  4449. #endif /* TCPIPLIB */
  4450. #ifdef CK_KERBEROS
  4451.     /* If we are automatically destroying Kerberos credentials on Close */
  4452.     /* do it now. */
  4453. #ifdef KRB4
  4454.     if (krb4_autodel == KRB_DEL_CL) {
  4455.         extern struct krb_op_data krb_op;
  4456.         krb_op.version = 4;
  4457.         krb_op.cache = NULL;
  4458.         ck_krb4_destroy(&krb_op);
  4459.     }
  4460. #endif /* KRB4 */
  4461. #ifdef KRB5
  4462.     if (krb5_autodel == KRB_DEL_CL) {
  4463.         extern struct krb_op_data krb_op;
  4464.         extern char * krb5_d_cc;
  4465.         krb_op.version = 5;
  4466.         krb_op.cache = krb5_d_cc;
  4467.         ck_krb5_destroy(&krb_op);
  4468.     }
  4469. #endif /* KRB5 */
  4470. #endif /* CK_KERBEROS */
  4471.     close_in_progress = 0;              /* Remember we are done. */
  4472.     return(x);
  4473. }
  4474.  
  4475. #ifdef OS2
  4476. int
  4477. os2socketerror( int s_errno ) {
  4478.     switch (s_errno) {
  4479.       case 0:                /* NO ERROR */
  4480.         debug(F100,"os2socketerror NOERROR","",0);
  4481.         return(0);
  4482. #ifdef OS2ONLY
  4483.       case EOS2ERR:
  4484.         debug(F100,"os2socketerror EOS2ERR","",0);
  4485.         return(0);
  4486.       case ENOENT:            /* ENOENT */
  4487.         debug(F100,"os2socketerror ENOENT","",0);
  4488.         return(0);
  4489.       case EPASTEOF:            /* EPASTEOF */
  4490.         debug(F100,"os2socketerror EPASTEOF","",0);
  4491.         return(0);
  4492. #endif /* OS2ONLY */
  4493. #ifdef NT
  4494.       case WSAECONNRESET:
  4495. #else /* NT */
  4496.       case SOCECONNRESET:
  4497.       case SOCECONNRESET - SOCBASEERR:
  4498. #endif /* NT */
  4499.         debug(F100,"os2socketerror ECONRESET","",0);
  4500.         tn_debug("ECONRESET");
  4501.         netclos();              /* *** *** */
  4502.         return(-1);             /* Connection is broken. */
  4503. #ifdef NT
  4504.       case WSAECONNABORTED:
  4505. #else /* NT */
  4506.       case SOCECONNABORTED:
  4507.       case SOCECONNABORTED - SOCBASEERR:
  4508. #endif /* NT */
  4509.         debug(F100,"os2socketerror ECONNABORTED","",0);
  4510.         tn_debug("ECONNABORTED");
  4511.         netclos();              /* *** *** */
  4512.         return(-1);             /* Connection is broken. */
  4513. #ifdef NT
  4514.       case WSAENETRESET:
  4515. #else /* NT */
  4516.       case SOCENETRESET:
  4517.       case SOCENETRESET - SOCBASEERR:
  4518. #endif /* NT */
  4519.         debug(F100,"os2socketerror ENETRESET","",0);
  4520.         tn_debug("ENETRESET");
  4521.         netclos();              /* *** *** */
  4522.         return(-1);             /* Connection is broken. */
  4523. #ifdef NT
  4524.       case WSAENOTCONN:
  4525. #else /* NT */
  4526.       case SOCENOTCONN:
  4527.       case SOCENOTCONN - SOCBASEERR:
  4528. #endif /* NT */
  4529.         debug(F100,"os2socketerror ENOTCONN","",0);
  4530.         tn_debug("ENOTCONN");
  4531.         netclos();              /* *** *** */
  4532.         return(-1);             /* Connection is broken. */
  4533. #ifdef NT
  4534.       case WSAESHUTDOWN:
  4535.         debug(F100,"os2socketerror ESHUTDOWN","",0);
  4536.         tn_debug("ESHUTDOWN");
  4537.         netclos();              /* *** *** */
  4538.         return(-1);             /* Connection is broken. */
  4539. #endif /* NT */
  4540. #ifdef NT
  4541.       case WSAEWOULDBLOCK:
  4542. #else
  4543.       case SOCEWOULDBLOCK:
  4544.       case SOCEWOULDBLOCK - SOCBASEERR:
  4545. #endif /* NT */
  4546.         debug(F100,"os2socketerror EWOULDBLOCK","",0);
  4547.         return(0);
  4548. #ifdef NT
  4549.       case ERROR_IO_INCOMPLETE:
  4550.       case ERROR_IO_PENDING:
  4551.       case ERROR_OPERATION_ABORTED:
  4552.         return(0);
  4553. #endif /* NT */
  4554.       default:
  4555.         return(-2);
  4556.     }
  4557.     return(0);
  4558. }
  4559. #endif /* OS2 */
  4560.  
  4561. /*  N E T T C H K  --  Check if network up, and how many bytes can be read */
  4562. /*
  4563.   Returns number of bytes waiting, or -1 if connection has been dropped.
  4564. */
  4565. int                                     /* Check how many bytes are ready */
  4566. nettchk() {                             /* for reading from network */
  4567. #ifdef TCPIPLIB
  4568.     long count = 0;
  4569.     int x = 0;
  4570.     long y;
  4571.     char c;
  4572. #ifdef NT
  4573.     extern int ionoblock;               /* For Overlapped I/O */
  4574. #endif /* NT */
  4575.  
  4576.     debug(F101,"nettchk entry ttibn","",ttibn);
  4577.     debug(F101,"nettchk entry ttibp","",ttibp);
  4578.  
  4579. #ifdef NETLEBUF
  4580.     {
  4581.         int n = 0;
  4582.         if (ttpush >= 0)
  4583.           n++;
  4584.         n += le_inbuf();
  4585.         if (n > 0)
  4586.           return(n);
  4587.     }
  4588. #endif /* NETLEBUF */
  4589.  
  4590. #ifndef OS2
  4591. #ifndef BEBOX
  4592.     socket_errno = 0; /* This is a function call in NT, and BeOS */
  4593. #endif /* BEBOX */
  4594. #endif /* OS2 */
  4595.  
  4596.     if (ttyfd == -1) {
  4597.         debug(F100,"nettchk socket is closed","",0);
  4598.         return(-1);
  4599.     }
  4600. /*
  4601.   Note: this socket_ioctl() call does NOT return an error if the
  4602.   connection has been broken.  (At least not in MultiNet.)
  4603. */
  4604. #ifdef COMMENT
  4605. /*  Another trick that can be tried here is something like this: */
  4606.  
  4607.     if (ttnet == NET_TCPB) {
  4608.         char dummy;
  4609.         x = read(ttyfd,&dummy,0);       /* Try to read nothing */
  4610.         if (x < 0) {                    /* "Connection reset by peer" */
  4611.             perror("TCP/IP");           /* or somesuch... */
  4612.             ttclos(0);                  /* Close our end too. */
  4613.             return(-1);
  4614.         }
  4615.     }
  4616. #endif /* COMMENT */
  4617.  
  4618. #ifdef CK_SSL
  4619.     if (ssl_active_flag) {
  4620.         count = SSL_pending(ssl_con);
  4621.         if (count < 0) {
  4622.             debug(F111,"nettchk","SSL_pending error",count);
  4623.             netclos();
  4624.             return(-1);
  4625.         }
  4626. #ifdef COMMENT
  4627.         else if (count == 0) {
  4628.             int ch = netinc(-50);
  4629.             if ( ch >= 0 )
  4630.                 le_putchar((CHAR)(ch & 0xFF));
  4631.         }
  4632. #endif /* COMMENT */
  4633.     } else if (tls_active_flag) {
  4634.         count = SSL_pending(tls_con);
  4635.         if (count < 0) {
  4636.             debug(F111,"nettchk","TLS_pending error",count);
  4637.             netclos();
  4638.             return(-1);
  4639.         }
  4640. #ifdef COMMENT
  4641.         else if (count == 0) {
  4642.             int ch = netinc(-50);
  4643.             if ( ch >= 0 )
  4644.                 le_putchar((CHAR)(ch & 0xFF));
  4645.         }
  4646. #endif /* COMMENT */
  4647.     } else
  4648. #endif /* CK_SSL */
  4649.  
  4650.     if (socket_ioctl(ttyfd,FIONREAD,
  4651. #ifdef COMMENT
  4652.     /* Now we've changed the ioctl(..,..,x) prototype for DECC to (void *) */
  4653. #ifdef __DECC
  4654.     /* NOTE: "&count" might need to be "(char *)&count" in some settings. */
  4655.                      /* Cast needed for DECC 4.1 & later? */
  4656.                      /* Maybe, but __DECC_VER only exists in 5.0 and later */
  4657.                      (char *)
  4658. #endif /* __DECC */
  4659. #endif /* COMMENT */
  4660.                      &count
  4661.                      ) < 0) {
  4662.         debug(F101,"nettchk socket_ioctl error","",socket_errno);
  4663.         /* If the connection is gone, the connection is gone. */
  4664.         netclos();
  4665. #ifdef NT_TCP_OVERLAPPED
  4666.         /* Is there anything in the overlapped I/O buffers? */
  4667.         count += OverlappedDataWaiting();
  4668. #endif /* NT_TCP_OVERLAPPED */
  4669.         count += ttibn;
  4670.         return(count>0?count:-1);
  4671.     }
  4672.     debug(F101,"nettchk count","",count);
  4673. #ifdef NT_TCP_OVERLAPPED
  4674.     /* Is there anything in the overlapped I/O buffers? */
  4675.     count += OverlappedDataWaiting();
  4676.     debug(F101,"nettchk count w/overlapped","",count);
  4677. #endif /* NT_TCP_OVERLAPPED */
  4678.  
  4679. /* For the sake of efficiency, if there is still data in the ttibuf */
  4680. /* do not go to the bother of checking to see of the connection is  */
  4681. /* still valid.  The handle is still good, so just return the count */
  4682. /* of the bytes that we already have left to process.               */
  4683. #ifdef OS2
  4684.     if ( ttibn > 0 ) {
  4685.         debug(F101,"nettchk (ttibn > 0) returns","",count+ttibn);
  4686.         return(count+ttibn);
  4687.     } else {
  4688.         if ( ttibn == 0 )
  4689.             ttibp = 0;      /* reset for next read */
  4690.     }
  4691. #else /* OS2 */
  4692.     if ( ttibn ) {
  4693.         debug(F101,"nettchk returns","",count+ttibn);
  4694.         return(count+ttibn);
  4695.     }
  4696. #endif /* OS2 */
  4697.  
  4698. /*
  4699.   The following code works well in most settings, but messes things up in
  4700.   others, including CMU/Tek TCP/IP and UCX 2.0, where it somehow manages to
  4701.   make it impossible to ever make a new connection to the same host again with
  4702.   CONNECT, once it has been logged out from the first time.  Not even if you
  4703.   HANGUP first, or SET HOST<CR>, or SET LINE<CR>.  Reportedly, however, it
  4704.   does work OK in later releases of UCX.  But there is no way we can
  4705.   accommodate both old and new -- we might have static linking or dynamic
  4706.   linking, etc etc.  If we have static, I only have access to 2.0, where this
  4707.   doesn't work, etc etc blah blah.
  4708.  
  4709.   In the following lines, we define a symbol NOCOUNT for builds where we want
  4710.   to omit this code.  By default, it is omitted for CMU/Tek.  You can force
  4711.   omission of it for other combinations by defining NOCOUNT in CFLAGS.  You
  4712.   can force inclusion of this code, even for CMU/Tek, by including NONOCOUNT
  4713.   in CFLAGS.
  4714. */
  4715. #ifdef NONOCOUNT
  4716. #ifdef NOCOUNT
  4717. #undef NOCOUNT
  4718. #endif /* NOCOUNT */
  4719. #else
  4720. #ifndef NOCOUNT
  4721. #ifdef CMU_TCPIP
  4722. #define NOCOUNT
  4723. #endif /* CMU_TCPIP */
  4724. #endif /* NOCOUNT */
  4725. #endif /* NONOCOUNT */
  4726.  
  4727.     /* we know now that count >= 0 and that ttibn == 0 */
  4728.  
  4729.     if (count == 0
  4730. #ifdef CK_SSL
  4731.         && ttnproto != NP_SSL && ttnproto != NP_TLS
  4732.         && !tls_active_flag && !ssl_active_flag
  4733. #endif /* CK_SSL */
  4734. #ifdef RLOGCODE
  4735. #ifdef CK_KERBEROS
  4736.         && ttnproto != NP_EK4LOGIN && ttnproto != NP_EK5LOGIN
  4737. #endif /* CK_KERBEROS */
  4738. #endif /* RLOGCODE */
  4739.         ) {
  4740.         int s_errno = 0;
  4741. #ifdef OS2
  4742.         RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  4743. #endif /* OS2 */
  4744. #ifndef NOCOUNT
  4745. /*
  4746.   Here we need to tell the difference between a 0 count on an active
  4747.   connection, and a 0 count because the remote end of the socket broke the
  4748.   connection.  There is no mechanism in TGV MultiNet (or WIN/TCP?) to query
  4749.   the status of the connection, so we have to do a read.  -1 means there was
  4750.   no data available (socket_errno == EWOULDBLOCK), 0 means the connection is
  4751.   down.  But if, by chance, we actually get a character, we have to put it
  4752.   where it won't be lost.
  4753. */
  4754. #ifndef NON_BLOCK_IO
  4755.         y = 1;                          /* Turn on nonblocking reads */
  4756.         x = socket_ioctl(ttyfd,FIONBIO,&y);
  4757.         debug(F101,"nettchk FIONBIO","",x);
  4758. #endif /* NON_BLOCK_IO */
  4759. #ifdef NT_TCP_OVERLAPPED
  4760.         ionoblock = 1;                  /* For Overlapped I/O */
  4761. #endif /* NT_TCP_OVERLAPPED */
  4762. #ifdef OS2
  4763.         x = socket_read(ttyfd,&ttibuf[ttibp+ttibn],
  4764.                          TTIBUFL-ttibp-ttibn);  /* Returns -1 if no data */
  4765. #else /* OS2 */
  4766.         x = socket_read(ttyfd,&c,1);    /* Returns -1 if no data */
  4767. #endif /* OS2 */
  4768.         s_errno = socket_errno;         /* socket_errno may be a function */
  4769.         debug(F101,"nettchk socket_read","",x);
  4770.  
  4771. #ifndef NON_BLOCK_IO
  4772.         y = 0;                          /* Turn them back off */
  4773.         socket_ioctl(ttyfd,FIONBIO,&y);
  4774. #endif /* NON_BLOCK_IO */
  4775. #ifdef NT_TCP_OVERLAPPED
  4776.         ionoblock = 0;                  /* For Overlapped I/O */
  4777. #endif /* NT_TCP_OVERLAPPED */
  4778.  
  4779.         if (x == -1) {
  4780.             debug(F101,"nettchk socket_read errno","",s_errno);
  4781. #ifdef OS2
  4782.             if (os2socketerror(s_errno) < 0) {
  4783.                 ReleaseTCPIPMutex();
  4784.                 return(-1);
  4785.             }
  4786. #endif /* OS2 */
  4787.         } else if (x == 0) {
  4788.             debug(F100,"nettchk connection closed","",0);
  4789. #ifdef OS2
  4790.             ReleaseTCPIPMutex();
  4791. #endif /* OS2 */
  4792.             netclos();                  /* *** *** */
  4793.             return(-1);                 /* Connection is broken. */
  4794.         }
  4795.         if (x >= 1) {                   /* Oops, actually got a byte? */
  4796. #ifdef OS2
  4797.             /* In OS/2 we read directly into ttibuf[] */
  4798.             hexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
  4799.             ttibn += x;
  4800. #else /* OS2 */
  4801.             debug(F101,"nettchk socket_read char","",c);
  4802.             debug(F101,"nettchk ttibp","",ttibp);
  4803.             debug(F101,"nettchk ttibn","",ttibn);
  4804. /*
  4805.   In the case of Overlapped I/O the character would have come from
  4806.   the beginning of the buffer, so put it back.
  4807. */
  4808.             if (ttibp > 0) {
  4809.                 ttibp--;
  4810.                 ttibuf[ttibp] = c;
  4811.                 ttibn++;
  4812.             } else {
  4813.                 ttibuf[ttibp+ttibn] = c;
  4814.                 ttibn++;
  4815.             }
  4816. #endif /* OS2 */
  4817.         }
  4818. #ifdef OS2
  4819.         ReleaseTCPIPMutex();
  4820. #endif /* OS2 */
  4821. #else /* NOCOUNT */
  4822.         if (ttnet == NET_TCPB) {
  4823.             char dummy;
  4824.             x = read(ttyfd,&dummy,0);   /* Try to read nothing */
  4825.             if (x < 0) {                /* "Connection reset by peer" */
  4826.                 perror("TCP/IP");       /* or somesuch... */
  4827. #ifdef OS2
  4828.                 ReleaseTCPIPMutex();
  4829. #endif /* OS2 */
  4830.                 ttclos(0);              /* Close our end too. */
  4831.                 return(-1);
  4832.             }
  4833.         }
  4834. #endif /* NOCOUNT */
  4835. #ifdef OS2
  4836.         ReleaseTCPIPMutex();
  4837. #endif /* OS2 */
  4838.     }
  4839. #ifdef CK_KERBEROS
  4840. #ifdef KRB4
  4841.     if (ttnproto == NP_EK4LOGIN)
  4842.       count += krb4_des_avail(ttyfd);
  4843. #endif /* KRB4 */
  4844. #ifdef KRB5
  4845.     if (ttnproto == NP_EK5LOGIN)
  4846.       count += krb5_des_avail(ttyfd);
  4847. #endif /* KRB5 */
  4848. #endif /* CK_KERBEROS */
  4849.  
  4850.     debug(F101,"nettchk returns","",count+ttibn);
  4851.     return(count + ttibn);
  4852.  
  4853. #else /* Not TCPIPLIB */
  4854. /*
  4855.   UNIX just uses ttchk(), in which the ioctl() calls on the file descriptor
  4856.   seem to work OK.
  4857. */
  4858.     return(0);
  4859. #endif /* TCPIPLIB */
  4860. /*
  4861.   But what about X.25?
  4862. */
  4863. }
  4864.  
  4865. #ifndef OS2
  4866. VOID
  4867. nettout(i) int i; {                     /* Catch the alarm interrupts */
  4868.     debug(F100,"nettout caught timeout","",0);
  4869.     ttimoff();
  4870.     cklongjmp(njbuf, -1);
  4871. }
  4872. #endif /* !OS2 */
  4873.  
  4874. #ifdef TCPIPLIB
  4875.  
  4876. VOID
  4877. #ifdef CK_ANSIC
  4878. donetinc(void * threadinfo)
  4879. #else /* CK_ANSIC */
  4880. donetinc(threadinfo) VOID * threadinfo;
  4881. #endif /* CK_ANSIC */
  4882. /* donetinc */ {
  4883. #ifdef IKSD
  4884.     extern int inserver;
  4885. #endif /* IKSD */
  4886. #ifdef NTSIG
  4887.     extern int TlsIndex;
  4888.     setint();
  4889.     if (threadinfo) {                   /* Thread local storage... */
  4890.         TlsSetValue(TlsIndex,threadinfo);
  4891.     }
  4892. #endif /* NTSIG */
  4893. #ifdef CK_LOGIN
  4894. #ifdef NT
  4895. #ifdef IKSD
  4896.     if (inserver)
  4897.       setntcreds();
  4898. #endif /* IKSD */
  4899. #endif /* NT */
  4900. #endif /* CK_LOGIN */
  4901.     while (1) {
  4902.         if (ttbufr() < 0)               /* Keep trying to refill it. */
  4903.           break;                        /* Till we get an error. */
  4904.         if (ttibn > 0)                  /* Or we get a character. */
  4905.           break;
  4906.     }
  4907. }
  4908. #endif /* TCPIPLIB */
  4909.  
  4910. VOID
  4911. #ifdef CK_ANSIC
  4912. failnetinc(void * threadinfo)
  4913. #else /* CK_ANSIC */
  4914. failnetinc(threadinfo) VOID * threadinfo;
  4915. #endif /* CK_ANSIC */
  4916. /* failnetinc */ {
  4917.     ; /* Nothing to do on an error */
  4918. }
  4919.  
  4920. /* N E T X I N -- Input block of characters from network */
  4921.  
  4922. int
  4923. netxin(n,buf) int n; CHAR * buf; {
  4924.     int len;
  4925.     int rc;
  4926.     int i, j;
  4927.     if (ttyfd == -1) {
  4928.         debug(F100,"netinc socket is closed","",0);
  4929.         return(-2);
  4930.     }
  4931. #ifdef RLOGCODE
  4932. #ifdef CK_KERBEROS
  4933. #ifdef KRB4
  4934.     if (ttnproto == NP_EK4LOGIN) {
  4935.         if ((len = krb4_des_read(ttyfd,buf,n)) < 0)
  4936.           return(-1);
  4937.         else
  4938.           return(len);
  4939.     }
  4940. #endif /* KRB4 */
  4941. #ifdef KRB5
  4942.     if (ttnproto == NP_EK5LOGIN) {
  4943.         if ((len = krb5_des_read(ttyfd,buf,n)) < 0)
  4944.           return(-1);
  4945.         else
  4946.           return(len);
  4947.     }
  4948. #endif /* KRB5 */
  4949. #endif /* CK_KERBEROS */
  4950. #endif /* RLOGCODE */
  4951.  
  4952. #ifdef TCPIPLIB
  4953.     if (!ttibn)
  4954.       if ((rc = ttbufr()) <= 0)
  4955.         return(rc);
  4956.  
  4957.     if (ttibn <= n) {
  4958.         len = ttibn;
  4959.         memcpy(buf,&ttibuf[ttibp],len);
  4960.         ttibp += len;
  4961.         ttibn = 0;
  4962.     } else {
  4963.         memcpy(buf,&ttibuf[ttibp],n);
  4964.         ttibp += n;
  4965.         ttibn -= n;
  4966.         len = n;
  4967.     }
  4968. #else /* TCPIPLIB */
  4969.     for (i = 0; i < n; i++) {
  4970.         if ((j = netinc(0)) < 0) {
  4971.             if (j < -1)
  4972.               return(j);
  4973.             else
  4974.               break;
  4975.         }
  4976.         buf[i] = j;
  4977.     }
  4978.     len = i;
  4979. #endif /* TCPIPLIB */
  4980.  
  4981. #ifdef COMMENT
  4982. #ifdef CK_ENCRYPTION
  4983.     /* This would be great if it worked.  But what if the buffer we read  */
  4984.     /* contains a telnet negotiation that changes the state of the        */
  4985.     /* encryption.  If so, we would be either decrypting unencrypted text */
  4986.     /* or not decrypting encrypted text.  So we must move this call to    */
  4987.     /* all functions that call ttxin().  In OS2 that means os2_netxin()   */
  4988.     /* where the Telnet Negotiations are handled.                         */
  4989.     if (u_encrypt)
  4990.       ck_tn_decrypt(buf,len);
  4991. #endif /* CK_ENCRYPTION */
  4992. #endif /* COMMENT */
  4993.  
  4994.     return(len);
  4995. }
  4996.  
  4997. /*  N E T I N C --  Input character from network */
  4998.  
  4999. #ifdef NETLEBUF
  5000. #define LEBUF
  5001. #endif /* NETLEBUF */
  5002. #ifdef TTLEBUF
  5003. #define LEBUF
  5004. #endif /* TTLEBUF */
  5005. #ifndef LEBUF
  5006. #ifdef OS2
  5007. #define LEBUF
  5008. #endif /* OS2 */
  5009. #endif /* LEBUF */
  5010.  
  5011. int
  5012. netinc(timo) int timo; {
  5013. #ifdef TCPIPLIB
  5014.     int x; unsigned char c;             /* The locals. */
  5015.  
  5016. #ifdef NETLEBUF
  5017.     if (ttpush >= 0) {
  5018.         debug(F111,"netinc","ttpush",ttpush);
  5019.         c = ttpush;
  5020.         ttpush = -1;
  5021.         return(c);
  5022.     }
  5023.     if (le_data) {
  5024.         if (le_getchar((CHAR *)&c) > 0) {
  5025.             debug(F111,"netinc le_getchar","c",c);
  5026.             return(c);
  5027.         }
  5028.     }
  5029. #endif /* NETLEBUF */
  5030.  
  5031.     if (ttyfd == -1) {
  5032.         debug(F100,"netinc socket is closed","",0);
  5033.         return(-2);
  5034.     }
  5035.  
  5036. #ifdef RLOGCODE
  5037. #ifdef CK_KERBEROS
  5038. #ifdef KRB4
  5039.     if (ttnproto == NP_EK4LOGIN) {
  5040.         if ((x = krb4_des_read(ttyfd,&c,1)) == 0)
  5041.           return(-1);
  5042.         else if (x < 0)
  5043.           return(-2);
  5044.         else
  5045.           return(c);
  5046.     }
  5047. #endif /* KRB4 */
  5048. #ifdef KRB5
  5049.     if (ttnproto == NP_EK5LOGIN) {
  5050.         if ((x = krb5_des_read(ttyfd,&c,1)) == 0)
  5051.           return(-1);
  5052.         else if (x < 0)
  5053.           return(-2);
  5054.         else
  5055.           return(c);
  5056.     }
  5057. #endif /* KRB5 */
  5058. #endif /* CK_KERBEROS */
  5059. #endif /* RLOGCODE */
  5060.  
  5061.     if (ttibn > 0) {                    /* Something in internal buffer? */
  5062. #ifdef COMMENT
  5063.         debug(F100,"netinc char in buf","",0); /* Yes. */
  5064. #endif /* COMMENT */
  5065.         x = 0;                          /* Success. */
  5066.     } else {                            /* Else must read from network. */
  5067.         x = -1;                         /* Assume failure. */
  5068. #ifdef DEBUG
  5069.         debug(F101,"netinc goes to net, timo","",timo);
  5070.         ttibuf[ttibp+ttibn+1] = '\0';
  5071.         debug(F111,"netinc ttibuf",ttibuf,ttibp);
  5072. #endif /* DEBUG */
  5073. #ifdef CK_SSL
  5074.         if (ssl_active_flag) {
  5075.             x = SSL_pending(ssl_con);
  5076.             if (x < 0) {
  5077.                 debug(F111,"netinc","SSL_pending error",x);
  5078.                 netclos();
  5079.                 return(-1);
  5080.             } else if ( x > 0 ) {
  5081.                 if ( ttbufr() >= 0 )
  5082.                     return(netinc(timo));
  5083.             }
  5084.             x = -1;
  5085.         } else if (tls_active_flag) {
  5086.             x = SSL_pending(tls_con);
  5087.             if (x < 0) {
  5088.                 debug(F111,"netinc","TLS_pending error",x);
  5089.                 netclos();
  5090.                 return(-1);
  5091.             } else if ( x > 0 ) {
  5092.                 if ( ttbufr() >= 0 )
  5093.                     return(netinc(timo));
  5094.             }
  5095.             x = -1;
  5096.         }
  5097. #endif /* CK_SSL */
  5098. #ifndef LEBUF
  5099.         if (timo == 0) {                /* Untimed case. */
  5100.             while (1) {                 /* Wait forever if necessary. */
  5101.                 if (ttbufr() < 0)       /* Refill buffer. */
  5102.                   break;                /* Error, fail. */
  5103.                 if (ttibn > 0) {        /* Success. */
  5104.                     x = 0;
  5105.                     break;
  5106.                 }
  5107.             }
  5108.         } else                          /* Timed case... */
  5109. #endif /* LEBUF */
  5110.           {
  5111. #ifdef NT_TCP_OVERLAPPED
  5112.             /* This code is for use on NT when we are using */
  5113.             /* Overlapped I/O to handle reads.  In the case */
  5114.             /* of outstanding reads select() doesn't work   */
  5115.  
  5116.             if (WaitForOverlappedReadData(timo)) {
  5117.                 while (1) {
  5118.                     if (ttbufr() < 0)   /* Keep trying to refill it. */
  5119.                         break;          /* Till we get an error. */
  5120.                     if (ttibn > 0) {    /* Or we get a character. */
  5121.                         x = 0;
  5122.                         break;
  5123.                     }
  5124.                 }
  5125.             }
  5126. #else /* NT_TCP_OVERLAPPED */
  5127. #ifdef BSDSELECT
  5128.             fd_set rfds;
  5129.             struct timeval tv;
  5130.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5131.             debug(F101,"netinc BSDSELECT","",timo);
  5132.  
  5133.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5134.                 int rc;
  5135.                 debug(F111,"netinc","timeout",timeout);
  5136.                 /* Don't move select() initialization out of the loop. */
  5137.                 FD_ZERO(&rfds);
  5138.                 FD_SET(ttyfd, &rfds);
  5139.                 tv.tv_sec  = tv.tv_usec = 0L;
  5140.                 if (timo)
  5141.                   tv.tv_usec = (long) 100000L;
  5142.                 else
  5143.                   tv.tv_sec = 30;
  5144. #ifdef NT
  5145.                 WSASafeToCancel = 1;
  5146. #endif /* NT */
  5147.                 rc = select(FD_SETSIZE,
  5148. #ifndef __DECC
  5149.                             (fd_set *)
  5150. #endif /* __DECC */
  5151.                             &rfds, NULL, NULL, &tv);
  5152.                 if (rc < 0) {
  5153.                     int s_errno = socket_errno;
  5154.                     debug(F111,"netinc","select",rc);
  5155.                     debug(F111,"netinc","socket_errno",s_errno);
  5156.                     if (s_errno)
  5157.                       return(-1);
  5158.                 }
  5159.                 debug(F111,"netinc","select",rc);
  5160. #ifdef NT
  5161.                 WSASafeToCancel = 0;
  5162. #endif /* NT */
  5163.                 if (!FD_ISSET(ttyfd, &rfds)) {
  5164. #ifdef LEBUF
  5165.                     if (le_inbuf() > 0) {
  5166.                         timeout = -1;
  5167.                         break;
  5168.                     }
  5169. #endif /* LEBUF */
  5170.                     /* If waiting forever we have no way of knowing if the */
  5171.                     /* socket closed so try writing a 0-length TCP packet  */
  5172.                     /* which should force an error if the socket is closed */
  5173.                     if (!timo) {
  5174.                         if ((rc = socket_write(ttyfd,"",0)) < 0) {
  5175.                             int s_errno = socket_errno;
  5176.                             debug(F101,"netinc socket_write error","",s_errno);
  5177. #ifdef OS2
  5178.                             if (os2socketerror(s_errno) < 0)
  5179.                               return(-2);
  5180. #endif /* OS2 */
  5181.                             return(-1); /* Call it an i/o error */
  5182.                         }
  5183.                     }
  5184.                     continue;
  5185.                 }
  5186.                 while (1) {
  5187.                     if (ttbufr() < 0) { /* Keep trying to refill it. */
  5188.                         timeout = -1;
  5189.                         break;          /* Till we get an error. */
  5190.                     }
  5191.                     if (ttibn > 0) {    /* Or we get a character. */
  5192.                         x = 0;
  5193.                         timeout = -1;
  5194.                         break;
  5195.                     }
  5196.                 }
  5197.             }
  5198. #ifdef NT
  5199.             WSASafeToCancel = 0;
  5200. #endif /* NT */
  5201. #else /* !BSDSELECT */
  5202. #ifdef IBMSELECT
  5203. /*
  5204.   Was used by OS/2, currently not used, but might come in handy some day...
  5205.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  5206.   and timeval stuff since this is the only place where it is used.
  5207. */
  5208.             int socket = ttyfd;
  5209.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5210.  
  5211.             debug(F101,"netinc IBMSELECT","",timo);
  5212.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5213.                 if (select(&socket, 1, 0, 0, 100L) == 1) {
  5214.                     while (1) {
  5215.                         if (ttbufr() < 0) { /* Keep trying to refill it. */
  5216.                             timeout = -1;
  5217.                             break;      /* Till we get an error. */
  5218.                         }
  5219.                         if (ttibn > 0) { /* Or we get a character. */
  5220.                             x = 0;
  5221.                             timeout = -1;
  5222.                             break;
  5223.                         }
  5224.                     }
  5225.                 }
  5226. #ifdef LEBUF
  5227.                 else if (le_inbuf() > 0)  {
  5228.                     timeout = -1;
  5229.                     break;
  5230.                 }
  5231. #endif /* LEBUF */
  5232.             }
  5233. #else /* !IBMSELECT */
  5234. #ifdef WINSOCK
  5235.        /* Actually, under WinSock we have a better mechanism than select() */
  5236.        /* for setting timeouts (SO_RCVTIMEO, SO_SNDTIMEO) */
  5237.             SOCKET socket = ttyfd;
  5238.             debug(F101,"netinc NTSELECT","",timo);
  5239.             if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timo,
  5240.                             sizeof(timo))  == NO_ERROR)
  5241.               while (1) {
  5242.                   if (ttbufr() < 0)     /* Keep trying to refill it. */
  5243.                     break;              /* Till we get an error. */
  5244.                   if (ttibn > 0) {      /* Or we get a character. */
  5245.                       x = 0;
  5246.                       break;
  5247.                   }
  5248.               }
  5249. #else /* WINSOCK */
  5250. /*
  5251.   If we can't use select(), then we use the regular alarm()/signal()
  5252.   timeout mechanism.
  5253. */
  5254.             debug(F101,"netinc alarm","",timo);
  5255.             x = alrm_execute(ckjaddr(njbuf),timo,nettout,donetinc,failnetinc);
  5256.             ttimoff();                  /* Timer off. */
  5257. #endif /* WINSOCK */
  5258. #endif /* IBMSELECT */
  5259. #endif /* BSDSELECT */
  5260. #endif /* NT_TCP_OVERLAPPED */
  5261.         }
  5262.     }
  5263.  
  5264. #ifdef LEBUF
  5265.     if (le_inbuf() > 0) {               /* If data was inserted into the */
  5266.         if (le_getchar((CHAR *)&c) > 0) /* Local Echo buffer while the   */
  5267.           return(c);                    /* was taking place do not mix   */
  5268.     }                                   /* the le data with the net data */
  5269. #endif /* LEBUF */
  5270.     if (x < 0) {                        /* Return -1 if we failed. */
  5271.         debug(F100,"netinc timed out","",0);
  5272.         return(-1);
  5273.     } else {                            /* Otherwise */
  5274.         c = ttibuf[ttibp];              /* Return the first char in ttibuf[] */
  5275.         if (deblog) {
  5276. #ifndef COMMENT
  5277.             debug(F101,"netinc returning","",c);
  5278. #endif /* COMMENT */
  5279.             if (c == 0) {
  5280.                 debug(F101,"netinc 0 ttibn","",ttibn);
  5281.                 debug(F101,"netinc 0 ttibp","",ttibp);
  5282. #ifdef BETATEST
  5283.                 {
  5284. #ifdef OS2
  5285.                     extern int tt_type_mode;
  5286.                     if ( !ISVTNT(tt_type_mode) )
  5287. #endif /* OS2 */
  5288.                     hexdump("netinc &ttbuf[ttibp]",&ttibuf[ttibp],ttibn);
  5289.                 }
  5290. #endif /* BETATEST */
  5291.             }
  5292.         }
  5293.         ttibp++;
  5294.         ttibn--;
  5295.  
  5296. #ifdef CK_ENCRYPTION
  5297.         if (TELOPT_U(TELOPT_ENCRYPTION))
  5298.           ck_tn_decrypt(&c,1);
  5299. #endif /* CK_ENCRYPTION */
  5300.         return(c);
  5301.     }
  5302. #else /* Not using TCPIPLIB */
  5303.     return(-1);
  5304. #endif /* TCPIPLIB */
  5305. }
  5306.  
  5307. /*  N E T T O L  --  Output a string of bytes to the network  */
  5308. /*
  5309.   Call with s = pointer to string, n = length.
  5310.   Returns number of bytes actually written on success, or
  5311.   -1 on i/o error, -2 if called improperly.
  5312. */
  5313.  
  5314. int
  5315. nettol(s,n) CHAR *s; int n; {
  5316. #ifdef TCPIPLIB
  5317.     int count = 0;
  5318.     int len = n;
  5319.     int try = 0;
  5320.  
  5321.     if (ttyfd == -1) {
  5322.         debug(F100,"nettol socket is closed","",0);
  5323.         return -1;
  5324.     }
  5325.     debug(F101,"nettol TCPIPLIB ttnet","",ttnet);
  5326. #ifdef COMMENT
  5327.     hexdump("nettol",s,n);
  5328. #endif /* COMMENT */
  5329.  
  5330. #ifdef RLOGCODE
  5331. #ifdef CK_KERBEROS
  5332. #ifdef KRB4
  5333.     if (ttnproto == NP_EK4LOGIN) {
  5334.         return(krb4_des_write(ttyfd,s,n));
  5335.     }
  5336. #endif /* KRB4 */
  5337. #ifdef KRB5
  5338.     if (ttnproto == NP_EK5LOGIN) {
  5339.         return(krb5_des_write(ttyfd,s,n));
  5340.     }
  5341. #endif /* KRB5 */
  5342. #endif /* CK_KERBEROS */
  5343. #endif /* RLOGCODE */
  5344.  
  5345. #ifdef CK_ENCRYPTION
  5346.     if (TELOPT_ME(TELOPT_ENCRYPTION))
  5347.       ck_tn_encrypt(s,n);
  5348. #endif /* CK_ENCRYPTION */
  5349.  
  5350. #ifdef CK_SSL
  5351.     if (ssl_active_flag || tls_active_flag) {
  5352.         int error;
  5353.         /* Write using SSL */
  5354.         if (ssl_active_flag)
  5355.           len = SSL_write(ssl_con, s, len);
  5356.         else
  5357.           len = SSL_write(tls_con, s, len);
  5358.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
  5359.           case SSL_ERROR_NONE:
  5360.             debug(F111,"nettol","SSL_write",len);
  5361.             return(len);
  5362.           case SSL_ERROR_WANT_WRITE:
  5363.             debug(F100,"nettol SSL_ERROR_WANT_WRITE","",0);
  5364.             return(-1);
  5365.           case SSL_ERROR_WANT_READ:
  5366.             debug(F100,"nettol SSL_ERROR_WANT_READ","",0);
  5367.             return(-1);
  5368.           case SSL_ERROR_SYSCALL:
  5369. #ifdef NT
  5370.             debug(F111,"nettol SSL_ERROR_SYSCALL",
  5371.                   "GetLastError()",GetLastError());
  5372. #endif /* NT */
  5373.             netclos();
  5374.             return(-2);
  5375.           case SSL_ERROR_WANT_X509_LOOKUP:
  5376.             debug(F100,"nettol SSL_ERROR_WANT_X509_LOOKUP","",0);
  5377.             netclos();
  5378.             return(-2);
  5379.           case SSL_ERROR_SSL:
  5380.             debug(F100,"nettol SSL_ERROR_SSL","",0);
  5381.             netclos();
  5382.             return(-2);
  5383.           case SSL_ERROR_ZERO_RETURN:
  5384.             debug(F100,"nettol SSL_ERROR_ZERO_RETURN","",0);
  5385.             netclos();
  5386.             return(-2);
  5387.           default:
  5388.             debug(F100,"nettol SSL_ERROR_?????","",0);
  5389.             netclos();
  5390.             return(-2);
  5391.         }
  5392.     }
  5393. #endif /* CK_SSL */
  5394.  
  5395.   nettol_retry:
  5396.     try++;                              /* Increase the try counter */
  5397.  
  5398.     if (ttnet == NET_TCPB) {
  5399. #ifdef BSDSELECT
  5400.         fd_set wfds;
  5401.         struct timeval tv;
  5402.  
  5403.         debug(F101,"nettol BSDSELECT","",0);
  5404.         tv.tv_usec = 0L;
  5405.         tv.tv_sec=30;
  5406. #ifdef NT
  5407.         WSASafeToCancel = 1;
  5408. #endif /* NT */
  5409. #ifdef STREAMING
  5410.       do_select:
  5411. #endif /* STREAMING */
  5412.         FD_ZERO(&wfds);
  5413.         FD_SET(ttyfd, &wfds);
  5414.         if (select(FD_SETSIZE, NULL,
  5415. #ifdef __DECC
  5416. #ifndef __DECC_VER
  5417.                     (int *)
  5418. #endif /* __DECC_VER */
  5419. #endif /* __DECC */
  5420.                    &wfds, NULL, &tv) < 0) {
  5421.             int s_errno = socket_errno;
  5422.             debug(F101,"nettol select failed","",s_errno);
  5423. #ifdef BETATEST
  5424.             printf("nettol select failed: %d\n", s_errno);
  5425. #endif /* BETATEST */
  5426. #ifdef NT
  5427.             WSASafeToCancel = 0;
  5428.             if (!win95selectbug)
  5429. #endif /* NT */
  5430.               return(-1);
  5431.         }
  5432.         if (!FD_ISSET(ttyfd, &wfds)) {
  5433. #ifdef STREAMING
  5434.             if (streaming)
  5435.               goto do_select;
  5436. #endif /* STREAMING */
  5437.             debug(F111,"nettol","!FD_ISSET",ttyfd);
  5438. #ifdef NT
  5439.             WSASafeToCancel = 0;
  5440.             if (!win95selectbug)
  5441. #endif /* NT */
  5442.               return(-1);
  5443.         }
  5444. #ifdef NT
  5445.         WSASafeToCancel = 0;
  5446. #endif /* NT */
  5447. #else /* BSDSELECT */
  5448. #ifdef IBMSELECT
  5449.         {
  5450.             int tries = 0;
  5451.             debug(F101,"nettol IBMSELECT","",0);
  5452.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  5453.                 int count;
  5454.                 if (tries++ >= 60) {
  5455.                     /* if after 60 seconds we can't get permission to write */
  5456.                     debug(F101,"nettol select failed","",socket_errno);
  5457.                     return(-1);
  5458.                 }
  5459.                 if ((count = nettchk()) < 0) {
  5460.                     debug(F111,"nettol","nettchk()",count);
  5461.                     return(count);
  5462.                 }
  5463.             }
  5464.         }
  5465. #endif /* IBMSELECT */
  5466. #endif /* BSDSELECT */
  5467.         if ((count = socket_write(ttyfd,s,n)) < 0) {
  5468.             int s_errno = socket_errno; /* maybe a function */
  5469.             debug(F101,"nettol socket_write error","",s_errno);
  5470. #ifdef OS2
  5471.             if (os2socketerror(s_errno) < 0)
  5472.               return(-2);
  5473. #endif /* OS2 */
  5474.             return(-1);                 /* Call it an i/o error */
  5475.         }
  5476.         if (count < n) {
  5477.             debug(F111,"nettol socket_write",s,count);
  5478.             if (try > 25) {
  5479.                 /* don't try more than 25 times */
  5480.                 debug(F100,"nettol tried more than 25 times","",0);
  5481.                 return(-1);
  5482.             }
  5483.             if (count > 0) {
  5484.                 s += count;
  5485.                 n -= count;
  5486.             }
  5487.             debug(F111,"nettol retry",s,n);
  5488.             goto nettol_retry;
  5489.         } else {
  5490.             debug(F111,"nettol socket_write",s,count);
  5491.             return(len); /* success - return total length */
  5492.         }
  5493.     } else
  5494.       return(-2);
  5495. #else
  5496.     debug(F100,"nettol TCPIPLIB not defined","",0);
  5497.     return(-2);
  5498. #endif /* TCPIPLIB */
  5499. }
  5500.  
  5501. /*  N E T T O C  --   Output character to network */
  5502. /*
  5503.   Call with character to be transmitted.
  5504.   Returns 0 if transmission was successful, or
  5505.   -1 upon i/o error, or -2 if called improperly.
  5506. */
  5507. int
  5508. #ifdef CK_ANSIC
  5509. nettoc(CHAR c)
  5510. #else
  5511. nettoc(c) CHAR c;
  5512. #endif /* CK_ANSIC */
  5513. /* nettoc */ {
  5514. #ifdef UNIX
  5515.     return(ttoc(c));
  5516. #else
  5517. #ifdef TCPIPLIB
  5518.     unsigned char cc;
  5519.     if (ttyfd == -1) {
  5520.         debug(F100,"nettoc socket is closed","",0);
  5521.         return -1;
  5522.     }
  5523.     cc = c;
  5524.     debug(F101,"nettoc cc","",cc);
  5525.  
  5526. #ifdef RLOGCODE
  5527. #ifdef CK_KERBEROS
  5528. #ifdef KRB4
  5529.     if (ttnproto == NP_EK4LOGIN) {
  5530.         return(krb4_des_write(ttyfd,&cc,1)==1?0:-1);
  5531.     }
  5532. #endif /* KRB4 */
  5533. #ifdef KRB5
  5534.     if (ttnproto == NP_EK5LOGIN) {
  5535.         return(krb5_des_write(ttyfd,&cc,1)==1?0:-1);
  5536.     }
  5537. #endif /* KRB5 */
  5538. #endif /* CK_KERBEROS */
  5539. #endif /* RLOGCODE */
  5540.  
  5541. #ifdef CK_ENCRYPTION
  5542.         if ( TELOPT_ME(TELOPT_ENCRYPTION) )
  5543.             ck_tn_encrypt(&cc,1);
  5544. #endif /* CK_ENCRYPTION */
  5545. #ifdef CK_SSL
  5546.     if (ssl_active_flag || tls_active_flag) {
  5547.         int len, error;
  5548.         /* Write using SSL */
  5549.         if (ssl_active_flag)
  5550.           len = SSL_write(ssl_con, &cc, 1);
  5551.         else
  5552.           len = SSL_write(tls_con, &cc, 1);
  5553.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
  5554.           case SSL_ERROR_NONE:
  5555.             debug(F111,"nettoc","SSL_write",len);
  5556.             return(len == 1 ? 0 : -1);
  5557.           case SSL_ERROR_WANT_WRITE:
  5558.           case SSL_ERROR_WANT_READ:
  5559.             return(-1);
  5560.           case SSL_ERROR_SYSCALL:
  5561.           case SSL_ERROR_WANT_X509_LOOKUP:
  5562.           case SSL_ERROR_SSL:
  5563.           case SSL_ERROR_ZERO_RETURN:
  5564.           default:
  5565.             netclos();
  5566.             return(-2);
  5567.         }
  5568.     }
  5569. #endif /* CK_SSL */
  5570.     if (ttnet == NET_TCPB) {
  5571. #ifdef BSDSELECT
  5572.         fd_set wfds;
  5573.         struct timeval tv;
  5574.  
  5575.         debug(F101,"nettoc BSDSELECT","",0);
  5576.         tv.tv_usec = 0L;
  5577.         tv.tv_sec = 30;
  5578.  
  5579. #ifdef STREAMING
  5580.       do_select:
  5581. #endif /* STREAMING */
  5582.  
  5583.         FD_ZERO(&wfds);
  5584.         FD_SET(ttyfd, &wfds);
  5585.         if (select(FD_SETSIZE, NULL,
  5586. #ifdef __DECC
  5587. #ifndef __DECC_VER
  5588.                    (int *)
  5589. #endif /* __DECC_VER */
  5590. #endif /* __DECC */
  5591.                    &wfds, NULL, &tv) < 0) {
  5592.             int s_errno = socket_errno;
  5593.             debug(F101,"nettoc select failed","",s_errno);
  5594. #ifdef BETATEST
  5595.             printf("nettoc select failed: %d\n", s_errno);
  5596. #endif /* BETATEST */
  5597. #ifdef NT
  5598.             WSASafeToCancel = 0;
  5599.             if (!win95selectbug)
  5600. #endif /* NT */
  5601.               return(-1);
  5602.         }
  5603.         if (!FD_ISSET(ttyfd, &wfds)) {
  5604. #ifdef STREAMING
  5605.             if (streaming)
  5606.               goto do_select;
  5607. #endif /* STREAMING */
  5608.             debug(F111,"nettoc","!FD_ISSET",ttyfd);
  5609. #ifdef NT
  5610.             WSASafeToCancel = 0;
  5611.             if (!win95selectbug)
  5612. #endif /* NT */
  5613.               return(-1);
  5614.         }
  5615. #ifdef NT
  5616.         WSASafeToCancel = 0;
  5617. #endif /* NT */
  5618. #else /* BSDSELECT */
  5619. #ifdef IBMSELECT
  5620.         {
  5621.             int tries = 0;
  5622.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  5623.                 int count;
  5624.                 if (tries++ >= 60) {
  5625.                     /* if after 60 seconds we can't get permission to write */
  5626.                     debug(F101,"nettoc select failed","",socket_errno);
  5627.                     return(-1);
  5628.                 }
  5629.                 if ((count = nettchk()) < 0) {
  5630.                     debug(F111,"nettoc","nettchk()",count);
  5631.                     return(count);
  5632.                 }
  5633.             }
  5634.         }
  5635. #endif /* IBMSELECT */
  5636. #endif /* BSDSELECT */
  5637.         if (socket_write(ttyfd,&cc,1) < 1) {
  5638.             int s_errno = socket_errno;         /* maybe a function */
  5639.             debug(F101,"nettoc socket_write error","",s_errno);
  5640. #ifdef OS2
  5641.             if (os2socketerror(s_errno) < 0)
  5642.               return(-2);
  5643. #endif /* OS2 */
  5644.             return(-1);
  5645.         }
  5646.         debug(F101,"nettoc socket_write","", cc);
  5647.         return(0);
  5648.     } else return(-2);
  5649. #else
  5650.     return(-2);
  5651. #endif /* TCPIPLIB */
  5652. #endif /* UNIX */
  5653. }
  5654.  
  5655. /*  N E T F L U I  --  Flush network input buffer  */
  5656.  
  5657. #ifdef TNCODE
  5658. static int
  5659. #ifdef CK_ANSIC
  5660. netgetc(int timo)                       /* Input function to point to... */
  5661. #else  /* CK_ANSIC */
  5662. netgetc(timo) int timo;
  5663. #endif /* CK_ANSIC */
  5664. {                                       /* ...in the tn_doop() call */
  5665. #ifdef TCPIPLIB
  5666.     return netinc(timo);
  5667. #else /* TCPIPLIB */
  5668.     return ttinc(timo);
  5669. #endif /* TCPIPLIB */
  5670. }
  5671. #endif /* TNCODE */
  5672.  
  5673. int
  5674. netflui() {
  5675.     int n;
  5676.     int ch;
  5677. #ifdef NETLEBUF
  5678.     ttpush = -1;                        /* Clear the peek-ahead char */
  5679.     while (le_data && (le_inbuf() > 0)) {
  5680.         CHAR ch = '\0';
  5681.         if (le_getchar(&ch) > 0) {
  5682.             debug(F101,"ttflui le_inbuf ch","",ch);
  5683.         }
  5684.     }
  5685. #endif /* NETLEBUF */
  5686.  
  5687. #ifdef TCPIPLIB
  5688. #ifdef TNCODE
  5689.     if (ttnproto == NP_TELNET) {
  5690.         /* Netflui must process Telnet negotiations or get out of sync */
  5691.         if ((n = nettchk()) <= 0) return(0);
  5692.         while (n-- > 0) {
  5693.             ch = netinc(1);
  5694.             if (ch == IAC) {
  5695.                 extern int duplex;  /* this really shouldn't be here but ... */
  5696.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  5697.                 if (tx == 1) duplex = 1;
  5698.                 else if (tx == 2) duplex = 0;
  5699.                 n = nettchk();
  5700.             }
  5701.         }
  5702.     } else
  5703. #endif /* TNCODE */
  5704.     {
  5705.         ttibuf[ttibp+ttibn] = '\0';
  5706.         debug(F111,"netflui 1",ttibuf,ttibn);
  5707. #ifdef CK_ENCRYPTION
  5708.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  5709.             ck_tn_decrypt(&ttibuf[ttibp],ttibn);
  5710.         }
  5711. #endif /* CK_ENCRYPTION */
  5712.         ttibn = ttibp = 0;              /* Flush internal buffer *FIRST* */
  5713.         if (ttyfd < 1)
  5714.             return(0);
  5715.         if ((n = nettchk()) > 0) {      /* Now see what's waiting on the net */
  5716.             if (n > TTIBUFL) n = TTIBUFL;       /* and sponge it up */
  5717.             debug(F101,"netflui 2","",n);       /* ... */
  5718.             n = socket_read(ttyfd,ttibuf,n); /* into our buffer */
  5719.             if (n >= 0) ttibuf[n] = '\0';
  5720.             debug(F111,"netflui 3",ttibuf,n);
  5721. #ifdef CK_ENCRYPTION
  5722.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  5723.                 ck_tn_decrypt(&ttibuf[ttibp],n);
  5724.             }
  5725. #endif /* CK_ENCRYPTION */
  5726.             ttibuf[0] = '\0';
  5727.         }
  5728.     }
  5729. #else  /* !TCPIPLIB */
  5730.     if (ttyfd < 1)
  5731.       return(0);
  5732. #ifdef TNCODE
  5733.     if (ttnproto == NP_TELNET) {
  5734.         if ((n = ttchk()) <= 0) return(0);
  5735.         while (n-- >= 0) {
  5736.             /* Netflui must process Telnet negotiations or get out of sync */
  5737.             ch = ttinc(1);
  5738.             if (ch == IAC) {
  5739.                 extern int duplex;  /* this really shouldn't be here but ... */
  5740.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  5741.                 if (tx == 1) duplex = 1;
  5742.                 else if (tx == 2) duplex = 0;
  5743.                 n = ttchk();
  5744.             }
  5745.         };
  5746.     } else
  5747. #endif /* TNCODE */
  5748.     if ((n = ttchk()) > 0) {
  5749.         debug(F101,"netflui non-TCPIPLIB","",n);
  5750.         while ((n--) && ttinc(1) > -1)  /* Don't worry, ttinc() is buffered */
  5751.           ;                             /* and it handles the decryption... */
  5752.     }
  5753. #endif /* TCPIPLIB */
  5754.     return(0);
  5755. }
  5756. #endif /* NOLOCAL */
  5757.  
  5758. /* getlocalipaddr() attempts to resolve an IP Address for the local machine.
  5759.  *   If the host is multi-homed it returns only one address.
  5760.  *
  5761.  * Two techniques are used.
  5762.  * (1) get the local host name and perform a DNS lookup, then take
  5763.  *     the first entry;
  5764.  * (2) open a UDP socket, use it to connect to a fictitious host (it's OK,
  5765.  *    no data is sent), then retrieve the local address from the socket.
  5766.  * Note: the second technique won't work on Microsoft systems.  See
  5767.  * Article ID: Q129065 PRB: Getsockname() Returns IP Address 0.0.0.0 for UDP
  5768.  */
  5769.  
  5770. /* Technique number one cannot work reliably if the machine is a laptop
  5771.  * and the hostname is associated with a physical adapter which is not
  5772.  * installed and a PPP connection is being used instead.  This is because
  5773.  * the hostname DNS lookup will succeed for the physical adapter even though
  5774.  * it would be impossible to use it.  In NT4 SP4, the gethostbyname()
  5775.  * when given the result of gethostname() returns not the real DNS entries
  5776.  * for that name+domain.  Instead it returns all of the static and dynamic
  5777.  * IP addresses assigned to any physical or virtual adapter defined in the
  5778.  * system regardless of whether or not it is installed.  The order of the
  5779.  * addresses is fixed according to the binding order in the NT registry.
  5780.  */
  5781.  
  5782. /*
  5783.  * It appears that calling gethostbyname(NULL) is more reliable than
  5784.  * calling gethostbyname(gethostname()) on Windows.  So on Windows we will
  5785.  * only call gethostbyname(NULL).
  5786.  */
  5787.  
  5788. int
  5789. getlocalipaddr() {
  5790. #ifndef datageneral
  5791.     struct sockaddr_in l_sa;
  5792.     struct sockaddr_in r_sa;
  5793.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  5794.     int sock;
  5795.     int rc;
  5796.     struct in_addr laddr;
  5797.  
  5798.     /* if still not resolved, then try second strategy */
  5799.     /* This second strategy does not work on Windows */
  5800.  
  5801.     memset(&l_sa,0,slen);
  5802.     memset(&r_sa,0,slen);
  5803.  
  5804.     /* get a UDP socket */
  5805.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  5806.     if (sock != -1) {
  5807.         /* connect to arbirary port and address (NOT loopback) */
  5808.         r_sa.sin_family = AF_INET;
  5809.         r_sa.sin_port = htons(IPPORT_ECHO);
  5810.  
  5811.         /* The following is an "illegal conversion" in AOS/VS */
  5812.         /* (and who knows where else) */
  5813.  
  5814. #ifdef INADDRX
  5815.         inaddrx = inet_addr("128.127.50.1");
  5816.         r_sa.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  5817. #else
  5818.         r_sa.sin_addr.s_addr = inet_addr("128.127.50.1");
  5819. #endif /* INADDRX */
  5820.         rc = connect(sock, (struct sockaddr *) &r_sa, sizeof(struct sockaddr));
  5821.         if (!rc) {                      /* get local address */
  5822.             getsockname(sock,(struct sockaddr *)&l_sa,&slen);
  5823. #ifdef TCPIPLIB
  5824.             socket_close(sock);         /* We're done with the socket */
  5825. #else
  5826.             close(sock);
  5827. #endif /* TCPIPLIB */
  5828.             if (l_sa.sin_addr.s_addr != INADDR_ANY) {
  5829.                 myxipaddr = ntohl(l_sa.sin_addr.s_addr);
  5830.                 ckstrncpy(myipaddr,(char *)inet_ntoa(l_sa.sin_addr),20);
  5831.                 debug(F110,"getlocalipaddr setting buf to",myipaddr,0);
  5832.                 return(0);
  5833.             }
  5834.         }
  5835.     }
  5836.     return getlocalipaddrs(myipaddr,sizeof(myipaddr),0);
  5837. #else /* datageneral */
  5838.     return(-1);
  5839. #endif /* datageneral */
  5840. }
  5841.  
  5842. int
  5843. getlocalipaddrs(buf,bufsz,index)
  5844.     char * buf;
  5845.     int    bufsz;
  5846.     int    index;
  5847. /* getlocalipaddrs */ {
  5848. #ifndef datageneral
  5849.     char localhost[256];
  5850.     struct hostent * host=NULL;
  5851.     struct sockaddr_in l_sa;
  5852.     struct sockaddr_in r_sa;
  5853.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  5854.     int sock;
  5855.     int rc;
  5856.     char messageBuf[60];
  5857.     struct in_addr laddr;
  5858.  
  5859.     memset(&l_sa,0,slen);
  5860.     memset(&r_sa,0,slen);
  5861.  
  5862.     /* init local address (to zero) */
  5863.     l_sa.sin_addr.s_addr = INADDR_ANY;
  5864.  
  5865. #ifdef CKGHNLHOST
  5866.     rc = gethostname(localhost, 256);
  5867.     debug(F110,"getlocalipaddrs localhost",localhost,0);
  5868. #else
  5869.     /* This doesn't work on some platforms, e.g. Solaris */
  5870.     rc = 0;
  5871.     localhost[0] = '\0';
  5872. #endif /* CKGHNLHOST */
  5873.     if (!rc) {
  5874.         /* resolve host name for local address */
  5875.         host = gethostbyname(localhost);
  5876.         if (host) {
  5877. #ifdef HADDRLIST
  5878.             if ( index < 0 || index > 63 || !host->h_addr_list[index] ) {
  5879.                 buf[0] = '\0';
  5880.                 return(-1);
  5881.             }
  5882.             l_sa.sin_addr.s_addr =
  5883.               *((unsigned long *) (host->h_addr_list[index]));
  5884.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),20);
  5885.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  5886.  
  5887. #ifdef COMMENT
  5888.             /* This is for reporting multiple IP Address */
  5889.             while (host->h_addr_list && host->h_addr_list[0]) {
  5890.                 l_sa.sin_addr.s_addr =
  5891.                   *((unsigned long *) (host->h_addr_list[0]));
  5892.                 ckstrncpy(messageBuf,
  5893.                         (char *)inet_ntoa(l_sa.sin_addr),60);
  5894.                 if (tcp_address) {
  5895.                     if (!strcmp(messageBuf,tcp_address))
  5896.                       ckstrncpy(myipaddr,tcp_address,20);
  5897.                 }
  5898.                 debug(F110,"getlocalipaddrs ip address list", messageBuf, 0);
  5899.                 host->h_addr_list++;
  5900.             }
  5901. #endif /* COMMENT */
  5902. #else   /* HADDRLIST */
  5903.             if (index != 0) {
  5904.                 buf[0] = '\0';
  5905.                 return(-1);
  5906.             }
  5907.             l_sa.sin_addr.s_addr = *((unsigned long *) (host->h_addr));
  5908.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),bufsz);
  5909.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  5910. #endif  /* HADDRLIST */
  5911.             return(0);
  5912.         } else debug(F110,
  5913.                      "getlocalipaddrs: gethostbyname() failed",
  5914.                      localhost,
  5915.                      0
  5916.                      );
  5917.     }
  5918. #endif /* datageneral */
  5919.     return(-1);
  5920. }
  5921.  
  5922. #ifdef RLOGCODE                 /* TCP/IP RLOGIN protocol support code */
  5923. int
  5924. rlog_naws() {
  5925.     struct rlog_naws {
  5926.         char id[4];
  5927.         unsigned short rows, cols, ypix, xpix;
  5928.     } nawsbuf;
  5929.  
  5930.     if (ttnet != NET_TCPB)
  5931.       return 0;
  5932.     if (ttnproto != NP_RLOGIN
  5933. #ifdef CK_KERBEROS
  5934.         && ttnproto != NP_K4LOGIN
  5935.         && ttnproto != NP_EK4LOGIN
  5936.         && ttnproto != NP_K5LOGIN
  5937.         && ttnproto != NP_EK5LOGIN
  5938. #endif /* CK_KERBEROS */
  5939.          )
  5940.       return 0;
  5941.     if (!TELOPT_ME(TELOPT_NAWS))
  5942.       return 0;
  5943.  
  5944.     debug(F100,"rlogin Window Size sent","",0);
  5945.  
  5946.     nawsbuf.id[0] = nawsbuf.id[1] = 0xFF;
  5947.     nawsbuf.id[2] = nawsbuf.id[3] = 's';
  5948. #ifdef OS2
  5949.     nawsbuf.rows = htons((unsigned short) (VscrnGetHeight(VTERM)
  5950.                           -(tt_status?1:0)));
  5951.     nawsbuf.cols = htons((unsigned short) VscrnGetWidth(VTERM));
  5952. #else /* OS2 */
  5953.     nawsbuf.rows = htons((unsigned short) tt_rows);
  5954.     nawsbuf.cols = htons((unsigned short) tt_cols);
  5955. #endif /* OS2 */
  5956.     nawsbuf.ypix = htons(0);            /* y pixels */
  5957.  
  5958.     nawsbuf.xpix = htons(0);            /* x pixels */
  5959.     if (ttol((CHAR *)(&nawsbuf), 12) < 0)
  5960.       return(-1);
  5961.     return(0);
  5962. }
  5963.  
  5964. #ifdef OS2ORUNIX
  5965. #define RLOGOUTBUF
  5966. #endif /* OS2 */
  5967. static int
  5968. #ifdef CK_ANSIC
  5969. rlog_ini(CHAR * hostname, int port,
  5970.          struct sockaddr_in * l_addr, struct sockaddr_in * r_addr)
  5971. #else /* CK_ANSIC */
  5972. rlog_ini(hostname, port, l_addr, r_addr)
  5973.     CHAR * hostname;
  5974.     int port;
  5975.     struct sockaddr_in * l_addr;
  5976.     struct sockaddr_in * r_addr;
  5977. #endif /* CK_ANSIC */
  5978. /* rlog_ini */ {
  5979.  
  5980. #ifdef RLOGOUTBUF
  5981.     char outbuf[512];
  5982.     int  outbytes=0;
  5983. #endif /* RLOGOUTBUF */
  5984.     int flag = 0;
  5985. #define TERMLEN 16
  5986. #define CONSPDLEN 16
  5987.     CHAR localuser[UIDBUFLEN+1];
  5988.     CHAR remoteuser[UIDBUFLEN+1];
  5989.     int userlen = 0;
  5990.     CHAR term_speed[TERMLEN+CONSPDLEN+1];
  5991. #ifdef CONGSPD
  5992.     long conspd = -1L;
  5993. #endif /* CONGSPD */
  5994. #ifdef OS2
  5995.     extern int tt_type, max_tt;
  5996.     extern struct tt_info_rec tt_info[];
  5997. #endif /* OS2 */
  5998.     int i, n;
  5999.  
  6000.     int rc = 0;
  6001.     tn_reset();                 /* This call will reset all of the Telnet */
  6002.                                 /* options and then quit.  We need to do  */
  6003.                                 /* this since we use the Telnet options   */
  6004.                                 /* to hold various state information      */
  6005.     duplex = 0;                 /* Rlogin is always remote echo */
  6006.  
  6007. #ifdef CK_TTGWSIZ
  6008. /*
  6009.   But compute the values anyway before the first read since the out-
  6010.   of-band NAWS request would arrive before the first data byte (NULL).
  6011. */
  6012. #ifdef OS2
  6013.     /* Console terminal screen rows and columns */
  6014.     debug(F101,"rlog_ini tt_rows 1","",VscrnGetHeight(VTERM)
  6015.            -(tt_status?1:0));
  6016.     debug(F101,"rlog_ini tt_cols 1","",VscrnGetWidth(VTERM));
  6017.     /* Not known yet */
  6018.     if (VscrnGetWidth(VTERM) < 0 ||
  6019.         VscrnGetHeight(VTERM)-(tt_status?1:0) < 0) {
  6020.         ttgwsiz();                      /* Try to get screen dimensions */
  6021.     }
  6022.     debug(F101,"rlog_ini tt_rows 2","",VscrnGetHeight(VTERM)-(tt_status?1:0));
  6023.     debug(F101,"rlog_ini tt_cols 2","",VscrnGetWidth(VTERM));
  6024. #else /* OS2 */
  6025.     debug(F101,"rlog_ini tt_rows 1","",tt_rows);
  6026.     debug(F101,"rlog_ini tt_cols 1","",tt_cols);
  6027.     if (tt_rows < 0 || tt_cols < 0) {   /* Not known yet */
  6028.         ttgwsiz();                      /* Try to find out */
  6029.     }
  6030.     debug(F101,"rlog_ini tt_rows 2","",tt_rows);
  6031.     debug(F101,"rlog_ini tt_cols 2","",tt_cols);
  6032. #endif /* OS2 */
  6033. #endif /* CK_TTGWSIZ */
  6034.  
  6035.     ttflui();                           /* Start by flushing the buffers */
  6036.  
  6037.     rlog_mode = RL_COOKED;
  6038.  
  6039.     /* Followed by client username ... */
  6040.  
  6041.     localuser[0] = '\0';
  6042. #ifdef NT
  6043.     {
  6044.         char localuid[UIDBUFLEN+1];
  6045.         unsigned long len = UIDBUFLEN;
  6046.         localuid[0] = '\0';
  6047. #ifdef COMMENT
  6048.         WNetGetUser(NULL, localuid, &len);
  6049. #else /* COMMENT */
  6050.         GetUserName(localuid,&len);
  6051. #endif /* COMMENT */
  6052.         ckstrncpy((char *)localuser,localuid,UIDBUFLEN);
  6053.     }
  6054. #else /* NT */
  6055.     {
  6056.         char * user = getenv("USER");
  6057.         if (!user)
  6058.           user = "";
  6059.         userlen = strlen(user);
  6060.         debug(F111,"rlogin getenv(USER)",user,userlen);
  6061.         ckstrncpy((char *)localuser,user,UIDBUFLEN);
  6062.         debug(F110,"rlog_ini localuser 1",localuser,0);
  6063.         if (ck_lcname) {
  6064.             cklower((char *)localuser);
  6065.             debug(F110,"rlog_ini localuser 2",localuser,0);
  6066.         }
  6067.     }
  6068. #endif /* NT */
  6069.  
  6070.     /* Then the server userid... */
  6071.  
  6072.     if (uidbuf[0]) {
  6073.         ckstrncpy((char *)remoteuser,uidbuf,UIDBUFLEN);
  6074.         debug(F110,"rlog_ini remoteuser 1",remoteuser,0);
  6075.     } else if (localuser[0]) {
  6076.         ckstrncpy((char *)remoteuser,(char *)localuser,UIDBUFLEN);
  6077.         debug(F110,"rlog_ini remoteuser 2",remoteuser,0);
  6078.     } else {
  6079.         remoteuser[0] = '\0';
  6080.         debug(F110,"rlog_ini remoteuser 3",remoteuser,0);
  6081.     }
  6082.     if (ck_lcname)
  6083.       cklower((char *)remoteuser);
  6084.     debug(F110,"rlog_ini remoteuser 4",remoteuser,0);
  6085.  
  6086.     /* Finally the terminal type and speed */
  6087.  
  6088.     term_speed[0] = '\0';
  6089.     if (tn_term) {                      /* SET TELNET TERMINAL-TYPE value */
  6090.         if (*tn_term) {                 /* (if any) takes precedence. */
  6091.             ckstrncpy((char *)term_speed, tn_term, TERMLEN);
  6092.             flag = 1;
  6093.         }
  6094.     } else {                            /* Otherwise the local terminal type */
  6095. #ifdef OS2
  6096.         /* In terminal-emulating versions, it's the SET TERM TYPE value */
  6097.         ckstrncpy(term_speed, (tt_type >= 0 && tt_type <= max_tt) ?
  6098.                 tt_info[tt_type].x_name : "network", TERMLEN);
  6099. #else
  6100.         /* In the others, we just look at the TERM environment variable */
  6101.         {
  6102.             char *p = getenv("TERM");
  6103.             if (p)
  6104.               ckstrncpy((char *)term_speed,p,TERMLEN);
  6105.             else
  6106.               term_speed[0] = '\0';
  6107. #ifdef VMS
  6108.             for (p = (char *) term_speed; *p; p++) {
  6109.                 if (*p == '-' && (!strcmp(p,"-80") || !strcmp(p,"-132")))
  6110.                   break;
  6111.                 else if (isupper(*p))
  6112.                   *p = tolower(*p);
  6113.             }
  6114.             *p = '\0';
  6115. #endif /* VMS */
  6116.         }
  6117. #endif /* OS2 */
  6118.     }
  6119.     n = strlen((char *)term_speed);
  6120.     if (n > 0) {                        /* We have a terminal type */
  6121.         if (!flag) {                    /* If not user-specified */
  6122.             for (i = 0; i < n; i++)     /* then lowercase it.    */
  6123.               if (isupper(term_speed[i]))
  6124.                 term_speed[i] = tolower(term_speed[i]);
  6125.         }
  6126.         debug(F110,"rlog_ini term_speed 1",term_speed,0);
  6127.  
  6128. #ifdef CONGSPD
  6129.         /* conspd() is not yet defined in all ck*tio.c modules */
  6130.         conspd = congspd();
  6131.         if (conspd > 0L) {
  6132.             sprintf((char *)(&term_speed[strlen((char *)term_speed)]),
  6133.                     "/%ld",
  6134.                     conspd
  6135.                     );
  6136.         } else
  6137. #endif /* CONGSPD */
  6138.           strcat((char *)term_speed,"/19200");
  6139.         debug(F110,"rlog_ini term_speed 2",term_speed,0);
  6140.     } else {
  6141.         term_speed[0] = '\0';
  6142.         debug(F110,"rlog_ini term_speed 3",term_speed,0);
  6143.     }
  6144.  
  6145. #ifdef CK_KERBEROS
  6146.     if (ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  6147.         ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) {
  6148.         int kver, encrypt, rc;
  6149.         switch (ttnproto) {
  6150.           case NP_K4LOGIN:
  6151.             kver = 4;
  6152.             encrypt = 0;
  6153.             break;
  6154.           case NP_EK4LOGIN:
  6155.             kver = 4;
  6156.             encrypt = 1;
  6157.             break;
  6158.           case NP_K5LOGIN:
  6159.             kver = 5;
  6160.             encrypt = 0;
  6161.             break;
  6162.           case NP_EK5LOGIN:
  6163.             kver = 5;
  6164.             encrypt = 1;
  6165.             break;
  6166.         default:
  6167.             kver = 0;
  6168.             encrypt = 0;
  6169.         }
  6170.         rc = ck_krb_rlogin(hostname, port,
  6171.                            localuser, remoteuser, term_speed,
  6172.                            l_addr, r_addr, kver, encrypt);
  6173.         if (!rc) {                      /* success */
  6174.             TELOPT_ME(TELOPT_NAWS) = 1;
  6175.             rc = rlog_naws();
  6176.         }
  6177.         return(rc);
  6178.     } else
  6179. #endif /* CK_KERBEROS */
  6180.     if (ttnproto == NP_RLOGIN) {
  6181. #ifdef RLOGOUTBUF
  6182.         outbuf[outbytes++] = 0;
  6183.         strcpy((char *)outbuf+outbytes,(char *)localuser);
  6184.         outbytes += strlen((char *)localuser) + 1;
  6185.         strcpy((char *)outbuf+outbytes,(char *)remoteuser);
  6186.         outbytes += strlen((char *)remoteuser) + 1;
  6187.         strcpy((char *)outbuf+outbytes,(char *)term_speed);
  6188.         outbytes += strlen((char *)term_speed) + 1;
  6189.         rc = ttol((CHAR *)outbuf,outbytes);
  6190. #else /* RLOGOUTBUF */
  6191.         ttoc(0);                        /* Send an initial NUL as wake-up */
  6192.         /* Send each variable with the trailing NUL */
  6193.         rc = ttol(localuser,strlen((char *)localuser)+1);
  6194.         if (rc > 0)
  6195.           rc = ttol(remoteuser,strlen((char *)remoteuser)+1);
  6196.         if (rc > 0)
  6197.           rc = ttol(term_speed,strlen((char *)term_speed)+1);
  6198. #endif /* RLOGOUTBUF */
  6199.  
  6200.         /* Now we are supposed to get back a single NUL as confirmation */
  6201.         errno = 0;
  6202.         rc = ttinc(60);
  6203.         debug(F101,"rlogin first ttinc","",rc);
  6204.         if (rc > 0) {
  6205.             debug(F101,"rlogin ttinc 1","",rc);
  6206.             printf(
  6207.                "Rlogin protocol error - 0x%x received instead of 0x00\n", rc);
  6208.             return(-1);
  6209.         } else if (rc < 0) {
  6210.             debug(F101,"rlogin ttinc errno","",errno);
  6211.             /* printf("Network error: %d\n", errno); */
  6212.             return(-1);
  6213.         }
  6214.     }
  6215.     return(0);
  6216. }
  6217.  
  6218. #ifdef TCPIPLIB
  6219. static VOID
  6220. rlog_oob(oobdata, count) CHAR * oobdata; int count; {
  6221.     int i;
  6222.  
  6223.     debug(F111,"rlogin out_of_band","count",count);
  6224.  
  6225.     for (i = 0; i<count; i++)   {
  6226.         debug(F101,"rlogin out_of_band","",oobdata[i]);
  6227.         if (oobdata[i] == 0x02) { /* Flush Buffered Data not yet displayed */
  6228.             debug(F101,"rlogin Flush Buffered Data command","",oobdata[i]);
  6229.  
  6230.             /* Only flush the data if in fact we are in a mode that won't */
  6231.             /* get out of sync.  Ie, not when we are in protocol mode.    */
  6232.             switch ( what ) {
  6233.             case W_NOTHING:
  6234.             case W_CONNECT:
  6235.             case W_COMMAND:
  6236.                 ttflui();
  6237.                 break;
  6238.             }
  6239.         }
  6240.         if (oobdata[i] & 0x10) {        /* Switch to RAW mode */
  6241.             debug(F101,"rlogin Raw Mode command","",oobdata[i]);
  6242.             rlog_mode = RL_RAW;
  6243.         }
  6244.  
  6245.         if (oobdata[i] & 0x20) {        /* Switch to COOKED mode */
  6246.             debug(F101,"rlogin Cooked Mode command","",oobdata[i]);
  6247.             rlog_mode = RL_COOKED;
  6248.         }
  6249.         if (oobdata[i] & 0x80) {        /* Send Window Size Info */
  6250.             debug(F101,"rlogin Window Size command","",oobdata[i]);
  6251.             /* Remember to send WS Info when Window Size changes */
  6252.             TELOPT_ME(TELOPT_NAWS) = 1;
  6253.             rlog_naws();
  6254.         }
  6255.     }
  6256. }
  6257. #else /* TCPIPLIB */
  6258. static SIGTYP
  6259. rlogoobh(sig) int sig; {
  6260. #ifdef SOLARIS
  6261.     char                                /* Or should it be char for all? */
  6262. #else
  6263.     CHAR
  6264. #endif /* SOLARIS */
  6265.       oobdata;
  6266.  
  6267.     int  count = 0;
  6268.  
  6269.     while (recv(ttyfd, &oobdata, 1, MSG_OOB) < 0) {
  6270.       /*
  6271.        * We need to do some special processing here.
  6272.        * Just in case the socket is blocked for input
  6273.        *
  6274.        */
  6275.         switch (errno) {
  6276.           case EWOULDBLOCK:
  6277.             break;
  6278.           default:
  6279.             return;
  6280.         }
  6281.     }
  6282.     debug(F101,"rlogin out_of_band","",oobdata);
  6283.     if (oobdata == 0x02) {      /* Flush Buffered Data not yet displayed */
  6284.         debug(F101,"rlogin Flush Buffered Data command","",oobdata);
  6285.         netflui();
  6286.     }
  6287.     if (oobdata & 0x10) {               /* Switch to raw mode */
  6288.         debug(F101,"rlogin Raw Mode command","",oobdata);
  6289.         rlog_mode = RL_RAW;
  6290.     }
  6291.     if (oobdata & 0x20) {               /* Switch to cooked mode */
  6292.         debug(F101,"rlogin Cooked Mode command","",oobdata);
  6293.         rlog_mode = RL_COOKED;
  6294.     }
  6295.     if (oobdata & 0x80) {                 /* Send Window Size Info */
  6296.         debug(F101,"rlogin Window Size command","",oobdata);
  6297.         /* Remember to send WS Info when Window Size changes */
  6298.         TELOPT_ME(TELOPT_NAWS) = 1;
  6299.         rlog_naws();
  6300.     }
  6301. }
  6302. #endif /* TCPIPLIB */
  6303. #endif /* RLOGCODE */
  6304.  
  6305. /* Send network BREAK */
  6306. /*
  6307.   Returns -1 on error, 0 if nothing happens, 1 if BREAK sent successfully.
  6308. */
  6309. int
  6310. netbreak() {
  6311.     CHAR buf[3];
  6312.     if (ttnet == NET_TCPB) {
  6313.         if (ttnproto == NP_TELNET) {
  6314. #ifdef TNCODE
  6315.             buf[0] = (CHAR) IAC; buf[1] = (CHAR) BREAK; buf[2] = (CHAR) 0;
  6316.             if (
  6317. #ifdef OS2
  6318.                 nettol((char *) buf, 2)
  6319. #else
  6320.                 ttol(buf, 2)
  6321. #endif /* OS2 */
  6322.                 < 2)
  6323.               return(-1);
  6324.             if (tn_deb || debses || deblog) {
  6325.                 extern char tn_msg[];
  6326.                 sprintf(tn_msg,"TELNET SENT %s",TELCMD(BREAK));
  6327.                 debug(F101,tn_msg,"",BREAK);
  6328.                 if (debses || tn_deb) tn_debug(tn_msg);
  6329.             }
  6330.             return(1);
  6331. #else
  6332.             debug(F100,"netbreak no TNCODE","",0);
  6333.             return(0);
  6334. #endif /* TNCODE */
  6335.         }
  6336.         /* Insert other TCP/IP protocols here */
  6337.     }
  6338.     /* Insert other networks here */
  6339.     return(0);
  6340. }
  6341. #endif /* NETCONN */
  6342.  
  6343.  
  6344. #ifdef NETCONN
  6345. #ifdef SUNX25
  6346. /*
  6347.   SunLink X.25 support by Marcello Frutig, Catholic University,
  6348.   Rio de Janeiro, Brazil, 1990.
  6349. */
  6350.  
  6351. /* PAD X.3, X.28 and X.29 support */
  6352.  
  6353. static CHAR x29err[MAXPADPARMS+3] = { X29_ERROR, INVALID_PAD_PARM, '\0' };
  6354.  
  6355. /* Initialize PAD */
  6356.  
  6357. extern CHAR padparms[];
  6358.  
  6359. VOID
  6360. initpad() {
  6361.   padparms[PAD_BREAK_CHARACTER]        = 0;  /* Break character */
  6362.   padparms[PAD_ESCAPE]                 = 1;  /* Escape permitted */
  6363.   padparms[PAD_ECHO]                   = 1;  /* Kermit PAD does echo */
  6364.   padparms[PAD_DATA_FORWARD_CHAR]      = 2;  /* forward character CR */
  6365.   padparms[PAD_DATA_FORWARD_TIMEOUT]   = 0;  /* no timeout forward condition */
  6366.   padparms[PAD_FLOW_CONTROL_BY_PAD]    = 0;  /* not used */
  6367.   padparms[PAD_SUPPRESSION_OF_SIGNALS] = 1;  /* allow PAD service signals */
  6368.   padparms[PAD_BREAK_ACTION]           = 21; /* brk action: INT pk + brk ind*/
  6369.   padparms[PAD_SUPPRESSION_OF_DATA]    = 0;  /* no supression of user data */
  6370.   padparms[PAD_PADDING_AFTER_CR]       = 0;  /* no padding after CR */
  6371.   padparms[PAD_LINE_FOLDING]           = 0;  /* no line fold */
  6372.   padparms[PAD_LINE_SPEED]             = 0;  /* line speed - don't care */
  6373.   padparms[PAD_FLOW_CONTROL_BY_USER]   = 0;  /* flow cont of PAD - not used */
  6374.   padparms[PAD_LF_AFTER_CR]            = 0;  /* no LF insertion after CR */
  6375.   padparms[PAD_PADDING_AFTER_LF]       = 0;  /* no padding after LF */
  6376.   padparms[PAD_EDITING]                = 1;  /* can edit */
  6377.   padparms[PAD_CHAR_DELETE_CHAR]       = 8;  /* character delete character */
  6378.   padparms[PAD_BUFFER_DELETE_CHAR]     = 21; /* buffer delete character */
  6379.   padparms[PAD_BUFFER_DISPLAY_CHAR]    = 18; /* buffer display character */
  6380. }
  6381.  
  6382. /* Set PAD parameters */
  6383.  
  6384. VOID
  6385. setpad(s,n) CHAR *s; int n; {
  6386.     int i;
  6387.     CHAR *ps = s;
  6388.  
  6389.     if (n < 1) {
  6390.         initpad();
  6391.     } else {
  6392.         for (i = 0; i < n; i++) {
  6393.             if (*ps > MAXPADPARMS)
  6394.               x29err[i+2] = *ps;
  6395.             else
  6396.               padparms[*ps] = *(ps+1);
  6397.             ps += 2;
  6398.         }
  6399.     }
  6400. }
  6401.  
  6402. /* Read PAD parameters */
  6403.  
  6404. VOID
  6405. readpad(s,n,r) CHAR *s; int n; CHAR *r; {
  6406.     int i;
  6407.     CHAR *ps = s;
  6408.     CHAR *pr = r;
  6409.  
  6410.     *pr++ = X29_PARAMETER_INDICATION;
  6411.     if (n > 0) {
  6412.         for (i = 0; i < n; i++, ps++) {
  6413.             if (*ps > MAXPADPARMS) {
  6414.                 x29err[i+2] = *ps++;
  6415.             } else {
  6416.                 *pr++ = *ps;
  6417.                 *pr++ = padparms[*ps++];
  6418.             }
  6419.         }
  6420.     } else {
  6421.         for (i = 1; i < MAXPADPARMS; i++) {
  6422.             *pr++ = i;
  6423.             *pr++ = padparms[i];
  6424.         }
  6425.     }
  6426. }
  6427.  
  6428. int
  6429. qbitpkt(s,n) CHAR *s; int n; {
  6430.     CHAR *ps = s;
  6431.     int x29cmd = *ps;
  6432.     CHAR *psa = s+1;
  6433.     CHAR x29resp[(MAXPADPARMS*2)+1];
  6434.  
  6435.     switch (x29cmd) {
  6436.  
  6437.         case X29_SET_PARMS:
  6438.             setpad (ps+1,n/2);
  6439.             if ((int)strlen((char *)x29err) > 2) {
  6440.                 ttol(x29err,(int)strlen((char *)x29err));
  6441.                 x29err[2] = '\0';
  6442.             }
  6443.             return (-2);
  6444.         case X29_READ_PARMS:
  6445.             readpad (ps+1,n/2,x29resp);
  6446.             setqbit ();
  6447.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  6448.             if ((int)strlen((char *)x29err) > 2) {
  6449.                 ttol(x29err,(int)strlen((char *)x29err));
  6450.                 x29err[2] = '\0';
  6451.             }
  6452.             resetqbit();
  6453.             break;
  6454.         case X29_SET_AND_READ_PARMS:
  6455.             setpad (ps+1,n/2);
  6456.             readpad (ps+1,n/2,x29resp);
  6457.             setqbit();
  6458.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  6459.             if ((int)strlen((char *)x29err) > 2) {
  6460.                 ttol (x29err,(int)strlen((char *)x29err));
  6461.                 x29err [2] = '\0';
  6462.             }
  6463.             resetqbit();
  6464.             return (-2);
  6465.         case X29_INVITATION_TO_CLEAR:
  6466.             (VOID) x25clear();
  6467.             return (-1);
  6468.         case X29_INDICATION_OF_BREAK:
  6469.             break;
  6470.     }
  6471.     return (0);
  6472. }
  6473.  
  6474. /* PAD break action processor */
  6475.  
  6476. VOID
  6477. breakact() {
  6478.     extern char x25obuf[MAXOX25];
  6479.     extern int obufl;
  6480.     extern int active;
  6481.     extern unsigned char tosend;
  6482.     static CHAR indbrk[3] = {
  6483.         X29_INDICATION_OF_BREAK,
  6484.         PAD_SUPPRESSION_OF_DATA,
  6485.         1
  6486.     };
  6487.     CHAR intudat, cause, diag;
  6488.  
  6489.     if (x25stat() < 0) return;  /* Ignore if no virtual call established */
  6490.  
  6491.     if (padparms[PAD_BREAK_ACTION] != 0) /* Forward condition */
  6492.         if (ttol((CHAR *)x25obuf,obufl) < 0) {
  6493.             perror ("\r\nCan't send characters");
  6494.             active = 0;
  6495.         } else {
  6496.             bzero (x25obuf,sizeof(x25obuf));
  6497.             obufl = 0;
  6498.             tosend = 0;
  6499.         };
  6500.  
  6501.     switch (padparms[PAD_BREAK_ACTION]) {
  6502.  
  6503.        case 0 : break;                  /* do nothing */
  6504.        case 1 : /* send interrupt packet with interrupt user data field = 1 */
  6505.                 intudat = 1;
  6506.                 x25intr (intudat);
  6507.                 break;
  6508.        case 2 : /* send reset packet with cause and diag = 0 */
  6509.                 cause = diag = 0;
  6510.                 x25reset (cause,diag);
  6511.                 break;
  6512.        case 5 : /* send interrupt packet with interrupt user data field = 0 */
  6513.                 intudat = 0;
  6514.                 x25intr (intudat);
  6515.                 setqbit ();
  6516.                 /* send indication of break without a parameter field */
  6517.                 ttoc(X29_INDICATION_OF_BREAK);
  6518.                 resetqbit ();
  6519.                 break;
  6520.        case 8 : active = 0;             /* leave data transfer */
  6521.                 conol ("\r\n");
  6522.                 break;
  6523.        case 21: /* send interrupt packet with interrupt user data field = 0 */
  6524.                 intudat = 0;
  6525.                 x25intr (intudat);
  6526.                 setpad (indbrk+1,2);    /* set pad to discard input */
  6527.                 setqbit ();
  6528.                 /* send indication of break with parameter field */
  6529.                 ttol (indbrk,sizeof(indbrk));
  6530.                 resetqbit ();
  6531.                 break;
  6532.      }
  6533. }
  6534.  
  6535. /* X.25 support functions */
  6536.  
  6537. X25_CAUSE_DIAG diag;
  6538.  
  6539. /*
  6540.   Convert a null-terminated string representing an X.121 address
  6541.   to a packed BCD form.
  6542. */
  6543. int
  6544. pkx121(str,bcd) char *str; CHAR *bcd; {
  6545.     int i, j;
  6546.     u_char c;
  6547.  
  6548.     i = j = 0;
  6549.     while (str[i]) {
  6550.         if (i >= 15 || str [i] < '0' || str [i] > '9')
  6551.           return (-1);
  6552.         c = str [i] - '0';
  6553.         if (i & 1)
  6554.           bcd [j++] |= c;
  6555.         else
  6556.           bcd [j] = c << 4;
  6557.         i++;
  6558.     }
  6559.     return (i);
  6560. }
  6561.  
  6562. /* Reads and prints X.25 diagnostic */
  6563.  
  6564. int
  6565. x25diag () {
  6566.     int i;
  6567.  
  6568.     bzero ((char *)&diag,sizeof(diag));
  6569.     if (ioctl(ttyfd,X25_RD_CAUSE_DIAG,&diag)) {
  6570.         perror ("Reading X.25 diagnostic");
  6571.         return(-1);
  6572.     }
  6573.     if (diag.datalen > 0) {
  6574.         printf ("X.25 Diagnostic :");
  6575.         for (i = 0; i < (int)diag.datalen; i++)
  6576.           printf(" %02h",diag.data[i])+
  6577.         printf ("\r\n");
  6578.     }
  6579.     return(0);
  6580. }
  6581.  
  6582. /* X.25 Out-of-Band Signal Handler */
  6583.  
  6584. SIGTYP
  6585. x25oobh(foo) int foo; {
  6586.     int oobtype;
  6587.     u_char oobdata;
  6588.     int t;
  6589.  
  6590.     (VOID) signal(SIGURG,x25oobh);
  6591.     do {
  6592.         if (ioctl(ttyfd,X25_OOB_TYPE,&oobtype)) {
  6593.             perror ("Getting signal type");
  6594.             return;
  6595.         }
  6596.         switch (oobtype) {
  6597.           case INT_DATA:
  6598.             if (recv(ttyfd,(char *)&oobdata,1,MSG_OOB) < 0) {
  6599.                 perror ("Receiving X.25 interrupt data");
  6600.                 return;
  6601.             }
  6602.             t = oobdata;
  6603.             printf ("\r\nInterrupt received, data = %d\r\n", t);
  6604.             break;
  6605.           case VC_RESET:
  6606.             printf ("\r\nVirtual circuit reset\r\n");
  6607.             x25diag ();
  6608.             break;
  6609.           case N_RESETS:
  6610.             printf ("\r\nReset timeout\r\n");
  6611.             break;
  6612.           case N_CLEARS:
  6613.             printf ("\r\nClear timeout\r\n");
  6614.             break;
  6615.           case MSG_TOO_LONG:
  6616.             printf ("\r\nMessage discarded, too long\r\n");
  6617.             break;
  6618.           default:
  6619.             if (oobtype) printf("\r\nUnknown oob type %d\r\n",oobtype);
  6620.             break;
  6621.         }
  6622.     } while (oobtype);
  6623. }
  6624.  
  6625. /* Send a X.25 interrupt packet */
  6626.  
  6627. int
  6628. #ifdef CK_ANSIC
  6629. x25intr(char intr)
  6630. #else
  6631. x25intr(intr) char intr;
  6632. #endif /* CK_ANSIC */
  6633. /* x25intr */ {
  6634.     if (send(ttyfd,&intr,1,MSG_OOB) < 0) return(-1);
  6635.     debug(F100,"X.25 intr","",0);
  6636.     return(0);
  6637. }
  6638.  
  6639. /* Reset X.25 virtual circuit */
  6640. int
  6641. #ifdef CK_ANSIC
  6642. x25reset(char cause, char diagn)
  6643. #else
  6644. x25reset(cause, diagn) char cause; char diagn;
  6645. #endif /* CK_ANSIC */
  6646. /* x25reset */ {
  6647.     bzero ((char *)&diag,sizeof(diag));
  6648.     diag.flags   = 0;
  6649.     diag.datalen = 2;
  6650.     diag.data[0] = cause;
  6651.     diag.data[1] = diagn;
  6652.     if (ioctl(ttyfd,X25_WR_CAUSE_DIAG,&diag) < 0)
  6653.       return(-1);
  6654.     debug(F100,"X.25 reset","",0);
  6655.     return(0);
  6656. }
  6657.  
  6658. /* Clear X.25 virtual circuit */
  6659. int
  6660. x25clear() {
  6661.     int i;
  6662.     debug(F100,"X.25 clear","",0);
  6663.     bzero ((char *)&diag,sizeof(diag));
  6664.     diag.flags = (1 << DIAG_TYPE);
  6665.     diag.datalen = 2;
  6666.     diag.data[0] = 0;
  6667.     diag.data[1] = 0;
  6668.     ioctl (ttyfd,X25_WR_CAUSE_DIAG,&diag); /* Send Clear Request */
  6669.     return(ttclos(0));                  /* Close socket */
  6670. }
  6671.  
  6672. /* X.25 status */
  6673. int
  6674. x25stat() {
  6675.     if (ttyfd == -1) return (-1);
  6676.     return(0);
  6677. }
  6678.  
  6679. /* Set Q_BIT on */
  6680. VOID
  6681. setqbit() {
  6682.     static int qbiton = 1 << Q_BIT;
  6683.     ioctl (ttyfd,X25_SEND_TYPE,&qbiton);
  6684. }
  6685.  
  6686. /* Set Q_BIT off */
  6687. VOID
  6688. resetqbit() {
  6689.     static int qbitoff = 0;
  6690.     ioctl (ttyfd,X25_SEND_TYPE,&qbitoff);
  6691. }
  6692.  
  6693. /* Read n characters from X.25 circuit into buf */
  6694.  
  6695. int
  6696. x25xin(n,buf) int n; CHAR *buf; {
  6697.     register int x, c;
  6698.     int qpkt;
  6699.  
  6700.     do {
  6701.         x = read(ttyfd,buf,n);
  6702.         if (buf[0] & (1 << Q_BIT)) { /* If Q_BIT packet, process it */
  6703.             /* If return -1 : invitation to clear; -2 : PAD changes */
  6704.             if ((c=qbitpkt(buf+1,x-2)) < 0) return(c);
  6705.             qpkt = 1;
  6706.         } else qpkt = 0;
  6707.     } while (qpkt);
  6708.  
  6709. #ifdef COMMENT                  /* Disabled by Stephen Riehm 19.12.97 */
  6710.     /* BUG!
  6711.      * if buf[] is full, then this null lands in nirvana!
  6712.      * I was unable to find any code which needs a trailing null in buf[]
  6713.      */
  6714.     if (x > 0) buf[x] = '\0';
  6715. #endif /* COMMENT */
  6716.     if (x < 1) x = -1;
  6717.     debug(F101,"x25xin x","",x);
  6718.  
  6719.     return(x);
  6720. }
  6721.  
  6722. #ifdef COMMENT /* NO LONGER NEEDED! */
  6723. /* X.25 read a line */
  6724.  
  6725. int
  6726. #ifdef PARSENSE
  6727. #ifdef CK_ANSIC
  6728. x25inl(CHAR *dest, int max,int timo, CHAR eol, CHAR start)
  6729. #else
  6730. x25inl(dest,max,timo,eol,start) int max,timo; CHAR *dest, eol, start;
  6731. #endif /* CK_ANSIC */
  6732. #else /* not PARSENSE */
  6733. #ifdef CK_ANSIC
  6734. x25inl(CHAR *dest, int max,int timo, CHAR eol)
  6735. #else
  6736. x25inl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  6737. #endif /* __SDTC__ */
  6738. #endif /*PARSENSE */
  6739.  /* x25inl */ {
  6740.     CHAR *pdest;
  6741.     int pktype, goteol, rest, n;
  6742.     int i, flag = 0;
  6743.     extern int ttprty, ttpflg;
  6744.     int ttpmsk;
  6745.  
  6746.     ttpmsk = (ttprty) ? 0177 : 0377;    /* Set parity stripping mask */
  6747.  
  6748.     debug(F101,"x25inl max","",max);
  6749.     debug(F101,"x25inl eol","",eol);
  6750.     pdest  = dest;
  6751.     rest   = max;
  6752.     goteol = 0;
  6753.     do {
  6754.         n = read(ttyfd,pdest,rest);
  6755.         n--;
  6756.         pktype = *pdest & 0x7f;
  6757.         switch (pktype) {
  6758.           case 1 << Q_BIT:
  6759.             if (qbitpkt(pdest+1,--n) < 0) return(-2);
  6760.             break;
  6761.           default:
  6762.             if (flag == 0) { /* if not in packet, search start */
  6763.                 for (i = 1; (i < n) &&
  6764.                      !(flag = ((dest[i] & 0x7f) == start));
  6765.                      i++);
  6766.                 if (flag == 0) { /* not found, discard junk */
  6767.                     debug(F101,"x25inl skipping","",n);
  6768.                     continue;
  6769.                 } else {                /* found, discard junk before start */
  6770.                     int k;
  6771.                     n = n - i + 1;
  6772.                     for (k = 1; k <= n; k++, i++) dest[k] = dest[i];
  6773.                 }
  6774.             }
  6775.             for (i = 0; (i < n) && /* search for eol */
  6776.                  !(goteol=(((*pdest = *(pdest+1)&ttpmsk)&0x7f)== eol));
  6777.                  i++,pdest++);
  6778.             *pdest = '\0';
  6779.             rest -= n;
  6780.         }
  6781.     } while ((rest > 0) && (!goteol));
  6782.  
  6783.     if (goteol) {
  6784.         n = max - rest;
  6785.         debug (F111,"x25inl X.25 got",(char *) dest,n);
  6786.         if (timo) ttimoff();
  6787.         if (ttpflg++ == 0 && ttprty == 0) {
  6788.             if ((ttprty = parchk(dest,start,n)) > 0) {
  6789.                 int j;
  6790.                 debug(F101,"x25inl senses parity","",ttprty);
  6791.                 debug(F110,"x25inl packet before",(char *)dest,0);
  6792.                 ttpmsk = 0x7f;
  6793.                 for (j = 0; j < n; j++)
  6794.                   dest[j] &= 0x7f; /* Strip parity from packet */
  6795.                 debug(F110,"x25inl packet after ",dest,0);
  6796.             } else {
  6797.                 debug(F101,"parchk","",ttprty);
  6798.                 if (ttprty < 0) { ttprty = 0; n = -1; }
  6799.             }
  6800.         }
  6801.         ttimoff();
  6802.         return(n);
  6803.     }
  6804.     ttimoff();
  6805.     return(-1);
  6806. }
  6807. #endif /* COMMENT */
  6808. #endif /* SUNX25 */
  6809.  
  6810. #ifdef IBMX25
  6811. /*
  6812.  * IBM X25 support - using the NPI streams interface
  6813.  * written by Stephen Riehm, pc-plus, Munich Germany
  6814.  */
  6815.  
  6816. /* riehm: missing functions / TODO list */
  6817.  
  6818. /*
  6819.   x25intr() - Send an interrupt packet
  6820. */
  6821.  
  6822. /* return an error message depending on packet type */
  6823. char *
  6824. x25err(n) int n; {
  6825.     static char buf[30];
  6826.     switch (n) {
  6827.       case NBADADDR:     return "invalid address";
  6828.       case NBADOPT:      return "invalid options";
  6829.       case NACCESS:      return "no permission";
  6830.       case NNOADDR:      return "unable to allocate address";
  6831.       case NOUTSTATE:    return "invalid state";
  6832.       case NBADSEQ:      return "invalid sequence number";
  6833.       case NSYSERR:      return "system error";
  6834.       case NBADDATA:     return "invalid data size";
  6835.       case NBADFLAG:     return "invalid flag";
  6836.       case NNOTSUPPORT:  return "unsupported primitive";
  6837.       case NBOUND:       return "address in use";
  6838.       case NBADQOSPARAM: return "bad QOS parameters";
  6839.       case NBADQOSTYPE:  return "bad QOS type";
  6840.       case NBADTOKEN:    return "bad token value";
  6841.       case NNOPROTOID:   return "protocol id could not be allocated";
  6842.       case NODDCUD:      return "odd length call user data";
  6843.       default: (void) sprintf(buf, "Unknown NPI error %d", n); return buf;
  6844.     }
  6845. }
  6846.  
  6847. /* turn a meaningless primitive number into a meaningful primitive name */
  6848. char *
  6849. x25prim(n) int n; {
  6850.     static char buf[30];
  6851.     switch(n) {
  6852.       case N_BIND_ACK:     return "N_BIND_ACK";
  6853.       case N_BIND_REQ:     return "N_BIND_REQ";
  6854.       case N_CONN_CON:     return "N_CONN_CON";
  6855.       case N_CONN_IND:     return "N_CONN_IND";
  6856.       case N_CONN_REQ:     return "N_CONN_REQ";
  6857.       case N_CONN_RES:     return "N_CONN_RES";
  6858.       case N_DATACK_IND:   return "N_DATAACK_IND";
  6859.       case N_DATACK_REQ:   return "N_DATAACK_REQ";
  6860.       case N_DATA_IND:     return "N_DATA_IND";
  6861.       case N_DATA_REQ:     return "N_DATA_REQ";
  6862.       case N_DISCON_IND:   return "N_DISCON_IND";
  6863.       case N_DISCON_REQ:   return "N_DISCON_REQ";
  6864.       case N_ERROR_ACK:    return "N_ERROR_ACK";
  6865.       case N_EXDATA_IND:   return "N_EXDATA_IND";
  6866.       case N_EXDATA_REQ:   return "N_EXDATA_REQ";
  6867.       case N_INFO_ACK:     return "N_INFO_ACK";
  6868.       case N_INFO_REQ:     return "N_INFO_REQ";
  6869.       case N_OK_ACK:       return "N_OK_ACK";
  6870.       case N_OPTMGMT_REQ:  return "N_OPTMGMT_REQ";
  6871.       case N_RESET_CON:    return "N_RESET_CON";
  6872.       case N_RESET_IND:    return "N_RESET_IND";
  6873.       case N_RESET_REQ:    return "N_RESET_REQ";
  6874.       case N_RESET_RES:    return "N_RESET_RES";
  6875.       case N_UDERROR_IND:  return "N_UDERROR_IND";
  6876.       case N_UNBIND_REQ:   return "N_UNBIND_REQ";
  6877.       case N_UNITDATA_REQ: return "N_UNITDATA_REQ";
  6878.       case N_UNITDATA_IND: return "N_UNITDATA_IND";
  6879.       default: (void) sprintf(buf, "UNKNOWN (%d)", n); return buf;
  6880.     }
  6881. }
  6882.  
  6883. /*****************************************************************************
  6884.  * Function: x25getmsg()
  6885.  * Description: get a STREAMS message, and check it for errors
  6886.  *
  6887.  * Parameters:
  6888.  * fd           - file descriptor to x25 device (opened)
  6889.  * control      - control buffer (pre-allocated)
  6890.  * ctl_size     - size of control buffer
  6891.  * data         - data buffer (pre-allocated)
  6892.  * data_size    - size of data buffer
  6893.  * flags        - flags for getmsg()
  6894.  * expected     - expected Primitive type
  6895.  *
  6896.  * Return Value:
  6897.  *      >= 0    OK (size of data returned)
  6898.  *      -1      error
  6899.  *
  6900.  */
  6901. int
  6902. x25getmsg( fd, control, ctl_size, data, data_size, get_flags, expected )
  6903.     int                 fd;             /* X25 device (opened) */
  6904.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  6905.     int                 ctl_size;       /* size of control buffer */
  6906.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  6907.     int                 data_size;      /* size of data buffer */
  6908.     int                 *get_flags;     /* getmsg() flags */
  6909.     int                 expected;       /* expected primitive type */
  6910. /* x25getmsg */ {
  6911.     int                 rc = 0;         /* return code */
  6912.     struct strbuf       *get_ctl=NULL;  /* getmsg control */
  6913.     struct strbuf       *get_data=NULL; /* getmsg data */
  6914.     int                 more = 0;       /* flag for more data etc */
  6915.     int                 file_status = -1; /* file async status */
  6916.     N_npi_ctl_t         * result;       /* pointer to simplify switch() */
  6917.     int                 packet_type = -1; /* unknown packet thus far */
  6918.  
  6919. #ifdef TRACE
  6920.     printf( "TRACE: entering x25getmsg\n" );
  6921. #endif /* TRACE */
  6922.  
  6923.     debug( F110, "x25getmsg waiting for packet ", x25prim( expected ), 0);
  6924.     /* prepare the control structures for getmsg */
  6925.     if (control) {
  6926.         if ((get_ctl = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  6927.           {
  6928.               perror("kermit x25getmsg(): get_ctl malloc failed\n");
  6929.               debug( F100, "x25getmsg malloc failed for get_ctl\n", "", 0);
  6930.               return(-1);
  6931.           }
  6932.         /* allow getmsg to return an unexpected packet type (which may be
  6933.          * larger than the expected one)
  6934.          */
  6935.         get_ctl->maxlen = NPI_MAX_CTL;
  6936.         get_ctl->len = 0;
  6937.         get_ctl->buf = (char *)control;
  6938.     } else {
  6939.         printf(
  6940.  "kermit x25getmsg(): internal error. control buffer MUST be pre-allocated!\n"
  6941.                );
  6942.         debug(F100,"x25getmsg internal error. no buffer pre-allocated","",0);
  6943.         return( -1 );
  6944.     }
  6945.     if (data) {
  6946.         if ((get_data = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  6947.           {
  6948.             perror("kermit x25getmsg(): get_data malloc failed\n");
  6949.             debug( F100, "x25getmsg malloc failed for get_data\n", "", 0);
  6950.             return(-1);
  6951.         }
  6952.         get_data->maxlen = (NPI_MAX_DATA < data_size ) ?
  6953.           NPI_MAX_DATA :
  6954.             data_size;
  6955.         get_data->len = 0;
  6956.         get_data->buf = (char *)data;
  6957.     }
  6958.  
  6959.     /* get an X.25 packet -
  6960.      * it may be any kind of packet, so check for special cases
  6961.      * it may be split into multiple parts - so loop if necessary
  6962.      */
  6963.     do {
  6964. #ifdef DEBUG
  6965.         printf( "kermit: x25getmsg(): getting a message\n" );
  6966. #endif /* DEBUG */
  6967.         errno = 0;
  6968.         if ((more = getmsg(fd, get_ctl, get_data, get_flags)) < 0) {
  6969. #ifdef DEBUG
  6970.             printf( "kermit: x25getmsg(): getmsg returned an error\n" );
  6971.             perror( "getmsg error was" );
  6972. #endif /* DEBUG */
  6973.             debug(F101, "x25getmsg getmsg returned an error\n", "", errno);
  6974.             if ((errno == EAGAIN) && (get_data && (get_data->len > 0)) ) {
  6975.                 /* was in non-blocking mode, nothing to get, but we're
  6976.                  * already waiting for the rest of the packet -
  6977.                  * switch to blocking mode for the next read.
  6978.                  * file_status used to reset file status before returning
  6979.                  */
  6980.                 if ((file_status = fcntl(fd, F_GETFL, 0)) < 0
  6981.                     || fcntl(fd, F_SETFL, file_status & ~O_NDELAY) < 0)
  6982.                   {
  6983.                       perror("x25getmsg(): couldn't change x25 blocking mode");
  6984.                       debug(F101,
  6985.                             "x25getmsg fcntl returned an error\n", "", errno);
  6986.                       /* netclos(); */
  6987.                       rc = -1;
  6988.                       break;
  6989.                   } else {
  6990.                       /* loop again into a blocking getmsg() */
  6991.                       continue;
  6992.                   }
  6993.             } else {
  6994.                 /* no data to get in non-blocking mode - return empty handed */
  6995.                 perror( "x25getmsg(): getmsg failed" );
  6996.                 debug(F101,"x25getmsg getmsg returned an error\n", "", errno);
  6997.                 rc = -1;
  6998.                 break;
  6999.             }
  7000.         } else if (more & MORECTL) {
  7001.             /* panic - the control information was larger than the
  7002.              * maximum control buffer size!
  7003.              */
  7004.             /* riehm: close connection? */
  7005. #ifdef DEBUG
  7006.             printf("x25getmsg(): received partial control packet - panic\n");
  7007. #endif /* DEBUG */
  7008.             debug( F101, "x25getmsg getmsg bad control block\n", "", errno);
  7009.             rc = -1;
  7010.             break;
  7011.         }
  7012.  
  7013.         if (result = (N_npi_ctl_t *)control) {
  7014.             packet_type = result->bind_ack.PRIM_type;
  7015.             if (packet_type != N_OK_ACK) {
  7016.                 x25lastmsg = packet_type;
  7017.             }
  7018.         }
  7019. #ifdef DEBUG
  7020.         /* printf( "kermit: x25getmsg(): getting " ); */
  7021.         if (get_ctl->len > 0) {
  7022.             x25dump_prim(result);
  7023.         }
  7024.         debug(F110,
  7025.               "x25getmsg got packet ",
  7026.               x25prim( result->bind_ack.PRIM_type ),
  7027.               0
  7028.               );
  7029. #endif /* DEBUG */
  7030.  
  7031.         if (get_ctl->len >= (int)sizeof(result->bind_ack.PRIM_type)) {
  7032.             /* not as pretty as a switch(), but switch can't handle
  7033.              * runtime variable values :-(
  7034.              */
  7035.             if (packet_type == expected ) {
  7036.                 /* got what we wanted, special case for DATA_IND
  7037.                  * packets though */
  7038.                 /* riehm: check Q-bit ? */
  7039. #ifdef DEBUG
  7040.                 printf("x25getmsg(): got expected packet\nrc is %d\n", rc);
  7041. #endif /* DEBUG */
  7042.                 if (packet_type == N_DATA_IND ) {
  7043.                     /* data received. May be incomplete, even though
  7044.                      * getmsg returned OK
  7045.                      */
  7046.                     if (result->data_ind.DATA_xfer_flags & N_MORE_DATA_FLAG)
  7047.                         more |= MOREDATA;
  7048.                     if (result->data_ind.DATA_xfer_flags & N_RC_FLAG)
  7049.                         printf( "x25getmsg(): data packet wants ack\n" );
  7050.                 }
  7051.             } else if( packet_type == N_DISCON_IND) {
  7052.                 printf( "X25 diconnected\n" );
  7053.                 /* riehm: need to acknowledge a disconnection? */
  7054.                 x25clear();
  7055.                 /* x25unbind( ttyfd ); */
  7056.                 rc = -1;
  7057.             } else if( packet_type == N_ERROR_ACK) {
  7058.                 errno = result->error_ack.UNIX_error;
  7059.                 perror( "X25 error received" );
  7060.                 rc = -1;
  7061.             } else {
  7062.                 printf("x25getmsg(): failed %s\n", x25err(packet_type));
  7063.                 rc = -1;
  7064.             }
  7065.         }
  7066. #ifdef COMMENT
  7067.         else {
  7068.             /* Panic - no control data */
  7069.             printf( "kermit: x25getmsg(): no control data with packet\n" );
  7070.             rc = -1;
  7071.         }
  7072. #endif /* COMMENT */
  7073.  
  7074.         if (get_data && (get_data->len >= 0)) {
  7075.             get_data->buf += get_data->len;
  7076.             get_data->maxlen -= get_data->len;
  7077.         }
  7078.     } while ((rc == 0)
  7079.              && (get_data && (get_data->maxlen > 0))
  7080.              && (more & MOREDATA)
  7081.              );
  7082.  
  7083.     /* return the file status to its original value, unless its still
  7084.      * set to -1, or one of the fcntl's failed */
  7085.     if ((file_status >= 0) && fcntl(fd, F_SETFL, file_status) < 0)
  7086.         rc = -1;
  7087.  
  7088.     /*
  7089.      * Verify that we received an expected primitive
  7090.      * there is apparantly an error case where the primitive is set
  7091.      * correctly, but there is not enough data in the control structure
  7092.      */
  7093.     if ((packet_type != expected) && (get_ctl->len >= ctl_size) ) {
  7094.         fprintf(stderr,
  7095.                 "x25getmsg(): %s NOT received. Primitive received was %s\n",
  7096.                 x25prim( expected ), x25prim( packet_type ));
  7097.         debug(F110, "x25getmsg got an unexpected packet ",
  7098.               x25prim(packet_type),
  7099.               0
  7100.               );
  7101.         rc = -1;
  7102.     }
  7103.  
  7104.     if (rc == 0) {
  7105.         if (get_data && ( get_data->len >= 0)) {
  7106.             rc = get_data->len;
  7107.         }
  7108.     }
  7109.  
  7110.     if (get_ctl)  { free(get_ctl); get_ctl = NULL; }
  7111.     if (get_data) { free(get_data); get_data = NULL; }
  7112.  
  7113. #ifdef COMMENT
  7114. #ifdef DEBUG
  7115.     printf( "kermit x25getmsg(): returning %d\n", rc );
  7116. #endif /* DEBUG */
  7117. #endif /* COMMENT */
  7118.     debug(F110, "x25getmsg returning packet ", x25prim( packet_type ), 0);
  7119.  
  7120. #ifdef TRACE
  7121.     printf( "TRACE: leaving x25getmsg\n" );
  7122. #endif /* TRACE */
  7123.     return(rc);
  7124. }
  7125.  
  7126. /*****************************************************************************
  7127.  * Function: x25putmsg()
  7128.  *
  7129.  * Description:
  7130.  *      send a message to a X25 STREAM
  7131.  *
  7132.  * Parameters:
  7133.  *      fd              - file descriptor to x25 device (opened)
  7134.  *      control         - control buffer (pre-allocated)
  7135.  *      data            - data buffer (pre-allocated)
  7136.  *      data_len        - length of data to be transmitted
  7137.  *      put_flags       - flags for putmsg()
  7138.  *
  7139.  * Return Value:
  7140.  *      >= 0    number of bytes transmitted
  7141.  *      -1      error
  7142.  */
  7143. int
  7144. x25putmsg(fd, control, data, data_len, put_flags)
  7145.     int                 fd;             /* X25 device (opened) */
  7146.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  7147.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  7148.     int                 data_len;       /* length of data (not the size of
  7149.                                            the buffer) */
  7150.     int                 *put_flags;     /* putmsg() flags */
  7151. /* x25putmsg */ {
  7152.     int                 rc = 0;         /* return code */
  7153.     ulong               type;           /* primitive type */
  7154.     struct strbuf       *put_ctl = NULL; /* putmsg control */
  7155.     struct strbuf       *put_data = NULL; /* putmsg data */
  7156.  
  7157. #ifdef TRACE
  7158.     printf( "TRACE: entering x25putmsg\n" );
  7159. #endif /* TRACE */
  7160.  
  7161. #ifdef DEBUG
  7162.     printf( "kermit: x25putmsg(): putting " );
  7163.     x25dump_prim( control );
  7164.     printf( "\tdata:\t\t" );
  7165.     x25dump_data( data, 0, data_len );
  7166.     debug(F110,"x25putmsg: putting packet ",x25prim(control->PRIM_type),0);
  7167. #endif /* DEBUG */
  7168.  
  7169.     if (control) {
  7170.         put_ctl = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  7171.         if (put_ctl == NULL) {
  7172.             perror("kermit x25putmsg(): put_ctl malloc failed\n");
  7173.             return(-1);
  7174.         }
  7175.         put_ctl->maxlen = 0;                    /* unused by putmsg */
  7176.         put_ctl->len = NPI_MAX_CTL;
  7177.         put_ctl->buf = (char *)control;
  7178.     }
  7179.     if (data && ( data_len > 0)) {
  7180.         put_data = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  7181.         if( put_data == NULL) {
  7182.             perror("kermit x25putmsg(): put_data malloc failed\n");
  7183.             return(-1);
  7184.         }
  7185.         put_data->maxlen = 0;                   /* unused by putmsg */
  7186.         put_data->len = data_len;
  7187.         put_data->buf = (char *)data;
  7188.     }
  7189.  
  7190.     errno = 0;
  7191.     rc = putmsg (fd, put_ctl, put_data, 0);
  7192.     if (rc < 0) {
  7193.         printf("x25putmsg(): couldn't put %s\n",x25prim(control->PRIM_type));
  7194.         perror("kermit: x25putmsg(): putmsg failed");
  7195.         return(-1);
  7196.     }
  7197.  
  7198.     /* riehm: this should perhaps be discounted! */
  7199.     x25lastmsg = control->PRIM_type;
  7200.  
  7201. #ifdef COMMENT
  7202. #ifdef DEBUG
  7203.     printf( "kermit debug: x25putmsg() returning %d\n", data_len );
  7204. #endif /* DEBUG */
  7205. #endif /* COMMENT */
  7206.     debug( F101, "x25putmsg block size put ", "", data_len);
  7207.  
  7208. #ifdef TRACE
  7209.     printf( "TRACE: leaving x25putmsg\n" );
  7210. #endif /* TRACE */
  7211.  
  7212.     return( data_len );
  7213. }
  7214.  
  7215. /*****************************************************************************
  7216. * Function: x25bind
  7217. * Description:  The bind submitted to NPI provides the information required
  7218. *               by the packet layer for it to listen for suitable incoming
  7219. *               calls.
  7220. *
  7221. * WARNING:
  7222. *
  7223. * This routine needs to be called in a completely different manner for
  7224. * the client and server side. When starting a client, the
  7225. * num_waiting_calls and CUD information should all be set to 0! The
  7226. * client's CUD must be inserted in the CONN_REQ data block.
  7227. * When starting a server, the CUD must be set to a CUD pattern, and
  7228. * the number of waiting calls should be set to a number other than 0.
  7229. * (num waiting calls is the number of incomming calls which are to be
  7230. * put on hold while the server is servicing another client.)
  7231. *
  7232. * Who invented this crap?
  7233. *
  7234. * Parameters:
  7235. *       fd              - X25 device (opened)
  7236. *       addr            - local address
  7237. *       cud             - User Data (null terminated)
  7238. *       cud_len         - User Data length
  7239. *       num_waiting_calls - number of outstanding calls allowed on this stream
  7240. *       line            - logical port number (1)
  7241. *       flags           - 0, DEFAULT_LISTENER or TOKEN_REQUEST
  7242. *
  7243. * Return Value:
  7244. *       if binding is successful, 0 is returned for a client, and a token is
  7245. *       returned for a server
  7246. *
  7247. * Return code: 0 if successful
  7248. *              -1 if unsuccessful
  7249. *****************************************************************************/
  7250.  
  7251. ulong
  7252. x25bind(fd, addr, cud, cud_len, num_waiting_calls, line, bind_flags)
  7253.     int fd;                             /* X25 device (opened) */
  7254.     char * addr;                        /* local address */
  7255.     char * cud;                         /* Call User Data (null terminated) */
  7256.     int cud_len;                        /* User Data length */
  7257.     int num_waiting_calls;              /* Outstanding calls allowed */
  7258.     int line;                           /* logical port number */
  7259.     ulong bind_flags;           /* 0, DEFAULT_LISTENER or TOKEN_REQUEST */
  7260. /* x25bind */ {
  7261.     ulong rc;                           /* return code */
  7262.     int get_flags;                      /* priority flag passed to getmsg */
  7263.     int put_flags = 0;                  /* output flags for putmsg, always 0 */
  7264.     ulong type;                         /* primitive type */
  7265.     N_bind_req_t *bind_req;             /* pointer to N_BIND_REQ primitive */
  7266.     N_bind_ack_t *bind_ack;             /* pointer to N_BIND_ACK primitive */
  7267.     char *addtl_info;                   /* pointer to info in addition to
  7268.                                          * the N_BIND_REQ primitive that is
  7269.                                          * passed in the control structure
  7270.                                          * to putmsg */
  7271.     int addr_len = 0;                   /* length of address string */
  7272.     ulong bind_req_t_size;              /* for debugging only */
  7273.  
  7274. #ifdef TRACE
  7275.     printf("TRACE: entering x25bind\n" );
  7276. #endif /* TRACE */
  7277.  
  7278. #ifdef DEBUG
  7279.     printf("TRACE: x25bind( %d, %s, %s, %d, %d )\n",
  7280.            fd, addr, cud, line, bind_flags
  7281.            );
  7282. #endif /* DEBUG */
  7283.  
  7284.     /*
  7285.      * Allocate  and zero out space to hold the control portion of the
  7286.      * message passed to putmsg. This will contain the N_BIND_REQ
  7287.      * primitive and any additional info required for that.
  7288.      *
  7289.      * Note: allocated space is the size of the union typedef
  7290.      * N_npi_ctl_t to allow the use fo the generic x25putmsg routine.
  7291.      */
  7292.     bind_req = (N_bind_req_t *) malloc(sizeof( N_npi_ctl_t));
  7293.     if (bind_req == NULL) {
  7294.         perror("kermit: x25bind(): bind_req malloc failed");
  7295.         debug(F100, "x25bind bind_req malloc failed", "", 0);
  7296.         return(-1);
  7297.     }
  7298.     bzero((char *)bind_req, sizeof(N_npi_ctl_t));
  7299.  
  7300.     /* Build the Bind Request Primitive */
  7301.     bind_req->PRIM_type = (ulong) N_BIND_REQ;
  7302.  
  7303.     /* Note that the address length is n+2 and NOT n. Two bytes MUST preceed
  7304.      * the actual address in an N_BIND_REQ. The first byte contains the
  7305.      * line number being used with this address, and the second byte is the
  7306.      * X.121 address prefix, which must be zero.
  7307.      */
  7308.     addr_len = strlen(addr);
  7309.     bind_req->ADDR_length = (ulong) (addr_len + 2);
  7310.     bind_req->ADDR_offset = (ulong)(sizeof(N_bind_req_t));
  7311.     bind_req->CONIND_number = (ulong)num_waiting_calls; /* server only */
  7312.     bind_req->BIND_flags = (ulong) bind_flags; /* 0 in client */
  7313.     bind_req->PROTOID_length = (ulong) cud_len; /* 0 in client */
  7314.     if (cud_len == 0) {
  7315.         bind_req->PROTOID_offset = (ulong) 0;
  7316.     } else {
  7317.         /* need to remember the trailing NULL in the address - not
  7318.          * counted in the address length
  7319.          */
  7320.         bind_req->PROTOID_offset
  7321.           = (ulong) (sizeof(N_bind_req_t) + bind_req->ADDR_length);
  7322.     }
  7323.  
  7324.     /*
  7325.      * Now fill in the additional information required with this primitive
  7326.      * (address and protocol information (Call User Data))
  7327.      */
  7328.     addtl_info = (char *) ((void *)bind_req + bind_req->ADDR_offset);
  7329.     /*
  7330.      * The bitwise "&" ensures that the line number is only one byte long
  7331.      */
  7332.     *addtl_info++ = (char) line & 0xff;
  7333.     *addtl_info++ = (char) 0; /* X.121 format */
  7334.     bcopy( addr, addtl_info, addr_len ); /* include trailing null */
  7335.     addtl_info += addr_len;
  7336.     if (cud_len > 0)
  7337.       bcopy( cud, addtl_info, cud_len );
  7338.     /*
  7339.      * Call putmsg() to put the bind request message on the stream
  7340.      */
  7341.     if (x25putmsg(fd,
  7342.                   (N_npi_ctl_t*)bind_req,
  7343.                   (N_npi_data_t *)NULL,
  7344.                   0,
  7345.                   &put_flags
  7346.                   ) < 0) {
  7347.         printf( "kermit: x25bind(): x25putmsg failed\n" );
  7348.         return(-1);
  7349.     }
  7350.  
  7351.     /*
  7352.      * Allocate and zero out space for the N_BIND_ACK primitive
  7353.      */
  7354.     bind_ack = (N_bind_ack_t *) malloc(sizeof(N_npi_ctl_t));
  7355.     if (bind_ack == NULL){
  7356.         perror("kermit: x25bind(): bind_ack malloc failed");
  7357.         return(-1);
  7358.     }
  7359.     bzero(bind_ack, sizeof(N_npi_ctl_t));
  7360.     /*
  7361.      * Initialize the control structure and flag variable sent to getmsg
  7362.      */
  7363.     get_flags=0;
  7364.  
  7365.     /* get the ACK for the bind */
  7366. #ifdef DEBUG
  7367.     printf( "kermit: x25bind() trying to get a BIND_ACK\n" );
  7368. #endif /* DEBUG */
  7369.     rc = (ulong)x25getmsg( fd, (N_npi_ctl_t*)bind_ack,
  7370.             (int)sizeof( N_bind_ack_t ), (N_npi_data_t*)NULL, 0, &get_flags,
  7371.             N_BIND_ACK );
  7372.  
  7373.     /* turn quantitive return code into a qualitative one */
  7374.     if (rc > 0) rc = 0;
  7375.  
  7376.     /* if all went well, get the token from the acknowledgement packet */
  7377.     if ((bind_flags & TOKEN_REQUEST ) && ( rc >= 0)) {
  7378.         rc = bind_ack->TOKEN_value;
  7379.     }
  7380.  
  7381.     /* free up the memory we allocated earlier */
  7382.     free(bind_req);
  7383.     free(bind_ack);
  7384.  
  7385. #ifdef TRACE
  7386.     printf( "TRACE: leaving x25bind\n" );
  7387. #endif /* TRACE */
  7388.  
  7389.     return( rc );
  7390. }
  7391.  
  7392. /*****************************************************************************
  7393. * Function: x25call
  7394. * Description:  This routine builds and sends an N_CONN_REQ primitive, then
  7395. *               checks for an N_CONN_CON primitive in return.
  7396. *
  7397. * Parameters:
  7398. * fd    - file descriptor of stream
  7399. * caddr - called address (remote address)
  7400. *
  7401. * Functions Referenced:
  7402. * malloc()
  7403. * bzero()
  7404. * getmsg()
  7405. * putmsg()
  7406. *
  7407. * Return code:
  7408. * 0 - if successful
  7409. * -1 if not successful
  7410. *****************************************************************************/
  7411. int
  7412. x25call(fd, remote_nua, cud)
  7413.     int fd;                             /* X25 device (opened) */
  7414.     char * remote_nua;                  /* remote address to call */
  7415.     char * cud;                         /* call user data */
  7416. /* x25call */ {
  7417.     int rc;                             /* return code */
  7418.     int flags;                          /* Connection flags */
  7419.     int get_flags;                      /* priority flags for getmsg */
  7420.     ulong type;                         /* primitive type */
  7421.     N_conn_req_t *connreq_ctl;          /* pointer to N_CONN_REQ primitive */
  7422.     N_npi_data_t *connreq_data;         /* pointer to N_CONN_REQ data (CUD) */
  7423.     int connreq_data_len;               /* length of filled data buffer */
  7424.     N_conn_con_t *conncon_ctl;          /* pointer to N_CONN_CON primitive */
  7425.     N_npi_data_t *conncon_data;         /* pointer to any data associated with
  7426.                                          * the N_CONN_CON primitive */
  7427.     char *addtl_info;                   /* pointer to additional info needed
  7428.                                          * for N_CONN_REQ primitive */
  7429.     int addr_len;                       /* length of address */
  7430.  
  7431. #ifdef TRACE
  7432.     printf( "TRACE: entering x25call\n" );
  7433. #endif /* TRACE */
  7434.  
  7435. #ifdef DEBUG
  7436.     printf( "x25call( %d, %s )\n", fd, remote_nua );
  7437.     printf( "connecting to %s on fd %d\n", remote_nua, fd );
  7438. #endif /* DEBUG */
  7439.  
  7440.     /*
  7441.      * Allocate and zero out space for the N_CONN_REQ primitive
  7442.      * use the size of the generic NPI primitive control buffer
  7443.      */
  7444.     connreq_ctl  = (N_conn_req_t *) malloc(sizeof(N_npi_ctl_t));
  7445.     if (connreq_ctl == NULL){
  7446.         perror("kermit: x25call(): connreq_ctl malloc failed");
  7447.         return(-1);
  7448.     }
  7449.     bzero(connreq_ctl,sizeof(N_npi_ctl_t));
  7450.     /*
  7451.      * Build the Connection Request Primitive
  7452.      */
  7453.     flags = 0;
  7454.     connreq_ctl->PRIM_type = (ulong) N_CONN_REQ;
  7455.  
  7456.     /* Note that the address length is nchai+1 and not n+2. The line number
  7457.      * is only passed with the address for the bind. The first byte of
  7458.      * the address for the N_CONN primitives contains the X.121
  7459.      * address prefix, which must be zero. The remaining bytes are the
  7460.      * address itself.
  7461.      */
  7462.     addr_len = strlen( remote_nua );
  7463.     connreq_ctl->DEST_length = (ulong) (addr_len + 1);
  7464.     connreq_ctl->DEST_offset = (ulong) sizeof(N_conn_req_t);
  7465.     /* connreq_ctl->CONN_flags = (ulong)EX_DATA_OPT | REC_CONF_OPT; */
  7466.     connreq_ctl->CONN_flags = (ulong) 0;
  7467.     connreq_ctl->QOS_length = (ulong) 0;        /* unsupported in AIX 4.1 */
  7468.     connreq_ctl->QOS_offset = (ulong) 0;        /* unsupported in AIX 4.1 */
  7469.  
  7470.     addtl_info = (char *) ((void*)connreq_ctl + connreq_ctl->DEST_offset);
  7471.     *addtl_info++ = (char) 0; /* X.121 format */
  7472.     bcopy( remote_nua, addtl_info, addr_len );
  7473.  
  7474.     /*
  7475.      * setup the data buffer for the connection request
  7476.      */
  7477.     connreq_data  = (N_npi_data_t *) malloc(sizeof(N_npi_data_t));
  7478.     if (connreq_data == NULL){
  7479.         perror("kermit: x25call(): connreq_data malloc failed");
  7480.         return(-1);
  7481.     }
  7482.     bzero(connreq_data,sizeof(N_npi_data_t));
  7483.  
  7484.     /* facility selection needs to be put in the front of connreq_data */
  7485.     connreq_data_len = 0;
  7486.     connreq_data_len += x25facilities( (char *)connreq_data );
  7487.     if (cud && *cud) {
  7488.         bcopy(cud,
  7489.               (char *)((char *)connreq_data + connreq_data_len),
  7490.               strlen(cud)
  7491.               );
  7492.         connreq_data_len += strlen( cud );
  7493.         }
  7494.  
  7495.     /*
  7496.      * Call putmsg() to put the connection request message on the stream
  7497.      */
  7498.     rc = x25putmsg( fd, (N_npi_ctl_t*)connreq_ctl, connreq_data,
  7499.             connreq_data_len, &flags );
  7500.     if (rc < 0) {
  7501.         return(-1);
  7502.     }
  7503.  
  7504.     /*
  7505.      * Allocate and zero out space for the N_CONN_CON primitive
  7506.      */
  7507.     if ((conncon_ctl = (N_conn_con_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  7508.         perror("kermit: x25call(): conncon_ctl malloc failed");
  7509.         return(-1);
  7510.     }
  7511.     bzero(conncon_ctl, sizeof(N_npi_ctl_t));
  7512.  
  7513.     /*
  7514.      * Allocate and zero out space for any data associated with N_CONN_CON
  7515.      */
  7516.     if ( (conncon_data = (N_npi_data_t *) malloc(NPI_MAX_DATA)) == NULL) {
  7517.         perror("kermit: x25call(): conncon_data malloc failed");
  7518.         return(-1);
  7519.     }
  7520.     bzero(conncon_data, NPI_MAX_DATA);
  7521.  
  7522.     /* Initialize and build the structures for getmsg */
  7523.     get_flags=0;
  7524.  
  7525.     rc = x25getmsg( fd, (N_npi_ctl_t*)conncon_ctl, (int)sizeof( N_conn_con_t ),
  7526.             conncon_data, NPI_MAX_DATA, &get_flags, N_CONN_CON );
  7527.  
  7528.     /* turn quantitive return code into a qualitative one */
  7529.     if (rc > 0) rc = 0;
  7530.  
  7531.     /* Free the space that we no longer need */
  7532.     if (connreq_ctl) { free(connreq_ctl); connreq_ctl = NULL; }
  7533.     if (conncon_ctl) { free(conncon_ctl); conncon_ctl = NULL; }
  7534.     if (conncon_data) { free(conncon_data); conncon_data = NULL; }
  7535.  
  7536. #ifdef TRACE
  7537.     printf( "TRACE: leaving x25call\n" );
  7538. #endif /* TRACE */
  7539.  
  7540.     return(rc);
  7541. }
  7542.  
  7543. /*****************************************************************************
  7544.  * Function: x25getcall
  7545.  *
  7546.  * Description: This routine checks for an incomming call, verified
  7547.  * that it is a CONNIND (connection indication) message, and then
  7548.  * accepts the call and returns the file descriptor of the new stream
  7549.  *
  7550.  * Parameters:
  7551.  * fd   - file descriptor of listening stream
  7552.  *
  7553.  * Return Codes:
  7554.  * callfd       - file descriptor of connected incomming call.
  7555.  *              - set to -1 if an error occured
  7556.  *
  7557.  *****************************************************************************/
  7558. int
  7559. x25getcall(fd) int fd; {
  7560.     int x25callfd;                      /* fd of incomming call */
  7561.     N_conn_ind_t *connind_ctl;          /* connind controll buffer */
  7562.     N_npi_data_t *connind_data;         /* connind data buffer */
  7563.     int get_flags;                      /* flags for getmsg */
  7564.     ulong flags;                        /* connection flags */
  7565.     int rc;                             /* return code */
  7566.  
  7567.     extern x25addr_t remote_nua;        /* remote X.25 addr global var */
  7568.  
  7569. #ifdef TRACE
  7570.     printf( "TRACE: entering x25getcall\n" );
  7571. #endif /* TRACE */
  7572.  
  7573.     /* allocate space for connection indication buffers */
  7574.     if ((connind_ctl = (N_conn_ind_t *)malloc(sizeof(N_npi_ctl_t))) == NULL) {
  7575.         perror("kermit: x25getcall(): connind_ctl malloc failed");
  7576.         return (-1);
  7577.     }
  7578.     bzero(connind_ctl, sizeof(N_npi_ctl_t));
  7579.  
  7580.     if ((connind_data = (N_npi_data_t *)malloc(NPI_MAX_DATA)) == NULL) {
  7581.         perror("kermit: x25getcall(): connind_data malloc failed");
  7582.         return (-1);
  7583.     }
  7584.     bzero(connind_data, NPI_MAX_DATA);
  7585.  
  7586.     /* initialise control structures */
  7587.     get_flags = 0;
  7588.  
  7589.     /* call getmsg to check for a connection indication */
  7590.     if (x25getmsg(fd,
  7591.                   (N_npi_ctl_t*)connind_ctl,
  7592.                   (int)sizeof(N_conn_ind_t),
  7593.                   connind_data,
  7594.                   NPI_MAX_DATA,
  7595.                   &get_flags,
  7596.                   N_CONN_IND
  7597.                   ) < 0) {
  7598. #ifdef DEBUG
  7599.         printf( "x25getcall(): errno is: %d\n", errno );
  7600. #endif /* DEBUG */
  7601.         perror ("x25getcall(): getmsg failed");
  7602.         return(-1);
  7603.     }
  7604.  
  7605.     /* a connection indication was received
  7606.      * - pull it to bits and answer the call
  7607.      */
  7608.     x25seqno = connind_ctl->SEQ_number;
  7609.     flags = connind_ctl->CONN_flags;
  7610. #ifdef DEBUG
  7611.     printf( "setting remote_nua to a new value due to incomming call\n" );
  7612. #endif /* DEBUG */
  7613.     /*
  7614.      * no guarantee that the address is null terminated, ensure that
  7615.      * after copying that it is (assumption: remote_nua is longer than
  7616.      * the address + 1)
  7617.      */
  7618.     bzero(remote_nua, sizeof(remote_nua));
  7619.     /* note: connind_ctl contains a x121 address, which has a null as
  7620.      * the FIRST character - strip it off!
  7621.      */
  7622.     ckstrncpy(remote_nua,
  7623.             (char*)((char*)connind_ctl + connind_ctl->SRC_offset + 1),
  7624.             connind_ctl->SRC_length - 1
  7625.             );
  7626. #ifdef DEBUG
  7627.     printf( "remote_nua set to new value of %s\n", remote_nua );
  7628. #endif /* DEBUG */
  7629.  
  7630.     /* errors handled by callee */
  7631.     x25callfd = x25accept(x25seqno, flags);
  7632.  
  7633.     /* free the malloc'd buffers */
  7634.     if (connind_ctl) { free(connind_ctl); connind_ctl = NULL; }
  7635.     if (connind_data) { free(connind_data); connind_data = NULL; }
  7636.  
  7637. #ifdef TRACE
  7638.     printf( "TRACE: leaving x25getcall\n" );
  7639. #endif /* TRACE */
  7640.  
  7641.     /* return the file descriptor (or error if < 0) */
  7642.     return( x25callfd );
  7643. }
  7644.  
  7645. /*****************************************************************************
  7646.  * Function: x25accept
  7647.  *
  7648.  * Description: accept an incomming call
  7649.  *              This essentially means opening a new STREAM and sending
  7650.  *              an acknowledge back to the caller.
  7651.  *
  7652.  * Parameters:
  7653.  *      seqno   - sequence number for acknowledgement
  7654.  *      flags   - flags passed to us by the caller
  7655.  *
  7656.  * Return Codes:
  7657.  *      fd      - file descriptor of new STREAM
  7658.  *                set to -1 if an error occured
  7659.  *
  7660.  *****************************************************************************/
  7661. int
  7662. x25accept(seqno,flags)
  7663.     ulong seqno;                        /* connection sequence number */
  7664.     ulong flags;                        /* connection flags */
  7665. /* x25accept */ {
  7666.     int x25callfd;                      /* fd for incomming call */
  7667.     int get_flags;                      /* priority flags for getmsg */
  7668.     int put_flags = 0;                  /* flags for putmsg, always 0 */
  7669.     int addr_len;                       /* length of local address */
  7670.     ulong token;                        /* connection token */
  7671.     N_conn_res_t *conn_res;             /* N_CONN_RES primitive */
  7672.     N_ok_ack_t *ok_ack;                 /* N_OK_ACK primitive */
  7673.     char *addtl_info;                   /* temp pointer */
  7674.     int rc;                             /* temporary return code */
  7675.  
  7676. /* global variables from ckcmai.c */
  7677.     extern int revcall, closgr, cudata;
  7678.     extern char udata[];
  7679.     extern x25addr_t local_nua;         /* local X.25 address */
  7680.     extern char x25name[];              /* x25 device name (sx25a0) */
  7681.     extern char x25dev[];               /* x25 device file /dev/x25pkt */
  7682.     extern int x25port;                 /* logical port to use */
  7683.     ulong bind_flags = 0;               /* flags for binding the X25 stream */
  7684.  
  7685. #ifdef TRACE
  7686.     printf( "TRACE: entering x25accept\n" );
  7687. #endif /* TRACE */
  7688.  
  7689.     /* open a new packet level stream */
  7690.     if ((x25callfd = open(x25dev, O_RDWR)) < 0) {
  7691.         perror ("kermit: x25accept(): X.25 device open error");
  7692.         debug(F101,"x25accept() device open error","",errno);
  7693.         return(-1);
  7694.     }
  7695.  
  7696.     /* push the NPI onto the STREAM */
  7697.     if (ioctl(x25callfd,I_PUSH,"npi") < 0) {
  7698.         perror( "kermit: x25accept(): couldn't push npi on the X25 stream" );
  7699.         debug(F101,"x25accept can't push npi on the X25 stream","",errno);
  7700.         return (-1);
  7701.     }
  7702.  
  7703.     /* bind kermit server to the local X25 address */
  7704.     /* taken from /usr/samples/sx25/npi/npiserver.c (AIX 4) */
  7705.     bind_flags |= TOKEN_REQUEST;
  7706.     token = x25bind(x25callfd,local_nua,(char *)NULL,0,0,x25port,bind_flags);
  7707.     if (token < 0) {
  7708.         printf( "kermit: x25accept(): couldn't bind to local X25 address\n" );
  7709.         netclos();
  7710.         return(-1);
  7711.     }
  7712.  
  7713.     /* allocate connection response primitive */
  7714.     if ((conn_res = (N_conn_res_t *)malloc( NPI_MAX_CTL )) == NULL) {
  7715.         perror("kermit: x25accept(): conn_res malloc failed");
  7716.         return (-1);
  7717.     }
  7718.     bzero((char *)conn_res, NPI_MAX_CTL);
  7719.  
  7720.     /* setup connection response primitive */
  7721.     addr_len = strlen( local_nua );
  7722.     conn_res->PRIM_type = (ulong)N_CONN_RES;
  7723.     conn_res->TOKEN_value = token;
  7724.     /* note address length is n+1 to accomodate the X.121 address prefix */
  7725.     conn_res->RES_length = (ulong)(addr_len + 1);
  7726.     conn_res->RES_offset = (ulong)sizeof( N_conn_res_t );
  7727.     conn_res->SEQ_number = seqno;
  7728.     conn_res->CONN_flags = 0;
  7729.     conn_res->QOS_length = 0;           /* unsupported - must be 0 (!?) */
  7730.     conn_res->QOS_offset = 0;
  7731.  
  7732.     addtl_info = (char *)((char *)conn_res + conn_res->RES_offset);
  7733.     *addtl_info++ = (char)0;    /* X.121 address prefix */
  7734.     bcopy( local_nua, addtl_info, addr_len );
  7735.  
  7736.     /*
  7737.      * send off the connect response
  7738.      */
  7739.     if (x25putmsg(x25callfd,
  7740.                   (N_npi_ctl_t*)conn_res,
  7741.                   (N_npi_data_t *)NULL,
  7742.                   0,
  7743.                   &put_flags
  7744.                   ) < 0 ) {
  7745.         perror("kermit: x25accept(): putmsg connect response failed");
  7746.         return(-1);
  7747.     }
  7748.  
  7749.     /*
  7750.      * Allocate and zero out space for the OK_ACK primitive
  7751.      */
  7752.     if ((ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  7753.         perror("kermit: x25call(): ok_ack malloc failed");
  7754.         return(-1);
  7755.     }
  7756.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  7757.  
  7758.     /* Initialize and build the structures for getmsg */
  7759.     get_flags=0;
  7760.  
  7761.     rc = (int)x25getmsg(x25callfd,
  7762.                         (N_npi_ctl_t*)ok_ack,
  7763.                         (int)sizeof(N_ok_ack_t),
  7764.                         (N_npi_data_t*)NULL,
  7765.                         0,
  7766.                         &get_flags,
  7767.                         N_OK_ACK
  7768.                         );
  7769.     if (rc == 0) {
  7770.         /* sequence number is only for disconnecting when not connected !? */
  7771.         x25seqno = 0;
  7772.     }
  7773.  
  7774.     /* free up malloc'ed buffer space */
  7775.     if (conn_res) { free(conn_res); conn_res = NULL; }
  7776.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  7777.  
  7778. #ifdef TRACE
  7779.     printf( "TRACE: leaving x25accept\n" );
  7780. #endif /* TRACE */
  7781.  
  7782.     return( ( rc >= 0 ) ? x25callfd : -1 );
  7783. }
  7784.  
  7785. /*****************************************************************************
  7786.  * Function: x25unbind
  7787.  *
  7788.  * Description:  This subroutine builds and sends an unbind request and gets
  7789.  * the acknowledgement for it.
  7790.  *
  7791.  * Parameters:
  7792.  * fd - File descriptor of the stream
  7793.  *
  7794.  * Functions Referenced:
  7795.  * getmsg()
  7796.  * putmsg()
  7797.  * malloc()
  7798.  * bzero()
  7799.  *
  7800.  * Return code:
  7801.  * 0 - if successful
  7802.  * -1 - if not successful
  7803.  *****************************************************************************/
  7804. int
  7805. x25unbind(fd) int fd; {                 /* X25 device (opened) */
  7806.     int rc;                             /* return code */
  7807.     int flags;                          /* bind flags */
  7808.     int get_flags;                      /* priority flag for getmsg */
  7809.     ulong type;                         /* primitive type */
  7810.     N_unbind_req_t *unbind_req;         /* pointer to N_UNBIND_REQ */
  7811.     N_ok_ack_t *ok_ack;                 /* pointer to N_OK_ACK */
  7812.  
  7813. #ifdef TRACE
  7814.     printf( "TRACE: entering x25unbind\n" );
  7815. #endif /* TRACE */
  7816.  
  7817. #ifdef DEBUG
  7818.     /* printf( "x25unbind( %d )\n", fd ); */
  7819. #endif /* DEBUG */
  7820.     debug(F101,"x25unbind closing x25 connection #","",fd);
  7821.  
  7822.     /* Allocate and zero out space to hold the N_UNBIND_REQ primitive */
  7823.     unbind_req = (N_unbind_req_t *) malloc(sizeof(N_npi_ctl_t));
  7824.     if (unbind_req == NULL) {
  7825.         perror("kermit: x25unbind(): unbind_req malloc failed");
  7826.         return(-1);
  7827.     }
  7828.     bzero(unbind_req, sizeof(N_npi_ctl_t));
  7829.  
  7830.     /*
  7831.      * Build the Unbind Request Primitive
  7832.      */
  7833.     flags = 0;
  7834.     unbind_req->PRIM_type = (ulong) N_UNBIND_REQ;
  7835.  
  7836.     /*
  7837.      * Call putmsg() to put the bind request message on the stream
  7838.      */
  7839.     if (x25putmsg(fd,
  7840.                   (N_npi_ctl_t*)unbind_req,
  7841.                   (N_npi_data_t *)NULL,
  7842.                   0,
  7843.                   &flags
  7844.                   ) < 0) {
  7845.         perror ("kermit: x25unbind(): putmsg failed");
  7846.         return(-1);
  7847.     }
  7848.  
  7849.     /* Allocate and Zero out space for the N_OK_ACK primitive */
  7850.     ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t));
  7851.     if (ok_ack == NULL) {
  7852.         perror("kermit x25unbind(): ok_ack malloc failed\n");
  7853.         return(-1);
  7854.     }
  7855.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  7856.  
  7857.     /* Initialize and build the control structure for getmsg */
  7858.     get_flags=0;
  7859.  
  7860.     /* Call getmsg() to check for an acknowledgement */
  7861.     rc = x25getmsg(fd,
  7862.                    (N_npi_ctl_t*)ok_ack,
  7863.                    (int)sizeof(N_ok_ack_t),
  7864.                    (N_npi_data_t*)NULL,
  7865.                    0,
  7866.                    &get_flags,
  7867.                    N_OK_ACK
  7868.                    );
  7869.     if (rc < 0) {
  7870.         perror ("kermit: x25unbind: getmsg failed");
  7871.         return(-1);
  7872.     }
  7873.  
  7874.     /* Free up the space that we no longer need */
  7875.     if (unbind_req) { free(unbind_req); unbind_req = NULL; }
  7876.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  7877.  
  7878. #ifdef TRACE
  7879.     printf( "TRACE: leaving x25unbind\n" );
  7880. #endif /* TRACE */
  7881.  
  7882.     return(0);
  7883. }
  7884.  
  7885. /*****************************************************************************
  7886.  * Function: x25xin
  7887.  *
  7888.  * Description:
  7889.  *      Read n characters from X.25 circuit into buf (AIX only)
  7890.  *
  7891.  * Parameters:
  7892.  *      data_buf_len    maximum size of data buffer
  7893.  *      data_buf        pointer to pre-allocated buffer space
  7894.  *
  7895.  * Return Value:
  7896.  *      the number of characters actually read
  7897.  */
  7898. int
  7899. x25xin(data_buf_len,data_buf) int data_buf_len; CHAR *data_buf; {
  7900.     struct strbuf getmsg_ctl;           /* streams control structure */
  7901.     struct strbuf getmsg_data;          /* streams data structure */
  7902.     int rc = 0;                         /* return code */
  7903.     int getmsg_flags;                   /* packet priority flags */
  7904.     char * ctl_buf;                     /* npi control buffer */
  7905.     N_npi_ctl_t * result;               /* pointer to simplify switch() */
  7906.  
  7907. #ifdef TRACE
  7908.     printf( "TRACE: entering x25xin\n" );
  7909. #endif /* TRACE */
  7910.  
  7911.     /* ensure that no maximum's are overridden */
  7912.     data_buf_len = (NPI_MAX_DATA < data_buf_len) ? NPI_MAX_DATA : data_buf_len;
  7913.  
  7914.     /* allocate space for packet control info */
  7915.     if ((ctl_buf = (char *)malloc(NPI_MAX_CTL)) == NULL) {
  7916.         perror( "kermit: x25xin(): ctl_buf malloc" );
  7917.         return(-1);
  7918.     }
  7919. #ifdef COMMENT
  7920.     /* riehm: need zeroed buffer for getmsg? */
  7921.     bzero( ctl_buf, NPI_MAX_CTL );
  7922.     /* clear data buffer */
  7923.     bzero( data_buf, data_buf_len );
  7924. #endif /* COMMENT */
  7925.  
  7926.     getmsg_flags = 0;                   /* get the first packet available */
  7927.  
  7928.     rc = x25getmsg(ttyfd,
  7929.                    ctl_buf,
  7930.                    NPI_MAX_CTL,
  7931.                    data_buf,
  7932.                    data_buf_len,
  7933.                    &getmsg_flags,
  7934.                    N_DATA_IND
  7935.                    );
  7936. #ifdef COMMENT
  7937. #ifdef DEBUG
  7938.     if (rc >= 0) {
  7939.         printf( "kermit: x25xin(): got " );
  7940.         x25dump_data( data_buf, 0, rc );
  7941.     } else {
  7942.         printf( "x25xin(): attempt to get data resulted in an error\n" );
  7943.     }
  7944. #endif /* DEBUG */
  7945. #endif /* COMMENT */
  7946.  
  7947.     /* free buffers */
  7948.     if (ctl_buf) { free(ctl_buf); ctl_buf = NULL; }
  7949.  
  7950. #ifdef TRACE
  7951.     printf( "TRACE: leaving x25xi\n" );
  7952. #endif /* TRACE */
  7953.  
  7954.     return(rc);
  7955. }
  7956.  
  7957. /*****************************************************************************
  7958.  * Function: x25write
  7959.  *
  7960.  * Description:
  7961.  *      write a block of characters to the X25 STREAM (AIX)
  7962.  *
  7963.  * Parameters:
  7964.  *      fd              file descriptor to write to
  7965.  *      databuf         buffer containing data to write
  7966.  *      databufsize             size of the buffer to write
  7967.  *
  7968.  * Return Value:
  7969.  *      size            the number of bytes actually transmitted
  7970.  */
  7971. int
  7972. x25write(fd, databuf, databufsize)
  7973.     int         fd;                  /* X25 STREAMS file descriptor (ttyfd) */
  7974.     char        *databuf;               /* buffer to write */
  7975.     int         databufsize;            /* buffer size */
  7976. /* x25write */ {
  7977.     N_data_req_t *data_req_ctl;
  7978.     int rc;                             /* return code (size transmitted) */
  7979.     int write_flags = 0;                /* always 0 !? */
  7980.  
  7981. #ifdef TRACE
  7982.     printf( "TRACE: entering x25write\n" );
  7983. #endif /* TRACE */
  7984.  
  7985.     if ((data_req_ctl = (N_data_req_t *)malloc(NPI_MAX_CTL) ) == NULL) {
  7986.         perror( "kermit: x25write(): data_req_ctl malloc" );
  7987.         return(-1);
  7988.     }
  7989.     data_req_ctl->PRIM_type = N_DATA_REQ;
  7990.     data_req_ctl->DATA_xfer_flags = 0;
  7991.  
  7992.     /* riehm: possible extension
  7993.      * possibly need to think about splitting up the data buffer
  7994.      * into multiple parts if databufsize > NPI_MAX_DATA
  7995.      */
  7996.  
  7997. #ifdef COMMENT
  7998. #ifdef DEBUG
  7999.     printf( "kermit: x25write(): writing data to x25 stream\n" );
  8000.     printf( "\tdata:\t" );
  8001.     x25dump_data(databuf, 0, databufsize);
  8002. #endif /* DEBUG */
  8003. #endif /* COMMENT */
  8004.     rc = x25putmsg(fd,
  8005.                    (N_npi_ctl_t*)data_req_ctl,
  8006.                    (N_npi_data_t*)databuf,
  8007.                    databufsize,
  8008.                    &write_flags
  8009.                    );
  8010.     if (data_req) { free(data_req_ctl);  data_req = NULL; }
  8011.  
  8012. #ifdef TRACE
  8013.     printf( "TRACE: leaving x25write\n" );
  8014. #endif /* TRACE */
  8015.  
  8016.     return(rc);
  8017. }
  8018.  
  8019. /*****************************************************************************
  8020.  * Function: x25local_nua
  8021.  *
  8022.  * Description:
  8023.  *      This routine is only interesting for IBM computers. In order
  8024.  *      to set up a connection (see x25bind()) you need to know the
  8025.  *      local NUA (x25 address). Unfortunately, you need all this code
  8026.  *      to find that out, I just hope this works for everyone else!
  8027.  *
  8028.  * Parameters:
  8029.  *      a pre-allocated character buffer, long enough to hold an X.25 address
  8030.  *      and the tailing null.
  8031.  *
  8032.  * Return Value:
  8033.  *      the length of the address string.
  8034.  *      0 = error
  8035.  */
  8036. int
  8037. x25local_nua(char *buf) {
  8038.     struct CuAt *response;      /* structure to fill with info from ODM */
  8039.     CLASS_SYMBOL retClass;      /* ODM class */
  8040.     char query[64];             /* odm database query */
  8041.     int rc = 0;                 /* return value (length of local NUA) */
  8042.     extern char x25name[];      /* x25 device name (sx25a0) */
  8043.  
  8044. #ifdef TRACE
  8045.     printf( "TRACE: entering x25local_nua\n" );
  8046. #endif /* TRACE */
  8047.  
  8048.     /* set up query string */
  8049.     if (x25name[0] == '\0') {
  8050. #ifdef DEBUG
  8051.         printf( "kermit: x25local_nua(): No x25 device set, trying sx25a0\n" );
  8052. #endif /* DEBUG */
  8053.         strcpy( x25name, "sx25a0" );
  8054.     }
  8055.     sprintf(query, "name like %s and attribute like local_nua", x25name);
  8056.  
  8057.     /* initialise ODM database */
  8058.     odmerrno = 0;
  8059.     if (odm_initialize() == -1) {
  8060.         printf( "x25local_nua(): can't initialize ODM database");
  8061.         switch (odmerrno) {
  8062.           case ODMI_INVALID_PATH:
  8063.             printf( "invalid path\n" );
  8064.             break;
  8065.           case ODMI_MALLOC_ERR:
  8066.             printf( "malloc failed\n" );
  8067.             break;
  8068.           default:
  8069.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8070.         }
  8071.         return(rc);
  8072.     }
  8073.  
  8074.     /* open the CuAt class */
  8075.     retClass = odm_open_class(CuAt_CLASS);
  8076.     if (((int)retClass) == -1) {
  8077.         printf( "kermit: x25local_nua(): can't open CuAt class in odm. " );
  8078.         switch (odmerrno) {
  8079.           case ODMI_CLASS_DNE:
  8080.             printf( "CuAt class doesn't exist\n" );
  8081.             break;
  8082.           case ODMI_CLASS_PERMS:
  8083.             printf( "permission to CuAt class file denied\n" );
  8084.             break;
  8085.           case ODMI_MAGICNO_ERR:
  8086.             printf( "CuAt is an invalid ODM object class\n" );
  8087.             break;
  8088.           case ODMI_OPEN_ERR:
  8089.             printf( "cannot open CuAt class - and don't know why!\n" );
  8090.             break;
  8091.           case ODMI_INVALID_PATH:
  8092.             printf( "invalid path\n" );
  8093.             break;
  8094.           case ODMI_TOOMANYCLASSES:
  8095.             printf( "too many object classes have been opened\n" );
  8096.             break;
  8097.           default:
  8098.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8099.         }
  8100.         return(rc);
  8101.     }
  8102.  
  8103. #ifdef DEBUG
  8104.     printf("retClass= %d\n", retClass);
  8105. #endif /* DEBUG */
  8106.  
  8107.     response = (struct CuAt *)odm_get_first( retClass, query, NULL );
  8108.     if (((int)response) == -1) {
  8109.         printf( "kermit: x25local_nua(): odm query failed " );
  8110.         switch (odmerrno) {
  8111.           case ODMI_BAD_CRIT:           /* Programming error */
  8112.             printf( "bad search criteria\n" );
  8113.             break;
  8114.           case ODMI_CLASS_DNE:
  8115.             printf( "CuAt class doesn't exist\n" );
  8116.             break;
  8117.           case ODMI_CLASS_PERMS:
  8118.             printf( "permission to CuAt class file denied\n" );
  8119.             break;
  8120.           case ODMI_INTERNAL_ERR:
  8121.             printf("odm internal error\nPlease contact your administrator\n" );
  8122.             break;
  8123.           case ODMI_INVALID_CLXN:
  8124.             printf("CuAt is invalid or inconsistent odm class collection\n");
  8125.             break;
  8126.           case ODMI_INVALID_PATH:
  8127.             printf( "invalid path\n" );
  8128.             break;
  8129.           case ODMI_MAGICNO_ERR:
  8130.             printf( "CuAt is an invalid ODM object class\n" );
  8131.             break;
  8132.           case ODMI_MALLOC_ERR:
  8133.             printf( "malloc failed\n" );
  8134.             break;
  8135.           case ODMI_OPEN_ERR:
  8136.             printf( "cannot open CuAt class - and don't know why!\n" );
  8137.             break;
  8138.           case ODMI_TOOMANYCLASSES:
  8139.             printf( "too many object classes have been opened\n" );
  8140.             break;
  8141.           default:
  8142.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8143.         }
  8144.         return(rc);
  8145.     }
  8146.  
  8147.     /* check for a meaningfull response */
  8148.     if (response != NULL) {
  8149.         if (response->value != NULL) {
  8150.             strcpy(buf, response->value);
  8151.             rc = strlen( buf );
  8152. #ifdef DEBUG
  8153. /*
  8154.             printf( "attribute name is: %s\n", (char *)response->attribute );
  8155.             printf( "I think my address is %s\n", (char*)response->value );
  8156. */
  8157. #endif /* DEBUG */
  8158.         } else {
  8159.             printf( "kermit: x25local_nua(): couldn't find the local NUA\n" );
  8160.         }
  8161.     } else {
  8162.         switch (odmerrno) {
  8163.           case ODMI_BAD_CRIT:
  8164.             printf( "Error: ODMI_BAD_CRIT - bad criteria\n" );
  8165.             break;
  8166.           case ODMI_CLASS_DNE:
  8167.             printf( "Error: ODMI_CLASS_DNE - class doesn't exist\n" );
  8168.             break;
  8169.           case ODMI_CLASS_PERMS:
  8170.             printf( "Error: ODMI_CLASS_PERMS - class permissions\n" );
  8171.             break;
  8172.           case ODMI_INTERNAL_ERR:
  8173.             printf( "Error: ODMI_INTERNAL_ERR - panic\n" );
  8174.             break;
  8175.           case ODMI_INVALID_CLXN:
  8176.             printf( "Error: ODMI_INVALID_CLXN - invalid collection\n" );
  8177.             break;
  8178.           case ODMI_INVALID_PATH:
  8179.             printf( "Error: ODMI_INVALID_PATH - invalid path - what path?\n" );
  8180.             break;
  8181.           case ODMI_MAGICNO_ERR:
  8182.             printf( "Error: ODMI_MAGICNO_ERR - invalid object magic\n" );
  8183.             break;
  8184.           case ODMI_MALLOC_ERR:
  8185.             printf( "Error: ODMI_MALLOC_ERR - malloc failed\n" );
  8186.             break;
  8187.           case ODMI_OPEN_ERR:
  8188.             printf( "Error: ODMI_OPEN_ERR - cannot open class\n" );
  8189.             break;
  8190.           case ODMI_TOOMANYCLASSES:
  8191.             printf( "Error: ODMI_TOOMANYCLASSES - too many classes\n" );
  8192.             break;
  8193.           default:
  8194.             printf( "Unknown error!\n" );
  8195.         }
  8196.         return(rc);
  8197.     }
  8198.  
  8199.     /* close the database again */
  8200.     odm_close_class( retClass );
  8201.  
  8202.     /* forget about ODM all together */
  8203.     odm_terminate();
  8204.  
  8205. #ifdef TRACE
  8206.     printf( "TRACE: leaving x25local_nua\n" );
  8207. #endif /* TRACE */
  8208.  
  8209.     debug(F110, "x25local_nua local address is ", buf, 0);
  8210.     return(rc);
  8211. }
  8212.  
  8213. /*****************************************************************************
  8214.  * Function: x25facilities
  8215.  *
  8216.  * Description:
  8217.  *      build up the facilities data packet for a connection request
  8218.  *
  8219.  * Parameters:
  8220.  *      a pre-allocated char buffer, normally NPI_MAX_DATA big.
  8221.  *
  8222.  * Return Value:
  8223.  *      the number of characters inserted into the buffer
  8224.  */
  8225. int
  8226. x25facilities(buffer) char *buffer; {
  8227.     extern int revcall;
  8228.     extern int closgr;
  8229.     char *p;                            /* temp pointer */
  8230.     char *start;                        /* temp pointer */
  8231.  
  8232. #ifdef TRACE
  8233.     printf( "TRACE: entering x25facilities\n" );
  8234. #endif /* TRACE */
  8235.  
  8236.     p = buffer + 1;
  8237.     start = p;
  8238.  
  8239. #ifdef DEBUG
  8240.     printf( "kermit: x25facilities(): getting X25 facilities\n" );
  8241. #endif /* DEBUG */
  8242.  
  8243.     if (revcall != 0) {
  8244. #ifdef DEBUG
  8245.         printf("reverse charge: %d\n", revcall );
  8246. #endif /* DEBUG */
  8247.         *++p = 0x01;
  8248.         *++p = revcall;
  8249.     }
  8250.     if (closgr > 0) {
  8251. #ifdef DEBUG
  8252.         printf("closed user group: %d\n", closgr );
  8253. #endif /* DEBUG */
  8254.         *++p = 0x03;
  8255.         *++p = closgr;
  8256.     }
  8257.  
  8258. #ifdef DEBUG
  8259.     if (p == start) {
  8260.         printf( "no facilities\n" );
  8261.     }
  8262. #endif /* DEBUG */
  8263.  
  8264.     /* set the size of the facilities buffer */
  8265.     *buffer = (char)( p - start ) & 0xff;
  8266.  
  8267. #ifdef DEBUG
  8268.     printf( "kermit: x25facilities(): returning %d\n", (int)(p - buffer)  );
  8269. #endif /* DEBUG */
  8270.  
  8271. #ifdef TRACE
  8272.     printf( "TRACE: leaving x25facilities\n" );
  8273. #endif /* TRACE */
  8274.  
  8275.     /* return the size of the facilities with size byte */
  8276.     /* 1 == no facilities, 0 byte returned as facilities size */
  8277.     return( (int)(p - buffer) );
  8278. }
  8279.  
  8280. /*
  8281.  * reset the connection
  8282.  */
  8283. int
  8284. x25reset(cause, diagn) char cause; char diagn; {
  8285.     /* not implemented */
  8286.  
  8287. #ifdef TRACE
  8288.     printf( "TRACE: entering x25reset\n" );
  8289. #endif /* TRACE */
  8290.  
  8291. #ifdef TRACE
  8292.     printf( "TRACE: leaving x25reset\n" );
  8293. #endif /* TRACE */
  8294.  
  8295.     return(0);
  8296. }
  8297.  
  8298. /*
  8299.  * clear the x25 connection - ie: hang up
  8300.  */
  8301. int
  8302. x25clear() {
  8303.     int get_flags = 0;                  /* priority flag for getmsg */
  8304.     int put_flags = 0;                  /* send flags, always 0 */
  8305.     ulong type;                         /* primitive type */
  8306.     N_discon_req_t *discon_req;         /* pointer to N_DISCON_REQ */
  8307.     N_discon_ind_t *discon_ind;         /* pointer to N_DISCON_IND */
  8308.     N_npi_data_t *discon_data;          /* pointer to N_DISCON_IND data */
  8309.     int rc = 0;                         /* return code */
  8310.  
  8311. #ifdef TRACE
  8312.     printf( "TRACE: entering x25clear\n" );
  8313. #endif /* TRACE */
  8314.  
  8315. #ifdef DEBUG
  8316.     /* printf( "x25clear(): checking last msg: %s\n", x25prim(x25lastmsg)); */
  8317. #endif /* DEBUG */
  8318.  
  8319.     /*
  8320.     * The following checks are used to ensure that we don't disconnect
  8321.     * or unbind twice - this seems to throw the NPI interface right out of
  8322.     * kilter.
  8323.     */
  8324.     switch(x25lastmsg) {
  8325.       case N_BIND_ACK:
  8326.       case N_CONN_CON:
  8327.       case N_CONN_REQ:
  8328.       case N_DATA_REQ:
  8329.       case N_DATA_IND:
  8330.         {
  8331. #ifdef DEBUG
  8332.             /* printf("x25clear(): actively disconnecting\n"); */
  8333. #endif /* DEBUG */
  8334.  
  8335.                 discon_req = (N_discon_req_t *)malloc(NPI_MAX_CTL);
  8336.                 if (discon_req == NULL) {
  8337.                     perror("kermit x25clear(): discon_req malloc failed\n");
  8338.                     /* fallthrough, try to unbind the NPI anyway */
  8339.                 } else {
  8340.                     discon_req->PRIM_type = N_DISCON_REQ;
  8341.                     discon_req->DISCON_reason = 0;      /* not used by AIX */
  8342.                     discon_req->RES_length = 0;
  8343.                     discon_req->RES_offset = (ulong)(sizeof(N_discon_req_t));
  8344.                     discon_req->SEQ_number = x25seqno;  /* global */
  8345.  
  8346.                     if (x25putmsg(ttyfd,
  8347.                                   (N_npi_ctl_t*)discon_req,
  8348.                                   (N_npi_data_t*)NULL,
  8349.                                   0,
  8350.                                   &put_flags
  8351.                                   ) < 0) {
  8352.                         perror("x25putmsg failed in x25clear()");
  8353.                     }
  8354.                     discon_ind = (N_discon_ind_t *)malloc(NPI_MAX_CTL);
  8355.                     discon_data = (N_npi_data_t *)malloc(NPI_MAX_DATA);
  8356.                     if((discon_ind == NULL) || (discon_data == NULL)) {
  8357.                         perror("x25clear(): discon_ind malloc failed\n");
  8358.                         /* fallthrough, try to unbind the NPI anyway */
  8359.                     } else {
  8360.                         if(x25getmsg(ttyfd,
  8361.                                      (N_npi_ctl_t*)discon_ind,
  8362.                                      NPI_MAX_CTL,
  8363.                                      (N_npi_data_t*)discon_data,
  8364.                                      NPI_MAX_DATA,
  8365.                                      &get_flags,
  8366.                                      N_OK_ACK
  8367.                                      ) < 0 ) {
  8368.                             perror("x25getmsg failed in x25clear()");
  8369.                             /* fallthrough, try to unbind the NPI anyway */
  8370.                         }
  8371.                     }
  8372.                 }
  8373.                 break;
  8374.             }
  8375.     }
  8376.  
  8377.     if (x25lastmsg != N_UNBIND_REQ) {
  8378.         rc = x25unbind(ttyfd);
  8379.     }
  8380.  
  8381. #ifdef TRACE
  8382.     printf( "TRACE: leaving x25clear\n" );
  8383. #endif /* TRACE */
  8384.  
  8385.     return(rc);
  8386. }
  8387.  
  8388. #ifdef DEBUG
  8389. /*
  8390.  * only for debugging
  8391.  *
  8392.  * turn the internal representation of a datablock into something
  8393.  * half-way readable. Because the length is known, we can print
  8394.  * the string including null's etc (important, because the first(!)
  8395.  * byte of an X121 address is a null! (X121 addr == 0 + X25 addr)
  8396.  */
  8397. x25dump_data(char *addr, ulong offset, ulong length) {
  8398.     char *ptr = addr + offset;
  8399.     ulong i = length;
  8400.     /* allocate enough memory for all unprintable chars */
  8401.     char *buf = (char *)malloc( length * 4 );
  8402.     char *bptr = buf;   /* pointer to current place in the print buffer */
  8403.  
  8404.     while (i > 0) {
  8405.         if (isprint(*ptr)) {
  8406.             *bptr++ = *ptr;
  8407.         } else {
  8408.             *bptr++ = '[';
  8409.             bptr += sprintf(bptr, "%2.2x", *ptr);
  8410.             *bptr++ = ']';
  8411.         }
  8412.         ptr++;
  8413.         i--;
  8414.     }
  8415.     if (length > 0) {
  8416.         *bptr = '\0';
  8417.         printf( "%s", buf );
  8418.     }
  8419.     printf( " (%d+%d)\n", offset, length );
  8420.  
  8421.     if (buf) { free(buf); buf = NULL; }
  8422.     return;
  8423. }
  8424.  
  8425. /*
  8426.  * only for debugging
  8427.  * print as much useful information about a packet as possible
  8428.  */
  8429. x25dump_prim(primitive)    N_npi_ctl_t *primitive; {
  8430.     printf("Primitive");
  8431.     switch (primitive->PRIM_type) {
  8432.       case N_BIND_ACK:
  8433.         printf( "\tN_BIND_ACK\n\taddress:\t" );
  8434.         x25dump_data( (char *)primitive,
  8435.                      primitive->bind_ack.ADDR_offset,
  8436.                      primitive->bind_ack.ADDR_length );
  8437.         printf( "\tproto id:\t" );
  8438.         x25dump_data( (char *)primitive,
  8439.                      primitive->bind_ack.PROTOID_offset,
  8440.                      primitive->bind_ack.PROTOID_length );
  8441.         printf( "\tconnind:\t%d\n\ttoken:\t\t%d\n",
  8442.                primitive->bind_ack.CONIND_number,
  8443.                primitive->bind_ack.TOKEN_value );
  8444.         break;
  8445.  
  8446.       case N_BIND_REQ:
  8447.         printf( "\tN_BIND_REQ\n\taddress:\t" );
  8448.         x25dump_data( (char *)primitive,
  8449.                      primitive->bind_req.ADDR_offset,
  8450.                      primitive->bind_req.ADDR_length );
  8451.         printf( "\tproto id:\t" );
  8452.         x25dump_data( (char *)primitive,
  8453.                      primitive->bind_req.PROTOID_offset,
  8454.                      primitive->bind_req.PROTOID_length );
  8455.         printf( "\tconnind:\t%d\n\tflags:\t\t%d\n",
  8456.                primitive->bind_req.CONIND_number,
  8457.                primitive->bind_req.BIND_flags );
  8458.         break;
  8459.  
  8460.       case N_CONN_CON:
  8461.         printf( "\tN_CONN_CON\n" );
  8462.         printf( "\tRES\t\t" );
  8463.         x25dump_data( (char *)primitive,
  8464.                      primitive->conn_con.RES_offset,
  8465.                      primitive->conn_con.RES_length );
  8466.         printf( "\tflags:\t%d\n", primitive->conn_con.CONN_flags );
  8467.         break;
  8468.  
  8469.       case N_CONN_IND:
  8470.         printf( "\tN_CONN_IND\n" );
  8471.         printf( "\tsource:\t\t" );
  8472.         x25dump_data( (char *)primitive,
  8473.                      primitive->conn_ind.SRC_offset,
  8474.                      primitive->conn_ind.SRC_length );
  8475.         printf( "\tdestination:\t" );
  8476.         x25dump_data( (char *)primitive,
  8477.                      primitive->conn_ind.DEST_offset,
  8478.                      primitive->conn_ind.DEST_length );
  8479.         printf( "\tSEQ_number:\t%d\n", primitive->conn_ind.SEQ_number );
  8480.         printf( "\tflags:\t%d\n", primitive->conn_ind.CONN_flags );
  8481.         break;
  8482.  
  8483.       case N_CONN_REQ:
  8484.         printf( "\tN_CONN_REQ\n\tdestination:\t" );
  8485.         x25dump_data( (char *)primitive,
  8486.                      primitive->conn_req.DEST_offset,
  8487.                      primitive->conn_req.DEST_length );
  8488.         printf( "\tflags:\t%d\n", primitive->conn_req.CONN_flags );
  8489.         break;
  8490.  
  8491.       case N_CONN_RES:
  8492.         printf( "\tN_CONN_RES\n" );
  8493.         printf( "\tTOKEN_value\t%d\n", primitive->conn_res.TOKEN_value );
  8494.         printf( "\tSEQ_number\t%d\n", primitive->conn_res.SEQ_number );
  8495.         printf( "\tCONN_flags\t%d\n", primitive->conn_res.CONN_flags );
  8496.         printf( "\tRES\t\t" );
  8497.         x25dump_data( (char *)primitive,
  8498.                      primitive->conn_res.RES_offset,
  8499.                      primitive->conn_res.RES_length );
  8500.         break;
  8501.  
  8502.       case N_DATACK_IND:
  8503.         printf( "\tN_DATACK_IND\n" );
  8504.         break;
  8505.  
  8506.       case N_DATACK_REQ:
  8507.         printf( "\tN_DATACK_REQ\n" );
  8508.         printf( "\tflags:\t%d\n", primitive->data_req.DATA_xfer_flags );
  8509.         break;
  8510.  
  8511.       case N_DATA_IND:
  8512.         printf( "\tN_DATA_IND\n" );
  8513.         printf( "\tflags:\t%d\n", primitive->data_ind.DATA_xfer_flags );
  8514.         break;
  8515.  
  8516.       case N_DATA_REQ:
  8517.         printf( "\tN_DATA_REQ\n" );
  8518.         break;
  8519.  
  8520.       case N_DISCON_IND:
  8521.         printf( "\tN_DISCON_IND\n" );
  8522.         printf( "\torigin:\t%d\n", primitive->discon_ind.DISCON_orig );
  8523.         printf( "\treason:\t\t%d\n", primitive->discon_ind.DISCON_reason );
  8524.         printf( "\tseq no:\t\t%d\n", primitive->discon_ind.SEQ_number );
  8525.         printf( "\tRES:\t" );
  8526.         x25dump_data( (char *)primitive,
  8527.                      primitive->discon_ind.RES_offset,
  8528.                      primitive->discon_ind.RES_length );
  8529.         break;
  8530.  
  8531.       case N_DISCON_REQ:
  8532.         printf( "\tN_DISCON_REQ\n" );
  8533.         printf( "\tDISCON_reason:\t%d\n",
  8534.                primitive->discon_req.DISCON_reason );
  8535.         printf( "\tRES:\t" );
  8536.         x25dump_data( (char *)primitive,
  8537.                      primitive->discon_req.RES_offset,
  8538.                      primitive->discon_req.RES_length );
  8539.         printf( "\tSEQ_number:\t%d\n", primitive->discon_req.SEQ_number );
  8540.         break;
  8541.  
  8542.       case N_ERROR_ACK:
  8543.         printf( "\tN_ERROR_ACK\n" );
  8544.         printf( "\tCaused by:\t%s\n",
  8545.                x25prim( primitive->error_ack.ERROR_prim ) );
  8546.         printf( "\tNPI error:\t%s\n",
  8547.                x25err( primitive->error_ack.NPI_error ));
  8548.         errno = primitive->error_ack.UNIX_error;
  8549.         perror( "\t" );
  8550.         break;
  8551.  
  8552.       case N_EXDATA_IND:
  8553.         printf( "\tN_EXDATA_ACK\n" );
  8554.         break;
  8555.  
  8556.       case N_EXDATA_REQ:
  8557.         printf( "\tN_EXDATA_REQ\n" );
  8558.         break;
  8559.  
  8560.       case N_INFO_ACK:
  8561.         printf( "\tN_INFO_ACK\n" );
  8562.         printf( "\tNSDU size:\t%d\n", primitive->info_ack.NSDU_size );
  8563.         printf( "\tENSDU size:\t%d\n", primitive->info_ack.ENSDU_size );
  8564.         printf( "\tCDATA size:\t%d\n", primitive->info_ack.CDATA_size );
  8565.         printf( "\tDDATA size:\t%d\n", primitive->info_ack.DDATA_size );
  8566.         printf( "\tADDR size:\t%d\n", primitive->info_ack.ADDR_size );
  8567.         printf( "\tNIDU size:\t%d\n", primitive->info_ack.NIDU_size );
  8568.         break;
  8569.  
  8570.       case N_INFO_REQ:
  8571.         printf( "\tN_INFO_REQ\n" );
  8572.         break;
  8573.  
  8574.       case N_OK_ACK:
  8575.         printf( "\tN_OK_ACK\n" );
  8576.         break;
  8577.  
  8578.       case N_OPTMGMT_REQ:
  8579.         printf( "\tN_OPTMGMT_REQ\n" );
  8580.         break;
  8581.  
  8582.       case N_RESET_CON:
  8583.         printf( "\tN_RESET_CON\n" );
  8584.         break;
  8585.  
  8586.       case N_RESET_IND:
  8587.         printf( "\tN_RESET_IND\n" );
  8588.         printf( "\treason:\t\t%d\n", primitive->reset_ind.RESET_reason );
  8589.         printf( "\torigin:\t\t%d\n", primitive->reset_ind.RESET_orig );
  8590.         break;
  8591.  
  8592.       case N_RESET_REQ:
  8593.         printf( "\tN_RESET_REQ\n" );
  8594.         printf( "\treason:\t\t%d\n", primitive->reset_req.RESET_reason );
  8595.         break;
  8596.  
  8597.       case N_RESET_RES:
  8598.         printf( "\tN_RESET_RES\n" );
  8599.         break;
  8600.  
  8601.       case N_UDERROR_IND:
  8602.         printf( "\tN_UDERROR_IND\n" );
  8603.         break;
  8604.  
  8605.       case N_UNBIND_REQ:
  8606.         printf( "\tN_UNBIND_REQ\n" );
  8607.         break;
  8608.  
  8609.       case N_UNITDATA_REQ:
  8610.         printf( "\tN_UNITDATA_REQ\n" );
  8611.         break;
  8612.  
  8613.       case N_UNITDATA_IND:
  8614.         printf( "\tN_UNITDATA_IND\n" );
  8615.         break;
  8616.  
  8617.       default:
  8618.         (void) printf( "Unknown NPI error %d", primitive->PRIM_type );
  8619.         return 0;
  8620.     }
  8621. }
  8622. #endif /* DEBUG */
  8623.  
  8624. /* it looks like signal handling is not needed with streams! */
  8625. /* x25oobh()    - handle SIGURG signals - take from isode ? */
  8626.  
  8627. #endif /* IBMX25 */
  8628.  
  8629. #ifndef NOHTTP
  8630. #ifdef Plan9
  8631. #include <sys/time.h>
  8632. #else
  8633. #ifdef AIX41
  8634. #include <time.h>
  8635. #else
  8636. #ifdef SUNOS4
  8637. #include <sys/time.h>
  8638. #else
  8639. #ifdef SYSTIMEH
  8640. #include <sys/time.h>
  8641. #else
  8642. #ifdef OS2
  8643. #include <time.h>
  8644. #else
  8645. #include <time.h>
  8646. /* #include <utime.h> */
  8647. #endif /* OS2 */
  8648. #endif /* SYSTIMEH */
  8649. #endif /* SUNOS4 */
  8650. #endif /* AIX41 */
  8651. #endif /* Plan9 */
  8652.  
  8653. #ifdef OS2
  8654. #include <sys/utime.h>
  8655. #ifdef NT
  8656. #define utimbuf _utimbuf
  8657. #endif /* NT */
  8658. #define utime   _utime
  8659. #else
  8660. #ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
  8661. #include <sys/utime.h>                  /* for extra fields required by */
  8662. #else                                   /* 88Open spec. */
  8663. #ifdef UTIMEH                           /* or <utime.h> if requested */
  8664. #include <utime.h>                      /* (SVR4, POSIX) */
  8665. #define SYSUTIMEH                       /* Use this for both cases. */
  8666. #endif /* UTIMEH */
  8667. #endif /* SYSUTIMEH */
  8668. #endif /* OS2 */
  8669.  
  8670. #define HTTP_VERSION "HTTP/1.0"
  8671.  
  8672. #ifdef CMDATE2TM
  8673. time_t
  8674. #ifdef CK_ANSIC
  8675. http_date(char * date)
  8676. #else
  8677. http_date(date) char * date;
  8678. #endif /* CK_ANSIC */
  8679. /* http_date */ {
  8680.     /* HTTP dates are of the form:  "Sun, 12 Oct 1997 20:11:47 GMT" */
  8681.     extern char cmdatebuf[18];
  8682.     struct tm t_tm;
  8683.     time_t t;
  8684.     char ldate[32];
  8685.     int j;
  8686.  
  8687.     j = ckindex(",",date,0,0,0);
  8688.     ckstrncpy(ldate,&date[j+1],20);
  8689.  
  8690.     if (cmcvtdate(ldate,0) < 0)         /* Convert to normal form */
  8691.       return(0);
  8692.  
  8693.     t_tm = *cmdate2tm(cmdatebuf,1);
  8694.  
  8695.     t = mktime(&t_tm);                  /* PROBABLY NOT PORTABLE */
  8696. #ifdef XX_TIMEZONE
  8697.     t -= _timezone;                     /* NOT DECLARED */
  8698. #endif /* XX_TIMEZONE */
  8699.     return(t);
  8700. }
  8701. #endif /* CMDATE2TM */
  8702.  
  8703. char *
  8704. http_now() {
  8705.     static char nowstr[32];
  8706. #ifdef CMDATE2TM
  8707.     struct tm  *gmt;
  8708.     time_t ltime;                       /* NOT PORTABLE */
  8709.  
  8710.     time(<ime);
  8711.  
  8712.     gmt = gmtime(<ime);               /* PROBABLY NOT PORTABLE */
  8713.     strftime(nowstr,32,"%a, %d %b %Y %H:%M:%S GMT",gmt); /* NOT PORTABLE */
  8714.     /* not only is it not portable but it's locale-dependent */
  8715. #else
  8716. /*
  8717.   This is hopeless.  First of all, it seems that HTTP wants Day and Month
  8718.   NAMES?  In English?  Whose idea was that?  Even worse, the date/time must be
  8719.   expressed in Zulu (UTC (GMT)), and converting from local time to GMT is a
  8720.   nightmare.  Every platform does it differently, if at all -- even if we
  8721.   restrict ourselves to UNIX.  For example (quoting from recent C-Kermit edit
  8722.   history), "Fixed a longstanding bug in the BSDI version, in which incoming
  8723.   file dates were set in GMT rather than local time.  It seems in 4.4BSD,
  8724.   localtime() does not return the local time, but rather Zero Meridian (Zulu)
  8725.   time (GMT), and must be adjusted by the tm_gmtoff value."  Swell.  For
  8726.   greater appreciation of the scope of the problem, just take a look at the
  8727.   time-related #ifdefs in ckutio.c.  The only right way to do this is to add
  8728.   our own portable API for converting between local time and GMT/UTC/Zulu
  8729.   that shields us not only from UNIXisms like time_t and struct tm, but also
  8730.   the unbelievable amount of differences in time-related APIs -- e.g. is
  8731.   "timezone" an external variable or a function; which header file(s) do we
  8732.   include, etc etc etc.  It's a major project.
  8733. */
  8734.     int x;
  8735.     x = cmcvtdate("",1);
  8736.     if (x < 0)
  8737.       return("");
  8738. /*  yyyymmdd hh:mm:ss */
  8739. /*  01234567890123456 */
  8740.     nowstr[0]  = 'X';                   /* 1st letter of day */
  8741.     nowstr[1]  = 'x';                   /* 2nd letter of day */
  8742.     nowstr[2]  = 'x';                   /* 3rd letter of day */
  8743.     nowstr[3]  = ',';
  8744.     nowstr[4]  = ' ';
  8745.     nowstr[5]  = cmdate[6];
  8746.     nowstr[6]  = cmdate[7];
  8747.     nowstr[7]  = ' ';
  8748.     nowstr[8]  = ' ';                   /* first letter of month */
  8749.     nowstr[9]  = ' ';                   /* second letter of month */
  8750.     nowstr[10] = ' ';                   /* third letter of month */
  8751.     nowstr[11] = ' ';
  8752.     nowstr[12] = cmdate[0];
  8753.     nowstr[13] = cmdate[1];
  8754.     nowstr[14] = cmdate[2];
  8755.     nowstr[15] = cmdate[3];
  8756.     nowstr[16] = ' ';
  8757.     nowstr[17] = cmdate[9];
  8758.     nowstr[18] = cmdate[10];
  8759.     nowstr[19] = cmdate[11];
  8760.     nowstr[20] = cmdate[12];
  8761.     nowstr[21] = cmdate[13];
  8762.     nowstr[22] = cmdate[14];
  8763.     nowstr[23] = cmdate[15];
  8764.     nowstr[24] = cmdate[16];
  8765.     nowstr[25] = ' ';
  8766.     nowstr[26] = 'G';
  8767.     nowstr[27] = 'M';
  8768.     nowstr[28] = 'T';
  8769.     nowstr[29] = '\0';
  8770. #endif /* CMDATE2TM */
  8771.     return(nowstr);
  8772. }
  8773.  
  8774. #ifndef OS2
  8775. #ifndef CK_AUTHENTICATION
  8776. /* from ckuusr.h, which this module normally doesn't include */
  8777. _PROTOTYP( int dclarray, (char, int) );
  8778. #endif /* CK_AUTHENTICATION */
  8779. #endif /* OS2 */
  8780. /*
  8781.   Assign http response pairs to given array.
  8782.   For best results, response pairs should contain no spaces.
  8783.  
  8784.   Call with:
  8785.     resp  =  pointer to response list.
  8786.     n     =  size of response list.
  8787.     array =  array letter.
  8788.   Returns:
  8789.     0 on failure.
  8790.     >= 1, size of array, on success.
  8791. */
  8792. static int
  8793. #ifdef CK_ANSIC
  8794. http_mkarray(char ** resp, int n, char array)
  8795. #else
  8796. http_mkarray(resp, n, array) char ** resp; int n; char array;
  8797. #endif /* CK_ANSIC */
  8798. {
  8799. #ifndef NOSPL
  8800.     int i, x;
  8801.     char ** ap;
  8802.     extern char ** a_ptr[];
  8803.     extern int a_dim[];
  8804.  
  8805.     if (!array || n <= 0)
  8806.       return(0);
  8807.     if ((x = dclarray(array,n)) < 0) {
  8808.         printf("?Array declaration failure\n");
  8809.         return(-9);
  8810.     }
  8811.     ap = a_ptr[x];
  8812.     for (i = 1; i <=n; i++) {
  8813.         ap[i] = resp[i];                /* If resp elements were malloc'd */
  8814.         resp[i] = NULL;
  8815.     }
  8816.     a_dim[x] = n;
  8817.     return(n);
  8818. #else
  8819.     return(0);
  8820. #endif /* NOSPL */
  8821. }
  8822.  
  8823. #define HTTPBUFLEN  1024
  8824. #define HTTPHEADCNT 64
  8825.  
  8826. int
  8827. #ifdef CK_ANSIC
  8828. http_get(char * agent, char ** hdrlist, char * user,
  8829.          char * pwd, char array, char * local, char * remote)
  8830. #else
  8831. http_get(agent, hdrlist, user, pwd, array, local, remote)
  8832.     char * agent; char ** hdrlist; char * user;
  8833.     char * pwd; char array; char * local; char * remote;
  8834. #endif /* CK_ANSIC */
  8835. {
  8836.     char * request = NULL;
  8837.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  8838.     int    ch;
  8839.     char   buf[HTTPBUFLEN], *p;
  8840.     int    nullline;
  8841. #ifdef OS2
  8842.     struct utimbuf u_t;
  8843. #else /* OS2 */
  8844. #ifdef SYSUTIMEH
  8845.     struct utimbuf u_t;
  8846. #else
  8847.     struct utimbuf {
  8848.         time_t atime;
  8849.         time_t mtime;
  8850.     } u_t;
  8851. #endif /* SYSUTIMH */
  8852. #endif /* OS2 */
  8853.     time_t mod_t = 0;
  8854.     time_t srv_t = 0;
  8855.     time_t local_t = 0;
  8856.     char passwd[64];
  8857.     char b64in[128];
  8858.     char b64out[256];
  8859.     char * headers[HTTPHEADCNT];
  8860.  
  8861.     if (ttyfd == -1)
  8862.       return(-1);
  8863.  
  8864.     if (array) {
  8865.         for (i = 0; i < HTTPHEADCNT; i++)
  8866.           headers[i] = NULL;
  8867.     }
  8868.     len = 8;                            /* GET */
  8869.     len += strlen(HTTP_VERSION);
  8870.     len += strlen(remote);
  8871.  
  8872.     for (i = 0; hdrlist[i]; i++)
  8873.       len += strlen(hdrlist[i]) + 2;
  8874.     if (agent)
  8875.       len += 13 + strlen(agent);
  8876.     if (user) {
  8877.         if (!pwd) {
  8878.             readpass("Password: ",passwd,64);
  8879.             pwd = passwd;
  8880.         }
  8881.         sprintf(b64in,"%s:%s",user,pwd);
  8882.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  8883.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  8884.         if (j < 0)
  8885.           return(-1);
  8886.         b64out[j] = '\0';
  8887.         len += j + 24;
  8888.     }
  8889.     len += 3;                           /* blank line + null */
  8890.  
  8891.     request = malloc(len);
  8892.     if (!request)
  8893.       return(-1);
  8894.  
  8895.     sprintf(request,"GET %s %s\r\n",remote,HTTP_VERSION);
  8896.     if (agent) {
  8897.         strcat(request,"User-Agent: ");
  8898.         strcat(request,agent);
  8899.         strcat(request,"\r\n");
  8900.     }
  8901.     if (user) {
  8902.         strcat(request,"Authorization: Basic ");
  8903.         strcat(request,b64out);
  8904.         strcat(request,"\r\n");
  8905.     }
  8906.     for (i = 0; hdrlist[i]; i++) {
  8907.         strcat(request,hdrlist[i]);
  8908.         strcat(request,"\r\n");
  8909.     }
  8910.     strcat(request,"\r\n");
  8911.     ttol((CHAR *)request,strlen(request));
  8912.  
  8913.     /* Process the headers */
  8914.     local_t = time(NULL);
  8915.     nullline = 0;
  8916.     i = 0;
  8917.     while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  8918.         buf[i] = ch;
  8919.         if ( buf[i] == 10 ) { /* found end of line */
  8920.             if (i <= 1)
  8921.               nullline = 1;
  8922.             i++;
  8923.             buf[i] = '\0';
  8924.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  8925.               makestr(&headers[hdcnt++],buf);
  8926.             if (!strncmp(buf,"HTTP",4)) {
  8927.                 j = ckindex(" ",buf,0,0,0);
  8928.                 p = &buf[j];
  8929.                 if (strncmp(p,"200",3)) {
  8930.                     /* an error has occurred */
  8931.                     printf("Failure: Server reports %s",p);
  8932.                     rc = -1;
  8933.                     goto getexit;
  8934.                 }
  8935. #ifdef CMDATE2TM
  8936.             } else if (!strncmp(buf,"Last-Modified",13)) {
  8937.                 mod_t = http_date(&buf[15]);
  8938.             } else if (!strncmp(buf,"Date",4)) {
  8939.                 srv_t = http_date(&buf[4]);
  8940. #endif /* CMDATE2TM */
  8941.             }
  8942.             i = 0;
  8943.         } else {
  8944.             i++;
  8945.         }
  8946.     }
  8947.  
  8948.     /* Now we have the contents of the file */
  8949.     if ( local && local[0] ) {
  8950.         if (zopeno(ZOFILE,local,NULL,NULL)) {
  8951.             while ((ch = ttinc(0)) >= 0) {
  8952.                 zchout(ZOFILE,(CHAR)ch);
  8953.             }
  8954.             zclose(ZOFILE);
  8955. #ifdef CMDATE2TM
  8956. #ifdef OS2
  8957.             u_t.actime = srv_t ? srv_t : local_t;
  8958.             u_t.modtime = mod_t ? mod_t : local_t;
  8959. #else /* OS2 */
  8960. #ifdef SYSUTIMEH
  8961.             u_t.actime = srv_t ? srv_t : local_t;
  8962.             u_t.modtime = mod_t ? mod_t : local_t;
  8963. #else
  8964. #ifdef BSD44
  8965.             u_t[0].tv_sec = srv_t ? srv_t : local_t;
  8966.             u_t[1].tv_sec = mod_t ? mod_t : local_t;
  8967. #else
  8968.             u_t.mtime = srv_t ? srv_t : local_t;
  8969.             u_t.atime = mod_t ? mod_t : local_t;
  8970. #endif /* BSD44 */
  8971. #endif /* SYSUTIMEH */
  8972. #endif /* OS2 */
  8973.             utime(local,&u_t);
  8974. #endif /* CMDATE2TM */
  8975.             if (array)
  8976.                 http_mkarray(headers,hdcnt,array);
  8977.             rc = 0;
  8978.         } else {
  8979.             rc = -1;
  8980.         }
  8981.     } else {
  8982.         while ((ch = ttinc(0)) >= 0)
  8983.             conoc((CHAR)ch);
  8984.         if (array)
  8985.             http_mkarray(headers,hdcnt,array);
  8986.         rc = 0;
  8987.     }
  8988.  
  8989.   getexit:
  8990.     ttclos(0);
  8991.     free(request);
  8992.     for (i = 0; i < hdcnt; i++) {
  8993.         if (headers[i])
  8994.           free(headers[i]);
  8995.     }
  8996.     return(rc);
  8997. }
  8998.  
  8999. int
  9000. #ifdef CK_ANSIC
  9001. http_head(char * agent, char ** hdrlist, char * user,
  9002.           char * pwd, char array, char * local, char * remote)
  9003. #else
  9004. http_head(agent, hdrlist, user, pwd, array, local, remote)
  9005.     char * agent; char ** hdrlist; char * user;
  9006.     char * pwd; char array; char * local; char * remote;
  9007. #endif /* CK_ANSIC */
  9008. {
  9009.     char * request = NULL;
  9010.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  9011.     int    ch;
  9012.     char   buf[HTTPBUFLEN], *p;
  9013.     int    nullline;
  9014.     time_t mod_t;
  9015.     time_t srv_t;
  9016.     time_t local_t;
  9017.     char passwd[64];
  9018.     char b64in[128];
  9019.     char b64out[256];
  9020.     char * headers[HTTPHEADCNT];
  9021.  
  9022.     if (ttyfd == -1)
  9023.       return(-1);
  9024.  
  9025.     if (array) {
  9026.         for (i = 0; i < HTTPHEADCNT; i++)
  9027.           headers[i] = NULL;
  9028.     }
  9029.     len = 9;                            /* HEAD */
  9030.     len += strlen(HTTP_VERSION);
  9031.     len += strlen(remote);
  9032.  
  9033.     for (i = 0; hdrlist[i]; i++)
  9034.       len += strlen(hdrlist[i]) + 2;
  9035.     if (agent)
  9036.       len += 13 + strlen(agent);
  9037.     if (user) {
  9038.         if (!pwd) {
  9039.             readpass("Password: ",passwd,64);
  9040.             pwd = passwd;
  9041.         }
  9042.         sprintf(b64in,"%s:%s",user,pwd);
  9043.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  9044.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  9045.         if (j < 0)
  9046.           return(-1);
  9047.         b64out[j] = '\0';
  9048.         len += j + 24;
  9049.     }
  9050.     len += 3;                           /* blank line + null */
  9051.  
  9052.     request = (char *)malloc(len);
  9053.     if (!request)
  9054.       return(-1);
  9055.  
  9056.     sprintf(request,"HEAD %s %s\r\n",remote,HTTP_VERSION);
  9057.     if (agent) {
  9058.         strcat(request,"User-Agent: ");
  9059.         strcat(request,agent);
  9060.         strcat(request,"\r\n");
  9061.     }
  9062.     if (user) {
  9063.         strcat(request,"Authorization: Basic ");
  9064.         strcat(request,b64out);
  9065.         strcat(request,"\r\n");
  9066.     }
  9067.     for (i = 0; hdrlist[i]; i++) {
  9068.         strcat(request,hdrlist[i]);
  9069.         strcat(request,"\r\n");
  9070.     }
  9071.     strcat(request,"\r\n");
  9072.  
  9073.     if (!zopeno(ZOFILE,local,NULL,NULL)) {
  9074.         free(request);
  9075.         return(-1);
  9076.     }
  9077.     ttol((CHAR *)request,strlen(request));
  9078.  
  9079.     /* Process the headers */
  9080.  
  9081.     local_t = time(NULL);
  9082.     nullline = 0;
  9083.     i = 0;
  9084.     while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  9085.         buf[i] = ch;
  9086.         if (buf[i] == 10) {             /* found end of line */
  9087.             if (i <= 1)
  9088.               nullline = 1;
  9089.             i++;
  9090.             buf[i] = '\0';
  9091.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  9092.               makestr(&headers[hdcnt++],buf);
  9093.             if (!strncmp(buf,"HTTP",4)) {
  9094.                 j = ckindex(" ",buf,0,0,0);
  9095.                 p = &buf[j];
  9096.                 if (strncmp(p,"200",3)) {
  9097.                     /* an error has occurred */
  9098.                     printf("Failure: Server reports %s",p);
  9099.                     rc = -1;
  9100.                     goto headexit;
  9101.                 }
  9102.             } else {
  9103.                 zsout(ZOFILE,buf);
  9104.             }
  9105.             i = 0;
  9106.         } else {
  9107.             i++;
  9108.         }
  9109.     }
  9110.     if (array)
  9111.       http_mkarray(headers,hdcnt,array);
  9112.     rc = 0;
  9113.  
  9114.   headexit:
  9115.     zclose(ZOFILE);
  9116.     ttclos(0);
  9117.     free(request);
  9118.     for (i = 0; i < hdcnt; i++) {
  9119.         if (headers[i])
  9120.           free(headers[i]);
  9121.     }
  9122.     return(rc);
  9123. }
  9124.  
  9125. int
  9126. #ifdef CK_ANSIC
  9127. http_index(char * agent, char ** hdrlist, char * user, char * pwd,
  9128.              char array, char * local, char * remote)
  9129. #else
  9130. http_index(agent, hdrlist, user, pwd, array, local, remote)
  9131.     char * agent; char ** hdrlist; char * user; char * pwd;
  9132.     char array; char * local; char * remote;
  9133. #endif /* CK_ANSIC */
  9134. {
  9135.     char * request = NULL;
  9136.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  9137.     int    ch;
  9138.     char   buf[HTTPBUFLEN], *p;
  9139.     int    nullline;
  9140.     time_t mod_t;
  9141.     time_t srv_t;
  9142.     time_t local_t;
  9143.     char passwd[64];
  9144.     char b64in[128];
  9145.     char b64out[256];
  9146.     char * headers[HTTPHEADCNT];
  9147.  
  9148.     if (ttyfd == -1)
  9149.       return(-1);
  9150.  
  9151.     if (array) {
  9152.         for (i = 0; i < HTTPHEADCNT; i++)
  9153.           headers[i] = NULL;
  9154.     }
  9155.     len = 10;                            /* INDEX */
  9156.     len += strlen(HTTP_VERSION);
  9157.     len += strlen(remote);
  9158.  
  9159.     for (i = 0; hdrlist[i]; i++)
  9160.       len += strlen(hdrlist[i]) + 2;
  9161.     if (agent)
  9162.         len += 13 + strlen(agent);
  9163.     if (user) {
  9164.         if (!pwd) {
  9165.             readpass("Password: ",passwd,64);
  9166.             pwd = passwd;
  9167.         }
  9168.         sprintf(b64in,"%s:%s",user,pwd);
  9169.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  9170.         memset(pwd,0,strlen(pwd));
  9171.         if (j < 0)
  9172.           return(-1);
  9173.         b64out[j] = '\0';
  9174.         len += j + 24;
  9175.     }
  9176.     len += 3;                           /* blank line + null */
  9177.  
  9178.     request = malloc(len);
  9179.     if (!request)
  9180.       return(-1);
  9181.  
  9182.     sprintf(request,"INDEX %s\r\n",HTTP_VERSION);
  9183.     if (agent) {
  9184.         strcat(request,"User-Agent: ");
  9185.         strcat(request,agent);
  9186.         strcat(request,"\r\n");
  9187.     }
  9188.     if (user) {
  9189.         strcat(request,"Authorization: Basic ");
  9190.         strcat(request,b64out);
  9191.         strcat(request,"\r\n");
  9192.     }
  9193.     for (i = 0; hdrlist[i]; i++) {
  9194.         strcat(request,hdrlist[i]);
  9195.         strcat(request,"\r\n");
  9196.     }
  9197.     strcat(request,"\r\n");
  9198.     ttol((CHAR *)request,strlen(request));
  9199.  
  9200.     /* Process the headers */
  9201.     local_t = time(NULL);
  9202.     nullline = 0;
  9203.     i = 0;
  9204.     while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  9205.         buf[i] = ch;
  9206.         if (buf[i] == 10) {             /* found end of line */
  9207.             if (i <= 1)
  9208.               nullline = 1;
  9209.             i++;
  9210.             buf[i] = '\0';
  9211.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  9212.               makestr(&headers[hdcnt++],buf);
  9213.             if (!strncmp(buf,"HTTP",4)) {
  9214.                 j = ckindex(" ",buf,0,0,0);
  9215.                 p = &buf[j];
  9216.                 if (strncmp(p,"200",3)) {
  9217.                     /* an error has occurred */
  9218.                     printf("Failure: Server reports %s",p);
  9219.                     rc = -1;
  9220.                     goto indexexit;
  9221.                 }
  9222.             } else if ( !nullline ) {
  9223.                 printf("%s",buf);
  9224.             }
  9225.             i = 0;
  9226.         } else {
  9227.             i++;
  9228.         }
  9229.     }
  9230.  
  9231.     /* Now we have the contents of the file */
  9232.     if ( local && local[0] ) {
  9233.         if (zopeno(ZOFILE,local,NULL,NULL)) {
  9234.             while ( (ch = ttinc(0)) >= 0 ) {
  9235.                 zchout(ZOFILE,(CHAR)ch);
  9236.             }
  9237.             zclose(ZOFILE);
  9238.         }
  9239.     } else {
  9240.         while ((ch = ttinc(0)) >= 0)
  9241.             conoc((CHAR)ch);
  9242.     }
  9243.     if (array)
  9244.       http_mkarray(headers,hdcnt,array);
  9245.     rc = 0;
  9246.  
  9247.   indexexit:
  9248.     ttclos(0);
  9249.     free(request);
  9250.     for (i = 0; i < hdcnt; i++) {
  9251.         if (headers[i])
  9252.           free(headers[i]);
  9253.     }
  9254.     return(rc);
  9255. }
  9256.  
  9257. int
  9258. #ifdef CK_ANSIC
  9259. http_put(char * agent, char ** hdrlist, char * mime, char * user,
  9260.           char * pwd, char array, char * local, char * remote)
  9261. #else
  9262. http_put(agent, hdrlist, mime, user, pwd, array, local, remote)
  9263.     char * agent; char ** hdrlist; char * mime; char * user;
  9264.     char * pwd; char array; char * local; char * remote;
  9265. #endif /* CK_ANSIC */
  9266. {
  9267.     char * request=NULL;
  9268.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  9269.     int    ch;
  9270.     char   buf[HTTPBUFLEN], *p;
  9271.     int    nullline;
  9272.     time_t mod_t;
  9273.     time_t srv_t;
  9274.     time_t local_t;
  9275.     char passwd[64];
  9276.     char b64in[128];
  9277.     char b64out[256];
  9278.     int  filelen;
  9279.     char * headers[HTTPHEADCNT];
  9280.  
  9281.     if (ttyfd == -1)
  9282.       return(-1);
  9283.  
  9284.     if (array) {
  9285.         for (i = 0; i < HTTPHEADCNT; i++)
  9286.           headers[i] = NULL;
  9287.     }
  9288.     filelen = zchki(local);
  9289.     if (filelen < 0)
  9290.       return(-1);
  9291.  
  9292.     /* Compute length of request header */
  9293.     len = 8;                            /* PUT */
  9294.     len += strlen(HTTP_VERSION);
  9295.     len += strlen(remote);
  9296.  
  9297.     for (i = 0; hdrlist[i]; i++)
  9298.       len += strlen(hdrlist[i]) + 2;
  9299.     if (agent)
  9300.       len += 13 + strlen(agent);
  9301.     if (user) {
  9302.         if (!pwd) {
  9303.             readpass("Password: ",passwd,64);
  9304.             pwd = passwd;
  9305.         }
  9306.         sprintf(b64in,"%s:%s",user,pwd);
  9307.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  9308.         memset(pwd,0,strlen(pwd));
  9309.         if (j < 0)
  9310.           return(-1);
  9311.         b64out[j] = '\0';
  9312.         len += j + 24;
  9313.     }
  9314.     len += 16 + strlen(mime);           /* Content-type: */
  9315.     len += 32;                          /* Content-length: */
  9316.     len += 32;                          /* Date: */
  9317.     len += 3;                           /* blank line + null */
  9318.  
  9319.     request = malloc(len);
  9320.     if (!request)
  9321.       return(-1);
  9322.  
  9323.     sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
  9324.     strcat(request,"Date: ");
  9325. #ifdef CMDATE2TM
  9326.     strcat(request,http_now());
  9327. #else
  9328.     strcap(request,...);
  9329. #endif /* CMDATE2TM */
  9330.     strcat(request,"\r\n");
  9331.     if (agent) {
  9332.         strcat(request,"User-Agent: ");
  9333.         strcat(request,agent);
  9334.         strcat(request,"\r\n");
  9335.     }
  9336.     if (user) {
  9337.         strcat(request,"Authorization: Basic ");
  9338.         strcat(request,b64out);
  9339.         strcat(request,"\r\n");
  9340.     }
  9341.     for (i = 0; hdrlist[i]; i++) {
  9342.         strcat(request,hdrlist[i]);
  9343.         strcat(request,"\r\n");
  9344.     }
  9345.     strcat(request,"Content-type: ");
  9346.     strcat(request,mime);
  9347.     strcat(request,"\r\n");
  9348.     sprintf(buf,"Content-length: %d\r\n",filelen);
  9349.     strcat(request,buf);
  9350.     strcat(request,"\r\n");
  9351.  
  9352.     /* Now we have the contents of the file */
  9353.     if (zopeni(ZIFILE,local)) {
  9354.         if (ttol((CHAR *)request,strlen(request)) <= 0) { /* Send request */
  9355.             zclose(ZIFILE);
  9356.             goto putexit;
  9357.         }
  9358.         /* Request headers have been sent */
  9359.  
  9360.         i = 0;
  9361.         while (zchin(ZIFILE,&ch) == 0) {
  9362.             buf[i++] = ch;
  9363.             if (i == HTTPBUFLEN) {
  9364.                 ttol((CHAR *)buf,HTTPBUFLEN);
  9365.                 i = 0;
  9366.             }
  9367.         }
  9368.         if (i > 0)
  9369.           ttol((CHAR *)buf,i);
  9370.         zclose(ZIFILE);
  9371.  
  9372.         /* Process the response headers */
  9373.         local_t = time(NULL);
  9374.         nullline = 0;
  9375.         i = 0;
  9376.         while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  9377.             buf[i] = ch;
  9378.             if (buf[i] == 10) {         /* found end of line */
  9379.                 if (i <= 1)
  9380.                   nullline = 1;
  9381.                 i++;
  9382.                 buf[i] = '\0';
  9383.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  9384.                   makestr(&headers[hdcnt++],buf);
  9385.                 if (!strncmp(buf,"HTTP",4)) {
  9386.                     j = ckindex(" ",buf,0,0,0);
  9387.                     p = &buf[j];
  9388.                     if (strncmp(p,"200",3)) {
  9389.                         /* an error has occurred */
  9390.                         printf("Failure: Server reports %s",p);
  9391.                         rc = -1;
  9392.                         goto putexit;
  9393.                     }
  9394.                 } else {
  9395.                     printf("%s",buf);
  9396.                 }
  9397.                 i = 0;
  9398.             } else {
  9399.                 i++;
  9400.             }
  9401.         }
  9402.         if (array)
  9403.           http_mkarray(headers,hdcnt,array);
  9404.         rc = 0;
  9405.     }
  9406.  
  9407.   putexit:
  9408.     ttclos(0);
  9409.     free(request);
  9410.     for (i = 0; i < hdcnt; i++) {
  9411.         if (headers[i])
  9412.           free(headers[i]);
  9413.     }
  9414.     return(rc);
  9415. }
  9416.  
  9417. int
  9418. #ifdef CK_ANSIC
  9419. http_delete(char * agent, char ** hdrlist, char * user,
  9420.           char * pwd, char array, char * remote)
  9421. #else
  9422. http_delete(agent, hdrlist, user, pwd, array, remote)
  9423.     char * agent; char ** hdrlist; char * user;
  9424.     char * pwd; char array; char * remote;
  9425. #endif /* CK_ANSIC */
  9426. {
  9427.     char * request=NULL;
  9428.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  9429.     int    ch;
  9430.     char   buf[HTTPBUFLEN], *p;
  9431.     int    nullline;
  9432.     time_t mod_t;
  9433.     time_t srv_t;
  9434.     time_t local_t;
  9435.     char passwd[64];
  9436.     char b64in[128];
  9437.     char b64out[256];
  9438.     char * headers[HTTPHEADCNT];
  9439.  
  9440.     if (ttyfd == -1)
  9441.       return(-1);
  9442.  
  9443.     if (array) {
  9444.         for (i = 0; i < HTTPHEADCNT; i++)
  9445.           headers[i] = NULL;
  9446.     }
  9447.  
  9448.     /* Compute length of request header */
  9449.     len = 11;                            /* DELETE */
  9450.     len += strlen(HTTP_VERSION);
  9451.     len += strlen(remote);
  9452.  
  9453.     for (i = 0; hdrlist[i]; i++)
  9454.       len += strlen(hdrlist[i]) + 2;
  9455.     if (agent)
  9456.       len += 13 + strlen(agent);
  9457.     if (user) {
  9458.         if (!pwd) {
  9459.             readpass("Password: ",passwd,64);
  9460.             pwd = passwd;
  9461.         }
  9462.         sprintf(b64in,"%s:%s",user,pwd);
  9463.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  9464.         memset(pwd,0,strlen(pwd));
  9465.         if (j < 0)
  9466.           return(-1);
  9467.         b64out[j] = '\0';
  9468.         len += j + 24;
  9469.     }
  9470.     len += 32;                          /* Date: */
  9471.     len += 3;                           /* blank line + null */
  9472.  
  9473.     request = malloc(len);
  9474.     if (!request)
  9475.       return(-1);
  9476.  
  9477.     sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
  9478.     strcat(request,"Date: ");
  9479. #ifdef CMDATE2TM
  9480.     strcat(request,http_now());
  9481. #else
  9482.     strcap(request,...);
  9483. #endif /* CMDATE2TM */
  9484.     strcat(request,"\r\n");
  9485.     if (agent) {
  9486.         strcat(request,"User-Agent: ");
  9487.         strcat(request,agent);
  9488.         strcat(request,"\r\n");
  9489.     }
  9490.     if (user) {
  9491.         strcat(request,"Authorization: Basic ");
  9492.         strcat(request,b64out);
  9493.         strcat(request,"\r\n");
  9494.     }
  9495.     for (i = 0; hdrlist[i]; i++) {
  9496.         strcat(request,hdrlist[i]);
  9497.         strcat(request,"\r\n");
  9498.     }
  9499.     strcat(request,"\r\n");
  9500.  
  9501.     /* Process the response headers */
  9502.     local_t = time(NULL);
  9503.     nullline = 0;
  9504.     i = 0;
  9505.     while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  9506.         buf[i] = ch;
  9507.         if (buf[i] == 10) {         /* found end of line */
  9508.             if (i <= 1)
  9509.                 nullline = 1;
  9510.             i++;
  9511.             buf[i] = '\0';
  9512.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  9513.                 makestr(&headers[hdcnt++],buf);
  9514.             if (!strncmp(buf,"HTTP",4)) {
  9515.                 j = ckindex(" ",buf,0,0,0);
  9516.                 p = &buf[j];
  9517.                 if (strncmp(p,"200",3)) {
  9518.                     /* an error has occurred */
  9519.                     printf("Failure: Server reports %s",p);
  9520.                     rc = -1;
  9521.                     goto putexit;
  9522.                 }
  9523.             } else {
  9524.                 printf("%s",buf);
  9525.             }
  9526.             i = 0;
  9527.         } else {
  9528.                 i++;
  9529.         }
  9530.     }
  9531.     if (array)
  9532.         http_mkarray(headers,hdcnt,array);
  9533.     rc = 0;
  9534.  
  9535.   putexit:
  9536.     ttclos(0);
  9537.     free(request);
  9538.     for (i = 0; i < hdcnt; i++) {
  9539.         if (headers[i])
  9540.           free(headers[i]);
  9541.     }
  9542.     return(rc);
  9543. }
  9544.  
  9545. int
  9546. #ifdef CK_ANSIC
  9547. http_post(char * agent, char ** hdrlist, char * mime, char * user,
  9548.           char * pwd, char array, char * local, char * remote)
  9549. #else
  9550. http_post(agent, hdrlist, mime, user, pwd, array, local, remote)
  9551.     char * agent; char ** hdrlist; char * mime; char * user;
  9552.     char * pwd; char array; char * local; char * remote;
  9553. #endif /* CK_ANSIC */
  9554. {
  9555.     char * request=NULL;
  9556.     int    i, j, len = 0, hdcnt = 0, rc = -1;
  9557.     int    ch;
  9558.     char   buf[HTTPBUFLEN], *p;
  9559.     int    nullline;
  9560.     time_t mod_t;
  9561.     time_t srv_t;
  9562.     time_t local_t;
  9563.     char passwd[64];
  9564.     char b64in[128];
  9565.     char b64out[256];
  9566.     int  filelen;
  9567.     char * headers[HTTPHEADCNT];
  9568.  
  9569.     if (ttyfd == -1)
  9570.       return(-1);
  9571.  
  9572.     if (array) {
  9573.         for (i = 0; i < HTTPHEADCNT; i++)
  9574.           headers[i] = NULL;
  9575.     }
  9576.     filelen = zchki(local);
  9577.     if (filelen < 0)
  9578.       return(-1);
  9579.  
  9580.     /* Compute length of request header */
  9581.     len = 9;                            /* POST */
  9582.     len += strlen(HTTP_VERSION);
  9583.     len += strlen(remote);
  9584.  
  9585.     for (i = 0; hdrlist[i]; i++)
  9586.       len += strlen(hdrlist[i]) + 2;
  9587.     if (agent)
  9588.       len += 13 + strlen(agent);
  9589.     if (user) {
  9590.         if (!pwd) {
  9591.             readpass("Password: ",passwd,64);
  9592.             pwd = passwd;
  9593.         }
  9594.         sprintf(b64in,"%s:%s",user,pwd);
  9595.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  9596.         memset(pwd,0,strlen(pwd));
  9597.         if (j < 0)
  9598.           return(-1);
  9599.         b64out[j] = '\0';
  9600.         len += j + 24;
  9601.     }
  9602.     len += 16 + strlen(mime);           /* Content-type: */
  9603.     len += 32;                          /* Content-length: */
  9604.     len += 32;                          /* Date: */
  9605.     len += 3;                           /* blank line + null */
  9606.  
  9607.     request = malloc(len);
  9608.     if (!request)
  9609.       return(-1);
  9610.  
  9611.     sprintf(request,"POST %s %s\r\n",remote,HTTP_VERSION);
  9612.     strcat(request,"Date: ");
  9613.     strcat(request,http_now());
  9614.     strcat(request,"\r\n");
  9615.     if (agent) {
  9616.         strcat(request,"User-Agent: ");
  9617.         strcat(request,agent);
  9618.         strcat(request,"\r\n");
  9619.     }
  9620.     if (user) {
  9621.         strcat(request,"Authorization: Basic ");
  9622.         strcat(request,b64out);
  9623.         strcat(request,"\r\n");
  9624.     }
  9625.     for (i = 0; hdrlist[i]; i++) {
  9626.         strcat(request,hdrlist[i]);
  9627.         strcat(request,"\r\n");
  9628.     }
  9629.     strcat(request,"Content-type: ");
  9630.     strcat(request,mime);
  9631.     strcat(request,"\r\n");
  9632.     sprintf(buf,"Content-length: %d\r\n",filelen);
  9633.     strcat(request,buf);
  9634.     strcat(request,"\r\n");
  9635.     strcat(request,"\r\n");
  9636.  
  9637.     /* Now we have the contents of the file */
  9638.     if (zopeni(ZIFILE,local)) {
  9639.         ttol((CHAR *)request,strlen(request)); /* Send request */
  9640.  
  9641.         i = 0;
  9642.         while (zchin(ZIFILE,&ch) == 0) {
  9643.             buf[i++] = ch;
  9644.             if (i == HTTPBUFLEN) {
  9645.                 ttol((CHAR *)buf,HTTPBUFLEN);
  9646.                 i = 0;
  9647.             }
  9648.         }
  9649.         if (i > 0)
  9650.           ttol((CHAR *)buf,HTTPBUFLEN);
  9651.         zclose(ZIFILE);
  9652.  
  9653.         /* Process the response headers */
  9654.         local_t = time(NULL);
  9655.         nullline = 0;
  9656.         i = 0;
  9657.         while (!nullline && (ch = ttinc(0)) >= 0 && i < HTTPBUFLEN) {
  9658.             buf[i] = ch;
  9659.             if (buf[i] == 10) {         /* found end of line */
  9660.                 if (i <= 1)
  9661.                   nullline = 1;
  9662.                 i++;
  9663.                 buf[i] = '\0';
  9664.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  9665.                   makestr(&headers[hdcnt++],buf);
  9666.                 if (!strncmp(buf,"HTTP",4)) {
  9667.                     j = ckindex(" ",buf,0,0,0);
  9668.                     p = &buf[j];
  9669.                     if (strncmp(p,"200",3)) {
  9670.                         /* an error has occurred */
  9671.                         printf("Failure: Server reports %s",p);
  9672.                         rc = -1;
  9673.                         goto postexit;
  9674.                     }
  9675.                 } else {
  9676.                     printf("%s",buf);
  9677.                 }
  9678.                 i = 0;
  9679.             } else {
  9680.                 i++;
  9681.             }
  9682.         }
  9683.         if (array)
  9684.           http_mkarray(headers,hdcnt,array);
  9685.         rc = 0;
  9686.     }
  9687.  
  9688.   postexit:
  9689.     ttclos(0);
  9690.     free(request);
  9691.     for (i = 0; i < hdcnt; i++) {
  9692.         if (headers[i])
  9693.           free(headers[i]);
  9694.     }
  9695.     return(rc);
  9696. }
  9697. #endif /* NOHTTP */
  9698.  
  9699. #ifdef CK_DNS_SRV
  9700.  
  9701. #define INCR_CHECK(x,y) x += y; if (x > size + answer.bytes) goto dnsout
  9702. #define CHECK(x,y) if (x + y > size + answer.bytes) goto dnsout
  9703. #define NTOHSP(x,y) x[0] << 8 | x[1]; x += y
  9704.  
  9705. #ifndef CKQUERYTYPE
  9706. #ifdef UNIXWARE
  9707. #ifndef UW7
  9708. #define CKQUERYTYPE CHAR
  9709. #endif /* UW7 */
  9710. #endif /* UNIXWARE */
  9711. #endif /* CKQUERYTYPE */
  9712.  
  9713. #ifndef CKQUERYTYPE
  9714. #define CKQUERYTYPE char
  9715. #endif /* CKQUERYTYPE */
  9716.  
  9717. /* 1 is success, 0 is failure */
  9718. int
  9719. locate_srv_dns(host, service, protocol, addr_pp, naddrs)
  9720. #ifdef CK_ANSIC
  9721.     const char *host;                   /* "const" not portable... */
  9722.     const char *service;
  9723.     const char *protocol;
  9724. #else
  9725.     char *host;
  9726.     char *service;
  9727.     char *protocol;
  9728. #endif /* CK_ANSIC */
  9729.     struct sockaddr **addr_pp;
  9730.     int *naddrs;
  9731. {
  9732.     int code, nout, j, count;
  9733.     union {
  9734.         unsigned char bytes[2048];
  9735.         HEADER hdr;
  9736.     } answer;
  9737.     unsigned char *p=NULL;
  9738.     CKQUERYTYPE query[MAX_DNS_NAMELEN];
  9739.     struct sockaddr *addr = NULL;
  9740.     struct sockaddr_in *sin = NULL;
  9741.     struct hostent *hp = NULL;
  9742.     int type, class;
  9743.     int status, priority, weight, size, len, numanswers, numqueries, rdlen;
  9744.     unsigned short port;
  9745. #ifdef CK_ANSIC
  9746.     const
  9747. #endif /* CK_ANSIC */
  9748.       int hdrsize = sizeof(HEADER);
  9749.     struct srv_dns_entry {
  9750.         struct srv_dns_entry *next;
  9751.         int priority;
  9752.         int weight;
  9753.         unsigned short port;
  9754.         char *host;
  9755.     };
  9756.     struct srv_dns_entry *head = NULL;
  9757.     struct srv_dns_entry *srv = NULL, *entry = NULL;
  9758.     char * s = NULL;
  9759.  
  9760.     nout = 0;
  9761.     addr = (struct sockaddr *) malloc(sizeof(struct sockaddr));
  9762.     if (addr == NULL)
  9763.       return 0;
  9764.  
  9765.     count = 1;
  9766.  
  9767.     /*
  9768.      * First build a query of the form:
  9769.      *
  9770.      *   service.protocol.host
  9771.      *
  9772.      * which will most likely be something like:
  9773.      *
  9774.      *   _telnet._tcp.host
  9775.      *
  9776.      */
  9777.     if (((int)strlen(service) + strlen(protocol) + strlen(host) + 5)
  9778.         > MAX_DNS_NAMELEN
  9779.         )
  9780.       goto dnsout;
  9781.     sprintf((char *)query, "_%s._%s.%s", service, protocol, host);
  9782.  
  9783.     size = res_search(query, C_IN, T_SRV, answer.bytes, sizeof(answer.bytes));
  9784.  
  9785.     if (size < hdrsize)
  9786.       goto dnsout;
  9787.  
  9788.     /* We got a reply - See how many answers it contains. */
  9789.  
  9790.     p = answer.bytes;
  9791.  
  9792.     numqueries = ntohs(answer.hdr.qdcount);
  9793.     numanswers = ntohs(answer.hdr.ancount);
  9794.  
  9795.     p += sizeof(HEADER);
  9796.  
  9797.     /*
  9798.      * We need to skip over all of the questions, so we have to iterate
  9799.      * over every query record.  dn_expand() is able to tell us the size
  9800.      * of compressed DNS names, so we use it.
  9801.      */
  9802.     while (numqueries--) {
  9803.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  9804.         if (len < 0)
  9805.           goto dnsout;
  9806.         INCR_CHECK(p, len + 4);
  9807.     }
  9808.  
  9809.     /*
  9810.      * We're now pointing at the answer records.  Only process them if
  9811.      * they're actually T_SRV records (they might be CNAME records,
  9812.      * for instance).
  9813.      *
  9814.      * But in a DNS reply, if you get a CNAME you always get the associated
  9815.      * "real" RR for that CNAME.  RFC 1034, 3.6.2:
  9816.      *
  9817.      * CNAME RRs cause special action in DNS software.  When a name server
  9818.      * fails to find a desired RR in the resource set associated with the
  9819.      * domain name, it checks to see if the resource set consists of a CNAME
  9820.      * record with a matching class.  If so, the name server includes the CNAME
  9821.      * record in the response and restarts the query at the domain name
  9822.      * specified in the data field of the CNAME record.  The one exception to
  9823.      * this rule is that queries which match the CNAME type are not restarted.
  9824.      *
  9825.      * In other words, CNAMEs do not need to be expanded by the client.
  9826.      */
  9827.     while (numanswers--) {
  9828.  
  9829.         /* First is the name; use dn_expand() to get the compressed size. */
  9830.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  9831.         if (len < 0)
  9832.           goto dnsout;
  9833.         INCR_CHECK(p, len);
  9834.  
  9835.         CHECK(p,2);                     /* Query type */
  9836.         type = NTOHSP(p,2);
  9837.  
  9838.         CHECK(p, 6);                    /* Query class */
  9839.         class = NTOHSP(p,6);            /* Also skip over 4-byte TTL */
  9840.  
  9841.         CHECK(p,2);                     /* Record data length */
  9842.         rdlen = NTOHSP(p,2);
  9843.         /*
  9844.          * If this is an SRV record, process it.  Record format is:
  9845.          *
  9846.          * Priority
  9847.          * Weight
  9848.          * Port
  9849.          * Server name
  9850.          */
  9851.         if (class == C_IN && type == T_SRV) {
  9852.             CHECK(p,2);
  9853.             priority = NTOHSP(p,2);
  9854.             CHECK(p, 2);
  9855.             weight = NTOHSP(p,2);
  9856.             CHECK(p, 2);
  9857.             port = NTOHSP(p,2);
  9858.             len = dn_expand(answer.
  9859.                             bytes,
  9860.                             answer.bytes + size,
  9861.                             p,
  9862.                             query,
  9863.                             sizeof(query)
  9864.                             );
  9865.             if (len < 0)
  9866.               goto dnsout;
  9867.             INCR_CHECK(p, len);
  9868.             /*
  9869.              * We got everything.  Insert it into our list, but make sure
  9870.              * it's in the right order.  Right now we don't do anything
  9871.              * with the weight field
  9872.              */
  9873.             srv = (struct srv_dns_entry *)malloc(sizeof(struct srv_dns_entry));
  9874.             if (srv == NULL)
  9875.               goto dnsout;
  9876.  
  9877.             srv->priority = priority;
  9878.             srv->weight = weight;
  9879.             srv->port = port;
  9880.             makestr(&s,(char *)query);  /* strdup() is not portable */
  9881.             srv->host = s;
  9882.  
  9883.             if (head == NULL || head->priority > srv->priority) {
  9884.                 srv->next = head;
  9885.                 head = srv;
  9886.             } else
  9887.                 /*
  9888.                  * Confusing.  Insert an entry into this spot only if:
  9889.                  *  . The next person has a higher priority (lower
  9890.                  *    priorities are preferred), or:
  9891.                  *  . There is no next entry (we're at the end)
  9892.                  */
  9893.               for (entry = head; entry != NULL; entry = entry->next)
  9894.                 if ((entry->next &&
  9895.                      entry->next->priority > srv->priority) ||
  9896.                     entry->next == NULL) {
  9897.                     srv->next = entry->next;
  9898.                     entry->next = srv;
  9899.                     break;
  9900.                 }
  9901.         } else
  9902.           INCR_CHECK(p, rdlen);
  9903.     }
  9904.  
  9905.     /*
  9906.      * Now we've got a linked list of entries sorted by priority.
  9907.      * Start looking up A records and returning addresses.
  9908.      */
  9909.     if (head == NULL)
  9910.       goto dnsout;
  9911.  
  9912.     for (entry = head; entry != NULL; entry = entry->next) {
  9913.         hp = gethostbyname(entry->host);
  9914.         if (hp != 0) {
  9915.  
  9916.             /* Watch out - memset() and memcpy() are not portable... */
  9917.  
  9918.             switch (hp->h_addrtype) {
  9919.               case AF_INET:
  9920.                 for (j = 0; hp->h_addr_list[j]; j++) {
  9921.                     sin = (struct sockaddr_in *) &addr[nout++];
  9922.                     memset ((char *) sin, 0, sizeof (struct sockaddr));
  9923.                     sin->sin_family = hp->h_addrtype;
  9924.                     sin->sin_port = htons(entry->port);
  9925.                     memcpy((char *) &sin->sin_addr,
  9926.                            (char *) hp->h_addr_list[j],
  9927.                            sizeof(struct in_addr));
  9928.                     if (nout + 1 >= count) {
  9929.                         count += 5;
  9930.                         addr = (struct sockaddr *)
  9931.                           realloc((char *) addr,
  9932.                                   sizeof(struct sockaddr) * count);
  9933.                         if (!addr)
  9934.                           goto dnsout;
  9935.                     }
  9936.                 }
  9937.                 break;
  9938.               default:
  9939.                 break;
  9940.             }
  9941.         }
  9942.     }
  9943.     for (entry = head; entry != NULL;) {
  9944.         free(entry->host);
  9945.         entry->host = NULL;
  9946.         srv = entry;
  9947.         entry = entry->next;
  9948.         free(srv);
  9949.         srv = NULL;
  9950.     }
  9951.  
  9952.   dnsout:
  9953.     if (srv)
  9954.       free(srv);
  9955.  
  9956.     if (nout == 0) {                    /* No good servers */
  9957.         if (addr)
  9958.           free(addr);
  9959.         return 0;
  9960.     }
  9961.     *addr_pp = addr;
  9962.     *naddrs = nout;
  9963.     return 1;
  9964. }
  9965. #endif /* CK_DNS_SRV */
  9966.  
  9967. #ifdef TNCODE
  9968. #ifdef CK_FORWARD_X
  9969. int
  9970. fwdx_create_listen_socket(screen) int screen; {
  9971. #ifdef NOPUTENV
  9972.     return(-1);
  9973. #else /* NOPUTENV */
  9974.     struct sockaddr_in saddr;
  9975.     int display, port, sock=-1, i;
  9976.     static char env[512];
  9977.  
  9978.     /*
  9979.      * X Windows Servers support multiple displays by listening on
  9980.      * one socket per display.  Display 0 is port 6000; Display 1 is
  9981.      * port 6001; etc.
  9982.      *
  9983.      * We start by trying to open port 6001 so that display 0 is
  9984.      * reserved for the local X Windows Server.
  9985.      */
  9986.  
  9987.     for ( display=1; display < 1000 ; display++  ) {
  9988.  
  9989.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  9990.             debug(F111,"fwdx_create_listen_socket()","socket() < 0",sock);
  9991.             return(-1);
  9992.         }
  9993.  
  9994.         port = 6000 + display;
  9995.         bzero((char *)&saddr, sizeof(saddr));
  9996.         saddr.sin_family = AF_INET;
  9997.         saddr.sin_addr.s_addr = inet_addr(myipaddr);
  9998.         saddr.sin_port = htons(port);
  9999.  
  10000.         if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  10001.             i = errno;                  /* Save error code */
  10002. #ifdef TCPIPLIB
  10003.             socket_close(sock);
  10004. #else /* TCPIPLIB */
  10005.             close(sock);
  10006. #endif /* TCPIPLIB */
  10007.             sock = -1;
  10008.             debug(F110,"fwdx_create_listen_socket()","bind() < 0",0);
  10009.             continue;
  10010.         }
  10011.  
  10012.         debug(F100,"fdwx_create_listen_socket() bind OK","",0);
  10013.         break;
  10014.     }
  10015.  
  10016.     if ( display > 1000 ) {
  10017.         debug(F100,"fwdx_create_listen_socket() Out of Displays","",0);
  10018.         return(-1);
  10019.     }
  10020.  
  10021.     if (listen(sock, 5) < 0) {
  10022.         i = errno;                  /* Save error code */
  10023. #ifdef TCPIPLIB
  10024.         socket_close(sock);
  10025. #else /* TCPIPLIB */
  10026.         close(sock);
  10027. #endif /* TCPIPLIB */
  10028.         debug(F101,"fdwx_create_listen_socket() listen() errno","",errno);
  10029.         return(-1);
  10030.     }
  10031.     debug(F100,"fwdx_create_listen_socket() listen OK","",0);
  10032.  
  10033.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = sock;
  10034.     if (!myipaddr[0])
  10035.         getlocalipaddr();
  10036.     if ( myipaddr[0] )
  10037.         sprintf(env,"DISPLAY=%s:%d:%d",myipaddr,display,screen);
  10038.     else
  10039.         sprintf(env,"DISPLAY=%d:%d",display,screen);
  10040.     putenv(env);
  10041.     return(0);
  10042. #endif /* NOPUTENV */
  10043. }
  10044.  
  10045.  
  10046. int
  10047. fwdx_open_client_channel(channel) int channel; {
  10048.     char * env;
  10049.     struct sockaddr_in saddr;
  10050.     int colon, dot, display, port, sock, i;
  10051.     char buf[256];
  10052. #ifdef TCP_NODELAY
  10053.     int on=1;
  10054. #endif /* TCP_NODELAY */
  10055.  
  10056.     debug(F111,"fwdx_create_client_channel()","channel",channel);
  10057.  
  10058.     for ( i=0; i<MAXFWDX ; i++ ) {
  10059.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel) {
  10060.             /* Already open */
  10061.             debug(F110,"fwdx_create_client_channel()","already open",0);
  10062.             return(0);
  10063.         }
  10064.     }
  10065.  
  10066.     env = getenv("DISPLAY");
  10067.     if ( env )
  10068.         ckstrncpy(buf,env,256);
  10069.     else
  10070.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  10071.  
  10072.     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  10073.         debug(F111,"fwdx_create_client_channel()","socket() < 0",sock);
  10074.         return(-1);
  10075.     }
  10076.  
  10077.     bzero((char *)&saddr,sizeof(saddr));
  10078.     saddr.sin_family = AF_INET;
  10079.  
  10080.     colon = ckindex(":",buf,0,0,1);
  10081.     dot   = ckindex(".",&buf[colon],0,0,1);
  10082.     if ( dot )
  10083.         buf[colon+dot-1] = '\0';
  10084.     display = atoi(&buf[colon+dot-1]);
  10085.  
  10086.     port = 6000 + display;
  10087.     saddr.sin_port = htons(port);
  10088.  
  10089.     if ( colon ) {
  10090.         buf[colon-1] = '\0';
  10091.         debug(F110,"fwdx_create_client_channel() ip-address",buf,0);
  10092.         saddr.sin_addr.s_addr = inet_addr(buf);
  10093.     } else {
  10094.         debug(F110,"fwdx_create_client_channel() ip-address",myipaddr,0);
  10095.         saddr.sin_addr.s_addr = inet_addr(myipaddr);
  10096.     }
  10097.  
  10098.     if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  10099.         debug(F110,"fwdx_create_client_channel()","connect() failed",0);
  10100. #ifdef TCPIPLIB
  10101.         socket_close(sock);
  10102. #else /* TCPIPLIB */
  10103.         close(sock);
  10104. #endif /* TCPIPLIB */
  10105.         return(-1);
  10106.     }
  10107.  
  10108. #ifdef TCP_NODELAY
  10109.     setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  10110. #endif /* TCP_NODELAY */
  10111.  
  10112.     for ( i=0; i<MAXFWDX ; i++ ) {
  10113.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == -1) {
  10114.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = sock;
  10115.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = channel;
  10116.             debug(F111,"fwdx_create_client_channel()","socket",sock);
  10117.             return(0);
  10118.         }
  10119.     }
  10120.     return(-1);
  10121. }
  10122.  
  10123. int
  10124. fwdx_open_server_channel() {
  10125.     int sock, ready_to_accept, sock2,channel,i;
  10126. #ifdef TCP_NODELAY
  10127.     int on=1;
  10128. #endif /* TCP_NODELAY */
  10129. #ifdef UCX50
  10130.     static u_int saddrlen;
  10131. #else
  10132.     static SOCKOPT_T saddrlen;
  10133. #endif /* UCX50 */
  10134.     struct sockaddr_in saddr;
  10135.     char sb[8];
  10136.     extern char tn_msg[];
  10137. #ifdef BSDSELECT
  10138.     fd_set rfds;
  10139.     struct timeval tv;
  10140. #else
  10141. #ifdef BELLSELCT
  10142.     fd_set rfds;
  10143. #else
  10144.     fd_set rfds;
  10145.     struct timeval {
  10146.         long tv_sec;
  10147.         long tv_usec;
  10148.     } tv;
  10149. #endif /* BELLSELECT */
  10150. #endif /* BSDSELECT */
  10151.     unsigned short nchannel;
  10152.     unsigned char * p;
  10153.  
  10154.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket;
  10155.  
  10156.   try_again:
  10157.  
  10158. #ifdef BSDSELECT
  10159.     tv.tv_sec  = tv.tv_usec = 0L;
  10160.     tv.tv_usec = 50;
  10161.     FD_ZERO(&rfds);
  10162.     FD_SET(sock, &rfds);
  10163.     ready_to_accept =
  10164.         ((select(FD_SETSIZE,
  10165. #ifdef HPUX
  10166. #ifdef HPUX1010
  10167.                   (fd_set *)
  10168. #else
  10169.  
  10170.                   (int *)
  10171. #endif /* HPUX1010 */
  10172. #else
  10173. #ifdef __DECC
  10174.                   (fd_set *)
  10175. #endif /* __DECC */
  10176. #endif /* HPUX */
  10177.                   &rfds, NULL, NULL, &tv) > 0) &&
  10178.           FD_ISSET(sock, &rfds));
  10179. #else /* BSDSELECT */
  10180. #ifdef IBMSELECT
  10181.     ready_to_accept = (select(&sock, 1, 0, 0, 50) == 1);
  10182. #else
  10183. #ifdef BELLSELECT
  10184.     FD_ZERO(rfds);
  10185.     FD_SET(sock, rfds);
  10186.     ready_to_accept =
  10187.         ((select(128, rfds, NULL, NULL, 50) > 0) &&
  10188.           FD_ISSET(sock, rfds));
  10189. #else
  10190. /* Try this - what's the worst that can happen... */
  10191.  
  10192.     tv.tv_sec  = tv.tv_usec = 0L;
  10193.     tv.tv_usec = 50;
  10194.     FD_ZERO(&rfds);
  10195.     FD_SET(sock, &rfds);
  10196.     ready_to_accept =
  10197.         ((select(FD_SETSIZE,
  10198.                   (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  10199.           FD_ISSET(sock, &rfds));
  10200. #endif /* BELLSELECT */
  10201. #endif /* IBMSELECT */
  10202. #endif /* BSDSELECT */
  10203.  
  10204.     if ( !ready_to_accept )
  10205.         return(0);
  10206.  
  10207.     if ((sock2 = accept(sock,(struct sockaddr *)&saddr,&saddrlen)) < 0) {
  10208.         int i = errno;                  /* save error code */
  10209.         debug(F101,"tcpsrv_open accept errno","",i);
  10210.         return(-1);
  10211.     }
  10212.  
  10213.     /*
  10214.      * Now we have the open socket.  We must now find a channel to store
  10215.      * it in, and then notify the client.
  10216.      */
  10217.  
  10218.     for ( channel=0;channel<MAXFWDX;channel++ ) {
  10219.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd == -1 )
  10220.             break;
  10221.     }
  10222.  
  10223.     if ( channel == MAXFWDX ) {
  10224. #ifdef TCPIPLIB
  10225.         socket_close(sock2);
  10226. #else /* TCPIPLIB */
  10227.         close(sock2);
  10228. #endif /* TCPIPLIB */
  10229.         return(-1);
  10230.     }
  10231.  
  10232.     if ( fwdx_send_open(channel) < 0 ) {
  10233. #ifdef TCPIPLIB
  10234.         socket_close(sock2);
  10235. #else /* TCPIPLIB */
  10236.         close(sock2);
  10237. #endif /* TCPIPLIB */
  10238.     }
  10239.  
  10240. #ifdef TCP_NODELAY
  10241.     setsockopt(sock2,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  10242. #endif /* TCP_NODELAY */
  10243.  
  10244.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd = sock2;
  10245.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].id = channel;
  10246.     goto try_again;
  10247.  
  10248.     return(0);  /* never reached */
  10249. }
  10250.  
  10251. int
  10252. fwdx_close_channel(channel) int channel; {
  10253.     int i;
  10254.  
  10255.     for ( i=0; i<MAXFWDX ; i++ ) {
  10256.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  10257.             break;
  10258.     }
  10259.     if ( i == MAXFWDX )
  10260.         return(-1);
  10261.  
  10262. #ifdef TCPIPLIB
  10263.     socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd);
  10264. #else /* TCPIPLIB */
  10265.     close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd);
  10266. #endif /* TCPIPLIB */
  10267.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = -1;
  10268.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = -1;
  10269.     return(0);
  10270. }
  10271.  
  10272. int
  10273. fwdx_close_all() {
  10274.     int x;
  10275.  
  10276.     if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1 ) {
  10277. #ifdef TCPIPLIB
  10278.         socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  10279. #else /* TCPIPLIB */
  10280.         close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  10281. #endif /* TCPIPLIB */
  10282.         TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = -1;
  10283.     }
  10284.  
  10285.     for ( x=0 ; x<MAXFWDX ; x++ ) {
  10286.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1 ) {
  10287. #ifdef TCPIPLIB
  10288.             socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd);
  10289. #else /* TCPIPLIB */
  10290.             close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd);
  10291. #endif /* TCPIPLIB */
  10292.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd = -1;
  10293.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id = -1;
  10294.         }
  10295.     }
  10296.     return(0);
  10297. }
  10298.  
  10299. /* The following definitions are for Unix */
  10300. #ifndef socket_write
  10301. #define socket_write(f,s,n)    write(f,s,n)
  10302. #endif /* socket_write */
  10303. #ifndef socket_read
  10304. #define socket_read(f,s,n)     read(f,s,n)
  10305. #endif /* socket_read */
  10306.  
  10307. int
  10308. fwdx_write_data_to_channel(channel, data, len)
  10309.     int channel; char * data; int len;
  10310. {
  10311.     int sock, count, try=0, length = 0, i;
  10312.  
  10313.     for ( i=0; i<MAXFWDX ; i++ ) {
  10314.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  10315.             break;
  10316.     }
  10317.     if ( i == MAXFWDX ) {
  10318.         debug(F110,"fwdx_write_data_to_channel",
  10319.                "attempting to write to closed channel",0);
  10320.         return(-1);
  10321.     }
  10322.  
  10323.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  10324.     debug(F111,"fwdx_write_data_to_channel","socket",sock);
  10325.     hexdump("fwdx_write_data_to_channel",data,len);
  10326.  
  10327.   fwdx_write_data_to_channel_retry:
  10328.  
  10329.     if ((count = socket_write(sock,data,len)) < 0) {
  10330.         int s_errno = socket_errno; /* maybe a function */
  10331.         debug(F101,"fwdx_write_data_to_channel socket_write error","",s_errno);
  10332. #ifdef OS2
  10333.         if (os2socketerror(s_errno) < 0)
  10334.             return(-2);
  10335. #endif /* OS2 */
  10336.         return(-1);                 /* Call it an i/o error */
  10337.     }
  10338.     if (count < len) {
  10339.         debug(F111,"fwdx_write_data_to_channel socket_write",data,count);
  10340.         if (try > 25) {
  10341.             /* don't try more than 25 times */
  10342.             debug(F100,
  10343.           "fwdx_write_data_to_channel tried more than 25 times","",0);
  10344.             return(-1);
  10345.         }
  10346.         if (count > 0) {
  10347.             data += count;
  10348.             len -= count;
  10349.         }
  10350.         debug(F111,"fwdx_write_data_to_channel retry",data,len);
  10351.         if ( len > 0 )
  10352.             goto fwdx_write_data_to_channel_retry;
  10353.     }
  10354.  
  10355.     debug(F111,"fwdx_write_data_to_channel socket_write",data,length);
  10356.     return(length); /* success - return total length */
  10357. }
  10358.  
  10359. int
  10360. fwdx_send_data_from_channel(channel, data, len)
  10361.     int channel; char * data; int len;
  10362. {
  10363.     extern char tn_msg[];
  10364.     int nchannel;
  10365.     static CHAR sb[2048];
  10366.     CHAR * p;
  10367.     int i, j;
  10368.     unsigned int tmp;
  10369.  
  10370.     debug(F111,"fwdx_send_data_from_channel()","channel",channel);
  10371.  
  10372.     nchannel = htons(channel);
  10373.     p = (unsigned char *) &nchannel;
  10374.  
  10375.     sb[0] = (CHAR) IAC;                 /* I Am a Command */
  10376.     sb[1] = (CHAR) SB;                  /* Subnegotiation */
  10377.     sb[2] = TELOPT_FORWARD_X;           /* Forward X */
  10378.     sb[3] = FWDX_DATA;                  /* Data */
  10379.     sb[4] = p[0];
  10380.     sb[5] = p[1];
  10381.  
  10382.     for ( i=0, j=6 ; i<len ; i++ ) {
  10383.         tmp = (unsigned int)data[i];
  10384.         if ( tmp == IAC ) {
  10385.             sb[j++] = IAC;
  10386.             sb[j++] = IAC;
  10387.         } else {
  10388.             sb[j++] = tmp;
  10389.         }
  10390.         if ( j == 2046 && (i < len-1) ) {
  10391.             sb[j++] = (CHAR) IAC;                 /* End of Subnegotiation */
  10392.             sb[j++] = (CHAR) SE;                  /* marked by IAC SE */
  10393.             if ( ttol(sb,j) < 0 ) {
  10394.                 debug(F110,"fwdx_send_data_from_channel()","ttol() failed",0);
  10395.                 return(-1);
  10396.             }
  10397. #ifdef DEBUG
  10398.             if (deblog || tn_deb || debses) {
  10399.                 sprintf(tn_msg,"TELNET SENT SB %s DATA %02x %02x ",
  10400.                          TELOPT(TELOPT_FORWARD_X),p[0],p[1]);
  10401. #ifdef HEXDISP
  10402.                 {
  10403.                     int was_hex = 1, k;
  10404.                     extern char hexbuf[];
  10405.                     for (k=6; k < j-2; k++) {
  10406.                         if (sb[k] < 32 || sb[k] >= 127) {
  10407.                             sprintf(hexbuf,"%s%02X ",was_hex?"":"\" ",sb[k]);
  10408.                             was_hex = 1;
  10409.                         } else {
  10410.                             sprintf(hexbuf,"%s%c",was_hex?"\"":"",sb[k]);
  10411.                             was_hex = 0;
  10412.                         }
  10413.                         strcat(tn_msg,hexbuf);
  10414.                     }
  10415.                     if (!was_hex)
  10416.                         strcat(tn_msg,"\" ");
  10417.                 }
  10418. #else /* HEXDISP */
  10419.                 memcpy(hexbuf,&sb[k],j-k);
  10420.                 hexbuf[j-k] = ' ';
  10421.                 hexbuf[j-k+1] = '\0';
  10422.                 strcat(tn_msg,hexbuf);
  10423. #endif /* HEXDISP */
  10424.                 strcat(tn_msg," IAC SE");
  10425.                 debug(F100,tn_msg,"",0);
  10426.                 if (tn_deb || debses) tn_debug(tn_msg);
  10427.             }
  10428. #endif /* DEBUG */
  10429.  
  10430.             sb[0] = (CHAR) IAC;                 /* I Am a Command */
  10431.             sb[1] = (CHAR) SB;                  /* Subnegotiation */
  10432.             sb[2] = TELOPT_FORWARD_X;           /* Forward X */
  10433.             sb[3] = FWDX_DATA;                  /* Data */
  10434.             sb[4] = p[0];
  10435.             sb[5] = p[1];
  10436.  
  10437.             j = 6;
  10438.         }
  10439.     }
  10440.  
  10441.     sb[j++] = (CHAR) IAC;                 /* End of Subnegotiation */
  10442.     sb[j++] = (CHAR) SE;                  /* marked by IAC SE */
  10443.     if ( ttol(sb,j) < 0 ) {
  10444.         debug(F110,"fwdx_send_data_from_channel()","ttol() failed",0);
  10445.         return(-1);
  10446.     }
  10447.  
  10448. #ifdef DEBUG
  10449.     if (deblog || tn_deb || debses) {
  10450.         sprintf(tn_msg,"TELNET SENT SB %s DATA %02x %02x ",
  10451.                  TELOPT(TELOPT_FORWARD_X),p[0],p[1]);
  10452. #ifdef HEXDISP
  10453.         {
  10454.             int was_hex = 1, k;
  10455.             extern char hexbuf[];
  10456.             for (k=6; k < j-2; k++) {
  10457.                 if (sb[k] < 32 || sb[k] >= 127) {
  10458.                     sprintf(hexbuf,"%s%02X ",was_hex?"":"\" ",sb[k]);
  10459.                     was_hex = 1;
  10460.                 } else {
  10461.                     sprintf(hexbuf,"%s%c",was_hex?"\"":"",sb[k]);
  10462.                     was_hex = 0;
  10463.                 }
  10464.                 strcat(tn_msg,hexbuf);
  10465.             }
  10466.             if (!was_hex)
  10467.                 strcat(tn_msg,"\" ");
  10468.         }
  10469. #else /* HEXDISP */
  10470.         memcpy(hexbuf,&sb[k],j-k-2);
  10471.         hexbuf[j-k-2] = ' ';
  10472.         hexbuf[j-k-1] = '\0';
  10473.         strcat(tn_msg,hexbuf);
  10474. #endif /* HEXDISP */
  10475.         strcat(tn_msg," IAC SE");
  10476.         debug(F100,tn_msg,"",0);
  10477.         if (tn_deb || debses) tn_debug(tn_msg);
  10478.     }
  10479. #endif /* DEBUG */
  10480.  
  10481.     return(0);
  10482. }
  10483.  
  10484. VOID
  10485. fwdx_check_sockets(fd_set *ibits)
  10486. {
  10487.     int x, sock, channel;
  10488.     static char buffer[32000];
  10489.  
  10490.     debug(F100,"fwdx_check_sockets()","",0);
  10491.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  10492.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  10493.         debug(F110,"fwdx_check_sockets()","TELOPT_FORWARD_X not negotiated",0);
  10494.         return;
  10495.     }
  10496.  
  10497.     for (x = 0; x < MAXFWDX; x++) {
  10498.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd == -1 )
  10499.             continue;
  10500.  
  10501.         sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  10502.         channel = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id;
  10503.         if (FD_ISSET(sock, ibits))
  10504.         {
  10505.             int bytes, nn = 1;
  10506.             fd_set fdset;
  10507.             struct timeval tv;
  10508.  
  10509.             debug(F111,"fwdx_check_sockets()","channel set",x);
  10510.  
  10511.             memset(&tv, 0, sizeof(tv));
  10512.             /* make sure we read _all_ available data */
  10513.             do {
  10514.  
  10515.                 bytes = socket_read(sock, buffer, sizeof(buffer));
  10516.                 if (bytes > 0)
  10517.                     fwdx_send_data_from_channel(channel, buffer, bytes);
  10518.                 else {
  10519.                     fwdx_close_channel(channel);
  10520.                     fwdx_send_close(channel);
  10521.                 }
  10522.                 FD_ZERO(&fdset);
  10523.                 FD_SET(sock, &fdset);
  10524.             } while (select(128, &fdset, NULL, NULL, &tv) > 0);
  10525.         }
  10526.     }
  10527. }
  10528.  
  10529. int
  10530. fwdx_init_fd_set(fd_set *ibits)
  10531. {
  10532.     int x,set=0;
  10533.     debug(F100,"fwdx_init_fd_set()","",0);
  10534.  
  10535.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  10536.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  10537.         debug(F110,"fwdx_init_fd_set()","TELOPT_FORWARD_X not negotiated",0);
  10538.         return(0);
  10539.     }
  10540.  
  10541.     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1) {
  10542.         set++;
  10543.         FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket, ibits);
  10544.     }
  10545.     for (x = 0; x < MAXFWDX; x++) {
  10546.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  10547.             set++;
  10548.             FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd, ibits);
  10549.         }
  10550.     }
  10551.     return(set);
  10552. }
  10553.  
  10554. #ifdef NT
  10555. VOID
  10556. fwdx_thread( VOID * dummy )
  10557. {
  10558.     fd_set ifds;
  10559.     struct timeval tv;
  10560.     extern int priority;
  10561.  
  10562.     setint();
  10563.     SetThreadPrty(priority,isWin95() ? 3 : 11);
  10564.  
  10565.     while ( !sstelnet && TELOPT_U(TELOPT_FORWARD_X) ||
  10566.             sstelnet && TELOPT_ME(TELOPT_FORWARD_X))
  10567.     {
  10568.         FD_ZERO(&ifds);
  10569.         if (fwdx_init_fd_set(&ifds) > 0) {
  10570.             tv.tv_sec = 0;
  10571.             tv.tv_usec = 2500;
  10572.             if ( select(FD_SETSIZE, &ifds, NULL, NULL, &tv) > 0 )
  10573.                 fwdx_check_sockets(&ifds);
  10574.  
  10575.         } else {
  10576.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.thread_started = 0;
  10577.             ckThreadEnd(NULL);
  10578.         }
  10579.     }
  10580. }
  10581. #endif /* NT */
  10582. #endif /* CK_FORWARD_X */
  10583. #endif /* TNCODE */
  10584. #endif /* NETCONN */
  10585.