home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / cku200.tar / ckcnet.c < prev    next >
C/C++ Source or Header  |  2001-12-08  |  427KB  |  13,832 lines

  1. char *cknetv = "Network support, 8.0.255, 8 Dec 2001";
  2.  
  3. /*  C K C N E T  --  Network support  */
  4.  
  5. /*
  6.   Copyright (C) 1985, 2001,
  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) -- Primary maintainer/developer
  28.     since about 1996.
  29.   netopen() routine for TCP/IP originally by Ken Yap, Rochester University
  30.     (ken@cs.rochester.edu) (no longer at that address).
  31.   Missing pieces for Excelan sockets library from William Bader.
  32.   Telnet protocol by Frank da Cruz and Jeffrey Altman.
  33.   Rlogin protocol by Jeffrey Altman.
  34.   SSL support adapted by Jeffrey Altman from work done by
  35.     Tim Hudson <tjh@cryptosoft.com> +61 7 32781581
  36.   TLS support by Jeffrey Altman.
  37.   HTTP support by Jeffrey Altman.
  38.   TGV MultiNet code by Frank da Cruz.
  39.   MultiNet code adapted to WIN/TCP by Ray Hunter of TWG.
  40.   MultiNet code adapted to DEC TCP/IP by Lee Tibbert of DEC and Frank da Cruz.
  41.   TCP/IP support adapted to IBM TCP/IP 1.2.1,2.0 for OS/2 by Kai Uwe Rommel.
  42.   CMU-OpenVMS/IP modifications by Mike O'Malley, Digital (DEC).
  43.   X.25 support by Marcello Frutig, Catholic University,
  44.     Rio de Janeiro, Brazil (frutig@rnp.impa.br) with fixes from
  45.     Stefaan Eeckels, Eurokom, Luxembourg.
  46.     David Lane added support for Stratus X.25 1996.
  47.     Stephen Riehm added support for IBM AIX X.25 in April 1998.
  48.   Other contributions as indicated in the code.
  49. */
  50. #define CKCNET_C
  51. #include "ckcsym.h"
  52. #include "ckcdeb.h"
  53. #include "ckcker.h"
  54. #include "ckcasc.h"
  55. #ifdef I386IX                           /* Has to come before ckcnet.h in */
  56. #include <errno.h>                      /* this version, but after in others */
  57. #endif /* I386IX */
  58. #include "ckcnet.h"                     /* which includes ckctel.h */
  59. #ifdef CK_SSL
  60. #include "ck_ssl.h"
  61. #endif /* CK_SSL */
  62.  
  63. #ifdef CK_DNS_SRV
  64. #ifdef OS2
  65. #ifdef NT
  66. #include <wshelper.h>
  67. #else /* NT */
  68. /* !Error OS/2 does not support DNS Service Records. */
  69. #endif /* NT */
  70. #else /* OS2 */
  71. #include <arpa/inet.h>
  72. #include <arpa/nameser.h>
  73. #include <resolv.h>
  74. #ifndef PS2AIX10
  75. #ifndef BSD4
  76. #ifndef I386IX
  77. #ifndef RTAIX
  78. #include <netdb.h>
  79. #endif /* RTAIX */
  80. #endif /* I386IX */
  81. #endif /* BSD4 */
  82. #endif /* PS2AIX10 */
  83. #endif /* OS2 */
  84. #ifndef T_SRV
  85. #define T_SRV 33
  86. #endif /* T_SRV */
  87. #ifndef T_TXT
  88. #define T_TXT 16
  89. #endif /* T_TXT */
  90.  
  91. /* for old Unixes and friends ... */
  92. #ifndef MAXHOSTNAMELEN
  93. #define MAXHOSTNAMELEN 64
  94. #endif /* MAXHOSTNAMELEN */
  95.  
  96. #define MAX_DNS_NAMELEN (15*(MAXHOSTNAMELEN + 1)+1)
  97. #endif /* CK_DNS_SRV */
  98.  
  99. #ifdef NONET
  100. #ifdef TCPIPLIB
  101. #undef TCPIPLIB
  102. #endif /* TCPIPLIB */
  103. #endif /* NONET */
  104.  
  105. #ifndef NOMHHOST
  106. #ifdef datageneral
  107. #define NOMHHOST
  108. #else
  109. #ifdef HPUX5WINTCP
  110. #define NOMHHOST
  111. #endif /* HPUX5WINTCP */
  112. #endif /* datageneral */
  113. #endif /* NOMHHOST */
  114.  
  115. #ifdef INADDRX
  116.   struct in_addr inaddrx;
  117. #endif /* INADDRX */
  118.  
  119. int ttnet = NET_NONE;                   /* Network type */
  120. int ttnproto = NP_DEFAULT;              /* Network virtual terminal protocol */
  121.  
  122. /* 0 = don't lowercase username for Rlogin/Telnet protocol */
  123. /* nonzero = do lowercase it.  Add a SET command if necessary... */
  124. #ifdef VMS
  125. int ck_lcname = 1;
  126. #else
  127. int ck_lcname = 0;
  128. #endif /* VMS */
  129.  
  130. extern int                              /* External variables */
  131.   duplex, debses, seslog, sessft, wasclosed,
  132.   ttyfd, quiet, msgflg, what, nettype, ttmdm;
  133. #ifdef IKSD
  134. extern int inserver;
  135. #endif /* IKSD */
  136.  
  137. char myipaddr[20] = { '\0' };           /* Global copy of my IP address */
  138.  
  139. #ifdef NETCONN
  140. /* Don't need any of this if there is no network support. */
  141.  
  142. /*
  143.   NETLEBUF is (must be) defined for those platforms that call this
  144.   module to do network i/o (e.g. netinc(), nettchk(), etc) rather
  145.   than doing it themselves (ttinc(), ttchk(), etc).  In this case
  146.   the Telnet local-echo buffers and routines are defined and referenced
  147.   here, rather than in the ck?tio.c module.
  148. */
  149. #ifdef NETLEBUF
  150. #define LEBUFSIZ 4096
  151. int ttpush = -1, le_data = 0;           /* These are seen from outside */
  152. static CHAR le_buf[LEBUFSIZ];           /* These are used internally */
  153. static int le_start = 0, le_end = 0;
  154. int tt_push_inited = 0;
  155. #endif /* NETLEBUF */
  156.  
  157. #ifdef CK_SOCKS                         /* SOCKS Internet relay package */
  158. #ifdef CK_SOCKS5                        /* SOCKS 5 */
  159. #define accept  SOCKSaccept
  160. #define bind    SOCKSbind
  161. #define connect SOCKSconnect
  162. #define getsockname SOCKSgetsockname
  163. #define listen SOCKSlisten
  164. #else  /* Not SOCKS 5 */
  165. #define accept  Raccept
  166. #define bind    Rbind
  167. #define connect Rconnect
  168. #define getsockname Rgetsockname
  169. #define listen Rlisten
  170. #endif /* CK_SOCKS5 */
  171. #endif /* CK_SOCKS */
  172.  
  173. #ifdef DEC_TCPIP
  174. #include <time.h>
  175. #include <inet.h>
  176. #endif /* DEC_TCPIP */
  177.  
  178. /* Also see ckcnet.h -- hmmm, why don't we always include inet.h? */
  179.  
  180. #ifdef HPUX
  181. #ifndef HPUX7                           /* HPUX 7.00 doesn't have it */
  182. #include <arpa/inet.h>                  /* For inet_ntoa() prototype */
  183. #endif /* HPUX7 */
  184. #endif /* HPUX */
  185.  
  186. #ifdef CMU_TCPIP
  187. #include <time.h>
  188. #endif /* CMU_TCPIP */
  189.  
  190. #ifndef NODCLTIMEVAL
  191. #ifdef DCLTIMEVAL                       /* UnixWare 7 */
  192. struct timeval {                        /* And define these ourselves. */
  193.     long tv_sec;                        /* (see comments in ckutio.c) */
  194.     long tv_usec;
  195. };
  196. struct timezone {
  197.     int tz_minuteswest;
  198.     int tz_dsttime;
  199. };
  200. #endif /* DCLTIMEVAL */
  201. #endif /* NODCLTIMEVAL */
  202.  
  203. #ifdef WINTCP
  204.  
  205. #include <setjmp.h>
  206. #include <signal.h>
  207. #include <sys/time.h>
  208. /*
  209.   The WIN/TCP code path is the same as that for MultiNet.
  210.   Only the routine names have changed ...
  211. */
  212. #define socket_read     netread
  213. #define socket_ioctl    ioctl
  214. #define socket_write    netwrite
  215. #define socket_close    netclose
  216.  
  217. #ifdef OLD_TWG                         /* some routines have evolved */
  218.         extern int vmserrno, uerrno;
  219. #define socket_errno    uerrno
  220. #define socket_perror   perror         /* which uses errno, not uerrno! */
  221. #else
  222. #define socket_errno    errno
  223. #define socket_perror   win$perror
  224. #endif /* OLD_TWG */
  225.  
  226. #else /* Not WINTCP */
  227.  
  228. #ifdef OSF13
  229. #ifdef CK_ANSIC
  230. #ifdef _NO_PROTO
  231. #undef _NO_PROTO
  232. #endif /* _NO_PROTO */
  233. #endif /* CK_ANSIC */
  234. #endif /* OSF13 */
  235.  
  236. #ifndef I386IX
  237. #include <errno.h>                      /* Already included above */
  238. #endif /* I386IX */
  239.  
  240. #include <signal.h>                     /* Everybody needs this */
  241.  
  242. #ifdef ZILOG                            /* Zilog has different name for this */
  243. #include <setret.h>
  244. #else
  245. #include <setjmp.h>
  246. #endif /* ZILOG */
  247.  
  248. #endif /* WINTCP */
  249.  
  250. #ifdef datageneral                      /* Data General AOS/VS */
  251. #include <:usr:include:vs_tcp_errno.h>
  252. #include <:usr:include:sys:vs_tcp_types.h>
  253. #ifdef SELECT
  254. /*
  255.   NOTE: This can be compiled and linked OK with SELECT defined
  256.   but it doesn't work at all.  Anybody who cares and knows how
  257.   to fix it, feel free.
  258. */
  259. #include <:usr:include:sys:vs_tcp_time.h>
  260. #endif /* SELECT */
  261. #include <:usr:include:sys:socket.h>
  262. #include <:usr:include:netinet:in.h>
  263. #include <:usr:include:netdb.h>
  264. #endif /* datageneral */
  265.  
  266. #ifndef socket_errno
  267. #define socket_errno errno
  268. #endif /* socket_errno */
  269.  
  270. #ifdef TNCODE
  271. extern int tn_deb;
  272. #endif /* TNCODE */
  273.  
  274. int tcp_rdns =                          /* Reverse DNS lookup */
  275. #ifdef DEC_TCPIP_OLD
  276.     SET_OFF                             /* Doesn't seem to work in UCX */
  277. #else
  278.      SET_AUTO
  279. #endif /* DEC_TCPIP */
  280.       ;
  281. #ifdef CK_DNS_SRV
  282. int tcp_dns_srv = SET_OFF;
  283. #endif /* CK_DNS_SRV */
  284.  
  285. _PROTOTYP( char * cmcvtdate, (char *, int) );
  286.  
  287. #ifdef RLOGCODE
  288. #ifdef TCPIPLIB
  289. _PROTOTYP( static VOID rlog_oob, (CHAR *, int) );
  290. #else
  291. _PROTOTYP( static SIGTYP rlogoobh, ( int ) );
  292. #endif /* TCPIPLIB */
  293. _PROTOTYP( static int rlog_ini, (CHAR *, int,
  294.                                  struct sockaddr_in *,
  295.                                  struct sockaddr_in *) );
  296. int rlog_mode = RL_COOKED;
  297. int rlog_stopped = 0;
  298. #endif /* RLOGCODE */
  299.  
  300. #ifndef NOICP
  301. extern int doconx;                      /* CONNECT-class command active */
  302. #endif /* NOICP */
  303.  
  304. #ifdef IBMX25
  305. /* This variable should probably be generalised for true client/server
  306.  * support - ie: the fd of the listening server, accepted calls should
  307.  * be forked or at least handled via a second fd (for IBM's X.25 -
  308.  * ttyfd always holds the active fd - ie the server becomes inactive
  309.  * as long as a client is connected, and becomes active again when the
  310.  * connection is closed)
  311.  */
  312. int x25serverfd = 0;            /* extern in ckcnet.h */
  313. int x25seqno = 0;               /* Connection sequence number */
  314. int x25lastmsg = -1;            /* A cheapskate's state table */
  315.  
  316. #define X25_CLOSED      0       /* Default state: no connection, no STREAM */
  317. #define X25_SETUP       1       /* X.25 has been set up (no connection) */
  318. #define X25_CONNECTED   2       /* X.25 connection has been established */
  319. int x25_state = X25_CLOSED;     /* Default state */
  320. #endif /* IBMX25 */
  321.  
  322. #ifndef DEBUG
  323. #define deblog 0
  324. #endif /* DEBUG */
  325.  
  326. #ifdef CK_NAWS                          /* Negotiate About Window Size */
  327. #ifdef RLOGCODE
  328. _PROTOTYP( int rlog_naws, (void) );
  329. #endif /* RLOGCODE */
  330. #endif /* CK_NAWS */
  331.  
  332. #ifdef OS2                              /* For terminal type name string */
  333. #include "ckuusr.h"
  334. #ifndef NT
  335. #include <os2.h>
  336. #undef COMMENT
  337. #endif /* NT */
  338. #include "ckocon.h"
  339. extern int tt_type, max_tt;
  340. extern struct tt_info_rec tt_info[];
  341. extern char ttname[];
  342. #else
  343. #ifdef CK_AUTHENTICATION
  344. #include "ckuusr.h"
  345. #endif /* CK_AUTHENTICATION */
  346. #endif /* OS2 */
  347.  
  348. #ifdef NT
  349. extern int winsock_version;
  350. #endif /* NT */
  351.  
  352. #ifdef CK_AUTHENTICATION
  353. #include "ckuath.h"
  354. #endif /* CK_AUTHENTICATION */
  355.  
  356. #include "ckcsig.h"
  357.  
  358. #ifndef OS2                             /* For timeout longjumps */
  359. static ckjmpbuf njbuf;
  360. #endif /* OS2 */
  361.  
  362. #define NAMECPYL 1024                   /* Local copy of hostname */
  363. char namecopy[NAMECPYL];                /* Referenced by ckctel.c */
  364. #ifndef NOHTTP
  365. char http_host_port[NAMECPYL];          /* orig host/port necessary for http */
  366. char http_ip[20] = { '\0' };        /* ip address of host */
  367. char http_port = 0;
  368. int  http_ssl = 0;
  369. int  httpfd = -1;                       /* socket for http connections */
  370. int  http_code = 0;
  371. #define HTTPBUFLEN  1024
  372. char http_reply_str[HTTPBUFLEN] = "";
  373. #endif /* NOHTTP */
  374.  
  375. char ipaddr[20] = { '\0' };             /* Global copy of IP address */
  376. unsigned long myxipaddr = 0L;           /* Ditto as a number */
  377. #endif /* NETCONN */
  378.  
  379. char *tcp_address = NULL;               /* Preferred IP Address */
  380. extern char uidbuf[];                   /* User ID buffer */
  381. extern char pwbuf[];                    /* Password buffer */
  382.  
  383. #ifndef NOHTTP
  384. char * tcp_http_proxy = NULL;           /* Name[:port] of http proxy server */
  385. int    tcp_http_proxy_errno = 0;
  386. char * tcp_http_proxy_user = NULL;
  387. char * tcp_http_proxy_pwd  = NULL;
  388. #define HTTPCPYL 1024
  389. static char proxycopy[HTTPCPYL];
  390. #endif /* NOHTTP */
  391.  
  392. #ifdef OS2
  393. extern int tt_rows[], tt_cols[];
  394. extern int tt_status[VNUM];
  395. #else /* OS2 */
  396. extern int tt_rows, tt_cols;            /* Everybody has this */
  397. #endif /* OS2 */
  398.  
  399. extern int cmd_cols, cmd_rows;
  400.  
  401. #ifdef STREAMING                        /* Use blocking writes for streaming */
  402. extern int streaming;
  403. #endif /* STREAMING */
  404.  
  405. #ifdef NT
  406. extern int WSASafeToCancel;
  407. int win95selectbug = 0;                 /* For TCP/IP stacks whose select() */
  408. /* always fails on write requests such as Cisco and Quarterdeck */
  409. #define stricmp _stricmp
  410. #endif /* NT */
  411.  
  412. #ifndef NOTCPOPTS
  413.  
  414. /* Skip all this if NOTCPOPTS specified. */
  415.  
  416. #ifdef SOL_SOCKET
  417.  
  418. #ifdef TCP_NODELAY
  419. int tcp_nodelay = 0;                    /* Nagle algorithm TCP_NODELAY */
  420. #endif /* TCP_NODELAY */
  421.  
  422. #ifdef SO_DONTROUTE
  423. int tcp_dontroute = 0;
  424. #endif /* SO_DONTROUTE */
  425.  
  426. #ifdef SO_LINGER
  427. int tcp_linger  = 0;                    /* SO_LINGER */
  428. int tcp_linger_tmo = 0;                 /* SO_LINGER timeout */
  429. #endif /* SO_LINGER */
  430.  
  431. #ifdef HPUX                             /* But the data structures */
  432. #ifndef HPUX8                           /* needed for linger are not */
  433. #ifndef HPUX9                           /* defined in HP-UX versions */
  434. #ifndef HPUX10                          /* prior to 8.00. */
  435. #ifdef SO_LINGER
  436. #undef SO_LINGER
  437. #endif /* SO_LINGER */
  438. #endif /* HPUX10 */
  439. #endif /* HPUX9 */
  440. #endif /* HPUX8 */
  441. #endif /* HPUX */
  442.  
  443. #ifndef SO_OOBINLINE                    /* Hopefully only HP-UX 7.0 */
  444. #define SO_OOBINLINE 0x0100
  445. #endif /* SO_OOBINLINE */
  446.  
  447. #ifndef TCPSNDBUFSIZ
  448. #ifdef VMS
  449. #ifdef __alpha
  450. #define TCPSNDBUFSIZ 16384
  451. #endif /* __alpha */
  452. #endif /* VMS */
  453. #endif /* TCPSNDBUFSIZ */
  454.  
  455. #ifndef TCPSNDBUFSIZ
  456. #define TCPSNDBUFSIZ -1
  457. #endif /* TCPSNDBUFSIZ */
  458.  
  459. #ifdef SO_SNDBUF
  460. int tcp_sendbuf = TCPSNDBUFSIZ;
  461. #endif /* SO_SNDBUF */
  462.  
  463. #ifdef SO_RCVBUF
  464. int tcp_recvbuf = -1;
  465. #endif /* SO_RCVBUF */
  466.  
  467. #ifdef SO_KEEPALIVE
  468. int tcp_keepalive = 1;
  469. #endif /* SO_KEEPALIVE */
  470.  
  471. #endif /* SOL_SOCKET */
  472. #endif /* NOTCPOPTS */
  473.  
  474. #ifndef NETCONN
  475. /*
  476.   Network support not defined.
  477.   Dummy functions here in case #ifdef's forgotten elsewhere.
  478. */
  479. int                                     /* Open network connection */
  480. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  481.     return(-1);
  482. }
  483. int                                     /* Close network connection */
  484. netclos() {
  485.     return(-1);
  486. }
  487. int                                     /* Check network input buffer */
  488. nettchk() {
  489.     return(-1);
  490. }
  491. int                                     /* Flush network input buffer */
  492. netflui() {
  493.     return(-1);
  494. }
  495. int                                     /* Send network BREAK */
  496. netbreak() {
  497.     return(-1);
  498. }
  499. int                                     /* Input character from network */
  500. netinc(timo) int timo; {
  501.     return(-1);
  502. }
  503. int                                     /* Output character to network */
  504. #ifdef CK_ANSIC
  505. nettoc(CHAR c)
  506. #else
  507. nettoc(c) CHAR c;
  508. #endif /* CK_ANSIC */
  509. /* nettoc */ {
  510.     return(-1);
  511. }
  512. int
  513. nettol(s,n) CHAR *s; int n; {
  514.     return(-1);
  515. }
  516.  
  517. #else /* NETCONN is defined (much of this module...) */
  518.  
  519. #ifdef NETLEBUF
  520. VOID
  521. le_init() {                             /* LocalEchoInit() */
  522.     int i;
  523.     for (i = 0; i < LEBUFSIZ; i++)
  524.       le_buf[i] = '\0';
  525.     le_start = 0;
  526.     le_end = 0;
  527.     le_data = 0;
  528.     tt_push_inited = 1;
  529. }
  530.  
  531. VOID
  532. le_clean() {                            /* LocalEchoCleanup() */
  533.     le_init();
  534.     return;
  535. }
  536.  
  537. int
  538. le_inbuf() {
  539.     int rc = 0;
  540.     if (le_start != le_end) {
  541.         rc = (le_end -
  542.               le_start +
  543.               LEBUFSIZ) % LEBUFSIZ;
  544.     }
  545.     return(rc);
  546. }
  547.  
  548. int
  549. #ifdef CK_ANSIC
  550. le_putchar(CHAR ch)
  551. #else
  552. le_putchar(ch) CHAR ch;
  553. #endif /* CK_ANSIC */
  554. /* le_putchar */ {
  555.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  556.         debug(F110,"le_putchar","buffer is full",0);
  557.         return(-1);
  558.     }
  559.     le_buf[le_end++] = ch;
  560.     if (le_end == LEBUFSIZ)
  561.       le_end = 0;
  562.     le_data = 1;
  563.     return(0);
  564. }
  565.  
  566. int
  567. #ifdef CK_ANSIC
  568. le_puts(CHAR * s, int n)
  569. #else
  570. le_puts(s,n) CHAR * s; int n;
  571. #endif /* CK_ANSIC */
  572. /* le_puts */ {
  573.     int rc = 0;
  574.     int i = 0;
  575.     CHAR * p = (CHAR *)"le_puts";
  576.     hexdump(p,s,n);
  577.     for (i = 0; i < n; i++)
  578.       rc = le_putchar((char)s[i]);
  579.     debug(F101,"le_puts","",rc);
  580.     return(rc);
  581. }
  582.  
  583. int
  584. #ifdef CK_ANSIC
  585. le_putstr(CHAR * s)
  586. #else
  587. le_putstr(s) CHAR * s;
  588. #endif /* CK_ANSIC */
  589. /* le_puts */ {
  590.     CHAR * p;
  591.     int rc = 0;
  592.     p = (CHAR *)"le_putstr";
  593.     hexdump(p,s,(int)strlen((char *)s));
  594.     for (p = s; *p && !rc; p++)
  595.       rc = le_putchar(*p);
  596.     return(rc);
  597. }
  598.  
  599. int
  600. #ifdef CK_ANSIC
  601. le_getchar(CHAR * pch)
  602. #else /* CK_ANSIC */
  603. le_getchar(pch) CHAR * pch;
  604. #endif /* CK_ANSIC */
  605. /* le_gatchar */ {
  606.     int rc = 0;
  607.     if (le_start != le_end) {
  608.         *pch = le_buf[le_start];
  609.         le_buf[le_start] = 0;
  610.         le_start++;
  611.  
  612.         if (le_start == LEBUFSIZ)
  613.           le_start = 0;
  614.  
  615.         if (le_start == le_end) {
  616.             le_data = 0;
  617.         }
  618.         rc++;
  619.     } else {
  620.         *pch = 0;
  621.     }
  622.     return(rc);
  623. }
  624. #endif /* NETLEBUF */
  625.  
  626. #ifdef VMS
  627. /*
  628.   In edit 190, we moved tn_ini() to be called from within netopen().
  629.   But tn_ini() calls ttol(), and ttol() checks to see if it's a net
  630.   connection, but the flag for that isn't set until after netopen()
  631.   is finished.  Since, in this module, we are always doing network
  632.   output anyway, we just call nettol() directly, instead of going thru
  633.   ttol().  Only needed for VMS, since UNIX, AOS/VS, and VOS can handle
  634.   net connections just like regular connections in ttol(), and OS/2
  635.   has a special routine for this.
  636. */
  637. #define ttol nettol
  638. #endif /* VMS */
  639.  
  640. int tcpsrfd = -1;
  641.  
  642. #ifdef CK_KERBEROS
  643.  
  644. char * krb5_d_principal = NULL;         /* Default principal */
  645. char * krb5_d_instance = NULL;          /* Default instance */
  646. char * krb5_d_realm = NULL;             /* Default realm */
  647. char * krb5_d_cc = NULL;                /* Default credentials cache */
  648. char * krb5_d_srv   = NULL;             /* Default Service */
  649. int    krb5_d_lifetime = 600;           /* Default lifetime (10 hours) */
  650. int    krb5_d_forwardable = 0;          /* creds not forwardable */
  651. int    krb5_d_proxiable = 0;            /* creds not proxiable */
  652. int    krb5_d_renewable = 0;            /* creds not renewable (0 min) */
  653. int    krb5_autoget = 1;                /* Autoget TGTs */
  654. int    krb5_autodel = 0;                /* Auto delete TGTs */
  655. int    krb5_d_getk4 = 0;                /* K5 Kinit gets K4 TGTs */
  656. int    krb5_checkaddrs = 1;             /* Check TGT Addrs */
  657. int    krb5_d_no_addresses = 0;         /* Do not include IP Addresses */
  658. char * krb5_d_addrs[KRB5_NUM_OF_ADDRS+1]={NULL,NULL}; /* Addrs to include */
  659. int    krb5_errno = 0;                  /* Last K5 errno */
  660. char * krb5_errmsg = NULL;              /* Last K5 errmsg */
  661. char * k5_keytab = NULL;
  662.  
  663. char * krb4_d_principal = NULL;         /* Default principal */
  664. char * krb4_d_realm = NULL;             /* Default realm */
  665. char * krb4_d_srv   = NULL;             /* Default Service */
  666. int    krb4_d_lifetime = 600;           /* Default lifetime (10 hours) */
  667. int    krb4_d_preauth = 1;              /* Use preauth requests */
  668. char * krb4_d_instance = NULL;          /* Default instance */
  669. int    krb4_autoget = 1;                /* Autoget TGTs */
  670. int    krb4_autodel = 0;                /* Auto delete TGTs */
  671. int    krb4_checkaddrs = 1;             /* Check TGT Addrs */
  672. char * k4_keytab = NULL;
  673.  
  674. int    krb4_errno = 0;                  /* Last K4 errno */
  675. char * krb4_errmsg = NULL;              /* Last K4 errmsg */
  676.  
  677. struct krb_op_data krb_op = {           /* Operational data structure */
  678.     0, NULL                             /* (version, cachefile) */
  679. };
  680.  
  681. struct krb4_init_data krb4_init = {     /* Kerberos 4 INIT data structure */
  682.     0, NULL, NULL, NULL, NULL
  683. };
  684.  
  685. struct krb5_init_data krb5_init = {     /* Kerberos 5 INIT data structure */
  686.     0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0,
  687.     { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  688.       NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
  689.     0
  690. };
  691.  
  692. struct krb5_list_cred_data krb5_lc = {  /* List Credentials data structure */
  693.     0, 0, 0
  694. };
  695.  
  696. int krb_action = -1;                    /* Kerberos action to perform */
  697.  
  698. #ifndef CK_AUTHENTICATION
  699. char *
  700. ck_krb4_getrealm() {
  701.     return("");
  702. }
  703. char *
  704. ck_krb5_getrealm(cc) char * cc; {
  705.     return("");
  706. }
  707. char *
  708. ck_krb4_getprincipal() {
  709.     return("");
  710. }
  711. char *
  712. ck_krb5_getprincipal(cc) char * cc; {
  713.     return("");
  714. }
  715. #endif /* CK_AUTHENTICATION */
  716.  
  717. /*  I N I _ K E R B  --  Initialize Kerberos data  */
  718.  
  719. VOID
  720. ini_kerb() {
  721.     int i;
  722.  
  723.     krb_action = -1;                    /* No action specified */
  724.  
  725.     krb_op.version = 0;                 /* Kerberos version (none) */
  726.     krb_op.cache = NULL;                /* Cache file (none) */
  727.  
  728. /* Kerberos 5 */
  729.  
  730.     krb5_init.forwardable = krb5_d_forwardable; /* Init switch values... */
  731.     krb5_init.proxiable   = krb5_d_proxiable;
  732.     krb5_init.lifetime    = krb5_d_lifetime;
  733.     krb5_init.renew       = 0;
  734.     krb5_init.renewable   = krb5_d_renewable;
  735.     krb5_init.validate    = 0;
  736.     krb5_init.no_addresses = krb5_d_no_addresses;
  737.     if (krb5_init.postdate) {
  738.         free(krb5_init.postdate);
  739.         krb5_init.postdate = NULL;
  740.     }
  741.     if (krb5_init.service) {
  742.         free(krb5_init.service);
  743.         krb5_init.service = NULL;
  744.     }
  745.     if (!krb5_d_cc || !krb5_d_cc[0]) {  /* Set default cache */
  746.         char * p;
  747.         p = ck_krb5_get_cc_name();
  748.         makestr(&krb5_d_cc,(p && p[0]) ? p : NULL);
  749.     }
  750.     if (!krb5_d_realm || !krb5_d_realm[0]) { /* Set default realm */
  751.         char * p;
  752.         p = ck_krb5_getrealm(krb5_d_cc);
  753.         makestr(&krb5_d_realm,(p && p[0]) ? p : NULL);
  754.     }
  755.     makestr(&krb5_init.instance,krb5_d_instance);
  756.     makestr(&krb5_init.realm,krb5_d_realm); /* Set realm from default */
  757.     if (krb5_init.password) {
  758.         memset(krb5_init.password,0xFF,strlen(krb5_init.password));
  759.         free(krb5_init.password);
  760.         krb5_init.password = NULL;
  761.     }
  762.     if (!krb5_d_principal) {            /* Default principal */
  763.         /* a Null principal indicates the user should be prompted */
  764.         char * p = ck_krb5_getprincipal(krb5_d_cc);
  765.         if (!p || !(*p))
  766.           p = (char *)uidbuf;           /* Principal = user */
  767.         makestr(&krb5_d_principal,(p && p[0]) ? p : NULL);
  768.     }
  769.     makestr(&krb5_init.principal,krb5_d_principal);
  770.     for (i = 0; i <= KRB5_NUM_OF_ADDRS; i++) {
  771.         if (krb5_init.addrs[i])
  772.           free(krb5_init.addrs[i]);
  773.         krb5_init.addrs[i] = NULL;
  774.     }
  775.     for (i = 0; i <= KRB5_NUM_OF_ADDRS && krb5_d_addrs[i]; i++) {
  776.         makestr(&krb5_init.addrs[i],krb5_d_addrs[i]);
  777.     }
  778.  
  779.     /* Kerberos 4 */
  780.  
  781.     krb4_init.lifetime = krb4_d_lifetime;
  782.     krb4_init.preauth  = krb4_d_preauth;
  783.     makestr(&krb4_init.instance,krb4_d_instance);
  784.     if (!krb4_d_realm || !krb4_d_realm[0]) {/* Set default realm */
  785.         char * p;
  786.         p = ck_krb4_getrealm();
  787.         makestr(&krb4_d_realm,(p && p[0]) ? p : NULL);
  788.     }
  789.     makestr(&krb4_init.realm,krb4_d_realm);
  790.     if (krb4_init.password) {
  791.         memset(krb4_init.password,0xFF,strlen(krb4_init.password));
  792.         free(krb4_init.password);
  793.         krb4_init.password = NULL;
  794.     }
  795.     if (!krb4_d_principal) {            /* Default principal */
  796.         /* a Null principal indicates the user should be prompted */
  797.         char * p = ck_krb4_getprincipal();
  798.         if (!p || !(*p))
  799.           p = (char *)uidbuf;           /* Principal = user */
  800.         makestr(&(krb4_d_principal),(p && p[0]) ? p : NULL);
  801.     }
  802.     makestr(&(krb4_init.principal),krb4_d_principal);
  803. }
  804.  
  805. /*  D O A U T H  --  AUTHENTICATE action routine  */
  806.  
  807. int
  808. doauth(cx) int cx; {                    /* AUTHENTICATE action routine */
  809.     int rc = 0;                         /* Return code */
  810.  
  811. #ifdef CK_AUTHENTICATION
  812. #ifdef OS2
  813.     if (!ck_security_loaddll())        /* Load various DLLs */
  814.       return(rc);
  815. #endif /* OS2 */
  816.     if (krb_op.version == 4) {          /* Version = 4 */
  817. #ifdef COMMENT
  818.         sho_auth(AUTHTYPE_KERBEROS_V4);
  819. #endif /* COMMENT */
  820.         if (!ck_krb4_is_installed()) {
  821.             printf("?Kerberos 4 is not installed\n");
  822.             return(0);
  823.         }
  824.         switch (krb_action) {           /* Perform V4 functions */
  825.           case KRB_A_IN:                /* INIT */
  826.             rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
  827.             break;
  828.           case KRB_A_DE:                /* DESTROY */
  829.             rc |= !(ck_krb4_destroy(&krb_op) < 0);
  830.             break;
  831.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  832.             rc |= !(ck_krb4_list_creds(&krb_op) < 0);
  833.             break;
  834.         }
  835.     }
  836.     if (krb_op.version == 5) {          /* V5 functions */
  837. #ifdef COMMENT
  838.         sho_auth(AUTHTYPE_KERBEROS_V5);
  839. #endif /* COMMENT */
  840.         if (!ck_krb5_is_installed()) {
  841.             printf("?Kerberos 5 is not installed\n");
  842.             return(0);
  843.         }
  844.         switch (krb_action) {
  845.           case KRB_A_IN:                /* INIT */
  846.             rc |= !(ck_krb5_initTGT(&krb_op,&krb5_init,
  847.                                      krb5_init.getk4 ? &krb4_init : 0) < 0);
  848.             break;
  849.           case KRB_A_DE:                /* DESTROY */
  850.             rc |= !(ck_krb5_destroy(&krb_op) < 0);
  851.             break;
  852.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  853.             if (krb_op.version == 0)
  854.               printf("\n");
  855.             rc |= !(ck_krb5_list_creds(&krb_op,&krb5_lc) < 0);
  856.             break;
  857.         }
  858.     }
  859. #else
  860. #ifndef NOICP
  861. #ifndef NOSHOW
  862.     rc = sho_auth(0);                   /* Show all */
  863. #endif /* NOSHOW */
  864. #endif /* NOICP */
  865. #endif /* CK_AUTHENTICATION */
  866.     return(rc);
  867. }
  868. #endif /* CK_KERBEROS */
  869.  
  870. #ifdef TCPSOCKET
  871. #ifndef OS2
  872. #ifndef NOLISTEN                        /* For incoming connections */
  873.  
  874. #ifndef INADDR_ANY
  875. #define INADDR_ANY 0
  876. #endif /* INADDR_ANY */
  877.  
  878. _PROTOTYP( int ttbufr, ( VOID ) );
  879. _PROTOTYP( int tcpsrv_open, (char *, int *, int, int ) );
  880.  
  881. static unsigned short tcpsrv_port = 0;
  882.  
  883. #endif /* NOLISTEN */
  884. #endif /* OS2 */
  885.  
  886. static char svcbuf[80];                 /* TCP service string */
  887. static int svcnum = 0;                  /* TCP port number */
  888.  
  889. #endif /* TCPSOCKET */
  890.  
  891. /*
  892.   TCPIPLIB means use separate socket calls for i/o, while on UNIX the
  893.   normal file system calls are used for TCP/IP sockets too.
  894.   Means "DEC_TCPIP or MULTINET or WINTCP or OS2 or BEBOX" (see ckcnet.h),
  895. */
  896.  
  897. #ifdef TCPIPLIB
  898.  
  899. /* For buffered network reads... */
  900. /*
  901.   If the buffering code is written right, it shouldn't matter
  902.   how long this buffer is.
  903. */
  904. #ifdef OS2
  905. #ifdef NT
  906. #define TTIBUFL 64240                   /* 44 * 1460 (MSS) */
  907. #else
  908. #define TTIBUFL 32120                   /* 22 * 1460 (MSS) */
  909. #endif /* NT */
  910. #else /* OS2 */
  911. #define TTIBUFL 8191                    /* Let's use 8K. */
  912. #endif /* OS2 */
  913.  
  914. CHAR ttibuf[TTIBUFL+1];
  915.  
  916. /*
  917.   select() is used in preference to alarm()/signal(), but different systems
  918.   use different forms of select()...
  919. */
  920. #ifndef NOSELECT         /* Option to override BSDSELECT */
  921. #ifdef BELLV10
  922. /*
  923.   Note: Although BELLV10 does have TCP/IP support, and does use the unique
  924.   form of select() that is evident in this module (and in ckutio.c), it does
  925.   not have a sockets library and so we can't build Kermit TCP/IP support for
  926.   it.  For this, somebody would have to write TCP/IP streams code.
  927. */
  928. #define BELLSELECT
  929. #ifndef FD_SETSIZE
  930. #define FD_SETSIZE 128
  931. #endif /* FD_SETSIZE */
  932. #else
  933. #ifdef WINTCP                           /* VMS with Wollongong WIN/TCP */
  934. #ifndef OLD_TWG                         /* TWG 3.2 has only select(read) */
  935. #define BSDSELECT
  936. #endif /* OLD_TWG */
  937. #else
  938. #ifdef CMU_TCPIP                        /* LIBCMU can do select */
  939. #define BSDSELECT
  940. #else
  941. #ifdef DEC_TCPIP
  942. #define BSDSELECT
  943. #else
  944. #ifdef OS2                              /* OS/2 with TCP/IP */
  945. #ifdef NT
  946. #define BSDSELECT
  947. #else /* NT */
  948. #define IBMSELECT
  949. #endif /* NT */
  950. #endif /* OS2 */
  951. #endif /* DEC_TCPIP */
  952. #endif /* CMU_TCPIP */
  953. #endif /* WINTCP */
  954. #endif /* BELLV10 */
  955. #endif /* NOSELECT */
  956. /*
  957.   Others (TGV, TCPware, ...) use alarm()/signal().  The BSDSELECT case does not
  958.   compile at all; the IBMSELECT case compiles and links but crashes at runtime.
  959.   NOTE: If any of these can be converted to select(), they should be for two
  960.   reasons: (1) It's a lot faster; (2) certain sockets libraries do not like
  961.   their socket_read() calls to be interrupted; subsequent socket_read()'s tend
  962.   to fail with EBUSY.  This happened in the UCX case before it was converted
  963.   to use select().
  964. */
  965. #ifndef OS2
  966. #ifndef VMS
  967. static                                  /* These are used in CKVTIO.C */
  968. #endif /* VMS */                        /* And in CKONET.C            */
  969. #endif /* OS2 */
  970. int
  971.   ttibp = 0,
  972.   ttibn = 0;
  973. /*
  974.   Read bytes from network into internal buffer ttibuf[].
  975.   To be called when input buffer is empty, i.e. when ttibn == 0.
  976.  
  977.   Other network reading routines, like ttinc, ttinl, ttxin, should check the
  978.   internal buffer first, and call this routine for a refill if necessary.
  979.  
  980.   Returns -1 on error, 0 if nothing happens.  When data is read successfully,
  981.   returns number of bytes read, and sets global ttibn to that number and
  982.   ttibp (the buffer pointer) to zero.
  983. */
  984. _PROTOTYP( int ttbufr, ( VOID ) );
  985. int
  986. ttbufr() {                              /* TT Buffer Read */
  987.     int count;
  988.  
  989.     if (ttnet != NET_TCPB)              /* First make sure current net is */
  990.       return(-1);                       /* TCP/IP; if not, do nothing. */
  991.  
  992. #ifdef OS2
  993.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  994. #endif /* OS2 */
  995.  
  996.     if (ttibn > 0) {                    /* Our internal buffer is not empty, */
  997. #ifdef OS2
  998.         ReleaseTCPIPMutex();
  999. #endif /* OS2 */
  1000.         return(ttibn);                  /* so keep using it. */
  1001.     }
  1002.  
  1003.     if (ttyfd == -1) {                  /* No connection, error */
  1004. #ifdef OS2
  1005.         ReleaseTCPIPMutex();
  1006. #endif /* OS2 */
  1007.         return(-2);
  1008.     }
  1009.  
  1010.     ttibp = 0;                          /* Else reset pointer to beginning */
  1011.  
  1012. #ifdef WINTCP
  1013.     count = 512;                        /* This works for WIN/TCP */
  1014. #else
  1015. #ifdef DEC_TCPIP
  1016.     count = 512;                        /* UCX */
  1017. #else
  1018. #ifdef OS2
  1019.     count = TTIBUFL;
  1020. #else                                   /* Multinet, etc. */
  1021.     count = ttchk();                    /* Check network input buffer, */
  1022.     if (ttibn > 0) {                    /* which can put a char there! */
  1023.         debug(F111,"ttbufr","ttchk() returns",count);
  1024. #ifdef OS2
  1025.         ReleaseTCPIPMutex();
  1026. #endif /* OS2 */
  1027.         return(ttibn);
  1028.     }
  1029.     if (count < 0) {                     /* Read error - connection closed */
  1030. #ifdef OS2
  1031.         ReleaseTCPIPMutex();
  1032. #endif /* OS2 */
  1033.         return(-2);
  1034.     }
  1035.     else if (count > TTIBUFL)           /* Too many to read */
  1036.       count = TTIBUFL;
  1037.     else if (count == 0)                /* None, so force blocking read */
  1038.       count = 1;
  1039. #endif /* OS2 */
  1040. #endif /* DEC_TCPIP */
  1041. #endif /* WINTCP */
  1042.     debug(F101,"ttbufr count 1","",count);
  1043.  
  1044. #ifdef CK_SSL
  1045.     if (ssl_active_flag || tls_active_flag) {
  1046.         int error;
  1047.         if (ssl_active_flag)
  1048.           count = SSL_read(ssl_con, ttibuf, count);
  1049.         else
  1050.           count = SSL_read(tls_con, ttibuf, count);
  1051.         error = SSL_get_error(ssl_active_flag?ssl_con:tls_con,count);
  1052.         switch (error) {
  1053.           case SSL_ERROR_NONE:
  1054.             debug(F111,"ttbufr SSL_ERROR_NONE","count",count);
  1055.             if (count > 0) {
  1056.                 ttibp = 0;              /* Reset buffer pointer. */
  1057.                 ttibn = count;
  1058. #ifdef OS2
  1059.                 ReleaseTCPIPMutex();
  1060. #endif /* OS2 */
  1061.                 return(ttibn);          /* Return buffer count. */
  1062.             } else if (count < 0) {
  1063. #ifdef OS2
  1064.                 ReleaseTCPIPMutex();
  1065. #endif /* OS2 */
  1066.                 return(-1);
  1067.             } else {
  1068.                 netclos();
  1069. #ifdef OS2
  1070.                 ReleaseTCPIPMutex();
  1071. #endif /* OS2 */
  1072.                 return(-2);
  1073.             }
  1074.           case SSL_ERROR_WANT_WRITE:
  1075.             debug(F100,"ttbufr SSL_ERROR_WANT_WRITE","",0);
  1076. #ifdef OS2
  1077.               ReleaseTCPIPMutex();
  1078. #endif /* OS2 */
  1079.             return(-1);
  1080.           case SSL_ERROR_WANT_READ:
  1081.             debug(F100,"ttbufr SSL_ERROR_WANT_READ","",0);
  1082. #ifdef OS2
  1083.               ReleaseTCPIPMutex();
  1084. #endif /* OS2 */
  1085.             return(-1);
  1086.           case SSL_ERROR_SYSCALL:
  1087.               if ( count == 0 ) { /* EOF */
  1088.                   netclos();
  1089. #ifdef OS2
  1090.                   ReleaseTCPIPMutex();
  1091. #endif /* OS2 */
  1092.                   return(-2);
  1093.               } else {
  1094. #ifdef NT
  1095.                   int gle = GetLastError();
  1096.                   debug(F111,"ttbufr SSL_ERROR_SYSCALL",
  1097.                          "GetLastError()",gle);
  1098. #endif /* NT */
  1099. #ifdef OS2
  1100.                   ReleaseTCPIPMutex();
  1101. #endif /* OS2 */
  1102.                   return(-1);
  1103.               }
  1104.           case SSL_ERROR_WANT_X509_LOOKUP:
  1105.             debug(F100,"ttbufr SSL_ERROR_WANT_X509_LOOKUP","",0);
  1106.             netclos();
  1107. #ifdef OS2
  1108.               ReleaseTCPIPMutex();
  1109. #endif /* OS2 */
  1110.             return(-2);
  1111.           case SSL_ERROR_SSL:
  1112.             debug(F100,"ttbufr SSL_ERROR_SSL","",0);
  1113. #ifdef COMMENT
  1114.             netclos();
  1115. #endif /* COMMENT */
  1116. #ifdef OS2
  1117.               ReleaseTCPIPMutex();
  1118. #endif /* OS2 */
  1119.             return(-2);
  1120.           case SSL_ERROR_ZERO_RETURN:
  1121.             debug(F100,"ttbufr SSL_ERROR_ZERO_RETURN","",0);
  1122.             netclos();
  1123. #ifdef OS2
  1124.               ReleaseTCPIPMutex();
  1125. #endif /* OS2 */
  1126.             return(-2);
  1127.           default:
  1128.               debug(F100,"ttbufr SSL_ERROR_?????","",0);
  1129.               netclos();
  1130. #ifdef OS2
  1131.               ReleaseTCPIPMutex();
  1132. #endif /* OS2 */
  1133.               return(-2);
  1134.           }
  1135.     }
  1136. #endif /* CK_SSL */
  1137.  
  1138. #ifdef COMMENT
  1139. /*
  1140.  This is for nonblocking reads, which we don't do any more.  This code didn't
  1141.  work anyway, in the sense that a broken connection was never sensed.
  1142. */
  1143.     if ((count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count)) < 1) {
  1144.         if (count == -1 && socket_errno == EWOULDBLOCK) {
  1145.             debug(F100,"ttbufr finds nothing","",0);
  1146. #ifdef OS2
  1147.             ReleaseTCPIPMutex();
  1148. #endif /* OS2 */
  1149.             return(0);
  1150.         } else {
  1151.             debug(F101,"ttbufr socket_read error","",socket_errno);
  1152. #ifdef OS2
  1153.             ReleaseTCPIPMutex();
  1154. #endif /* OS2 */
  1155.             return(-1);
  1156.         }
  1157.  
  1158.     } else if (count == 0) {
  1159.         debug(F100,"ttbufr socket eof","",0);
  1160. #ifdef OS2
  1161.         ReleaseTCPIPMutex();
  1162. #endif /* OS2 */
  1163.         return(-1);
  1164.     }
  1165. #else /* COMMENT */
  1166.  
  1167. /* This is for blocking reads */
  1168.  
  1169. #ifndef VMS
  1170. #ifdef SO_OOBINLINE
  1171.     {
  1172.         int outofband = 0;
  1173. #ifdef BELLSELECT
  1174.         if (select(128, NULL, NULL, efds, 0) > 0 && FD_ISSET(ttyfd, efds))
  1175.           outofband = 1;
  1176. #else
  1177. #ifdef BSDSELECT
  1178.         fd_set efds;
  1179.         struct timeval tv;
  1180.         FD_ZERO(&efds);
  1181.         FD_SET(ttyfd, &efds);
  1182.         tv.tv_sec  = tv.tv_usec = 0L;
  1183.         debug(F100,"Out-of-Band BSDSELECT","",0);
  1184. #ifdef NT
  1185.         WSASafeToCancel = 1;
  1186. #endif /* NT */
  1187.         if (select(FD_SETSIZE, NULL, NULL, &efds, &tv) > 0 &&
  1188.             FD_ISSET(ttyfd, &efds))
  1189.           outofband = 1;
  1190. #ifdef NT
  1191.         WSASafeToCancel = 0;
  1192. #endif /* NT */
  1193. #else /* !BSDSELECT */
  1194. #ifdef IBMSELECT
  1195. /* Is used by OS/2 ... */
  1196. /* ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set */
  1197. /* and timeval stuff since this is the only place where it is used. */
  1198.         int socket = ttyfd;
  1199.         debug(F100,"Out-of-Band IBMSELECT","",0);
  1200.         if ((select(&socket, 0, 0, 1, 0L) == 1) && (socket == ttyfd))
  1201.           outofband = 1;
  1202. #else /* !IBMSELECT */
  1203. /*
  1204.   If we can't use select(), then we use the regular alarm()/signal()
  1205.   timeout mechanism.
  1206. */
  1207.       debug(F101,"Out-of-Band data not supported","",0);
  1208.       outofband = 0;
  1209.  
  1210. #endif /* IBMSELECT */
  1211. #endif /* BSDSELECT */
  1212. #endif /* BELLSELECT */
  1213.       if (outofband) {
  1214.          /* Get the Urgent Data */
  1215.          /* if OOBINLINE is disabled this should be only a single byte      */
  1216.          /* MS Winsock has a bug in Windows 95.  Extra bytes are delivered  */
  1217.          /* That were never sent.                                           */
  1218. #ifdef OS2
  1219.           RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1220. #endif /* OS2 */
  1221.           count = socket_recv(ttyfd,&ttibuf[ttibp+ttibn],count,MSG_OOB);
  1222. #ifdef OS2
  1223.           ReleaseTCPIPMutex();
  1224. #endif /* OS2 */
  1225.           if (count <= 0) {
  1226.               int s_errno = socket_errno;
  1227.               debug(F101, "ttbufr socket_recv MSG_OOB","",count);
  1228.               debug(F101, "ttbufr socket_errno","",s_errno);
  1229. #ifdef OS2ONLY
  1230.               if (count < 0 && (s_errno == 0 || s_errno == 23)) {
  1231.                   /* These appear in OS/2 - don't know why   */
  1232.                   /* ignore it and read as normal data       */
  1233.                   /* and break, then we will attempt to read */
  1234.                   /* the port using normal read() techniques */
  1235.                   debug(F100,"ttbufr handing as in-band data","",0);
  1236.                   count = 1;
  1237.               } else {
  1238.                   netclos();                    /* *** *** */
  1239. #ifdef OS2
  1240.                   ReleaseTCPIPMutex();
  1241. #endif /* OS2 */
  1242.                   return(-2);
  1243.               }
  1244. #else /* OS2ONLY */
  1245.               netclos();                        /* *** *** */
  1246. #ifdef OS2
  1247.               ReleaseTCPIPMutex();
  1248. #endif /* OS2 */
  1249.               return(-2);
  1250. #endif /* OS2ONLY */
  1251.           } else {                      /* we got out-of-band data */
  1252.               hexdump("ttbufr out-of-band chars",&ttibuf[ttibp+ttibn],count);
  1253. #ifdef BETADEBUG
  1254.               bleep(BP_NOTE);
  1255. #endif /* BETADEBUG */
  1256. #ifdef RLOGCODE                         /* blah */
  1257.               if (ttnproto == NP_RLOGIN  ||
  1258.                   ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  1259.                   ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  1260.                    )
  1261.               {
  1262.                   /*
  1263.                     When urgent data is read with MSG_OOB and not OOBINLINE
  1264.                     then urgent data and normal data are not mixed.  So
  1265.                     treat the entire buffer as urgent data.
  1266.                   */
  1267.                   rlog_oob(&ttibuf[ttibp+ttibn], count);
  1268. #ifdef OS2
  1269.                   ReleaseTCPIPMutex();
  1270. #endif /* OS2 */
  1271.                   return ttbufr();
  1272.               } else
  1273. #endif /* RLOGCODE */ /* blah */
  1274. #ifdef COMMENT
  1275.             /*
  1276.                I haven't written this yet, nor do I know what it should do
  1277.              */
  1278.                 if (ttnproto == NP_TELNET) {
  1279.                     tn_oob();
  1280. #ifdef OS2
  1281.                     ReleaseTCPIPMutex();
  1282. #endif /* OS2 */
  1283.                     return 0;
  1284.               } else
  1285. #endif /* COMMENT */
  1286.               {
  1287.                   /* For any protocols we don't have a special out-of-band  */
  1288.                   /* handler for, just put the bytes in the normal buffer   */
  1289.                   /* and return                                             */
  1290.  
  1291.                   ttibp += 0;       /* Reset buffer pointer. */
  1292.                   ttibn += count;
  1293. #ifdef DEBUG
  1294.                   /* Got some bytes. */
  1295.                   debug(F101,"ttbufr count 2","",count);
  1296.                   if (count > 0)
  1297.                       ttibuf[ttibp+ttibn] = '\0';
  1298.                   debug(F111,"ttbufr ttibuf",ttibuf,ttibp);
  1299. #endif /* DEBUG */
  1300. #ifdef OS2
  1301.                   ReleaseTCPIPMutex();
  1302. #endif /* OS2 */
  1303.                   return(ttibn);    /* Return buffer count. */
  1304.               }
  1305.           }
  1306.       }
  1307.     }
  1308. #endif /* SO_OOBINLINE */
  1309. #endif /* VMS */
  1310.  
  1311.     count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count);
  1312.     if (count <= 0) {
  1313.         int s_errno = socket_errno;
  1314.         debug(F101,"ttbufr socket_read","",count);
  1315.         debug(F101,"ttbufr socket_errno","",s_errno);
  1316. #ifdef OS2
  1317.         if (count == 0 || os2socketerror(s_errno) < 0) {
  1318.             netclos();
  1319.             ReleaseTCPIPMutex();
  1320.             return(-2);
  1321.         }
  1322.         ReleaseTCPIPMutex();
  1323.         return(-1);
  1324. #else /* OS2 */
  1325.         netclos();                      /* *** *** */
  1326.         return(-2);
  1327. #endif /* OS2 */
  1328.     }
  1329. #endif /* COMMENT */ /* (blocking vs nonblock reads...) */
  1330.     else {
  1331.         ttibp = 0;                      /* Reset buffer pointer. */
  1332.         ttibn += count;
  1333. #ifdef DEBUG
  1334.         debug(F101,"ttbufr count 2","",count); /* Got some bytes. */
  1335.         if (count > 0)
  1336.           ttibuf[ttibp+ttibn] = '\0';
  1337.         debug(F111,"ttbufr ttibuf",&ttibuf[ttibp],ttibn);
  1338. #endif /* DEBUG */
  1339. #ifdef OS2
  1340.         ReleaseTCPIPMutex();
  1341. #endif /* OS2 */
  1342.         return(ttibn);                  /* Return buffer count. */
  1343.     }
  1344. }
  1345. #endif /* TCPIPLIB */
  1346.  
  1347. #ifndef IBMSELECT
  1348. #ifndef BELLSELECT
  1349. #ifndef BSDSELECT               /* Non-TCPIPLIB case */
  1350. #ifdef SELECT
  1351. #define BSDSELECT
  1352. #endif /* SELECT */
  1353. #endif /* BSDSELECT */
  1354. #endif /* BELLSELECT */
  1355. #endif /* IBMSELECT */
  1356.  
  1357. #define TELNET_PORT 23          /* Should do lookup, but it won't change */
  1358. #define RLOGIN_PORT 513
  1359. #define KERMIT_PORT 1649
  1360. #define KLOGIN_PORT 543
  1361. #define EKLOGIN_PORT 2105
  1362.  
  1363. #ifndef NONET
  1364. /*
  1365.   C-Kermit network open/close functions for BSD-sockets.
  1366.   Much of this code shared by SunLink X.25, which also uses the socket library.
  1367. */
  1368.  
  1369. /*  N E T O P N  --  Open a network connection.  */
  1370. /*
  1371.   Call with:
  1372.     name of host (or host:service),
  1373.     lcl - local-mode flag to be set if this function succeeds,
  1374.     network type - value defined in ckunet.h.
  1375. */
  1376. #ifdef TCPSOCKET
  1377. struct hostent *
  1378. #ifdef CK_ANSIC
  1379. ck_copyhostent(struct hostent * h)
  1380. #else /* CK_ANSIC */
  1381. ck_copyhostent(h) struct hostent * h;
  1382. #endif /* CK_ANSIC */
  1383. {
  1384.     /*
  1385.      *  The hostent structure is dynamic in nature.
  1386.      *  struct  hostent {
  1387.      *  char    * h_name;
  1388.      *  char    * * h_aliases;
  1389.      *  short   h_addrtype;
  1390.      *  short   h_length;
  1391.      *  char    * * h_addr_list;
  1392.      *  #define h_addr  h_addr_list[0]
  1393.      */
  1394. #define HOSTENTCNT 5
  1395.     static struct hostent hosts[HOSTENTCNT] = {{NULL,NULL,0,0,NULL},
  1396.                                                {NULL,NULL,0,0,NULL},
  1397.                                                {NULL,NULL,0,0,NULL},
  1398.                                                {NULL,NULL,0,0,NULL},
  1399.                                                {NULL,NULL,0,0,NULL}};
  1400.     static int    next = 0;
  1401.     int    i,cnt;
  1402.     char ** pp;
  1403.  
  1404.     if ( h == NULL )
  1405.         return(NULL);
  1406.  
  1407.     if (next == HOSTENTCNT)
  1408.         next = 0;
  1409.  
  1410.     if ( hosts[next].h_name ) {
  1411.         free(hosts[next].h_name);
  1412.         hosts[next].h_name = NULL;
  1413.     }
  1414.     if ( hosts[next].h_aliases ) {
  1415.         pp = hosts[next].h_aliases;
  1416.         while ( *pp ) {
  1417.             free(*pp);
  1418.             pp++;
  1419.         }
  1420.         free(hosts[next].h_aliases);
  1421.     }
  1422. #ifdef HADDRLIST
  1423.     if ( hosts[next].h_addr_list ) {
  1424.         pp = hosts[next].h_addr_list;
  1425.         while ( *pp ) {
  1426.             free(*pp);
  1427.             pp++;
  1428.         }
  1429.         free(hosts[next].h_addr_list);
  1430.     }
  1431. #endif /* HADDRLIST */
  1432.  
  1433.     makestr(&hosts[next].h_name,h->h_name);
  1434.     if (h->h_aliases) {
  1435.         for ( cnt=0,pp=h->h_aliases; pp && *pp; pp++,cnt++) ;
  1436.     /* The following can give warnings in non-ANSI builds */
  1437.         hosts[next].h_aliases = (char **) malloc(sizeof(char *) * (cnt+1));
  1438.         for ( i=0; i<cnt; i++) {
  1439.             hosts[next].h_aliases[i] = NULL;
  1440.             makestr(&hosts[next].h_aliases[i],h->h_aliases[i]);
  1441.     }
  1442.         hosts[next].h_aliases[i] = NULL;
  1443.     } else
  1444.         hosts[next].h_aliases = NULL;
  1445.  
  1446.     hosts[next].h_addrtype = h->h_addrtype;
  1447.     hosts[next].h_length = h->h_length;
  1448.  
  1449. #ifdef HADDRLIST
  1450. #ifdef h_addr
  1451.     if (h->h_addr_list) {
  1452.         for ( cnt=0,pp=h->h_addr_list; pp && *pp; pp++,cnt++) ;
  1453.     /* The following can give warnings non-ANSI builds */
  1454.         hosts[next].h_addr_list = (char **) malloc(sizeof(char *) * (cnt+1));
  1455.         for ( i=0; i<cnt; i++) {
  1456.             hosts[next].h_addr_list[i] = malloc(h->h_length);
  1457.             bcopy(h->h_addr_list[i],hosts[next].h_addr_list[i],h->h_length);
  1458.         }
  1459.         hosts[next].h_addr_list[i] = NULL;
  1460.     } else
  1461.         hosts[next].h_addr_list = NULL;
  1462. #else
  1463.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1464. #endif /* h_addr */
  1465. #else /* HADDRLIST */
  1466.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1467. #endif /* HADDRLIST */
  1468.  
  1469.     return(&hosts[next++]);
  1470. }
  1471.  
  1472. #ifdef EXCELAN
  1473. /*
  1474.   Most other BSD sockets implementations define these in header files
  1475.   and libraries.
  1476. */
  1477. struct servent {
  1478.     unsigned short s_port;
  1479. };
  1480.  
  1481. struct hostent {
  1482.     short h_addrtype;
  1483.     struct in_addr h_addr;
  1484.     int h_length;
  1485. };
  1486.  
  1487. struct servent *
  1488. getservbyname(service, connection) char *service,*connection; {
  1489.     static struct servent servrec;
  1490.     int port;
  1491.  
  1492.     port = 0;
  1493.     if (strcmp(service, "telnet") == 0) port = 23;
  1494.     else if (strcmp(service, "smtp") == 0) port = 25;
  1495.     else port = atoi(service);
  1496.  
  1497.     debug(F101,"getservbyname return port ","",port);
  1498.  
  1499.     if (port > 0) {
  1500.         servrec.s_port = htons(port);
  1501.         return(&servrec);
  1502.     }
  1503.     return((struct servent *) NULL);
  1504. }
  1505.  
  1506. struct hostent *
  1507. gethostbyname(hostname) char *hostname; {
  1508.     return((struct hostent *) NULL);
  1509. }
  1510.  
  1511. unsigned long
  1512. inet_addr(name) char *name; {
  1513.     unsigned long addr;
  1514.  
  1515.     addr = rhost(&name);
  1516.     debug(F111,"inet_addr ",name,(int)addr);
  1517.     return(addr);
  1518. }
  1519.  
  1520. char *
  1521. inet_ntoa(in) struct in_addr in; {
  1522.     static char name[80];
  1523.     ckmakxmsg(name, ckuitoa(in.s_net),".",ckuitoa(in.s_host),".",
  1524.                ckuitoa(in.s_lh),".", ckuitoa(in.s_impno));
  1525.     return(name);
  1526. }
  1527. #else
  1528. #ifdef DEC_TCPIP                        /* UCX */
  1529.  
  1530. int ucx_port_bug = 0;                   /* Explained below */
  1531.  
  1532. #ifndef __DECC                          /* VAXC or GCC */
  1533.  
  1534. #define getservbyname my_getservbyname
  1535.  
  1536. #ifdef CK_ANSIC
  1537. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1538. extern void C$$TRANSLATE();
  1539. extern void C$$SOCK_TRANSLATE();
  1540. #else
  1541. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1542. extern VOID C$$TRANSLATE();
  1543. extern VOID C$$SOCK_TRANSLATE();
  1544. #endif /* CK_ANSIC */
  1545.  
  1546. struct servent *
  1547. my_getservbyname (service, proto) char *service, *proto; {
  1548.     static struct servent sent;
  1549.     struct iosb {
  1550.         union {
  1551.             unsigned long status;
  1552.             unsigned short st[2];
  1553.         } sb;
  1554.         unsigned long spare;
  1555.     } s;
  1556.     struct {
  1557.         struct iosb *s;
  1558.         char *serv;
  1559.         char *prot;
  1560.     } par;
  1561.     unsigned long e;
  1562.     char sbuf[30], pbuf[30];
  1563.     char *p;
  1564.  
  1565.     debug(F111,"UCX getservbyname",service,(int)C$$GA_UCX_GETSERVBYNAME);
  1566.  
  1567.     p = sbuf;
  1568.     ckstrncpy(p, service, 29);
  1569.     while (*p = toupper(*p), *p++) {}
  1570.     p = pbuf;
  1571.     ckstrncpy(p, proto, 29);
  1572.     while (*p = toupper(*p), *p++) {}
  1573.  
  1574.     par.s = &s;
  1575.  
  1576.     par.serv = "";
  1577.     par.prot = "";
  1578.     /* reset file pointer or something like that!?!? */
  1579.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1580.     par.serv = sbuf;
  1581.     par.prot = pbuf;            /* that is don't care */
  1582.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1583.     if ((long)e == -1L)
  1584.       return NULL;
  1585.     if ((e & 1) == 0L) {
  1586.         C$$TRANSLATE(e);
  1587.         return NULL;
  1588.     }
  1589.     if ((s.sb.st[0] & 1) == 0) {
  1590.         C$$SOCK_TRANSLATE(&s.sb.st[0]);
  1591.         return NULL;
  1592.     }
  1593. /*
  1594.   sent.s_port is supposed to be returned by UCX in network byte order.
  1595.   However, UCX 2.0 through 2.0C did not do this; 2.0D and later do it.
  1596.   But there is no way of knowing which UCX version, so we have a user-settable
  1597.   runtime variable.  Note: UCX 2.0 was only for the VAX.
  1598. */
  1599.     debug(F101,"UCX getservbyname port","",sent.s_port);
  1600.     debug(F101,"UCX getservbyname ntohs(port)","",ntohs(sent.s_port));
  1601.     if (ucx_port_bug) {
  1602.         sent.s_port = htons(sent.s_port);
  1603.         debug(F100,"UCX-PORT-BUG ON: swapping bytes","",0);
  1604.         debug(F101,"UCX swapped port","",sent.s_port);
  1605.         debug(F101,"UCX swapped ntohs(port)","",ntohs(sent.s_port));
  1606.     }
  1607.     return &sent;
  1608. }
  1609. #endif /* __DECC */
  1610. #endif /* DEC_TCPIP */
  1611. #endif /* EXCELAN */
  1612. #endif /* TCPSOCKET */
  1613.  
  1614. #ifndef NOTCPOPTS
  1615. #ifndef datageneral
  1616. int
  1617. ck_linger(onoff, timo) int onoff; int timo; {
  1618. /*
  1619.   The following, from William Bader, turns off the socket linger parameter,
  1620.   which makes a close() block until all data is sent.  "I don't think that
  1621.   disabling linger can ever cause kermit to lose data, but you telnet to a
  1622.   flaky server (or to our modem server when the modem is in use), disabling
  1623.   linger prevents kermit from hanging on the close if you try to exit."
  1624.  
  1625.   Modified by Jeff Altman to be generally useful.
  1626. */
  1627. #ifdef SOL_SOCKET
  1628. #ifdef SO_LINGER
  1629.     struct linger set_linger_opt;
  1630.     struct linger get_linger_opt;
  1631.     SOCKOPT_T x;
  1632.  
  1633. #ifdef IKSD
  1634.     if (!inserver)
  1635. #endif /* IKSD */
  1636.       if (ttyfd == -1 ||
  1637.     nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1638.         tcp_linger = onoff;
  1639.         tcp_linger_tmo = timo;
  1640.         return(1);
  1641.     }
  1642.     x = sizeof(get_linger_opt);
  1643.     if (getsockopt(ttyfd, SOL_SOCKET, SO_LINGER,
  1644.                     (char *)&get_linger_opt, &x)) {
  1645.         debug(F111,"TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1646.     } else if (x != sizeof(get_linger_opt)) {
  1647. #ifdef OS2
  1648.         struct _linger16 {
  1649.             short s_linger;
  1650.             short s_onoff;
  1651.         } get_linger_opt16, set_linger_opt16;
  1652.         if ( x == sizeof(get_linger_opt16) ) {
  1653.             debug(F111,"TCP setlinger warning: SO_LINGER","len is 16-bit",x);
  1654.             if (getsockopt(ttyfd,
  1655.                            SOL_SOCKET, SO_LINGER,
  1656.                            (char *)&get_linger_opt16, &x)
  1657.                 ) {
  1658.                 debug(F111,
  1659.                       "TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1660.             } else if (get_linger_opt16.s_onoff != onoff ||
  1661.                        get_linger_opt16.s_linger != timo)
  1662.             {
  1663.                 set_linger_opt16.s_onoff  = onoff;
  1664.                 set_linger_opt16.s_linger = timo;
  1665.                 if (setsockopt(ttyfd,
  1666.                                SOL_SOCKET,
  1667.                                SO_LINGER,
  1668.                                (char *)&set_linger_opt16,
  1669.                                sizeof(set_linger_opt16))
  1670.                     ) {
  1671.                     debug(F111,
  1672.                           "TCP ck_linger can't set SO_LINGER",
  1673.                           ck_errstr(),
  1674.                           errno
  1675.                           );
  1676.                     tcp_linger = get_linger_opt16.s_onoff;
  1677.                     tcp_linger_tmo = get_linger_opt16.s_linger;
  1678.                 } else {
  1679.                     debug(F101,
  1680.                           "TCP ck_linger new SO_LINGER","",
  1681.                           set_linger_opt16.s_onoff);
  1682.                     tcp_linger = set_linger_opt16.s_onoff;
  1683.                     tcp_linger_tmo = set_linger_opt16.s_linger;
  1684.                     return 1;
  1685.                 }
  1686.             } else {
  1687.                 debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1688.                        get_linger_opt16.s_onoff);
  1689.                 tcp_linger = get_linger_opt16.s_onoff;
  1690.                 tcp_linger_tmo = get_linger_opt16.s_linger;
  1691.                 return 1;
  1692.             }
  1693.             return(0);
  1694.         }
  1695. #endif /* OS2 */
  1696.         debug(F111,"TCP ck_linger error: SO_LINGER","len",x);
  1697.         debug(F111,"TCP ck_linger SO_LINGER",
  1698.               "expected len",sizeof(get_linger_opt));
  1699.         debug(F111,"TCP ck_linger SO_LINGER","linger_opt.l_onoff",
  1700.               get_linger_opt.l_onoff);
  1701.         debug(F111,"TCP linger SO_LINGER","linger_opt.l_linger",
  1702.                get_linger_opt.l_linger);
  1703.     } else if (get_linger_opt.l_onoff != onoff ||
  1704.                get_linger_opt.l_linger != timo) {
  1705.         set_linger_opt.l_onoff  = onoff;
  1706.         set_linger_opt.l_linger = timo;
  1707.         if (setsockopt(ttyfd,
  1708.                        SOL_SOCKET,
  1709.                        SO_LINGER,
  1710.                        (char *)&set_linger_opt,
  1711.                        sizeof(set_linger_opt))) {
  1712.             debug(F111,"TCP ck_linger can't set SO_LINGER",ck_errstr(),errno);
  1713.             tcp_linger = get_linger_opt.l_onoff;
  1714.             tcp_linger_tmo = get_linger_opt.l_linger;
  1715.          } else {
  1716.              debug(F101,
  1717.                    "TCP ck_linger new SO_LINGER",
  1718.                    "",
  1719.                    set_linger_opt.l_onoff
  1720.                    );
  1721.              tcp_linger = set_linger_opt.l_onoff;
  1722.              tcp_linger_tmo = set_linger_opt.l_linger;
  1723.              return 1;
  1724.          }
  1725.     } else {
  1726.         debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1727.               get_linger_opt.l_onoff);
  1728.         tcp_linger = get_linger_opt.l_onoff;
  1729.         tcp_linger_tmo = get_linger_opt.l_linger;
  1730.         return 1;
  1731.     }
  1732. #else
  1733.     debug(F100,"TCP ck_linger SO_LINGER not defined","",0);
  1734. #endif /* SO_LINGER */
  1735. #else
  1736.     debug(F100,"TCP ck_linger SO_SOCKET not defined","",0);
  1737. #endif /* SOL_SOCKET */
  1738.     return(0);
  1739. }
  1740.  
  1741. int
  1742. sendbuf(size) int size; {
  1743. /*
  1744.   The following, from William Bader, allows changing of socket buffer sizes,
  1745.   in case that might affect performance.
  1746.  
  1747.   Modified by Jeff Altman to be generally useful.
  1748. */
  1749. #ifdef SOL_SOCKET
  1750. #ifdef SO_SNDBUF
  1751.     int i, j;
  1752.     SOCKOPT_T x;
  1753.  
  1754. #ifdef IKSD
  1755.     if (!inserver)
  1756. #endif /* IKSD */
  1757.       if (ttyfd == -1 ||
  1758.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1759.         tcp_sendbuf = size;
  1760.         return 1;
  1761.     }
  1762.     x = sizeof(i);
  1763.     if (getsockopt(ttyfd, SOL_SOCKET, SO_SNDBUF, (char *)&i, &x)) {
  1764.         debug(F111,"TCP sendbuf can't get SO_SNDBUF",ck_errstr(),errno);
  1765.     } else if (x != sizeof(i)) {
  1766. #ifdef OS2
  1767.         short i16,j16;
  1768.         if (x == sizeof(i16)) {
  1769.             debug(F111,"TCP sendbuf warning: SO_SNDBUF","len is 16-bit",x);
  1770.             if (getsockopt(ttyfd,
  1771.                            SOL_SOCKET, SO_SNDBUF,
  1772.                            (char *)&i16, &x)
  1773.                 ) {
  1774.                 debug(F111,"TCP sendbuf can't get SO_SNDBUF",
  1775.                       ck_errstr(),errno);
  1776.             } else if (size <= 0) {
  1777.                 tcp_sendbuf = i16;
  1778.                 debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i16);
  1779.                 return 1;
  1780.             } else if (i16 != size) {
  1781.                 j16 = size;
  1782.                 if (setsockopt(ttyfd,
  1783.                                SOL_SOCKET,
  1784.                                SO_SNDBUF,
  1785.                                (char *)&j16,
  1786.                                sizeof(j16))
  1787.                     ) {
  1788.                     debug(F111,"TCP sendbuf can't set SO_SNDBUF",
  1789.                           ck_errstr(),errno);
  1790.                 } else {
  1791.                     debug(F101,"TCP sendbuf old SO_SNDBUF","",i16);
  1792.                     debug(F101,"TCP sendbuf new SO_SNDBUF","",j16);
  1793.                     tcp_sendbuf = size;
  1794.                     return 1;
  1795.                 }
  1796.             } else {
  1797.                 debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i16);
  1798.                 tcp_sendbuf = size;
  1799.                 return 1;
  1800.             }
  1801.             return(0);
  1802.         }
  1803. #endif /* OS2 */
  1804.         debug(F111,"TCP sendbuf error: SO_SNDBUF","len",x);
  1805.         debug(F111,"TCP sendbuf SO_SNDBUF","expected len",sizeof(i));
  1806.         debug(F111,"TCP sendbuf SO_SNDBUF","i",i);
  1807.     } else if (size <= 0) {
  1808.         tcp_sendbuf = i;
  1809.         debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i);
  1810.         return 1;
  1811.     } else if (i != size) {
  1812.         j = size;
  1813.         if (setsockopt(ttyfd, SOL_SOCKET, SO_SNDBUF, (char *)&j, sizeof(j))) {
  1814.             debug(F111,"TCP sendbuf can't set SO_SNDBUF",ck_errstr(),errno);
  1815.             tcp_sendbuf = i;
  1816.         } else {
  1817.             debug(F101,"TCP sendbuf old SO_SNDBUF","",i);
  1818.             debug(F101,"TCP sendbuf new SO_SNDBUF","",j);
  1819.             tcp_sendbuf = size;
  1820.             return 1;
  1821.         }
  1822.     } else {
  1823.         debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i);
  1824.         tcp_sendbuf = size;
  1825.         return 1;
  1826.     }
  1827. #else
  1828.     debug(F100,"TCP sendbuf SO_SNDBUF not defined","",0);
  1829. #endif /* SO_SNDBUF */
  1830. #else
  1831.     debug(F100,"TCP sendbuf SO_SOCKET not defined","",0);
  1832. #endif /* SOL_SOCKET */
  1833.     return(0);
  1834. }
  1835.  
  1836. int
  1837. recvbuf(size) int size; {
  1838. /*
  1839.   The following, from William Bader, allows changing of socket buffer sizes,
  1840.   in case that might affect performance.
  1841.  
  1842.   Modified by Jeff Altman to be generally useful.
  1843. */
  1844. #ifdef SOL_SOCKET
  1845. #ifdef SO_RCVBUF
  1846.     int i, j;
  1847.     SOCKOPT_T x;
  1848.  
  1849. #ifdef IKSD
  1850.     if (!inserver)
  1851. #endif /* IKSD */
  1852.       if (ttyfd == -1 ||
  1853.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1854.         tcp_recvbuf = size;
  1855.         return(1);
  1856.     }
  1857.     x = sizeof(i);
  1858.     if (getsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&i, &x)) {
  1859.         debug(F111,"TCP recvbuf can't get SO_RCVBUF",ck_errstr(),errno);
  1860.     } else if (x != sizeof(i)) {
  1861. #ifdef OS2
  1862.         short i16,j16;
  1863.         if ( x == sizeof(i16) ) {
  1864.             debug(F111,"TCP recvbuf warning: SO_RCVBUF","len is 16-bit",x);
  1865.             if (getsockopt(ttyfd,
  1866.                            SOL_SOCKET, SO_RCVBUF,
  1867.                            (char *)&i16, &x)
  1868.                 ) {
  1869.                 debug(F111,"TCP recvbuf can't get SO_RCVBUF",
  1870.                       ck_errstr(),errno);
  1871.             } else if (size <= 0) {
  1872.                 tcp_recvbuf = i16;
  1873.                 debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i16);
  1874.                 return 1;
  1875.             } else if (i16 != size) {
  1876.                 j16 = size;
  1877.                 if (setsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&j16,
  1878.                                sizeof(j16))) {
  1879.                     debug(F111,"TCP recvbuf can' set SO_RCVBUF",
  1880.                           ck_errstr(),errno);
  1881.                 } else {
  1882.                     debug(F101,"TCP recvbuf old SO_RCVBUF","",i16);
  1883.                     debug(F101,"TCP recvbuf new SO_RCVBUF","",j16);
  1884.                     tcp_recvbuf = size;
  1885.                     return 1;
  1886.                 }
  1887.             } else {
  1888.                 debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i16);
  1889.                 tcp_recvbuf = size;
  1890.                 return 1;
  1891.             }
  1892.             return(0);
  1893.         }
  1894. #endif /* OS2 */
  1895.         debug(F111,"TCP recvbuf error: SO_RCVBUF","len",x);
  1896.         debug(F111,"TCP recvbuf SO_RCVBUF","expected len",sizeof(i));
  1897.         debug(F111,"TCP recvbuf SO_RCVBUF","i",i);
  1898.     } else if (size <= 0) {
  1899.         tcp_recvbuf = i;
  1900.         debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i);
  1901.         return 1;
  1902.     } else if (i != size) {
  1903.         j = size;
  1904.         if (setsockopt(ttyfd, SOL_SOCKET, SO_RCVBUF, (char *)&j, sizeof(j))) {
  1905.             debug(F111,"TCP recvbuf can't set SO_RCVBUF",ck_errstr(),errno);
  1906.             tcp_recvbuf = i;
  1907.         } else {
  1908.             debug(F101,"TCP recvbuf old SO_RCVBUF","",i);
  1909.             debug(F101,"TCP recvbuf new SO_RCVBUF","",j);
  1910.             tcp_recvbuf = size;
  1911.             return 1;
  1912.         }
  1913.     } else {
  1914.         debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i);
  1915.         tcp_recvbuf = size;
  1916.         return 1;
  1917.     }
  1918. #else
  1919.     debug(F100,"TCP recvbuf SO_RCVBUF not defined","",0);
  1920. #endif /* SO_RCVBUF */
  1921. #else
  1922.     debug(F100,"TCP recvbuf SO_SOCKET not defined","",0);
  1923. #endif /* SOL_SOCKET */
  1924.     return 0;
  1925. }
  1926.  
  1927. int
  1928. keepalive(onoff) int onoff; {
  1929. #ifdef SOL_SOCKET
  1930. #ifdef SO_KEEPALIVE
  1931.     int get_keepalive_opt;
  1932.     int set_keepalive_opt;
  1933.     SOCKOPT_T x;
  1934.  
  1935.     debug(F111,"TCP keepalive","ttyfd",ttyfd);
  1936.     debug(F111,"TCP keepalive","nettype",nettype);
  1937.     debug(F111,"TCP keepalive","ttmdm",ttmdm);
  1938.  
  1939. #ifdef IKSD
  1940.     if (!inserver)
  1941. #endif /* IKSD */
  1942.       if (ttyfd == -1 ||
  1943.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  1944.         tcp_keepalive = onoff;
  1945.         return 1;
  1946.     }
  1947.     x = sizeof(get_keepalive_opt);
  1948.     if (getsockopt(ttyfd,
  1949.                    SOL_SOCKET, SO_KEEPALIVE, (char *)&get_keepalive_opt, &x)) {
  1950.         debug(F111,"TCP keepalive can't get SO_KEEPALIVE",ck_errstr(),errno);
  1951.     } else if (x != sizeof(get_keepalive_opt)) {
  1952. #ifdef OS2
  1953.         short get_keepalive_opt16;
  1954.         short set_keepalive_opt16;
  1955.         if (x == sizeof(get_keepalive_opt16)) {
  1956.             debug(F111,"TCP keepalive warning: SO_KEEPALIVE",
  1957.                   "len is 16-bit",x);
  1958.             if (getsockopt(ttyfd,
  1959.                            SOL_SOCKET, SO_KEEPALIVE,
  1960.                            (char *)&get_keepalive_opt16, &x)
  1961.                 ) {
  1962.                 debug(F111,
  1963.                       "TCP keepalive can't get SO_KEEPALIVE",
  1964.                       ck_errstr(),
  1965.                       errno
  1966.                       );
  1967.             } else if (get_keepalive_opt16 != onoff) {
  1968.                 set_keepalive_opt16 = onoff;
  1969.                 if (setsockopt(ttyfd,
  1970.                                SOL_SOCKET,
  1971.                                SO_KEEPALIVE,
  1972.                                (char *)&set_keepalive_opt16,
  1973.                                sizeof(set_keepalive_opt16))
  1974.                     ) {
  1975.                     debug(F111,
  1976.                           "TCP keepalive can't clear SO_KEEPALIVE",
  1977.                           ck_errstr(),
  1978.                           errno
  1979.                           );
  1980.                     tcp_keepalive = get_keepalive_opt16;
  1981.                 } else {
  1982.                     debug(F101,
  1983.                           "TCP keepalive new SO_KEEPALIVE","",
  1984.                           set_keepalive_opt16);
  1985.                     tcp_keepalive = set_keepalive_opt16;
  1986.                     return 1;
  1987.                 }
  1988.             } else {
  1989.                 debug(F101,"TCP keepalive SO_KEEPALIVE unchanged","",
  1990.                       get_keepalive_opt16);
  1991.                 tcp_keepalive = onoff;
  1992.                 return 1;
  1993.             }
  1994.             return(0);
  1995.         }
  1996. #endif /* OS2 */
  1997.         debug(F111,"TCP keepalive error: SO_KEEPALIVE","len",x);
  1998.         debug(F111,
  1999.               "TCP keepalive SO_KEEPALIVE",
  2000.               "expected len",
  2001.               sizeof(get_keepalive_opt)
  2002.               );
  2003.         debug(F111,
  2004.               "TCP keepalive SO_KEEPALIVE",
  2005.               "keepalive_opt",
  2006.               get_keepalive_opt
  2007.               );
  2008.     } else if (get_keepalive_opt != onoff) {
  2009.             set_keepalive_opt = onoff;
  2010.             if (setsockopt(ttyfd,
  2011.                             SOL_SOCKET,
  2012.                             SO_KEEPALIVE,
  2013.                             (char *)&set_keepalive_opt,
  2014.                             sizeof(set_keepalive_opt))
  2015.                 ) {
  2016.                 debug(F111,
  2017.                       "TCP keepalive can't clear SO_KEEPALIVE",
  2018.                       ck_errstr(),
  2019.                       errno
  2020.                       );
  2021.                 tcp_keepalive = get_keepalive_opt;
  2022.             } else {
  2023.                 debug(F101,
  2024.                       "TCP keepalive new SO_KEEPALIVE",
  2025.                       "",
  2026.                       set_keepalive_opt
  2027.                       );
  2028.                 tcp_keepalive = onoff;
  2029.                 return 1;
  2030.             }
  2031.         } else {
  2032.             debug(F101,"TCP keepalive SO_KEEPALIVE unchanged",
  2033.                   "",
  2034.                   get_keepalive_opt
  2035.                   );
  2036.             tcp_keepalive = onoff;
  2037.             return 1;
  2038.     }
  2039. #else
  2040.     debug(F100,"TCP keepalive SO_KEEPALIVE not defined","",0);
  2041. #endif /* SO_KEEPALIVE */
  2042. #else
  2043.     debug(F100,"TCP keepalive SO_SOCKET not defined","",0);
  2044. #endif /* SOL_SOCKET */
  2045.     return(0);
  2046. }
  2047.  
  2048. int
  2049. dontroute(onoff) int onoff; {
  2050. #ifdef SOL_SOCKET
  2051. #ifdef SO_DONTROUTE
  2052.     int get_dontroute_opt;
  2053.     int set_dontroute_opt;
  2054.     SOCKOPT_T x;
  2055.  
  2056. #ifdef IKSD
  2057.     if (!inserver)
  2058. #endif /* IKSD */
  2059.       if (ttyfd == -1 ||
  2060.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  2061.         tcp_dontroute = onoff;
  2062.         return 1;
  2063.     }
  2064.     x = sizeof(get_dontroute_opt);
  2065.     if (getsockopt(ttyfd,
  2066.                    SOL_SOCKET, SO_DONTROUTE, (char *)&get_dontroute_opt, &x)) {
  2067.         debug(F111,"TCP dontroute can't get SO_DONTROUTE",ck_errstr(),errno);
  2068.     } else if (x != sizeof(get_dontroute_opt)) {
  2069. #ifdef OS2
  2070.         short get_dontroute_opt16;
  2071.         short set_dontroute_opt16;
  2072.         if (x == sizeof(get_dontroute_opt16)) {
  2073.             debug(F111,"TCP dontroute warning: SO_DONTROUTE",
  2074.                   "len is 16-bit",x);
  2075.             if (getsockopt(ttyfd,
  2076.                            SOL_SOCKET, SO_DONTROUTE,
  2077.                            (char *)&get_dontroute_opt16, &x)
  2078.                 ) {
  2079.                 debug(F111,
  2080.                       "TCP dontroute can't get SO_DONTROUTE",
  2081.                       ck_errstr(),
  2082.                       errno
  2083.                       );
  2084.             } else if (get_dontroute_opt16 != onoff) {
  2085.                 set_dontroute_opt16 = onoff;
  2086.                 if (setsockopt(ttyfd,
  2087.                                SOL_SOCKET,
  2088.                                SO_DONTROUTE,
  2089.                                (char *)&set_dontroute_opt16,
  2090.                                sizeof(set_dontroute_opt16))
  2091.                     ) {
  2092.                     debug(F111,
  2093.                           "TCP dontroute can't clear SO_DONTROUTE",
  2094.                           ck_errstr(),
  2095.                           errno
  2096.                           );
  2097.                     tcp_dontroute = get_dontroute_opt16;
  2098.                 } else {
  2099.                     debug(F101,
  2100.                           "TCP dontroute new SO_DONTROUTE","",
  2101.                           set_dontroute_opt16);
  2102.                     tcp_dontroute = set_dontroute_opt16;
  2103.                     return 1;
  2104.                 }
  2105.             } else {
  2106.                 debug(F101,"TCP dontroute SO_DONTROUTE unchanged","",
  2107.                       get_dontroute_opt16);
  2108.                 tcp_dontroute = onoff;
  2109.                 return 1;
  2110.             }
  2111.             return(0);
  2112.         }
  2113. #endif /* OS2 */
  2114.         debug(F111,"TCP dontroute error: SO_DONTROUTE","len",x);
  2115.         debug(F111,
  2116.               "TCP dontroute SO_DONTROUTE",
  2117.               "expected len",
  2118.               sizeof(get_dontroute_opt)
  2119.               );
  2120.         debug(F111,
  2121.               "TCP dontroute SO_DONTROUTE",
  2122.               "dontroute_opt",
  2123.               get_dontroute_opt
  2124.               );
  2125.     } else if (get_dontroute_opt != onoff) {
  2126.             set_dontroute_opt = onoff;
  2127.             if (setsockopt(ttyfd,
  2128.                             SOL_SOCKET,
  2129.                             SO_DONTROUTE,
  2130.                             (char *)&set_dontroute_opt,
  2131.                             sizeof(set_dontroute_opt))
  2132.                 ) {
  2133.                 debug(F111,
  2134.                       "TCP dontroute can't clear SO_DONTROUTE",
  2135.                       ck_errstr(),
  2136.                       errno
  2137.                       );
  2138.                 tcp_dontroute = get_dontroute_opt;
  2139.             } else {
  2140.                 debug(F101,
  2141.                       "TCP dontroute new SO_DONTROUTE",
  2142.                       "",
  2143.                       set_dontroute_opt
  2144.                       );
  2145.                 tcp_dontroute = onoff;
  2146.                 return 1;
  2147.             }
  2148.         } else {
  2149.             debug(F101,"TCP dontroute SO_DONTROUTE unchanged",
  2150.                   "",
  2151.                   get_dontroute_opt
  2152.                   );
  2153.             tcp_dontroute = onoff;
  2154.             return 1;
  2155.     }
  2156. #else
  2157.     debug(F100,"TCP dontroute SO_DONTROUTE not defined","",0);
  2158. #endif /* SO_DONTROUTE */
  2159. #else
  2160.     debug(F100,"TCP dontroute SO_SOCKET not defined","",0);
  2161. #endif /* SOL_SOCKET */
  2162.     return(0);
  2163. }
  2164.  
  2165. int
  2166. no_delay(onoff)  int onoff; {
  2167. #ifdef SOL_SOCKET
  2168. #ifdef TCP_NODELAY
  2169.     int get_nodelay_opt;
  2170.     int set_nodelay_opt;
  2171.     SOCKOPT_T x;
  2172.  
  2173. #ifdef IKSD
  2174.     if (!inserver)
  2175. #endif /* IKSD */
  2176.       if (ttyfd == -1 ||
  2177.         nettype != NET_TCPA && nettype != NET_TCPB || ttmdm >= 0) {
  2178.         tcp_nodelay = onoff;
  2179.         return(1);
  2180.     }
  2181.     x = sizeof(get_nodelay_opt);
  2182.     if (getsockopt(ttyfd,IPPROTO_TCP,TCP_NODELAY,
  2183.                    (char *)&get_nodelay_opt,&x)) {
  2184.         debug(F111,
  2185.               "TCP no_delay can't get TCP_NODELAY",
  2186.               ck_errstr(),
  2187.               errno);
  2188.     } else if (x != sizeof(get_nodelay_opt)) {
  2189. #ifdef OS2
  2190.         short get_nodelay_opt16;
  2191.         short set_nodelay_opt16;
  2192.         if (x == sizeof(get_nodelay_opt16)) {
  2193.             debug(F111,"TCP no_delay warning: TCP_NODELAY","len is 16-bit",x);
  2194.             if (getsockopt(ttyfd,
  2195.                            IPPROTO_TCP, TCP_NODELAY,
  2196.                            (char *)&get_nodelay_opt16, &x)
  2197.                 ) {
  2198.                 debug(F111,
  2199.                       "TCP no_delay can't get TCP_NODELAY",
  2200.                       ck_errstr(),
  2201.                       errno);
  2202.             } else if (get_nodelay_opt16 != onoff) {
  2203.                 set_nodelay_opt16 = onoff;
  2204.                 if (setsockopt(ttyfd,
  2205.                                IPPROTO_TCP,
  2206.                                TCP_NODELAY,
  2207.                                (char *)&set_nodelay_opt16,
  2208.                                sizeof(set_nodelay_opt16))
  2209.                     ) {
  2210.                     debug(F111,
  2211.                           "TCP no_delay can't clear TCP_NODELAY",
  2212.                           ck_errstr(),
  2213.                           errno);
  2214.                     tcp_nodelay = get_nodelay_opt16;
  2215.                 } else {
  2216.                     debug(F101,
  2217.                           "TCP no_delay new TCP_NODELAY",
  2218.                           "",
  2219.                           set_nodelay_opt16);
  2220.                     tcp_nodelay = onoff;
  2221.                     return 1;
  2222.                 }
  2223.             } else {
  2224.                 debug(F101,"TCP no_delay TCP_NODELAY unchanged","",
  2225.                       get_nodelay_opt16);
  2226.                 tcp_nodelay = onoff;
  2227.                 return 1;
  2228.             }
  2229.             return(0);
  2230.         }
  2231. #endif /* OS2 */
  2232.         debug(F111,"TCP no_delay error: TCP_NODELAY","len",x);
  2233.         debug(F111,"TCP no_delay TCP_NODELAY","expected len",
  2234.               sizeof(get_nodelay_opt));
  2235.         debug(F111,"TCP no_delay TCP_NODELAY","nodelay_opt",get_nodelay_opt);
  2236.     } else if (get_nodelay_opt != onoff) {
  2237.         set_nodelay_opt = onoff;
  2238.         if (setsockopt(ttyfd,
  2239.                        IPPROTO_TCP,
  2240.                        TCP_NODELAY,
  2241.                        (char *)&set_nodelay_opt,
  2242.                        sizeof(set_nodelay_opt))) {
  2243.             debug(F111,
  2244.                   "TCP no_delay can't clear TCP_NODELAY",
  2245.                   ck_errstr(),
  2246.                   errno
  2247.                   );
  2248.             tcp_nodelay = get_nodelay_opt;
  2249.         } else {
  2250.             debug(F101,"TCP no_delay new TCP_NODELAY","",set_nodelay_opt);
  2251.             tcp_nodelay = onoff;
  2252.             return 1;
  2253.         }
  2254.     } else {
  2255.         debug(F101,"TCP no_delay TCP_NODELAY unchanged","",get_nodelay_opt);
  2256.         tcp_nodelay = onoff;
  2257.         return(1);
  2258.     }
  2259. #else
  2260.     debug(F100,"TCP no_delay TCP_NODELAY not defined","",0);
  2261. #endif /* TCP_NODELAY */
  2262. #else
  2263.     debug(F100,"TCP no_delay SO_SOCKET not defined","",0);
  2264. #endif /* SOL_SOCKET */
  2265.     return 0;
  2266. }
  2267. #endif /* datageneral */
  2268. #endif /* NOTCPOPTS */
  2269.  
  2270. #ifdef SUNX25
  2271. #ifndef X25_WR_FACILITY
  2272. /* For Solaris 2.3 / SunLink 8.x - see comments in ckcnet.h */
  2273. void
  2274. bzero(s,n) char *s; int n; {
  2275.     memset(s,0,n);
  2276. }
  2277. #endif /* X25_WR_FACILITY */
  2278. #endif /* SUNX25 */
  2279.  
  2280. #ifdef TCPSOCKET
  2281. #ifndef OS2
  2282. #ifndef NOLISTEN
  2283.  
  2284. #ifdef BSDSELECT
  2285. #ifndef VMS
  2286. #ifndef BELLV10
  2287. #ifndef datageneral
  2288. #ifdef hp9000s500                       /* HP-9000/500 HP-U 5.21 */
  2289. #include <time.h>
  2290. #else
  2291.  
  2292. /****** THIS SECTION ADDED BY STEVE RANCE - OS9 NETWORK SERVER
  2293. *       ------------------------------------------------------
  2294. *
  2295. *       Due to OS9's Lack of a select() call, the following seems to be
  2296. *       enough to fool the rest of the code into compiling. The only
  2297. *       effect that I can see is using control L to refresh the status
  2298. *       display gets qued up until some network packets arrive.
  2299. *
  2300. *       This solution is by no means elegant but works enough to be
  2301. *       a (the) solution.
  2302. *
  2303. *       Also with the defines I had specified in my makefile I had to
  2304. *       have an #endif right at the end of the file when compiling.
  2305. *       I did not bother speding time to find out why.
  2306. *
  2307. *       COPTS   = -to=osk -d=OSK -d=TCPSOCKET -d=SELECT -d=VOID=void -d=SIG_V \
  2308. *          -d=DYNAMIC -d=PARSENSE -d=KANJI -d=MYCURSES -d=ZFCDAT \
  2309. *          -d=CK_APC -d=CK_REDIR -d=RENAME -d=CK_TTYFD -d=NOOLDMODEMS \
  2310. *          -d=CK_ANSIC -d=CK_XYZ -tp=68040d -l=netdb.l -l=socklib.l \
  2311. *          -l=termlib.l -l=math.l -l=sys_clib.l
  2312. *
  2313. *       stever@ozemail.com.au
  2314. */
  2315.  
  2316. #ifdef  OSK
  2317. #define BSDSELECT                       /* switch on BSD select code */
  2318. #define FD_SETSIZE 32                   /* Max # of paths in OS9 */
  2319. #define FD_ZERO(p)                      ((*p)=0)
  2320. #define FD_SET(n,b)                     ((*b)|=(1<<(n)))
  2321. #define FD_ISSET(n,b)           1       /* always say data is ready */
  2322. #define select(a,b,c,d,e)       1       /* always say 1 path has data */
  2323. typedef int     fd_set;                 /* keep BSD Code Happy */
  2324. struct timeval {int tv_sec,tv_usec;};   /* keep BSD Code Happy */
  2325.  
  2326. /****** END OF OS9 MODS FROM STEVE RANCE **************************/
  2327. #endif /* OSK */
  2328.  
  2329. #include <sys/time.h>
  2330. #endif /* hp9000s500 */
  2331. #endif /* datageneral */
  2332. #endif /* BELLV10 */
  2333. #endif /* VMS */
  2334. #ifdef SELECT_H
  2335. #include <sys/select.h>
  2336. #endif /* SELECT_H */
  2337. #endif /* BSDSELECT */
  2338.  
  2339. #ifdef SELECT
  2340. #ifdef CK_SCOV5
  2341. #include <sys/select.h>
  2342. #endif /* CK_SCOV5 */
  2343. #endif /* SELECT */
  2344.  
  2345. #ifdef NOTUSED
  2346. /* T C P S O C K E T _ O P E N -- Open a preexisting socket number */
  2347.  
  2348. int
  2349. tcpsocket_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo {
  2350.     int on = 1;
  2351.     static struct servent *service, servrec;
  2352.     static struct hostent *host;
  2353.     static struct sockaddr_in saddr;
  2354.     static
  2355. #ifdef UCX50
  2356.       unsigned
  2357. #endif /* UCX50 */
  2358.       int saddrlen;
  2359. #ifdef BSDSELECT
  2360.     fd_set rfds;
  2361.     struct timeval tv;
  2362. #else
  2363. #ifdef BELLSELECT
  2364.     fd_set rfds;
  2365. #else
  2366.     fd_set rfds;
  2367.     fd_set rfds;
  2368.     struct timeval {
  2369.         long tv_sec;
  2370.         long tv_usec;
  2371.     } tv;
  2372. #endif /* BELLSELECT */
  2373. #endif /* BSDSELECT */
  2374.  
  2375.     debug(F101,"tcpsocket_open nett","",nett);
  2376.     *ipaddr = '\0';
  2377.  
  2378.     if (nett != NET_TCPB)
  2379.       return(-1);                       /* BSD socket support */
  2380.  
  2381.     netclos();                          /* Close any previous connection. */
  2382.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2383.     if (ttnproto != NP_TCPRAW)
  2384.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2385.     debug(F110,"tcpsocket_open namecopy",namecopy,0);
  2386.  
  2387.     /* Assign the socket number to ttyfd and then fill in tcp structures */
  2388.     ttyfd = atoi(&name[1]);
  2389.     debug(F111,"tcpsocket_open","ttyfd",ttyfd);
  2390.  
  2391. #ifndef NOTCPOPTS
  2392. #ifdef SOL_SOCKET
  2393.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2394.  
  2395. #ifndef datageneral
  2396. #ifdef TCP_NODELAY
  2397.     no_delay(tcp_nodelay);
  2398. #endif /* TCP_NODELAY */
  2399. #ifdef SO_KEEPALIVE
  2400.     keepalive(tcp_keepalive);
  2401. #endif /* SO_KEEPALIVE */
  2402. #ifdef SO_LINGER
  2403.     ck_linger(tcp_linger, tcp_linger_tmo);
  2404. #endif /* SO_LINGER */
  2405. #ifdef SO_SNDBUF
  2406.     sendbuf(tcp_sendbuf);
  2407. #endif /* SO_SNDBUF */
  2408. #ifdef SO_RCVBUF
  2409.     recvbuf(tcp_recvbuf);
  2410. #endif /* SO_RCVBUF */
  2411. #endif /* datageneral */
  2412. #endif /* SOL_SOCKET */
  2413. #endif /* NOTCPOPTS */
  2414.  
  2415. #ifdef NT_TCP_OVERLAPPED
  2416.     OverlappedWriteInit();
  2417.     OverlappedReadInit();
  2418. #endif /* NT_TCP_OVERLAPPED */
  2419.  
  2420.  
  2421.     /* Get the name of the host we are connected to */
  2422.  
  2423.     saddrlen = sizeof(saddr);
  2424.     getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen);
  2425.  
  2426.     ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2427.  
  2428.     if (tcp_rdns == SET_ON
  2429. #ifdef CK_KERBEROS
  2430.         || tcp_rdns == SET_AUTO &&
  2431.          (ck_krb5_is_installed() || ck_krb4_is_installed())
  2432. #endif /* CK_KERBEROS */
  2433. #ifndef NOHTTP
  2434.           && (tcp_http_proxy == NULL)
  2435. #endif /* NOHTTP */
  2436. #ifdef CK_SSL
  2437.           && !(ssl_only_flag || tls_only_flag)
  2438. #endif /* CK_SSL */
  2439.          ) {                            /* Reverse DNS */
  2440.         if (!quiet) {
  2441.             printf(" Reverse DNS Lookup... ");
  2442.             fflush(stdout);
  2443.         }
  2444.         host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET);
  2445.         debug(F110,"tcpsocket_open gethostbyaddr",host ? "OK" : "FAILED",0);
  2446.         if (host) {
  2447.             host = ck_copyhostent(host);
  2448.             debug(F100,"tcpsocket_open gethostbyaddr != NULL","",0);
  2449.             if (!quiet) {
  2450.                 printf("(OK)\n");
  2451.                 fflush(stdout);
  2452.             }
  2453.             ckstrncpy(name, host->h_name, 80);
  2454.             ckstrncat(name, ":", 80);
  2455.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)), 80);
  2456.             if (!quiet
  2457. #ifndef NOICP
  2458.                 && !doconx
  2459. #endif /* NOICP */
  2460.                 )
  2461.               printf("%s connected on port %d\n",
  2462.                    host->h_name,
  2463.                    ntohs(saddr.sin_port)
  2464.                    );
  2465.         } else if (!quiet)
  2466.           printf("Failed\n");
  2467.     } else if (!quiet)
  2468.       printf("(OK)\n");
  2469.  
  2470.     if (tcp_rdns != SET_ON || !host) {
  2471.         ckstrncpy(name,ipaddr,80);
  2472.         ckstrncat(name,":",80);
  2473.         ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  2474.         if (!quiet
  2475. #ifdef NOICP
  2476.             && !doconx
  2477. #endif /* NOICP */
  2478.             )
  2479.           printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2480.     }
  2481.     if (!quiet) fflush(stdout);
  2482.     ttnet = nett;                       /* TCP/IP (sockets) network */
  2483.  
  2484. #ifdef RLOGCODE
  2485.     if (ntohs(saddr.sin_port) == 513)
  2486.         ttnproto = NP_LOGIN;
  2487.     else
  2488. #endif /* RLOGCODE */
  2489.     /* Assume the service is TELNET. */
  2490.     if (ttnproto != NP_TCPRAW)
  2491.         ttnproto = NP_TELNET;           /* Yes, set global flag. */
  2492. #ifdef CK_AUTHENTICATION
  2493.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2494.     ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2495.                 host->h_name : ipaddr,
  2496.                 ipaddr,
  2497.                 uidbuf,
  2498.                 ttyfd
  2499.                 );
  2500. #endif /* CK_AUTHENTICATION */
  2501.     if (tn_ini() < 0)                   /* Start/Reset TELNET negotiations */
  2502.       if (ttchk() < 0)                  /* Did it fail due to connect loss? */
  2503.         return(-1);
  2504.  
  2505.     if (*lcl < 0) *lcl = 1;             /* Local mode. */
  2506.  
  2507.     return(0);                          /* Done. */
  2508. }
  2509. #endif /* NOTUSED */
  2510.  
  2511. /*  T C P S R V _ O P E N  --  Open a TCP/IP Server connection  */
  2512. /*
  2513.   Calling conventions same as ttopen(), except third argument is network
  2514.   type rather than modem type.
  2515. */
  2516. int
  2517. tcpsrv_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo; {
  2518.     char *p;
  2519.     int i, x;
  2520.     SOCKOPT_T on = 1;
  2521.     int ready_to_accept = 0;
  2522.     static struct servent *service, *service2, servrec;
  2523.     static struct hostent *host;
  2524.     static struct sockaddr_in saddr;
  2525.     struct sockaddr_in l_addr;
  2526.     GSOCKNAME_T l_slen;
  2527. #ifdef UCX50
  2528.     static u_int saddrlen;
  2529. #else
  2530.     static SOCKOPT_T saddrlen;
  2531. #endif /* UCX50 */
  2532.  
  2533. #ifdef BSDSELECT
  2534.     fd_set rfds;
  2535.     struct timeval tv;
  2536. #else
  2537. #ifdef BELLSELCT
  2538.     fd_set rfds;
  2539. #else
  2540.     fd_set rfds;
  2541.     struct timeval {
  2542.         long tv_sec;
  2543.         long tv_usec;
  2544.     } tv;
  2545. #endif /* BELLSELECT */
  2546. #endif /* BSDSELECT */
  2547. #ifdef CK_SSL
  2548.     int ssl_failed = 0;
  2549. #endif /* CK_SSL */
  2550.  
  2551.     debug(F101,"tcpsrv_open nett","",nett);
  2552.     *ipaddr = '\0';
  2553.  
  2554.     if (nett != NET_TCPB)
  2555.       return(-1);                       /* BSD socket support */
  2556.  
  2557.     netclos();                          /* Close any previous connection. */
  2558.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2559. #ifdef COMMENT
  2560.     /* Don't do this. */
  2561.     if (ttnproto != NP_TCPRAW)
  2562.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2563. #endif /* COMMENT */
  2564.     debug(F110,"tcpsrv_open namecopy",namecopy,0);
  2565.  
  2566.     p = namecopy;                       /* Was a service requested? */
  2567.     while (*p != '\0' && *p != ':')
  2568.       p++; /* Look for colon */
  2569.     if (*p == ':') {                    /* Have a colon */
  2570.         *p++ = '\0';                    /* Get service name or number */
  2571.     } else {                            /* Otherwise use kermit */
  2572.         p = "kermit";
  2573.     }
  2574.     debug(F110,"tcpsrv_open service requested",p,0);
  2575.     if (isdigit(*p)) {                  /* Use socket number without lookup */
  2576.         service = &servrec;
  2577.         service->s_port = htons((unsigned short)atoi(p));
  2578.     } else {                            /* Otherwise lookup the service name */
  2579.         service = getservbyname(p, "tcp");
  2580.     }
  2581.     if (!service && !strcmp("kermit",p)) { /* Use Kermit service port */
  2582.         service = &servrec;
  2583.         service->s_port = htons(1649);
  2584.     }
  2585. #ifdef RLOGCODE
  2586.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  2587.         fprintf(stderr,
  2588.                 "  Warning: login service on port %d instead of port 513\n",
  2589.                  ntohs(service->s_port));
  2590.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  2591.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  2592.     }
  2593. #endif /* RLOGCODE */
  2594.     if (!service) {
  2595.         fprintf(stderr, "Cannot find port for service: %s\n", p);
  2596.         debug(F111,"tcpsrv_open can't get service",p,errno);
  2597.         errno = 0;                      /* rather than mislead */
  2598.         return(-1);
  2599.     }
  2600.  
  2601.     /* If we currently have a listen active but port has changed then close */
  2602.  
  2603.     debug(F101,"tcpsrv_open checking previous connection","",tcpsrfd);
  2604.     debug(F101,"tcpsrv_open previous tcpsrv_port","",tcpsrv_port);
  2605.     if (tcpsrfd != -1 &&
  2606.         tcpsrv_port != ntohs((unsigned short)service->s_port)) {
  2607.         debug(F100,"tcpsrv_open closing previous connection","",0);
  2608. #ifdef TCPIPLIB
  2609.         socket_close(tcpsrfd);
  2610. #else
  2611.         close(tcpsrfd);
  2612. #endif /* TCPIPLIB */
  2613.         tcpsrfd = -1;
  2614.     }
  2615.     debug(F100,"tcpsrv_open tcpsrfd","",tcpsrfd);
  2616.     if (tcpsrfd == -1) {
  2617.  
  2618.         /* Set up socket structure and get host address */
  2619.  
  2620.         bzero((char *)&saddr, sizeof(saddr));
  2621.         debug(F100,"tcpsrv_open bzero ok","",0);
  2622.         saddr.sin_family = AF_INET;
  2623.         if (tcp_address) {
  2624. #ifdef INADDRX
  2625.             inaddrx = inet_addr(tcp_address);
  2626.             saddr.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  2627. #else
  2628.             saddr.sin_addr.s_addr = inet_addr(tcp_address);
  2629. #endif /* INADDRX */
  2630.         } else
  2631.           saddr.sin_addr.s_addr = INADDR_ANY;
  2632.  
  2633.         /* Get a file descriptor for the connection. */
  2634.  
  2635.         saddr.sin_port = service->s_port;
  2636.         ipaddr[0] = '\0';
  2637.  
  2638.         debug(F100,"tcpsrv_open calling socket","",0);
  2639.         if ((tcpsrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  2640.             perror("TCP socket error");
  2641.             debug(F101,"tcpsrv_open socket error","",errno);
  2642.             return (-1);
  2643.         }
  2644.         errno = 0;
  2645.  
  2646.         /* Specify the Port may be reused */
  2647.  
  2648.         debug(F100,"tcpsrv_open calling setsockopt","",0);
  2649.         x = setsockopt(tcpsrfd,
  2650.                        SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof on);
  2651.         debug(F101,"tcpsrv_open setsockopt","",x);
  2652.  
  2653.        /* Now bind to the socket */
  2654.         printf("\nBinding socket to port %d ...\n",
  2655.                ntohs((unsigned short)service->s_port));
  2656.         if (bind(tcpsrfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  2657.             i = errno;                  /* Save error code */
  2658. #ifdef TCPIPLIB
  2659.             socket_close(tcpsrfd);
  2660. #else /* TCPIPLIB */
  2661.             close(tcpsrfd);
  2662. #endif /* TCPIPLIB */
  2663.             tcpsrfd = -1;
  2664.             tcpsrv_port = 0;
  2665.             ttyfd = -1;
  2666.             wasclosed = 1;
  2667.             errno = i;                  /* and report this error */
  2668.             debug(F101,"tcpsrv_open bind errno","",errno);
  2669.             printf("?Unable to bind to socket (errno = %d)\n",errno);
  2670.             return(-1);
  2671.         }
  2672.         debug(F100,"tcpsrv_open bind OK","",0);
  2673.         printf("Listening ...\n");
  2674.         if (listen(tcpsrfd, 15) < 0) {
  2675.             i = errno;                  /* Save error code */
  2676. #ifdef TCPIPLIB
  2677.             socket_close(tcpsrfd);
  2678. #else /* TCPIPLIB */
  2679.             close(tcpsrfd);
  2680. #endif /* TCPIPLIB */
  2681.             tcpsrfd = -1;
  2682.             tcpsrv_port = 0;
  2683.             ttyfd = -1;
  2684.             wasclosed = 1;
  2685.             errno = i;                  /* And report this error */
  2686.             debug(F101,"tcpsrv_open listen errno","",errno);
  2687.             return(-1);
  2688.         }
  2689.         debug(F100,"tcpsrv_open listen OK","",0);
  2690.         tcpsrv_port = ntohs((unsigned short)service->s_port);
  2691.     }
  2692.  
  2693. #ifdef CK_SSL
  2694.     if (ck_ssleay_is_installed()) {
  2695.         if (!ssl_tn_init(SSL_SERVER)) {
  2696.             ssl_failed = 1;
  2697.             if (bio_err!=NULL) {
  2698.                 BIO_printf(bio_err,"do_ssleay_init() failed\n");
  2699.                 ERR_print_errors(bio_err);
  2700.             } else {
  2701.                 fflush(stderr);
  2702.                 fprintf(stderr,"do_ssleay_init() failed\n");
  2703.                 ERR_print_errors_fp(stderr);
  2704.             }
  2705.             if (tls_only_flag || ssl_only_flag) {
  2706. #ifdef TCPIPLIB
  2707.                 socket_close(ttyfd);
  2708.                 socket_close(tcpsrfd);
  2709. #else /* TCPIPLIB */
  2710.                 close(ttyfd);
  2711.                 close(tcpsrfd);
  2712. #endif /* TCPIPLIB */
  2713.                 ttyfd = -1;
  2714.                 wasclosed = 1;
  2715.                 tcpsrfd = -1;
  2716.                 tcpsrv_port = 0;
  2717.                 return(-1);
  2718.             }
  2719.             /* we will continue to accept the connection   */
  2720.             /* without SSL or TLS support unless required. */
  2721.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2722.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2723.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2724.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2725.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2726.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2727.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2728.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2729.         }
  2730.     }
  2731. #endif /* CK_SSL */
  2732.  
  2733.     printf("\nWaiting to Accept a TCP/IP connection on port %d ...\n",
  2734.            ntohs((unsigned short)service->s_port));
  2735.     saddrlen = sizeof(saddr);
  2736.  
  2737. #ifdef BSDSELECT
  2738.     tv.tv_sec  = tv.tv_usec = 0L;
  2739.     if (timo < 0)
  2740.       tv.tv_usec = (long) -timo * 10000L;
  2741.     else
  2742.       tv.tv_sec = timo;
  2743.     debug(F101,"tcpsrv_open BSDSELECT","",timo);
  2744. #else
  2745.     debug(F101,"tcpsrv_open not BSDSELECT","",timo);
  2746. #endif /* BSDSELECT */
  2747.  
  2748.     if (timo) {
  2749.         while (!ready_to_accept) {
  2750. #ifdef BSDSELECT
  2751.             FD_ZERO(&rfds);
  2752.             FD_SET(tcpsrfd, &rfds);
  2753.             ready_to_accept =
  2754.               ((select(FD_SETSIZE,
  2755. #ifdef HPUX
  2756. #ifdef HPUX1010
  2757.                        (fd_set *)
  2758. #else
  2759.  
  2760.                        (int *)
  2761. #endif /* HPUX1010 */
  2762. #else
  2763. #ifdef __DECC
  2764.                        (fd_set *)
  2765. #endif /* __DECC */
  2766. #endif /* HPUX */
  2767.                        &rfds, NULL, NULL, &tv) > 0) &&
  2768.                FD_ISSET(tcpsrfd, &rfds));
  2769. #else /* BSDSELECT */
  2770. #ifdef IBMSELECT
  2771. #define ck_sleepint 250
  2772.             ready_to_accept =
  2773.               (select(&tcpsrfd, 1, 0, 0,
  2774.                       timo < 0 ? -timo :
  2775.                       (timo > 0 ? timo * 1000L : ck_sleepint)) == 1
  2776.                );
  2777. #else
  2778. #ifdef BELLSELECT
  2779.             FD_ZERO(rfds);
  2780.             FD_SET(tcpsrfd, rfds);
  2781.             ready_to_accept =
  2782.               ((select(128, rfds, NULL, NULL, timo < 0 ? -timo :
  2783.                       (timo > 0 ? timo * 1000L)) > 0) &&
  2784.                FD_ISSET(tcpsrfd, rfds));
  2785. #else
  2786. /* Try this - what's the worst that can happen... */
  2787.  
  2788.             FD_ZERO(&rfds);
  2789.             FD_SET(tcpsrfd, &rfds);
  2790.             ready_to_accept =
  2791.               ((select(FD_SETSIZE,
  2792.                        (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  2793.                FD_ISSET(tcpsrfd, &rfds));
  2794.  
  2795. #endif /* BELLSELECT */
  2796. #endif /* IBMSELECT */
  2797. #endif /* BSDSELECT */
  2798.         }
  2799.     }
  2800.     if (ready_to_accept || timo == 0) {
  2801.         if ((ttyfd = accept(tcpsrfd,
  2802.                             (struct sockaddr *)&saddr,&saddrlen)) < 0) {
  2803.             i = errno;                  /* save error code */
  2804. #ifdef TCPIPLIB
  2805.             socket_close(tcpsrfd);
  2806. #else /* TCPIPLIB */
  2807.             close(tcpsrfd);
  2808. #endif /* TCPIPLIB */
  2809.             ttyfd = -1;
  2810.             wasclosed = 1;
  2811.             tcpsrfd = -1;
  2812.             tcpsrv_port = 0;
  2813.             errno = i;                  /* and report this error */
  2814.             debug(F101,"tcpsrv_open accept errno","",errno);
  2815.             return(-1);
  2816.         }
  2817.         setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2818.  
  2819. #ifndef NOTCPOPTS
  2820. #ifndef datageneral
  2821. #ifdef SOL_SOCKET
  2822. #ifdef TCP_NODELAY
  2823.         no_delay(tcp_nodelay);
  2824.         debug(F101,"tcpsrv_open no_delay","",tcp_nodelay);
  2825. #endif /* TCP_NODELAY */
  2826. #ifdef SO_KEEPALIVE
  2827.         keepalive(tcp_keepalive);
  2828.         debug(F101,"tcpsrv_open keepalive","",tcp_keepalive);
  2829. #endif /* SO_KEEPALIVE */
  2830. #ifdef SO_LINGER
  2831.         ck_linger(tcp_linger, tcp_linger_tmo);
  2832.         debug(F101,"tcpsrv_open linger","",tcp_linger_tmo);
  2833. #endif /* SO_LINGER */
  2834. #ifdef SO_SNDBUF
  2835.         sendbuf(tcp_sendbuf);
  2836. #endif /* SO_SNDBUF */
  2837. #ifdef SO_RCVBUF
  2838.         recvbuf(tcp_recvbuf);
  2839. #endif /* SO_RCVBUF */
  2840. #endif /* SOL_SOCKET */
  2841. #endif /* datageneral */
  2842. #endif /* NOTCPOPTS */
  2843.  
  2844.         ttnet = nett;                   /* TCP/IP (sockets) network */
  2845.         tcp_incoming = 1;               /* This is an incoming connection */
  2846.         sstelnet = 1;                   /* Do server-side Telnet protocol */
  2847.  
  2848.         /* See if the service is TELNET. */
  2849.         x = (unsigned short)service->s_port;
  2850.         service2 = getservbyname("telnet", "tcp");
  2851.         if (service2 && x == service2->s_port) {
  2852.             if (ttnproto != NP_TCPRAW)  /* Yes and if raw port not requested */
  2853.               ttnproto = NP_TELNET;     /* Set protocol to TELNET. */
  2854.         }
  2855. #ifdef CK_AUTHENTICATION
  2856.         /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2857.         ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2858.                      (char *)host->h_name : ipaddr,
  2859.                      ipaddr,
  2860.                      uidbuf,
  2861.                      ttyfd
  2862.                      );
  2863. #endif /* CK_AUTHENTICATION */
  2864.  
  2865. #ifdef CK_SSL
  2866.         if (ck_ssleay_is_installed() && !ssl_failed) {
  2867.             if (ck_ssl_incoming(ttyfd) < 0) {
  2868. #ifdef TCPIPLIB
  2869.                     socket_close(ttyfd);
  2870.                     socket_close(tcpsrfd);
  2871. #else /* TCPIPLIB */
  2872.                     close(ttyfd);
  2873.                     close(tcpsrfd);
  2874. #endif /* TCPIPLIB */
  2875.                     ttyfd = -1;
  2876.                     wasclosed = 1;
  2877.                     tcpsrfd = -1;
  2878.                     tcpsrv_port = 0;
  2879.                     return(-1);
  2880.             }
  2881.         }
  2882. #endif /* CK_SSL */
  2883.  
  2884. #ifndef datageneral
  2885.         /* Find out our own IP address. */
  2886.         l_slen = sizeof(l_addr);
  2887.         bzero((char *)&l_addr, l_slen);
  2888. #ifndef EXCELAN
  2889.         if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  2890.             char * s = (char *)inet_ntoa(l_addr.sin_addr);
  2891.             ckstrncpy(myipaddr, s,20);
  2892.             debug(F110,"getsockname",myipaddr,0);
  2893.         }
  2894. #endif /* EXCELAN */
  2895. #endif /* datageneral */
  2896.  
  2897.         if (tn_ini() < 0)               /* Start TELNET negotiations. */
  2898.           if (ttchk() < 0) {            /* Disconnected? */
  2899.               i = errno;                /* save error code */
  2900. #ifdef TCPIPLIB
  2901.               socket_close(tcpsrfd);
  2902. #else /* TCPIPLIB */
  2903.               close(tcpsrfd);
  2904. #endif /* TCPIPLIB */
  2905.               ttyfd = -1;
  2906.               wasclosed = 1;
  2907.               tcpsrfd = -1;
  2908.               tcpsrv_port = 0;
  2909.               errno = i;                /* and report this error */
  2910.               debug(F101,"tcpsrv_open accept errno","",errno);
  2911.               return(-1);
  2912.           }
  2913.         debug(F101,"tcpsrv_open service","",x);
  2914.         if (*lcl < 0)                   /* Set local mode. */
  2915.           *lcl = 1;
  2916.  
  2917. #ifdef CK_KERBEROS
  2918. #ifdef KRB5_U2U
  2919.         if ( ttnproto == NP_K5U2U ) {
  2920.             if (k5_user_to_user_server_auth() != 0) {
  2921.                 i = errno;                /* save error code */
  2922. #ifdef TCPIPLIB
  2923.                 socket_close(tcpsrfd);
  2924. #else /* TCPIPLIB */
  2925.                 close(tcpsrfd);
  2926. #endif /* TCPIPLIB */
  2927.                 ttyfd = -1;
  2928.                 wasclosed = 1;
  2929.                 tcpsrfd = -1;
  2930.                 tcpsrv_port = 0;
  2931.                 errno = i;                /* and report this error */
  2932.                 debug(F101,"tcpsrv_open accept errno","",errno);
  2933.                 return(-1);
  2934.             }
  2935.         }
  2936. #endif /* KRB5_U2U */
  2937. #endif /* CK_KERBEROS */
  2938.  
  2939.         ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2940.         if (tcp_rdns) {
  2941.             if (!quiet) {
  2942.                 printf(" Reverse DNS Lookup... ");
  2943.                 fflush(stdout);
  2944.             }
  2945.             if (host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET)) {
  2946.                 host = ck_copyhostent(host);
  2947.                 debug(F100,"tcpsrv_open gethostbyaddr != NULL","",0);
  2948.                 if (!quiet) {
  2949.                     printf("(OK)\n");
  2950.                     fflush(stdout);
  2951.                 }
  2952.                 name[0] = '*';
  2953.                 ckstrncpy(&name[1],host->h_name,78);
  2954.                 strncat(name,":",80-strlen(name));
  2955.                 strncat(name,p,80-strlen(name));
  2956.                 if (!quiet
  2957. #ifndef NOICP
  2958.                     && !doconx
  2959. #endif /* NOICP */
  2960.                     )
  2961.                   printf("%s connected on port %s\n",host->h_name,p);
  2962.             } else {
  2963.                 if (!quiet) printf("Failed.\n");
  2964.             }
  2965.         } else if (!quiet) printf("(OK)\n");
  2966.  
  2967.         if (!tcp_rdns || !host) {
  2968.             ckstrncpy(name,ipaddr,80);
  2969.             ckstrncat(name,":",80);
  2970.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  2971.             if (!quiet
  2972. #ifndef NOICP
  2973.                 && !doconx
  2974. #endif /* NOICP */
  2975.                 )
  2976.               printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2977.         }
  2978.         if (!quiet) fflush(stdout);
  2979.         return(0);                      /* Done. */
  2980.     } else {
  2981.         i = errno;                      /* save error code */
  2982. #ifdef TCPIPLIB
  2983.         socket_close(tcpsrfd);
  2984. #else /* TCPIPLIB */
  2985.         close(tcpsrfd);
  2986. #endif /* TCPIPLIB */
  2987.         ttyfd = -1;
  2988.         wasclosed = 1;
  2989.         tcpsrfd = -1;
  2990.         tcpsrv_port = 0;
  2991.         errno = i;                      /* and report this error */
  2992.         debug(F101,"tcpsrv_open accept errno","",errno);
  2993.         return(-1);
  2994.     }
  2995. }
  2996. #endif /* NOLISTEN */
  2997. #endif /* OS2 */
  2998. #endif /* TCPSOCKET */
  2999. #endif /* NONET */
  3000.  
  3001. #ifdef TCPSOCKET
  3002. char *
  3003. ckname2addr(name) char * name; 
  3004. {
  3005. #ifdef HPUX5
  3006.     return("");
  3007. #else
  3008.     struct hostent *host;
  3009.  
  3010.     if (name == NULL || *name == '\0')
  3011.         return("");
  3012.  
  3013.     host = gethostbyname(name);
  3014.     if ( host ) {
  3015.         host = ck_copyhostent(host);
  3016.         return(inet_ntoa(*((struct in_addr *) host->h_addr)));
  3017.     }
  3018.     return("");
  3019. #endif /* HPUX5 */
  3020. }
  3021.  
  3022. char *
  3023. ckaddr2name(addr) char * addr;
  3024. {
  3025. #ifdef HPUX5
  3026.     return("");
  3027. #else
  3028.     struct hostent *host;
  3029.     struct in_addr sin_addr;
  3030.  
  3031.     if (addr == NULL || *addr == '\0')
  3032.         return("");
  3033.  
  3034.     sin_addr.s_addr = inet_addr(addr);
  3035.     host = gethostbyaddr((char *)&sin_addr,4,AF_INET);
  3036.     if (host) {
  3037.         host = ck_copyhostent(host);
  3038.         return((char *)host->h_name);
  3039.     }
  3040.     return("");
  3041. #endif /* HPUX5 */
  3042. }       
  3043. #endif /* TCPSOCKET */
  3044.  
  3045. unsigned long peerxipaddr = 0L;
  3046.  
  3047. char *
  3048. ckgetpeer() {
  3049. #ifdef TCPSOCKET
  3050.     static char namebuf[256];
  3051.     static struct hostent *host;
  3052.     static struct sockaddr_in saddr;
  3053. #ifdef PTX
  3054.     static size_t saddrlen;
  3055. #else
  3056. #ifdef AIX42
  3057.     /* It's size_t in 4.2 but int in 4.1 and earlier. */
  3058.     /* Note: the 4.2 man page lies; believe socket.h. */
  3059.     static size_t saddrlen;
  3060. #else
  3061. #ifdef UNIXWARE
  3062.     static size_t saddrlen;
  3063. #else  /* UNIXWARE */
  3064. #ifdef DEC_TCPIP
  3065.     static unsigned int saddrlen;
  3066. #else
  3067.     static int saddrlen;
  3068. #endif /* VMS */
  3069. #endif /* UNIXWARE */
  3070. #endif /* AIX42 */
  3071. #endif /* PTX */
  3072.     saddrlen = sizeof(saddr);
  3073.     if (getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen) < 0) {
  3074.         debug(F111,"ckgetpeer failure",ckitoa(ttyfd),errno);
  3075.         return(NULL);
  3076.     }
  3077.     host = gethostbyaddr((char *)&saddr.sin_addr,4,AF_INET);
  3078.     if (host) {
  3079.         host = ck_copyhostent(host);
  3080.         ckstrncpy(namebuf,(char *)host->h_name,80);
  3081.     } else {
  3082.         ckstrncpy(namebuf,(char *)inet_ntoa(saddr.sin_addr),80);
  3083.     }
  3084.     peerxipaddr = ntohl(saddr.sin_addr.s_addr);
  3085.     debug(F111,"ckgetpeer",namebuf,peerxipaddr);
  3086.     return(namebuf);
  3087. #else
  3088.     return(NULL);
  3089. #endif /* TCPSOCKET */
  3090. }
  3091.  
  3092. #ifndef NONET
  3093.  
  3094. char *
  3095. #ifdef CK_ANSIC
  3096. ckgetfqhostname(char * name)
  3097. #else
  3098. ckgetfqhostname(name) char * name;
  3099. #endif /* CK_ANSIC */
  3100. {
  3101.     static char namebuf[256];
  3102.     struct hostent *host=NULL;
  3103.     struct sockaddr_in r_addr;
  3104.     int i;
  3105.  
  3106.     debug(F110,"ckgetfqhn()",name,0);
  3107.  
  3108.     ckstrncpy(namebuf,name,256);
  3109.     namebuf[255] = '\0';
  3110.     i = ckindex(":",namebuf,0,0,0);
  3111.     if (i)
  3112.       namebuf[i-1] = '\0';
  3113.  
  3114.     bzero((char *)&r_addr, sizeof(r_addr));
  3115.  
  3116.     host = gethostbyname(namebuf);
  3117.     if (host) {
  3118.         host = ck_copyhostent(host);
  3119.         debug(F100,"ckgetfqhn() gethostbyname != NULL","",0);
  3120.         r_addr.sin_family = host->h_addrtype;
  3121. #ifdef HADDRLIST
  3122. #ifdef h_addr
  3123.         /* This is for trying multiple IP addresses - see <netdb.h> */
  3124.         if (!(host->h_addr_list))
  3125.           goto exit_func;
  3126.         bcopy(host->h_addr_list[0],
  3127.               (caddr_t)&r_addr.sin_addr,
  3128.               host->h_length
  3129.               );
  3130. #else
  3131.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3132. #endif /* h_addr */
  3133. #else  /* HADDRLIST */
  3134.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3135. #endif /* HADDRLIST */
  3136. #ifndef EXCELAN
  3137.         debug(F111,"BCOPY","host->h_addr",host->h_addr);
  3138. #endif /* EXCELAN */
  3139.         debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  3140.               (caddr_t)&r_addr.sin_addr);
  3141.         debug(F111,"BCOPY","host->h_length",host->h_length);
  3142.  
  3143. #ifdef NT
  3144.         /* Windows 95/98 requires a 1 second wait between calls to Microsoft */
  3145.         /* provided DNS functions.  Otherwise, the TTL of the DNS response */
  3146.         /* is ignored. */
  3147.         if (isWin95())
  3148.           sleep(1);
  3149. #endif /* NT */
  3150.         host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET);
  3151.         if (host) {
  3152.             host = ck_copyhostent(host);
  3153.             debug(F100,"ckgetfqhn() gethostbyaddr != NULL","",0);
  3154.             ckstrncpy(namebuf, host->h_name, 256);
  3155.         }
  3156.     }
  3157.  
  3158. #ifdef HADDRLIST
  3159. #ifdef h_addr
  3160.   exit_func:
  3161. #endif /* h_addr */
  3162. #endif /* HADDRLIST */
  3163.  
  3164.     if (i > 0)
  3165.       strncat(namebuf,&name[i-1],256-strlen(namebuf)-strlen(&name[i-1]));
  3166.     debug(F110,"ckgetfqhn()",namebuf,0);
  3167.     return(namebuf);
  3168. }
  3169.  
  3170. VOID
  3171. #ifdef CK_ANSIC
  3172. setnproto(char * p)
  3173. #else
  3174. setnproto(p) char * p;
  3175. #endif /* CK_ANSIC */
  3176. {
  3177.     if (!isdigit(*p)) {
  3178.         if (!strcmp("kermit",p))
  3179.           ttnproto = NP_KERMIT;
  3180.         else if (!strcmp("telnet",p))
  3181.           ttnproto = NP_TELNET;
  3182.         else if (!strcmp("http",p))
  3183.           ttnproto = NP_TCPRAW;
  3184. #ifdef RLOGCODE
  3185.         else if (!strcmp("login",p))
  3186.           ttnproto = NP_RLOGIN;
  3187. #endif /* RLOGCODE */
  3188. #ifdef CK_SSL
  3189.         /* Commonly used SSL ports (might not be in services file) */
  3190.         else if (!strcmp("https",p)) {
  3191.           ttnproto = NP_SSL;
  3192.           ssl_only_flag = 1;
  3193.         } else if (!strcmp("ssl-telnet",p)) {
  3194.           ttnproto = NP_TELNET;
  3195.           ssl_only_flag = 1;
  3196.         } else if (!strcmp("telnets",p)) {
  3197.           ttnproto = NP_TELNET;
  3198.           ssl_only_flag = 1;
  3199.         }
  3200. #endif /* CK_SSL */
  3201. #ifdef CK_KERBEROS
  3202. #ifdef RLOGCODE
  3203.         else if (!strcmp("klogin",p)) {
  3204.             if (ck_krb5_is_installed())
  3205.               ttnproto = NP_K5LOGIN;
  3206.             else if (ck_krb4_is_installed())
  3207.               ttnproto = NP_K4LOGIN;
  3208.             else
  3209.               ttnproto = NP_RLOGIN;
  3210.         } else if (!strcmp("eklogin",p)) {
  3211.             if (ck_krb5_is_installed())
  3212.               ttnproto = NP_EK5LOGIN;
  3213.             else if (ck_krb4_is_installed())
  3214.               ttnproto = NP_EK4LOGIN;
  3215.             else
  3216.               ttnproto = NP_RLOGIN;
  3217.         }
  3218. #endif /* RLOGCODE */
  3219. #endif /* CK_KERBEROS */
  3220.         else
  3221.           ttnproto = NP_NONE;
  3222.     } else {
  3223.         switch (atoi(p)) {
  3224.           case 23:                      /* Telnet */
  3225.             ttnproto = NP_TELNET;
  3226.             break;
  3227.           case 513:
  3228.             ttnproto = NP_RLOGIN;
  3229.             break;
  3230.           case 1649:
  3231.             ttnproto = NP_KERMIT;
  3232.             break;
  3233. #ifdef CK_SSL
  3234.           case 443:
  3235.             ttnproto = NP_SSL;
  3236.             ssl_only_flag = 1;
  3237.             break;
  3238.           case 151:
  3239.           case 992:
  3240.             ttnproto = NP_TELNET;
  3241.             ssl_only_flag = 1;
  3242.             break;
  3243. #endif /* CK_SSL */
  3244. #ifdef CK_KERBEROS
  3245.           case 543:
  3246.             if (ck_krb5_is_installed())
  3247.               ttnproto = NP_K5LOGIN;
  3248.             else if (ck_krb4_is_installed())
  3249.               ttnproto = NP_K4LOGIN;
  3250.             else
  3251.               ttnproto = NP_RLOGIN;
  3252.             break;
  3253.           case 2105:
  3254.             if (ck_krb5_is_installed())
  3255.               ttnproto = NP_EK5LOGIN;
  3256.             else if (ck_krb4_is_installed())
  3257.               ttnproto = NP_EK4LOGIN;
  3258.             else
  3259.               ttnproto = NP_RLOGIN;
  3260.             break;
  3261. #endif /* CK_KERBEROS */
  3262.           case 80:                      /* HTTP */
  3263.             ttnproto = NP_TCPRAW;
  3264.             break;
  3265.           default:
  3266.             ttnproto = NP_NONE;
  3267.             break;
  3268.         }
  3269.     }
  3270. }
  3271.  
  3272. /* ckgetservice() is used to determine the port number for a given */
  3273. /* service taking into account the use of DNS SRV records.         */
  3274.  
  3275. static struct servent servrec;
  3276. static struct servent *
  3277. ckgetservice(hostname, servicename, ip, iplen)
  3278.     char *hostname; char * servicename; char * ip; int iplen;
  3279. {
  3280.     struct servent * service = NULL;
  3281. #ifdef CK_DNS_SRV
  3282.     struct sockaddr * dns_addrs = NULL;
  3283.     int dns_naddrs = 0;
  3284. #endif /* CK_DNS_SRV */
  3285.  
  3286.     if (isdigit(*servicename)) {    /* Use socket number without lookup */
  3287.         service = &servrec;
  3288.         service->s_port = htons((unsigned short)atoi(servicename));
  3289.     } else {                            /* Otherwise lookup the service name */
  3290. #ifdef CK_DNS_SRV
  3291.         if (tcp_dns_srv && !quiet) {
  3292.             printf(" DNS SRV Lookup... ");
  3293.             fflush(stdout);
  3294.         }
  3295.         if (tcp_dns_srv &&
  3296.             locate_srv_dns(hostname,
  3297.                servicename,
  3298.                "tcp",
  3299.                &dns_addrs,
  3300.                &dns_naddrs
  3301.                )
  3302.         ) {
  3303.             /* Use the first one.  Eventually we should cycle through all */
  3304.             /* the returned IP addresses and port numbers. */
  3305.             struct sockaddr_in *sin = NULL;
  3306. #ifdef BETADEBUG
  3307.             int i;
  3308.             printf("\r\n");
  3309.             for ( i=0;i<dns_naddrs;i++ ) {
  3310.                 sin = (struct sockaddr_in *) &dns_addrs[i];
  3311.                 printf("dns_addrs[%d] = %s %d\r\n", i,
  3312.                         (char *)inet_ntoa(sin->sin_addr),
  3313.                         ntohs(sin->sin_port));
  3314.             }
  3315. #endif /* BETADEBUG */
  3316.             sin = (struct sockaddr_in *) &dns_addrs[0];
  3317.             if ( ip && iplen > 0 )
  3318.                 ckstrncpy(ip,(char *)inet_ntoa(sin->sin_addr),iplen);
  3319.             service = &servrec;
  3320.             service->s_port = sin->sin_port;
  3321.  
  3322.             free(dns_addrs);
  3323.             dns_addrs = NULL;
  3324.             dns_naddrs = 0;
  3325.         } else
  3326. #endif /* CK_DNS_SRV */
  3327.             service = getservbyname(servicename, "tcp");
  3328.     }
  3329.     if (!service) {
  3330.         if (!ckstrcmp("kermit",servicename,-1,0)) { /* Kermit service port */
  3331.             service = &servrec;
  3332.             service->s_port = htons(1649);
  3333.         } else if (!ckstrcmp("telnet",servicename,-1,0)) { /* Telnet port */
  3334.             service = &servrec;
  3335.             service->s_port = htons(23);
  3336.         } else if (!ckstrcmp("http",servicename,-1,0)) {
  3337.             service = &servrec;
  3338.             service->s_port = htons(80);
  3339.         }
  3340. #ifdef RLOGCODE
  3341.         else if (!ckstrcmp("login",servicename,-1,0)) {
  3342.             service = &servrec;
  3343.             service->s_port = htons(513);
  3344.         }
  3345. #endif /* RLOGCODE */
  3346. #ifdef CK_SSL
  3347.         /* Commonly used SSL ports (might not be in services file) */
  3348.         else if (!ckstrcmp("https",servicename,-1,0)) {
  3349.             service = &servrec;
  3350.             service->s_port = htons(443);
  3351.         } else if (!ckstrcmp("ssl-telnet",servicename,-1,0)) {
  3352.             service = &servrec;
  3353.             service->s_port = htons(151);
  3354.         } else if (!ckstrcmp("telnets",servicename,-1,0)) {
  3355.             service = &servrec;
  3356.             service->s_port = htons(992);
  3357.         }
  3358. #endif /* CK_SSL */
  3359. #ifdef CK_KERBEROS
  3360. #ifdef RLOGCODE
  3361.         else if (!ckstrcmp("klogin",servicename,-1,0)) {
  3362.             service = &servrec;
  3363.             service->s_port = htons(543);
  3364.         } else if (!ckstrcmp("eklogin",servicename,-1,0)) {
  3365.             service = &servrec;
  3366.             service->s_port = htons(2105);
  3367.         }
  3368. #endif /* RLOGCODE */
  3369. #endif /* CK_KERBEROS */
  3370.     }
  3371.     return(service);
  3372. }
  3373.  
  3374. /*  N E T O P E N  --  Open a network connection  */
  3375. /*
  3376.   Calling conventions same as ttopen(), except third argument is network
  3377.   type rather than modem type.  Designed to be called from within ttopen.
  3378. */
  3379.  
  3380. int
  3381. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  3382.     char *p;
  3383.     int i, x, dns = 0;
  3384. #ifdef TCPSOCKET
  3385.     int isconnect = 0;
  3386. #ifdef SO_OOBINLINE
  3387.     int on = 1;
  3388. #endif /* SO_OOBINLINE */
  3389.     struct servent *service=NULL;
  3390.     struct hostent *host=NULL;
  3391.     struct sockaddr_in r_addr;
  3392.     struct sockaddr_in sin;
  3393.     struct sockaddr_in l_addr;
  3394.     GSOCKNAME_T l_slen;
  3395. #ifdef EXCELAN
  3396.     struct sockaddr_in send_socket;
  3397. #endif /* EXCELAN */
  3398.  
  3399. #ifdef INADDRX
  3400. /* inet_addr() is of type struct in_addr */
  3401. #ifdef datageneral
  3402.     extern struct in_addr inet_addr();
  3403. #else
  3404. #ifdef HPUX5WINTCP
  3405.     extern struct in_addr inet_addr();
  3406. #endif /* HPUX5WINTCP */
  3407. #endif /* datageneral */
  3408.     struct in_addr iax;
  3409. #else
  3410. #ifdef INADDR_NONE
  3411.     struct in_addr iax;
  3412. #else /* INADDR_NONE */
  3413.     long iax;
  3414. #endif /* INADDR_NONE */
  3415. #endif /* INADDRX */
  3416. #endif /* TCPSOCKET */
  3417.  
  3418. #ifdef COMMENT
  3419. /* This causes big trouble */
  3420. #ifndef INADDR_NONE
  3421. #define INADDR_NONE 0xffffffff
  3422. #endif /* INADDR_NONE */
  3423. #endif /* COMMENT */
  3424.  
  3425. #ifdef SUNX25                           /* Code for SunLink X.25 support */
  3426. #define X29PID 1                        /* X.29 Protocol ID */
  3427. _PROTOTYP(SIGTYP x25oobh, (int) );
  3428.     CONN_DB x25host;
  3429. #ifndef X25_WR_FACILITY
  3430.     FACILITY x25facil;
  3431. #else
  3432.     FACILITY_DB x25facil;
  3433. #endif /* X25_WR_FACILITY */
  3434.     static int needh = 1;
  3435.     PID_T pid;
  3436.     extern int linkid, lcn, x25ver;
  3437. #endif /* SUNX25 */
  3438. #ifdef ANYX25
  3439.     extern int revcall, closgr, cudata;
  3440.     extern char udata[];
  3441. #endif /* ANYX25 */
  3442.  
  3443. #ifdef IBMX25                           /* Variables for IBM X25 */
  3444.     extern int x25port;                 /* Logical port to use */
  3445.     extern x25addr_t local_nua;         /* Local X.25 address */
  3446.     extern x25addr_t remote_nua;        /* Remote X.25 address */
  3447.     extern char x25name[];              /* X25 device name (sx25a0) */
  3448.     extern char x25dev[];               /* X25 device file /dev/x25pkt */
  3449.     ulong bind_flags = 0;               /* Flags for binding the X25 stream */
  3450.     ulong token = 0;                    /* Temporary return code */
  3451. #endif /* IBMX25 */
  3452.  
  3453.     debug(F101,"netopen nett","",nett);
  3454.     *ipaddr = '\0';                     /* Initialize IP address string */
  3455.  
  3456. #ifdef SUNX25
  3457.     if (nett == NET_SX25) {             /* If network type is X.25 */
  3458.         netclos();                      /* Close any previous net connection */
  3459.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3460.  
  3461.         /* Set up host structure */
  3462.         bzero((char *)&x25host,sizeof(x25host));
  3463.         if ((x25host.hostlen = pkx121(name,x25host.host)) < 0) {
  3464.             fprintf (stderr,"Invalid X.121 host address %s\n",name);
  3465.             errno = 0;
  3466.             return (-1);
  3467.         }
  3468.         x25host.datalen = X29PIDLEN;
  3469.         x25host.data[0] = X29PID;
  3470.  
  3471.         /* Set call user data if specified */
  3472.         if (cudata) {
  3473.             ckstrncpy((char *)x25host.data+X29PIDLEN,udata,(int)strlen(udata));
  3474.             x25host.datalen += (int)strlen(udata);
  3475.         }
  3476.  
  3477.         /* Open SunLink X.25 socket */
  3478.         if (!quiet && *name) {
  3479.             printf(" Trying %s... ", name);
  3480.             fflush(stdout);
  3481.         }
  3482.         if ((ttyfd = socket(AF_X25, SOCK_STREAM, 0)) < 0) {
  3483.             debug(F101,"netopen socket error","",errno);
  3484.             perror ("X.25 socket error");
  3485.             return (-1);
  3486.         }
  3487.  
  3488.         /* Setting X.25 out-of-band data handler */
  3489.         pid = getpid();
  3490.         if (ioctl(ttyfd,SIOCSPGRP,&pid)) {
  3491.             perror("X.25 set process group id error");
  3492.             return(-1);
  3493.         }
  3494.         (VOID) signal(SIGURG,x25oobh);
  3495.  
  3496.         /* Set reverse charge call and closed user group if requested */
  3497.         bzero ((char *)&x25facil,sizeof(x25facil));
  3498.  
  3499. #ifndef X25_WR_FACILITY
  3500. /*  New SunLink (7.0 or 8.0, not sure which)... */
  3501.         x25facil.type = T_REVERSE_CHARGE; /* Reverse Charge */
  3502.         x25facil.f_reverse_charge = revcall ? 1 : 0;
  3503.         if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3504.             perror ("Setting X.25 reverse charge");
  3505.             return (-1);
  3506.         }
  3507.         if (closgr > -1) {              /* Closed User Group (Outgoing) */
  3508.             bzero ((char *)&x25facil,sizeof(x25facil));
  3509.             x25facil.type = T_CUG;
  3510.             x25facil.f_cug_req = CUG_REQ_ACS;
  3511.             x25facil.f_cug_index = closgr;
  3512.             if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3513.                 perror ("Setting X.25 closed user group");
  3514.                 return (-1);
  3515.             }
  3516.         }
  3517. #else
  3518. /*  Old SunLink 6.0 (or 7.0?)... */
  3519.         if (revcall) x25facil.reverse_charge = revcall;
  3520.         if (closgr > -1) {
  3521.             x25facil.cug_req = 1;
  3522.             x25facil.cug_index = closgr;
  3523.         }
  3524.         if (ioctl(ttyfd,X25_WR_FACILITY,&x25facil) < 0) {
  3525.             perror ("Setting X.25 facilities");
  3526.             return (-1);
  3527.         }
  3528. #endif /* X25_WR_FACILITY */
  3529.  
  3530.         /*  Need X.25 header with bits Q and M */
  3531.         if (ioctl (ttyfd,X25_HEADER,&needh) < 0) {
  3532.             perror ("Setting X.25 header");
  3533.             return (-1);
  3534.         }
  3535.  
  3536.         /* Connects to remote host via SunLink X.25 */
  3537.         if (connect(ttyfd,(struct sockaddr *)&x25host,sizeof(x25host)) < 0) {
  3538.             i = errno;
  3539.             debug(F101,"netopen connect errno","",i);
  3540.             if (i) {
  3541.                 perror("netopen x25 connect");
  3542.                 x25diag();
  3543.             }
  3544.             (VOID) netclos();
  3545.             ttyfd = -1;
  3546.             wasclosed = 1;
  3547.             ttnproto = NP_NONE;
  3548.             errno = i;
  3549.             return (-1);
  3550.         }
  3551.  
  3552.         /* Get X.25 link identification used for the connection */
  3553.         if (ioctl(ttyfd,X25_GET_LINK,&linkid) < 0) {
  3554.             perror ("Getting X.25 link id");
  3555.             return (-1);
  3556.         }
  3557.  
  3558.         /* Get X.25 logical channel number used for the connection */
  3559.         if (ioctl(ttyfd,X25_RD_LCGN,&lcn) < 0) {
  3560.             perror ("Getting X.25 lcn");
  3561.             return (-1);
  3562.         }
  3563.  
  3564.         /* Get SunLink X.25 version */
  3565.         if (ioctl(ttyfd,X25_VERSION,&x25ver) < 0) {
  3566.             perror ("Getting SunLink X.25 version");
  3567.             return (-1);
  3568.         }
  3569.         ttnet = nett;                   /* Sunlink X.25 network */
  3570.         ttnproto = NP_X3;               /* PAD X.3, X.28, X.29 protocol */
  3571.     if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3572.         return(0);
  3573.     } else /* Note that SUNX25 support can coexist with TCP/IP support. */
  3574. #endif /* SUNX25 */
  3575.  
  3576. #ifdef IBMX25
  3577.     /* riehm */
  3578.     if (nett == NET_IX25) {             /* IBM AIX X.25 */
  3579.         netclos();                      /* Close any previous net connection */
  3580.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3581.  
  3582.         /* find out who we are - this is not so easy on AIX */
  3583.         /* riehm: need to write the code that finds this out
  3584.          * automatically, or at least allow it to be configured
  3585.          * somehow
  3586.          */
  3587.         if (!local_nua[0] && !x25local_nua(local_nua)) {
  3588.             return(-1);
  3589.         }
  3590.  
  3591.         /* Initialise the X25 API (once per process? once per connection?) */
  3592.  
  3593.         debug(F110, "Opening ", x25dev, 0 );
  3594.         /* set O_NDELAY to allow polling? */
  3595.         if ((ttyfd = open(x25dev, O_RDWR)) < 0) {
  3596.             perror ("X.25 device open error");
  3597.             debug(F101,"netopen: device open error","",errno);
  3598.             return (-1);
  3599.         }
  3600.  
  3601.         /* push the NPI onto the STREAM */
  3602.         if (ioctl(ttyfd,I_PUSH,"npi") < 0 ) {
  3603.             close(ttyfd);
  3604.             ttyfd = -1;
  3605.             wasclosed = 1;
  3606.             perror( "kermit: netopen(): couldn't push npi on the X25 stream" );
  3607.             debug(F101,"netopen: can't push npi on the X25 stream","",errno);
  3608.             return (-1);
  3609.         }
  3610.  
  3611.         /* set up server mode - bind the x25 port and wait for
  3612.          * incoming connections
  3613.          */
  3614.         if (name[0] == '*') {           /* Server */
  3615.             /* set up a server - see the warning in x25bind() */
  3616.             bind_flags |= TOKEN_REQUEST;
  3617.  
  3618.             /* bind kermit to the local X25 address */
  3619.             token = x25bind(ttyfd,
  3620.                             local_nua,
  3621.                             udata,
  3622.                             (int)strlen( udata ),
  3623.                             1,
  3624.                             x25port,
  3625.                             bind_flags
  3626.                             );
  3627.             if (token < 0) {
  3628.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3629.                 netclos();
  3630.                 return(-1);
  3631.             }
  3632.             /* Currently not connected to a remote host */
  3633.  
  3634.             remote_nua[0] = '\0';
  3635.  
  3636.             /* store the fd so that incoming calls can have their own fd
  3637.              * This is almost support for a true server (ie: a'la ftpd)
  3638.              * but we're not quite there yet.
  3639.              * used in netclos()
  3640.              */
  3641.             x25serverfd = ttyfd;
  3642.             /*
  3643.              * wait for an incoming call
  3644.              * this should happen in the "server" command and not in
  3645.              * the "set host *" command.
  3646.              */
  3647.             if ((ttyfd = x25getcall(ttyfd)) < 0) {
  3648.                 netclos();
  3649.                 return(-1);
  3650.             }
  3651.         } else {                        /* Client */
  3652.             /* Bind kermit to the local X25 address */
  3653.             token = x25bind(
  3654.                             ttyfd,
  3655.                             local_nua,
  3656.                             (char *)NULL,
  3657.                             0,
  3658.                             0,
  3659.                             x25port,
  3660.                             bind_flags
  3661.                             );
  3662.             if (token < 0) {
  3663.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3664.                 netclos();
  3665.                 return(-1);
  3666.             }
  3667. /* riehm: this should be done via the CONNECT command, not HOST! */
  3668.             {
  3669.                 x25serverfd = 0;
  3670.                 /* call the remote host */
  3671.                 /* name == address of remote host as char* */
  3672.                 if (x25call(ttyfd, name, udata) < 0 ) {
  3673.                     debug(F100,
  3674.                           "netopen: couldn't connect to remote X25 address",
  3675.                           "", 0);
  3676.                     netclos();
  3677.                     return(-1);
  3678.                 }
  3679.                 strcpy(remote_nua, name);
  3680.             }
  3681.         }
  3682.         ttnet = nett;                   /* AIX X.25 network */
  3683.         if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3684.         return(0);
  3685.  
  3686.     } else /* Note that IBMX25 support can coexist with TCP/IP support. */
  3687. #endif /* IBMX25 */
  3688.  
  3689. /*   Add support for other networks here. */
  3690.  
  3691.       if (nett != NET_TCPB) return(-1); /* BSD socket support */
  3692.  
  3693. #ifdef TCPSOCKET
  3694.     netclos();                          /* Close any previous connection. */
  3695.     ckstrncpy(namecopy, name, NAMECPYL);        /* Copy the hostname. */
  3696.     debug(F110,"netopen namecopy",namecopy,0);
  3697.  
  3698. #ifndef NOLISTEN
  3699.     if (name[0] == '*')
  3700.       return(tcpsrv_open(name, lcl, nett, 0));
  3701. #endif /* NOLISTEN */
  3702.  
  3703.     p = namecopy;                       /* Was a service requested? */
  3704.     while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3705.     if (*p == ':') {                    /* Have a colon */
  3706.         debug(F110,"netopen name has colon",namecopy,0);
  3707.         *p++ = '\0';                    /* Get service name or number */
  3708. #ifdef CK_URL
  3709.         /*
  3710.            Here we have to check for various popular syntaxes:
  3711.            host:port (our original syntax)
  3712.            URL such as telnet:host or telnet://host/
  3713.            Or even telnet://user:password@host:port/path/
  3714.            Or a malformed URL such as generated by Netscape 4.0 like:
  3715.            telnet:telnet or telnet::host.
  3716.         */
  3717.  
  3718.         /* 
  3719.          * REPLACE THIS CODE WITH urlparse() but not on the day of the 
  3720.          * C-Kermit 8.0 RELEASE.
  3721.          */
  3722.  
  3723.         if (*p == ':')                  /* a second colon */
  3724.           *p++ = '\0';                  /* get rid of that one too */
  3725.         while (*p == '/') *p++ = '\0';  /* and slashes */
  3726.         x = strlen(p);                  /* Length of remainder */
  3727.         if (p[x-1] == '/')              /* If there is a trailing slash */
  3728.           p[x-1] = '\0';                /* remove it. */
  3729.         debug(F110,"netopen namecopy after stripping",namecopy,0);
  3730.         debug(F110,"netopen p after stripping",p,0);
  3731.         service = getservbyname(namecopy,"tcp");
  3732.         if (service ||
  3733. #ifdef RLOGCODE
  3734.             !ckstrcmp("rlogin",namecopy,NAMECPYL,0) ||
  3735. #endif /* RLOGCODE */
  3736. #ifdef CK_SSL
  3737.             !ckstrcmp("telnets",namecopy,NAMECPYL,0) ||
  3738. #endif /* CK_SSL */
  3739.             !ckstrcmp("iksd",namecopy,NAMECPYL,0)
  3740.         ) {
  3741.             char temphost[256], tempservice[80], temppath[256];
  3742.             char * q = p, *r = p, *w = p;
  3743.             int uidfound=0;
  3744.             extern char pwbuf[];
  3745.             extern int pwflg, pwcrypt;
  3746.  
  3747.             if (ttnproto == NP_DEFAULT)
  3748.           setnproto(namecopy);
  3749.  
  3750.             /* Check for userid and possibly password */
  3751.             while (*p != '\0' && *p != '@')
  3752.                 p++; /* look for @ */
  3753.             if (*p == '@') {
  3754.                 /* found username and perhaps password */
  3755.                 debug(F110,"netopen namecopy found @","",0);
  3756.                 *p = '\0';
  3757.                 p++;
  3758.                 while (*w != '\0' && *w != ':')
  3759.                   w++;
  3760.                 if (*w == ':')
  3761.                   *w++ = '\0';
  3762.                 /* r now points to username, save it and the password */
  3763.                 debug(F110,"netopen namecopy username",r,0);
  3764.                 debug(F110,"netopen namecopy password",w,0);
  3765.                 uidfound=1;
  3766.                 if ( strcmp(uidbuf,r) || *w )
  3767.                     ckstrncpy(pwbuf,w,PWBUFL+1);
  3768.                 ckstrncpy(uidbuf,r,UIDBUFLEN);
  3769.                 pwflg = 1;
  3770.                 pwcrypt = 0;
  3771.                 q = p;                  /* Host after user and pwd */
  3772.             } else {
  3773.                 p = q;                  /* No username or password */
  3774.             }
  3775.             /* Now we must look for the optional port. */
  3776.             debug(F110,"netopen x p",p,0);
  3777.             debug(F110,"netopen x q",q,0);
  3778.  
  3779.             /* Look for the port/service or a file/directory path */
  3780.             while (*p != '\0' && *p != ':' && *p != '/')
  3781.               p++;
  3782.             if (*p == ':') {
  3783.                 debug(F110,"netopen found port",q,0);
  3784.                 *p++ = '\0';            /* Found a port name or number */
  3785.                 r = p;
  3786.  
  3787.                 /* Look for the end of port/service or a file/directory path */
  3788.                 while (*p != '\0' && *p != '/')
  3789.                     p++;
  3790.                 if (*p == '/')
  3791.                     *p++ = '\0';
  3792.  
  3793.                 debug(F110,"netopen port",r,0);
  3794.                 ckstrncpy(tempservice,r,80);
  3795.                 ckstrncpy(temphost,q,256);
  3796.                 ckstrncpy(temppath,p,256);
  3797.                 ckstrncpy(namecopy,temphost,NAMECPYL);
  3798.                 debug(F110,"netopen tempservice",tempservice,0);
  3799.                 debug(F110,"netopen temphost",temphost,0);
  3800.                 debug(F110,"netopen temppath",temppath,0);
  3801.  
  3802.                 /* move port/service to a buffer that won't go away */
  3803.                 x = strlen(namecopy);
  3804.                 p = namecopy + x + 1;
  3805.                 ckstrncpy(p, tempservice, NAMECPYL - x);
  3806.             } else {
  3807.                 /* Handle a path if we found one */
  3808.                 if (*p == '/')
  3809.                     *p++ = '\0';
  3810.                 ckstrncpy(temppath,p,256);
  3811.  
  3812.                 /* We didn't find another port, but if q is a service */
  3813.                 /* then assume that namecopy is actually a host.      */
  3814.                 if (getservbyname(q,"tcp")) {
  3815.                     p = q;
  3816.                 } else {
  3817. #ifdef RLOGCODE
  3818.                     /* rlogin is not a valid service */
  3819.                     if (!ckstrcmp("rlogin",namecopy,6,0)) {
  3820.                         ckstrncpy(namecopy,"login",NAMECPYL);
  3821.                     }
  3822. #endif /* RLOGCODE */
  3823.                     /* iksd is not a valid service */
  3824.                     if (!ckstrcmp("iksd",namecopy,6,0)) {
  3825.                         ckstrncpy(namecopy,"kermit",NAMECPYL);
  3826.                     }
  3827.                     /* Reconstruct namecopy */
  3828.                     ckstrncpy(tempservice,namecopy,80);
  3829.                     ckstrncpy(temphost,q,256);
  3830.                     ckstrncpy(namecopy,temphost,NAMECPYL);
  3831.                     debug(F110,"netopen tempservice",tempservice,0);
  3832.                     debug(F110,"netopen temphost",temphost,0);
  3833.                     debug(F110,"netopen temppath",temppath,0);
  3834.  
  3835.                     /* move port/service to a buffer that won't go away */
  3836.                     x = strlen(namecopy);
  3837.                     p = namecopy + x + 1;
  3838.                     ckstrncpy(p, tempservice, NAMECPYL - x - 1);
  3839.                 }
  3840.             }
  3841.             debug(F110,"netopen URL result: host",namecopy,0);
  3842.             debug(F110,"netopen URL result: service",p,0);
  3843.             debug(F110,"netopen URL result: path",temppath,0);
  3844.  
  3845. #ifdef IKS_GET
  3846.             /* If we have set a path specified, we need to try to GET it */
  3847.             /* But we have another problem, we have to login first.  How */
  3848.             /* do we specify that a login must be done before the GET?   */
  3849.             /* The user's name if specified is in 'userid' and the       */
  3850.             /* password if any is in 'pwbuf'.                            */
  3851.             if ( temppath[0] ) {
  3852.                 extern int action;
  3853.                 extern char * cmarg;
  3854.  
  3855.                 if ( !uidfound ) {
  3856.                     /* If no userid was specified as part of the URL but
  3857.                      * a path was specified, then we
  3858.                      * set the user name to anonymous and the password
  3859.                      * to the current userid.
  3860.                      */
  3861.                     ckstrncpy(pwbuf,uidbuf,PWBUFL);
  3862.                     ckstrncat(pwbuf,"@",PWBUFL);
  3863.                     pwflg = 1;
  3864.                     pwcrypt = 0;
  3865.                     ckstrncpy(uidbuf,"anonymous",UIDBUFLEN);
  3866.                 }
  3867.  
  3868.                 /*
  3869.                  * If a file path was specified we perform the GET
  3870.                  * operation and then terminate the connection.
  3871.                  *
  3872.                  * If a directory was given instead of a file, then
  3873.                  * we should REMOTE CD to the directory and list its
  3874.                  * contents.  But how do we tell the difference?
  3875.                  */
  3876.                 makestr(&cmarg,temppath);
  3877.                 action = 'r';
  3878.             }
  3879. #endif /* IKS_GET */
  3880.         }
  3881. #endif /* CK_URL */
  3882.     } else {                            /* Otherwise use telnet */
  3883.         p = "telnet";
  3884.     }
  3885. /*
  3886.   By the time we get here, namecopy[] should hold the null-terminated
  3887.   hostname or address, and p should point to the service name or number.
  3888. */
  3889.     debug(F110,"netopen host",namecopy,0);
  3890.     debug(F110,"netopen service requested",p,0);
  3891.  
  3892.    /* Use the service port to set the default protocol type if necessary */
  3893.     if (ttnproto == NP_DEFAULT)
  3894.        setnproto(p);
  3895.  
  3896.     service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3897.     if (!service) {
  3898.         fprintf(stderr, "Can't find port for service %s\n", p);
  3899. #ifdef TGVORWIN
  3900.         debug(F101,"netopen can't get service","",socket_errno);
  3901. #else
  3902.         debug(F101,"netopen can't get service","",errno);
  3903. #endif /* TGVORWIN */
  3904.         errno = 0;                  /* (rather than mislead) */
  3905.         return(-1);
  3906.     } else {
  3907.         ckstrncpy(svcbuf,ckuitoa(ntohs(service->s_port)),sizeof(svcbuf));
  3908.         debug(F110,"netopen service ok",svcbuf,0);
  3909.     }
  3910.  
  3911. #ifdef RLOGCODE
  3912.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  3913.         fprintf(stderr,
  3914.                 "  Warning: login service on port %d instead of port 513\n",
  3915.                  ntohs(service->s_port)
  3916.                 );
  3917.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  3918.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  3919.     }
  3920. #endif /* RLOGCODE */
  3921.  
  3922. #ifndef NOHTTP
  3923.    /* For HTTP connections we must preserve the original hostname and */
  3924.    /* service requested so we can include them in the Host header.    */
  3925.     ckmakmsg(http_host_port,sizeof(http_host_port),namecopy,":",
  3926.               ckitoa(ntohs(service->s_port)),NULL);
  3927. #endif /* NOHTTP */
  3928.  
  3929. #ifndef NOHTTP
  3930.     /* 'namecopy' contains the name of the host to which we want to connect */
  3931.     /* 'svcbuf'   contains the service name                                 */
  3932.     /* 'service->s_port' contains the port number in network byte order     */
  3933.  
  3934.     /* If we are using an http proxy, we need to create a buffer containing */
  3935.     /*   hostname:port-number                                               */
  3936.     /* to pass to the http_connect() function.  Then we need to replace     */
  3937.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  3938.     /* with the port number of the proxy (default port 80).                 */
  3939.  
  3940.     if ( tcp_http_proxy ) {
  3941.         ckmakmsg(proxycopy,sizeof(proxycopy),namecopy,":",
  3942.                  ckuitoa(ntohs(service->s_port)),NULL);
  3943.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  3944.  
  3945.         p = namecopy;                       /* Was a service requested? */
  3946.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3947.         if (*p == ':') {                    /* Have a colon */
  3948.             debug(F110,"netopen name has colon",namecopy,0);
  3949.             *p++ = '\0';                    /* Get service name or number */
  3950.         } else {
  3951.             strcpy(++p,"http");
  3952.         }
  3953.  
  3954.         service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3955.         if (!service) {
  3956.             fprintf(stderr, "Can't find port for service %s\n", p);
  3957. #ifdef TGVORWIN
  3958.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  3959. #else
  3960.             debug(F101,"netopen can't get service for proxy","",errno);
  3961. #endif /* TGVORWIN */
  3962.             errno = 0;                  /* (rather than mislead) */
  3963.             return(-1);
  3964.         }
  3965.         ckstrncpy(p,ckuitoa(ntohs(service->s_port)),NAMECPYL-(p-namecopy));
  3966.  
  3967.     }
  3968. #endif /* NOHTTP */
  3969.  
  3970.     /* Set up socket structure and get host address */
  3971.  
  3972.     bzero((char *)&r_addr, sizeof(r_addr));
  3973.     debug(F100,"netopen bzero ok","",0);
  3974. /*
  3975.    NOTE: Originally the inet_addr() check was #ifdef NT, but is enabled for
  3976.    all as of 20 Sep 97, to allow people to "set host" to a specific numeric IP
  3977.    address without going through the multihomed host sequence and winding up
  3978.    at a different place than the one requested.
  3979. */
  3980. #ifdef INADDR_NONE
  3981.     debug(F101,"netopen INADDR_NONE defined","",INADDR_NONE);
  3982. #else /* INADDR_NONE */
  3983.     debug(F100,"netopen INADDR_NONE not defined","",0);
  3984. #endif /* INADDR_NONE */
  3985. #ifdef INADDRX
  3986.     debug(F100,"netopen INADDRX defined","",0);
  3987. #else /* INADDRX */
  3988.     debug(F100,"netopen INADDRX not defined","",0);
  3989. #endif /* INADDRX */
  3990.  
  3991. #ifndef NOMHHOST
  3992. #ifdef INADDRX
  3993.     iax = inet_addr(namecopy);
  3994.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  3995. #else /* INADDRX */
  3996. #ifdef INADDR_NONE
  3997.     iax.s_addr = inet_addr(namecopy);
  3998.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  3999. #else /* INADDR_NONE */
  4000. #ifndef datageneral
  4001.     iax = (unsigned int) inet_addr(namecopy);
  4002. #else
  4003.     iax = -1L;
  4004. #endif /* datageneral */
  4005.     debug(F111,"netopen inet_addr",namecopy,iax);
  4006. #endif /* INADDR_NONE */
  4007. #endif /* INADDRX */
  4008.  
  4009.     dns = 0;
  4010.     if (
  4011. #ifdef INADDR_NONE
  4012.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  4013. #else /* INADDR_NONE */
  4014.         iax < 0
  4015. #endif /* INADDR_NONE */
  4016.         ) {
  4017.         if (!quiet) {
  4018.             printf(" DNS Lookup... ");
  4019.             fflush(stdout);
  4020.         }
  4021.         if ((host = gethostbyname(namecopy)) != NULL) {
  4022.             debug(F100,"netopen gethostbyname != NULL","",0);
  4023.             host = ck_copyhostent(host);
  4024.             dns = 1;                    /* Remember we performed dns lookup */
  4025.             r_addr.sin_family = host->h_addrtype;
  4026.             if (host->h_name && host->h_name[0]
  4027. #ifndef NOHTTP
  4028.                  && (tcp_http_proxy == NULL)
  4029. #endif /* NOHTTP */
  4030.                  ) {                   /* Copying into our argument? */
  4031.                 ckstrncpy(name,host->h_name,80);  /* Bad Bad Bad */
  4032.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4033.                     strncat(name,":",80-strlen(name));
  4034.                     strncat(name,svcbuf,80-strlen(name));
  4035.                 }
  4036.             }
  4037.  
  4038. #ifdef HADDRLIST
  4039. #ifdef h_addr
  4040.             /* This is for trying multiple IP addresses - see <netdb.h> */
  4041.             if (!(host->h_addr_list))
  4042.               return(-1);
  4043.             bcopy(host->h_addr_list[0],
  4044.                   (caddr_t)&r_addr.sin_addr,
  4045.                   host->h_length
  4046.                   );
  4047. #else
  4048.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4049. #endif /* h_addr */
  4050. #else  /* HADDRLIST */
  4051.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4052. #endif /* HADDRLIST */
  4053. #ifndef EXCELAN
  4054.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  4055. #endif /* EXCELAN */
  4056.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  4057.                   (caddr_t)&r_addr.sin_addr);
  4058.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  4059.                   r_addr.sin_addr.s_addr);
  4060.             debug(F111,"BCOPY","host->h_length",host->h_length);
  4061.         }
  4062.     }
  4063. #endif /* NOMHHOST */
  4064.  
  4065.     if (!dns) {
  4066. #ifdef INADDRX
  4067. /* inet_addr() is of type struct in_addr */
  4068.         struct in_addr ina;
  4069.         unsigned long uu;
  4070.         debug(F100,"netopen gethostbyname == NULL: INADDRX","",0);
  4071.         ina = inet_addr(namecopy);
  4072.         uu = *(unsigned int *)&ina;
  4073. #else /* Not INADDRX */
  4074. /* inet_addr() is unsigned long */
  4075.         unsigned long uu;
  4076.         debug(F100,"netopen gethostbyname == NULL: Not INADDRX","",0);
  4077.         uu = inet_addr(namecopy);
  4078. #endif /* INADDRX */
  4079.         debug(F101,"netopen uu","",uu);
  4080.         if (
  4081. #ifdef INADDR_NONE
  4082.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  4083. #else   /* INADDR_NONE */
  4084.             uu != ((unsigned long)-1)
  4085. #endif /* INADDR_NONE */
  4086.             ) {
  4087.             r_addr.sin_addr.s_addr = uu;
  4088.             r_addr.sin_family = AF_INET;
  4089.         } else {
  4090. #ifdef VMS
  4091.             fprintf(stdout, "\r\n");    /* complete any previous message */
  4092. #endif /* VMS */
  4093.             fprintf(stderr, "Can't get address for %s\n", namecopy);
  4094. #ifdef TGVORWIN
  4095.             debug(F101,"netopen can't get address","",socket_errno);
  4096. #else
  4097.             debug(F101,"netopen can't get address","",errno);
  4098. #endif /* TGVORWIN */
  4099.             errno = 0;                  /* Rather than mislead */
  4100.             return(-1);
  4101.         }
  4102.     }
  4103.  
  4104.     /* Get a file descriptor for the connection. */
  4105.  
  4106.     r_addr.sin_port = service->s_port;
  4107.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4108.     debug(F110,"netopen trying",ipaddr,0);
  4109.     if (!quiet && *ipaddr) {
  4110.         printf(" Trying %s... ", ipaddr);
  4111.         fflush(stdout);
  4112.     }
  4113.  
  4114.     /* Loop to try additional IP addresses, if any. */
  4115.  
  4116.     do {
  4117. #ifdef EXCELAN
  4118.         send_socket.sin_family = AF_INET;
  4119.         send_socket.sin_addr.s_addr = 0;
  4120.         send_socket.sin_port = 0;
  4121.         if ((ttyfd = socket(SOCK_STREAM, (struct sockproto *)0,
  4122.                             &send_socket, SO_REUSEADDR)) < 0)
  4123. #else  /* EXCELAN */
  4124. #ifdef NT
  4125. #ifdef COMMENT_X
  4126.        /*
  4127.          Must make sure that all sockets are opened in
  4128.          Non-overlapped mode since we use the standard
  4129.          C RTL functions to read and write data.
  4130.          But it doesn't seem to work as planned.
  4131.        */
  4132.           {
  4133.               int optionValue = SO_SYNCHRONOUS_NONALERT;
  4134.               if (setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
  4135.                              (char *) &optionValue, sizeof(optionValue))
  4136.                   != NO_ERROR)
  4137.                 return(-1);
  4138.           }
  4139. #endif /* COMMENT */
  4140. #endif /* NT */
  4141.  
  4142.         if ((ttyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  4143. #endif /* EXCELAN */
  4144.             {
  4145. #ifdef EXCELAN
  4146.                 experror("TCP socket error");
  4147. #else
  4148. #ifdef VMS
  4149.                 fprintf(stdout, "\r\n"); /* complete any previous stdout */
  4150. #endif /* VMS */
  4151. #ifdef TGVORWIN
  4152. #ifdef OLD_TWG
  4153.                 errno = socket_errno;
  4154. #endif /* OLD_TWG */
  4155.                 socket_perror("TCP socket error");
  4156.                 debug(F101,"netopen socket error","",socket_errno);
  4157. #else
  4158.                 perror("TCP socket error");
  4159.                 debug(F101,"netopen socket error","",errno);
  4160. #endif /* TGVORWIN */
  4161. #endif /* EXCELAN */
  4162.                 return (-1);
  4163.             }
  4164.         errno = 0;
  4165.  
  4166. #ifdef RLOGCODE
  4167.        /* Not part of the RLOGIN RFC, but the BSD implementation     */
  4168.        /* requires that the client port be a priviliged port (<1024) */
  4169.        /* on a Unix system this would require SuperUser permissions  */
  4170.        /* thereby saying that the root of the Unix system has given  */
  4171.        /* permission for this connection to be created               */
  4172.        if (service->s_port == htons((unsigned short)RLOGIN_PORT)) {
  4173.            static unsigned short lport = 1024;  /* max reserved port */
  4174. #ifdef OS2
  4175.            int s_errno;
  4176. #endif /* OS2 */
  4177.  
  4178.            lport--;                     /* Make sure we do not reuse a port */
  4179.            if (lport == 512)
  4180.              lport = 1023;
  4181.  
  4182.            sin.sin_family = AF_INET;
  4183.            if (tcp_address) {
  4184. #ifdef INADDRX
  4185.                inaddrx = inet_addr(tcp_address);
  4186.                sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4187. #else
  4188.                sin.sin_addr.s_addr = inet_addr(tcp_address);
  4189. #endif /* INADDRX */
  4190.            } else
  4191.              sin.sin_addr.s_addr = INADDR_ANY;
  4192.            while (1) {
  4193.                sin.sin_port = htons(lport);
  4194.                if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
  4195.                  break;
  4196. #ifdef OS2
  4197.                s_errno = socket_errno;
  4198.                if (s_errno && /* OS2 bind fails with 0, if already in use */
  4199. #ifdef NT
  4200.                    s_errno != WSAEADDRINUSE
  4201. #else
  4202.                    s_errno != SOCEADDRINUSE &&
  4203.                    s_errno != (SOCEADDRINUSE - SOCBASEERR)
  4204. #endif /* NT */
  4205.                    )
  4206. #else /* OS2 */
  4207. #ifdef TGVORWIN
  4208.                  if (socket_errno != EADDRINUSE)
  4209. #else
  4210.                  if (errno != EADDRINUSE)
  4211. #endif /* TGVORWIN */
  4212. #endif /* OS2 */
  4213.                    {
  4214. #ifdef COMMENT
  4215.                        printf("\nBind failed with errno %d  for port %d.\n",
  4216. #ifdef OS2
  4217.                               s_errno
  4218. #else
  4219. #ifdef TGVORWIN
  4220.                               socket_errno
  4221. #else
  4222.                               errno
  4223. #endif /* TGVORWIN */
  4224. #endif /* OS2 */
  4225.                               , lport
  4226.                               );
  4227. #ifdef OS2
  4228.                        debug(F101,"rlogin bind failed","",s_errno);
  4229. #else
  4230. #ifdef TGVORWIN
  4231.                        debug(F101,"rlogin bind failed","",socket_errno);
  4232. #ifdef OLD_TWG
  4233.                        errno = socket_errno;
  4234. #endif /* OLD_TWG */
  4235.                        socket_perror("rlogin bind");
  4236. #else
  4237.                        debug(F101,"rlogin bind failed","",errno);
  4238.                        perror("rlogin bind");
  4239. #endif /* TGVORWIN */
  4240. #endif /* OS2 */
  4241. #else  /* COMMENT */
  4242. #ifdef OS2
  4243.                        debug(F101,"rlogin bind s_errno","",s_errno);
  4244.                        perror("rlogin bind");
  4245. #else
  4246. #ifdef VMS
  4247.                        printf("\r\n");    /* complete any previous message */
  4248. #endif /* VMS */
  4249. #ifdef TGVORWIN
  4250.                        debug(F101,"rlogin bind socket_errno","",socket_errno);
  4251. #ifdef OLD_TWG
  4252.                        errno = socket_errno;
  4253. #endif /* OLD_TWG */
  4254.                        socket_perror("rlogin bind");
  4255. #else
  4256.                        debug(F101,"rlogin bind errno","",errno);
  4257.                        perror("rlogin bind");
  4258. #endif /* TGVORWIN */
  4259. #endif /* OS2 */
  4260.                        debug(F101,"rlogin local port","",lport);
  4261. #endif /* COMMENT */
  4262.                netclos();
  4263.                return -1;
  4264.            }
  4265.            lport--;
  4266.            if (lport == 512 /* lowest reserved port to use */ ) {
  4267.            printf("\nNo reserved ports available.\n");
  4268.            netclos();
  4269.            return -1;
  4270.            }
  4271.        }
  4272.            debug(F101,"rlogin lport","",lport);
  4273.            ttnproto = NP_RLOGIN;
  4274.        } else
  4275. #endif /* RLOGCODE  */
  4276.  
  4277.        /* If a specific TCP address on the local host is desired we */
  4278.        /* must bind it to the socket.                               */
  4279. #ifndef datageneral
  4280.          if (tcp_address) {
  4281.              int s_errno;
  4282.  
  4283.              debug(F110,"netopen binding socket to",tcp_address,0);
  4284.              bzero((char *)&sin,sizeof(sin));
  4285.              sin.sin_family = AF_INET;
  4286. #ifdef INADDRX
  4287.              inaddrx = inet_addr(tcp_address);
  4288.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4289. #else
  4290.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  4291. #endif /* INADDRX */
  4292.              sin.sin_port = 0;
  4293.              if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  4294.                  s_errno = socket_errno; /* Save error code */
  4295. #ifdef TCPIPLIB
  4296.                  socket_close(ttyfd);
  4297. #else /* TCPIPLIB */
  4298.                  close(ttyfd);
  4299. #endif /* TCPIPLIB */
  4300.                  ttyfd = -1;
  4301.                  wasclosed = 1;
  4302.                  errno = s_errno;       /* and report this error */
  4303.                  debug(F101,"netopen bind errno","",errno);
  4304.                  return(-1);
  4305.              }
  4306.          }
  4307. #endif /* datageneral */
  4308.  
  4309. /* Now connect to the socket on the other end. */
  4310.  
  4311. #ifdef EXCELAN
  4312.         if (connect(ttyfd, &r_addr) < 0)
  4313. #else
  4314. #ifdef NT
  4315.           WSASafeToCancel = 1;
  4316. #endif /* NT */
  4317.         if (connect(ttyfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  4318. #endif /* EXCELAN */
  4319.           {
  4320. #ifdef NT
  4321.               WSASafeToCancel = 0;
  4322. #endif /* NT */
  4323. #ifdef OS2
  4324.               i = socket_errno;
  4325. #else /* OS2 */
  4326. #ifdef TGVORWIN
  4327.               i = socket_errno;
  4328. #else
  4329.               i = errno;                /* Save error code */
  4330. #endif /* TGVORWIN */
  4331. #endif /* OS2 */
  4332. #ifdef RLOGCODE
  4333.               if (
  4334. #ifdef OS2
  4335.                  i && /* OS2 bind fails with 0, if already in use */
  4336. #ifdef NT
  4337.                  i == WSAEADDRINUSE
  4338. #else
  4339.                  (i == SOCEADDRINUSE ||
  4340.                  i == (SOCEADDRINUSE - SOCBASEERR))
  4341. #endif /* NT */
  4342. #else /* OS2 */
  4343. #ifdef TGVORWIN
  4344.                   socket_errno == EADDRINUSE
  4345. #else
  4346.                   errno == EADDRINUSE
  4347. #endif /* TGVORWIN */
  4348. #endif /* OS2 */
  4349.                   && ttnproto == NP_RLOGIN) {
  4350. #ifdef TCPIPLIB
  4351.                    socket_close(ttyfd); /* Close it. */
  4352. #else
  4353.                    close(ttyfd);
  4354. #endif /* TCPIPLIB */
  4355.                    continue;            /* Try a different lport */
  4356.                }
  4357. #endif /* RLOGCODE */
  4358. #ifdef HADDRLIST
  4359. #ifdef h_addr
  4360.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  4361.                   perror("");
  4362.                   host->h_addr_list++;
  4363.                   bcopy(host->h_addr_list[0],
  4364.                         (caddr_t)&r_addr.sin_addr,
  4365.                         host->h_length);
  4366.  
  4367.                   ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4368.                   debug(F110,"netopen h_addr_list",ipaddr,0);
  4369.                   if (!quiet && *ipaddr) {
  4370.                       printf(" Trying %s... ", ipaddr);
  4371.                       fflush(stdout);
  4372.                   }
  4373. #ifdef TCPIPLIB
  4374.                   socket_close(ttyfd); /* Close it. */
  4375. #else
  4376.                   close(ttyfd);
  4377. #endif /* TCPIPLIB */
  4378.                   continue;
  4379.               }
  4380. #endif /* h_addr */
  4381. #endif  /* HADDRLIST */
  4382.               netclos();
  4383.               ttyfd = -1;
  4384.               wasclosed = 1;
  4385.               ttnproto = NP_NONE;
  4386.               errno = i;                /* And report this error */
  4387. #ifdef EXCELAN
  4388.               if (errno) experror("netopen connect");
  4389. #else
  4390. #ifdef TGVORWIN
  4391.               debug(F101,"netopen connect error","",socket_errno);
  4392.               /* if (errno) socket_perror("netopen connect"); */
  4393. #ifdef OLD_TWG
  4394.               errno = socket_errno;
  4395. #endif /* OLD_TWG */
  4396.           if (!quiet)
  4397.         socket_perror("netopen connect");
  4398. #else /* TGVORWIN */
  4399.               debug(F101,"netopen connect errno","",errno);
  4400. #ifdef VMS
  4401.           if (!quiet)
  4402.         perror("\r\nFailed");
  4403. #else
  4404.           if (!quiet)
  4405.         perror("Failed");
  4406. #endif /* VMS */
  4407. #ifdef DEC_TCPIP
  4408.           if (!quiet)
  4409.         perror("netopen connect");
  4410. #endif /* DEC_TCPIP */
  4411. #ifdef CMU_TCPIP
  4412.           if (!quiet)
  4413.         perror("netopen connect");
  4414. #endif /* CMU_TCPIP */
  4415. #endif /* TGVORWIN */
  4416. #endif /* EXCELAN */
  4417.               return(-1);
  4418.           }
  4419. #ifdef NT
  4420.         WSASafeToCancel = 0;
  4421. #endif /* NT */
  4422.         isconnect = 1;
  4423.     } while (!isconnect);
  4424.  
  4425. #ifdef NON_BLOCK_IO
  4426.     on = 1;
  4427.     x = socket_ioctl(ttyfd,FIONBIO,&on);
  4428.     debug(F101,"netopen FIONBIO","",x);
  4429. #endif /* NON_BLOCK_IO */
  4430.  
  4431. #ifdef NT_TCP_OVERLAPPED
  4432.     OverlappedWriteInit();
  4433.     OverlappedReadInit();
  4434. #endif /* NT_TCP_OVERLAPPED */
  4435.  
  4436.     ttnet = nett;                       /* TCP/IP (sockets) network */
  4437.  
  4438. #ifndef NOHTTP
  4439.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  4440.     /* need to attempt to connect through the proxy to the actual host */
  4441.     /* If that is successful, we have to pretend that we made a direct */
  4442.     /* connection to the actual host.                                  */
  4443.  
  4444.     if ( tcp_http_proxy ) {
  4445. #ifdef OS2
  4446.     char * agent = "Kermit 95";        /* Default user agent */
  4447. #else
  4448.     char * agent = "C-Kermit";
  4449. #endif /* OS2 */
  4450.  
  4451.         if (http_connect(ttyfd,agent,NULL,
  4452.              tcp_http_proxy_user,
  4453.              tcp_http_proxy_pwd,
  4454.              0,
  4455.              proxycopy
  4456.              ) < 0) {
  4457.             netclos();
  4458.             return(-1);
  4459.         }
  4460.  
  4461.         ckstrncpy(namecopy,proxycopy,NAMECPYL);
  4462.         p = namecopy;                       /* Was a service requested? */
  4463.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  4464.         *p = '\0';
  4465.     }
  4466. #endif /* NOHTTP */
  4467.  
  4468.     /* Jeff - Does this next block of code that set's the protocol */
  4469.     /* need to be here anymore?  5/10/2000                         */
  4470.  
  4471.     /* There are certain magic port numbers that when used require */
  4472.     /* the use of specific protocols.  Check this now before we    */
  4473.     /* set the SO_OOBINLINE state or we might get it wrong.        */
  4474.     x = ntohs((unsigned short)service->s_port);
  4475.     svcnum = x;
  4476.     /* See if the service is TELNET. */
  4477.     if (x == TELNET_PORT) {
  4478.     /* Yes, so if raw port not requested */
  4479.         if (ttnproto != NP_TCPRAW && ttnproto != NP_NONE)
  4480.           ttnproto = NP_TELNET;         /* Select TELNET protocol. */
  4481.     }
  4482. #ifdef RLOGCODE
  4483.     else if (x == RLOGIN_PORT) {
  4484.         ttnproto = NP_RLOGIN;
  4485.     }
  4486. #ifdef CK_KERBEROS
  4487.     /* There is no good way to do this.  If the user didn't tell    */
  4488.     /* which one to use up front.  We may guess wrong if the user   */
  4489.     /* has both Kerberos versions installed and valid TGTs for each */
  4490.     else if (x == KLOGIN_PORT &&
  4491.              ttnproto != NP_K4LOGIN &&
  4492.              ttnproto != NP_K5LOGIN) {
  4493.         if (ck_krb5_is_installed() &&
  4494.             ck_krb5_is_tgt_valid())
  4495.           ttnproto = NP_K5LOGIN;
  4496.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4497.           ttnproto = NP_K4LOGIN;
  4498.         else
  4499.           ttnproto = NP_K4LOGIN;
  4500.     } else if (x == EKLOGIN_PORT &&
  4501.                ttnproto != NP_EK4LOGIN &&
  4502.                ttnproto != NP_EK5LOGIN) {
  4503.         if (ck_krb5_is_installed() && ck_krb5_is_tgt_valid())
  4504.           ttnproto = NP_EK5LOGIN;
  4505.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4506.           ttnproto = NP_EK4LOGIN;
  4507.         else
  4508.           ttnproto = NP_EK4LOGIN;
  4509.     }
  4510. #endif /* CK_KERBEROS */
  4511. #endif /* RLOGCODE */
  4512. #ifdef IKS_OPTION
  4513.     else if (x == KERMIT_PORT) {        /* IKS uses Telnet protocol */
  4514.         if (ttnproto == NP_NONE)
  4515.           ttnproto = NP_KERMIT;
  4516.     }
  4517. #endif /* IKS_OPTION */
  4518.  
  4519. #ifdef SO_OOBINLINE
  4520. /*
  4521.   The symbol SO_OOBINLINE is not known to Ultrix 2.0.
  4522.   It means "leave out of band data inline".  The normal value is 0x0100,
  4523.   but don't try this on systems where the symbol is undefined.
  4524. */
  4525. /*
  4526.   Note from Jeff Altman: 12/13/95
  4527.   In implementing rlogin protocol I have come to the conclusion that it is
  4528.   a really bad idea to read out-of-band data inline.
  4529.   At least Windows and OS/2 does not handle this well.
  4530.   And if you need to know that data is out-of-band, then it becomes
  4531.   absolutely pointless.
  4532.  
  4533.   Therefore, at least on OS2 and Windows (NT) I have changed the value of
  4534.   on to 0, so that out-of-band data stays out-of-band.
  4535.  
  4536.   12/18/95
  4537.   Actually, OOB data should be read inline when possible.  Especially with
  4538.   protocols that don't care about the Urgent flag.  This is true with Telnet.
  4539.   With Rlogin, you need to be able to catch OOB data.  However, the best
  4540.   way to do this is to set a signal handler on SIGURG.  This isn't possible
  4541.   on OS/2 and Windows.  But it is in UNIX.  We will also need OOB data for
  4542.   FTP so better create a general mechanism.
  4543.  
  4544.   The reason for making OOB data be inline is that the standard ttinc/ttoc
  4545.   calls can be used for reading that data on UNIX systems.  If we didn't
  4546.   have the OOBINLINE option set then we would have to use recv(,MSG_OOB)
  4547.   to read it.
  4548. */
  4549. #ifdef RLOGCODE
  4550. #ifdef TCPIPLIB
  4551.     if (ttnproto == NP_RLOGIN
  4552. #ifdef CK_KERBEROS
  4553.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4554.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4555. #endif /* CK_KERBEROS */
  4556.       )
  4557.       on = 0;
  4558. #else /* TCPIPLIB */
  4559.     if (ttnproto == NP_RLOGIN
  4560. #ifdef CK_KERBEROS
  4561.          || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4562.          || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4563. #endif /* CK_KERBEROS */
  4564.          ) {
  4565.         debug(F100,"Installing rlogoobh on SIGURG","",0);
  4566.         signal(SIGURG, rlogoobh);
  4567.         on = 0;
  4568.     } else {
  4569.         debug(F100,"Ignoring SIGURG","",0);
  4570.         signal(SIGURG, SIG_DFL);
  4571.     }
  4572. #endif /* TCPIPLIB */
  4573. #endif /* RLOGCODE */
  4574.  
  4575. #ifdef datageneral
  4576.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4577. #else
  4578. #ifdef BSD43
  4579.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4580. #else
  4581. #ifdef OSF1
  4582.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4583. #else
  4584. #ifdef POSIX
  4585.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4586. #else
  4587. #ifdef MOTSV88R4
  4588.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4589. #else
  4590. #ifdef SOLARIS
  4591. /*
  4592.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  4593.   compiling and working fine on all the others, so best not to change it.
  4594. */
  4595.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4596. #else
  4597. #ifdef OSK
  4598.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4599. #else
  4600. #ifdef OS2
  4601.     {
  4602.         int rc;
  4603.         rc = setsockopt(ttyfd,
  4604.                         SOL_SOCKET,
  4605.                         SO_OOBINLINE,
  4606.                         (char *) &on,
  4607.                         sizeof on
  4608.                         );
  4609.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  4610.     }
  4611. #else
  4612. #ifdef VMS /* or, at least, VMS with gcc */
  4613.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4614. #else
  4615. #ifdef CLIX
  4616.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4617. #else
  4618.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  4619. #endif /* CLIX */
  4620. #endif /* VMS */
  4621. #endif /* OS2 */
  4622. #endif /* OSK */
  4623. #endif /* SOLARIS */
  4624. #endif /* MOTSV88R4 */
  4625. #endif /* POSIX */
  4626. #endif /* BSD43 */
  4627. #endif /* OSF1 */
  4628. #endif /* datageneral */
  4629. #endif /* SO_OOBINLINE */
  4630.  
  4631. #ifndef NOTCPOPTS
  4632. #ifndef datageneral
  4633. #ifdef SOL_SOCKET
  4634. #ifdef TCP_NODELAY
  4635.     no_delay(tcp_nodelay);
  4636. #endif /* TCP_NODELAY */
  4637. #ifdef SO_KEEPALIVE
  4638.     keepalive(tcp_keepalive);
  4639. #endif /* SO_KEEPALIVE */
  4640. #ifdef SO_LINGER
  4641.     ck_linger(tcp_linger, tcp_linger_tmo);
  4642. #endif /* SO_LINGER */
  4643. #ifdef SO_SNDBUF
  4644.     sendbuf(tcp_sendbuf);
  4645. #endif /* SO_SNDBUF */
  4646. #ifdef SO_RCVBUF
  4647.     recvbuf(tcp_recvbuf);
  4648. #endif /* SO_RCVBUF */
  4649. #endif /* SOL_SOCKET */
  4650. #endif /* datageneral */
  4651. #endif /* NOTCPOPTS */
  4652.  
  4653. #ifndef datageneral
  4654.     /* Find out our own IP address. */
  4655.     /* We need the l_addr structure for [E]KLOGIN. */
  4656.     l_slen = sizeof(l_addr);
  4657.     bzero((char *)&l_addr, l_slen);
  4658. #ifndef EXCELAN
  4659.     if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  4660.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  4661.         ckstrncpy(myipaddr, s, 20);
  4662.         debug(F110,"getsockname",myipaddr,0);
  4663.     }
  4664. #endif /* EXCELAN */
  4665. #endif /* datageneral */
  4666.  
  4667. /*
  4668.   This is really only needed for Kerberos IV but is useful information in any
  4669.   case.  If we connect to a name that is really a pool, we need to get the
  4670.   name of the machine we are actually connecting to for K4 to authenticate
  4671.   properly.  This way we also update the names properly.
  4672.  
  4673.   However, it is a security hole when used with insecure DNS.
  4674.  
  4675.   Note: This does not work on Windows 95 or Windows NT 3.5x.  This is because
  4676.   of the Microsoft implementation of gethostbyaddr() in both Winsock 1.1
  4677.   and Winsock 2.0 on those platforms.  Their algorithm is:
  4678.  
  4679.   1. Check the HOSTENT cache.
  4680.   2. Check the HOSTS file at %SystemRoot%\System32\DRIVERS\ETC.
  4681.   3. Do a DNS query if the DNS server is configured for name resolution.
  4682.   4. Do an additional NetBIOS remote adapter status to an IP address for its
  4683.      NetBIOS name table. This step is specific only to the Windows NT version
  4684.      3.51 implementation.
  4685.  
  4686.   The problem is the use of the HOSTENT cache.  It means that gethostbyaddr()
  4687.   can not be used to resolve the real name of machine if it was originally
  4688.   accessed by an alias used to represent a cluster.
  4689. */
  4690.      if ((tcp_rdns && dns || tcp_rdns == SET_ON
  4691. #ifdef CK_KERBEROS
  4692.          || tcp_rdns == SET_AUTO &&
  4693.           (ck_krb5_is_installed() || ck_krb4_is_installed())
  4694. #endif /* CK_KERBEROS */
  4695.          )
  4696. #ifndef NOHTTP
  4697.           && (tcp_http_proxy == NULL)
  4698. #endif /* NOHTTP */
  4699. #ifdef CK_SSL
  4700.           && !(ssl_only_flag || tls_only_flag)
  4701. #endif /* CK_SSL */
  4702.          ) {
  4703. #ifdef NT
  4704.         if (isWin95())
  4705.           sleep(1);
  4706. #endif /* NT */
  4707.         if (!quiet) {
  4708.             printf(" Reverse DNS Lookup... ");
  4709.             fflush(stdout);
  4710.         }
  4711.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  4712.             char * s;
  4713.             host = ck_copyhostent(host);
  4714.             debug(F100,"netopen gethostbyname != NULL","",0);
  4715.             if (!quiet) {
  4716.                 printf("(OK)\n");
  4717.                 fflush(stdout);
  4718.             }
  4719.             s = host->h_name;
  4720.             if (!s) {                   /* This can happen... */
  4721.                 debug(F100,"netopen host->h_name is NULL","",0);
  4722.                 s = "";
  4723.             }
  4724.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  4725.             /* The compiler says "Integral value implicitly converted to */
  4726.             /* pointer in assignment."  The prototype is right there */
  4727.             /* in <arpa/inet.h> so what's the problem? */
  4728.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  4729.             if (!*s) {                  /* No name so substitute the address */
  4730.                 debug(F100,"netopen host->h_name is empty","",0);
  4731.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  4732.                 if (!s)                 /* Trust No 1 */
  4733.                   s = "";
  4734.                 if (*s) {               /* If it worked, use this string */
  4735.                     ckstrncpy(ipaddr,s,20);
  4736.                 }
  4737.                 s = ipaddr;             /* Otherwise stick with the IP */
  4738.                 if (!*s)                /* or failing that */
  4739.                   s = namecopy;         /* the name we were called with. */
  4740.             }
  4741.             if (*s) {                   /* Copying into our argument? */
  4742.                 ckstrncpy(name,s,80);   /* Bad Bad Bad */
  4743.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4744.                     strncat(name,":",80-strlen(name));
  4745.                     strncat(name,svcbuf,80-strlen(name));
  4746.                 }
  4747.             }
  4748.             if (!quiet && *s
  4749. #ifndef NOICP
  4750.                 && !doconx
  4751. #endif /* NOICP */
  4752.                 ) {
  4753.                 printf(" %s connected on port %s\n",s,p);
  4754. #ifdef BETADEBUG
  4755.                 /* This is simply for testing the DNS entries */
  4756.                 if (host->h_aliases) {
  4757.                     char ** a = host->h_aliases;
  4758.                     while (*a) {
  4759.                         printf(" alias => %s\n",*a);
  4760.                         a++;
  4761.                     }
  4762.                 }
  4763. #endif /* BETADEBUG */
  4764.             }
  4765.         } else {
  4766.             if (!quiet) printf("Failed.\n");
  4767.         }
  4768.     } else if (!quiet) printf("(OK)\n");
  4769.     if (!quiet) fflush(stdout);
  4770.  
  4771.     /* This should already have been done but just in case */
  4772.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4773.  
  4774. #ifdef CK_AUTHENTICATION
  4775.  
  4776.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  4777. #ifndef NOHTTP
  4778.     if (tcp_http_proxy) {
  4779.         for (i=strlen(proxycopy); i >= 0 ; i--)
  4780.             if ( proxycopy[i] == ':' )
  4781.                 proxycopy[i] = '\0';
  4782.     }
  4783. #endif /* NOHTTP */
  4784.     ck_auth_init(
  4785. #ifndef NOHTTP
  4786.                  tcp_http_proxy ? proxycopy :
  4787. #endif /* NOHTTP */
  4788.                  (host && host->h_name && host->h_name[0]) ?
  4789.                  (char *)host->h_name : (namecopy[0] ? namecopy : ipaddr),
  4790.                  ipaddr,
  4791.                  uidbuf,
  4792.                  ttyfd
  4793.                  );
  4794. #endif /* CK_AUTHENTICATION */
  4795. #ifdef CK_SSL
  4796.     if (ck_ssleay_is_installed()) {
  4797.         if (!ssl_tn_init(SSL_CLIENT)) {
  4798.         debug(F100,"netopen ssl_tn_init() failed","",0);
  4799.             if (bio_err!=NULL) {
  4800.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  4801.                 ERR_print_errors(bio_err);
  4802.             } else {
  4803.                 fflush(stderr);
  4804.                 fprintf(stderr,"ssl_tn_init() failed\n");
  4805.                 ERR_print_errors_fp(stderr);
  4806.             }
  4807.             if (tls_only_flag || ssl_only_flag) {
  4808.         debug(F100,"netopen ssl/tls required","",0);
  4809.                 netclos();
  4810.                 return(-1);
  4811.             }
  4812.  
  4813.             /* we will continue to accept the connection   */
  4814.             /* without SSL or TLS support unless required. */
  4815.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4816.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4817.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4818.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4819.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4820.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4821.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4822.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4823.         } else if ( ck_ssl_outgoing(ttyfd) < 0 ) {
  4824.         debug(F100,"ck_ssl_outgoing() failed","",0);
  4825.             netclos();
  4826.             return(-1);
  4827.         }
  4828.     }
  4829. #endif /* CK_SSL */
  4830.  
  4831. #ifdef RLOGCODE
  4832.     if (ttnproto == NP_RLOGIN
  4833. #ifdef CK_KERBEROS
  4834.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4835.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4836. #endif /* CK_KERBEROS */
  4837.         ) {                             /* Similar deal for rlogin */
  4838.         if (rlog_ini(((host && host->h_name && host->h_name[0]) ?
  4839.                       (CHAR *)host->h_name : (CHAR *)ipaddr),
  4840.                      service->s_port,
  4841.                      &l_addr,&r_addr
  4842.                      ) < 0) {
  4843.             debug(F100,"rlogin initialization failed","",0);
  4844.             netclos();
  4845.             return(-1);
  4846.         }
  4847.     } else
  4848. #endif /* RLOGCODE */
  4849.     if (tn_ini() < 0) {                 /* Start Telnet negotiations. */
  4850.     netclos();
  4851.         return(-1);                     /* Gone, so open failed.  */
  4852.     }
  4853.     if (ttchk() < 0) {
  4854.     netclos();
  4855.         return(-1);
  4856.     }
  4857. #ifdef CK_KERBEROS
  4858. #ifdef KRB5_U2U
  4859.    if ( ttnproto == NP_K5U2U ) {
  4860.        if (k5_user_to_user_client_auth()) {
  4861.            netclos();
  4862.            return(-1);
  4863.        }
  4864.    }
  4865. #endif /* KRB5_U2U */
  4866. #endif /* CK_KERBEROS */
  4867.  
  4868.     debug(F101,"netopen service","",svcnum);
  4869.     debug(F110,"netopen name",name,0);
  4870.  
  4871.     if (lcl) if (*lcl < 0)        /* Local mode. */
  4872.       *lcl = 1;
  4873. #endif /* TCPSOCKET */
  4874.     return(0);                          /* Done. */
  4875. }
  4876.  
  4877. /*  N E T C L O S  --  Close current network connection.  */
  4878.  
  4879. #ifndef NOLOCAL
  4880. _PROTOTYP(VOID slrestor,(VOID));
  4881. #ifdef CK_SSL
  4882. int tls_norestore = 0;
  4883. #endif /* CK_SSL */
  4884. #endif /* NOLOCAL */
  4885.  
  4886. int
  4887. netclos() {
  4888.     static int close_in_progress = 0;
  4889.     int x = 0;
  4890.     debug(F101,"netclos","",ttyfd);
  4891.  
  4892. #ifdef NETLEBUF
  4893.     if (!tt_push_inited)
  4894.       le_init();
  4895. #endif /* NETLEBUF */
  4896.  
  4897.     if (ttyfd == -1)                    /* Was open? */
  4898.       return(0);                        /* Wasn't. */
  4899.  
  4900.     if (close_in_progress)
  4901.       return(0);
  4902.     close_in_progress = 1;              /* Remember */
  4903.  
  4904. #ifndef NOLOCAL
  4905.     /* This function call should not be here since this is a direct call */
  4906.     /* from an I/O routine to a user interface level function.  However, */
  4907.     /* the reality is that we do not have pure interfaces.  If we ever   */
  4908.     /* decide to clean this up the UI level should assign this function  */
  4909.     /* via a pointer assignment.  - Jeff 9/10/1999                       */
  4910. #ifdef CK_SSL
  4911.     if (!tls_norestore)
  4912. #endif /* CK_SSL */
  4913.       slrestor();
  4914. #endif /* NOLOCAL */
  4915. #ifndef OS2
  4916.     if (ttyfd > -1)                     /* Was. */
  4917. #endif /* OS2 */
  4918.       {
  4919. #ifdef TNCODE
  4920.       if (ttnproto == NP_TELNET) {
  4921.             tn_push();                    /* Place any waiting data into input*/
  4922.             tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  4923.             TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  4924.       }
  4925. #endif /* TNCODE */
  4926. #ifdef CK_SSL
  4927.           if (ssl_active_flag) {
  4928.               if (ssl_debug_flag)
  4929.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4930.               SSL_shutdown(ssl_con);
  4931.               ssl_active_flag = 0;
  4932.           }
  4933.           if (tls_active_flag) {
  4934.               if (ssl_debug_flag)
  4935.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4936.               SSL_shutdown(tls_con);
  4937.               tls_active_flag = 0;
  4938.           }
  4939. #endif /* CK_SSL */
  4940. #ifdef VMS
  4941.           ck_cancio();                  /* Cancel any outstanding reads. */
  4942. #endif /* VMS */
  4943. #ifdef TCPIPLIB
  4944.           x = socket_close(ttyfd);      /* Close it. */
  4945. #else
  4946. #ifndef OS2
  4947. #ifdef IBMX25
  4948.         if (ttnet == NET_IX25) {
  4949.             /* riehm: should send a disc_req - but only if link is still OK */
  4950.             x = x25clear();
  4951.             close(ttyfd);
  4952.             if (x25serverfd) {
  4953.                   /* we were the passive client of a server, now we
  4954.                    * go back to being the normal client.
  4955.                    * I hope that kermit can cope with the logic that
  4956.                    * there can still be a connection after netclos
  4957.                    * has been called.
  4958.                    */
  4959.                   ttyfd = x25serverfd;
  4960.                   x25serverfd = 0;
  4961.                   /*
  4962.                    * need to close the server connection too - because
  4963.                    * all file descriptors connected to the NPI have the
  4964.                    * same status.
  4965.                    *
  4966.                    * The problem is that any waiting connections get
  4967.                    * lost, the client doesn't realise, and hangs.
  4968.                    */
  4969.                   netclos();
  4970.               }
  4971.             x25_state = X25_CLOSED;     /* riehm: dead code? */
  4972.         } else
  4973. #endif /* IBMX25 */
  4974.           x = close(ttyfd);
  4975. #endif /* OS2 */
  4976. #endif /* TCPIPLIB */
  4977.       }
  4978.     ttyfd = -1;                         /* Mark it as closed. */
  4979.     wasclosed = 1;
  4980. #ifdef TNCODE
  4981. #ifdef CK_FORWARD_X
  4982.     fwdx_close_all();                   /* Shut down any Forward X sockets */
  4983. #endif /* CK_FORWARD_X */
  4984.     tn_reset();                   /* The Reset Telnet Option table.  */
  4985.     debug(F100,"netclose setting tn_init = 0","",0);
  4986.     tn_init = 0;                        /* Remember about telnet protocol... */
  4987.     sstelnet = 0;                       /* Client-side Telnet */
  4988. #endif /* TNCODE */
  4989.     *ipaddr = '\0';                     /* Zero the IP address string */
  4990.     tcp_incoming = 0;                   /* No longer incoming */
  4991.     /* Don't reset ttnproto so that we can remember which protocol is in use */
  4992.  
  4993. #ifdef TCPIPLIB
  4994. /*
  4995.   Empty the internal buffers so they won't be used as invalid input on
  4996.   the next connect attempt (rlogin).
  4997. */
  4998.     ttibp = 0;
  4999.     ttibn = 0;
  5000. #endif /* TCPIPLIB */
  5001. #ifdef CK_KERBEROS
  5002.     /* If we are automatically destroying Kerberos credentials on Close */
  5003.     /* do it now. */
  5004. #ifdef KRB4
  5005.     if (krb4_autodel == KRB_DEL_CL) {
  5006.         extern struct krb_op_data krb_op;
  5007.         krb_op.version = 4;
  5008.         krb_op.cache = NULL;
  5009.         ck_krb4_destroy(&krb_op);
  5010.     }
  5011. #endif /* KRB4 */
  5012. #ifdef KRB5
  5013.     if (krb5_autodel == KRB_DEL_CL) {
  5014.         extern struct krb_op_data krb_op;
  5015.         extern char * krb5_d_cc;
  5016.         krb_op.version = 5;
  5017.         krb_op.cache = krb5_d_cc;
  5018.         ck_krb5_destroy(&krb_op);
  5019.     }
  5020. #endif /* KRB5 */
  5021. #endif /* CK_KERBEROS */
  5022.     close_in_progress = 0;              /* Remember we are done. */
  5023.     return(x);
  5024. }
  5025.  
  5026. #ifdef OS2
  5027. int
  5028. os2socketerror( int s_errno ) {
  5029. #ifdef OS2ONLY
  5030.     if (s_errno > 0 && s_errno <= SOCBASEERR) {
  5031.         /* in OS/2, there is a problem with threading in that 
  5032.          * the value of errno is not thread safe.  It can be
  5033.          * set to a value from a previous library call and if
  5034.          * it was not cleared it will appear here.  Only treat
  5035.          * valid socket error codes as errors in this function.
  5036.          */
  5037.         debug(F100,"os2socketerror errno.h","",0);
  5038.         socket_errno = 0;
  5039.         return(0);
  5040.     }
  5041. #endif /* OS2ONLY */
  5042.  
  5043.     switch (s_errno) {
  5044.       case 0:                /* NO ERROR */
  5045.         debug(F100,"os2socketerror NOERROR","",0);
  5046.         return(0);
  5047. #ifdef NT
  5048.       case WSAECONNRESET:
  5049. #else /* NT */
  5050.       case SOCECONNRESET:
  5051.       case SOCECONNRESET - SOCBASEERR:
  5052. #endif /* NT */
  5053.         debug(F100,"os2socketerror ECONRESET","",0);
  5054.         tn_debug("ECONRESET");
  5055.         netclos();              /* *** *** */
  5056.         return(-1);             /* Connection is broken. */
  5057. #ifdef NT
  5058.       case WSAECONNABORTED:
  5059. #else /* NT */
  5060.       case SOCECONNABORTED:
  5061.       case SOCECONNABORTED - SOCBASEERR:
  5062. #endif /* NT */
  5063.         debug(F100,"os2socketerror ECONNABORTED","",0);
  5064.         tn_debug("ECONNABORTED");
  5065.         netclos();              /* *** *** */
  5066.         return(-1);             /* Connection is broken. */
  5067. #ifdef NT
  5068.       case WSAENETRESET:
  5069. #else /* NT */
  5070.       case SOCENETRESET:
  5071.       case SOCENETRESET - SOCBASEERR:
  5072. #endif /* NT */
  5073.         debug(F100,"os2socketerror ENETRESET","",0);
  5074.         tn_debug("ENETRESET");
  5075.         netclos();              /* *** *** */
  5076.         return(-1);             /* Connection is broken. */
  5077. #ifdef NT
  5078.       case WSAENOTCONN:
  5079. #else /* NT */
  5080.       case SOCENOTCONN:
  5081.       case SOCENOTCONN - SOCBASEERR:
  5082. #endif /* NT */
  5083.         debug(F100,"os2socketerror ENOTCONN","",0);
  5084.         tn_debug("ENOTCONN");
  5085.         netclos();            /* *** *** */
  5086.         return(-1);            /* Connection is broken. */
  5087. #ifdef NT
  5088.       case WSAESHUTDOWN:
  5089.     debug(F100,"os2socketerror ESHUTDOWN","",0);
  5090.     tn_debug("ESHUTDOWN");
  5091.     netclos();            /* *** *** */
  5092.     return(-1);            /* Connection is broken. */
  5093. #endif /* NT */
  5094. #ifdef NT
  5095.       case WSAEWOULDBLOCK:
  5096. #else
  5097.       case SOCEWOULDBLOCK:
  5098.       case SOCEWOULDBLOCK - SOCBASEERR:
  5099. #endif /* NT */
  5100.         debug(F100,"os2socketerror EWOULDBLOCK","",0);
  5101.         return(0);
  5102. #ifdef NT
  5103.       case ERROR_IO_INCOMPLETE:
  5104.       case ERROR_IO_PENDING:
  5105.       case ERROR_OPERATION_ABORTED:
  5106.         return(0);
  5107. #endif /* NT */
  5108.       default:
  5109.         return(-2);
  5110.     }
  5111.     return(0);
  5112. }
  5113. #endif /* OS2 */
  5114.  
  5115. /*  N E T T C H K  --  Check if network up, and how many bytes can be read */
  5116. /*
  5117.   Returns number of bytes waiting, or -1 if connection has been dropped.
  5118. */
  5119. int                                     /* Check how many bytes are ready */
  5120. nettchk() {                             /* for reading from network */
  5121. #ifdef TCPIPLIB
  5122.     long count = 0;
  5123.     int x = 0;
  5124.     long y;
  5125.     char c;
  5126.     int rc;
  5127. #ifdef NT
  5128.     extern int ionoblock;               /* For Overlapped I/O */
  5129. #endif /* NT */
  5130.  
  5131.     debug(F101,"nettchk entry ttibn","",ttibn);
  5132.     debug(F101,"nettchk entry ttibp","",ttibp);
  5133.  
  5134. #ifdef NETLEBUF
  5135.     {
  5136.         int n = 0;
  5137.         if (ttpush >= 0)
  5138.           n++;
  5139.         n += le_inbuf();
  5140.         if (n > 0)
  5141.           return(n);
  5142.     }
  5143. #endif /* NETLEBUF */
  5144.  
  5145. #ifndef OS2
  5146. #ifndef BEBOX
  5147.     socket_errno = 0; /* This is a function call in NT, and BeOS */
  5148. #endif /* BEBOX */
  5149. #endif /* OS2 */
  5150.  
  5151.     if (ttyfd == -1) {
  5152.         debug(F100,"nettchk socket is closed","",0);
  5153.         return(-1);
  5154.     }
  5155. /*
  5156.   Note: this socket_ioctl() call does NOT return an error if the
  5157.   connection has been broken.  (At least not in MultiNet.)
  5158. */
  5159. #ifdef COMMENT
  5160. /*  Another trick that can be tried here is something like this: */
  5161.  
  5162.     if (ttnet == NET_TCPB) {
  5163.         char dummy;
  5164.         x = read(ttyfd,&dummy,0);       /* Try to read nothing */
  5165.         if (x < 0) {                    /* "Connection reset by peer" */
  5166.             perror("TCP/IP");           /* or somesuch... */
  5167.             ttclos(0);                  /* Close our end too. */
  5168.             return(-1);
  5169.         }
  5170.     }
  5171. #endif /* COMMENT */
  5172.  
  5173.  
  5174. #ifdef CK_SSL
  5175.     if (ssl_active_flag) {
  5176.         count = SSL_pending(ssl_con);
  5177.         if (count < 0) {
  5178.             debug(F111,"nettchk","SSL_pending error",count);
  5179.             netclos();
  5180.             return(-1);
  5181.         }
  5182.     } else if (tls_active_flag) {
  5183.         count = SSL_pending(tls_con);
  5184.         if (count < 0) {
  5185.             debug(F111,"nettchk","TLS_pending error",count);
  5186.             netclos();
  5187.             return(-1);
  5188.         }
  5189.     } else
  5190. #endif /* CK_SSL */
  5191.  
  5192.     if (socket_ioctl(ttyfd,FIONREAD,
  5193. #ifdef COMMENT
  5194.     /* Now we've changed the ioctl(..,..,x) prototype for DECC to (void *) */
  5195. #ifdef __DECC
  5196.     /* NOTE: "&count" might need to be "(char *)&count" in some settings. */
  5197.                      /* Cast needed for DECC 4.1 & later? */
  5198.                      /* Maybe, but __DECC_VER only exists in 5.0 and later */
  5199.                      (char *)
  5200. #endif /* __DECC */
  5201. #endif /* COMMENT */
  5202.                      &count
  5203.                      ) < 0) {
  5204.         debug(F101,"nettchk socket_ioctl error","",socket_errno);
  5205.         /* If the connection is gone, the connection is gone. */
  5206.         netclos();
  5207. #ifdef NT_TCP_OVERLAPPED
  5208.         /* Is there anything in the overlapped I/O buffers? */
  5209.         count += OverlappedDataWaiting();
  5210. #endif /* NT_TCP_OVERLAPPED */
  5211.         count += ttibn;
  5212.         return(count>0?count:-1);
  5213.     }
  5214.     debug(F101,"nettchk count","",count);
  5215. #ifdef NT_TCP_OVERLAPPED
  5216.     /* Is there anything in the overlapped I/O buffers? */
  5217.     count += OverlappedDataWaiting();
  5218.     debug(F101,"nettchk count w/overlapped","",count);
  5219. #endif /* NT_TCP_OVERLAPPED */
  5220.  
  5221. /* For the sake of efficiency, if there is still data in the ttibuf */
  5222. /* do not go to the bother of checking to see of the connection is  */
  5223. /* still valid.  The handle is still good, so just return the count */
  5224. /* of the bytes that we already have left to process.               */
  5225. #ifdef OS2
  5226.     if ( ttibn > 0 ) {
  5227.         debug(F101,"nettchk (ttibn > 0) returns","",count+ttibn);
  5228.         return(count + ttibn);
  5229.     } else {
  5230.         if ( ttibn == 0 )
  5231.             ttibp = 0;      /* reset for next read */
  5232.     }
  5233. #else /* OS2 */
  5234.     if ( ttibn ) {
  5235.         debug(F101,"nettchk returns","",count+ttibn);
  5236.         return(count+ttibn);
  5237.     }
  5238. #endif /* OS2 */
  5239.  
  5240. /*
  5241.   The following code works well in most settings, but messes things up in
  5242.   others, including CMU/Tek TCP/IP and UCX 2.0, where it somehow manages to
  5243.   make it impossible to ever make a new connection to the same host again with
  5244.   CONNECT, once it has been logged out from the first time.  Not even if you
  5245.   HANGUP first, or SET HOST<CR>, or SET LINE<CR>.  Reportedly, however, it
  5246.   does work OK in later releases of UCX.  But there is no way we can
  5247.   accommodate both old and new -- we might have static linking or dynamic
  5248.   linking, etc etc.  If we have static, I only have access to 2.0, where this
  5249.   doesn't work, etc etc blah blah.
  5250.  
  5251.   In the following lines, we define a symbol NOCOUNT for builds where we want
  5252.   to omit this code.  By default, it is omitted for CMU/Tek.  You can force
  5253.   omission of it for other combinations by defining NOCOUNT in CFLAGS.  You
  5254.   can force inclusion of this code, even for CMU/Tek, by including NONOCOUNT
  5255.   in CFLAGS.
  5256. */
  5257. #ifdef NONOCOUNT
  5258. #ifdef NOCOUNT
  5259. #undef NOCOUNT
  5260. #endif /* NOCOUNT */
  5261. #else
  5262. #ifndef NOCOUNT
  5263. #ifdef CMU_TCPIP
  5264. #define NOCOUNT
  5265. #endif /* CMU_TCPIP */
  5266. #endif /* NOCOUNT */
  5267. #endif /* NONOCOUNT */
  5268.  
  5269.  
  5270.     /* From this point forward we have a possible race condition in K95
  5271.      * due to its use of multiple threads.  Therefore, we must ensure
  5272.      * that only one thread attempt to read/write from the socket at a
  5273.      * time.  Otherwise, it is possible for a buffer to be overwritten.
  5274.      */
  5275. #ifdef OS2
  5276.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5277. #endif /* OS2 */
  5278.  
  5279.     /* we know now that count >= 0 and that ttibn == 0 */
  5280.  
  5281.     if (count == 0
  5282. #ifdef RLOGCODE
  5283. #ifdef CK_KERBEROS
  5284.         && ttnproto != NP_EK4LOGIN && ttnproto != NP_EK5LOGIN
  5285. #endif /* CK_KERBEROS */
  5286. #endif /* RLOGCODE */
  5287.         ) {
  5288.         int s_errno = 0;
  5289. #ifndef NOCOUNT
  5290. /*
  5291.   Here we need to tell the difference between a 0 count on an active
  5292.   connection, and a 0 count because the remote end of the socket broke the
  5293.   connection.  There is no mechanism in TGV MultiNet (or WIN/TCP?) to query
  5294.   the status of the connection, so we have to do a read.  -1 means there was
  5295.   no data available (socket_errno == EWOULDBLOCK), 0 means the connection is
  5296.   down.  But if, by chance, we actually get a character, we have to put it
  5297.   where it won't be lost.
  5298. */
  5299. #ifndef NON_BLOCK_IO
  5300.         y = 1;                          /* Turn on nonblocking reads */
  5301.         x = socket_ioctl(ttyfd,FIONBIO,&y);
  5302.         debug(F101,"nettchk FIONBIO","",x);
  5303. #endif /* NON_BLOCK_IO */
  5304. #ifdef NT_TCP_OVERLAPPED
  5305.         ionoblock = 1;                  /* For Overlapped I/O */
  5306. #endif /* NT_TCP_OVERLAPPED */
  5307. #ifdef CK_SSL
  5308.         if ( ssl_active_flag || tls_active_flag ) {
  5309.             x = SSL_read( ssl_active_flag?ssl_con:tls_con,
  5310.                           &ttibuf[ttibp+ttibn],
  5311.                           TTIBUFL-ttibp-ttibn );
  5312.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  5313.             case SSL_ERROR_NONE:
  5314.                 debug(F111,"nettchk SSL_ERROR_NONE","count",count);
  5315.                 break;
  5316.             case SSL_ERROR_WANT_WRITE:
  5317.                 debug(F100,"nettchk SSL_ERROR_WANT_WRITE","",0);
  5318.                 x = -1;
  5319.                 break;
  5320.             case SSL_ERROR_WANT_READ:
  5321.                 debug(F100,"nettchk SSL_ERROR_WANT_READ","",0);
  5322.                 x = -1;
  5323.                 break;
  5324.             case SSL_ERROR_SYSCALL:
  5325.                 if ( x == 0 ) { /* EOF */
  5326.                     netclos();
  5327.                     rc = -1;
  5328.                     goto nettchk_return;
  5329.               } else {
  5330. #ifdef NT
  5331.                   int gle = GetLastError();
  5332.                   debug(F111,"nettchk SSL_ERROR_SYSCALL",
  5333.                          "GetLastError()",gle);
  5334. #endif /* NT */
  5335.                   break;
  5336.               }
  5337.           case SSL_ERROR_WANT_X509_LOOKUP:
  5338.                 debug(F100,"nettchk SSL_ERROR_WANT_X509_LOOKUP","",0);
  5339.                 break;
  5340.           case SSL_ERROR_SSL:
  5341.                 debug(F100,"nettchk SSL_ERROR_SSL","",0);
  5342.                 netclos();
  5343.                 rc = -1;
  5344.                 goto nettchk_return;
  5345.           case SSL_ERROR_ZERO_RETURN:
  5346.                 debug(F100,"nettchk SSL_ERROR_ZERO_RETURN","",0);
  5347.                 netclos();
  5348.                 rc = -1;
  5349.                 goto nettchk_return;
  5350.             default:
  5351.                 debug(F100,"nettchk SSL_ERROR_?????","",0);
  5352.                 netclos();
  5353.                 rc = -1;
  5354.                 goto nettchk_return;
  5355.             }
  5356.         } else
  5357. #endif /* CK_SSL */
  5358.         {
  5359. #ifdef OS2
  5360.         x = socket_read(ttyfd,&ttibuf[ttibp+ttibn],
  5361.                          TTIBUFL-ttibp-ttibn);  /* Returns -1 if no data */
  5362. #else /* OS2 */
  5363.         x = socket_read(ttyfd,&c,1);    /* Returns -1 if no data */
  5364. #endif /* OS2 */
  5365.         }
  5366.         s_errno = socket_errno;         /* socket_errno may be a function */
  5367.         debug(F101,"nettchk socket_read","",x);
  5368.  
  5369. #ifndef NON_BLOCK_IO
  5370.         y = 0;                          /* Turn them back off */
  5371.         socket_ioctl(ttyfd,FIONBIO,&y);
  5372. #endif /* NON_BLOCK_IO */
  5373. #ifdef NT_TCP_OVERLAPPED
  5374.         ionoblock = 0;                  /* For Overlapped I/O */
  5375. #endif /* NT_TCP_OVERLAPPED */
  5376.  
  5377.         if (x == -1) {
  5378.             debug(F101,"nettchk socket_read errno","",s_errno);
  5379. #ifdef OS2
  5380.             if (os2socketerror(s_errno) < 0) {
  5381.                 rc = -1;
  5382.                 goto nettchk_return;
  5383.             }
  5384. #endif /* OS2 */
  5385.         } else if (x == 0) {
  5386.             debug(F100,"nettchk connection closed","",0);
  5387.             netclos();                  /* *** *** */
  5388.             rc = -1;
  5389.             goto nettchk_return;
  5390.         }
  5391.         if (x >= 1) {                   /* Oops, actually got a byte? */
  5392. #ifdef OS2
  5393.             /* In OS/2 we read directly into ttibuf[] */
  5394.             hexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
  5395.             ttibn += x;
  5396. #else /* OS2 */
  5397.             debug(F101,"nettchk socket_read char","",c);
  5398.             debug(F101,"nettchk ttibp","",ttibp);
  5399.             debug(F101,"nettchk ttibn","",ttibn);
  5400. /*
  5401.   In the case of Overlapped I/O the character would have come from
  5402.   the beginning of the buffer, so put it back.
  5403. */
  5404.             if (ttibp > 0) {
  5405.                 ttibp--;
  5406.                 ttibuf[ttibp] = c;
  5407.                 ttibn++;
  5408.             } else {
  5409.                 ttibuf[ttibp+ttibn] = c;
  5410.                 ttibn++;
  5411.             }
  5412. #endif /* OS2 */
  5413.         }
  5414. #else /* NOCOUNT */
  5415.         if (ttnet == NET_TCPB) {
  5416.             char dummy;
  5417.             x = read(ttyfd,&dummy,0);   /* Try to read nothing */
  5418.             if (x < 0) {                /* "Connection reset by peer" */
  5419.                 perror("TCP/IP");       /* or somesuch... */
  5420.                 ttclos(0);              /* Close our end too. */
  5421.                 rc = -1;
  5422.                 goto nettchk_return;
  5423.             }
  5424.         }
  5425. #endif /* NOCOUNT */
  5426.     }
  5427. #ifdef CK_KERBEROS
  5428. #ifdef KRB4
  5429. #ifdef RLOGCODE
  5430.     if (ttnproto == NP_EK4LOGIN)
  5431.       count += krb4_des_avail(ttyfd);
  5432. #endif /* RLOGCODE */
  5433. #endif /* KRB4 */
  5434. #ifdef KRB5
  5435. #ifdef RLOGCODE
  5436.     if (ttnproto == NP_EK5LOGIN)
  5437.       count += krb5_des_avail(ttyfd);
  5438. #endif /* RLOGCODE */
  5439. #ifdef KRB5_U2U
  5440.     if (ttnproto == NP_K5U2U)
  5441.       count += krb5_u2u_avail(ttyfd);
  5442. #endif /* KRB5_U2U */
  5443. #endif /* KRB5 */
  5444. #endif /* CK_KERBEROS */
  5445.  
  5446.     debug(F101,"nettchk returns","",count+ttibn);
  5447.     rc = count + ttibn;
  5448.  
  5449.   nettchk_return:
  5450. #ifdef OS2
  5451.     ReleaseTCPIPMutex();
  5452. #endif /* OS2 */
  5453.     return(rc);
  5454.  
  5455. #else /* Not TCPIPLIB */
  5456. /*
  5457.   UNIX just uses ttchk(), in which the ioctl() calls on the file descriptor
  5458.   seem to work OK.
  5459. */
  5460.     return(0);
  5461. #endif /* TCPIPLIB */
  5462. /*
  5463.   But what about X.25?
  5464. */
  5465. }
  5466.  
  5467. #ifndef OS2
  5468. VOID
  5469. nettout(i) int i; {                     /* Catch the alarm interrupts */
  5470.     debug(F100,"nettout caught timeout","",0);
  5471.     ttimoff();
  5472.     cklongjmp(njbuf, -1);
  5473. }
  5474. #endif /* !OS2 */
  5475.  
  5476. #ifdef TCPIPLIB
  5477.  
  5478. VOID
  5479. #ifdef CK_ANSIC
  5480. donetinc(void * threadinfo)
  5481. #else /* CK_ANSIC */
  5482. donetinc(threadinfo) VOID * threadinfo;
  5483. #endif /* CK_ANSIC */
  5484. /* donetinc */ {
  5485. #ifdef NTSIG
  5486.     extern int TlsIndex;
  5487.     setint();
  5488.     if (threadinfo) {                   /* Thread local storage... */
  5489.         TlsSetValue(TlsIndex,threadinfo);
  5490.     }
  5491. #endif /* NTSIG */
  5492. #ifdef CK_LOGIN
  5493. #ifdef NT
  5494. #ifdef IKSD
  5495.     if (inserver)
  5496.       setntcreds();
  5497. #endif /* IKSD */
  5498. #endif /* NT */
  5499. #endif /* CK_LOGIN */
  5500.     while (1) {
  5501.         if (ttbufr() < 0)               /* Keep trying to refill it. */
  5502.           break;                        /* Till we get an error. */
  5503.         if (ttibn > 0)                  /* Or we get a character. */
  5504.           break;
  5505.     }
  5506. }
  5507. #endif /* TCPIPLIB */
  5508.  
  5509. VOID
  5510. #ifdef CK_ANSIC
  5511. failnetinc(void * threadinfo)
  5512. #else /* CK_ANSIC */
  5513. failnetinc(threadinfo) VOID * threadinfo;
  5514. #endif /* CK_ANSIC */
  5515. /* failnetinc */ {
  5516.     ; /* Nothing to do on an error */
  5517. }
  5518.  
  5519. /* N E T X I N -- Input block of characters from network */
  5520.  
  5521. int
  5522. netxin(n,buf) int n; CHAR * buf; {
  5523.     int len, i, j;
  5524. #ifdef TCPIPLIB
  5525.     int rc;
  5526. #endif /* TCPIPLIB */
  5527.  
  5528.     if (ttyfd == -1) {
  5529.         debug(F100,"netinc socket is closed","",0);
  5530.         return(-2);
  5531.     }
  5532. #ifdef CK_KERBEROS
  5533. #ifdef KRB4
  5534. #ifdef RLOGCODE
  5535.     if (ttnproto == NP_EK4LOGIN) {
  5536.         if ((len = krb4_des_read(ttyfd,buf,n)) < 0)
  5537.           return(-1);
  5538.         else
  5539.           return(len);
  5540.     }
  5541. #endif /* RLOGCODE */
  5542. #endif /* KRB4 */
  5543. #ifdef KRB5
  5544. #ifdef RLOGCODE
  5545.     if (ttnproto == NP_EK5LOGIN) {
  5546.         if ((len = krb5_des_read(ttyfd,buf,n)) < 0)
  5547.           return(-1);
  5548.         else
  5549.           return(len);
  5550.     }
  5551. #endif /* RLOGCODE */
  5552. #ifdef KRB5_U2U
  5553.     if (ttnproto == NP_K5U2U) {
  5554.         if ((len = krb5_u2u_read(ttyfd,buf,n)) < 0)
  5555.           return(-1);
  5556.         else
  5557.           return(len);
  5558.     }
  5559. #endif /* KRB5_U2U */
  5560. #endif /* KRB5 */
  5561. #endif /* CK_KERBEROS */
  5562.  
  5563. #ifdef TCPIPLIB
  5564.     if (!ttibn)
  5565.       if ((rc = ttbufr()) <= 0)
  5566.         return(rc);
  5567.  
  5568.     if (ttibn <= n) {
  5569.         len = ttibn;
  5570.         memcpy(buf,&ttibuf[ttibp],len);         /* safe */
  5571.         ttibp += len;
  5572.         ttibn = 0;
  5573.     } else {
  5574.         memcpy(buf,&ttibuf[ttibp],n);           /* safe */
  5575.         ttibp += n;
  5576.         ttibn -= n;
  5577.         len = n;
  5578.     }
  5579. #else /* TCPIPLIB */
  5580.     for (i = 0; i < n; i++) {
  5581.         if ((j = netinc(0)) < 0) {
  5582.             if (j < -1)
  5583.               return(j);
  5584.             else
  5585.               break;
  5586.         }
  5587.         buf[i] = j;
  5588.     }
  5589.     len = i;
  5590. #endif /* TCPIPLIB */
  5591.  
  5592. #ifdef COMMENT
  5593. #ifdef CK_ENCRYPTION
  5594.     /* This would be great if it worked.  But what if the buffer we read  */
  5595.     /* contains a telnet negotiation that changes the state of the        */
  5596.     /* encryption.  If so, we would be either decrypting unencrypted text */
  5597.     /* or not decrypting encrypted text.  So we must move this call to    */
  5598.     /* all functions that call ttxin().  In OS2 that means os2_netxin()   */
  5599.     /* where the Telnet Negotiations are handled.                         */
  5600.     if (u_encrypt)
  5601.       ck_tn_decrypt(buf,len);
  5602. #endif /* CK_ENCRYPTION */
  5603. #endif /* COMMENT */
  5604.  
  5605.     return(len);
  5606. }
  5607.  
  5608. /*  N E T I N C --  Input character from network */
  5609.  
  5610. #ifdef NETLEBUF
  5611. #define LEBUF
  5612. #endif /* NETLEBUF */
  5613. #ifdef TTLEBUF
  5614. #define LEBUF
  5615. #endif /* TTLEBUF */
  5616. #ifndef LEBUF
  5617. #ifdef OS2
  5618. #define LEBUF
  5619. #endif /* OS2 */
  5620. #endif /* LEBUF */
  5621.  
  5622. int
  5623. netinc(timo) int timo; {
  5624. #ifdef TCPIPLIB
  5625.     int x; unsigned char c;             /* The locals. */
  5626.  
  5627. #ifdef NETLEBUF
  5628.     if (ttpush >= 0) {
  5629.         debug(F111,"netinc","ttpush",ttpush);
  5630.         c = ttpush;
  5631.         ttpush = -1;
  5632.         return(c);
  5633.     }
  5634.     if (le_data) {
  5635.         if (le_getchar((CHAR *)&c) > 0) {
  5636.             debug(F111,"netinc le_getchar","c",c);
  5637.             return(c);
  5638.         }
  5639.     }
  5640. #endif /* NETLEBUF */
  5641.  
  5642.     if (ttyfd == -1) {
  5643.         debug(F100,"netinc socket is closed","",0);
  5644.         return(-2);
  5645.     }
  5646.  
  5647. #ifdef CK_KERBEROS
  5648. #ifdef KRB4
  5649. #ifdef RLOGCODE
  5650.     if (ttnproto == NP_EK4LOGIN) {
  5651.         if ((x = krb4_des_read(ttyfd,&c,1)) == 0)
  5652.           return(-1);
  5653.         else if (x < 0)
  5654.           return(-2);
  5655.         else
  5656.           return(c);
  5657.     }
  5658. #endif /* RLOGCODE */
  5659. #endif /* KRB4 */
  5660. #ifdef KRB5
  5661. #ifdef RLOGCODE
  5662.     if (ttnproto == NP_EK5LOGIN) {
  5663.         if ((x = krb5_des_read(ttyfd,&c,1)) == 0)
  5664.           return(-1);
  5665.         else if (x < 0)
  5666.           return(-2);
  5667.         else
  5668.           return(c);
  5669.     }
  5670. #endif /* RLOGCODE */
  5671. #ifdef KRB5_U2U
  5672.     if (ttnproto == NP_K5U2U) {
  5673.         if ((x = krb5_u2u_read(ttyfd,&c,1)) == 0)
  5674.           return(-1);
  5675.         else if (x < 0)
  5676.           return(-2);
  5677.         else
  5678.           return(c);
  5679.     }
  5680. #endif /* KRB5_U2U */
  5681. #endif /* KRB5 */
  5682. #endif /* CK_KERBEROS */
  5683.  
  5684.     if (ttibn > 0) {                    /* Something in internal buffer? */
  5685. #ifdef COMMENT
  5686.         debug(F100,"netinc char in buf","",0); /* Yes. */
  5687. #endif /* COMMENT */
  5688.         x = 0;                          /* Success. */
  5689.     } else {                            /* Else must read from network. */
  5690.         x = -1;                         /* Assume failure. */
  5691. #ifdef DEBUG
  5692.         debug(F101,"netinc goes to net, timo","",timo);
  5693.         ttibuf[ttibp+ttibn+1] = '\0';
  5694.         debug(F111,"netinc ttibuf",ttibuf,ttibp);
  5695. #endif /* DEBUG */
  5696. #ifdef CK_SSL
  5697.         /*
  5698.          * In the case of OpenSSL, it is possible that there is still
  5699.          * data waiting in the SSL session buffers that has not yet
  5700.          * been read by Kermit.  If this is the case we must process
  5701.          * it without calling select() because select() will not return
  5702.          * with an indication that there is data to be read from the
  5703.          * socket.  If there is no data pending in the SSL session
  5704.          * buffers then fall through to the select() code and wait for
  5705.          * some data to arrive.
  5706.          */
  5707.         if (ssl_active_flag) {
  5708.             x = SSL_pending(ssl_con);
  5709.             if (x < 0) {
  5710.                 debug(F111,"netinc","SSL_pending error",x);
  5711.                 netclos();
  5712.                 return(-1);
  5713.             } else if ( x > 0 ) {
  5714.                 if ( ttbufr() >= 0 )
  5715.                     return(netinc(timo));
  5716.             }
  5717.             x = -1;
  5718.         } else if (tls_active_flag) {
  5719.             x = SSL_pending(tls_con);
  5720.             if (x < 0) {
  5721.                 debug(F111,"netinc","TLS_pending error",x);
  5722.                 netclos();
  5723.                 return(-1);
  5724.             } else if ( x > 0 ) {
  5725.                 if ( ttbufr() >= 0 )
  5726.                     return(netinc(timo));
  5727.             }
  5728.             x = -1;
  5729.         }
  5730. #endif /* CK_SSL */
  5731. #ifndef LEBUF
  5732.         if (timo == 0) {                /* Untimed case. */
  5733.             while (1) {                 /* Wait forever if necessary. */
  5734.                 if (ttbufr() < 0)       /* Refill buffer. */
  5735.                   break;                /* Error, fail. */
  5736.                 if (ttibn > 0) {        /* Success. */
  5737.                     x = 0;
  5738.                     break;
  5739.                 }
  5740.             }
  5741.         } else                          /* Timed case... */
  5742. #endif /* LEBUF */
  5743.           {
  5744. #ifdef NT_TCP_OVERLAPPED
  5745.             /* This code is for use on NT when we are using */
  5746.             /* Overlapped I/O to handle reads.  In the case */
  5747.             /* of outstanding reads select() doesn't work   */
  5748.  
  5749.             if (WaitForOverlappedReadData(timo)) {
  5750.                 while (1) {
  5751.                     if (ttbufr() < 0)   /* Keep trying to refill it. */
  5752.                         break;          /* Till we get an error. */
  5753.                     if (ttibn > 0) {    /* Or we get a character. */
  5754.                         x = 0;
  5755.                         break;
  5756.                     }
  5757.                 }
  5758.             }
  5759. #else /* NT_TCP_OVERLAPPED */
  5760. #ifdef BSDSELECT
  5761.             fd_set rfds;
  5762.             struct timeval tv;
  5763.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5764.             debug(F101,"netinc BSDSELECT","",timo);
  5765.  
  5766.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5767.                 int rc;
  5768.                 debug(F111,"netinc","timeout",timeout);
  5769.                 /* Don't move select() initialization out of the loop. */
  5770.                 FD_ZERO(&rfds);
  5771.                 FD_SET(ttyfd, &rfds);
  5772.                 tv.tv_sec  = tv.tv_usec = 0L;
  5773.                 if (timo)
  5774.                   tv.tv_usec = (long) 100000L;
  5775.                 else
  5776.                   tv.tv_sec = 30;
  5777. #ifdef NT
  5778.                 WSASafeToCancel = 1;
  5779. #endif /* NT */
  5780.                 rc = select(FD_SETSIZE,
  5781. #ifndef __DECC
  5782.                             (fd_set *)
  5783. #endif /* __DECC */
  5784.                             &rfds, NULL, NULL, &tv);
  5785.                 if (rc < 0) {
  5786.                     int s_errno = socket_errno;
  5787.                     debug(F111,"netinc","select",rc);
  5788.                     debug(F111,"netinc","socket_errno",s_errno);
  5789.                     if (s_errno)
  5790.                       return(-1);
  5791.                 }
  5792.                 debug(F111,"netinc","select",rc);
  5793. #ifdef NT
  5794.                 WSASafeToCancel = 0;
  5795. #endif /* NT */
  5796.                 if (!FD_ISSET(ttyfd, &rfds)) {
  5797. #ifdef LEBUF
  5798.                     if (le_inbuf() > 0) {
  5799.                         timeout = -1;
  5800.                         break;
  5801.                     }
  5802. #endif /* LEBUF */
  5803.                     /* If waiting forever we have no way of knowing if the */
  5804.                     /* socket closed so try writing a 0-length TCP packet  */
  5805.                     /* which should force an error if the socket is closed */
  5806.                     if (!timo) {
  5807.                         if ((rc = socket_write(ttyfd,"",0)) < 0) {
  5808.                             int s_errno = socket_errno;
  5809.                             debug(F101,"netinc socket_write error","",s_errno);
  5810. #ifdef OS2
  5811.                             if (os2socketerror(s_errno) < 0)
  5812.                               return(-2);
  5813. #endif /* OS2 */
  5814.                             return(-1); /* Call it an i/o error */
  5815.                         }
  5816.                     }
  5817.                     continue;
  5818.                 }
  5819.                 while (1) {
  5820.                     if (ttbufr() < 0) { /* Keep trying to refill it. */
  5821.                         timeout = -1;
  5822.                         break;          /* Till we get an error. */
  5823.                     }
  5824.                     if (ttibn > 0) {    /* Or we get a character. */
  5825.                         x = 0;
  5826.                         timeout = -1;
  5827.                         break;
  5828.                     }
  5829.                 }
  5830.             }
  5831. #ifdef NT
  5832.             WSASafeToCancel = 0;
  5833. #endif /* NT */
  5834. #else /* !BSDSELECT */
  5835. #ifdef IBMSELECT
  5836. /*
  5837.   Was used by OS/2, currently not used, but might come in handy some day...
  5838.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  5839.   and timeval stuff since this is the only place where it is used.
  5840. */
  5841.             int socket = ttyfd;
  5842.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5843.  
  5844.             debug(F101,"netinc IBMSELECT","",timo);
  5845.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5846.                 if (select(&socket, 1, 0, 0, 100L) == 1) {
  5847.                     while (1) {
  5848.                         if (ttbufr() < 0) { /* Keep trying to refill it. */
  5849.                             timeout = -1;
  5850.                             break;      /* Till we get an error. */
  5851.                         }
  5852.                         if (ttibn > 0) { /* Or we get a character. */
  5853.                             x = 0;
  5854.                             timeout = -1;
  5855.                             break;
  5856.                         }
  5857.                     }
  5858.                 }
  5859. #ifdef LEBUF
  5860.                 else if (le_inbuf() > 0)  {
  5861.                     timeout = -1;
  5862.                     break;
  5863.                 }
  5864. #endif /* LEBUF */
  5865.             }
  5866. #else /* !IBMSELECT */
  5867. #ifdef WINSOCK
  5868.        /* Actually, under WinSock we have a better mechanism than select() */
  5869.        /* for setting timeouts (SO_RCVTIMEO, SO_SNDTIMEO) */
  5870.             SOCKET socket = ttyfd;
  5871.             debug(F101,"netinc NTSELECT","",timo);
  5872.             if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timo,
  5873.                             sizeof(timo))  == NO_ERROR)
  5874.               while (1) {
  5875.                   if (ttbufr() < 0)     /* Keep trying to refill it. */
  5876.                     break;              /* Till we get an error. */
  5877.                   if (ttibn > 0) {      /* Or we get a character. */
  5878.                       x = 0;
  5879.                       break;
  5880.                   }
  5881.               }
  5882. #else /* WINSOCK */
  5883. /*
  5884.   If we can't use select(), then we use the regular alarm()/signal()
  5885.   timeout mechanism.
  5886. */
  5887.             debug(F101,"netinc alarm","",timo);
  5888.             x = alrm_execute(ckjaddr(njbuf),timo,nettout,donetinc,failnetinc);
  5889.             ttimoff();                  /* Timer off. */
  5890. #endif /* WINSOCK */
  5891. #endif /* IBMSELECT */
  5892. #endif /* BSDSELECT */
  5893. #endif /* NT_TCP_OVERLAPPED */
  5894.         }
  5895.     }
  5896.  
  5897. #ifdef LEBUF
  5898.     if (le_inbuf() > 0) {               /* If data was inserted into the */
  5899.         if (le_getchar((CHAR *)&c) > 0) /* Local Echo buffer while the   */
  5900.           return(c);                    /* was taking place do not mix   */
  5901.     }                                   /* the le data with the net data */
  5902. #endif /* LEBUF */
  5903.     if (x < 0) {                        /* Return -1 if we failed. */
  5904.         debug(F100,"netinc timed out","",0);
  5905.         return(-1);
  5906.     } else {                            /* Otherwise */
  5907.         c = ttibuf[ttibp];              /* Return the first char in ttibuf[] */
  5908.         if (deblog) {
  5909. #ifndef COMMENT
  5910.             debug(F101,"netinc returning","",c);
  5911. #endif /* COMMENT */
  5912.             if (c == 0) {
  5913.                 debug(F101,"netinc 0 ttibn","",ttibn);
  5914.                 debug(F101,"netinc 0 ttibp","",ttibp);
  5915. #ifdef BETADEBUG
  5916.                 {
  5917. #ifdef OS2
  5918.                     extern int tt_type_mode;
  5919.                     if ( !ISVTNT(tt_type_mode) )
  5920. #endif /* OS2 */
  5921.                     hexdump("netinc &ttbuf[ttibp]",&ttibuf[ttibp],ttibn);
  5922.                 }
  5923. #endif /* BETADEBUG */
  5924.             }
  5925.         }
  5926.         ttibp++;
  5927.         ttibn--;
  5928.  
  5929. #ifdef CK_ENCRYPTION
  5930.         if (TELOPT_U(TELOPT_ENCRYPTION))
  5931.           ck_tn_decrypt(&c,1);
  5932. #endif /* CK_ENCRYPTION */
  5933.         return(c);
  5934.     }
  5935. #else /* Not using TCPIPLIB */
  5936.     return(-1);
  5937. #endif /* TCPIPLIB */
  5938. }
  5939.  
  5940. /*  N E T T O L  --  Output a string of bytes to the network  */
  5941. /*
  5942.   Call with s = pointer to string, n = length.
  5943.   Returns number of bytes actually written on success, or
  5944.   -1 on i/o error, -2 if called improperly.
  5945. */
  5946.  
  5947. int
  5948. nettol(s,n) CHAR *s; int n; {
  5949. #ifdef TCPIPLIB
  5950.     int count = 0;
  5951.     int len = n;
  5952.     int try = 0;
  5953.  
  5954.     if (ttyfd == -1) {
  5955.         debug(F100,"nettol socket is closed","",0);
  5956.         return -1;
  5957.     }
  5958.     debug(F101,"nettol TCPIPLIB ttnet","",ttnet);
  5959. #ifdef COMMENT
  5960.     hexdump("nettol",s,n);
  5961. #endif /* COMMENT */
  5962.  
  5963. #ifdef CK_KERBEROS
  5964. #ifdef KRB4
  5965. #ifdef RLOGCODE
  5966.     if (ttnproto == NP_EK4LOGIN) {
  5967.         return(krb4_des_write(ttyfd,s,n));
  5968.     }
  5969. #endif /* RLOGCODE */
  5970. #endif /* KRB4 */
  5971. #ifdef KRB5
  5972. #ifdef RLOGCODE
  5973.     if (ttnproto == NP_EK5LOGIN) {
  5974.         return(krb5_des_write(ttyfd,s,n));
  5975.     }
  5976. #endif /* RLOGCODE */
  5977. #ifdef KRB5_U2U
  5978.     if (ttnproto == NP_K5U2U) {
  5979.         return(krb5_u2u_write(ttyfd,s,n));
  5980.     }
  5981. #endif /* KRB5_U2U */
  5982. #endif /* KRB5 */
  5983. #endif /* CK_KERBEROS */
  5984.  
  5985. #ifdef CK_ENCRYPTION
  5986.     if (TELOPT_ME(TELOPT_ENCRYPTION))
  5987.       ck_tn_encrypt(s,n);
  5988. #endif /* CK_ENCRYPTION */
  5989.  
  5990. #ifdef CK_SSL
  5991.     if (ssl_active_flag || tls_active_flag) {
  5992.         int error, r;
  5993.         /* Write using SSL */
  5994.       ssl_retry:
  5995.         if (ssl_active_flag)
  5996.           r = SSL_write(ssl_con, s, len /* >1024?1024:len */);
  5997.         else
  5998.           r = SSL_write(tls_con, s, len /* >1024?1024:len */);
  5999.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,r)) {
  6000.           case SSL_ERROR_NONE:
  6001.             debug(F111,"nettol","SSL_write",r);
  6002.             if ( r == len )
  6003.                 return(n);
  6004.              s += r;
  6005.              len -= r;
  6006.              goto ssl_retry;
  6007.           case SSL_ERROR_WANT_WRITE:
  6008.             debug(F100,"nettol SSL_ERROR_WANT_WRITE","",0);
  6009.             return(-1);
  6010.           case SSL_ERROR_WANT_READ:
  6011.             debug(F100,"nettol SSL_ERROR_WANT_READ","",0);
  6012.             return(-1);
  6013.           case SSL_ERROR_SYSCALL:
  6014.               if ( r == 0 ) { /* EOF */
  6015.                   netclos();
  6016.                   return(-2);
  6017.               } else {
  6018. #ifdef NT
  6019.                   int gle = GetLastError();
  6020.                   debug(F111,"nettol SSL_ERROR_SYSCALL",
  6021.                          "GetLastError()",gle);
  6022. #endif /* NT */
  6023.                   return(-1);
  6024.               }
  6025.           case SSL_ERROR_WANT_X509_LOOKUP:
  6026.             debug(F100,"nettol SSL_ERROR_WANT_X509_LOOKUP","",0);
  6027.             netclos();
  6028.             return(-2);
  6029.           case SSL_ERROR_SSL:
  6030.             debug(F100,"nettol SSL_ERROR_SSL","",0);
  6031.             netclos();
  6032.             return(-2);
  6033.           case SSL_ERROR_ZERO_RETURN:
  6034.             debug(F100,"nettol SSL_ERROR_ZERO_RETURN","",0);
  6035.             netclos();
  6036.             return(-2);
  6037.           default:
  6038.             debug(F100,"nettol SSL_ERROR_?????","",0);
  6039.             netclos();
  6040.             return(-2);
  6041.         }
  6042.     }
  6043. #endif /* CK_SSL */
  6044.  
  6045.   nettol_retry:
  6046.     try++;                              /* Increase the try counter */
  6047.  
  6048.     if (ttnet == NET_TCPB) {
  6049. #ifdef BSDSELECT
  6050.         fd_set wfds;
  6051.         struct timeval tv;
  6052.  
  6053.         debug(F101,"nettol BSDSELECT","",0);
  6054.         tv.tv_usec = 0L;
  6055.         tv.tv_sec=30;
  6056. #ifdef NT
  6057.         WSASafeToCancel = 1;
  6058. #endif /* NT */
  6059. #ifdef STREAMING
  6060.       do_select:
  6061. #endif /* STREAMING */
  6062.         FD_ZERO(&wfds);
  6063.         FD_SET(ttyfd, &wfds);
  6064.         if (select(FD_SETSIZE, NULL,
  6065. #ifdef __DECC
  6066. #ifndef __DECC_VER
  6067.                     (int *)
  6068. #endif /* __DECC_VER */
  6069. #endif /* __DECC */
  6070.                    &wfds, NULL, &tv) < 0) {
  6071.             int s_errno = socket_errno;
  6072.             debug(F101,"nettol select failed","",s_errno);
  6073. #ifdef BETADEBUG
  6074.             printf("nettol select failed: %d\n", s_errno);
  6075. #endif /* BETADEBUG */
  6076. #ifdef NT
  6077.             WSASafeToCancel = 0;
  6078.             if (!win95selectbug)
  6079. #endif /* NT */
  6080.               return(-1);
  6081.         }
  6082.         if (!FD_ISSET(ttyfd, &wfds)) {
  6083. #ifdef STREAMING
  6084.             if (streaming)
  6085.               goto do_select;
  6086. #endif /* STREAMING */
  6087.             debug(F111,"nettol","!FD_ISSET",ttyfd);
  6088. #ifdef NT
  6089.             WSASafeToCancel = 0;
  6090.             if (!win95selectbug)
  6091. #endif /* NT */
  6092.               return(-1);
  6093.         }
  6094. #ifdef NT
  6095.         WSASafeToCancel = 0;
  6096. #endif /* NT */
  6097. #else /* BSDSELECT */
  6098. #ifdef IBMSELECT
  6099.         {
  6100.             int tries = 0;
  6101.             debug(F101,"nettol IBMSELECT","",0);
  6102.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6103.                 int count;
  6104.                 if (tries++ >= 60) {
  6105.                     /* if after 60 seconds we can't get permission to write */
  6106.                     debug(F101,"nettol select failed","",socket_errno);
  6107.                     return(-1);
  6108.                 }
  6109.                 if ((count = nettchk()) < 0) {
  6110.                     debug(F111,"nettol","nettchk()",count);
  6111.                     return(count);
  6112.                 }
  6113.             }
  6114.         }
  6115. #endif /* IBMSELECT */
  6116. #endif /* BSDSELECT */
  6117.         if ((count = socket_write(ttyfd,s,n)) < 0) {
  6118.             int s_errno = socket_errno; /* maybe a function */
  6119.             debug(F101,"nettol socket_write error","",s_errno);
  6120. #ifdef OS2
  6121.             if (os2socketerror(s_errno) < 0)
  6122.               return(-2);
  6123. #endif /* OS2 */
  6124.             return(-1);                 /* Call it an i/o error */
  6125.         }
  6126.         if (count < n) {
  6127.             debug(F111,"nettol socket_write",s,count);
  6128.             if (try > 25) {
  6129.                 /* don't try more than 25 times */
  6130.                 debug(F100,"nettol tried more than 25 times","",0);
  6131.                 return(-1);
  6132.             }
  6133.             if (count > 0) {
  6134.                 s += count;
  6135.                 n -= count;
  6136.             }
  6137.             debug(F111,"nettol retry",s,n);
  6138.             goto nettol_retry;
  6139.         } else {
  6140.             debug(F111,"nettol socket_write",s,count);
  6141.             return(len); /* success - return total length */
  6142.         }
  6143.     } else
  6144.       return(-2);
  6145. #else
  6146.     debug(F100,"nettol TCPIPLIB not defined","",0);
  6147.     return(-2);
  6148. #endif /* TCPIPLIB */
  6149. }
  6150.  
  6151. /*  N E T T O C  --   Output character to network */
  6152. /*
  6153.   Call with character to be transmitted.
  6154.   Returns 0 if transmission was successful, or
  6155.   -1 upon i/o error, or -2 if called improperly.
  6156. */
  6157. int
  6158. #ifdef CK_ANSIC
  6159. nettoc(CHAR c)
  6160. #else
  6161. nettoc(c) CHAR c;
  6162. #endif /* CK_ANSIC */
  6163. /* nettoc */ {
  6164. #ifdef UNIX
  6165.     return(ttoc(c));
  6166. #else
  6167. #ifdef TCPIPLIB
  6168.     unsigned char cc;
  6169.     if (ttyfd == -1) {
  6170.         debug(F100,"nettoc socket is closed","",0);
  6171.         return -1;
  6172.     }
  6173.     cc = c;
  6174.     debug(F101,"nettoc cc","",cc);
  6175.  
  6176. #ifdef CK_KERBEROS
  6177. #ifdef KRB4
  6178. #ifdef RLOGCODE
  6179.     if (ttnproto == NP_EK4LOGIN) {
  6180.         return(krb4_des_write(ttyfd,&cc,1)==1?0:-1);
  6181.     }
  6182. #endif /* RLOGCODE */
  6183. #endif /* KRB4 */
  6184. #ifdef KRB5
  6185. #ifdef RLOGCODE
  6186.     if (ttnproto == NP_EK5LOGIN) {
  6187.         return(krb5_des_write(ttyfd,&cc,1)==1?0:-1);
  6188.     }
  6189. #endif /* RLOGCODE */
  6190. #ifdef KRB5_U2U
  6191.     if (ttnproto == NP_K5U2U) {
  6192.         return(krb5_u2u_write(ttyfd,&cc,1)==1?0:-1);
  6193.     }
  6194. #endif /* KRB5_U2U */
  6195. #endif /* KRB5 */
  6196. #endif /* CK_KERBEROS */
  6197.  
  6198. #ifdef CK_ENCRYPTION
  6199.         if ( TELOPT_ME(TELOPT_ENCRYPTION) )
  6200.             ck_tn_encrypt(&cc,1);
  6201. #endif /* CK_ENCRYPTION */
  6202. #ifdef CK_SSL
  6203.     if (ssl_active_flag || tls_active_flag) {
  6204.         int len, error;
  6205.         /* Write using SSL */
  6206.         if (ssl_active_flag)
  6207.           len = SSL_write(ssl_con, &cc, 1);
  6208.         else
  6209.           len = SSL_write(tls_con, &cc, 1);
  6210.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
  6211.           case SSL_ERROR_NONE:
  6212.             debug(F111,"nettoc","SSL_write",len);
  6213.             return(len == 1 ? 0 : -1);
  6214.           case SSL_ERROR_WANT_WRITE:
  6215.           case SSL_ERROR_WANT_READ:
  6216.             return(-1);
  6217.           case SSL_ERROR_SYSCALL:
  6218.               if ( len == 0 ) { /* EOF */
  6219.                   netclos();
  6220.                   return(-2);
  6221.               } else {
  6222. #ifdef NT
  6223.                   int gle = GetLastError();
  6224.                   debug(F111,"nettoc SSL_ERROR_SYSCALL",
  6225.                          "GetLastError()",gle);
  6226. #endif /* NT */
  6227.                   return(-1);
  6228.               }
  6229.           case SSL_ERROR_WANT_X509_LOOKUP:
  6230.           case SSL_ERROR_SSL:
  6231.           case SSL_ERROR_ZERO_RETURN:
  6232.           default:
  6233.             netclos();
  6234.             return(-2);
  6235.         }
  6236.     }
  6237. #endif /* CK_SSL */
  6238.     if (ttnet == NET_TCPB) {
  6239. #ifdef BSDSELECT
  6240.         fd_set wfds;
  6241.         struct timeval tv;
  6242.  
  6243.         debug(F101,"nettoc BSDSELECT","",0);
  6244.         tv.tv_usec = 0L;
  6245.         tv.tv_sec = 30;
  6246.  
  6247. #ifdef STREAMING
  6248.       do_select:
  6249. #endif /* STREAMING */
  6250.  
  6251.         FD_ZERO(&wfds);
  6252.         FD_SET(ttyfd, &wfds);
  6253.         if (select(FD_SETSIZE, NULL,
  6254. #ifdef __DECC
  6255. #ifndef __DECC_VER
  6256.                    (int *)
  6257. #endif /* __DECC_VER */
  6258. #endif /* __DECC */
  6259.                    &wfds, NULL, &tv) < 0) {
  6260.             int s_errno = socket_errno;
  6261.             debug(F101,"nettoc select failed","",s_errno);
  6262. #ifdef BETADEBUG
  6263.             printf("nettoc select failed: %d\n", s_errno);
  6264. #endif /* BETADEBUG */
  6265. #ifdef NT
  6266.             WSASafeToCancel = 0;
  6267.             if (!win95selectbug)
  6268. #endif /* NT */
  6269.               return(-1);
  6270.         }
  6271.         if (!FD_ISSET(ttyfd, &wfds)) {
  6272. #ifdef STREAMING
  6273.             if (streaming)
  6274.               goto do_select;
  6275. #endif /* STREAMING */
  6276.             debug(F111,"nettoc","!FD_ISSET",ttyfd);
  6277. #ifdef NT
  6278.             WSASafeToCancel = 0;
  6279.             if (!win95selectbug)
  6280. #endif /* NT */
  6281.               return(-1);
  6282.         }
  6283. #ifdef NT
  6284.         WSASafeToCancel = 0;
  6285. #endif /* NT */
  6286. #else /* BSDSELECT */
  6287. #ifdef IBMSELECT
  6288.         {
  6289.             int tries = 0;
  6290.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6291.                 int count;
  6292.                 if (tries++ >= 60) {
  6293.                     /* if after 60 seconds we can't get permission to write */
  6294.                     debug(F101,"nettoc select failed","",socket_errno);
  6295.                     return(-1);
  6296.                 }
  6297.                 if ((count = nettchk()) < 0) {
  6298.                     debug(F111,"nettoc","nettchk()",count);
  6299.                     return(count);
  6300.                 }
  6301.             }
  6302.         }
  6303. #endif /* IBMSELECT */
  6304. #endif /* BSDSELECT */
  6305.         if (socket_write(ttyfd,&cc,1) < 1) {
  6306.             int s_errno = socket_errno;         /* maybe a function */
  6307.             debug(F101,"nettoc socket_write error","",s_errno);
  6308. #ifdef OS2
  6309.             if (os2socketerror(s_errno) < 0)
  6310.               return(-2);
  6311. #endif /* OS2 */
  6312.             return(-1);
  6313.         }
  6314.         debug(F101,"nettoc socket_write","", cc);
  6315.         return(0);
  6316.     } else return(-2);
  6317. #else
  6318.     return(-2);
  6319. #endif /* TCPIPLIB */
  6320. #endif /* UNIX */
  6321. }
  6322.  
  6323. /*  N E T F L U I  --  Flush network input buffer  */
  6324.  
  6325. #ifdef TNCODE
  6326. static int
  6327. #ifdef CK_ANSIC
  6328. netgetc(int timo)                       /* Input function to point to... */
  6329. #else  /* CK_ANSIC */
  6330. netgetc(timo) int timo;
  6331. #endif /* CK_ANSIC */
  6332. {                                       /* ...in the tn_doop() call */
  6333. #ifdef TCPIPLIB
  6334.     return netinc(timo);
  6335. #else /* TCPIPLIB */
  6336.     return ttinc(timo);
  6337. #endif /* TCPIPLIB */
  6338. }
  6339. #endif /* TNCODE */
  6340.  
  6341. int
  6342. netflui() {
  6343.     int n;
  6344.     int ch;
  6345. #ifdef NETLEBUF
  6346.     ttpush = -1;                        /* Clear the peek-ahead char */
  6347.     while (le_data && (le_inbuf() > 0)) {
  6348.         CHAR ch = '\0';
  6349.         if (le_getchar(&ch) > 0) {
  6350.             debug(F101,"ttflui le_inbuf ch","",ch);
  6351.         }
  6352.     }
  6353. #endif /* NETLEBUF */
  6354.  
  6355. #ifdef TCPIPLIB
  6356. #ifdef TNCODE
  6357.     if (ttnproto == NP_TELNET) {
  6358.         /* Netflui must process Telnet negotiations or get out of sync */
  6359.         if ((n = nettchk()) <= 0) return(0);
  6360.         while (n-- > 0) {
  6361.             ch = netinc(1);
  6362.             if (ch == IAC) {
  6363.                 extern int duplex;  /* this really shouldn't be here but ... */
  6364.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6365.                 if (tx == 1) duplex = 1;
  6366.                 else if (tx == 2) duplex = 0;
  6367.                 n = nettchk();
  6368.             }
  6369.         }
  6370.     } else
  6371. #endif /* TNCODE */
  6372.     {
  6373.         ttibuf[ttibp+ttibn] = '\0';
  6374.         debug(F111,"netflui 1",ttibuf,ttibn);
  6375. #ifdef CK_ENCRYPTION
  6376.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6377.             ck_tn_decrypt(&ttibuf[ttibp],ttibn);
  6378.         }
  6379. #endif /* CK_ENCRYPTION */
  6380.         ttibn = ttibp = 0;              /* Flush internal buffer *FIRST* */
  6381.         if (ttyfd < 1)
  6382.             return(0);
  6383.         if ((n = nettchk()) > 0) {      /* Now see what's waiting on the net */
  6384.             if (n > TTIBUFL) n = TTIBUFL;       /* and sponge it up */
  6385.             debug(F101,"netflui 2","",n);       /* ... */
  6386.             n = socket_read(ttyfd,ttibuf,n); /* into our buffer */
  6387.             if (n >= 0) ttibuf[n] = '\0';
  6388.             debug(F111,"netflui 3",ttibuf,n);
  6389. #ifdef CK_ENCRYPTION
  6390.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6391.                 ck_tn_decrypt(&ttibuf[ttibp],n);
  6392.             }
  6393. #endif /* CK_ENCRYPTION */
  6394.             ttibuf[0] = '\0';
  6395.         }
  6396.     }
  6397. #else  /* !TCPIPLIB */
  6398.     if (ttyfd < 1)
  6399.       return(0);
  6400. #ifdef TNCODE
  6401.     if (ttnproto == NP_TELNET) {
  6402.         if ((n = ttchk()) <= 0) return(0);
  6403.         while (n-- >= 0) {
  6404.             /* Netflui must process Telnet negotiations or get out of sync */
  6405.             ch = ttinc(1);
  6406.             if (ch == IAC) {
  6407.                 extern int duplex;  /* this really shouldn't be here but ... */
  6408.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6409.                 if (tx == 1) duplex = 1;
  6410.                 else if (tx == 2) duplex = 0;
  6411.                 n = ttchk();
  6412.             }
  6413.         };
  6414.     } else
  6415. #endif /* TNCODE */
  6416.     if ((n = ttchk()) > 0) {
  6417.         debug(F101,"netflui non-TCPIPLIB","",n);
  6418.         while ((n--) && ttinc(1) > -1)  /* Don't worry, ttinc() is buffered */
  6419.           ;                             /* and it handles the decryption... */
  6420.     }
  6421. #endif /* TCPIPLIB */
  6422.     return(0);
  6423. }
  6424.  
  6425. #ifdef CK_KERBEROS
  6426. /* The following two functions are required for encrypted rlogin */
  6427. /* They are called with nettoc() or nettol() are transmitting    */
  6428. /* encrypted data.  They call a function to encrypt the data     */
  6429. /* and that function needs to be able to write to/read from the  */
  6430. /* network in an unimpeded manner.  Hence, these two simple fns. */
  6431. int
  6432. net_write(fd, buf, len)
  6433.     int fd;
  6434.     register const char *buf;
  6435.     int len;
  6436. {
  6437.     int cc;
  6438.     register int wrlen = len;
  6439.     do {
  6440. #ifdef TCPIPLIB
  6441.     cc = socket_write(fd, buf, wrlen);
  6442. #else
  6443.         cc = write(fd,buf,wrlen);
  6444. #endif /* TCPIPLIB */
  6445.     if (cc < 0) {
  6446.             int s_errno = socket_errno;
  6447.             debug(F101,"net_write error","",s_errno);
  6448. #ifdef OS2
  6449.             if (os2socketerror(s_errno) < 0)
  6450.                 return(-1);
  6451.             else
  6452.                 continue;
  6453. #else /* OS2 */
  6454.         if (errno == EINTR)
  6455.         continue;
  6456.         return(-1);
  6457. #endif /* OS2 */
  6458.     }
  6459.     else {
  6460.         buf += cc;
  6461.         wrlen -= cc;
  6462.     }
  6463.     } while (wrlen > 0);
  6464.     return(len);
  6465. }
  6466. int
  6467. net_read(fd, buf, len)
  6468.     int fd;
  6469.     register char *buf;
  6470.     register int len;
  6471. {
  6472.     int cc, len2 = 0;
  6473.  
  6474.     do {
  6475. #ifdef TCPIPLIB
  6476.     cc = socket_read(fd, buf, len);
  6477. #else
  6478.         cc = read(fd,buf,len);
  6479. #endif
  6480.     if (cc < 0) {
  6481.             int s_errno = socket_errno;
  6482.             debug(F101,"net_read error","",s_errno);
  6483. #ifdef OS2
  6484.             if (os2socketerror(s_errno) < 0)
  6485.                 return(-1);
  6486. #endif /* OS2 */
  6487.         return(cc);         /* errno is already set */
  6488.     }
  6489.     else if (cc == 0) {
  6490.             netclos();
  6491.         return(len2);
  6492.     } else {
  6493.         buf += cc;
  6494.         len2 += cc;
  6495.         len -= cc;
  6496.     }
  6497.     } while (len > 0);
  6498.     return(len2);
  6499. }
  6500. #endif /* CK_KERBEROS */
  6501. #endif /* NONET */
  6502.  
  6503. /* getlocalipaddr() attempts to resolve an IP Address for the local machine.
  6504.  *   If the host is multi-homed it returns only one address.
  6505.  *
  6506.  * Two techniques are used.
  6507.  * (1) get the local host name and perform a DNS lookup, then take
  6508.  *     the first entry;
  6509.  * (2) open a UDP socket, use it to connect to a fictitious host (it's OK,
  6510.  *    no data is sent), then retrieve the local address from the socket.
  6511.  * Note: the second technique won't work on Microsoft systems.  See
  6512.  * Article ID: Q129065 PRB: Getsockname() Returns IP Address 0.0.0.0 for UDP
  6513.  */
  6514.  
  6515. /* Technique number one cannot work reliably if the machine is a laptop
  6516.  * and the hostname is associated with a physical adapter which is not
  6517.  * installed and a PPP connection is being used instead.  This is because
  6518.  * the hostname DNS lookup will succeed for the physical adapter even though
  6519.  * it would be impossible to use it.  In NT4 SP4, the gethostbyname()
  6520.  * when given the result of gethostname() returns not the real DNS entries
  6521.  * for that name+domain.  Instead it returns all of the static and dynamic
  6522.  * IP addresses assigned to any physical or virtual adapter defined in the
  6523.  * system regardless of whether or not it is installed.  The order of the
  6524.  * addresses is fixed according to the binding order in the NT registry.
  6525.  */
  6526.  
  6527. /*
  6528.  * It appears that calling gethostbyname(NULL) is more reliable than
  6529.  * calling gethostbyname(gethostname()) on Windows.  So on Windows we will
  6530.  * only call gethostbyname(NULL).
  6531.  */
  6532.  
  6533. int
  6534. getlocalipaddr() {
  6535. #ifndef datageneral
  6536.     struct sockaddr_in l_sa;
  6537.     struct sockaddr_in r_sa;
  6538.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6539.     int sock;
  6540.     int rc;
  6541.     struct in_addr laddr;
  6542.  
  6543.     /* if still not resolved, then try second strategy */
  6544.     /* This second strategy does not work on Windows */
  6545.  
  6546.     memset(&l_sa,0,slen);
  6547.     memset(&r_sa,0,slen);
  6548.  
  6549.     /* get a UDP socket */
  6550.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  6551.     if (sock != -1) {
  6552.         /* connect to arbirary port and address (NOT loopback) */
  6553.         r_sa.sin_family = AF_INET;
  6554.         r_sa.sin_port = htons(IPPORT_ECHO);
  6555.  
  6556.         /* The following is an "illegal conversion" in AOS/VS */
  6557.         /* (and who knows where else) */
  6558.  
  6559. #ifdef INADDRX
  6560.         inaddrx = inet_addr("128.127.50.1");
  6561.         r_sa.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  6562. #else
  6563.         r_sa.sin_addr.s_addr = inet_addr("128.127.50.1");
  6564. #endif /* INADDRX */
  6565.         rc = connect(sock, (struct sockaddr *) &r_sa, sizeof(struct sockaddr));
  6566.         if (!rc) {                      /* get local address */
  6567.             getsockname(sock,(struct sockaddr *)&l_sa,&slen);
  6568. #ifdef TCPIPLIB
  6569.             socket_close(sock);         /* We're done with the socket */
  6570. #else
  6571.             close(sock);
  6572. #endif /* TCPIPLIB */
  6573.             if (l_sa.sin_addr.s_addr != INADDR_ANY) {
  6574.                 myxipaddr = ntohl(l_sa.sin_addr.s_addr);
  6575.                 ckstrncpy(myipaddr,(char *)inet_ntoa(l_sa.sin_addr),20);
  6576.                 debug(F110,"getlocalipaddr setting buf to",myipaddr,0);
  6577.                 return(0);
  6578.             }
  6579.         }
  6580.     }
  6581.     return getlocalipaddrs(myipaddr,sizeof(myipaddr),0);
  6582. #else /* datageneral */
  6583.     return(-1);
  6584. #endif /* datageneral */
  6585. }
  6586.  
  6587. int
  6588. getlocalipaddrs(buf,bufsz,index)
  6589.     char * buf;
  6590.     int    bufsz;
  6591.     int    index;
  6592. /* getlocalipaddrs */ {
  6593. #ifndef datageneral
  6594.     char localhost[256];
  6595.     struct hostent * host=NULL;
  6596.     struct sockaddr_in l_sa;
  6597.     struct sockaddr_in r_sa;
  6598.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6599.     int rc;
  6600. #ifdef COMMENT
  6601.     int sock;
  6602.     char messageBuf[60];
  6603.     struct in_addr laddr;
  6604. #endif /* COMMENT */
  6605.  
  6606.     memset(&l_sa,0,slen);
  6607.     memset(&r_sa,0,slen);
  6608.  
  6609.     /* init local address (to zero) */
  6610.     l_sa.sin_addr.s_addr = INADDR_ANY;
  6611.  
  6612. #ifdef CKGHNLHOST
  6613.     rc = gethostname(localhost, 256);
  6614.     debug(F110,"getlocalipaddrs localhost",localhost,0);
  6615. #else
  6616.     /* This doesn't work on some platforms, e.g. Solaris */
  6617.     rc = 0;
  6618.     localhost[0] = '\0';
  6619. #ifdef NT
  6620.     if ( winsock_version < 20 ) {
  6621.         rc = gethostname(localhost, 256);
  6622.         debug(F110,"getlocalipaddrs localhost",localhost,0);
  6623.     }
  6624. #endif /* NT */
  6625. #endif /* CKGHNLHOST */
  6626.     if (!rc) {
  6627.         /* resolve host name for local address */
  6628.         debug(F110,"getlocalipaddrs","calling gethostbyname()",0);
  6629.         host = gethostbyname(localhost);
  6630.         debug(F111,"getlocalipaddrs","gethostbyname() returned",host);
  6631.         if (host) {
  6632. #ifdef HADDRLIST
  6633.             host = ck_copyhostent(host);
  6634.             if ( index < 0 || index > 63 || !host->h_addr_list[index] ) {
  6635.                 buf[0] = '\0';
  6636.                 return(-1);
  6637.             }
  6638.             l_sa.sin_addr.s_addr =
  6639.               *((unsigned long *) (host->h_addr_list[index]));
  6640.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),20);
  6641.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6642.  
  6643. #ifdef COMMENT
  6644.             /* This is for reporting multiple IP Address */
  6645.             while (host->h_addr_list && host->h_addr_list[0]) {
  6646.                 l_sa.sin_addr.s_addr =
  6647.                   *((unsigned long *) (host->h_addr_list[0]));
  6648.                 ckstrncpy(messageBuf,
  6649.                         (char *)inet_ntoa(l_sa.sin_addr),60);
  6650.                 if (tcp_address) {
  6651.                     if (!strcmp(messageBuf,tcp_address))
  6652.                       ckstrncpy(myipaddr,tcp_address,20);
  6653.                 }
  6654.                 debug(F110,"getlocalipaddrs ip address list", messageBuf, 0);
  6655.                 host->h_addr_list++;
  6656.             }
  6657. #endif /* COMMENT */
  6658. #else   /* HADDRLIST */
  6659.             if (index != 0) {
  6660.                 buf[0] = '\0';
  6661.                 return(-1);
  6662.             }
  6663.             l_sa.sin_addr.s_addr = *((unsigned long *) (host->h_addr));
  6664.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),bufsz);
  6665.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6666. #endif  /* HADDRLIST */
  6667.             return(0);
  6668.         } else debug(F110,
  6669.                      "getlocalipaddrs: gethostbyname() failed",
  6670.                      localhost,
  6671.                      0
  6672.                      );
  6673.     }
  6674. #endif /* datageneral */
  6675.     return(-1);
  6676. }
  6677.  
  6678. #ifdef RLOGCODE                 /* TCP/IP RLOGIN protocol support code */
  6679. int
  6680. rlog_naws() {
  6681.     struct rlog_naws {
  6682.         unsigned char id[4];
  6683.         unsigned short rows, cols, ypix, xpix;
  6684.     } nawsbuf;
  6685.  
  6686.     if (ttnet != NET_TCPB)
  6687.       return 0;
  6688.     if (ttnproto != NP_RLOGIN
  6689. #ifdef CK_KERBEROS
  6690.         && ttnproto != NP_K4LOGIN
  6691.         && ttnproto != NP_EK4LOGIN
  6692.         && ttnproto != NP_K5LOGIN
  6693.         && ttnproto != NP_EK5LOGIN
  6694. #endif /* CK_KERBEROS */
  6695.          )
  6696.       return 0;
  6697.     if (!TELOPT_ME(TELOPT_NAWS))
  6698.       return 0;
  6699.  
  6700.     debug(F100,"rlogin Window Size sent","",0);
  6701.  
  6702.     nawsbuf.id[0] = nawsbuf.id[1] = 0377;
  6703.     nawsbuf.id[2] = nawsbuf.id[3] = 's';
  6704. #ifdef OS2
  6705.     nawsbuf.rows = htons((unsigned short) (VscrnGetHeight(VTERM)
  6706.                           -(tt_status[VTERM]?1:0)));
  6707.     nawsbuf.cols = htons((unsigned short) VscrnGetWidth(VTERM));
  6708. #else /* OS2 */
  6709.     nawsbuf.rows = htons((unsigned short) tt_rows);
  6710.     nawsbuf.cols = htons((unsigned short) tt_cols);
  6711. #endif /* OS2 */
  6712.     nawsbuf.ypix = htons(0);            /* y pixels */
  6713.  
  6714.     nawsbuf.xpix = htons(0);            /* x pixels */
  6715.     if (ttol((CHAR *)(&nawsbuf), sizeof(nawsbuf)) < 0)
  6716.       return(-1);
  6717.     return(0);
  6718. }
  6719.  
  6720. #ifdef OS2ORUNIX
  6721. #define RLOGOUTBUF
  6722. #endif /* OS2 */
  6723. static int
  6724. #ifdef CK_ANSIC
  6725. rlog_ini(CHAR * hostname, int port,
  6726.          struct sockaddr_in * l_addr, struct sockaddr_in * r_addr)
  6727. #else /* CK_ANSIC */
  6728. rlog_ini(hostname, port, l_addr, r_addr)
  6729.     CHAR * hostname;
  6730.     int port;
  6731.     struct sockaddr_in * l_addr;
  6732.     struct sockaddr_in * r_addr;
  6733. #endif /* CK_ANSIC */
  6734. /* rlog_ini */ {
  6735.  
  6736. #ifdef RLOGOUTBUF
  6737.     char outbuf[512];
  6738.     int  outbytes=0;
  6739. #endif /* RLOGOUTBUF */
  6740.     int flag = 0;
  6741. #define TERMLEN 16
  6742. #define CONSPDLEN 16
  6743.     CHAR localuser[UIDBUFLEN+1];
  6744.     CHAR remoteuser[UIDBUFLEN+1];
  6745.     int userlen = 0;
  6746.     CHAR term_speed[TERMLEN+CONSPDLEN+1];
  6747. #ifdef CONGSPD
  6748.     long conspd = -1L;
  6749. #endif /* CONGSPD */
  6750. #ifdef OS2
  6751.     extern int tt_type, max_tt;
  6752.     extern struct tt_info_rec tt_info[];
  6753. #endif /* OS2 */
  6754.     int i, n;
  6755.  
  6756.     int rc = 0;
  6757.     tn_reset();                 /* This call will reset all of the Telnet */
  6758.                                 /* options and then quit.  We need to do  */
  6759.                                 /* this since we use the Telnet options   */
  6760.                                 /* to hold various state information      */
  6761.     duplex = 0;                 /* Rlogin is always remote echo */
  6762.  
  6763. #ifdef CK_TTGWSIZ
  6764. /*
  6765.   But compute the values anyway before the first read since the out-
  6766.   of-band NAWS request would arrive before the first data byte (NULL).
  6767. */
  6768. #ifdef OS2
  6769.     /* Console terminal screen rows and columns */
  6770.     debug(F101,"rlog_ini tt_rows 1","",VscrnGetHeight(VTERM)
  6771.            -(tt_status[VTERM]?1:0));
  6772.     debug(F101,"rlog_ini tt_cols 1","",VscrnGetWidth(VTERM));
  6773.     /* Not known yet */
  6774.     if (VscrnGetWidth(VTERM) < 0 ||
  6775.         VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0) < 0) {
  6776.         ttgwsiz();                      /* Try to get screen dimensions */
  6777.     }
  6778.     debug(F101,
  6779.       "rlog_ini tt_rows 2",
  6780.       "",
  6781.       VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0)
  6782.       );
  6783.     debug(F101,"rlog_ini tt_cols 2","",VscrnGetWidth(VTERM));
  6784. #else /* OS2 */
  6785.     debug(F101,"rlog_ini tt_rows 1","",tt_rows);
  6786.     debug(F101,"rlog_ini tt_cols 1","",tt_cols);
  6787.     if (tt_rows < 0 || tt_cols < 0) {   /* Not known yet */
  6788.         ttgwsiz();                      /* Try to find out */
  6789.     }
  6790.     debug(F101,"rlog_ini tt_rows 2","",tt_rows);
  6791.     debug(F101,"rlog_ini tt_cols 2","",tt_cols);
  6792. #endif /* OS2 */
  6793. #endif /* CK_TTGWSIZ */
  6794.  
  6795.     ttflui();                           /* Start by flushing the buffers */
  6796.  
  6797.     rlog_mode = RL_COOKED;
  6798.  
  6799.     /* Determine the user's local username ... */
  6800.  
  6801.     localuser[0] = '\0';
  6802. #ifdef NT
  6803.     {
  6804.         char localuid[UIDBUFLEN+1];
  6805.         unsigned long len = UIDBUFLEN;
  6806.         localuid[0] = '\0';
  6807. #ifdef COMMENT
  6808.         WNetGetUser(NULL, localuid, &len);
  6809. #else /* COMMENT */
  6810.         GetUserName(localuid,&len);
  6811. #endif /* COMMENT */
  6812.         ckstrncpy((char *)localuser,localuid,UIDBUFLEN);
  6813.     }
  6814.  
  6815.     if ( !localuser[0] )
  6816. #endif /* NT */
  6817.     {
  6818.         char * user = getenv("USER");
  6819.         if (!user)
  6820.           user = "";
  6821.         userlen = strlen(user);
  6822.         debug(F111,"rlogin getenv(USER)",user,userlen);
  6823.         ckstrncpy((char *)localuser,user,UIDBUFLEN);
  6824.         debug(F110,"rlog_ini localuser 1",localuser,0);
  6825.     }
  6826.     if ( !localuser[0] )
  6827.         strcpy((char *)localuser,"unknown");
  6828.     else if (ck_lcname) {
  6829.         cklower((char *)localuser);
  6830.         debug(F110,"rlog_ini localuser 2",localuser,0);
  6831.     }
  6832.  
  6833.     /* And the username to login with */
  6834.     if (uidbuf[0]) {
  6835.         ckstrncpy((char *)remoteuser,uidbuf,UIDBUFLEN);
  6836.         debug(F110,"rlog_ini remoteuser 1",remoteuser,0);
  6837.     } else if (localuser[0]) {
  6838.         ckstrncpy((char *)remoteuser,(char *)localuser,UIDBUFLEN);
  6839.         debug(F110,"rlog_ini remoteuser 2",remoteuser,0);
  6840.     } else {
  6841.         remoteuser[0] = '\0';
  6842.         debug(F110,"rlog_ini remoteuser 3",remoteuser,0);
  6843.     }
  6844.     if (ck_lcname)
  6845.       cklower((char *)remoteuser);
  6846.     debug(F110,"rlog_ini remoteuser 4",remoteuser,0);
  6847.  
  6848.     /* The command to issue is the terminal type and speed */
  6849.     term_speed[0] = '\0';
  6850.     if (tn_term) {                      /* SET TELNET TERMINAL-TYPE value */
  6851.         if (*tn_term) {                 /* (if any) takes precedence. */
  6852.             ckstrncpy((char *)term_speed, tn_term, TERMLEN);
  6853.             flag = 1;
  6854.         }
  6855.     } else {                            /* Otherwise the local terminal type */
  6856. #ifdef OS2
  6857.         /* In terminal-emulating versions, it's the SET TERM TYPE value */
  6858.         ckstrncpy(term_speed, (tt_type >= 0 && tt_type <= max_tt) ?
  6859.                 tt_info[tt_type].x_name : "network", TERMLEN);
  6860. #else
  6861.         /* In the others, we just look at the TERM environment variable */
  6862.         {
  6863.             char *p = getenv("TERM");
  6864.             if (p)
  6865.               ckstrncpy((char *)term_speed,p,TERMLEN);
  6866.             else
  6867.               term_speed[0] = '\0';
  6868. #ifdef VMS
  6869.             for (p = (char *) term_speed; *p; p++) {
  6870.                 if (*p == '-' && (!strcmp(p,"-80") || !strcmp(p,"-132")))
  6871.                   break;
  6872.                 else if (isupper(*p))
  6873.                   *p = tolower(*p);
  6874.             }
  6875.             *p = '\0';
  6876. #endif /* VMS */
  6877.         }
  6878. #endif /* OS2 */
  6879.     }
  6880.     n = strlen((char *)term_speed);
  6881.     if (n > 0) {                        /* We have a terminal type */
  6882.         if (!flag) {                    /* If not user-specified */
  6883.             for (i = 0; i < n; i++)     /* then lowercase it.    */
  6884.               if (isupper(term_speed[i]))
  6885.                 term_speed[i] = tolower(term_speed[i]);
  6886.         }
  6887.         debug(F110,"rlog_ini term_speed 1",term_speed,0);
  6888.  
  6889. #ifdef CONGSPD
  6890.         /* conspd() is not yet defined in all ck*tio.c modules */
  6891.         conspd = congspd();
  6892.         if (conspd > 0L) {
  6893.             ckstrncat((char *)term_speed,"/",sizeof(term_speed));
  6894.             ckstrncat((char *)term_speed,ckltoa(conspd),sizeof(term_speed));
  6895.         } else
  6896. #endif /* CONGSPD */
  6897.           ckstrncat((char *)term_speed,"/19200",sizeof(term_speed));
  6898.         debug(F110,"rlog_ini term_speed 2",term_speed,0);
  6899.     } else {
  6900.         term_speed[0] = '\0';
  6901.         debug(F110,"rlog_ini term_speed 3",term_speed,0);
  6902.     }
  6903.  
  6904. #ifdef CK_KERBEROS
  6905.     if (ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  6906.         ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) {
  6907.         int kver, encrypt, rc;
  6908.         switch (ttnproto) {
  6909.           case NP_K4LOGIN:
  6910.             kver = 4;
  6911.             encrypt = 0;
  6912.             break;
  6913.           case NP_EK4LOGIN:
  6914.             kver = 4;
  6915.             encrypt = 1;
  6916.             break;
  6917.           case NP_K5LOGIN:
  6918.             kver = 5;
  6919.             encrypt = 0;
  6920.             break;
  6921.           case NP_EK5LOGIN:
  6922.             kver = 5;
  6923.             encrypt = 1;
  6924.             break;
  6925.         default:
  6926.             kver = 0;
  6927.             encrypt = 0;
  6928.         }
  6929.         rc = ck_krb_rlogin(hostname, port,
  6930.                            localuser, remoteuser, term_speed,
  6931.                            l_addr, r_addr, kver, encrypt);
  6932.         if (!rc) {                      /* success */
  6933.             TELOPT_ME(TELOPT_NAWS) = 1;
  6934.             rc = rlog_naws();
  6935.         }
  6936.         return(rc);
  6937.     } else
  6938. #endif /* CK_KERBEROS */
  6939.     if (ttnproto == NP_RLOGIN) {
  6940. #ifdef RLOGOUTBUF
  6941.         /*
  6942.          *  The rcmds start the connection with a series of init data:
  6943.          *
  6944.          *    a port number upon which client is listening for stderr data
  6945.          *    the user's name on the client machine
  6946.          *    the user's name on the server machine
  6947.          *    the terminal_type/speed or command to execute
  6948.          */
  6949.         outbuf[outbytes++] = 0;
  6950.         strcpy((char *)outbuf+outbytes,(char *)localuser);
  6951.         outbytes += strlen((char *)localuser) + 1;
  6952.         strcpy((char *)outbuf+outbytes,(char *)remoteuser);
  6953.         outbytes += strlen((char *)remoteuser) + 1;
  6954.         strcpy((char *)outbuf+outbytes,(char *)term_speed);
  6955.         outbytes += strlen((char *)term_speed) + 1;
  6956.         rc = ttol((CHAR *)outbuf,outbytes);
  6957. #else /* RLOGOUTBUF */
  6958.         ttoc(0);                        /* Send an initial NUL as wake-up */
  6959.         /* Send each variable with the trailing NUL */
  6960.         rc = ttol(localuser,strlen((char *)localuser)+1);
  6961.         if (rc > 0)
  6962.           rc = ttol(remoteuser,strlen((char *)remoteuser)+1);
  6963.         if (rc > 0)
  6964.           rc = ttol(term_speed,strlen((char *)term_speed)+1);
  6965. #endif /* RLOGOUTBUF */
  6966.  
  6967.         /* Now we are supposed to get back a single NUL as confirmation */
  6968.         errno = 0;
  6969.         rc = ttinc(60);
  6970.         debug(F101,"rlogin first ttinc","",rc);
  6971.         if (rc > 0) {
  6972.             debug(F101,"rlogin ttinc 1","",rc);
  6973.             printf(
  6974.                "Rlogin protocol error - 0x%x received instead of 0x00\n", rc);
  6975.             return(-1);
  6976.         } else if (rc < 0) {
  6977.             debug(F101,"rlogin ttinc errno","",errno);
  6978.             /* printf("Network error: %d\n", errno); */
  6979.             return(-1);
  6980.         }
  6981.     }
  6982.     return(0);
  6983. }
  6984.  
  6985. #ifdef TCPIPLIB
  6986. static VOID
  6987. rlog_oob(oobdata, count) CHAR * oobdata; int count; {
  6988.     int i;
  6989.  
  6990.     debug(F111,"rlogin out_of_band","count",count);
  6991.  
  6992.     for (i = 0; i<count; i++)   {
  6993.         debug(F101,"rlogin out_of_band","",oobdata[i]);
  6994.         if (oobdata[i] & 0x01)
  6995.             continue;
  6996.  
  6997.         if (oobdata[i] & 0x02) { /* Flush Buffered Data not yet displayed */
  6998.             debug(F101,"rlogin Flush Buffered Data command","",oobdata[i]);
  6999.  
  7000.             /* Only flush the data if in fact we are in a mode that won't */
  7001.             /* get out of sync.  Ie, not when we are in protocol mode.    */
  7002.             switch ( what ) {
  7003.             case W_NOTHING:
  7004.             case W_CONNECT:
  7005.             case W_COMMAND:
  7006.                 ttflui();
  7007.                 break;
  7008.             }
  7009.         }
  7010.         if (oobdata[i] & 0x10) {        /* Switch to RAW mode */
  7011.             debug(F101,"rlogin Raw Mode command","",oobdata[i]);
  7012.             rlog_mode = RL_RAW;
  7013.         }
  7014.  
  7015.         if (oobdata[i] & 0x20) {        /* Switch to COOKED mode */
  7016.             debug(F101,"rlogin Cooked Mode command","",oobdata[i]);
  7017.             rlog_mode = RL_COOKED;
  7018.         }
  7019.         if (oobdata[i] & 0x80)
  7020.         {        /* Send Window Size Info */
  7021.             debug(F101,"rlogin Window Size command","",oobdata[i]);
  7022.             /* Remember to send WS Info when Window Size changes */
  7023.             if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7024.                 TELOPT_ME(TELOPT_NAWS) = 1;
  7025.                 rlog_naws();
  7026.             }
  7027.         }
  7028.     }
  7029. }
  7030. #else /* TCPIPLIB */
  7031. static SIGTYP
  7032. rlogoobh(sig) int sig; {
  7033. #ifdef SOLARIS
  7034.     char                                /* Or should it be char for all? */
  7035. #else
  7036.     CHAR
  7037. #endif /* SOLARIS */
  7038.       oobdata;
  7039.  
  7040.     /* int  count = 0; */ /* (not used) */
  7041.  
  7042.     while (recv(ttyfd, &oobdata, 1, MSG_OOB) < 0) {
  7043.       /*
  7044.        * We need to do some special processing here.
  7045.        * Just in case the socket is blocked for input
  7046.        *
  7047.        */
  7048.         switch (errno) {
  7049.           case EWOULDBLOCK:
  7050.             break;
  7051.           default:
  7052.             return;
  7053.         }
  7054.     }
  7055.     debug(F101,"rlogin out_of_band","",oobdata);
  7056.     if (oobdata == 0x02) {      /* Flush Buffered Data not yet displayed */
  7057.         debug(F101,"rlogin Flush Buffered Data command","",oobdata);
  7058.         netflui();
  7059.     }
  7060.     if (oobdata & 0x10) {               /* Switch to raw mode */
  7061.         debug(F101,"rlogin Raw Mode command","",oobdata);
  7062.         rlog_mode = RL_RAW;
  7063.     }
  7064.     if (oobdata & 0x20) {               /* Switch to cooked mode */
  7065.         debug(F101,"rlogin Cooked Mode command","",oobdata);
  7066.         rlog_mode = RL_COOKED;
  7067.     }
  7068.     if (oobdata & 0x80) {                 /* Send Window Size Info */
  7069.         debug(F101,"rlogin Window Size command","",oobdata);
  7070.         /* Remember to send WS Info when Window Size changes */
  7071.         if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7072.             TELOPT_ME(TELOPT_NAWS) = 1;
  7073.             rlog_naws();
  7074.         }
  7075.     }
  7076. }
  7077. #endif /* TCPIPLIB */
  7078. #endif /* RLOGCODE */
  7079.  
  7080. /* Send network BREAK */
  7081. /*
  7082.   Returns -1 on error, 0 if nothing happens, 1 if BREAK sent successfully.
  7083. */
  7084. int
  7085. netbreak() {
  7086.     CHAR buf[3];
  7087.     if (ttnet == NET_TCPB) {
  7088.         if (ttnproto == NP_TELNET) {
  7089. #ifdef TNCODE
  7090.             buf[0] = (CHAR) IAC; buf[1] = (CHAR) BREAK; buf[2] = (CHAR) 0;
  7091.             if (
  7092. #ifdef OS2
  7093.                 nettol((char *) buf, 2)
  7094. #else
  7095.                 ttol(buf, 2)
  7096. #endif /* OS2 */
  7097.                 < 2)
  7098.               return(-1);
  7099.             if (tn_deb || debses || deblog) {
  7100.                 extern char tn_msg[];
  7101.                 ckmakmsg(tn_msg,TN_MSG_LEN,"TELNET SENT ",TELCMD(BREAK),
  7102.                           NULL,NULL);
  7103.                 debug(F101,tn_msg,"",BREAK);
  7104.                 if (debses || tn_deb) tn_debug(tn_msg);
  7105.             }
  7106.             return(1);
  7107. #else
  7108.             debug(F100,"netbreak no TNCODE","",0);
  7109.             return(0);
  7110. #endif /* TNCODE */
  7111.         }
  7112.         /* Insert other TCP/IP protocols here */
  7113.     }
  7114.     /* Insert other networks here */
  7115.     return(0);
  7116. }
  7117. #endif /* NETCONN */
  7118.  
  7119.  
  7120. #ifdef NETCONN
  7121. #ifdef SUNX25
  7122. /*
  7123.   SunLink X.25 support by Marcello Frutig, Catholic University,
  7124.   Rio de Janeiro, Brazil, 1990.
  7125. */
  7126.  
  7127. /* PAD X.3, X.28 and X.29 support */
  7128.  
  7129. static CHAR x29err[MAXPADPARMS+3] = { X29_ERROR, INVALID_PAD_PARM, '\0' };
  7130.  
  7131. /* Initialize PAD */
  7132.  
  7133. extern CHAR padparms[];
  7134.  
  7135. VOID
  7136. initpad() {
  7137.   padparms[PAD_BREAK_CHARACTER]        = 0;  /* Break character */
  7138.   padparms[PAD_ESCAPE]                 = 1;  /* Escape permitted */
  7139.   padparms[PAD_ECHO]                   = 1;  /* Kermit PAD does echo */
  7140.   padparms[PAD_DATA_FORWARD_CHAR]      = 2;  /* forward character CR */
  7141.   padparms[PAD_DATA_FORWARD_TIMEOUT]   = 0;  /* no timeout forward condition */
  7142.   padparms[PAD_FLOW_CONTROL_BY_PAD]    = 0;  /* not used */
  7143.   padparms[PAD_SUPPRESSION_OF_SIGNALS] = 1;  /* allow PAD service signals */
  7144.   padparms[PAD_BREAK_ACTION]           = 21; /* brk action: INT pk + brk ind*/
  7145.   padparms[PAD_SUPPRESSION_OF_DATA]    = 0;  /* no supression of user data */
  7146.   padparms[PAD_PADDING_AFTER_CR]       = 0;  /* no padding after CR */
  7147.   padparms[PAD_LINE_FOLDING]           = 0;  /* no line fold */
  7148.   padparms[PAD_LINE_SPEED]             = 0;  /* line speed - don't care */
  7149.   padparms[PAD_FLOW_CONTROL_BY_USER]   = 0;  /* flow cont of PAD - not used */
  7150.   padparms[PAD_LF_AFTER_CR]            = 0;  /* no LF insertion after CR */
  7151.   padparms[PAD_PADDING_AFTER_LF]       = 0;  /* no padding after LF */
  7152.   padparms[PAD_EDITING]                = 1;  /* can edit */
  7153.   padparms[PAD_CHAR_DELETE_CHAR]       = 8;  /* character delete character */
  7154.   padparms[PAD_BUFFER_DELETE_CHAR]     = 21; /* buffer delete character */
  7155.   padparms[PAD_BUFFER_DISPLAY_CHAR]    = 18; /* buffer display character */
  7156. }
  7157.  
  7158. /* Set PAD parameters */
  7159.  
  7160. VOID
  7161. setpad(s,n) CHAR *s; int n; {
  7162.     int i;
  7163.     CHAR *ps = s;
  7164.  
  7165.     if (n < 1) {
  7166.         initpad();
  7167.     } else {
  7168.         for (i = 0; i < n; i++) {
  7169.             if (*ps > MAXPADPARMS)
  7170.               x29err[i+2] = *ps;
  7171.             else
  7172.               padparms[*ps] = *(ps+1);
  7173.             ps += 2;
  7174.         }
  7175.     }
  7176. }
  7177.  
  7178. /* Read PAD parameters */
  7179.  
  7180. VOID
  7181. readpad(s,n,r) CHAR *s; int n; CHAR *r; {
  7182.     int i;
  7183.     CHAR *ps = s;
  7184.     CHAR *pr = r;
  7185.  
  7186.     *pr++ = X29_PARAMETER_INDICATION;
  7187.     if (n > 0) {
  7188.         for (i = 0; i < n; i++, ps++) {
  7189.             if (*ps > MAXPADPARMS) {
  7190.                 x29err[i+2] = *ps++;
  7191.             } else {
  7192.                 *pr++ = *ps;
  7193.                 *pr++ = padparms[*ps++];
  7194.             }
  7195.         }
  7196.     } else {
  7197.         for (i = 1; i < MAXPADPARMS; i++) {
  7198.             *pr++ = i;
  7199.             *pr++ = padparms[i];
  7200.         }
  7201.     }
  7202. }
  7203.  
  7204. int
  7205. qbitpkt(s,n) CHAR *s; int n; {
  7206.     CHAR *ps = s;
  7207.     int x29cmd = *ps;
  7208.     CHAR *psa = s+1;
  7209.     CHAR x29resp[(MAXPADPARMS*2)+1];
  7210.  
  7211.     switch (x29cmd) {
  7212.  
  7213.         case X29_SET_PARMS:
  7214.             setpad (ps+1,n/2);
  7215.             if ((int)strlen((char *)x29err) > 2) {
  7216.                 ttol(x29err,(int)strlen((char *)x29err));
  7217.                 x29err[2] = '\0';
  7218.             }
  7219.             return (-2);
  7220.         case X29_READ_PARMS:
  7221.             readpad (ps+1,n/2,x29resp);
  7222.             setqbit ();
  7223.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7224.             if ((int)strlen((char *)x29err) > 2) {
  7225.                 ttol(x29err,(int)strlen((char *)x29err));
  7226.                 x29err[2] = '\0';
  7227.             }
  7228.             resetqbit();
  7229.             break;
  7230.         case X29_SET_AND_READ_PARMS:
  7231.             setpad (ps+1,n/2);
  7232.             readpad (ps+1,n/2,x29resp);
  7233.             setqbit();
  7234.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7235.             if ((int)strlen((char *)x29err) > 2) {
  7236.                 ttol (x29err,(int)strlen((char *)x29err));
  7237.                 x29err [2] = '\0';
  7238.             }
  7239.             resetqbit();
  7240.             return (-2);
  7241.         case X29_INVITATION_TO_CLEAR:
  7242.             (VOID) x25clear();
  7243.             return (-1);
  7244.         case X29_INDICATION_OF_BREAK:
  7245.             break;
  7246.     }
  7247.     return (0);
  7248. }
  7249.  
  7250. /* PAD break action processor */
  7251.  
  7252. VOID
  7253. breakact() {
  7254.     extern char x25obuf[MAXOX25];
  7255.     extern int obufl;
  7256.     extern int active;
  7257.     extern unsigned char tosend;
  7258.     static CHAR indbrk[3] = {
  7259.         X29_INDICATION_OF_BREAK,
  7260.         PAD_SUPPRESSION_OF_DATA,
  7261.         1
  7262.     };
  7263.     CHAR intudat, cause, diag;
  7264.  
  7265.     if (x25stat() < 0) return;  /* Ignore if no virtual call established */
  7266.  
  7267.     if (padparms[PAD_BREAK_ACTION] != 0) /* Forward condition */
  7268.         if (ttol((CHAR *)x25obuf,obufl) < 0) {
  7269.             perror ("\r\nCan't send characters");
  7270.             active = 0;
  7271.         } else {
  7272.             bzero (x25obuf,sizeof(x25obuf));
  7273.             obufl = 0;
  7274.             tosend = 0;
  7275.         };
  7276.  
  7277.     switch (padparms[PAD_BREAK_ACTION]) {
  7278.  
  7279.        case 0 : break;                  /* do nothing */
  7280.        case 1 : /* send interrupt packet with interrupt user data field = 1 */
  7281.                 intudat = 1;
  7282.                 x25intr (intudat);
  7283.                 break;
  7284.        case 2 : /* send reset packet with cause and diag = 0 */
  7285.                 cause = diag = 0;
  7286.                 x25reset (cause,diag);
  7287.                 break;
  7288.        case 5 : /* send interrupt packet with interrupt user data field = 0 */
  7289.                 intudat = 0;
  7290.                 x25intr (intudat);
  7291.                 setqbit ();
  7292.                 /* send indication of break without a parameter field */
  7293.                 ttoc(X29_INDICATION_OF_BREAK);
  7294.                 resetqbit ();
  7295.                 break;
  7296.        case 8 : active = 0;             /* leave data transfer */
  7297.                 conol ("\r\n");
  7298.                 break;
  7299.        case 21: /* send interrupt packet with interrupt user data field = 0 */
  7300.                 intudat = 0;
  7301.                 x25intr (intudat);
  7302.                 setpad (indbrk+1,2);    /* set pad to discard input */
  7303.                 setqbit ();
  7304.                 /* send indication of break with parameter field */
  7305.                 ttol (indbrk,sizeof(indbrk));
  7306.                 resetqbit ();
  7307.                 break;
  7308.      }
  7309. }
  7310.  
  7311. /* X.25 support functions */
  7312.  
  7313. X25_CAUSE_DIAG diag;
  7314.  
  7315. /*
  7316.   Convert a null-terminated string representing an X.121 address
  7317.   to a packed BCD form.
  7318. */
  7319. int
  7320. pkx121(str,bcd) char *str; CHAR *bcd; {
  7321.     int i, j;
  7322.     u_char c;
  7323.  
  7324.     i = j = 0;
  7325.     while (str[i]) {
  7326.         if (i >= 15 || str [i] < '0' || str [i] > '9')
  7327.           return (-1);
  7328.         c = str [i] - '0';
  7329.         if (i & 1)
  7330.           bcd [j++] |= c;
  7331.         else
  7332.           bcd [j] = c << 4;
  7333.         i++;
  7334.     }
  7335.     return (i);
  7336. }
  7337.  
  7338. /* Reads and prints X.25 diagnostic */
  7339.  
  7340. int
  7341. x25diag () {
  7342.     int i;
  7343.  
  7344.     bzero ((char *)&diag,sizeof(diag));
  7345.     if (ioctl(ttyfd,X25_RD_CAUSE_DIAG,&diag)) {
  7346.         perror ("Reading X.25 diagnostic");
  7347.         return(-1);
  7348.     }
  7349.     if (diag.datalen > 0) {
  7350.         printf ("X.25 Diagnostic :");
  7351.         for (i = 0; i < (int)diag.datalen; i++)
  7352.           printf(" %02h",diag.data[i])+
  7353.         printf ("\r\n");
  7354.     }
  7355.     return(0);
  7356. }
  7357.  
  7358. /* X.25 Out-of-Band Signal Handler */
  7359.  
  7360. SIGTYP
  7361. x25oobh(foo) int foo; {
  7362.     int oobtype;
  7363.     u_char oobdata;
  7364.     int t;
  7365.  
  7366.     (VOID) signal(SIGURG,x25oobh);
  7367.     do {
  7368.         if (ioctl(ttyfd,X25_OOB_TYPE,&oobtype)) {
  7369.             perror ("Getting signal type");
  7370.             return;
  7371.         }
  7372.         switch (oobtype) {
  7373.           case INT_DATA:
  7374.             if (recv(ttyfd,(char *)&oobdata,1,MSG_OOB) < 0) {
  7375.                 perror ("Receiving X.25 interrupt data");
  7376.                 return;
  7377.             }
  7378.             t = oobdata;
  7379.             printf ("\r\nInterrupt received, data = %d\r\n", t);
  7380.             break;
  7381.           case VC_RESET:
  7382.             printf ("\r\nVirtual circuit reset\r\n");
  7383.             x25diag ();
  7384.             break;
  7385.           case N_RESETS:
  7386.             printf ("\r\nReset timeout\r\n");
  7387.             break;
  7388.           case N_CLEARS:
  7389.             printf ("\r\nClear timeout\r\n");
  7390.             break;
  7391.           case MSG_TOO_LONG:
  7392.             printf ("\r\nMessage discarded, too long\r\n");
  7393.             break;
  7394.           default:
  7395.             if (oobtype) printf("\r\nUnknown oob type %d\r\n",oobtype);
  7396.             break;
  7397.         }
  7398.     } while (oobtype);
  7399. }
  7400.  
  7401. /* Send a X.25 interrupt packet */
  7402.  
  7403. int
  7404. #ifdef CK_ANSIC
  7405. x25intr(char intr)
  7406. #else
  7407. x25intr(intr) char intr;
  7408. #endif /* CK_ANSIC */
  7409. /* x25intr */ {
  7410.     if (send(ttyfd,&intr,1,MSG_OOB) < 0) return(-1);
  7411.     debug(F100,"X.25 intr","",0);
  7412.     return(0);
  7413. }
  7414.  
  7415. /* Reset X.25 virtual circuit */
  7416. int
  7417. #ifdef CK_ANSIC
  7418. x25reset(char cause, char diagn)
  7419. #else
  7420. x25reset(cause, diagn) char cause; char diagn;
  7421. #endif /* CK_ANSIC */
  7422. /* x25reset */ {
  7423.     bzero ((char *)&diag,sizeof(diag));
  7424.     diag.flags   = 0;
  7425.     diag.datalen = 2;
  7426.     diag.data[0] = cause;
  7427.     diag.data[1] = diagn;
  7428.     if (ioctl(ttyfd,X25_WR_CAUSE_DIAG,&diag) < 0)
  7429.       return(-1);
  7430.     debug(F100,"X.25 reset","",0);
  7431.     return(0);
  7432. }
  7433.  
  7434. /* Clear X.25 virtual circuit */
  7435. int
  7436. x25clear() {
  7437.     int i;
  7438.     debug(F100,"X.25 clear","",0);
  7439.     bzero ((char *)&diag,sizeof(diag));
  7440.     diag.flags = (1 << DIAG_TYPE);
  7441.     diag.datalen = 2;
  7442.     diag.data[0] = 0;
  7443.     diag.data[1] = 0;
  7444.     ioctl (ttyfd,X25_WR_CAUSE_DIAG,&diag); /* Send Clear Request */
  7445.     return(ttclos(0));                  /* Close socket */
  7446. }
  7447.  
  7448. /* X.25 status */
  7449. int
  7450. x25stat() {
  7451.     if (ttyfd == -1) return (-1);
  7452.     return(0);
  7453. }
  7454.  
  7455. /* Set Q_BIT on */
  7456. VOID
  7457. setqbit() {
  7458.     static int qbiton = 1 << Q_BIT;
  7459.     ioctl (ttyfd,X25_SEND_TYPE,&qbiton);
  7460. }
  7461.  
  7462. /* Set Q_BIT off */
  7463. VOID
  7464. resetqbit() {
  7465.     static int qbitoff = 0;
  7466.     ioctl (ttyfd,X25_SEND_TYPE,&qbitoff);
  7467. }
  7468.  
  7469. /* Read n characters from X.25 circuit into buf */
  7470.  
  7471. int
  7472. x25xin(n,buf) int n; CHAR *buf; {
  7473.     register int x, c;
  7474.     int qpkt;
  7475.  
  7476.     do {
  7477.         x = read(ttyfd,buf,n);
  7478.         if (buf[0] & (1 << Q_BIT)) { /* If Q_BIT packet, process it */
  7479.             /* If return -1 : invitation to clear; -2 : PAD changes */
  7480.             if ((c=qbitpkt(buf+1,x-2)) < 0) return(c);
  7481.             qpkt = 1;
  7482.         } else qpkt = 0;
  7483.     } while (qpkt);
  7484.  
  7485. #ifdef COMMENT                  /* Disabled by Stephen Riehm 19.12.97 */
  7486.     /* BUG!
  7487.      * if buf[] is full, then this null lands in nirvana!
  7488.      * I was unable to find any code which needs a trailing null in buf[]
  7489.      */
  7490.     if (x > 0) buf[x] = '\0';
  7491. #endif /* COMMENT */
  7492.     if (x < 1) x = -1;
  7493.     debug(F101,"x25xin x","",x);
  7494.  
  7495.     return(x);
  7496. }
  7497.  
  7498. #ifdef COMMENT /* NO LONGER NEEDED! */
  7499. /* X.25 read a line */
  7500.  
  7501. int
  7502. #ifdef PARSENSE
  7503. #ifdef CK_ANSIC
  7504. x25inl(CHAR *dest, int max,int timo, CHAR eol, CHAR start)
  7505. #else
  7506. x25inl(dest,max,timo,eol,start) int max,timo; CHAR *dest, eol, start;
  7507. #endif /* CK_ANSIC */
  7508. #else /* not PARSENSE */
  7509. #ifdef CK_ANSIC
  7510. x25inl(CHAR *dest, int max,int timo, CHAR eol)
  7511. #else
  7512. x25inl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  7513. #endif /* __SDTC__ */
  7514. #endif /*PARSENSE */
  7515.  /* x25inl */ {
  7516.     CHAR *pdest;
  7517.     int pktype, goteol, rest, n;
  7518.     int i, flag = 0;
  7519.     extern int ttprty, ttpflg;
  7520.     int ttpmsk;
  7521.  
  7522.     ttpmsk = (ttprty) ? 0177 : 0377;    /* Set parity stripping mask */
  7523.  
  7524.     debug(F101,"x25inl max","",max);
  7525.     debug(F101,"x25inl eol","",eol);
  7526.     pdest  = dest;
  7527.     rest   = max;
  7528.     goteol = 0;
  7529.     do {
  7530.         n = read(ttyfd,pdest,rest);
  7531.         n--;
  7532.         pktype = *pdest & 0x7f;
  7533.         switch (pktype) {
  7534.           case 1 << Q_BIT:
  7535.             if (qbitpkt(pdest+1,--n) < 0) return(-2);
  7536.             break;
  7537.           default:
  7538.             if (flag == 0) { /* if not in packet, search start */
  7539.                 for (i = 1; (i < n) &&
  7540.                      !(flag = ((dest[i] & 0x7f) == start));
  7541.                      i++);
  7542.                 if (flag == 0) { /* not found, discard junk */
  7543.                     debug(F101,"x25inl skipping","",n);
  7544.                     continue;
  7545.                 } else {                /* found, discard junk before start */
  7546.                     int k;
  7547.                     n = n - i + 1;
  7548.                     for (k = 1; k <= n; k++, i++) dest[k] = dest[i];
  7549.                 }
  7550.             }
  7551.             for (i = 0; (i < n) && /* search for eol */
  7552.                  !(goteol=(((*pdest = *(pdest+1)&ttpmsk)&0x7f)== eol));
  7553.                  i++,pdest++);
  7554.             *pdest = '\0';
  7555.             rest -= n;
  7556.         }
  7557.     } while ((rest > 0) && (!goteol));
  7558.  
  7559.     if (goteol) {
  7560.         n = max - rest;
  7561.         debug (F111,"x25inl X.25 got",(char *) dest,n);
  7562.         if (timo) ttimoff();
  7563.         if (ttpflg++ == 0 && ttprty == 0) {
  7564.             if ((ttprty = parchk(dest,start,n)) > 0) {
  7565.                 int j;
  7566.                 debug(F101,"x25inl senses parity","",ttprty);
  7567.                 debug(F110,"x25inl packet before",(char *)dest,0);
  7568.                 ttpmsk = 0x7f;
  7569.                 for (j = 0; j < n; j++)
  7570.                   dest[j] &= 0x7f; /* Strip parity from packet */
  7571.                 debug(F110,"x25inl packet after ",dest,0);
  7572.             } else {
  7573.                 debug(F101,"parchk","",ttprty);
  7574.                 if (ttprty < 0) { ttprty = 0; n = -1; }
  7575.             }
  7576.         }
  7577.         ttimoff();
  7578.         return(n);
  7579.     }
  7580.     ttimoff();
  7581.     return(-1);
  7582. }
  7583. #endif /* COMMENT */
  7584. #endif /* SUNX25 */
  7585.  
  7586. #ifdef IBMX25
  7587. /*
  7588.  * IBM X25 support - using the NPI streams interface
  7589.  * written by Stephen Riehm, pc-plus, Munich Germany
  7590.  */
  7591.  
  7592. /* riehm: missing functions / TODO list */
  7593.  
  7594. /*
  7595.   x25intr() - Send an interrupt packet
  7596. */
  7597.  
  7598. /* return an error message depending on packet type */
  7599. char *
  7600. x25err(n) int n; {
  7601.     static char buf[30];
  7602.     switch (n) {
  7603.       case NBADADDR:     return "invalid address";
  7604.       case NBADOPT:      return "invalid options";
  7605.       case NACCESS:      return "no permission";
  7606.       case NNOADDR:      return "unable to allocate address";
  7607.       case NOUTSTATE:    return "invalid state";
  7608.       case NBADSEQ:      return "invalid sequence number";
  7609.       case NSYSERR:      return "system error";
  7610.       case NBADDATA:     return "invalid data size";
  7611.       case NBADFLAG:     return "invalid flag";
  7612.       case NNOTSUPPORT:  return "unsupported primitive";
  7613.       case NBOUND:       return "address in use";
  7614.       case NBADQOSPARAM: return "bad QOS parameters";
  7615.       case NBADQOSTYPE:  return "bad QOS type";
  7616.       case NBADTOKEN:    return "bad token value";
  7617.       case NNOPROTOID:   return "protocol id could not be allocated";
  7618.       case NODDCUD:      return "odd length call user data";
  7619.       default:
  7620.         ckmakmsg(buf,sizeof(buf),"Unknown NPI error ",ckitoa(n),NULL,NULL);
  7621.         return buf;
  7622.     }
  7623. }
  7624.  
  7625. /* turn a meaningless primitive number into a meaningful primitive name */
  7626. char *
  7627. x25prim(n) int n; {
  7628.     static char buf[30];
  7629.     switch(n) {
  7630.       case N_BIND_ACK:     return "N_BIND_ACK";
  7631.       case N_BIND_REQ:     return "N_BIND_REQ";
  7632.       case N_CONN_CON:     return "N_CONN_CON";
  7633.       case N_CONN_IND:     return "N_CONN_IND";
  7634.       case N_CONN_REQ:     return "N_CONN_REQ";
  7635.       case N_CONN_RES:     return "N_CONN_RES";
  7636.       case N_DATACK_IND:   return "N_DATAACK_IND";
  7637.       case N_DATACK_REQ:   return "N_DATAACK_REQ";
  7638.       case N_DATA_IND:     return "N_DATA_IND";
  7639.       case N_DATA_REQ:     return "N_DATA_REQ";
  7640.       case N_DISCON_IND:   return "N_DISCON_IND";
  7641.       case N_DISCON_REQ:   return "N_DISCON_REQ";
  7642.       case N_ERROR_ACK:    return "N_ERROR_ACK";
  7643.       case N_EXDATA_IND:   return "N_EXDATA_IND";
  7644.       case N_EXDATA_REQ:   return "N_EXDATA_REQ";
  7645.       case N_INFO_ACK:     return "N_INFO_ACK";
  7646.       case N_INFO_REQ:     return "N_INFO_REQ";
  7647.       case N_OK_ACK:       return "N_OK_ACK";
  7648.       case N_OPTMGMT_REQ:  return "N_OPTMGMT_REQ";
  7649.       case N_RESET_CON:    return "N_RESET_CON";
  7650.       case N_RESET_IND:    return "N_RESET_IND";
  7651.       case N_RESET_REQ:    return "N_RESET_REQ";
  7652.       case N_RESET_RES:    return "N_RESET_RES";
  7653.       case N_UDERROR_IND:  return "N_UDERROR_IND";
  7654.       case N_UNBIND_REQ:   return "N_UNBIND_REQ";
  7655.       case N_UNITDATA_REQ: return "N_UNITDATA_REQ";
  7656.       case N_UNITDATA_IND: return "N_UNITDATA_IND";
  7657.       default:
  7658.         ckmakmsg(buf,sizeof(buf),"UNKNOWN (",ckitoa(n),")",NULL);
  7659.         return buf;
  7660.     }
  7661. }
  7662.  
  7663. /*****************************************************************************
  7664.  * Function: x25getmsg()
  7665.  * Description: get a STREAMS message, and check it for errors
  7666.  *
  7667.  * Parameters:
  7668.  * fd           - file descriptor to x25 device (opened)
  7669.  * control      - control buffer (pre-allocated)
  7670.  * ctl_size     - size of control buffer
  7671.  * data         - data buffer (pre-allocated)
  7672.  * data_size    - size of data buffer
  7673.  * flags        - flags for getmsg()
  7674.  * expected     - expected Primitive type
  7675.  *
  7676.  * Return Value:
  7677.  *      >= 0    OK (size of data returned)
  7678.  *      -1      error
  7679.  *
  7680.  */
  7681. int
  7682. x25getmsg( fd, control, ctl_size, data, data_size, get_flags, expected )
  7683.     int                 fd;             /* X25 device (opened) */
  7684.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  7685.     int                 ctl_size;       /* size of control buffer */
  7686.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  7687.     int                 data_size;      /* size of data buffer */
  7688.     int                 *get_flags;     /* getmsg() flags */
  7689.     int                 expected;       /* expected primitive type */
  7690. /* x25getmsg */ {
  7691.     int                 rc = 0;         /* return code */
  7692.     struct strbuf       *get_ctl=NULL;  /* getmsg control */
  7693.     struct strbuf       *get_data=NULL; /* getmsg data */
  7694.     int                 more = 0;       /* flag for more data etc */
  7695.     int                 file_status = -1; /* file async status */
  7696.     N_npi_ctl_t         * result;       /* pointer to simplify switch() */
  7697.     int                 packet_type = -1; /* unknown packet thus far */
  7698.  
  7699. #ifdef TRACE
  7700.     printf( "TRACE: entering x25getmsg\n" );
  7701. #endif /* TRACE */
  7702.  
  7703.     debug( F110, "x25getmsg waiting for packet ", x25prim( expected ), 0);
  7704.     /* prepare the control structures for getmsg */
  7705.     if (control) {
  7706.         if ((get_ctl = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7707.           {
  7708.               perror("kermit x25getmsg(): get_ctl malloc failed\n");
  7709.               debug( F100, "x25getmsg malloc failed for get_ctl\n", "", 0);
  7710.               return(-1);
  7711.           }
  7712.         /* allow getmsg to return an unexpected packet type (which may be
  7713.          * larger than the expected one)
  7714.          */
  7715.         get_ctl->maxlen = NPI_MAX_CTL;
  7716.         get_ctl->len = 0;
  7717.         get_ctl->buf = (char *)control;
  7718.     } else {
  7719.         printf(
  7720.  "kermit x25getmsg(): internal error. control buffer MUST be pre-allocated!\n"
  7721.                );
  7722.         debug(F100,"x25getmsg internal error. no buffer pre-allocated","",0);
  7723.         return( -1 );
  7724.     }
  7725.     if (data) {
  7726.         if ((get_data = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7727.           {
  7728.             perror("kermit x25getmsg(): get_data malloc failed\n");
  7729.             debug( F100, "x25getmsg malloc failed for get_data\n", "", 0);
  7730.             return(-1);
  7731.         }
  7732.         get_data->maxlen = (NPI_MAX_DATA < data_size ) ?
  7733.           NPI_MAX_DATA :
  7734.             data_size;
  7735.         get_data->len = 0;
  7736.         get_data->buf = (char *)data;
  7737.     }
  7738.  
  7739.     /* get an X.25 packet -
  7740.      * it may be any kind of packet, so check for special cases
  7741.      * it may be split into multiple parts - so loop if necessary
  7742.      */
  7743.     do {
  7744. #ifdef DEBUG
  7745.         printf( "kermit: x25getmsg(): getting a message\n" );
  7746. #endif /* DEBUG */
  7747.         errno = 0;
  7748.         if ((more = getmsg(fd, get_ctl, get_data, get_flags)) < 0) {
  7749. #ifdef DEBUG
  7750.             printf( "kermit: x25getmsg(): getmsg returned an error\n" );
  7751.             perror( "getmsg error was" );
  7752. #endif /* DEBUG */
  7753.             debug(F101, "x25getmsg getmsg returned an error\n", "", errno);
  7754.             if ((errno == EAGAIN) && (get_data && (get_data->len > 0)) ) {
  7755.                 /* was in non-blocking mode, nothing to get, but we're
  7756.                  * already waiting for the rest of the packet -
  7757.                  * switch to blocking mode for the next read.
  7758.                  * file_status used to reset file status before returning
  7759.                  */
  7760.                 if ((file_status = fcntl(fd, F_GETFL, 0)) < 0
  7761.                     || fcntl(fd, F_SETFL, file_status & ~O_NDELAY) < 0)
  7762.                   {
  7763.                       perror("x25getmsg(): couldn't change x25 blocking mode");
  7764.                       debug(F101,
  7765.                             "x25getmsg fcntl returned an error\n", "", errno);
  7766.                       /* netclos(); */
  7767.                       rc = -1;
  7768.                       break;
  7769.                   } else {
  7770.                       /* loop again into a blocking getmsg() */
  7771.                       continue;
  7772.                   }
  7773.             } else {
  7774.                 /* no data to get in non-blocking mode - return empty handed */
  7775.                 perror( "x25getmsg(): getmsg failed" );
  7776.                 debug(F101,"x25getmsg getmsg returned an error\n", "", errno);
  7777.                 rc = -1;
  7778.                 break;
  7779.             }
  7780.         } else if (more & MORECTL) {
  7781.             /* panic - the control information was larger than the
  7782.              * maximum control buffer size!
  7783.              */
  7784.             /* riehm: close connection? */
  7785. #ifdef DEBUG
  7786.             printf("x25getmsg(): received partial control packet - panic\n");
  7787. #endif /* DEBUG */
  7788.             debug( F101, "x25getmsg getmsg bad control block\n", "", errno);
  7789.             rc = -1;
  7790.             break;
  7791.         }
  7792.  
  7793.         if (result = (N_npi_ctl_t *)control) {
  7794.             packet_type = result->bind_ack.PRIM_type;
  7795.             if (packet_type != N_OK_ACK) {
  7796.                 x25lastmsg = packet_type;
  7797.             }
  7798.         }
  7799. #ifdef DEBUG
  7800.         /* printf( "kermit: x25getmsg(): getting " ); */
  7801.         if (get_ctl->len > 0) {
  7802.             x25dump_prim(result);
  7803.         }
  7804.         debug(F110,
  7805.               "x25getmsg got packet ",
  7806.               x25prim( result->bind_ack.PRIM_type ),
  7807.               0
  7808.               );
  7809. #endif /* DEBUG */
  7810.  
  7811.         if (get_ctl->len >= (int)sizeof(result->bind_ack.PRIM_type)) {
  7812.             /* not as pretty as a switch(), but switch can't handle
  7813.              * runtime variable values :-(
  7814.              */
  7815.             if (packet_type == expected ) {
  7816.                 /* got what we wanted, special case for DATA_IND
  7817.                  * packets though */
  7818.                 /* riehm: check Q-bit ? */
  7819. #ifdef DEBUG
  7820.                 printf("x25getmsg(): got expected packet\nrc is %d\n", rc);
  7821. #endif /* DEBUG */
  7822.                 if (packet_type == N_DATA_IND ) {
  7823.                     /* data received. May be incomplete, even though
  7824.                      * getmsg returned OK
  7825.                      */
  7826.                     if (result->data_ind.DATA_xfer_flags & N_MORE_DATA_FLAG)
  7827.                         more |= MOREDATA;
  7828.                     if (result->data_ind.DATA_xfer_flags & N_RC_FLAG)
  7829.                         printf( "x25getmsg(): data packet wants ack\n" );
  7830.                 }
  7831.             } else if( packet_type == N_DISCON_IND) {
  7832.                 printf( "X25 diconnected\n" );
  7833.                 /* riehm: need to acknowledge a disconnection? */
  7834.                 x25clear();
  7835.                 /* x25unbind( ttyfd ); */
  7836.                 rc = -1;
  7837.             } else if( packet_type == N_ERROR_ACK) {
  7838.                 errno = result->error_ack.UNIX_error;
  7839.                 perror( "X25 error received" );
  7840.                 rc = -1;
  7841.             } else {
  7842.                 printf("x25getmsg(): failed %s\n", x25err(packet_type));
  7843.                 rc = -1;
  7844.             }
  7845.         }
  7846. #ifdef COMMENT
  7847.         else {
  7848.             /* Panic - no control data */
  7849.             printf( "kermit: x25getmsg(): no control data with packet\n" );
  7850.             rc = -1;
  7851.         }
  7852. #endif /* COMMENT */
  7853.  
  7854.         if (get_data && (get_data->len >= 0)) {
  7855.             get_data->buf += get_data->len;
  7856.             get_data->maxlen -= get_data->len;
  7857.         }
  7858.     } while ((rc == 0)
  7859.              && (get_data && (get_data->maxlen > 0))
  7860.              && (more & MOREDATA)
  7861.              );
  7862.  
  7863.     /* return the file status to its original value, unless its still
  7864.      * set to -1, or one of the fcntl's failed */
  7865.     if ((file_status >= 0) && fcntl(fd, F_SETFL, file_status) < 0)
  7866.         rc = -1;
  7867.  
  7868.     /*
  7869.      * Verify that we received an expected primitive
  7870.      * there is apparantly an error case where the primitive is set
  7871.      * correctly, but there is not enough data in the control structure
  7872.      */
  7873.     if ((packet_type != expected) && (get_ctl->len >= ctl_size) ) {
  7874.         fprintf(stderr,
  7875.                 "x25getmsg(): %s NOT received. Primitive received was %s\n",
  7876.                 x25prim( expected ), x25prim( packet_type ));
  7877.         debug(F110, "x25getmsg got an unexpected packet ",
  7878.               x25prim(packet_type),
  7879.               0
  7880.               );
  7881.         rc = -1;
  7882.     }
  7883.  
  7884.     if (rc == 0) {
  7885.         if (get_data && ( get_data->len >= 0)) {
  7886.             rc = get_data->len;
  7887.         }
  7888.     }
  7889.  
  7890.     if (get_ctl)  { free(get_ctl); get_ctl = NULL; }
  7891.     if (get_data) { free(get_data); get_data = NULL; }
  7892.  
  7893. #ifdef COMMENT
  7894. #ifdef DEBUG
  7895.     printf( "kermit x25getmsg(): returning %d\n", rc );
  7896. #endif /* DEBUG */
  7897. #endif /* COMMENT */
  7898.     debug(F110, "x25getmsg returning packet ", x25prim( packet_type ), 0);
  7899.  
  7900. #ifdef TRACE
  7901.     printf( "TRACE: leaving x25getmsg\n" );
  7902. #endif /* TRACE */
  7903.     return(rc);
  7904. }
  7905.  
  7906. /*****************************************************************************
  7907.  * Function: x25putmsg()
  7908.  *
  7909.  * Description:
  7910.  *      send a message to a X25 STREAM
  7911.  *
  7912.  * Parameters:
  7913.  *      fd              - file descriptor to x25 device (opened)
  7914.  *      control         - control buffer (pre-allocated)
  7915.  *      data            - data buffer (pre-allocated)
  7916.  *      data_len        - length of data to be transmitted
  7917.  *      put_flags       - flags for putmsg()
  7918.  *
  7919.  * Return Value:
  7920.  *      >= 0    number of bytes transmitted
  7921.  *      -1      error
  7922.  */
  7923. int
  7924. x25putmsg(fd, control, data, data_len, put_flags)
  7925.     int                 fd;             /* X25 device (opened) */
  7926.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  7927.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  7928.     int                 data_len;       /* length of data (not the size of
  7929.                                            the buffer) */
  7930.     int                 *put_flags;     /* putmsg() flags */
  7931. /* x25putmsg */ {
  7932.     int                 rc = 0;         /* return code */
  7933.     ulong               type;           /* primitive type */
  7934.     struct strbuf       *put_ctl = NULL; /* putmsg control */
  7935.     struct strbuf       *put_data = NULL; /* putmsg data */
  7936.  
  7937. #ifdef TRACE
  7938.     printf( "TRACE: entering x25putmsg\n" );
  7939. #endif /* TRACE */
  7940.  
  7941. #ifdef DEBUG
  7942.     printf( "kermit: x25putmsg(): putting " );
  7943.     x25dump_prim( control );
  7944.     printf( "\tdata:\t\t" );
  7945.     x25dump_data( data, 0, data_len );
  7946.     debug(F110,"x25putmsg: putting packet ",x25prim(control->PRIM_type),0);
  7947. #endif /* DEBUG */
  7948.  
  7949.     if (control) {
  7950.         put_ctl = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  7951.         if (put_ctl == NULL) {
  7952.             perror("kermit x25putmsg(): put_ctl malloc failed\n");
  7953.             return(-1);
  7954.         }
  7955.         put_ctl->maxlen = 0;                    /* unused by putmsg */
  7956.         put_ctl->len = NPI_MAX_CTL;
  7957.         put_ctl->buf = (char *)control;
  7958.     }
  7959.     if (data && ( data_len > 0)) {
  7960.         put_data = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  7961.         if( put_data == NULL) {
  7962.             perror("kermit x25putmsg(): put_data malloc failed\n");
  7963.             return(-1);
  7964.         }
  7965.         put_data->maxlen = 0;                   /* unused by putmsg */
  7966.         put_data->len = data_len;
  7967.         put_data->buf = (char *)data;
  7968.     }
  7969.  
  7970.     errno = 0;
  7971.     rc = putmsg (fd, put_ctl, put_data, 0);
  7972.     if (rc < 0) {
  7973.         printf("x25putmsg(): couldn't put %s\n",x25prim(control->PRIM_type));
  7974.         perror("kermit: x25putmsg(): putmsg failed");
  7975.         return(-1);
  7976.     }
  7977.  
  7978.     /* riehm: this should perhaps be discounted! */
  7979.     x25lastmsg = control->PRIM_type;
  7980.  
  7981. #ifdef COMMENT
  7982. #ifdef DEBUG
  7983.     printf( "kermit debug: x25putmsg() returning %d\n", data_len );
  7984. #endif /* DEBUG */
  7985. #endif /* COMMENT */
  7986.     debug( F101, "x25putmsg block size put ", "", data_len);
  7987.  
  7988. #ifdef TRACE
  7989.     printf( "TRACE: leaving x25putmsg\n" );
  7990. #endif /* TRACE */
  7991.  
  7992.     return( data_len );
  7993. }
  7994.  
  7995. /*****************************************************************************
  7996. * Function: x25bind
  7997. * Description:  The bind submitted to NPI provides the information required
  7998. *               by the packet layer for it to listen for suitable incoming
  7999. *               calls.
  8000. *
  8001. * WARNING:
  8002. *
  8003. * This routine needs to be called in a completely different manner for
  8004. * the client and server side. When starting a client, the
  8005. * num_waiting_calls and CUD information should all be set to 0! The
  8006. * client's CUD must be inserted in the CONN_REQ data block.
  8007. * When starting a server, the CUD must be set to a CUD pattern, and
  8008. * the number of waiting calls should be set to a number other than 0.
  8009. * (num waiting calls is the number of incomming calls which are to be
  8010. * put on hold while the server is servicing another client.)
  8011. *
  8012. * Who invented this crap?
  8013. *
  8014. * Parameters:
  8015. *       fd              - X25 device (opened)
  8016. *       addr            - local address
  8017. *       cud             - User Data (null terminated)
  8018. *       cud_len         - User Data length
  8019. *       num_waiting_calls - number of outstanding calls allowed on this stream
  8020. *       line            - logical port number (1)
  8021. *       flags           - 0, DEFAULT_LISTENER or TOKEN_REQUEST
  8022. *
  8023. * Return Value:
  8024. *       if binding is successful, 0 is returned for a client, and a token is
  8025. *       returned for a server
  8026. *
  8027. * Return code: 0 if successful
  8028. *              -1 if unsuccessful
  8029. *****************************************************************************/
  8030.  
  8031. ulong
  8032. x25bind(fd, addr, cud, cud_len, num_waiting_calls, line, bind_flags)
  8033.     int fd;                             /* X25 device (opened) */
  8034.     char * addr;                        /* local address */
  8035.     char * cud;                         /* Call User Data (null terminated) */
  8036.     int cud_len;                        /* User Data length */
  8037.     int num_waiting_calls;              /* Outstanding calls allowed */
  8038.     int line;                           /* logical port number */
  8039.     ulong bind_flags;           /* 0, DEFAULT_LISTENER or TOKEN_REQUEST */
  8040. /* x25bind */ {
  8041.     ulong rc;                           /* return code */
  8042.     int get_flags;                      /* priority flag passed to getmsg */
  8043.     int put_flags = 0;                  /* output flags for putmsg, always 0 */
  8044.     ulong type;                         /* primitive type */
  8045.     N_bind_req_t *bind_req;             /* pointer to N_BIND_REQ primitive */
  8046.     N_bind_ack_t *bind_ack;             /* pointer to N_BIND_ACK primitive */
  8047.     char *addtl_info;                   /* pointer to info in addition to
  8048.                                          * the N_BIND_REQ primitive that is
  8049.                                          * passed in the control structure
  8050.                                          * to putmsg */
  8051.     int addr_len = 0;                   /* length of address string */
  8052.     ulong bind_req_t_size;              /* for debugging only */
  8053.  
  8054. #ifdef TRACE
  8055.     printf("TRACE: entering x25bind\n" );
  8056. #endif /* TRACE */
  8057.  
  8058. #ifdef DEBUG
  8059.     printf("TRACE: x25bind( %d, %s, %s, %d, %d )\n",
  8060.            fd, addr, cud, line, bind_flags
  8061.            );
  8062. #endif /* DEBUG */
  8063.  
  8064.     /*
  8065.      * Allocate  and zero out space to hold the control portion of the
  8066.      * message passed to putmsg. This will contain the N_BIND_REQ
  8067.      * primitive and any additional info required for that.
  8068.      *
  8069.      * Note: allocated space is the size of the union typedef
  8070.      * N_npi_ctl_t to allow the use fo the generic x25putmsg routine.
  8071.      */
  8072.     bind_req = (N_bind_req_t *) malloc(sizeof( N_npi_ctl_t));
  8073.     if (bind_req == NULL) {
  8074.         perror("kermit: x25bind(): bind_req malloc failed");
  8075.         debug(F100, "x25bind bind_req malloc failed", "", 0);
  8076.         return(-1);
  8077.     }
  8078.     bzero((char *)bind_req, sizeof(N_npi_ctl_t));
  8079.  
  8080.     /* Build the Bind Request Primitive */
  8081.     bind_req->PRIM_type = (ulong) N_BIND_REQ;
  8082.  
  8083.     /* Note that the address length is n+2 and NOT n. Two bytes MUST preceed
  8084.      * the actual address in an N_BIND_REQ. The first byte contains the
  8085.      * line number being used with this address, and the second byte is the
  8086.      * X.121 address prefix, which must be zero.
  8087.      */
  8088.     addr_len = strlen(addr);
  8089.     bind_req->ADDR_length = (ulong) (addr_len + 2);
  8090.     bind_req->ADDR_offset = (ulong)(sizeof(N_bind_req_t));
  8091.     bind_req->CONIND_number = (ulong)num_waiting_calls; /* server only */
  8092.     bind_req->BIND_flags = (ulong) bind_flags; /* 0 in client */
  8093.     bind_req->PROTOID_length = (ulong) cud_len; /* 0 in client */
  8094.     if (cud_len == 0) {
  8095.         bind_req->PROTOID_offset = (ulong) 0;
  8096.     } else {
  8097.         /* need to remember the trailing NULL in the address - not
  8098.          * counted in the address length
  8099.          */
  8100.         bind_req->PROTOID_offset
  8101.           = (ulong) (sizeof(N_bind_req_t) + bind_req->ADDR_length);
  8102.     }
  8103.  
  8104.     /*
  8105.      * Now fill in the additional information required with this primitive
  8106.      * (address and protocol information (Call User Data))
  8107.      */
  8108.     addtl_info = (char *) ((void *)bind_req + bind_req->ADDR_offset);
  8109.     /*
  8110.      * The bitwise "&" ensures that the line number is only one byte long
  8111.      */
  8112.     *addtl_info++ = (char) line & 0xff;
  8113.     *addtl_info++ = (char) 0; /* X.121 format */
  8114.     bcopy( addr, addtl_info, addr_len ); /* include trailing null */
  8115.     addtl_info += addr_len;
  8116.     if (cud_len > 0)
  8117.       bcopy( cud, addtl_info, cud_len );
  8118.     /*
  8119.      * Call putmsg() to put the bind request message on the stream
  8120.      */
  8121.     if (x25putmsg(fd,
  8122.                   (N_npi_ctl_t*)bind_req,
  8123.                   (N_npi_data_t *)NULL,
  8124.                   0,
  8125.                   &put_flags
  8126.                   ) < 0) {
  8127.         printf( "kermit: x25bind(): x25putmsg failed\n" );
  8128.         return(-1);
  8129.     }
  8130.  
  8131.     /*
  8132.      * Allocate and zero out space for the N_BIND_ACK primitive
  8133.      */
  8134.     bind_ack = (N_bind_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8135.     if (bind_ack == NULL){
  8136.         perror("kermit: x25bind(): bind_ack malloc failed");
  8137.         return(-1);
  8138.     }
  8139.     bzero(bind_ack, sizeof(N_npi_ctl_t));
  8140.     /*
  8141.      * Initialize the control structure and flag variable sent to getmsg
  8142.      */
  8143.     get_flags=0;
  8144.  
  8145.     /* get the ACK for the bind */
  8146. #ifdef DEBUG
  8147.     printf( "kermit: x25bind() trying to get a BIND_ACK\n" );
  8148. #endif /* DEBUG */
  8149.     rc = (ulong)x25getmsg( fd, (N_npi_ctl_t*)bind_ack,
  8150.             (int)sizeof( N_bind_ack_t ), (N_npi_data_t*)NULL, 0, &get_flags,
  8151.             N_BIND_ACK );
  8152.  
  8153.     /* turn quantitive return code into a qualitative one */
  8154.     if (rc > 0) rc = 0;
  8155.  
  8156.     /* if all went well, get the token from the acknowledgement packet */
  8157.     if ((bind_flags & TOKEN_REQUEST ) && ( rc >= 0)) {
  8158.         rc = bind_ack->TOKEN_value;
  8159.     }
  8160.  
  8161.     /* free up the memory we allocated earlier */
  8162.     free(bind_req);
  8163.     free(bind_ack);
  8164.  
  8165. #ifdef TRACE
  8166.     printf( "TRACE: leaving x25bind\n" );
  8167. #endif /* TRACE */
  8168.  
  8169.     return( rc );
  8170. }
  8171.  
  8172. /*****************************************************************************
  8173. * Function: x25call
  8174. * Description:  This routine builds and sends an N_CONN_REQ primitive, then
  8175. *               checks for an N_CONN_CON primitive in return.
  8176. *
  8177. * Parameters:
  8178. * fd    - file descriptor of stream
  8179. * caddr - called address (remote address)
  8180. *
  8181. * Functions Referenced:
  8182. * malloc()
  8183. * bzero()
  8184. * getmsg()
  8185. * putmsg()
  8186. *
  8187. * Return code:
  8188. * 0 - if successful
  8189. * -1 if not successful
  8190. *****************************************************************************/
  8191. int
  8192. x25call(fd, remote_nua, cud)
  8193.     int fd;                             /* X25 device (opened) */
  8194.     char * remote_nua;                  /* remote address to call */
  8195.     char * cud;                         /* call user data */
  8196. /* x25call */ {
  8197.     int rc;                             /* return code */
  8198.     int flags;                          /* Connection flags */
  8199.     int get_flags;                      /* priority flags for getmsg */
  8200.     ulong type;                         /* primitive type */
  8201.     N_conn_req_t *connreq_ctl;          /* pointer to N_CONN_REQ primitive */
  8202.     N_npi_data_t *connreq_data;         /* pointer to N_CONN_REQ data (CUD) */
  8203.     int connreq_data_len;               /* length of filled data buffer */
  8204.     N_conn_con_t *conncon_ctl;          /* pointer to N_CONN_CON primitive */
  8205.     N_npi_data_t *conncon_data;         /* pointer to any data associated with
  8206.                                          * the N_CONN_CON primitive */
  8207.     char *addtl_info;                   /* pointer to additional info needed
  8208.                                          * for N_CONN_REQ primitive */
  8209.     int addr_len;                       /* length of address */
  8210.  
  8211. #ifdef TRACE
  8212.     printf( "TRACE: entering x25call\n" );
  8213. #endif /* TRACE */
  8214.  
  8215. #ifdef DEBUG
  8216.     printf( "x25call( %d, %s )\n", fd, remote_nua );
  8217.     printf( "connecting to %s on fd %d\n", remote_nua, fd );
  8218. #endif /* DEBUG */
  8219.  
  8220.     /*
  8221.      * Allocate and zero out space for the N_CONN_REQ primitive
  8222.      * use the size of the generic NPI primitive control buffer
  8223.      */
  8224.     connreq_ctl  = (N_conn_req_t *) malloc(sizeof(N_npi_ctl_t));
  8225.     if (connreq_ctl == NULL){
  8226.         perror("kermit: x25call(): connreq_ctl malloc failed");
  8227.         return(-1);
  8228.     }
  8229.     bzero(connreq_ctl,sizeof(N_npi_ctl_t));
  8230.     /*
  8231.      * Build the Connection Request Primitive
  8232.      */
  8233.     flags = 0;
  8234.     connreq_ctl->PRIM_type = (ulong) N_CONN_REQ;
  8235.  
  8236.     /* Note that the address length is nchai+1 and not n+2. The line number
  8237.      * is only passed with the address for the bind. The first byte of
  8238.      * the address for the N_CONN primitives contains the X.121
  8239.      * address prefix, which must be zero. The remaining bytes are the
  8240.      * address itself.
  8241.      */
  8242.     addr_len = strlen( remote_nua );
  8243.     connreq_ctl->DEST_length = (ulong) (addr_len + 1);
  8244.     connreq_ctl->DEST_offset = (ulong) sizeof(N_conn_req_t);
  8245.     /* connreq_ctl->CONN_flags = (ulong)EX_DATA_OPT | REC_CONF_OPT; */
  8246.     connreq_ctl->CONN_flags = (ulong) 0;
  8247.     connreq_ctl->QOS_length = (ulong) 0;        /* unsupported in AIX 4.1 */
  8248.     connreq_ctl->QOS_offset = (ulong) 0;        /* unsupported in AIX 4.1 */
  8249.  
  8250.     addtl_info = (char *) ((void*)connreq_ctl + connreq_ctl->DEST_offset);
  8251.     *addtl_info++ = (char) 0; /* X.121 format */
  8252.     bcopy( remote_nua, addtl_info, addr_len );
  8253.  
  8254.     /*
  8255.      * setup the data buffer for the connection request
  8256.      */
  8257.     connreq_data  = (N_npi_data_t *) malloc(sizeof(N_npi_data_t));
  8258.     if (connreq_data == NULL){
  8259.         perror("kermit: x25call(): connreq_data malloc failed");
  8260.         return(-1);
  8261.     }
  8262.     bzero(connreq_data,sizeof(N_npi_data_t));
  8263.  
  8264.     /* facility selection needs to be put in the front of connreq_data */
  8265.     connreq_data_len = 0;
  8266.     connreq_data_len += x25facilities( (char *)connreq_data );
  8267.     if (cud && *cud) {
  8268.         bcopy(cud,
  8269.               (char *)((char *)connreq_data + connreq_data_len),
  8270.               strlen(cud)
  8271.               );
  8272.         connreq_data_len += strlen( cud );
  8273.         }
  8274.  
  8275.     /*
  8276.      * Call putmsg() to put the connection request message on the stream
  8277.      */
  8278.     rc = x25putmsg( fd, (N_npi_ctl_t*)connreq_ctl, connreq_data,
  8279.             connreq_data_len, &flags );
  8280.     if (rc < 0) {
  8281.         return(-1);
  8282.     }
  8283.  
  8284.     /*
  8285.      * Allocate and zero out space for the N_CONN_CON primitive
  8286.      */
  8287.     if ((conncon_ctl = (N_conn_con_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8288.         perror("kermit: x25call(): conncon_ctl malloc failed");
  8289.         return(-1);
  8290.     }
  8291.     bzero(conncon_ctl, sizeof(N_npi_ctl_t));
  8292.  
  8293.     /*
  8294.      * Allocate and zero out space for any data associated with N_CONN_CON
  8295.      */
  8296.     if ( (conncon_data = (N_npi_data_t *) malloc(NPI_MAX_DATA)) == NULL) {
  8297.         perror("kermit: x25call(): conncon_data malloc failed");
  8298.         return(-1);
  8299.     }
  8300.     bzero(conncon_data, NPI_MAX_DATA);
  8301.  
  8302.     /* Initialize and build the structures for getmsg */
  8303.     get_flags=0;
  8304.  
  8305.     rc = x25getmsg( fd, (N_npi_ctl_t*)conncon_ctl, (int)sizeof( N_conn_con_t ),
  8306.             conncon_data, NPI_MAX_DATA, &get_flags, N_CONN_CON );
  8307.  
  8308.     /* turn quantitive return code into a qualitative one */
  8309.     if (rc > 0) rc = 0;
  8310.  
  8311.     /* Free the space that we no longer need */
  8312.     if (connreq_ctl) { free(connreq_ctl); connreq_ctl = NULL; }
  8313.     if (conncon_ctl) { free(conncon_ctl); conncon_ctl = NULL; }
  8314.     if (conncon_data) { free(conncon_data); conncon_data = NULL; }
  8315.  
  8316. #ifdef TRACE
  8317.     printf( "TRACE: leaving x25call\n" );
  8318. #endif /* TRACE */
  8319.  
  8320.     return(rc);
  8321. }
  8322.  
  8323. /*****************************************************************************
  8324.  * Function: x25getcall
  8325.  *
  8326.  * Description: This routine checks for an incomming call, verified
  8327.  * that it is a CONNIND (connection indication) message, and then
  8328.  * accepts the call and returns the file descriptor of the new stream
  8329.  *
  8330.  * Parameters:
  8331.  * fd   - file descriptor of listening stream
  8332.  *
  8333.  * Return Codes:
  8334.  * callfd       - file descriptor of connected incomming call.
  8335.  *              - set to -1 if an error occured
  8336.  *
  8337.  *****************************************************************************/
  8338. int
  8339. x25getcall(fd) int fd; {
  8340.     int x25callfd;                      /* fd of incomming call */
  8341.     N_conn_ind_t *connind_ctl;          /* connind controll buffer */
  8342.     N_npi_data_t *connind_data;         /* connind data buffer */
  8343.     int get_flags;                      /* flags for getmsg */
  8344.     ulong flags;                        /* connection flags */
  8345.     int rc;                             /* return code */
  8346.  
  8347.     extern x25addr_t remote_nua;        /* remote X.25 addr global var */
  8348.  
  8349. #ifdef TRACE
  8350.     printf( "TRACE: entering x25getcall\n" );
  8351. #endif /* TRACE */
  8352.  
  8353.     /* allocate space for connection indication buffers */
  8354.     if ((connind_ctl = (N_conn_ind_t *)malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8355.         perror("kermit: x25getcall(): connind_ctl malloc failed");
  8356.         return (-1);
  8357.     }
  8358.     bzero(connind_ctl, sizeof(N_npi_ctl_t));
  8359.  
  8360.     if ((connind_data = (N_npi_data_t *)malloc(NPI_MAX_DATA)) == NULL) {
  8361.         perror("kermit: x25getcall(): connind_data malloc failed");
  8362.         return (-1);
  8363.     }
  8364.     bzero(connind_data, NPI_MAX_DATA);
  8365.  
  8366.     /* initialise control structures */
  8367.     get_flags = 0;
  8368.  
  8369.     /* call getmsg to check for a connection indication */
  8370.     if (x25getmsg(fd,
  8371.                   (N_npi_ctl_t*)connind_ctl,
  8372.                   (int)sizeof(N_conn_ind_t),
  8373.                   connind_data,
  8374.                   NPI_MAX_DATA,
  8375.                   &get_flags,
  8376.                   N_CONN_IND
  8377.                   ) < 0) {
  8378. #ifdef DEBUG
  8379.         printf( "x25getcall(): errno is: %d\n", errno );
  8380. #endif /* DEBUG */
  8381.         perror ("x25getcall(): getmsg failed");
  8382.         return(-1);
  8383.     }
  8384.  
  8385.     /* a connection indication was received
  8386.      * - pull it to bits and answer the call
  8387.      */
  8388.     x25seqno = connind_ctl->SEQ_number;
  8389.     flags = connind_ctl->CONN_flags;
  8390. #ifdef DEBUG
  8391.     printf( "setting remote_nua to a new value due to incomming call\n" );
  8392. #endif /* DEBUG */
  8393.     /*
  8394.      * no guarantee that the address is null terminated, ensure that
  8395.      * after copying that it is (assumption: remote_nua is longer than
  8396.      * the address + 1)
  8397.      */
  8398.     bzero(remote_nua, sizeof(remote_nua));
  8399.     /* note: connind_ctl contains a x121 address, which has a null as
  8400.      * the FIRST character - strip it off!
  8401.      */
  8402.     ckstrncpy(remote_nua,
  8403.             (char*)((char*)connind_ctl + connind_ctl->SRC_offset + 1),
  8404.             connind_ctl->SRC_length - 1
  8405.             );
  8406. #ifdef DEBUG
  8407.     printf( "remote_nua set to new value of %s\n", remote_nua );
  8408. #endif /* DEBUG */
  8409.  
  8410.     /* errors handled by callee */
  8411.     x25callfd = x25accept(x25seqno, flags);
  8412.  
  8413.     /* free the malloc'd buffers */
  8414.     if (connind_ctl) { free(connind_ctl); connind_ctl = NULL; }
  8415.     if (connind_data) { free(connind_data); connind_data = NULL; }
  8416.  
  8417. #ifdef TRACE
  8418.     printf( "TRACE: leaving x25getcall\n" );
  8419. #endif /* TRACE */
  8420.  
  8421.     /* return the file descriptor (or error if < 0) */
  8422.     return( x25callfd );
  8423. }
  8424.  
  8425. /*****************************************************************************
  8426.  * Function: x25accept
  8427.  *
  8428.  * Description: accept an incomming call
  8429.  *              This essentially means opening a new STREAM and sending
  8430.  *              an acknowledge back to the caller.
  8431.  *
  8432.  * Parameters:
  8433.  *      seqno   - sequence number for acknowledgement
  8434.  *      flags   - flags passed to us by the caller
  8435.  *
  8436.  * Return Codes:
  8437.  *      fd      - file descriptor of new STREAM
  8438.  *                set to -1 if an error occured
  8439.  *
  8440.  *****************************************************************************/
  8441. int
  8442. x25accept(seqno,flags)
  8443.     ulong seqno;                        /* connection sequence number */
  8444.     ulong flags;                        /* connection flags */
  8445. /* x25accept */ {
  8446.     int x25callfd;                      /* fd for incomming call */
  8447.     int get_flags;                      /* priority flags for getmsg */
  8448.     int put_flags = 0;                  /* flags for putmsg, always 0 */
  8449.     int addr_len;                       /* length of local address */
  8450.     ulong token;                        /* connection token */
  8451.     N_conn_res_t *conn_res;             /* N_CONN_RES primitive */
  8452.     N_ok_ack_t *ok_ack;                 /* N_OK_ACK primitive */
  8453.     char *addtl_info;                   /* temp pointer */
  8454.     int rc;                             /* temporary return code */
  8455.  
  8456. /* global variables from ckcmai.c */
  8457.     extern int revcall, closgr, cudata;
  8458.     extern char udata[];
  8459.     extern x25addr_t local_nua;         /* local X.25 address */
  8460.     extern char x25name[];              /* x25 device name (sx25a0) */
  8461.     extern char x25dev[];               /* x25 device file /dev/x25pkt */
  8462.     extern int x25port;                 /* logical port to use */
  8463.     ulong bind_flags = 0;               /* flags for binding the X25 stream */
  8464.  
  8465. #ifdef TRACE
  8466.     printf( "TRACE: entering x25accept\n" );
  8467. #endif /* TRACE */
  8468.  
  8469.     /* open a new packet level stream */
  8470.     if ((x25callfd = open(x25dev, O_RDWR)) < 0) {
  8471.         perror ("kermit: x25accept(): X.25 device open error");
  8472.         debug(F101,"x25accept() device open error","",errno);
  8473.         return(-1);
  8474.     }
  8475.  
  8476.     /* push the NPI onto the STREAM */
  8477.     if (ioctl(x25callfd,I_PUSH,"npi") < 0) {
  8478.         perror( "kermit: x25accept(): couldn't push npi on the X25 stream" );
  8479.         debug(F101,"x25accept can't push npi on the X25 stream","",errno);
  8480.         return (-1);
  8481.     }
  8482.  
  8483.     /* bind kermit server to the local X25 address */
  8484.     /* taken from /usr/samples/sx25/npi/npiserver.c (AIX 4) */
  8485.     bind_flags |= TOKEN_REQUEST;
  8486.     token = x25bind(x25callfd,local_nua,(char *)NULL,0,0,x25port,bind_flags);
  8487.     if (token < 0) {
  8488.         printf( "kermit: x25accept(): couldn't bind to local X25 address\n" );
  8489.         netclos();
  8490.         return(-1);
  8491.     }
  8492.  
  8493.     /* allocate connection response primitive */
  8494.     if ((conn_res = (N_conn_res_t *)malloc( NPI_MAX_CTL )) == NULL) {
  8495.         perror("kermit: x25accept(): conn_res malloc failed");
  8496.         return (-1);
  8497.     }
  8498.     bzero((char *)conn_res, NPI_MAX_CTL);
  8499.  
  8500.     /* setup connection response primitive */
  8501.     addr_len = strlen( local_nua );
  8502.     conn_res->PRIM_type = (ulong)N_CONN_RES;
  8503.     conn_res->TOKEN_value = token;
  8504.     /* note address length is n+1 to accomodate the X.121 address prefix */
  8505.     conn_res->RES_length = (ulong)(addr_len + 1);
  8506.     conn_res->RES_offset = (ulong)sizeof( N_conn_res_t );
  8507.     conn_res->SEQ_number = seqno;
  8508.     conn_res->CONN_flags = 0;
  8509.     conn_res->QOS_length = 0;           /* unsupported - must be 0 (!?) */
  8510.     conn_res->QOS_offset = 0;
  8511.  
  8512.     addtl_info = (char *)((char *)conn_res + conn_res->RES_offset);
  8513.     *addtl_info++ = (char)0;    /* X.121 address prefix */
  8514.     bcopy( local_nua, addtl_info, addr_len );
  8515.  
  8516.     /*
  8517.      * send off the connect response
  8518.      */
  8519.     if (x25putmsg(x25callfd,
  8520.                   (N_npi_ctl_t*)conn_res,
  8521.                   (N_npi_data_t *)NULL,
  8522.                   0,
  8523.                   &put_flags
  8524.                   ) < 0 ) {
  8525.         perror("kermit: x25accept(): putmsg connect response failed");
  8526.         return(-1);
  8527.     }
  8528.  
  8529.     /*
  8530.      * Allocate and zero out space for the OK_ACK primitive
  8531.      */
  8532.     if ((ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8533.         perror("kermit: x25call(): ok_ack malloc failed");
  8534.         return(-1);
  8535.     }
  8536.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8537.  
  8538.     /* Initialize and build the structures for getmsg */
  8539.     get_flags=0;
  8540.  
  8541.     rc = (int)x25getmsg(x25callfd,
  8542.                         (N_npi_ctl_t*)ok_ack,
  8543.                         (int)sizeof(N_ok_ack_t),
  8544.                         (N_npi_data_t*)NULL,
  8545.                         0,
  8546.                         &get_flags,
  8547.                         N_OK_ACK
  8548.                         );
  8549.     if (rc == 0) {
  8550.         /* sequence number is only for disconnecting when not connected !? */
  8551.         x25seqno = 0;
  8552.     }
  8553.  
  8554.     /* free up malloc'ed buffer space */
  8555.     if (conn_res) { free(conn_res); conn_res = NULL; }
  8556.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8557.  
  8558. #ifdef TRACE
  8559.     printf( "TRACE: leaving x25accept\n" );
  8560. #endif /* TRACE */
  8561.  
  8562.     return( ( rc >= 0 ) ? x25callfd : -1 );
  8563. }
  8564.  
  8565. /*****************************************************************************
  8566.  * Function: x25unbind
  8567.  *
  8568.  * Description:  This subroutine builds and sends an unbind request and gets
  8569.  * the acknowledgement for it.
  8570.  *
  8571.  * Parameters:
  8572.  * fd - File descriptor of the stream
  8573.  *
  8574.  * Functions Referenced:
  8575.  * getmsg()
  8576.  * putmsg()
  8577.  * malloc()
  8578.  * bzero()
  8579.  *
  8580.  * Return code:
  8581.  * 0 - if successful
  8582.  * -1 - if not successful
  8583.  *****************************************************************************/
  8584. int
  8585. x25unbind(fd) int fd; {                 /* X25 device (opened) */
  8586.     int rc;                             /* return code */
  8587.     int flags;                          /* bind flags */
  8588.     int get_flags;                      /* priority flag for getmsg */
  8589.     ulong type;                         /* primitive type */
  8590.     N_unbind_req_t *unbind_req;         /* pointer to N_UNBIND_REQ */
  8591.     N_ok_ack_t *ok_ack;                 /* pointer to N_OK_ACK */
  8592.  
  8593. #ifdef TRACE
  8594.     printf( "TRACE: entering x25unbind\n" );
  8595. #endif /* TRACE */
  8596.  
  8597. #ifdef DEBUG
  8598.     /* printf( "x25unbind( %d )\n", fd ); */
  8599. #endif /* DEBUG */
  8600.     debug(F101,"x25unbind closing x25 connection #","",fd);
  8601.  
  8602.     /* Allocate and zero out space to hold the N_UNBIND_REQ primitive */
  8603.     unbind_req = (N_unbind_req_t *) malloc(sizeof(N_npi_ctl_t));
  8604.     if (unbind_req == NULL) {
  8605.         perror("kermit: x25unbind(): unbind_req malloc failed");
  8606.         return(-1);
  8607.     }
  8608.     bzero(unbind_req, sizeof(N_npi_ctl_t));
  8609.  
  8610.     /*
  8611.      * Build the Unbind Request Primitive
  8612.      */
  8613.     flags = 0;
  8614.     unbind_req->PRIM_type = (ulong) N_UNBIND_REQ;
  8615.  
  8616.     /*
  8617.      * Call putmsg() to put the bind request message on the stream
  8618.      */
  8619.     if (x25putmsg(fd,
  8620.                   (N_npi_ctl_t*)unbind_req,
  8621.                   (N_npi_data_t *)NULL,
  8622.                   0,
  8623.                   &flags
  8624.                   ) < 0) {
  8625.         perror ("kermit: x25unbind(): putmsg failed");
  8626.         return(-1);
  8627.     }
  8628.  
  8629.     /* Allocate and Zero out space for the N_OK_ACK primitive */
  8630.     ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8631.     if (ok_ack == NULL) {
  8632.         perror("kermit x25unbind(): ok_ack malloc failed\n");
  8633.         return(-1);
  8634.     }
  8635.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8636.  
  8637.     /* Initialize and build the control structure for getmsg */
  8638.     get_flags=0;
  8639.  
  8640.     /* Call getmsg() to check for an acknowledgement */
  8641.     rc = x25getmsg(fd,
  8642.                    (N_npi_ctl_t*)ok_ack,
  8643.                    (int)sizeof(N_ok_ack_t),
  8644.                    (N_npi_data_t*)NULL,
  8645.                    0,
  8646.                    &get_flags,
  8647.                    N_OK_ACK
  8648.                    );
  8649.     if (rc < 0) {
  8650.         perror ("kermit: x25unbind: getmsg failed");
  8651.         return(-1);
  8652.     }
  8653.  
  8654.     /* Free up the space that we no longer need */
  8655.     if (unbind_req) { free(unbind_req); unbind_req = NULL; }
  8656.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8657.  
  8658. #ifdef TRACE
  8659.     printf( "TRACE: leaving x25unbind\n" );
  8660. #endif /* TRACE */
  8661.  
  8662.     return(0);
  8663. }
  8664.  
  8665. /*****************************************************************************
  8666.  * Function: x25xin
  8667.  *
  8668.  * Description:
  8669.  *      Read n characters from X.25 circuit into buf (AIX only)
  8670.  *
  8671.  * Parameters:
  8672.  *      data_buf_len    maximum size of data buffer
  8673.  *      data_buf        pointer to pre-allocated buffer space
  8674.  *
  8675.  * Return Value:
  8676.  *      the number of characters actually read
  8677.  */
  8678. int
  8679. x25xin(data_buf_len,data_buf) int data_buf_len; CHAR *data_buf; {
  8680.     struct strbuf getmsg_ctl;           /* streams control structure */
  8681.     struct strbuf getmsg_data;          /* streams data structure */
  8682.     int rc = 0;                         /* return code */
  8683.     int getmsg_flags;                   /* packet priority flags */
  8684.     char * ctl_buf;                     /* npi control buffer */
  8685.     N_npi_ctl_t * result;               /* pointer to simplify switch() */
  8686.  
  8687. #ifdef TRACE
  8688.     printf( "TRACE: entering x25xin\n" );
  8689. #endif /* TRACE */
  8690.  
  8691.     /* ensure that no maximum's are overridden */
  8692.     data_buf_len = (NPI_MAX_DATA < data_buf_len) ? NPI_MAX_DATA : data_buf_len;
  8693.  
  8694.     /* allocate space for packet control info */
  8695.     if ((ctl_buf = (char *)malloc(NPI_MAX_CTL)) == NULL) {
  8696.         perror( "kermit: x25xin(): ctl_buf malloc" );
  8697.         return(-1);
  8698.     }
  8699. #ifdef COMMENT
  8700.     /* riehm: need zeroed buffer for getmsg? */
  8701.     bzero( ctl_buf, NPI_MAX_CTL );
  8702.     /* clear data buffer */
  8703.     bzero( data_buf, data_buf_len );
  8704. #endif /* COMMENT */
  8705.  
  8706.     getmsg_flags = 0;                   /* get the first packet available */
  8707.  
  8708.     rc = x25getmsg(ttyfd,
  8709.                    ctl_buf,
  8710.                    NPI_MAX_CTL,
  8711.                    data_buf,
  8712.                    data_buf_len,
  8713.                    &getmsg_flags,
  8714.                    N_DATA_IND
  8715.                    );
  8716. #ifdef COMMENT
  8717. #ifdef DEBUG
  8718.     if (rc >= 0) {
  8719.         printf( "kermit: x25xin(): got " );
  8720.         x25dump_data( data_buf, 0, rc );
  8721.     } else {
  8722.         printf( "x25xin(): attempt to get data resulted in an error\n" );
  8723.     }
  8724. #endif /* DEBUG */
  8725. #endif /* COMMENT */
  8726.  
  8727.     /* free buffers */
  8728.     if (ctl_buf) { free(ctl_buf); ctl_buf = NULL; }
  8729.  
  8730. #ifdef TRACE
  8731.     printf( "TRACE: leaving x25xi\n" );
  8732. #endif /* TRACE */
  8733.  
  8734.     return(rc);
  8735. }
  8736.  
  8737. /*****************************************************************************
  8738.  * Function: x25write
  8739.  *
  8740.  * Description:
  8741.  *      write a block of characters to the X25 STREAM (AIX)
  8742.  *
  8743.  * Parameters:
  8744.  *      fd              file descriptor to write to
  8745.  *      databuf         buffer containing data to write
  8746.  *      databufsize             size of the buffer to write
  8747.  *
  8748.  * Return Value:
  8749.  *      size            the number of bytes actually transmitted
  8750.  */
  8751. int
  8752. x25write(fd, databuf, databufsize)
  8753.     int         fd;                  /* X25 STREAMS file descriptor (ttyfd) */
  8754.     char        *databuf;               /* buffer to write */
  8755.     int         databufsize;            /* buffer size */
  8756. /* x25write */ {
  8757.     N_data_req_t *data_req_ctl;
  8758.     int rc;                             /* return code (size transmitted) */
  8759.     int write_flags = 0;                /* always 0 !? */
  8760.  
  8761. #ifdef TRACE
  8762.     printf( "TRACE: entering x25write\n" );
  8763. #endif /* TRACE */
  8764.  
  8765.     if ((data_req_ctl = (N_data_req_t *)malloc(NPI_MAX_CTL) ) == NULL) {
  8766.         perror( "kermit: x25write(): data_req_ctl malloc" );
  8767.         return(-1);
  8768.     }
  8769.     data_req_ctl->PRIM_type = N_DATA_REQ;
  8770.     data_req_ctl->DATA_xfer_flags = 0;
  8771.  
  8772.     /* riehm: possible extension
  8773.      * possibly need to think about splitting up the data buffer
  8774.      * into multiple parts if databufsize > NPI_MAX_DATA
  8775.      */
  8776.  
  8777. #ifdef COMMENT
  8778. #ifdef DEBUG
  8779.     printf( "kermit: x25write(): writing data to x25 stream\n" );
  8780.     printf( "\tdata:\t" );
  8781.     x25dump_data(databuf, 0, databufsize);
  8782. #endif /* DEBUG */
  8783. #endif /* COMMENT */
  8784.     rc = x25putmsg(fd,
  8785.                    (N_npi_ctl_t*)data_req_ctl,
  8786.                    (N_npi_data_t*)databuf,
  8787.                    databufsize,
  8788.                    &write_flags
  8789.                    );
  8790.     if (data_req) { free(data_req_ctl);  data_req = NULL; }
  8791.  
  8792. #ifdef TRACE
  8793.     printf( "TRACE: leaving x25write\n" );
  8794. #endif /* TRACE */
  8795.  
  8796.     return(rc);
  8797. }
  8798.  
  8799. /*****************************************************************************
  8800.  * Function: x25local_nua
  8801.  *
  8802.  * Description:
  8803.  *      This routine is only interesting for IBM computers. In order
  8804.  *      to set up a connection (see x25bind()) you need to know the
  8805.  *      local NUA (x25 address). Unfortunately, you need all this code
  8806.  *      to find that out, I just hope this works for everyone else!
  8807.  *
  8808.  * Parameters:
  8809.  *      a pre-allocated character buffer, long enough to hold an X.25 address
  8810.  *      and the tailing null.
  8811.  *
  8812.  * Return Value:
  8813.  *      the length of the address string.
  8814.  *      0 = error
  8815.  */
  8816. int
  8817. x25local_nua(char *buf) {
  8818.     struct CuAt *response;      /* structure to fill with info from ODM */
  8819.     CLASS_SYMBOL retClass;      /* ODM class */
  8820.     char query[64];             /* odm database query */
  8821.     int rc = 0;                 /* return value (length of local NUA) */
  8822.     extern char x25name[];      /* x25 device name (sx25a0) */
  8823.  
  8824. #ifdef TRACE
  8825.     printf( "TRACE: entering x25local_nua\n" );
  8826. #endif /* TRACE */
  8827.  
  8828.     /* set up query string */
  8829.     if (x25name[0] == '\0') {
  8830. #ifdef DEBUG
  8831.         printf( "kermit: x25local_nua(): No x25 device set, trying sx25a0\n" );
  8832. #endif /* DEBUG */
  8833.         strcpy( x25name, "sx25a0" );
  8834.     }
  8835.     ckmakmsg(query, sizeof(query), "name like ",x25name,
  8836.              " and attribute like local_nua");
  8837.  
  8838.     /* initialise ODM database */
  8839.     odmerrno = 0;
  8840.     if (odm_initialize() == -1) {
  8841.         printf( "x25local_nua(): can't initialize ODM database");
  8842.         switch (odmerrno) {
  8843.           case ODMI_INVALID_PATH:
  8844.             printf( "invalid path\n" );
  8845.             break;
  8846.           case ODMI_MALLOC_ERR:
  8847.             printf( "malloc failed\n" );
  8848.             break;
  8849.           default:
  8850.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8851.         }
  8852.         return(rc);
  8853.     }
  8854.  
  8855.     /* open the CuAt class */
  8856.     retClass = odm_open_class(CuAt_CLASS);
  8857.     if (((int)retClass) == -1) {
  8858.         printf( "kermit: x25local_nua(): can't open CuAt class in odm. " );
  8859.         switch (odmerrno) {
  8860.           case ODMI_CLASS_DNE:
  8861.             printf( "CuAt class doesn't exist\n" );
  8862.             break;
  8863.           case ODMI_CLASS_PERMS:
  8864.             printf( "permission to CuAt class file denied\n" );
  8865.             break;
  8866.           case ODMI_MAGICNO_ERR:
  8867.             printf( "CuAt is an invalid ODM object class\n" );
  8868.             break;
  8869.           case ODMI_OPEN_ERR:
  8870.             printf( "cannot open CuAt class - and don't know why!\n" );
  8871.             break;
  8872.           case ODMI_INVALID_PATH:
  8873.             printf( "invalid path\n" );
  8874.             break;
  8875.           case ODMI_TOOMANYCLASSES:
  8876.             printf( "too many object classes have been opened\n" );
  8877.             break;
  8878.           default:
  8879.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8880.         }
  8881.         return(rc);
  8882.     }
  8883.  
  8884. #ifdef DEBUG
  8885.     printf("retClass= %d\n", retClass);
  8886. #endif /* DEBUG */
  8887.  
  8888.     response = (struct CuAt *)odm_get_first( retClass, query, NULL );
  8889.     if (((int)response) == -1) {
  8890.         printf( "kermit: x25local_nua(): odm query failed " );
  8891.         switch (odmerrno) {
  8892.           case ODMI_BAD_CRIT:           /* Programming error */
  8893.             printf( "bad search criteria\n" );
  8894.             break;
  8895.           case ODMI_CLASS_DNE:
  8896.             printf( "CuAt class doesn't exist\n" );
  8897.             break;
  8898.           case ODMI_CLASS_PERMS:
  8899.             printf( "permission to CuAt class file denied\n" );
  8900.             break;
  8901.           case ODMI_INTERNAL_ERR:
  8902.             printf("odm internal error\nPlease contact your administrator\n" );
  8903.             break;
  8904.           case ODMI_INVALID_CLXN:
  8905.             printf("CuAt is invalid or inconsistent odm class collection\n");
  8906.             break;
  8907.           case ODMI_INVALID_PATH:
  8908.             printf( "invalid path\n" );
  8909.             break;
  8910.           case ODMI_MAGICNO_ERR:
  8911.             printf( "CuAt is an invalid ODM object class\n" );
  8912.             break;
  8913.           case ODMI_MALLOC_ERR:
  8914.             printf( "malloc failed\n" );
  8915.             break;
  8916.           case ODMI_OPEN_ERR:
  8917.             printf( "cannot open CuAt class - and don't know why!\n" );
  8918.             break;
  8919.           case ODMI_TOOMANYCLASSES:
  8920.             printf( "too many object classes have been opened\n" );
  8921.             break;
  8922.           default:
  8923.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8924.         }
  8925.         return(rc);
  8926.     }
  8927.  
  8928.     /* check for a meaningfull response */
  8929.     if (response != NULL) {
  8930.         if (response->value != NULL) {
  8931.             strcpy(buf, response->value);
  8932.             rc = strlen( buf );
  8933. #ifdef DEBUG
  8934. /*
  8935.             printf( "attribute name is: %s\n", (char *)response->attribute );
  8936.             printf( "I think my address is %s\n", (char*)response->value );
  8937. */
  8938. #endif /* DEBUG */
  8939.         } else {
  8940.             printf( "kermit: x25local_nua(): couldn't find the local NUA\n" );
  8941.         }
  8942.     } else {
  8943.         switch (odmerrno) {
  8944.           case ODMI_BAD_CRIT:
  8945.             printf( "Error: ODMI_BAD_CRIT - bad criteria\n" );
  8946.             break;
  8947.           case ODMI_CLASS_DNE:
  8948.             printf( "Error: ODMI_CLASS_DNE - class doesn't exist\n" );
  8949.             break;
  8950.           case ODMI_CLASS_PERMS:
  8951.             printf( "Error: ODMI_CLASS_PERMS - class permissions\n" );
  8952.             break;
  8953.           case ODMI_INTERNAL_ERR:
  8954.             printf( "Error: ODMI_INTERNAL_ERR - panic\n" );
  8955.             break;
  8956.           case ODMI_INVALID_CLXN:
  8957.             printf( "Error: ODMI_INVALID_CLXN - invalid collection\n" );
  8958.             break;
  8959.           case ODMI_INVALID_PATH:
  8960.             printf( "Error: ODMI_INVALID_PATH - invalid path - what path?\n" );
  8961.             break;
  8962.           case ODMI_MAGICNO_ERR:
  8963.             printf( "Error: ODMI_MAGICNO_ERR - invalid object magic\n" );
  8964.             break;
  8965.           case ODMI_MALLOC_ERR:
  8966.             printf( "Error: ODMI_MALLOC_ERR - malloc failed\n" );
  8967.             break;
  8968.           case ODMI_OPEN_ERR:
  8969.             printf( "Error: ODMI_OPEN_ERR - cannot open class\n" );
  8970.             break;
  8971.           case ODMI_TOOMANYCLASSES:
  8972.             printf( "Error: ODMI_TOOMANYCLASSES - too many classes\n" );
  8973.             break;
  8974.           default:
  8975.             printf( "Unknown error!\n" );
  8976.         }
  8977.         return(rc);
  8978.     }
  8979.  
  8980.     /* close the database again */
  8981.     odm_close_class( retClass );
  8982.  
  8983.     /* forget about ODM all together */
  8984.     odm_terminate();
  8985.  
  8986. #ifdef TRACE
  8987.     printf( "TRACE: leaving x25local_nua\n" );
  8988. #endif /* TRACE */
  8989.  
  8990.     debug(F110, "x25local_nua local address is ", buf, 0);
  8991.     return(rc);
  8992. }
  8993.  
  8994. /*****************************************************************************
  8995.  * Function: x25facilities
  8996.  *
  8997.  * Description:
  8998.  *      build up the facilities data packet for a connection request
  8999.  *
  9000.  * Parameters:
  9001.  *      a pre-allocated char buffer, normally NPI_MAX_DATA big.
  9002.  *
  9003.  * Return Value:
  9004.  *      the number of characters inserted into the buffer
  9005.  */
  9006. int
  9007. x25facilities(buffer) char *buffer; {
  9008.     extern int revcall;
  9009.     extern int closgr;
  9010.     char *p;                            /* temp pointer */
  9011.     char *start;                        /* temp pointer */
  9012.  
  9013. #ifdef TRACE
  9014.     printf( "TRACE: entering x25facilities\n" );
  9015. #endif /* TRACE */
  9016.  
  9017.     p = buffer + 1;
  9018.     start = p;
  9019.  
  9020. #ifdef DEBUG
  9021.     printf( "kermit: x25facilities(): getting X25 facilities\n" );
  9022. #endif /* DEBUG */
  9023.  
  9024.     if (revcall != 0) {
  9025. #ifdef DEBUG
  9026.         printf("reverse charge: %d\n", revcall );
  9027. #endif /* DEBUG */
  9028.         *++p = 0x01;
  9029.         *++p = revcall;
  9030.     }
  9031.     if (closgr > 0) {
  9032. #ifdef DEBUG
  9033.         printf("closed user group: %d\n", closgr );
  9034. #endif /* DEBUG */
  9035.         *++p = 0x03;
  9036.         *++p = closgr;
  9037.     }
  9038.  
  9039. #ifdef DEBUG
  9040.     if (p == start) {
  9041.         printf( "no facilities\n" );
  9042.     }
  9043. #endif /* DEBUG */
  9044.  
  9045.     /* set the size of the facilities buffer */
  9046.     *buffer = (char)( p - start ) & 0xff;
  9047.  
  9048. #ifdef DEBUG
  9049.     printf( "kermit: x25facilities(): returning %d\n", (int)(p - buffer)  );
  9050. #endif /* DEBUG */
  9051.  
  9052. #ifdef TRACE
  9053.     printf( "TRACE: leaving x25facilities\n" );
  9054. #endif /* TRACE */
  9055.  
  9056.     /* return the size of the facilities with size byte */
  9057.     /* 1 == no facilities, 0 byte returned as facilities size */
  9058.     return( (int)(p - buffer) );
  9059. }
  9060.  
  9061. /*
  9062.  * reset the connection
  9063.  */
  9064. int
  9065. x25reset(cause, diagn) char cause; char diagn; {
  9066.     /* not implemented */
  9067.  
  9068. #ifdef TRACE
  9069.     printf( "TRACE: entering x25reset\n" );
  9070. #endif /* TRACE */
  9071.  
  9072. #ifdef TRACE
  9073.     printf( "TRACE: leaving x25reset\n" );
  9074. #endif /* TRACE */
  9075.  
  9076.     return(0);
  9077. }
  9078.  
  9079. /*
  9080.  * clear the x25 connection - ie: hang up
  9081.  */
  9082. int
  9083. x25clear() {
  9084.     int get_flags = 0;                  /* priority flag for getmsg */
  9085.     int put_flags = 0;                  /* send flags, always 0 */
  9086.     ulong type;                         /* primitive type */
  9087.     N_discon_req_t *discon_req;         /* pointer to N_DISCON_REQ */
  9088.     N_discon_ind_t *discon_ind;         /* pointer to N_DISCON_IND */
  9089.     N_npi_data_t *discon_data;          /* pointer to N_DISCON_IND data */
  9090.     int rc = 0;                         /* return code */
  9091.  
  9092. #ifdef TRACE
  9093.     printf( "TRACE: entering x25clear\n" );
  9094. #endif /* TRACE */
  9095.  
  9096. #ifdef DEBUG
  9097.     /* printf( "x25clear(): checking last msg: %s\n", x25prim(x25lastmsg)); */
  9098. #endif /* DEBUG */
  9099.  
  9100.     /*
  9101.     * The following checks are used to ensure that we don't disconnect
  9102.     * or unbind twice - this seems to throw the NPI interface right out of
  9103.     * kilter.
  9104.     */
  9105.     switch(x25lastmsg) {
  9106.       case N_BIND_ACK:
  9107.       case N_CONN_CON:
  9108.       case N_CONN_REQ:
  9109.       case N_DATA_REQ:
  9110.       case N_DATA_IND:
  9111.         {
  9112. #ifdef DEBUG
  9113.             /* printf("x25clear(): actively disconnecting\n"); */
  9114. #endif /* DEBUG */
  9115.  
  9116.                 discon_req = (N_discon_req_t *)malloc(NPI_MAX_CTL);
  9117.                 if (discon_req == NULL) {
  9118.                     perror("kermit x25clear(): discon_req malloc failed\n");
  9119.                     /* fallthrough, try to unbind the NPI anyway */
  9120.                 } else {
  9121.                     discon_req->PRIM_type = N_DISCON_REQ;
  9122.                     discon_req->DISCON_reason = 0;      /* not used by AIX */
  9123.                     discon_req->RES_length = 0;
  9124.                     discon_req->RES_offset = (ulong)(sizeof(N_discon_req_t));
  9125.                     discon_req->SEQ_number = x25seqno;  /* global */
  9126.  
  9127.                     if (x25putmsg(ttyfd,
  9128.                                   (N_npi_ctl_t*)discon_req,
  9129.                                   (N_npi_data_t*)NULL,
  9130.                                   0,
  9131.                                   &put_flags
  9132.                                   ) < 0) {
  9133.                         perror("x25putmsg failed in x25clear()");
  9134.                     }
  9135.                     discon_ind = (N_discon_ind_t *)malloc(NPI_MAX_CTL);
  9136.                     discon_data = (N_npi_data_t *)malloc(NPI_MAX_DATA);
  9137.                     if((discon_ind == NULL) || (discon_data == NULL)) {
  9138.                         perror("x25clear(): discon_ind malloc failed\n");
  9139.                         /* fallthrough, try to unbind the NPI anyway */
  9140.                     } else {
  9141.                         if(x25getmsg(ttyfd,
  9142.                                      (N_npi_ctl_t*)discon_ind,
  9143.                                      NPI_MAX_CTL,
  9144.                                      (N_npi_data_t*)discon_data,
  9145.                                      NPI_MAX_DATA,
  9146.                                      &get_flags,
  9147.                                      N_OK_ACK
  9148.                                      ) < 0 ) {
  9149.                             perror("x25getmsg failed in x25clear()");
  9150.                             /* fallthrough, try to unbind the NPI anyway */
  9151.                         }
  9152.                     }
  9153.                 }
  9154.                 break;
  9155.             }
  9156.     }
  9157.  
  9158.     if (x25lastmsg != N_UNBIND_REQ) {
  9159.         rc = x25unbind(ttyfd);
  9160.     }
  9161.  
  9162. #ifdef TRACE
  9163.     printf( "TRACE: leaving x25clear\n" );
  9164. #endif /* TRACE */
  9165.  
  9166.     return(rc);
  9167. }
  9168.  
  9169. #ifdef DEBUG
  9170. /*
  9171.  * only for debugging
  9172.  *
  9173.  * turn the internal representation of a datablock into something
  9174.  * half-way readable. Because the length is known, we can print
  9175.  * the string including null's etc (important, because the first(!)
  9176.  * byte of an X121 address is a null! (X121 addr == 0 + X25 addr)
  9177.  */
  9178. x25dump_data(char *addr, ulong offset, ulong length) {
  9179.     char *ptr = addr + offset;
  9180.     ulong i = length;
  9181.     /* allocate enough memory for all unprintable chars */
  9182.     char *buf = (char *)malloc( length * 4 );
  9183.     char *bptr = buf;   /* pointer to current place in the print buffer */
  9184.  
  9185.     while (i > 0) {
  9186.         if (isprint(*ptr)) {
  9187.             *bptr++ = *ptr;
  9188.         } else {
  9189.             *bptr++ = '[';
  9190.             strcpy(bptr,ckctox(*ptr,1)); bptr += 2;
  9191.             *bptr++ = ']';
  9192.         }
  9193.         ptr++;
  9194.         i--;
  9195.     }
  9196.     if (length > 0) {
  9197.         *bptr = '\0';
  9198.         printf( "%s", buf );
  9199.     }
  9200.     printf( " (%d+%d)\n", offset, length );
  9201.  
  9202.     if (buf) { free(buf); buf = NULL; }
  9203.     return;
  9204. }
  9205.  
  9206. /*
  9207.  * only for debugging
  9208.  * print as much useful information about a packet as possible
  9209.  */
  9210. x25dump_prim(primitive)    N_npi_ctl_t *primitive; {
  9211.     printf("Primitive");
  9212.     switch (primitive->PRIM_type) {
  9213.       case N_BIND_ACK:
  9214.         printf( "\tN_BIND_ACK\n\taddress:\t" );
  9215.         x25dump_data( (char *)primitive,
  9216.                      primitive->bind_ack.ADDR_offset,
  9217.                      primitive->bind_ack.ADDR_length );
  9218.         printf( "\tproto id:\t" );
  9219.         x25dump_data( (char *)primitive,
  9220.                      primitive->bind_ack.PROTOID_offset,
  9221.                      primitive->bind_ack.PROTOID_length );
  9222.         printf( "\tconnind:\t%d\n\ttoken:\t\t%d\n",
  9223.                primitive->bind_ack.CONIND_number,
  9224.                primitive->bind_ack.TOKEN_value );
  9225.         break;
  9226.  
  9227.       case N_BIND_REQ:
  9228.         printf( "\tN_BIND_REQ\n\taddress:\t" );
  9229.         x25dump_data( (char *)primitive,
  9230.                      primitive->bind_req.ADDR_offset,
  9231.                      primitive->bind_req.ADDR_length );
  9232.         printf( "\tproto id:\t" );
  9233.         x25dump_data( (char *)primitive,
  9234.                      primitive->bind_req.PROTOID_offset,
  9235.                      primitive->bind_req.PROTOID_length );
  9236.         printf( "\tconnind:\t%d\n\tflags:\t\t%d\n",
  9237.                primitive->bind_req.CONIND_number,
  9238.                primitive->bind_req.BIND_flags );
  9239.         break;
  9240.  
  9241.       case N_CONN_CON:
  9242.         printf( "\tN_CONN_CON\n" );
  9243.         printf( "\tRES\t\t" );
  9244.         x25dump_data( (char *)primitive,
  9245.                      primitive->conn_con.RES_offset,
  9246.                      primitive->conn_con.RES_length );
  9247.         printf( "\tflags:\t%d\n", primitive->conn_con.CONN_flags );
  9248.         break;
  9249.  
  9250.       case N_CONN_IND:
  9251.         printf( "\tN_CONN_IND\n" );
  9252.         printf( "\tsource:\t\t" );
  9253.         x25dump_data( (char *)primitive,
  9254.                      primitive->conn_ind.SRC_offset,
  9255.                      primitive->conn_ind.SRC_length );
  9256.         printf( "\tdestination:\t" );
  9257.         x25dump_data( (char *)primitive,
  9258.                      primitive->conn_ind.DEST_offset,
  9259.                      primitive->conn_ind.DEST_length );
  9260.         printf( "\tSEQ_number:\t%d\n", primitive->conn_ind.SEQ_number );
  9261.         printf( "\tflags:\t%d\n", primitive->conn_ind.CONN_flags );
  9262.         break;
  9263.  
  9264.       case N_CONN_REQ:
  9265.         printf( "\tN_CONN_REQ\n\tdestination:\t" );
  9266.         x25dump_data( (char *)primitive,
  9267.                      primitive->conn_req.DEST_offset,
  9268.                      primitive->conn_req.DEST_length );
  9269.         printf( "\tflags:\t%d\n", primitive->conn_req.CONN_flags );
  9270.         break;
  9271.  
  9272.       case N_CONN_RES:
  9273.         printf( "\tN_CONN_RES\n" );
  9274.         printf( "\tTOKEN_value\t%d\n", primitive->conn_res.TOKEN_value );
  9275.         printf( "\tSEQ_number\t%d\n", primitive->conn_res.SEQ_number );
  9276.         printf( "\tCONN_flags\t%d\n", primitive->conn_res.CONN_flags );
  9277.         printf( "\tRES\t\t" );
  9278.         x25dump_data( (char *)primitive,
  9279.                      primitive->conn_res.RES_offset,
  9280.                      primitive->conn_res.RES_length );
  9281.         break;
  9282.  
  9283.       case N_DATACK_IND:
  9284.         printf( "\tN_DATACK_IND\n" );
  9285.         break;
  9286.  
  9287.       case N_DATACK_REQ:
  9288.         printf( "\tN_DATACK_REQ\n" );
  9289.         printf( "\tflags:\t%d\n", primitive->data_req.DATA_xfer_flags );
  9290.         break;
  9291.  
  9292.       case N_DATA_IND:
  9293.         printf( "\tN_DATA_IND\n" );
  9294.         printf( "\tflags:\t%d\n", primitive->data_ind.DATA_xfer_flags );
  9295.         break;
  9296.  
  9297.       case N_DATA_REQ:
  9298.         printf( "\tN_DATA_REQ\n" );
  9299.         break;
  9300.  
  9301.       case N_DISCON_IND:
  9302.         printf( "\tN_DISCON_IND\n" );
  9303.         printf( "\torigin:\t%d\n", primitive->discon_ind.DISCON_orig );
  9304.         printf( "\treason:\t\t%d\n", primitive->discon_ind.DISCON_reason );
  9305.         printf( "\tseq no:\t\t%d\n", primitive->discon_ind.SEQ_number );
  9306.         printf( "\tRES:\t" );
  9307.         x25dump_data( (char *)primitive,
  9308.                      primitive->discon_ind.RES_offset,
  9309.                      primitive->discon_ind.RES_length );
  9310.         break;
  9311.  
  9312.       case N_DISCON_REQ:
  9313.         printf( "\tN_DISCON_REQ\n" );
  9314.         printf( "\tDISCON_reason:\t%d\n",
  9315.                primitive->discon_req.DISCON_reason );
  9316.         printf( "\tRES:\t" );
  9317.         x25dump_data( (char *)primitive,
  9318.                      primitive->discon_req.RES_offset,
  9319.                      primitive->discon_req.RES_length );
  9320.         printf( "\tSEQ_number:\t%d\n", primitive->discon_req.SEQ_number );
  9321.         break;
  9322.  
  9323.       case N_ERROR_ACK:
  9324.         printf( "\tN_ERROR_ACK\n" );
  9325.         printf( "\tCaused by:\t%s\n",
  9326.                x25prim( primitive->error_ack.ERROR_prim ) );
  9327.         printf( "\tNPI error:\t%s\n",
  9328.                x25err( primitive->error_ack.NPI_error ));
  9329.         errno = primitive->error_ack.UNIX_error;
  9330.         perror( "\t" );
  9331.         break;
  9332.  
  9333.       case N_EXDATA_IND:
  9334.         printf( "\tN_EXDATA_ACK\n" );
  9335.         break;
  9336.  
  9337.       case N_EXDATA_REQ:
  9338.         printf( "\tN_EXDATA_REQ\n" );
  9339.         break;
  9340.  
  9341.       case N_INFO_ACK:
  9342.         printf( "\tN_INFO_ACK\n" );
  9343.         printf( "\tNSDU size:\t%d\n", primitive->info_ack.NSDU_size );
  9344.         printf( "\tENSDU size:\t%d\n", primitive->info_ack.ENSDU_size );
  9345.         printf( "\tCDATA size:\t%d\n", primitive->info_ack.CDATA_size );
  9346.         printf( "\tDDATA size:\t%d\n", primitive->info_ack.DDATA_size );
  9347.         printf( "\tADDR size:\t%d\n", primitive->info_ack.ADDR_size );
  9348.         printf( "\tNIDU size:\t%d\n", primitive->info_ack.NIDU_size );
  9349.         break;
  9350.  
  9351.       case N_INFO_REQ:
  9352.         printf( "\tN_INFO_REQ\n" );
  9353.         break;
  9354.  
  9355.       case N_OK_ACK:
  9356.         printf( "\tN_OK_ACK\n" );
  9357.         break;
  9358.  
  9359.       case N_OPTMGMT_REQ:
  9360.         printf( "\tN_OPTMGMT_REQ\n" );
  9361.         break;
  9362.  
  9363.       case N_RESET_CON:
  9364.         printf( "\tN_RESET_CON\n" );
  9365.         break;
  9366.  
  9367.       case N_RESET_IND:
  9368.         printf( "\tN_RESET_IND\n" );
  9369.         printf( "\treason:\t\t%d\n", primitive->reset_ind.RESET_reason );
  9370.         printf( "\torigin:\t\t%d\n", primitive->reset_ind.RESET_orig );
  9371.         break;
  9372.  
  9373.       case N_RESET_REQ:
  9374.         printf( "\tN_RESET_REQ\n" );
  9375.         printf( "\treason:\t\t%d\n", primitive->reset_req.RESET_reason );
  9376.         break;
  9377.  
  9378.       case N_RESET_RES:
  9379.         printf( "\tN_RESET_RES\n" );
  9380.         break;
  9381.  
  9382.       case N_UDERROR_IND:
  9383.         printf( "\tN_UDERROR_IND\n" );
  9384.         break;
  9385.  
  9386.       case N_UNBIND_REQ:
  9387.         printf( "\tN_UNBIND_REQ\n" );
  9388.         break;
  9389.  
  9390.       case N_UNITDATA_REQ:
  9391.         printf( "\tN_UNITDATA_REQ\n" );
  9392.         break;
  9393.  
  9394.       case N_UNITDATA_IND:
  9395.         printf( "\tN_UNITDATA_IND\n" );
  9396.         break;
  9397.  
  9398.       default:
  9399.         (void) printf( "Unknown NPI error %d", primitive->PRIM_type );
  9400.         return 0;
  9401.     }
  9402. }
  9403. #endif /* DEBUG */
  9404.  
  9405. /* it looks like signal handling is not needed with streams! */
  9406. /* x25oobh()    - handle SIGURG signals - take from isode ? */
  9407.  
  9408. #endif /* IBMX25 */
  9409.  
  9410. #ifndef NOHTTP
  9411. /*
  9412.   Which time.h files to include... See ckcdeb.h for defaults.
  9413.   Note that 0, 1, 2, or all 3 of these can be included according to
  9414.   the symbol definitions.
  9415. */
  9416. #ifndef NOTIMEH
  9417. #ifdef TIMEH
  9418. #include <time.h>
  9419. #endif /* TIMEH */
  9420. #endif /* NOTIMEH */
  9421.  
  9422. #ifndef NOSYSTIMEH
  9423. #ifdef SYSTIMEH
  9424. #include <sys/time.h>
  9425. #endif /* SYSTIMEH */
  9426. #endif /* NOSYSTIMEH */
  9427.  
  9428. #ifndef NOSYSTIMEBH
  9429. #ifdef SYSTIMEBH
  9430. #include <sys/timeb.h>
  9431. #endif /* SYSTIMEBH */
  9432. #endif /* NOSYSTIMEBH */
  9433.  
  9434. #ifndef TIMEH
  9435. #ifndef SYSTIMEH
  9436. #ifndef SYSTIMEBH
  9437. #ifdef Plan9
  9438. #include <sys/time.h>
  9439. #else
  9440. #ifdef AIX41
  9441. #include <time.h>
  9442. #else
  9443. #ifdef SUNOS4
  9444. #include <sys/time.h>
  9445. #else
  9446. #ifdef SYSTIMEH
  9447. #include <sys/time.h>
  9448. #else
  9449. #ifdef POSIX
  9450. #include <posix/time.h>
  9451. #else
  9452. #ifdef CLIX
  9453. #include <sys/time.h>
  9454. #else
  9455. #ifdef OS2
  9456. #include <time.h>
  9457. #else
  9458. #include <time.h>
  9459. /* #include <utime.h> */
  9460. #endif /* OS2 */
  9461. #endif /* CLIX */
  9462. #endif /* POSIX */
  9463. #endif /* SYSTIMEH */
  9464. #endif /* SUNOS4 */
  9465. #endif /* AIX41 */
  9466. #endif /* Plan9 */
  9467. #endif
  9468. #endif
  9469. #endif
  9470.  
  9471. #ifdef OS2
  9472. #include <sys/utime.h>
  9473. #ifdef NT
  9474. #define utimbuf _utimbuf
  9475. #endif /* NT */
  9476. #define utime   _utime
  9477. #else
  9478. #ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
  9479. #include <sys/utime.h>                  /* for extra fields required by */
  9480. #else                                   /* 88Open spec. */
  9481. #ifdef UTIMEH                           /* or <utime.h> if requested */
  9482. #include <utime.h>                      /* (SVR4, POSIX) */
  9483. #define SYSUTIMEH                       /* Use this for both cases. */
  9484. #endif /* UTIMEH */
  9485. #endif /* SYSUTIMEH */
  9486. #endif /* OS2 */
  9487.  
  9488. #ifndef HTTP_VERSION
  9489. #define HTTP_VERSION "HTTP/1.1"
  9490. #endif /* HTTP_VERSION */
  9491.  
  9492. #ifdef CMDATE2TM
  9493. time_t
  9494. #ifdef CK_ANSIC
  9495. http_date(char * date)
  9496. #else
  9497. http_date(date) char * date;
  9498. #endif /* CK_ANSIC */
  9499. /* http_date */ {
  9500.     /* HTTP dates are of the form:  "Sun, 06 Oct 1997 20:11:47 GMT" */
  9501.     /* There are two older formats which we are required to parse
  9502.      * that we currently do not:
  9503.      * 
  9504.      * RFC 850:   "Sunday, 06-Oct-97 20:11:47 GMT"
  9505.      * asctime(): "Sun Nov  6 20:11:47 1997"
  9506.      *
  9507.      * However, it is required that all dates be sent in the form we 
  9508.      * do accept.  The other two formats are for compatibility with 
  9509.      * really old servers.
  9510.      */
  9511.     extern char cmdatebuf[18];
  9512.     struct tm t_tm;
  9513.     time_t t;
  9514.     char ldate[32];
  9515.     int j;
  9516.  
  9517.     j = ckindex(",",date,0,0,0);
  9518.     ckstrncpy(ldate,&date[j+1],25);
  9519.  
  9520.     {    /*
  9521.        cmcvtate() date changed to return a string pointer.
  9522.        fdc, 12 Aug 2001.
  9523.     */
  9524.     char * dp;
  9525.     dp = (char *)cmcvtdate(ldate,0); /* Convert to normal form */
  9526.     if (!dp)
  9527.       return(0);
  9528.     t_tm = *cmdate2tm(dp,1);
  9529.     }
  9530. /*
  9531.   From Lucas Hart, 5 Dec 2001:
  9532.   "On the systems to which I have access (SunOS 4.1.1, Solaris 8, and Tru64), 
  9533.   setting tm_isdst to -1 maintains the correct timezone offsets, i.e., writes 
  9534.   the specified (GMT) time if the buffer size is 21, or the contemporaneous 
  9535.   localtime if the buffer size is 25.  Perhaps tm_isdst should be set in
  9536.   cmdate2tm(), rather than only in http_date."
  9537. */
  9538. #ifndef NOTM_ISDST            /* For platforms where */
  9539.     t_tm.tm_isdst = -1;            /* tm_isdst doesn't exist. */
  9540. #endif /* NOTM_ISDST */
  9541.  
  9542.     t = mktime(&t_tm);                  /* NOT PORTABLE */
  9543.  
  9544. #ifdef XX_TIMEZONE
  9545.     t -= _timezone;
  9546. #endif /* XX_TIMEZONE */
  9547.  
  9548.     return(t);
  9549. }
  9550. #endif /* CMDATE2TM */
  9551.  
  9552. char *
  9553. http_now() {
  9554.     static char nowstr[32];
  9555. #ifdef CMDATE2TM
  9556.     struct tm  *gmt;
  9557.     time_t ltime;                       /* NOT PORTABLE */
  9558.  
  9559.     time(<ime);
  9560.  
  9561.     gmt = gmtime(<ime);               /* PROBABLY NOT PORTABLE */
  9562.     strftime(nowstr,32,"%a, %d %b %Y %H:%M:%S GMT",gmt); /* NOT PORTABLE */
  9563.     /* not only is it not portable but it's locale-dependent */
  9564. #else
  9565. /*
  9566.   This is hopeless.  First of all, it seems that HTTP wants Day and Month
  9567.   NAMES?  In English?  Whose idea was that?  Even worse, the date/time must be
  9568.   expressed in Zulu (UTC (GMT)), and converting from local time to GMT is a
  9569.   nightmare.  Every platform does it differently, if at all -- even if we
  9570.   restrict ourselves to UNIX.  For example (quoting from recent C-Kermit edit
  9571.   history), "Fixed a longstanding bug in the BSDI version, in which incoming
  9572.   file dates were set in GMT rather than local time.  It seems in 4.4BSD,
  9573.   localtime() does not return the local time, but rather Zero Meridian (Zulu)
  9574.   time (GMT), and must be adjusted by the tm_gmtoff value."  Swell.  For
  9575.   greater appreciation of the scope of the problem, just take a look at the
  9576.   time-related #ifdefs in ckutio.c.  The only right way to do this is to add
  9577.   our own portable API for converting between local time and GMT/UTC/Zulu
  9578.   that shields us not only from UNIXisms like time_t and struct tm, but also
  9579.   the unbelievable amount of differences in time-related APIs -- e.g. is
  9580.   "timezone" an external variable or a function; which header file(s) do we
  9581.   include, etc etc etc.  It's a major project.
  9582. */
  9583.     int x;
  9584.     x = cmcvtdate("",1);
  9585.  
  9586. Evidently this code is not used -- if it is, it must be fixed to use
  9587. new (aug 2001) cmcvtdate() calling conventions.
  9588.  
  9589.     if (x < 0)
  9590.       return("");
  9591. /*  yyyymmdd hh:mm:ss */
  9592. /*  01234567890123456 */
  9593.     nowstr[0]  = 'X';                   /* 1st letter of day */
  9594.     nowstr[1]  = 'x';                   /* 2nd letter of day */
  9595.     nowstr[2]  = 'x';                   /* 3rd letter of day */
  9596.     nowstr[3]  = ',';
  9597.     nowstr[4]  = ' ';
  9598.     nowstr[5]  = cmdate[6];
  9599.     nowstr[6]  = cmdate[7];
  9600.     nowstr[7]  = ' ';
  9601.     nowstr[8]  = ' ';                   /* first letter of month */
  9602.     nowstr[9]  = ' ';                   /* second letter of month */
  9603.     nowstr[10] = ' ';                   /* third letter of month */
  9604.     nowstr[11] = ' ';
  9605.     nowstr[12] = cmdate[0];
  9606.     nowstr[13] = cmdate[1];
  9607.     nowstr[14] = cmdate[2];
  9608.     nowstr[15] = cmdate[3];
  9609.     nowstr[16] = ' ';
  9610.     nowstr[17] = cmdate[9];
  9611.     nowstr[18] = cmdate[10];
  9612.     nowstr[19] = cmdate[11];
  9613.     nowstr[20] = cmdate[12];
  9614.     nowstr[21] = cmdate[13];
  9615.     nowstr[22] = cmdate[14];
  9616.     nowstr[23] = cmdate[15];
  9617.     nowstr[24] = cmdate[16];
  9618.     nowstr[25] = ' ';
  9619.     nowstr[26] = 'G';
  9620.     nowstr[27] = 'M';
  9621.     nowstr[28] = 'T';
  9622.     nowstr[29] = '\0';
  9623. #endif /* CMDATE2TM */
  9624.     return(nowstr);
  9625. }
  9626.  
  9627. #ifndef OS2
  9628. #ifndef CK_AUTHENTICATION
  9629. /* from ckuusr.h, which this module normally doesn't include */
  9630. _PROTOTYP( int dclarray, (char, int) );
  9631. #endif /* CK_AUTHENTICATION */
  9632. #endif /* OS2 */
  9633. /*
  9634.   Assign http response pairs to given array.
  9635.   For best results, response pairs should contain no spaces.
  9636.  
  9637.   Call with:
  9638.     resp  =  pointer to response list.
  9639.     n     =  size of response list.
  9640.     array =  array letter.
  9641.   Returns:
  9642.     0 on failure.
  9643.     >= 1, size of array, on success.
  9644. */
  9645. static int
  9646. #ifdef CK_ANSIC
  9647. http_mkarray(char ** resp, int n, char array)
  9648. #else
  9649. http_mkarray(resp, n, array) char ** resp; int n; char array;
  9650. #endif /* CK_ANSIC */
  9651. {
  9652. #ifndef NOSPL
  9653.     int i, x;
  9654.     char ** ap;
  9655.     extern char ** a_ptr[];
  9656.     extern int a_dim[];
  9657.  
  9658.     if (!array || n <= 0)
  9659.       return(0);
  9660.     if ((x = dclarray(array,n)) < 0) {
  9661.         printf("?Array declaration failure\n");
  9662.         return(-9);
  9663.     }
  9664.     /* Note: argument array is 0-based but Kermit array is 1-based */
  9665.     ap = a_ptr[x];
  9666.     ap[0] = NULL;            /* 0th element is empty */
  9667.     for (i = 1; i <= n; i++) {
  9668.         ap[i] = resp[i-1];        /* If resp elements were malloc'd */
  9669.         resp[i-1] = NULL;
  9670.     }
  9671.     a_dim[x] = n;
  9672.     return(n);
  9673. #else
  9674.     return(0);
  9675. #endif /* NOSPL */
  9676. }
  9677.  
  9678. #define HTTPHEADCNT 64
  9679. int
  9680. http_get_chunk_len() 
  9681. {
  9682.     int len = 0;
  9683.     int i = 0, j = -1;
  9684.     char buf[24];
  9685.     int ch;
  9686.  
  9687.     while ((ch = http_inc(0)) >= 0 && i < 24) {
  9688.         buf[i] = ch;
  9689.         if ( buf[i] == ';' )        /* Find chunk-extension (if any) */
  9690.             j = i;
  9691.         if ( buf[i] == 10 ) {        /* found end of line */
  9692.             if (i > 0 && buf[i-1] == 13)
  9693.                 i--;
  9694.             buf[i] = '\0';
  9695.             break;
  9696.         }
  9697.         i++;
  9698.     }
  9699.     if ( i < 24 ) {            /* buf now contains len in Hex */
  9700.         len = hextoulong(buf, j == -1 ? i : j-1);
  9701.     }
  9702.  
  9703.     return(len);
  9704. }
  9705.  
  9706. int
  9707. http_isconnected()
  9708. {
  9709.     return(httpfd != -1);
  9710. }       
  9711.  
  9712. char * 
  9713. http_host()
  9714. {
  9715.     return(httpfd != -1 ? http_host_port : "");
  9716. }
  9717.  
  9718. char *
  9719. http_security()
  9720. {
  9721.     if ( httpfd == -1 )
  9722.         return("NULL");
  9723. #ifdef CK_SSL
  9724.     if (tls_http_active_flag) {
  9725.         SSL_CIPHER * cipher;
  9726.         const char *cipher_list;
  9727.         static char buf[128];
  9728.     buf[0] = NUL;
  9729.         cipher = SSL_get_current_cipher(tls_http_con);
  9730.         cipher_list = SSL_CIPHER_get_name(cipher);
  9731.         SSL_CIPHER_description(cipher,buf,sizeof(buf));
  9732.         return(buf);
  9733.     }
  9734. #endif /* CK_SSL */
  9735.     return("NULL");
  9736. }
  9737.  
  9738. int
  9739. http_reopen()
  9740. {
  9741.     int rc = 0;
  9742.     char * s = NULL;            /* strdup is not portable */
  9743.     makestr(&s,(char *)http_ip);
  9744.     rc = http_open(s,ckuitoa(http_port),http_ssl,NULL,0);
  9745.     free(s);
  9746.     return(rc);
  9747. }
  9748.  
  9749.  
  9750. int
  9751. #ifdef CK_ANSIC
  9752. http_open(char * hostname, char * svcname, int use_ssl, char * rdns_name, 
  9753.           int rdns_len)
  9754. #else /* CK_ANSIC */
  9755. http_open(hostname, svcname, use_ssl, rdns_name, rdns_len)
  9756.     char * hostname;
  9757.     char * svcname;
  9758.     int    use_ssl;
  9759.     char * rdns_name;
  9760.     int    rdns_len;
  9761. #endif /* CK_ANSIC */
  9762. {
  9763.     char *p;
  9764.     int i, x, dns = 0;
  9765. #ifdef TCPSOCKET
  9766.     int isconnect = 0;
  9767. #ifdef SO_OOBINLINE
  9768.     int on = 1;
  9769. #endif /* SO_OOBINLINE */
  9770.     struct servent *service=NULL;
  9771.     struct hostent *host=NULL;
  9772.     struct sockaddr_in r_addr;
  9773.     struct sockaddr_in sin;
  9774.     struct sockaddr_in l_addr;
  9775.     GSOCKNAME_T l_slen;
  9776. #ifdef EXCELAN
  9777.     struct sockaddr_in send_socket;
  9778. #endif /* EXCELAN */
  9779.  
  9780. #ifdef INADDRX
  9781. /* inet_addr() is of type struct in_addr */
  9782. #ifdef datageneral
  9783.     extern struct in_addr inet_addr();
  9784. #else
  9785. #ifdef HPUX5WINTCP
  9786.     extern struct in_addr inet_addr();
  9787. #endif /* HPUX5WINTCP */
  9788. #endif /* datageneral */
  9789.     struct in_addr iax;
  9790. #else
  9791. #ifdef INADDR_NONE
  9792.     struct in_addr iax;
  9793. #else /* INADDR_NONE */
  9794.     long iax;
  9795. #endif /* INADDR_NONE */
  9796. #endif /* INADDRX */
  9797.  
  9798.     if ( rdns_name == NULL || rdns_len < 0 )
  9799.     rdns_len = 0;
  9800.  
  9801.     *http_ip = '\0';                     /* Initialize IP address string */
  9802.  
  9803. #ifdef DEBUG
  9804.     if (deblog) {
  9805.     debug(F110,"http_open hostname",hostname,0);
  9806.     debug(F110,"http_open svcname",svcname,0);
  9807.     }
  9808. #endif /* DEBUG */
  9809.     if (!hostname) hostname = "";
  9810.     if (!svcname) svcname = "";
  9811.     if (!*hostname || !*svcname) return(-1);
  9812.  
  9813.     service = ckgetservice(hostname,svcname,http_ip,20);
  9814.  
  9815.     if (service == NULL) {
  9816.         if ( !quiet ) 
  9817.             printf("?Invalid service: %s\r\n",svcname);
  9818.         return(-1);
  9819.     }
  9820.  
  9821.     /* For HTTP connections we must preserve the original hostname and */
  9822.     /* service requested so we can include them in the Host header.    */
  9823.     ckmakmsg(http_host_port,sizeof(http_host_port),hostname,":",
  9824.               ckuitoa(ntohs(service->s_port)),NULL);
  9825.     http_port = ntohs(service->s_port);
  9826.     http_ssl = use_ssl;
  9827.     debug(F111,"http_open",http_host_port,http_port);
  9828.  
  9829.     /* 'http_ip' contains the IP address to which we want to connect        */
  9830.     /* 'svcnam'   contains the service name                                 */
  9831.     /* 'service->s_port' contains the port number in network byte order     */
  9832.  
  9833.     /* If we are using an http proxy, we need to create a buffer containing */
  9834.     /*   hostname:port-number                                               */
  9835.     /* to pass to the http_connect() function.  Then we need to replace     */
  9836.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  9837.     /* with the port number of the proxy (default port 80).                 */
  9838.  
  9839.     if ( tcp_http_proxy ) {
  9840.     char namecopy[NAMECPYL];
  9841.  
  9842.     ckmakmsg(proxycopy,sizeof(proxycopy),hostname,":",
  9843.          ckuitoa(ntohs(service->s_port)),NULL);
  9844.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  9845.  
  9846.         p = namecopy;                       /* Was a service requested? */
  9847.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  9848.         if (*p == ':') {                    /* Have a colon */
  9849.             debug(F110,"netopen name has colon",namecopy,0);
  9850.             *p++ = '\0';                    /* Get service name or number */
  9851.         } else {
  9852.             strcpy(++p,"http");
  9853.         }
  9854.  
  9855.         service = ckgetservice(namecopy,p,http_ip,20);
  9856.         if (!service) {
  9857.             fprintf(stderr, "Can't find port for service %s\n", p);
  9858. #ifdef TGVORWIN
  9859.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  9860. #else
  9861.             debug(F101,"netopen can't get service for proxy","",errno);
  9862. #endif /* TGVORWIN */
  9863.             errno = 0;                  /* (rather than mislead) */
  9864.             return(-1);
  9865.         }
  9866.     }
  9867.  
  9868.     /* Set up socket structure and get host address */
  9869.     bzero((char *)&r_addr, sizeof(r_addr));
  9870.     debug(F100,"http_open bzero ok","",0);
  9871.  
  9872. #ifdef INADDR_NONE
  9873.     debug(F101,"http_open INADDR_NONE defined","",INADDR_NONE);
  9874. #else /* INADDR_NONE */
  9875.     debug(F100,"http_open INADDR_NONE not defined","",0);
  9876. #endif /* INADDR_NONE */
  9877. #ifdef INADDRX
  9878.     debug(F100,"http_open INADDRX defined","",0);
  9879. #else /* INADDRX */
  9880.     debug(F100,"http_open INADDRX not defined","",0);
  9881. #endif /* INADDRX */
  9882.  
  9883. #ifndef NOMHHOST
  9884. #ifdef INADDRX
  9885.     iax = inet_addr(http_ip[0]?http_ip:hostname);
  9886.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  9887. #else /* INADDRX */
  9888. #ifdef INADDR_NONE
  9889.     iax.s_addr = inet_addr(http_ip[0]?http_ip:hostname);
  9890.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  9891. #else /* INADDR_NONE */
  9892. #ifndef datageneral
  9893.     iax = (unsigned int) inet_addr(http_ip[0]?http_ip:hostname);
  9894. #else
  9895.     iax = -1L;
  9896. #endif /* datageneral */
  9897.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax);
  9898. #endif /* INADDR_NONE */
  9899. #endif /* INADDRX */
  9900.  
  9901.     dns = 0;
  9902.     if (
  9903. #ifdef INADDR_NONE
  9904.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  9905. #else /* INADDR_NONE */
  9906.         iax < 0
  9907. #endif /* INADDR_NONE */
  9908.         ) {
  9909.         if (!quiet) {
  9910.             printf(" DNS Lookup... ");
  9911.             fflush(stdout);
  9912.         }
  9913.         if ((host = gethostbyname(http_ip[0] ? http_ip : hostname)) != NULL) {
  9914.             debug(F100,"http_open gethostbyname != NULL","",0);
  9915.             host = ck_copyhostent(host);
  9916.             dns = 1;                    /* Remember we performed dns lookup */
  9917.             r_addr.sin_family = host->h_addrtype;
  9918.             if (host->h_name && host->h_name[0] && (rdns_len > 0)
  9919.                  && (tcp_http_proxy == NULL)
  9920.                  )
  9921.         ckmakmsg(rdns_name,rdns_len,host->h_name,":",svcname,NULL);
  9922.  
  9923. #ifdef HADDRLIST
  9924. #ifdef h_addr
  9925.             /* This is for trying multiple IP addresses - see <netdb.h> */
  9926.             if (!(host->h_addr_list))
  9927.               return(-1);
  9928.             bcopy(host->h_addr_list[0],
  9929.                   (caddr_t)&r_addr.sin_addr,
  9930.                   host->h_length
  9931.                   );
  9932. #else
  9933.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  9934. #endif /* h_addr */
  9935. #else  /* HADDRLIST */
  9936.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  9937. #endif /* HADDRLIST */
  9938. #ifndef EXCELAN
  9939.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  9940. #endif /* EXCELAN */
  9941.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  9942.                   (caddr_t)&r_addr.sin_addr);
  9943.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  9944.                   r_addr.sin_addr.s_addr);
  9945.             debug(F111,"BCOPY","host->h_length",host->h_length);
  9946.         }
  9947.     }
  9948. #endif /* NOMHHOST */
  9949.  
  9950.     if (!dns) {
  9951. #ifdef INADDRX
  9952. /* inet_addr() is of type struct in_addr */
  9953.         struct in_addr ina;
  9954.         unsigned long uu;
  9955.         debug(F100,"http_open gethostbyname == NULL: INADDRX","",0);
  9956.         ina = inet_addr(http_ip[0]?http_ip:hostname);
  9957.         uu = *(unsigned int *)&ina;
  9958. #else /* Not INADDRX */
  9959. /* inet_addr() is unsigned long */
  9960.         unsigned long uu;
  9961.         debug(F100,"http_open gethostbyname == NULL: Not INADDRX","",0);
  9962.         uu = inet_addr(http_ip[0]?http_ip:hostname);
  9963. #endif /* INADDRX */
  9964.         debug(F101,"http_open uu","",uu);
  9965.         if (
  9966. #ifdef INADDR_NONE
  9967.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  9968. #else   /* INADDR_NONE */
  9969.             uu != ((unsigned long)-1)
  9970. #endif /* INADDR_NONE */
  9971.             ) {
  9972.             r_addr.sin_addr.s_addr = uu;
  9973.             r_addr.sin_family = AF_INET;
  9974.         } else {
  9975. #ifdef VMS
  9976.             fprintf(stdout, "\r\n");    /* complete any previous message */
  9977. #endif /* VMS */
  9978.             fprintf(stderr, "Can't get address for %s\n", 
  9979.                      http_ip[0]?http_ip:hostname);
  9980. #ifdef TGVORWIN
  9981.             debug(F101,"http_open can't get address","",socket_errno);
  9982. #else
  9983.             debug(F101,"http_open can't get address","",errno);
  9984. #endif /* TGVORWIN */
  9985.             errno = 0;                  /* Rather than mislead */
  9986.             return(-1);
  9987.         }
  9988.     }
  9989.  
  9990.     /* Get a file descriptor for the connection. */
  9991.  
  9992.     r_addr.sin_port = service->s_port;
  9993.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  9994.     debug(F110,"http_open trying",http_ip,0);
  9995.     if (!quiet && *http_ip) {
  9996.         printf(" Trying %s... ", http_ip);
  9997.         fflush(stdout);
  9998.     }
  9999.  
  10000.     /* Loop to try additional IP addresses, if any. */
  10001.  
  10002.     do {
  10003. #ifdef EXCELAN
  10004.         send_socket.sin_family = AF_INET;
  10005.         send_socket.sin_addr.s_addr = 0;
  10006.         send_socket.sin_port = 0;
  10007.         if ((httpfd = socket(SOCK_STREAM, (struct sockproto *)0,
  10008.                             &send_socket, SO_REUSEADDR)) < 0)
  10009. #else  /* EXCELAN */
  10010.         if ((httpfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  10011. #endif /* EXCELAN */
  10012.             {
  10013. #ifdef EXCELAN
  10014.                 experror("TCP socket error");
  10015. #else
  10016. #ifdef TGVORWIN
  10017. #ifdef OLD_TWG
  10018.                 errno = socket_errno;
  10019. #endif /* OLD_TWG */
  10020.                 socket_perror("TCP socket error");
  10021.                 debug(F101,"http_open socket error","",socket_errno);
  10022. #else
  10023.                 perror("TCP socket error");
  10024.                 debug(F101,"http_open socket error","",errno);
  10025. #endif /* TGVORWIN */
  10026. #endif /* EXCELAN */
  10027.                 return (-1);
  10028.             }
  10029.         errno = 0;
  10030.  
  10031.        /* If a specific TCP address on the local host is desired we */
  10032.        /* must bind it to the socket.                               */
  10033. #ifndef datageneral
  10034.          if (tcp_address) {
  10035.              int s_errno;
  10036.  
  10037.              debug(F110,"http_open binding socket to",tcp_address,0);
  10038.              bzero((char *)&sin,sizeof(sin));
  10039.              sin.sin_family = AF_INET;
  10040. #ifdef INADDRX
  10041.              inaddrx = inet_addr(tcp_address);
  10042.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  10043. #else
  10044.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  10045. #endif /* INADDRX */
  10046.              sin.sin_port = 0;
  10047.              if (bind(httpfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  10048.                  s_errno = socket_errno; /* Save error code */
  10049. #ifdef TCPIPLIB
  10050.                  socket_close(httpfd);
  10051. #else /* TCPIPLIB */
  10052.                  close(httpfd);
  10053. #endif /* TCPIPLIB */
  10054.                  httpfd = -1;
  10055.                  errno = s_errno;       /* and report this error */
  10056.                  debug(F101,"http_open bind errno","",errno);
  10057.                  return(-1);
  10058.              }
  10059.          }
  10060. #endif /* datageneral */
  10061.  
  10062. /* Now connect to the socket on the other end. */
  10063.  
  10064. #ifdef EXCELAN
  10065.         if (connect(httpfd, &r_addr) < 0)
  10066. #else
  10067. #ifdef NT
  10068.           WSASafeToCancel = 1;
  10069. #endif /* NT */
  10070.         if (connect(httpfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  10071. #endif /* EXCELAN */
  10072.           {
  10073. #ifdef NT
  10074.               WSASafeToCancel = 0;
  10075. #endif /* NT */
  10076. #ifdef OS2
  10077.               i = socket_errno;
  10078. #else /* OS2 */
  10079. #ifdef TGVORWIN
  10080.               i = socket_errno;
  10081. #else
  10082.               i = errno;                /* Save error code */
  10083. #endif /* TGVORWIN */
  10084. #endif /* OS2 */
  10085. #ifdef HADDRLIST
  10086. #ifdef h_addr
  10087.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  10088.                   perror("");
  10089.                   host->h_addr_list++;
  10090.                   bcopy(host->h_addr_list[0],
  10091.                         (caddr_t)&r_addr.sin_addr,
  10092.                         host->h_length);
  10093.  
  10094.                   ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10095.                   debug(F110,"http_open h_addr_list",http_ip,0);
  10096.                   if (!quiet && *http_ip) {
  10097.                       printf(" Trying %s... ", http_ip);
  10098.                       fflush(stdout);
  10099.                   }
  10100. #ifdef TCPIPLIB
  10101.                   socket_close(httpfd); /* Close it. */
  10102. #else
  10103.                   close(httpfd);
  10104. #endif /* TCPIPLIB */
  10105.                   continue;
  10106.               }
  10107. #endif /* h_addr */
  10108. #endif  /* HADDRLIST */
  10109.               http_close();
  10110.               httpfd = -1;
  10111.               errno = i;                /* And report this error */
  10112. #ifdef EXCELAN
  10113.               if (errno) experror("http_open connect");
  10114. #else
  10115. #ifdef TGVORWIN
  10116.               debug(F101,"http_open connect error","",socket_errno);
  10117.               /* if (errno) socket_perror("http_open connect"); */
  10118. #ifdef OLD_TWG
  10119.               errno = socket_errno;
  10120. #endif /* OLD_TWG */
  10121.           if (!quiet)
  10122.         socket_perror("http_open connect");
  10123. #else /* TGVORWIN */
  10124.               debug(F101,"http_open connect errno","",errno);
  10125. #ifdef VMS
  10126.           if (!quiet)
  10127.         perror("\r\nFailed");
  10128. #else
  10129.           if (!quiet)
  10130.         perror("Failed");
  10131. #endif /* VMS */
  10132. #ifdef DEC_TCPIP
  10133.           if (!quiet)
  10134.         perror("http_open connect");
  10135. #endif /* DEC_TCPIP */
  10136. #ifdef CMU_TCPIP
  10137.           if (!quiet)
  10138.         perror("http_open connect");
  10139. #endif /* CMU_TCPIP */
  10140. #endif /* TGVORWIN */
  10141. #endif /* EXCELAN */
  10142.               return(-1);
  10143.           }
  10144. #ifdef NT
  10145.         WSASafeToCancel = 0;
  10146. #endif /* NT */
  10147.         isconnect = 1;
  10148.     } while (!isconnect);
  10149.  
  10150. #ifdef NON_BLOCK_IO
  10151.     on = 1;
  10152.     x = socket_ioctl(httpfd,FIONBIO,&on);
  10153.     debug(F101,"http_open FIONBIO","",x);
  10154. #endif /* NON_BLOCK_IO */
  10155.  
  10156.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  10157.     /* need to attempt to connect through the proxy to the actual host */
  10158.     /* If that is successful, we have to pretend that we made a direct */
  10159.     /* connection to the actual host.                                  */
  10160.  
  10161.     if ( tcp_http_proxy ) {
  10162. #ifdef OS2
  10163.     char * agent = "Kermit 95";        /* Default user agent */
  10164. #else
  10165.     char * agent = "C-Kermit";
  10166. #endif /* OS2 */
  10167.  
  10168.         if (http_connect(httpfd,agent,NULL,
  10169.              tcp_http_proxy_user,
  10170.              tcp_http_proxy_pwd,
  10171.              0,
  10172.              proxycopy
  10173.              ) < 0) {
  10174.             http_close();
  10175.             return(-1);
  10176.         }
  10177.     }
  10178.  
  10179. #ifdef SO_OOBINLINE
  10180.     /* See note on SO_OOBINLINE in netopen() */
  10181. #ifdef datageneral
  10182.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10183. #else
  10184. #ifdef BSD43
  10185.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10186. #else
  10187. #ifdef OSF1
  10188.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10189. #else
  10190. #ifdef POSIX
  10191.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10192. #else
  10193. #ifdef MOTSV88R4
  10194.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10195. #else
  10196. #ifdef SOLARIS
  10197. /*
  10198.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  10199.   compiling and working fine on all the others, so best not to change it.
  10200. */
  10201.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10202. #else
  10203. #ifdef OSK
  10204.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10205. #else
  10206. #ifdef OS2
  10207.     {
  10208.         int rc;
  10209.         rc = setsockopt(httpfd,
  10210.                         SOL_SOCKET,
  10211.                         SO_OOBINLINE,
  10212.                         (char *) &on,
  10213.                         sizeof on
  10214.                         );
  10215.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  10216.     }
  10217. #else
  10218. #ifdef VMS /* or, at least, VMS with gcc */
  10219.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10220. #else
  10221. #ifdef CLIX
  10222.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10223. #else
  10224.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  10225. #endif /* CLIX */
  10226. #endif /* VMS */
  10227. #endif /* OS2 */
  10228. #endif /* OSK */
  10229. #endif /* SOLARIS */
  10230. #endif /* MOTSV88R4 */
  10231. #endif /* POSIX */
  10232. #endif /* BSD43 */
  10233. #endif /* OSF1 */
  10234. #endif /* datageneral */
  10235. #endif /* SO_OOBINLINE */
  10236.  
  10237. #ifndef NOTCPOPTS
  10238. #ifndef datageneral
  10239. #ifdef SOL_SOCKET
  10240. #ifdef TCP_NODELAY
  10241.     no_delay(tcp_nodelay);
  10242. #endif /* TCP_NODELAY */
  10243. #ifdef SO_KEEPALIVE
  10244.     keepalive(tcp_keepalive);
  10245. #endif /* SO_KEEPALIVE */
  10246. #ifdef SO_LINGER
  10247.     ck_linger(tcp_linger, tcp_linger_tmo);
  10248. #endif /* SO_LINGER */
  10249. #ifdef SO_SNDBUF
  10250.     sendbuf(tcp_sendbuf);
  10251. #endif /* SO_SNDBUF */
  10252. #ifdef SO_RCVBUF
  10253.     recvbuf(tcp_recvbuf);
  10254. #endif /* SO_RCVBUF */
  10255. #endif /* SOL_SOCKET */
  10256. #endif /* datageneral */
  10257. #endif /* NOTCPOPTS */
  10258.  
  10259. #ifndef datageneral
  10260.     /* Find out our own IP address. */
  10261.     /* We need the l_addr structure for [E]KLOGIN. */
  10262.     l_slen = sizeof(l_addr);
  10263.     bzero((char *)&l_addr, l_slen);
  10264. #ifndef EXCELAN
  10265.     if (!getsockname(httpfd, (struct sockaddr *)&l_addr, &l_slen)) {
  10266.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  10267.         ckstrncpy(myipaddr, s, 20);
  10268.         debug(F110,"getsockname",myipaddr,0);
  10269.     }
  10270. #endif /* EXCELAN */
  10271. #endif /* datageneral */
  10272.  
  10273. /* See note in netopen() on Reverse DNS lookups */
  10274.      if (tcp_rdns == SET_ON) {
  10275. #ifdef NT
  10276.         if (isWin95())
  10277.           sleep(1);
  10278. #endif /* NT */
  10279.         if (!quiet) {
  10280.             printf(" Reverse DNS Lookup... ");
  10281.             fflush(stdout);
  10282.         }
  10283.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  10284.             char * s;
  10285.             host = ck_copyhostent(host);
  10286.             debug(F100,"http_open gethostbyname != NULL","",0);
  10287.             if (!quiet) {
  10288.                 printf("(OK)\n");
  10289.                 fflush(stdout);
  10290.             }
  10291.             s = host->h_name;
  10292.             if (!s) {                   /* This can happen... */
  10293.                 debug(F100,"http_open host->h_name is NULL","",0);
  10294.                 s = "";
  10295.             }
  10296.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  10297.             /* The compiler says "Integral value implicitly converted to */
  10298.             /* pointer in assignment."  The prototype is right there */
  10299.             /* in <arpa/inet.h> so what's the problem? */
  10300.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  10301.             if (!*s) {                  /* No name so substitute the address */
  10302.                 debug(F100,"http_open host->h_name is empty","",0);
  10303.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  10304.                 if (!s)                 /* Trust No 1 */
  10305.                   s = "";
  10306.                 if (*s) {               /* If it worked, use this string */
  10307.                     ckstrncpy(http_ip,s,20);
  10308.                 }
  10309.                 s = http_ip;             /* Otherwise stick with the IP */
  10310.                 if (!*s)                 /* or failing that */
  10311.                   s = http_host_port;    /* the name we were called with. */
  10312.             }
  10313.             if (*s)                     /* return the rdns name */
  10314.                 ckmakmsg(rdns_name,rdns_len,s,":",svcname,NULL);
  10315.             
  10316.             if (!quiet && *s
  10317. #ifndef NOICP
  10318.                 && !doconx
  10319. #endif /* NOICP */
  10320.                 ) {
  10321.                 printf(" %s connected on port %s\n",s,
  10322.                        ckuitoa(ntohs(service->s_port)));
  10323. #ifdef BETADEBUG
  10324.                 /* This is simply for testing the DNS entries */
  10325.                 if (host->h_aliases) {
  10326.                     char ** a = host->h_aliases;
  10327.                     while (*a) {
  10328.                         printf(" alias => %s\n",*a);
  10329.                         a++;
  10330.                     }
  10331.                 }
  10332. #endif /* BETADEBUG */
  10333.             }
  10334.         } else {
  10335.             if (!quiet) printf("Failed.\n");
  10336.         }
  10337.     } else if (!quiet) printf("(OK)\n");
  10338.     if (!quiet) fflush(stdout);
  10339.  
  10340.     /* This should already have been done but just in case */
  10341.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10342.  
  10343. #ifdef CK_SSL
  10344.     if (use_ssl && ck_ssleay_is_installed()) {
  10345.         if (!ssl_http_init(hostname)) {
  10346.             if (bio_err!=NULL) {
  10347.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  10348.                 ERR_print_errors(bio_err);
  10349.             } else {
  10350.                 fflush(stderr);
  10351.                 fprintf(stderr,"ssl_tn_init() failed\n");
  10352.                 ERR_print_errors_fp(stderr);
  10353.             }
  10354.             http_close();
  10355.             return(-1);
  10356.         } else if ( ck_ssl_http_client(httpfd,hostname) < 0 ) {
  10357.             http_close();
  10358.             return(-1);
  10359.         }
  10360.     }
  10361. #endif /* CK_SSL */
  10362. #endif /* TCPSOCKET */
  10363.     return(0);                          /* Done. */
  10364. }
  10365.  
  10366. int
  10367. #ifdef CK_ANSIC
  10368. http_close(VOID)
  10369. #else /* CK_ANSIC */
  10370. http_close()
  10371. #endif /* CK_ANSIC */
  10372. {
  10373.     int x = 0;
  10374.     debug(F101,"http_close","",httpfd);
  10375.  
  10376.     if (httpfd == -1)                    /* Was open? */
  10377.       return(0);                        /* Wasn't. */
  10378.  
  10379. #ifndef OS2
  10380.     if (httpfd > -1)                     /* Was. */
  10381. #endif /* OS2 */
  10382.       {
  10383. #ifdef CK_SSL
  10384.           if (tls_http_active_flag) {
  10385.               if (ssl_debug_flag)
  10386.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  10387.               SSL_shutdown(tls_http_con);
  10388.               tls_http_active_flag = 0;
  10389.           }
  10390. #endif /* CK_SSL */
  10391. #ifdef TCPIPLIB
  10392.           x = socket_close(httpfd);      /* Close it. */
  10393. #else
  10394. #ifndef OS2
  10395.           x = close(httpfd);
  10396. #endif /* OS2 */
  10397. #endif /* TCPIPLIB */
  10398.       }
  10399.     httpfd = -1;                          /* Mark it as closed. */
  10400.     /* do not erase http_host_port, http_ip, http_port so they */
  10401.     /* can be used by http_reopen() */
  10402.     return(x);
  10403. }
  10404.  
  10405.  
  10406. /* http_tol()
  10407.  * Call with s = pointer to string, n = length.
  10408.  * Returns number of bytes actually written on success, or
  10409.  * -1 on i/o error, -2 if called improperly.
  10410.  */
  10411.  
  10412. int
  10413. http_tol(s,n) CHAR *s; int n; {
  10414.     int count = 0;
  10415.     int len = n;
  10416.     int try = 0;
  10417.  
  10418.     if (httpfd == -1) {
  10419.         debug(F100,"http_tol socket is closed","",0);
  10420.         return -1;
  10421.     }
  10422.     debug(F101,"http_tol TCPIPLIB ttnet","",ttnet);
  10423. #ifdef COMMENT
  10424.     hexdump("http_tol",s,n);
  10425. #endif /* COMMENT */
  10426.  
  10427. #ifdef CK_SSL
  10428.     if (tls_http_active_flag) {
  10429.         int error, r;
  10430.         /* Write using SSL */
  10431.       ssl_retry:
  10432.           r = SSL_write(tls_http_con, s, len /* >1024?1024:len */);
  10433.         switch (SSL_get_error(tls_http_con,r)) {
  10434.           case SSL_ERROR_NONE:
  10435.             debug(F111,"http_tol","SSL_write",r);
  10436.             if ( r == len )
  10437.                 return(n);
  10438.              s += r;
  10439.              len -= r;
  10440.              goto ssl_retry;
  10441.           case SSL_ERROR_WANT_WRITE:
  10442.             debug(F100,"http_tol SSL_ERROR_WANT_WRITE","",0);
  10443.             return(-1);
  10444.           case SSL_ERROR_WANT_READ:
  10445.             debug(F100,"http_tol SSL_ERROR_WANT_READ","",0);
  10446.             return(-1);
  10447.           case SSL_ERROR_SYSCALL:
  10448.               if ( r == 0 ) { /* EOF */
  10449.                   http_close();
  10450.                   return(-2);
  10451.               } else {
  10452. #ifdef NT
  10453.                   int gle = GetLastError();
  10454.                   debug(F111,"http_tol SSL_ERROR_SYSCALL",
  10455.                          "GetLastError()",gle);
  10456. #endif /* NT */
  10457.                   return(-1);
  10458.               }
  10459.           case SSL_ERROR_WANT_X509_LOOKUP:
  10460.             debug(F100,"http_tol SSL_ERROR_WANT_X509_LOOKUP","",0);
  10461.             http_close();
  10462.             return(-2);
  10463.           case SSL_ERROR_SSL:
  10464.             debug(F100,"http_tol SSL_ERROR_SSL","",0);
  10465.             http_close();
  10466.             return(-2);
  10467.           case SSL_ERROR_ZERO_RETURN:
  10468.             debug(F100,"http_tol SSL_ERROR_ZERO_RETURN","",0);
  10469.             http_close();
  10470.             return(-2);
  10471.           default:
  10472.             debug(F100,"http_tol SSL_ERROR_?????","",0);
  10473.             http_close();
  10474.             return(-2);
  10475.         }
  10476.     }
  10477. #endif /* CK_SSL */
  10478.  
  10479.   http_tol_retry:
  10480.     try++;                              /* Increase the try counter */
  10481.  
  10482.     {
  10483. #ifdef BSDSELECT
  10484.         fd_set wfds;
  10485.         struct timeval tv;
  10486.  
  10487.         debug(F101,"http_tol BSDSELECT","",0);
  10488.         tv.tv_usec = 0L;
  10489.         tv.tv_sec=30;
  10490. #ifdef NT
  10491.         WSASafeToCancel = 1;
  10492. #endif /* NT */
  10493. #ifdef STREAMING
  10494.       do_select:
  10495. #endif /* STREAMING */
  10496.         FD_ZERO(&wfds);
  10497.         FD_SET(httpfd, &wfds);
  10498.         if (select(FD_SETSIZE, NULL,
  10499. #ifdef __DECC
  10500. #ifndef __DECC_VER
  10501.                     (int *)
  10502. #endif /* __DECC_VER */
  10503. #endif /* __DECC */
  10504.                    &wfds, NULL, &tv) < 0) {
  10505.             int s_errno = socket_errno;
  10506.             debug(F101,"http_tol select failed","",s_errno);
  10507. #ifdef BETADEBUG
  10508.             printf("http_tol select failed: %d\n", s_errno);
  10509. #endif /* BETADEBUG */
  10510. #ifdef NT
  10511.             WSASafeToCancel = 0;
  10512.             if (!win95selectbug)
  10513. #endif /* NT */
  10514.               return(-1);
  10515.         }
  10516.         if (!FD_ISSET(httpfd, &wfds)) {
  10517. #ifdef STREAMING
  10518.             if (streaming)
  10519.               goto do_select;
  10520. #endif /* STREAMING */
  10521.             debug(F111,"http_tol","!FD_ISSET",ttyfd);
  10522. #ifdef NT
  10523.             WSASafeToCancel = 0;
  10524.             if (!win95selectbug)
  10525. #endif /* NT */
  10526.               return(-1);
  10527.         }
  10528. #ifdef NT
  10529.         WSASafeToCancel = 0;
  10530. #endif /* NT */
  10531. #else /* BSDSELECT */
  10532. #ifdef IBMSELECT
  10533.         {
  10534.             int tries = 0;
  10535.             debug(F101,"http_tol IBMSELECT","",0);
  10536.             while (select(&httpfd, 0, 1, 0, 1000) != 1) {
  10537.                 int count;
  10538.                 if (tries++ >= 60) {
  10539.                     /* if after 60 seconds we can't get permission to write */
  10540.                     debug(F101,"http_tol select failed","",socket_errno);
  10541.                     return(-1);
  10542.                 }
  10543. #ifdef COMMENT
  10544.                 if ((count = http_tchk()) < 0) {
  10545.                     debug(F111,"http_tol","http_tchk()",count);
  10546.                     return(count);
  10547.                 }
  10548. #endif /* COMMENT */
  10549.             }
  10550.         }
  10551. #endif /* IBMSELECT */
  10552. #endif /* BSDSELECT */
  10553. #ifdef TCPIPLIB
  10554.         if ((count = socket_write(httpfd,s,n)) < 0) {
  10555.             int s_errno = socket_errno; /* maybe a function */
  10556.             debug(F101,"http_tol socket_write error","",s_errno);
  10557. #ifdef OS2
  10558.             if (os2socketerror(s_errno) < 0)
  10559.               return(-2);
  10560. #endif /* OS2 */
  10561.             return(-1);                 /* Call it an i/o error */
  10562.         }
  10563. #else /* TCPIPLIB */
  10564.         if ((count = write(httpfd,s,n)) < 0) {
  10565.             debug(F101,"http_tol socket_write error","",errno);
  10566.             return(-1);                 /* Call it an i/o error */
  10567.         }
  10568. #endif /* TCPIPLIB */
  10569.         if (count < n) {
  10570.             debug(F111,"http_tol socket_write",s,count);
  10571.             if (try > 25) {
  10572.                 /* don't try more than 25 times */
  10573.                 debug(F100,"http_tol tried more than 25 times","",0);
  10574.                 return(-1);
  10575.             }
  10576.             if (count > 0) {
  10577.                 s += count;
  10578.                 n -= count;
  10579.             }
  10580.             debug(F111,"http_tol retry",s,n);
  10581.             goto http_tol_retry;
  10582.         } else {
  10583.             debug(F111,"http_tol socket_write",s,count);
  10584.             return(len); /* success - return total length */
  10585.         }
  10586.     }
  10587. }
  10588.  
  10589.  
  10590. int
  10591. http_inc(timo) int timo; {
  10592.     int x=-1; unsigned char c;             /* The locals. */
  10593.  
  10594.     if (httpfd == -1) {
  10595.         debug(F100,"http_inc socket is closed","",0);
  10596.         return(-2);
  10597.     }
  10598.  
  10599. #ifdef CK_SSL
  10600.     /*
  10601.      * In the case of OpenSSL, it is possible that there is still
  10602.      * data waiting in the SSL session buffers that has not yet
  10603.      * been read by Kermit.  If this is the case we must process
  10604.      * it without calling select() because select() will not return
  10605.      * with an indication that there is data to be read from the
  10606.      * socket.  If there is no data pending in the SSL session
  10607.      * buffers then fall through to the select() code and wait for
  10608.      * some data to arrive.
  10609.      */
  10610.     if (tls_http_active_flag) {
  10611.         int error;
  10612.  
  10613.         x = SSL_pending(tls_http_con);
  10614.         if (x < 0) {
  10615.             debug(F111,"http_inc","SSL_pending error",x);
  10616.             http_close();
  10617.             return(-1);
  10618.         } else if ( x > 0 ) {
  10619.             x = SSL_read(tls_http_con, &c, 1);
  10620.             error = SSL_get_error(tls_http_con,x);
  10621.             switch (error) {
  10622.             case SSL_ERROR_NONE:
  10623.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  10624.                 if (x > 0) {
  10625. #ifdef OS2
  10626.                     ReleaseTCPIPMutex();
  10627. #endif /* OS2 */
  10628.                     return(c);          /* Return character. */
  10629.                 } else if (x < 0) {
  10630. #ifdef OS2
  10631.                     ReleaseTCPIPMutex();
  10632. #endif /* OS2 */
  10633.                     return(-1);
  10634.                 } else {
  10635.                     http_close();
  10636. #ifdef OS2
  10637.                     ReleaseTCPIPMutex();
  10638. #endif /* OS2 */
  10639.                     return(-2);
  10640.                 }
  10641.             case SSL_ERROR_WANT_WRITE:
  10642.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  10643. #ifdef OS2
  10644.                 ReleaseTCPIPMutex();
  10645. #endif /* OS2 */
  10646.                 return(-1);
  10647.             case SSL_ERROR_WANT_READ:
  10648.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  10649. #ifdef OS2
  10650.                 ReleaseTCPIPMutex();
  10651. #endif /* OS2 */
  10652.                 return(-1);
  10653.             case SSL_ERROR_SYSCALL:
  10654.                 if ( x == 0 ) { /* EOF */
  10655.                     http_close();
  10656. #ifdef OS2
  10657.                     ReleaseTCPIPMutex();
  10658. #endif /* OS2 */
  10659.                     return(-2);
  10660.                 } else {
  10661. #ifdef NT
  10662.                     int gle = GetLastError();
  10663.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  10664.                            "GetLastError()",gle);
  10665. #endif /* NT */
  10666. #ifdef OS2
  10667.                     ReleaseTCPIPMutex();
  10668. #endif /* OS2 */
  10669.                     return(-1);
  10670.                 }
  10671.             case SSL_ERROR_WANT_X509_LOOKUP:
  10672.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  10673.                 http_close();
  10674. #ifdef OS2
  10675.                 ReleaseTCPIPMutex();
  10676. #endif /* OS2 */
  10677.                 return(-2);
  10678.             case SSL_ERROR_SSL:
  10679.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  10680. #ifdef COMMENT
  10681.                 http_close();
  10682. #endif /* COMMENT */
  10683. #ifdef OS2
  10684.                 ReleaseTCPIPMutex();
  10685. #endif /* OS2 */
  10686.                 return(-2);
  10687.             case SSL_ERROR_ZERO_RETURN:
  10688.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  10689.                 http_close();
  10690. #ifdef OS2
  10691.                 ReleaseTCPIPMutex();
  10692. #endif /* OS2 */
  10693.                 return(-2);
  10694.             default:
  10695.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  10696.                 http_close();
  10697. #ifdef OS2
  10698.                 ReleaseTCPIPMutex();
  10699. #endif /* OS2 */
  10700.                 return(-2);
  10701.             }
  10702.         }
  10703.     }
  10704. #endif /* CK_SSL */
  10705.     {
  10706. #ifdef BSDSELECT
  10707.         fd_set rfds;
  10708.         struct timeval tv;
  10709.         int timeout = timo < 0 ? -timo : 1000 * timo;
  10710.         debug(F101,"http_inc BSDSELECT","",timo);
  10711.  
  10712.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  10713.             int rc;
  10714.             debug(F111,"http_inc","timeout",timeout);
  10715.             /* Don't move select() initialization out of the loop. */
  10716.             FD_ZERO(&rfds);
  10717.             FD_SET(httpfd, &rfds);
  10718.             tv.tv_sec  = tv.tv_usec = 0L;
  10719.             if (timo)
  10720.                 tv.tv_usec = (long) 100000L;
  10721.             else
  10722.                 tv.tv_sec = 30;
  10723. #ifdef NT
  10724.             WSASafeToCancel = 1;
  10725. #endif /* NT */
  10726.             rc = select(FD_SETSIZE,
  10727. #ifndef __DECC
  10728.                          (fd_set *)
  10729. #endif /* __DECC */
  10730.                          &rfds, NULL, NULL, &tv);
  10731.             if (rc < 0) {
  10732.                 int s_errno = socket_errno;
  10733.                 debug(F111,"http_inc","select",rc);
  10734.                 debug(F111,"http_inc","socket_errno",s_errno);
  10735.                 if (s_errno)
  10736.                     return(-1);
  10737.             }
  10738.             debug(F111,"http_inc","select",rc);
  10739. #ifdef NT
  10740.             WSASafeToCancel = 0;
  10741. #endif /* NT */
  10742.             if (FD_ISSET(httpfd, &rfds)) {
  10743.                 x = 0;
  10744.                 break;
  10745.             } else {
  10746.                 /* If waiting forever we have no way of knowing if the */
  10747.                 /* socket closed so try writing a 0-length TCP packet  */
  10748.                 /* which should force an error if the socket is closed */
  10749.                 if (!timo) {
  10750. #ifdef TCPIPLIB
  10751.                     if ((rc = socket_write(httpfd,"",0)) < 0) {
  10752.                         int s_errno = socket_errno;
  10753.                         debug(F101,"http_inc socket_write error","",s_errno);
  10754. #ifdef OS2
  10755.                         if (os2socketerror(s_errno) < 0)
  10756.                             return(-2);
  10757. #endif /* OS2 */
  10758.                         return(-1); /* Call it an i/o error */
  10759.                     }
  10760. #else /* TCPIPLIB */
  10761.                     if ((rc = write(httpfd,"",0)) < 0) {
  10762.                         debug(F101,"http_inc socket_write error","",errno);
  10763.                         return(-1); /* Call it an i/o error */
  10764.                     }
  10765. #endif /* TCPIPLIB */
  10766.                 }
  10767.                 continue;
  10768.             }
  10769.         }
  10770. #ifdef NT
  10771.         WSASafeToCancel = 0;
  10772. #endif /* NT */
  10773. #else /* !BSDSELECT */
  10774. #ifdef IBMSELECT
  10775.  /*
  10776.   Was used by OS/2, currently not used, but might come in handy some day...
  10777.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  10778.   and timeval stuff since this is the only place where it is used.
  10779.  */
  10780.         int socket = httpfd;
  10781.         int timeout = timo < 0 ? -timo : 1000 * timo;
  10782.  
  10783.         debug(F101,"http_inc IBMSELECT","",timo);
  10784.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  10785.             if (select(&socket, 1, 0, 0, 100L) == 1) {
  10786.                 x = 0;
  10787.                 break;
  10788.             }
  10789.         }
  10790. #else /* !IBMSELECT */
  10791.         SELECT is required for this code
  10792. #endif /* IBMSELECT */
  10793. #endif /* BSDSELECT */
  10794.     }
  10795.  
  10796.     if (timo && x < 0) {        /* select() timed out */
  10797.         debug(F100,"http_inc select() timed out","",0);
  10798.         return(-1); /* Call it an i/o error */
  10799.     }
  10800.  
  10801. #ifdef CK_SSL 
  10802.         if ( tls_http_active_flag ) {
  10803.             int error;
  10804.  
  10805.             x = SSL_read(tls_http_con, &c, 1);
  10806.             error = SSL_get_error(tls_http_con,x);
  10807.             switch (error) {
  10808.             case SSL_ERROR_NONE:
  10809.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  10810.                 if (x > 0) {
  10811. #ifdef OS2
  10812.                     ReleaseTCPIPMutex();
  10813. #endif /* OS2 */
  10814.                     return(c);          /* Return character. */
  10815.                 } else if (x < 0) {
  10816. #ifdef OS2
  10817.                     ReleaseTCPIPMutex();
  10818. #endif /* OS2 */
  10819.                     return(-1);
  10820.                 } else {
  10821.                     http_close();
  10822. #ifdef OS2
  10823.                     ReleaseTCPIPMutex();
  10824. #endif /* OS2 */
  10825.                     return(-2);
  10826.                 }
  10827.             case SSL_ERROR_WANT_WRITE:
  10828.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  10829. #ifdef OS2
  10830.                 ReleaseTCPIPMutex();
  10831. #endif /* OS2 */
  10832.                 return(-1);
  10833.             case SSL_ERROR_WANT_READ:
  10834.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  10835. #ifdef OS2
  10836.                 ReleaseTCPIPMutex();
  10837. #endif /* OS2 */
  10838.                 return(-1);
  10839.             case SSL_ERROR_SYSCALL:
  10840.                 if ( x == 0 ) { /* EOF */
  10841.                     http_close();
  10842. #ifdef OS2
  10843.                     ReleaseTCPIPMutex();
  10844. #endif /* OS2 */
  10845.                     return(-2);
  10846.                 } else {
  10847. #ifdef NT
  10848.                     int gle = GetLastError();
  10849.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  10850.                            "GetLastError()",gle);
  10851. #endif /* NT */
  10852. #ifdef OS2
  10853.                     ReleaseTCPIPMutex();
  10854. #endif /* OS2 */
  10855.                     return(-1);
  10856.                 }
  10857.             case SSL_ERROR_WANT_X509_LOOKUP:
  10858.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  10859.                 http_close();
  10860. #ifdef OS2
  10861.                 ReleaseTCPIPMutex();
  10862. #endif /* OS2 */
  10863.                 return(-2);
  10864.             case SSL_ERROR_SSL:
  10865.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  10866. #ifdef COMMENT
  10867.                 http_close();
  10868. #endif /* COMMENT */
  10869. #ifdef OS2
  10870.                 ReleaseTCPIPMutex();
  10871. #endif /* OS2 */
  10872.                 return(-2);
  10873.             case SSL_ERROR_ZERO_RETURN:
  10874.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  10875.                 http_close();
  10876. #ifdef OS2
  10877.                 ReleaseTCPIPMutex();
  10878. #endif /* OS2 */
  10879.                 return(-2);
  10880.             default:
  10881.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  10882.                 http_close();
  10883. #ifdef OS2
  10884.                 ReleaseTCPIPMutex();
  10885. #endif /* OS2 */
  10886.                 return(-2);
  10887.             }
  10888.         }
  10889. #endif /* CK_SSL */
  10890. #ifdef TCPIPLIB
  10891.         x = socket_read(httpfd,&c,1);
  10892. #else
  10893.         x = read(httpfd,&c,1);
  10894. #endif
  10895.  
  10896.         if (x <= 0) {
  10897.             int s_errno = socket_errno;
  10898.             debug(F101,"ttbufr socket_read","",x);
  10899.             debug(F101,"ttbufr socket_errno","",s_errno);
  10900. #ifdef OS2
  10901.             if (x == 0 || os2socketerror(s_errno) < 0) {
  10902.                 http_close();
  10903.                 ReleaseTCPIPMutex();
  10904.                 return(-2);
  10905.             }
  10906.             ReleaseTCPIPMutex();
  10907.             return(-1);
  10908. #else /* OS2 */
  10909.             http_close();                      /* *** *** */
  10910.             return(-2);
  10911. #endif /* OS2 */
  10912.         }
  10913.         return(c);
  10914. }
  10915.  
  10916. void
  10917. #ifdef CK_ANSIC
  10918. http_set_code_reply(char * msg)
  10919. #else
  10920. http_set_code_reply(msg)
  10921.     char * msg;
  10922. #endif /* CK_ANSIC */ 
  10923. {
  10924.     char * p = msg;
  10925.     char buf[16];
  10926.     int i=0;
  10927.  
  10928.     while ( *p != SP && *p != NUL ) {
  10929.         buf[i] = *p;
  10930.         p++;
  10931.         i++;
  10932.     }
  10933.  
  10934.     http_code = atoi(buf);
  10935.  
  10936.     while ( *p == SP )
  10937.         p++;
  10938.  
  10939.     ckstrncpy(http_reply_str,p,HTTPBUFLEN);
  10940. }
  10941.  
  10942. int
  10943. #ifdef CK_ANSIC
  10944. http_get(char * agent, char ** hdrlist, char * user,
  10945.          char * pwd, char array, char * local, char * remote,
  10946.          int stdio)
  10947. #else
  10948. http_get(agent, hdrlist, user, pwd, array, local, remote, stdio)
  10949.     char * agent; char ** hdrlist; char * user;
  10950.     char * pwd; char array; char * local; char * remote;
  10951.     int stdio;
  10952. #endif /* CK_ANSIC */
  10953. {
  10954.     char * request = NULL;
  10955.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  10956.     int    ch;
  10957.     int    http_fnd = 0;
  10958.     char   buf[HTTPBUFLEN], *p;
  10959.     int    nullline;
  10960. #ifdef OS2
  10961.     struct utimbuf u_t;
  10962. #else /* OS2 */
  10963. #ifdef SYSUTIMEH
  10964.     struct utimbuf u_t;
  10965. #else
  10966.     struct utimbuf {
  10967.         time_t atime;
  10968.         time_t mtime;
  10969.     } u_t;
  10970. #endif /* SYSUTIMH */
  10971. #endif /* OS2 */
  10972.     time_t mod_t = 0;
  10973.     time_t srv_t = 0;
  10974.     time_t local_t = 0;
  10975.     char passwd[64];
  10976.     char b64in[128];
  10977.     char b64out[256];
  10978.     char * headers[HTTPHEADCNT];
  10979.     int closecon = 0;
  10980.     int chunked = 0;
  10981.     int zfile = 0;
  10982.     int first = 1;
  10983.  
  10984. #ifdef DEBUG    
  10985.     if (deblog) {
  10986.     debug(F101,"http_get httpfd","",httpfd);
  10987.     debug(F110,"http_agent",agent,0);
  10988.     debug(F110,"http_user",user,0);
  10989.     debug(F110,"http_local",local,0);
  10990.     debug(F110,"http_remote",remote,0);
  10991.     }
  10992. #endif /* DEBUG */
  10993.     if (!remote) remote = "";
  10994.  
  10995.     if (httpfd == -1)
  10996.       return(-1);
  10997.  
  10998.     if (array) {
  10999.         for (i = 0; i < HTTPHEADCNT; i++)
  11000.           headers[i] = NULL;
  11001.     }
  11002.     len = 8;                            /* GET */
  11003.     len += strlen(HTTP_VERSION);
  11004.     len += strlen(remote);
  11005.     len += 16;
  11006.  
  11007.     if (hdrlist) {
  11008.         for (i = 0; hdrlist[i]; i++)
  11009.             len += strlen(hdrlist[i]) + 2;
  11010.     }
  11011.     len += (int) strlen(http_host_port) + 8;
  11012.  
  11013.     if (agent)
  11014.       len += 13 + strlen(agent);
  11015.     if (user) {
  11016.         if (!pwd) {
  11017.             readpass("Password: ",passwd,64);
  11018.             pwd = passwd;
  11019.         }
  11020.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11021.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11022.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11023.         if (j < 0)
  11024.           return(-1);
  11025.         b64out[j] = '\0';
  11026.         len += j + 24;
  11027.     }
  11028. #ifdef HTTP_CLOSE
  11029.     len += 19;                          /* Connection: close */
  11030. #endif
  11031.     len += 3;                           /* blank line + null */
  11032.  
  11033.     request = malloc(len);
  11034.     if (!request)
  11035.       return(-1);
  11036.  
  11037.     sprintf(request,"GET %s %s\r\n",remote,HTTP_VERSION);       /* safe */
  11038.     ckstrncat(request,"Host: ", len);
  11039.     ckstrncat(request,http_host_port, len);
  11040.     ckstrncat(request,"\r\n",len);
  11041.     if (agent) {
  11042.     ckstrncat(request,"User-agent: ",len);
  11043.         ckstrncat(request,agent,len);
  11044.         ckstrncat(request,"\r\n",len);
  11045.     }
  11046.     if (user) {
  11047.         ckstrncat(request,"Authorization: Basic ",len);
  11048.         ckstrncat(request,b64out,len);
  11049.         ckstrncat(request,"\r\n",len);
  11050.     }
  11051.     if ( hdrlist ) {
  11052.         for (i = 0; hdrlist[i]; i++) {
  11053.             ckstrncat(request,hdrlist[i],len);
  11054.             ckstrncat(request,"\r\n",len);
  11055.         }
  11056.     }
  11057. #ifdef HTTP_CLOSE
  11058.     ckstrncat(request,"Connection: close\r\n",len);
  11059. #endif
  11060.     ckstrncat(request,"\r\n",len);
  11061.  
  11062.   getreq:
  11063.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11064.     {
  11065.         http_close();
  11066.         if ( first ) {
  11067.             first--;
  11068.             http_reopen();
  11069.             goto getreq;
  11070.         }
  11071.         rc = -1;
  11072.         goto getexit;
  11073.     }
  11074.  
  11075.     /* Process the headers */
  11076.     local_t = time(NULL);
  11077.     nullline = 0;
  11078.     i = 0;
  11079.     len = -1;
  11080.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11081.         buf[i] = ch;
  11082.         if ( buf[i] == 10 ) { /* found end of line */
  11083.         if (i > 0 && buf[i-1] == 13)
  11084.           i--;
  11085.             if (i < 1)
  11086.               nullline = 1;
  11087.             buf[i] = '\0';
  11088.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11089.               makestr(&headers[hdcnt++],buf);
  11090.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11091.         http_fnd = 1;
  11092.                 j = ckindex(" ",buf,0,0,0);
  11093.                 p = &buf[j];
  11094.                 while ( isspace(*p) )
  11095.           p++;
  11096.                 switch ( p[0] ) {
  11097.           case '1':        /* Informational message */
  11098.                     break;
  11099.           case '2':        /* Success */
  11100.                     break;
  11101.           case '3':        /* Redirection */
  11102.           case '4':        /* Client failure */
  11103.           case '5':        /* Server failure */
  11104.           default:        /* Unknown */
  11105.             if (!quiet)
  11106.               printf("Failure: Server reports %s\n",p);
  11107.                     rc = -1;
  11108.                     local = NULL;
  11109.                 }
  11110.                 http_set_code_reply(p);
  11111. #ifdef CMDATE2TM
  11112.             } else if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11113.                 mod_t = http_date(&buf[15]);
  11114.             } else if (!ckstrcmp(buf,"Date",4,0)) {
  11115.                 srv_t = http_date(&buf[4]);
  11116. #endif /* CMDATE2TM */
  11117.             } else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11118.                 if ( ckindex("close",buf,11,0,0) != 0 )
  11119.                     closecon = 1;
  11120.             } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11121.                 len = atoi(&buf[16]);
  11122.             } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11123.                 if ( ckindex("chunked",buf,18,0,0) != 0 )
  11124.                     chunked = 1;
  11125.             }
  11126.             i = 0;
  11127.         } else {
  11128.             i++;
  11129.         }
  11130.     }
  11131.     if (ch < 0 && first) {
  11132.         first--;
  11133.         http_close();
  11134.         http_reopen();
  11135.         goto getreq;
  11136.     }
  11137.     if (http_fnd == 0) {
  11138.     rc = -1;
  11139.         closecon = 1;
  11140.         goto getexit;
  11141.     }
  11142.  
  11143.     /* Now we have the contents of the file */
  11144.     if ( local && local[0] ) {
  11145.         if (zopeno(ZOFILE,local,NULL,NULL)) 
  11146.             zfile = 1;
  11147.         else
  11148.             rc = -1;
  11149.     }
  11150.  
  11151.     if ( chunked ) {
  11152.         while ((len = http_get_chunk_len()) > 0) {
  11153.             while (len && (ch = http_inc(0)) >= 0) {
  11154.                 len--;
  11155.                 if ( zfile )
  11156.                     zchout(ZOFILE,(CHAR)ch);
  11157.                 if ( stdio )
  11158.                     conoc((CHAR)ch);
  11159.             }
  11160.             if ((ch = http_inc(0)) != CR)
  11161.                 break;
  11162.             if ((ch = http_inc(0)) != LF)
  11163.                 break;
  11164.         }
  11165.     } else {
  11166.         while (len && (ch = http_inc(0)) >= 0) {
  11167.             len--;
  11168.             if ( zfile )
  11169.                 zchout(ZOFILE,(CHAR)ch);
  11170.             if ( stdio )
  11171.                 conoc((CHAR)ch);
  11172.         }
  11173.     }
  11174.  
  11175.     if ( zfile )
  11176.         zclose(ZOFILE);
  11177.  
  11178.     if ( chunked ) {            /* Parse Trailing Headers */
  11179.         nullline = 0;
  11180.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11181.             buf[i] = ch;
  11182.             if ( buf[i] == 10 ) { /* found end of line */
  11183.         if (i > 0 && buf[i-1] == 13)
  11184.           i--;
  11185.                 if (i < 1)
  11186.           nullline = 1;
  11187.                 buf[i] = '\0';
  11188.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11189.                     makestr(&headers[hdcnt++],buf);
  11190. #ifdef CMDATE2TM
  11191.                 if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11192.                     mod_t = http_date(&buf[15]);
  11193.                 } else if (!ckstrcmp(buf,"Date",4,0)) {
  11194.                     srv_t = http_date(&buf[4]);
  11195.                 }
  11196. #endif /* CMDATE2TM */
  11197.                 else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11198.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11199.                         closecon = 1;
  11200.                 }
  11201.                 i = 0;
  11202.             } else {
  11203.                 i++;
  11204.             }
  11205.         }
  11206.     }
  11207.  
  11208.     if ( zfile ) {              /* Set timestamp */
  11209. #ifdef CMDATE2TM
  11210. #ifdef OS2
  11211.         u_t.actime = srv_t ? srv_t : local_t;
  11212.         u_t.modtime = mod_t ? mod_t : local_t;
  11213. #else /* OS2 */
  11214. #ifdef SYSUTIMEH
  11215.         u_t.actime = srv_t ? srv_t : local_t;
  11216.         u_t.modtime = mod_t ? mod_t : local_t;
  11217. #else
  11218. #ifdef BSD44
  11219.         u_t[0].tv_sec = srv_t ? srv_t : local_t;
  11220.         u_t[1].tv_sec = mod_t ? mod_t : local_t;
  11221. #else
  11222.         u_t.mtime = srv_t ? srv_t : local_t;
  11223.         u_t.atime = mod_t ? mod_t : local_t;
  11224. #endif /* BSD44 */
  11225. #endif /* SYSUTIMEH */
  11226. #endif /* OS2 */
  11227.             utime(local,&u_t);
  11228. #endif /* CMDATE2TM */
  11229.     }
  11230.  
  11231.   getexit:
  11232.     if (array)
  11233.       http_mkarray(headers,hdcnt,array);
  11234.  
  11235.     if ( closecon )
  11236.         http_close();
  11237.     free(request);
  11238.     for (i = 0; i < hdcnt; i++) {
  11239.         if (headers[i])
  11240.           free(headers[i]);
  11241.     }
  11242.     return(rc);
  11243. }
  11244.  
  11245. int
  11246. #ifdef CK_ANSIC
  11247. http_head(char * agent, char ** hdrlist, char * user,
  11248.           char * pwd, char array, char * local, char * remote,
  11249.           int stdio)
  11250. #else
  11251. http_head(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11252.     char * agent; char ** hdrlist; char * user;
  11253.     char * pwd; char array; char * local; char * remote;
  11254.     int stdio;
  11255. #endif /* CK_ANSIC */
  11256. {
  11257.     char * request = NULL;
  11258.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11259.     int    ch;
  11260.     int    http_fnd = 0;
  11261.     char   buf[HTTPBUFLEN], *p;
  11262.     int    nullline;
  11263.     time_t mod_t;
  11264.     time_t srv_t;
  11265.     time_t local_t;
  11266.     char passwd[64];
  11267.     char b64in[128];
  11268.     char b64out[256];
  11269.     char * headers[HTTPHEADCNT];
  11270.     int  closecon = 0;
  11271.     int  first = 1;
  11272.  
  11273.     if (httpfd == -1)
  11274.       return(-1);
  11275.  
  11276.     if (array) {
  11277.         for (i = 0; i < HTTPHEADCNT; i++)
  11278.           headers[i] = NULL;
  11279.     }
  11280.     len = 9;                            /* HEAD */
  11281.     len += strlen(HTTP_VERSION);
  11282.     len += strlen(remote);
  11283.     len += 16;
  11284.  
  11285.     if ( hdrlist ) {
  11286.         for (i = 0; hdrlist[i]; i++)
  11287.             len += strlen(hdrlist[i]) + 2;
  11288.     }
  11289.     len += strlen(http_host_port) + 8;
  11290.  
  11291.     if (agent)
  11292.       len += 13 + strlen(agent);
  11293.     if (user) {
  11294.         if (!pwd) {
  11295.             readpass("Password: ",passwd,64);
  11296.             pwd = passwd;
  11297.         }
  11298.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11299.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11300.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11301.         if (j < 0)
  11302.           return(-1);
  11303.         b64out[j] = '\0';
  11304.         len += j + 24;
  11305.     }
  11306. #ifdef HTTP_CLOSE
  11307.     len += 19;                          /* Connection: close */
  11308. #endif
  11309.     len += 3;                           /* blank line + null */
  11310.  
  11311.     request = (char *)malloc(len);
  11312.     if (!request)
  11313.       return(-1);
  11314.  
  11315.     sprintf(request,"HEAD %s %s\r\n",remote,HTTP_VERSION);
  11316.     ckstrncat(request,"Host: ", len);
  11317.     ckstrncat(request,http_host_port, len);
  11318.     ckstrncat(request,"\r\n",len);
  11319.     if (agent) {
  11320.         ckstrncat(request,"User-agent: ",len);
  11321.         ckstrncat(request,agent,len);
  11322.         ckstrncat(request,"\r\n",len);
  11323.     }
  11324.     if (user) {
  11325.         ckstrncat(request,"Authorization: Basic ",len);
  11326.         ckstrncat(request,b64out,len);
  11327.         ckstrncat(request,"\r\n",len);
  11328.     }
  11329.     if ( hdrlist ) {
  11330.         for (i = 0; hdrlist[i]; i++) {
  11331.             ckstrncat(request,hdrlist[i],len);
  11332.             ckstrncat(request,"\r\n",len);
  11333.         }
  11334.     }
  11335. #ifdef HTTP_CLOSE
  11336.     ckstrncat(request,"Connection: close\r\n",len);
  11337. #endif
  11338.     ckstrncat(request,"\r\n",len);
  11339.  
  11340.     if ( local && local[0] ) {
  11341.     if (!zopeno(ZOFILE,local,NULL,NULL)) {
  11342.         free(request);
  11343.         return(-1);
  11344.     }
  11345.     }
  11346.  
  11347.   headreq:
  11348.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11349.     {
  11350.         http_close();
  11351.         if ( first ) {
  11352.             first--;
  11353.             http_reopen();
  11354.             goto headreq;
  11355.         }
  11356.         rc = -1;
  11357.         goto headexit;
  11358.     }
  11359.  
  11360.     /* Process the headers */
  11361.  
  11362.     local_t = time(NULL);
  11363.     nullline = 0;
  11364.     i = 0;
  11365.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11366.         buf[i] = ch;
  11367.         if (buf[i] == 10) {             /* found end of line */
  11368.         if (i > 0 && buf[i-1] == 13)
  11369.           i--;
  11370.             if (i < 1)
  11371.               nullline = 1;
  11372.             buf[i] = '\0';
  11373.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11374.               makestr(&headers[hdcnt++],buf);
  11375.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11376.         http_fnd = 1;
  11377.                 j = ckindex(" ",buf,0,0,0);
  11378.                 p = &buf[j];
  11379.                 while (isspace(*p))
  11380.           p++;
  11381.                 switch (p[0]) {
  11382.           case '1':        /* Informational message */
  11383.                     break;
  11384.           case '2':        /* Success */
  11385.                     break;
  11386.           case '3':        /* Redirection */
  11387.           case '4':        /* Client failure */
  11388.           case '5':        /* Server failure */
  11389.           default:        /* Unknown */
  11390.             if (!quiet)
  11391.               printf("Failure: Server reports %s\n",p);
  11392.                     rc = -1;
  11393.                 }
  11394.                 http_set_code_reply(p);
  11395.             } else {
  11396.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11397.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11398.                         closecon = 1;
  11399.                 }
  11400.         if ( local && local[0] ) {
  11401.             zsout(ZOFILE,buf);
  11402.                     zsout(ZOFILE,"\r\n");
  11403.         }
  11404.                 if (stdio)
  11405.             printf("%s\r\n",buf);
  11406.             }
  11407.             i = 0;
  11408.         } else {
  11409.             i++;
  11410.         }
  11411.     }
  11412.     if (ch < 0 && first) {
  11413.         first--;
  11414.         http_close();
  11415.         http_reopen();
  11416.         goto headreq;
  11417.     }
  11418.     if ( http_fnd == 0 )
  11419.     rc = -1;
  11420.  
  11421.     if (array)
  11422.       http_mkarray(headers,hdcnt,array);
  11423.  
  11424.   headexit:
  11425.     if ( local && local[0] )
  11426.     zclose(ZOFILE);
  11427.     if (closecon)
  11428.         http_close();
  11429.     free(request);
  11430.     for (i = 0; i < hdcnt; i++) {
  11431.         if (headers[i])
  11432.           free(headers[i]);
  11433.     }
  11434.     return(rc);
  11435. }
  11436.  
  11437. int
  11438. #ifdef CK_ANSIC
  11439. http_index(char * agent, char ** hdrlist, char * user, char * pwd,
  11440.              char array, char * local, char * remote, int stdio)
  11441. #else
  11442. http_index(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11443.     char * agent; char ** hdrlist; char * user; char * pwd;
  11444.     char array; char * local; char * remote; int stdio;
  11445. #endif /* CK_ANSIC */
  11446. {
  11447.     char * request = NULL;
  11448.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11449.     int    ch;
  11450.     int    http_fnd = 0;
  11451.     char   buf[HTTPBUFLEN], *p;
  11452.     int    nullline;
  11453.     time_t mod_t;
  11454.     time_t srv_t;
  11455.     time_t local_t;
  11456.     char passwd[64];
  11457.     char b64in[128];
  11458.     char b64out[256];
  11459.     char * headers[HTTPHEADCNT];
  11460.     int  closecon = 0;
  11461.     int  chunked = 0;
  11462.     int  zfile = 0;
  11463.     int  first = 1;
  11464.  
  11465.     if (httpfd == -1)
  11466.       return(-1);
  11467.  
  11468.     if (array) {
  11469.         for (i = 0; i < HTTPHEADCNT; i++)
  11470.           headers[i] = NULL;
  11471.     }
  11472.     len = 10;                            /* INDEX */
  11473.     len += strlen(HTTP_VERSION);
  11474.     len += strlen(remote);
  11475.     len += 16;
  11476.  
  11477.     if ( hdrlist ) {
  11478.         for (i = 0; hdrlist[i]; i++)
  11479.             len += strlen(hdrlist[i]) + 2;
  11480.     }
  11481.     len += strlen(http_host_port) + 8;
  11482.  
  11483.     if (agent)
  11484.         len += 13 + strlen(agent);
  11485.     if (user) {
  11486.         if (!pwd) {
  11487.             readpass("Password: ",passwd,64);
  11488.             pwd = passwd;
  11489.         }
  11490.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11491.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11492.         memset(pwd,0,strlen(pwd));
  11493.         if (j < 0)
  11494.           return(-1);
  11495.         b64out[j] = '\0';
  11496.         len += j + 24;
  11497.     }
  11498. #ifdef HTTP_CLOSE
  11499.     len += 19;                          /* Connection: close */
  11500. #endif
  11501.     len += 3;                           /* blank line + null */
  11502.  
  11503.     request = malloc(len);
  11504.     if (!request)
  11505.       return(-1);
  11506.  
  11507.     sprintf(request,"INDEX %s\r\n",HTTP_VERSION);
  11508.     ckstrncat(request,"Host: ", len);
  11509.     ckstrncat(request,http_host_port, len);
  11510.     ckstrncat(request,"\r\n",len);
  11511.     if (agent) {
  11512.         ckstrncat(request,"User-agent: ",len);
  11513.         ckstrncat(request,agent,len);
  11514.         ckstrncat(request,"\r\n",len);
  11515.     }
  11516.     if (user) {
  11517.         ckstrncat(request,"Authorization: Basic ",len);
  11518.         ckstrncat(request,b64out,len);
  11519.         ckstrncat(request,"\r\n",len);
  11520.     }
  11521.     if ( hdrlist ) {
  11522.         for (i = 0; hdrlist[i]; i++) {
  11523.             ckstrncat(request,hdrlist[i],len);
  11524.             ckstrncat(request,"\r\n",len);
  11525.         }
  11526.     }
  11527. #ifdef HTTP_CLOSE
  11528.     ckstrncat(request,"Connection: close\r\n",len);
  11529. #endif
  11530.     ckstrncat(request,"\r\n",len);
  11531.   indexreq:
  11532.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11533.     {
  11534.         http_close();
  11535.         if ( first ) {
  11536.             first--;
  11537.             http_reopen();
  11538.             goto indexreq;
  11539.         }
  11540.         rc = -1;
  11541.         goto indexexit;
  11542.     }
  11543.  
  11544.     /* Process the headers */
  11545.     local_t = time(NULL);
  11546.     nullline = 0;
  11547.     i = 0;
  11548.     len = -1;
  11549.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11550.         buf[i] = ch;
  11551.         if (buf[i] == 10) {             /* found end of line */
  11552.         if (i > 0 && buf[i-1] == 13)
  11553.           i--;
  11554.             if (i < 1)
  11555.               nullline = 1;
  11556.             buf[i] = '\0';
  11557.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11558.               makestr(&headers[hdcnt++],buf);
  11559.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11560.         http_fnd = 1;
  11561.                 j = ckindex(" ",buf,0,0,0);
  11562.                 p = &buf[j];
  11563.                 while (isspace(*p))
  11564.           p++;
  11565.                 switch ( p[0] ) {
  11566.           case '1':        /* Informational message */
  11567.                     break;
  11568.           case '2':        /* Success */
  11569.                     break;
  11570.           case '3':        /* Redirection */
  11571.           case '4':        /* Client failure */
  11572.           case '5':        /* Server failure */
  11573.           default:        /* Unknown */
  11574.             if (!quiet)
  11575.               printf("Failure: Server reports %s\n",p);
  11576.                     rc = -1;
  11577.                 }
  11578.                 http_set_code_reply(p);
  11579.             } else if ( !nullline ) {
  11580.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11581.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11582.                         closecon = 1;
  11583.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11584.                     len = atoi(&buf[16]);
  11585.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11586.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  11587.                         chunked = 1;
  11588.                 }
  11589.                 printf("%s\n",buf);
  11590.             }
  11591.             i = 0;
  11592.         } else {
  11593.             i++;
  11594.         }
  11595.     }
  11596.  
  11597.     if (ch < 0 && first) {
  11598.         first--;
  11599.         http_close();
  11600.         http_reopen();
  11601.         goto indexreq;
  11602.     }
  11603.     if ( http_fnd == 0 ) {
  11604.     rc = -1;
  11605.         closecon = 1;
  11606.     goto indexexit;
  11607.     }
  11608.     
  11609.     /* Now we have the contents of the file */
  11610.     if ( local && local[0] ) {
  11611.         if (zopeno(ZOFILE,local,NULL,NULL))
  11612.             zfile = 1;
  11613.         else 
  11614.             rc = -1;
  11615.     }
  11616.  
  11617.     if ( chunked ) {
  11618.         while ((len = http_get_chunk_len()) > 0) {
  11619.             while (len && (ch = http_inc(0)) >= 0) {
  11620.                 len--;
  11621.                 if ( zfile )
  11622.                     zchout(ZOFILE,(CHAR)ch);
  11623.                 if ( stdio )
  11624.                     conoc((CHAR)ch);
  11625.             }
  11626.             if ((ch = http_inc(0)) != CR)
  11627.                 break;
  11628.             if ((ch = http_inc(0)) != LF)
  11629.                 break;
  11630.         }
  11631.     } else {
  11632.         while (len && (ch = http_inc(0)) >= 0) {
  11633.             len--;
  11634.             if ( zfile )
  11635.                 zchout(ZOFILE,(CHAR)ch);
  11636.             if ( stdio )
  11637.                 conoc((CHAR)ch);
  11638.         }
  11639.     }
  11640.  
  11641.     if ( zfile )
  11642.         zclose(ZOFILE);
  11643.  
  11644.     if ( chunked ) {            /* Parse Trailing Headers */
  11645.         nullline = 0;
  11646.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11647.             buf[i] = ch;
  11648.             if ( buf[i] == 10 ) { /* found end of line */
  11649.         if (i > 0 && buf[i-1] == 13)
  11650.           i--;
  11651.                 if (i < 1)
  11652.           nullline = 1;
  11653.                 buf[i] = '\0';
  11654.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11655.                     makestr(&headers[hdcnt++],buf);
  11656.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11657.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11658.                         closecon = 1;
  11659.                 }
  11660.                 i = 0;
  11661.             } else {
  11662.                 i++;
  11663.             }
  11664.         }
  11665.     }
  11666.     rc = 0;
  11667.  
  11668.   indexexit:
  11669.     if (array)
  11670.       http_mkarray(headers,hdcnt,array);
  11671.  
  11672.     if (closecon)
  11673.         http_close();
  11674.     free(request);
  11675.     for (i = 0; i < hdcnt; i++) {
  11676.         if (headers[i])
  11677.           free(headers[i]);
  11678.     }
  11679.     return(rc);
  11680. }
  11681.  
  11682. int
  11683. #ifdef CK_ANSIC
  11684. http_put(char * agent, char ** hdrlist, char * mime, char * user,
  11685.          char * pwd, char array, char * local, char * remote,
  11686.          char * dest, int stdio)
  11687. #else
  11688. http_put(agent, hdrlist, mime, user, pwd, array, local, remote, dest, stdio)
  11689.     char * agent; char ** hdrlist; char * mime; char * user;
  11690.     char * pwd; char array; char * local; char * remote; char * dest;
  11691.     int stdio;
  11692. #endif /* CK_ANSIC */
  11693. {
  11694.     char * request=NULL;
  11695.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11696.     int    ch;
  11697.     int    http_fnd = 0;
  11698.     char   buf[HTTPBUFLEN], *p;
  11699.     int    nullline;
  11700.     time_t mod_t;
  11701.     time_t srv_t;
  11702.     time_t local_t;
  11703.     char passwd[64];
  11704.     char b64in[128];
  11705.     char b64out[256];
  11706.     int  filelen;
  11707.     char * headers[HTTPHEADCNT];
  11708.     int  closecon = 0;
  11709.     int  chunked = 0;
  11710.     int  first = 1;
  11711.     int  zfile = 0;
  11712.  
  11713.     if (httpfd == -1)
  11714.       return(-1);
  11715.     if (!mime) mime = "";
  11716.     if (!remote) remote = "";
  11717.     if (!local) local = "";
  11718.     if (!*local) return(-1);
  11719.  
  11720.     if (array) {
  11721.         for (i = 0; i < HTTPHEADCNT; i++)
  11722.           headers[i] = NULL;
  11723.     }
  11724.     filelen = zchki(local);
  11725.     if (filelen < 0)
  11726.       return(-1);
  11727.  
  11728.     /* Compute length of request header */
  11729.     len = 8;                            /* PUT */
  11730.     len += strlen(HTTP_VERSION);
  11731.     len += strlen(remote);
  11732.     len += 16;
  11733.  
  11734.     if ( hdrlist ) {
  11735.         for (i = 0; hdrlist[i]; i++)
  11736.             len += strlen(hdrlist[i]) + 2;
  11737.     }
  11738.     len += strlen(http_host_port) + 8;
  11739.  
  11740.     if (agent)
  11741.       len += 13 + strlen(agent);
  11742.     if (user) {
  11743.         if (!pwd) {
  11744.             readpass("Password: ",passwd,64);
  11745.             pwd = passwd;
  11746.         }
  11747.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11748.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11749.         memset(pwd,0,strlen(pwd));
  11750.         if (j < 0)
  11751.           return(-1);
  11752.         b64out[j] = '\0';
  11753.         len += j + 24;
  11754.     }
  11755.     len += 16 + strlen(mime);           /* Content-type: */
  11756.     len += 32;                          /* Content-length: */
  11757.     len += 32;                          /* Date: */
  11758. #ifdef HTTP_CLOSE
  11759.     len += 19;                          /* Connection: close */
  11760. #endif
  11761.     len += 3;                           /* blank line + null */
  11762.  
  11763.     request = malloc(len);
  11764.     if (!request)
  11765.       return(-1);
  11766.  
  11767.     sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
  11768.     ckstrncat(request,"Date: ",len);
  11769. #ifdef CMDATE2TM
  11770.     ckstrncat(request,http_now(),len);
  11771. #else
  11772.     strcat(request,...);
  11773. #endif /* CMDATE2TM */
  11774.     ckstrncat(request,"\r\n",len);
  11775.     ckstrncat(request,"Host: ", len);
  11776.     ckstrncat(request,http_host_port, len);
  11777.     ckstrncat(request,"\r\n",len);
  11778.     if (agent) {
  11779.         ckstrncat(request,"User-agent: ",len);
  11780.         ckstrncat(request,agent,len);
  11781.         ckstrncat(request,"\r\n",len);
  11782.     }
  11783.     if (user) {
  11784.         ckstrncat(request,"Authorization: Basic ",len);
  11785.         ckstrncat(request,b64out,len);
  11786.         ckstrncat(request,"\r\n",len);
  11787.     }
  11788.     if ( hdrlist ) {
  11789.         for (i = 0; hdrlist[i]; i++) {
  11790.             ckstrncat(request,hdrlist[i],len);
  11791.             ckstrncat(request,"\r\n",len);
  11792.         }
  11793.     }
  11794.     ckstrncat(request,"Content-type: ",len);
  11795.     ckstrncat(request,mime,len);
  11796.     ckstrncat(request,"\r\n",len);
  11797.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  11798.     ckstrncat(request,buf,len);
  11799. #ifdef HTTP_CLOSE
  11800.     ckstrncat(request,"Connection: close\r\n",len);
  11801. #endif
  11802.     ckstrncat(request,"\r\n",len);
  11803.  
  11804.     /* Now we have the contents of the file */
  11805.     if (zopeni(ZIFILE,local)) {
  11806.  
  11807.       putreq:
  11808.         if (http_tol((CHAR *)request,strlen(request)) <= 0) { /* Send request */
  11809.             http_close();
  11810.             if ( first ) {
  11811.                 first--;
  11812.                 http_reopen();
  11813.                 goto putreq;
  11814.             }
  11815.             zclose(ZIFILE);
  11816.             rc = -1;
  11817.             goto putexit;
  11818.         }
  11819.         /* Request headers have been sent */
  11820.  
  11821.         i = 0;
  11822.         while (zchin(ZIFILE,&ch) == 0) {
  11823.             buf[i++] = ch;
  11824.             if (i == HTTPBUFLEN) {
  11825.                 if (http_tol((CHAR *)buf,HTTPBUFLEN) <= 0) {
  11826.                     http_close();
  11827.                     if ( first ) {
  11828.                         first--;
  11829.                         http_reopen();
  11830.                         goto putreq;
  11831.                     }
  11832.                 }
  11833.                 i = 0;
  11834.             }
  11835.         }
  11836.         if (i > 0) {
  11837.             if (http_tol((CHAR *)buf,i) < 0) {
  11838.                 http_close();
  11839.                 if ( first ) {
  11840.                     first--;
  11841.                     http_reopen();
  11842.                     goto putreq;
  11843.                 }
  11844.             }
  11845.         }
  11846.         zclose(ZIFILE);
  11847.  
  11848.         /* Process the response headers */
  11849.         local_t = time(NULL);
  11850.         nullline = 0;
  11851.         i = 0;
  11852.         len = -1;
  11853.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11854.             buf[i] = ch;
  11855.             if (buf[i] == 10) {         /* found end of line */
  11856.         if (i > 0 && buf[i-1] == 13)
  11857.           i--;
  11858.                 if (i < 1)
  11859.                   nullline = 1;
  11860.                 buf[i] = '\0';
  11861.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11862.                   makestr(&headers[hdcnt++],buf);
  11863.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  11864.             http_fnd = 1;
  11865.                     j = ckindex(" ",buf,0,0,0);
  11866.                     p = &buf[j];
  11867.                     while (isspace(*p))
  11868.               p++;
  11869.                     switch (p[0]) {
  11870.               case '1':        /* Informational message */
  11871.                         break;
  11872.               case '2':        /* Success */
  11873.                         break;
  11874.               case '3':        /* Redirection */
  11875.               case '4':        /* Client failure */
  11876.               case '5':        /* Server failure */
  11877.               default:        /* Unknown */
  11878.             if (!quiet)
  11879.               printf("Failure: Server reports %s\n",p);
  11880.                         rc = -1;
  11881.                     }
  11882.             http_set_code_reply(p);
  11883.                 } else {
  11884.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  11885.                         if ( ckindex("close",buf,11,0,0) != 0 )
  11886.                             closecon = 1;
  11887.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11888.                         len = atoi(&buf[16]);
  11889.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11890.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  11891.                             chunked = 1;
  11892.                     }
  11893.                     if ( stdio )
  11894.                         printf("%s\n",buf);
  11895.                 }
  11896.                 i = 0;
  11897.             } else {
  11898.                 i++;
  11899.             }
  11900.         }
  11901.         if (ch < 0 && first) {
  11902.             first--;
  11903.             http_close();
  11904.             http_reopen();
  11905.             goto putreq;
  11906.         }
  11907.     if ( http_fnd == 0 ) {
  11908.             closecon = 1;
  11909.         rc = -1;
  11910.             goto putexit;
  11911.         }
  11912.  
  11913.         /* Any response data? */
  11914.         if ( dest && dest[0] ) {
  11915.             if (zopeno(ZOFILE,dest,NULL,NULL))
  11916.                 zfile = 1;
  11917.             else 
  11918.                 rc = -1;
  11919.         }
  11920.  
  11921.         if ( chunked ) {
  11922.             while ((len = http_get_chunk_len()) > 0) {
  11923.                 while (len && (ch = http_inc(0)) >= 0) {
  11924.                     len--;
  11925.                     if ( zfile )
  11926.                         zchout(ZOFILE,(CHAR)ch);
  11927.                     if ( stdio )
  11928.                         conoc((CHAR)ch);
  11929.                 }
  11930.                 if ((ch = http_inc(0)) != CR)
  11931.                     break;
  11932.                 if ((ch = http_inc(0)) != LF)
  11933.                     break;
  11934.             }
  11935.         } else {
  11936.             while (len && (ch = http_inc(0)) >= 0) {
  11937.                 len--;
  11938.                 if ( zfile )
  11939.                     zchout(ZOFILE,(CHAR)ch);
  11940.                 if ( stdio )
  11941.                     conoc((CHAR)ch);
  11942.             }
  11943.         }
  11944.  
  11945.         if ( zfile )
  11946.             zclose(ZOFILE);
  11947.  
  11948.         if ( chunked ) {            /* Parse Trailing Headers */
  11949.             nullline = 0;
  11950.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11951.                 buf[i] = ch;
  11952.                 if ( buf[i] == 10 ) { /* found end of line */
  11953.             if (i > 0 && buf[i-1] == 13)
  11954.               i--;
  11955.                     if (i < 1)
  11956.               nullline = 1;
  11957.                     buf[i] = '\0';
  11958.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  11959.                         makestr(&headers[hdcnt++],buf);
  11960.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  11961.                         if ( ckindex("close",buf,11,0,0) != 0 )
  11962.                             closecon = 1;
  11963.                     }
  11964.                     i = 0;
  11965.                 } else {
  11966.                     i++;
  11967.                 }
  11968.             }
  11969.         }
  11970.     } else {
  11971.     rc = -1;
  11972.     }
  11973.  
  11974.   putexit:
  11975.     if ( array )
  11976.         http_mkarray(headers,hdcnt,array);
  11977.  
  11978.     if (closecon)
  11979.         http_close();
  11980.     free(request);
  11981.     for (i = 0; i < hdcnt; i++) {
  11982.         if (headers[i])
  11983.           free(headers[i]);
  11984.     }
  11985.     return(rc);
  11986. }
  11987.  
  11988. int
  11989. #ifdef CK_ANSIC
  11990. http_delete(char * agent, char ** hdrlist, char * user,
  11991.           char * pwd, char array, char * remote)
  11992. #else
  11993. http_delete(agent, hdrlist, user, pwd, array, remote)
  11994.     char * agent; char ** hdrlist; char * user;
  11995.     char * pwd; char array; char * remote;
  11996. #endif /* CK_ANSIC */
  11997. {
  11998.     char * request=NULL;
  11999.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12000.     int    ch;
  12001.     int    http_fnd = 0;
  12002.     char   buf[HTTPBUFLEN], *p;
  12003.     int    nullline;
  12004.     time_t mod_t;
  12005.     time_t srv_t;
  12006.     time_t local_t;
  12007.     char passwd[64];
  12008.     char b64in[128];
  12009.     char b64out[256];
  12010.     char * headers[HTTPHEADCNT];
  12011.     int  closecon = 0;
  12012.     int  chunked = 0;
  12013.     int  first = 1;
  12014.  
  12015.     if (httpfd == -1)
  12016.       return(-1);
  12017.  
  12018.     if (array) {
  12019.         for (i = 0; i < HTTPHEADCNT; i++)
  12020.           headers[i] = NULL;
  12021.     }
  12022.  
  12023.     /* Compute length of request header */
  12024.     len = 11;                            /* DELETE */
  12025.     len += strlen(HTTP_VERSION);
  12026.     len += strlen(remote);
  12027.     len += 16;
  12028.  
  12029.     if ( hdrlist ) {
  12030.         for (i = 0; hdrlist[i]; i++)
  12031.             len += strlen(hdrlist[i]) + 2;
  12032.     }
  12033.     len += strlen(http_host_port) + 8;
  12034.  
  12035.     if (agent)
  12036.       len += 13 + strlen(agent);
  12037.     if (user) {
  12038.         if (!pwd) {
  12039.             readpass("Password: ",passwd,64);
  12040.             pwd = passwd;
  12041.         }
  12042.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12043.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12044.         memset(pwd,0,strlen(pwd));
  12045.         if (j < 0)
  12046.           return(-1);
  12047.         b64out[j] = '\0';
  12048.         len += j + 24;
  12049.     }
  12050.     len += 32;                          /* Date: */
  12051. #ifdef HTTP_CLOSE
  12052.     len += 19;                          /* Connection: close */
  12053. #endif
  12054.     len += 3;                           /* blank line + null */
  12055.  
  12056.     request = malloc(len);
  12057.     if (!request)
  12058.       return(-1);
  12059.  
  12060.     sprintf(request,"DELETE %s %s\r\n",remote,HTTP_VERSION);
  12061.     ckstrncat(request,"Date: ",len);
  12062. #ifdef CMDATE2TM
  12063.     ckstrncat(request,http_now(),len);
  12064. #else
  12065.     strcat(request,...);
  12066. #endif /* CMDATE2TM */
  12067.     ckstrncat(request,"\r\n",len);
  12068.     ckstrncat(request,"Host: ", len);
  12069.     ckstrncat(request,http_host_port, len);
  12070.     ckstrncat(request,"\r\n",len);
  12071.     if (agent) {
  12072.         ckstrncat(request,"User-agent: ",len);
  12073.         ckstrncat(request,agent,len);
  12074.         ckstrncat(request,"\r\n",len);
  12075.     }
  12076.     if (user) {
  12077.         ckstrncat(request,"Authorization: Basic ",len);
  12078.         ckstrncat(request,b64out,len);
  12079.         ckstrncat(request,"\r\n",len);
  12080.     }
  12081.     if ( hdrlist ) {
  12082.         for (i = 0; hdrlist[i]; i++) {
  12083.             ckstrncat(request,hdrlist[i],len);
  12084.             ckstrncat(request,"\r\n",len);
  12085.         }
  12086.     }
  12087. #ifdef HTTP_CLOSE
  12088.     ckstrncat(request,"Connection: close\r\n",len);
  12089. #endif
  12090.     ckstrncat(request,"\r\n",len);
  12091.   delreq:
  12092.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  12093.     {
  12094.         http_close();
  12095.         if ( first ) {
  12096.             first--;
  12097.             http_reopen();
  12098.             goto delreq;
  12099.         }
  12100.         rc = -1;
  12101.         goto delexit;
  12102.     }
  12103.  
  12104.     /* Process the response headers */
  12105.     local_t = time(NULL);
  12106.     nullline = 0;
  12107.     i = 0;
  12108.     len = -1;
  12109.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12110.         buf[i] = ch;
  12111.         if (buf[i] == 10) {         /* found end of line */
  12112.         if (i > 0 && buf[i-1] == 13)
  12113.           i--;
  12114.             if (i < 1)
  12115.           nullline = 1;
  12116.             buf[i] = '\0';
  12117.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12118.                 makestr(&headers[hdcnt++],buf);
  12119.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12120.         http_fnd = 1;
  12121.                 j = ckindex(" ",buf,0,0,0);
  12122.                 p = &buf[j];
  12123.                 while (isspace(*p))
  12124.           p++;
  12125.                 switch (p[0]) {
  12126.           case '1':        /* Informational message */
  12127.                     break;
  12128.           case '2':        /* Success */
  12129.                     break;
  12130.           case '3':        /* Redirection */
  12131.           case '4':        /* Client failure */
  12132.           case '5':        /* Server failure */
  12133.           default:        /* Unknown */
  12134.             if (!quiet)
  12135.               printf("Failure: Server reports %s\n",p);
  12136.                     rc = -1;
  12137.                 }
  12138.                 http_set_code_reply(p);
  12139.             } else {
  12140.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12141.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12142.                         closecon = 1;
  12143.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12144.                     len = atoi(&buf[16]);
  12145.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12146.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  12147.                         chunked = 1;
  12148.                 }
  12149.                 printf("%s\n",buf);
  12150.             }
  12151.             i = 0;
  12152.         } else {
  12153.         i++;
  12154.         }
  12155.     }
  12156.     if (ch < 0 && first) {
  12157.         first--;
  12158.         http_close();
  12159.         http_reopen();
  12160.         goto delreq;
  12161.     }
  12162.     if ( http_fnd == 0 ) {
  12163.     rc = -1;
  12164.         closecon = 1;
  12165.         goto delexit;
  12166.     }
  12167.  
  12168.     /* Any response data? */
  12169.     if ( chunked ) {
  12170.         while ((len = http_get_chunk_len()) > 0) {
  12171.             while (len && (ch = http_inc(0)) >= 0) {
  12172.                 len--;
  12173.                 conoc((CHAR)ch);
  12174.             }
  12175.             if ((ch = http_inc(0)) != CR)
  12176.                 break;
  12177.             if ((ch = http_inc(0)) != LF)
  12178.                 break;
  12179.         }
  12180.     } else {
  12181.         while (len && (ch = http_inc(0)) >= 0) {
  12182.             len--;
  12183.             conoc((CHAR)ch);
  12184.         }
  12185.     }
  12186.  
  12187.     if ( chunked ) {            /* Parse Trailing Headers */
  12188.         nullline = 0;
  12189.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12190.             buf[i] = ch;
  12191.             if ( buf[i] == 10 ) { /* found end of line */
  12192.         if (i > 0 && buf[i-1] == 13)
  12193.           i--;
  12194.                 if (i < 1)
  12195.           nullline = 1;
  12196.                 buf[i] = '\0';
  12197.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12198.                     makestr(&headers[hdcnt++],buf);
  12199.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12200.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12201.                         closecon = 1;
  12202.                 }
  12203.                 i = 0;
  12204.             } else {
  12205.                 i++;
  12206.             }
  12207.         }
  12208.     }
  12209.  
  12210.   delexit:
  12211.     if (array)
  12212.         http_mkarray(headers,hdcnt,array);
  12213.  
  12214.     if (closecon)
  12215.         http_close();
  12216.     free(request);
  12217.     for (i = 0; i < hdcnt; i++) {
  12218.         if (headers[i])
  12219.           free(headers[i]);
  12220.     }
  12221.     return(rc);
  12222. }
  12223.  
  12224. int
  12225. #ifdef CK_ANSIC
  12226. http_post(char * agent, char ** hdrlist, char * mime, char * user,
  12227.           char * pwd, char array, char * local, char * remote,
  12228.           char * dest, int stdio)
  12229. #else
  12230. http_post(agent, hdrlist, mime, user, pwd, array, local, remote, dest,
  12231.           stdio)
  12232.     char * agent; char ** hdrlist; char * mime; char * user;
  12233.     char * pwd; char array; char * local; char * remote; char * dest;
  12234.     int stdio;
  12235. #endif /* CK_ANSIC */
  12236. {
  12237.     char * request=NULL;
  12238.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12239.     int    ch;
  12240.     int    http_fnd = 0;
  12241.     char   buf[HTTPBUFLEN], *p;
  12242.     int    nullline;
  12243.     time_t mod_t;
  12244.     time_t srv_t;
  12245.     time_t local_t;
  12246.     char passwd[64];
  12247.     char b64in[128];
  12248.     char b64out[256];
  12249.     int  filelen;
  12250.     char * headers[HTTPHEADCNT];
  12251.     int  closecon = 0;
  12252.     int  chunked = 0;
  12253.     int  zfile = 0;
  12254.     int  first = 1;
  12255.  
  12256.     if (httpfd == -1)
  12257.       return(-1);
  12258.  
  12259.     if (array) {
  12260.         for (i = 0; i < HTTPHEADCNT; i++)
  12261.           headers[i] = NULL;
  12262.     }
  12263.     filelen = zchki(local);
  12264.     if (filelen < 0)
  12265.       return(-1);
  12266.  
  12267.     /* Compute length of request header */
  12268.     len = 9;                            /* POST */
  12269.     len += strlen(HTTP_VERSION);
  12270.     len += strlen(remote);
  12271.     len += 16;
  12272.  
  12273.     if ( hdrlist ) {
  12274.         for (i = 0; hdrlist[i]; i++)
  12275.             len += strlen(hdrlist[i]) + 2;
  12276.     }
  12277.     len += strlen(http_host_port) + 8;
  12278.  
  12279.     if (agent)
  12280.       len += 13 + strlen(agent);
  12281.     if (user) {
  12282.         if (!pwd) {
  12283.             readpass("Password: ",passwd,64);
  12284.             pwd = passwd;
  12285.         }
  12286.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12287.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12288.         memset(pwd,0,strlen(pwd));
  12289.         if (j < 0)
  12290.           return(-1);
  12291.         b64out[j] = '\0';
  12292.         len += j + 24;
  12293.     }
  12294.     len += 16 + strlen(mime);           /* Content-type: */
  12295.     len += 32;                          /* Content-length: */
  12296.     len += 32;                          /* Date: */
  12297. #ifdef HTTP_CLOSE
  12298.     len += 19;                          /* Connection: close */
  12299. #endif
  12300.     len += 3;                           /* blank line + null */
  12301.  
  12302.     request = malloc(len);
  12303.     if (!request)
  12304.       return(-1);
  12305.  
  12306.     sprintf(request,"POST %s %s\r\n",remote,HTTP_VERSION);
  12307.     ckstrncat(request,"Date: ",len);
  12308.     ckstrncat(request,http_now(),len);
  12309.     ckstrncat(request,"\r\n",len);
  12310.     ckstrncat(request,"Host: ", len);
  12311.     ckstrncat(request,http_host_port, len);
  12312.     ckstrncat(request,"\r\n",len);
  12313.     if (agent) {
  12314.         ckstrncat(request,"User-agent: ",len);
  12315.         ckstrncat(request,agent,len);
  12316.         ckstrncat(request,"\r\n",len);
  12317.     }
  12318.     if (user) {
  12319.         ckstrncat(request,"Authorization: Basic ",len);
  12320.         ckstrncat(request,b64out,len);
  12321.         ckstrncat(request,"\r\n",len);
  12322.     }
  12323.     if ( hdrlist ) {
  12324.         for (i = 0; hdrlist[i]; i++) {
  12325.             ckstrncat(request,hdrlist[i],len);
  12326.             ckstrncat(request,"\r\n",len);
  12327.         }
  12328.     }
  12329.     ckstrncat(request,"Content-type: ",len);
  12330.     ckstrncat(request,mime,len);
  12331.     ckstrncat(request,"\r\n",len);
  12332. #ifdef HTTP_CLOSE
  12333.     ckstrncat(request,"Connection: close\r\n",len);
  12334. #endif
  12335.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  12336.     ckstrncat(request,buf,len);
  12337.     ckstrncat(request,"\r\n",len);
  12338.     ckstrncat(request,"\r\n",len);
  12339.  
  12340.     /* Now we have the contents of the file */
  12341.   postopen:
  12342.     if (zopeni(ZIFILE,local)) {
  12343.       postreq:
  12344.         if (http_tol((CHAR *)request,strlen(request)) < 0)
  12345.         {
  12346.             http_close();
  12347.             if ( first ) {
  12348.                 first--;
  12349.                 http_reopen();
  12350.                 goto postreq;
  12351.             }
  12352.             rc = -1;
  12353.             zclose(ZIFILE);
  12354.             goto postexit;
  12355.         }
  12356.  
  12357.         i = 0;
  12358.         while (zchin(ZIFILE,&ch) == 0) {
  12359.             buf[i++] = ch;
  12360.             if (i == HTTPBUFLEN) {
  12361.                 http_tol((CHAR *)buf,HTTPBUFLEN);
  12362.                 i = 0;
  12363.             }
  12364.         }
  12365.         if (i > 0)
  12366.           http_tol((CHAR *)buf,HTTPBUFLEN);
  12367.         zclose(ZIFILE);
  12368.  
  12369.         /* Process the response headers */
  12370.         local_t = time(NULL);
  12371.         nullline = 0;
  12372.         i = 0;
  12373.         len = -1;
  12374.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12375.             buf[i] = ch;
  12376.             if (buf[i] == 10) {         /* found end of line */
  12377.         if (i > 0 && buf[i-1] == 13)
  12378.           i--;
  12379.                 if (i < 1)
  12380.                   nullline = 1;
  12381.                 buf[i] = '\0';
  12382.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12383.                   makestr(&headers[hdcnt++],buf);
  12384.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  12385.             http_fnd = 1;
  12386.                     j = ckindex(" ",buf,0,0,0);
  12387.                     p = &buf[j];
  12388.             while (isspace(*p))
  12389.               p++;
  12390.                     switch (p[0]) {
  12391.               case '1':        /* Informational message */
  12392.                         break;
  12393.               case '2':        /* Success */
  12394.                         break;
  12395.               case '3':        /* Redirection */
  12396.               case '4':        /* Client failure */
  12397.               case '5':        /* Server failure */
  12398.               default:        /* Unknown */
  12399.             if (!quiet)
  12400.               printf("Failure: Server reports %s\n",p);
  12401.                         rc = -1;
  12402.                     }
  12403.                     http_set_code_reply(p);
  12404.                 } else {
  12405.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12406.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12407.                             closecon = 1;
  12408.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12409.                         len = atoi(&buf[16]);
  12410.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12411.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  12412.                             chunked = 1;
  12413.                     }
  12414.                     if (stdio)
  12415.                         printf("%s\n",buf);
  12416.                 }
  12417.                 i = 0;
  12418.             } else {
  12419.                 i++;
  12420.             }
  12421.         }
  12422.         if (ch < 0 && first) {
  12423.             first--;
  12424.             http_close();
  12425.             http_reopen();
  12426.             goto postopen;
  12427.         }
  12428.     if (http_fnd == 0) {
  12429.         rc = -1;
  12430.             closecon = 1;
  12431.             goto postexit;
  12432.         }
  12433.  
  12434.         /* Any response data? */
  12435.         if ( dest && dest[0] ) {
  12436.             if (zopeno(ZOFILE,dest,NULL,NULL)) 
  12437.                 zfile = 1;
  12438.             else
  12439.                 rc = -1;
  12440.         }
  12441.  
  12442.         if ( chunked ) {
  12443.             while ((len = http_get_chunk_len()) > 0) {
  12444.                 while (len && (ch = http_inc(0)) >= 0) {
  12445.                     len--;
  12446.                     if ( zfile )
  12447.                         zchout(ZOFILE,(CHAR)ch);
  12448.                     if ( stdio )
  12449.                         conoc((CHAR)ch);
  12450.                 }
  12451.                 if ((ch = http_inc(0)) != CR)
  12452.                     break;
  12453.                 if ((ch = http_inc(0)) != LF)
  12454.                     break;
  12455.             }
  12456.         } else {
  12457.             while (len && (ch = http_inc(0)) >= 0) {
  12458.                 len--;
  12459.                 if ( zfile )
  12460.                     zchout(ZOFILE,(CHAR)ch);
  12461.                 if ( stdio )
  12462.                     conoc((CHAR)ch);
  12463.             }
  12464.         }
  12465.  
  12466.         if ( zfile )
  12467.             zclose(ZOFILE);
  12468.  
  12469.         if ( chunked ) {            /* Parse Trailing Headers */
  12470.             nullline = 0;
  12471.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12472.                 buf[i] = ch;
  12473.                 if ( buf[i] == 10 ) { /* found end of line */
  12474.             if (i > 0 && buf[i-1] == 13)
  12475.               i--;
  12476.                     if (i < 1)
  12477.               nullline = 1;
  12478.                     buf[i] = '\0';
  12479.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  12480.                         makestr(&headers[hdcnt++],buf);
  12481.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12482.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12483.                             closecon = 1;
  12484.                     }
  12485.                     i = 0;
  12486.                 } else {
  12487.                     i++;
  12488.                 }
  12489.             }
  12490.         }
  12491.     } else {
  12492.     rc = -1;
  12493.     }
  12494.  
  12495.   postexit:
  12496.     if (array)
  12497.         http_mkarray(headers,hdcnt,array);
  12498.     if (closecon)
  12499.         http_close();
  12500.     free(request);
  12501.     for (i = 0; i < hdcnt; i++) {
  12502.         if (headers[i])
  12503.           free(headers[i]);
  12504.     }
  12505.     return(rc);
  12506. }
  12507.  
  12508. int
  12509. #ifdef CK_ANSIC
  12510. http_connect(int socket, char * agent, char ** hdrlist, char * user,
  12511.          char * pwd, char array, char * host_port)
  12512. #else
  12513. http_connect(socket, agent, hdrlist, user, pwd, array, host_port)
  12514.     int socket;
  12515.     char * agent; char ** hdrlist; char * user;
  12516.     char * pwd; char array; char * host_port;
  12517. #endif /* CK_ANSIC */
  12518. {
  12519.     char * request=NULL;
  12520.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12521.     int    http_fnd = 0;
  12522.     char   buf[HTTPBUFLEN], *p, ch;
  12523.     int    nullline;
  12524.     time_t mod_t;
  12525.     time_t srv_t;
  12526.     time_t local_t;
  12527.     char passwd[64];
  12528.     char b64in[128];
  12529.     char b64out[256];
  12530.     char * headers[HTTPHEADCNT];
  12531.     int    connected = 0;
  12532.     int    chunked = 0;
  12533.  
  12534.     tcp_http_proxy_errno = 0;
  12535.  
  12536.     if (socket == -1)
  12537.       return(-1);
  12538.  
  12539.     if (array) {
  12540.         for (i = 0; i < HTTPHEADCNT; i++)
  12541.           headers[i] = NULL;
  12542.     }
  12543.  
  12544.     /* Compute length of request header */
  12545.     len = 12;                            /* CONNECT */
  12546.     len += strlen(HTTP_VERSION);
  12547.     len += strlen(host_port);
  12548.     len += 16;
  12549.     len += strlen("Proxy-Connection: Keep-Alive\r\n");
  12550.     if ( hdrlist ) {
  12551.         for (i = 0; hdrlist[i]; i++)
  12552.             len += strlen(hdrlist[i]) + 2;
  12553.     }
  12554.     if (agent)
  12555.       len += 13 + strlen(agent);
  12556.     if (user) {
  12557.         if (!pwd) {
  12558.             readpass("Password: ",passwd,64);
  12559.             pwd = passwd;
  12560.         }
  12561.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12562.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12563.         memset(pwd,0,strlen(pwd));
  12564.         if (j < 0)
  12565.           return(-1);
  12566.         b64out[j] = '\0';
  12567.         len += j + 72;
  12568.     }
  12569.     len += 32;                          /* Date: */
  12570.     len += 3;                           /* blank line + null */
  12571.  
  12572.     request = malloc(len);
  12573.     if (!request)
  12574.       return(-1);
  12575.  
  12576.     sprintf(request,"CONNECT %s %s\r\n",host_port,HTTP_VERSION);
  12577.     ckstrncat(request,"Date: ",len);
  12578. #ifdef CMDATE2TM
  12579.     ckstrncat(request,http_now(),len);
  12580. #else
  12581.     strcat(request,...);
  12582. #endif /* CMDATE2TM */
  12583.     ckstrncat(request,"\r\n",len);
  12584.     if (agent) {
  12585.         ckstrncat(request,"User-agent: ",len);
  12586.         ckstrncat(request,agent,len);
  12587.         ckstrncat(request,"\r\n",len);
  12588.     }
  12589.     if (user) {
  12590.         ckstrncat(request,"Proxy-authorization: Basic ",len);
  12591.         ckstrncat(request,b64out,len);
  12592.         ckstrncat(request,"\r\n",len);
  12593.         ckstrncat(request,"Extension: Security/Remote-Passphrase\r\n",len);
  12594.     }
  12595.     ckstrncat(request,"Proxy-Connection: Keep-Alive\r\n",len);
  12596.     if ( hdrlist ) {
  12597.         for (i = 0; hdrlist[i]; i++) {
  12598.             ckstrncat(request,hdrlist[i],len);
  12599.             ckstrncat(request,"\r\n",len);
  12600.         }
  12601.     }
  12602.     ckstrncat(request,"\r\n",len);
  12603.     len = strlen(request);
  12604.  
  12605. #ifdef TCPIPLIB
  12606.     /* Send request */
  12607.     if (socket_write(socket,(CHAR *)request,strlen(request)) < 0) {
  12608.       rc = -1;
  12609.       goto connexit;
  12610.     }
  12611. #else
  12612.     if (write(socket,(CHAR *)request,strlen(request)) < 0) { /* Send request */
  12613.     rc = -1;
  12614.         goto connexit;
  12615.     }
  12616. #endif /* TCPIPLIB */
  12617.  
  12618.     /* Process the response headers */
  12619.     local_t = time(NULL);
  12620.     nullline = 0;
  12621.     i = 0;
  12622.     while (!nullline &&
  12623. #ifdef TCPIPLIB
  12624.            (socket_read(socket,&ch,1) == 1) &&
  12625. #else
  12626.            (read(socket,&ch,1) == 1) &&
  12627. #endif /* TCPIPLIB */
  12628.            i < HTTPBUFLEN) {
  12629.         buf[i] = ch;
  12630.         if (buf[i] == 10) {         /* found end of line */
  12631.         if (i > 0 && buf[i-1] == 13)
  12632.           i--;
  12633.             if (i < 1)
  12634.           nullline = 1;
  12635.             buf[i] = '\0';
  12636.  
  12637.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12638.                 makestr(&headers[hdcnt++],buf);
  12639.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12640.         http_fnd = 1;
  12641.                 j = ckindex(" ",buf,0,0,0);
  12642.                 p = &buf[j];
  12643.                 while (isspace(*p))
  12644.           p++;
  12645.                 tcp_http_proxy_errno = atoi(p);
  12646.                 switch (p[0]) {
  12647.           case '1':        /* Informational message */
  12648.                     break;
  12649.           case '2':        /* Success */
  12650.                     connected = 1;
  12651.                     break;
  12652.           case '3':        /* Redirection */
  12653.           case '4':        /* Client failure */
  12654.           case '5':        /* Server failure */
  12655.           default:        /* Unknown */
  12656.             if (!quiet)
  12657.               printf("Failure: Server reports %s\n",p);
  12658.                     rc = -1;
  12659.                 }
  12660.                 http_set_code_reply(p);
  12661.             } else {
  12662.                 printf("%s\n",buf);
  12663.             }
  12664.             i = 0;
  12665.         } else {
  12666.         i++;
  12667.         }
  12668.     }
  12669.     if ( http_fnd == 0 )
  12670.     rc = -1;
  12671.  
  12672.     if (array)
  12673.         http_mkarray(headers,hdcnt,array);
  12674.  
  12675.   connexit:
  12676.     if ( !connected ) {
  12677.         if ( socket == ttyfd ) {
  12678.             ttclos(0);
  12679.         }
  12680.         else if ( socket == httpfd ) {
  12681.             http_close();
  12682.         }
  12683.     }
  12684.  
  12685.     free(request);
  12686.     for (i = 0; i < hdcnt; i++) {
  12687.         if (headers[i])
  12688.           free(headers[i]);
  12689.     }
  12690.     return(rc);
  12691. }
  12692. #endif /* NOHTTP */
  12693.  
  12694. #ifdef CK_DNS_SRV
  12695.  
  12696. #define INCR_CHECK(x,y) x += y; if (x > size + answer.bytes) goto dnsout
  12697. #define CHECK(x,y) if (x + y > size + answer.bytes) goto dnsout
  12698. #define NTOHSP(x,y) x[0] << 8 | x[1]; x += y
  12699.  
  12700. #ifndef CKQUERYTYPE
  12701. #ifdef UNIXWARE
  12702. #ifndef UW7
  12703. #define CKQUERYTYPE CHAR
  12704. #endif /* UW7 */
  12705. #endif /* UNIXWARE */
  12706. #endif /* CKQUERYTYPE */
  12707.  
  12708. #ifndef CKQUERYTYPE
  12709. #define CKQUERYTYPE char
  12710. #endif /* CKQUERYTYPE */
  12711.  
  12712. /* 1 is success, 0 is failure */
  12713. int
  12714. locate_srv_dns(host, service, protocol, addr_pp, naddrs)
  12715.     char *host;
  12716.     char *service;
  12717.     char *protocol;
  12718.     struct sockaddr **addr_pp;
  12719.     int *naddrs;
  12720. {
  12721.     int nout, j, count;
  12722.     union {
  12723.         unsigned char bytes[2048];
  12724.         HEADER hdr;
  12725.     } answer;
  12726.     unsigned char *p=NULL;
  12727.     CKQUERYTYPE query[MAX_DNS_NAMELEN];
  12728. #ifdef CK_ANSIC
  12729.     const char * h;
  12730. #else
  12731.     char * h;
  12732. #endif /* CK_ANSIC */
  12733.     struct sockaddr *addr = NULL;
  12734.     struct sockaddr_in *sin = NULL;
  12735.     struct hostent *hp = NULL;
  12736.     int type, class;
  12737.     int priority, weight, size, len, numanswers, numqueries, rdlen;
  12738.     unsigned short port;
  12739. #ifdef CK_ANSIC
  12740.     const
  12741. #endif /* CK_ANSIC */
  12742.       int hdrsize = sizeof(HEADER);
  12743.     struct srv_dns_entry {
  12744.         struct srv_dns_entry *next;
  12745.         int priority;
  12746.         int weight;
  12747.         unsigned short port;
  12748.         char *host;
  12749.     };
  12750.     struct srv_dns_entry *head = NULL;
  12751.     struct srv_dns_entry *srv = NULL, *entry = NULL;
  12752.     char * s = NULL;
  12753.  
  12754.     nout = 0;
  12755.     addr = (struct sockaddr *) malloc(sizeof(struct sockaddr));
  12756.     if (addr == NULL)
  12757.       return 0;
  12758.  
  12759.     count = 1;
  12760.  
  12761.     /*
  12762.      * First build a query of the form:
  12763.      *
  12764.      *   service.protocol.host
  12765.      *
  12766.      * which will most likely be something like:
  12767.      *
  12768.      *   _telnet._tcp.host
  12769.      *
  12770.      */
  12771.     if (((int)strlen(service) + strlen(protocol) + strlen(host) + 5)
  12772.         > MAX_DNS_NAMELEN
  12773.         )
  12774.       goto dnsout;
  12775.  
  12776.     /* Realm names don't (normally) end with ".", but if the query
  12777.        doesn't end with "." and doesn't get an answer as is, the
  12778.        resolv code will try appending the local domain.  Since the
  12779.        realm names are absolutes, let's stop that.
  12780.  
  12781.        But only if a name has been specified.  If we are performing
  12782.        a search on the prefix alone then the intention is to allow
  12783.        the local domain or domain search lists to be expanded.
  12784.     */
  12785.     h = host + strlen (host);
  12786.     ckmakxmsg(query, sizeof(query), "_",service,"._",protocol,".", host,
  12787.               ((h > host) && (h[-1] != '.')?".":NULL),
  12788.                NULL,NULL,NULL,NULL,NULL);
  12789.  
  12790.     size = res_search(query, C_IN, T_SRV, answer.bytes, sizeof(answer.bytes));
  12791.  
  12792.     if (size < hdrsize)
  12793.       goto dnsout;
  12794.  
  12795.     /* We got a reply - See how many answers it contains. */
  12796.  
  12797.     p = answer.bytes;
  12798.  
  12799.     numqueries = ntohs(answer.hdr.qdcount);
  12800.     numanswers = ntohs(answer.hdr.ancount);
  12801.  
  12802.     p += sizeof(HEADER);
  12803.  
  12804.     /*
  12805.      * We need to skip over all of the questions, so we have to iterate
  12806.      * over every query record.  dn_expand() is able to tell us the size
  12807.      * of compressed DNS names, so we use it.
  12808.      */
  12809.     while (numqueries--) {
  12810.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  12811.         if (len < 0)
  12812.           goto dnsout;
  12813.         INCR_CHECK(p, len + 4);
  12814.     }
  12815.  
  12816.     /*
  12817.      * We're now pointing at the answer records.  Only process them if
  12818.      * they're actually T_SRV records (they might be CNAME records,
  12819.      * for instance).
  12820.      *
  12821.      * But in a DNS reply, if you get a CNAME you always get the associated
  12822.      * "real" RR for that CNAME.  RFC 1034, 3.6.2:
  12823.      *
  12824.      * CNAME RRs cause special action in DNS software.  When a name server
  12825.      * fails to find a desired RR in the resource set associated with the
  12826.      * domain name, it checks to see if the resource set consists of a CNAME
  12827.      * record with a matching class.  If so, the name server includes the CNAME
  12828.      * record in the response and restarts the query at the domain name
  12829.      * specified in the data field of the CNAME record.  The one exception to
  12830.      * this rule is that queries which match the CNAME type are not restarted.
  12831.      *
  12832.      * In other words, CNAMEs do not need to be expanded by the client.
  12833.      */
  12834.     while (numanswers--) {
  12835.  
  12836.         /* First is the name; use dn_expand() to get the compressed size. */
  12837.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  12838.         if (len < 0)
  12839.           goto dnsout;
  12840.         INCR_CHECK(p, len);
  12841.  
  12842.         CHECK(p,2);                     /* Query type */
  12843.         type = NTOHSP(p,2);
  12844.  
  12845.         CHECK(p, 6);                    /* Query class */
  12846.         class = NTOHSP(p,6);            /* Also skip over 4-byte TTL */
  12847.  
  12848.         CHECK(p,2);                     /* Record data length */
  12849.         rdlen = NTOHSP(p,2);
  12850.         /*
  12851.          * If this is an SRV record, process it.  Record format is:
  12852.          *
  12853.          * Priority
  12854.          * Weight
  12855.          * Port
  12856.          * Server name
  12857.          */
  12858.         if (class == C_IN && type == T_SRV) {
  12859.             CHECK(p,2);
  12860.             priority = NTOHSP(p,2);
  12861.             CHECK(p, 2);
  12862.             weight = NTOHSP(p,2);
  12863.             CHECK(p, 2);
  12864.             port = NTOHSP(p,2);
  12865.             len = dn_expand(answer.
  12866.                             bytes,
  12867.                             answer.bytes + size,
  12868.                             p,
  12869.                             query,
  12870.                             sizeof(query)
  12871.                             );
  12872.             if (len < 0)
  12873.               goto dnsout;
  12874.             INCR_CHECK(p, len);
  12875.             /*
  12876.              * We got everything.  Insert it into our list, but make sure
  12877.              * it's in the right order.  Right now we don't do anything
  12878.              * with the weight field
  12879.              */
  12880.             srv = (struct srv_dns_entry *)malloc(sizeof(struct srv_dns_entry));
  12881.             if (srv == NULL)
  12882.               goto dnsout;
  12883.  
  12884.             srv->priority = priority;
  12885.             srv->weight = weight;
  12886.             srv->port = port;
  12887.             makestr(&s,(char *)query);  /* strdup() is not portable */
  12888.             srv->host = s;
  12889.  
  12890.             if (head == NULL || head->priority > srv->priority) {
  12891.                 srv->next = head;
  12892.                 head = srv;
  12893.             } else
  12894.                 /*
  12895.                  * Confusing.  Insert an entry into this spot only if:
  12896.                  *  . The next person has a higher priority (lower
  12897.                  *    priorities are preferred), or:
  12898.                  *  . There is no next entry (we're at the end)
  12899.                  */
  12900.               for (entry = head; entry != NULL; entry = entry->next)
  12901.                 if ((entry->next &&
  12902.                      entry->next->priority > srv->priority) ||
  12903.                     entry->next == NULL) {
  12904.                     srv->next = entry->next;
  12905.                     entry->next = srv;
  12906.                     break;
  12907.                 }
  12908.         } else
  12909.           INCR_CHECK(p, rdlen);
  12910.     }
  12911.  
  12912.     /*
  12913.      * Now we've got a linked list of entries sorted by priority.
  12914.      * Start looking up A records and returning addresses.
  12915.      */
  12916.     if (head == NULL)
  12917.       goto dnsout;
  12918.  
  12919.     for (entry = head; entry != NULL; entry = entry->next) {
  12920.         hp = gethostbyname(entry->host);
  12921.         if (hp != 0) {
  12922.  
  12923.             /* Watch out - memset() and memcpy() are not portable... */
  12924.  
  12925.             switch (hp->h_addrtype) {
  12926.               case AF_INET:
  12927.                 for (j = 0; hp->h_addr_list[j]; j++) {
  12928.                     sin = (struct sockaddr_in *) &addr[nout++];
  12929.                     memset ((char *) sin, 0, sizeof (struct sockaddr));
  12930.                     sin->sin_family = hp->h_addrtype;
  12931.                     sin->sin_port = htons(entry->port);
  12932.                     memcpy((char *) &sin->sin_addr,
  12933.                            (char *) hp->h_addr_list[j],
  12934.                            sizeof(struct in_addr));             /* safe */
  12935.                     if (nout + 1 >= count) {
  12936.                         count += 5;
  12937.                         addr = (struct sockaddr *)
  12938.                           realloc((char *) addr,
  12939.                                   sizeof(struct sockaddr) * count);
  12940.                         if (!addr)
  12941.                           goto dnsout;
  12942.                     }
  12943.                 }
  12944.                 break;
  12945.               default:
  12946.                 break;
  12947.             }
  12948.         }
  12949.     }
  12950.     for (entry = head; entry != NULL;) {
  12951.         free(entry->host);
  12952.         entry->host = NULL;
  12953.         srv = entry;
  12954.         entry = entry->next;
  12955.         free(srv);
  12956.         srv = NULL;
  12957.     }
  12958.  
  12959.   dnsout:
  12960.     if (srv)
  12961.       free(srv);
  12962.  
  12963.     if (nout == 0) {                    /* No good servers */
  12964.         if (addr)
  12965.           free(addr);
  12966.         return 0;
  12967.     }
  12968.     *addr_pp = addr;
  12969.     *naddrs = nout;
  12970.     return 1;
  12971. }
  12972. #undef INCR_CHECK
  12973. #undef CHECK
  12974. #undef NTOHSP
  12975.  
  12976. #define INCR_CHECK(x, y) x += y; if (x > size + answer.bytes) \
  12977.                          return 0
  12978. #define CHECK(x, y) if (x + y > size + answer.bytes) \
  12979.                          return 0
  12980. #define NTOHSP(x, y) x[0] << 8 | x[1]; x += y
  12981.  
  12982. int
  12983. locate_txt_rr(prefix, name, retstr)
  12984.     char *prefix, *name;
  12985.     char **retstr;
  12986. {
  12987.     union {
  12988.         unsigned char bytes[2048];
  12989.         HEADER hdr;
  12990.     } answer;
  12991.     unsigned char *p;
  12992.     char host[MAX_DNS_NAMELEN], *h;
  12993.     int size;
  12994.     int type, class, numanswers, numqueries, rdlen, len;
  12995.  
  12996.     /*
  12997.      * Form our query, and send it via DNS
  12998.      */
  12999.  
  13000.     if (name == NULL || name[0] == '\0') {
  13001.         strcpy(host,prefix);
  13002.     } else {
  13003.         if ( strlen(prefix) + strlen(name) + 3 > MAX_DNS_NAMELEN )
  13004.             return 0;
  13005.  
  13006.         /* Realm names don't (normally) end with ".", but if the query
  13007.            doesn't end with "." and doesn't get an answer as is, the
  13008.            resolv code will try appending the local domain.  Since the
  13009.            realm names are absolutes, let's stop that.
  13010.  
  13011.            But only if a name has been specified.  If we are performing
  13012.            a search on the prefix alone then the intention is to allow
  13013.            the local domain or domain search lists to be expanded.
  13014.         */
  13015.         h = host + strlen (host);
  13016.         ckmakmsg(host,sizeof(host),prefix, ".", name,
  13017.                  ((h > host) && (h[-1] != '.'))?".":NULL);
  13018.  
  13019.     }
  13020.     size = res_search(host, C_IN, T_TXT, answer.bytes, sizeof(answer.bytes));
  13021.  
  13022.     if (size < 0)
  13023.         return 0;
  13024.  
  13025.     p = answer.bytes;
  13026.  
  13027.     numqueries = ntohs(answer.hdr.qdcount);
  13028.     numanswers = ntohs(answer.hdr.ancount);
  13029.  
  13030.     p += sizeof(HEADER);
  13031.  
  13032.     /*
  13033.      * We need to skip over the questions before we can get to the answers,
  13034.      * which means we have to iterate over every query record.  We use
  13035.      * dn_expand to tell us how long each compressed name is.
  13036.      */
  13037.  
  13038.     while (numqueries--) {
  13039.         len = dn_expand(answer.bytes, answer.bytes + size, p, host,
  13040.                          sizeof(host));
  13041.         if (len < 0)
  13042.             return 0;
  13043.         INCR_CHECK(p, len + 4);         /* Name plus type plus class */
  13044.     }
  13045.  
  13046.     /*
  13047.      * We're now pointing at the answer records.  Process the first
  13048.      * TXT record we find.
  13049.      */
  13050.  
  13051.     while (numanswers--) {
  13052.  
  13053.         /* First the name; use dn_expand to get the compressed size */
  13054.         len = dn_expand(answer.bytes, answer.bytes + size, p,
  13055.                         host, sizeof(host));
  13056.         if (len < 0)
  13057.             return 0;
  13058.         INCR_CHECK(p, len);
  13059.  
  13060.         /* Next is the query type */
  13061.         CHECK(p, 2);
  13062.         type = NTOHSP(p,2);
  13063.  
  13064.         /* Next is the query class; also skip over 4 byte TTL */
  13065.         CHECK(p,6);
  13066.         class = NTOHSP(p,6);
  13067.  
  13068.         /* Record data length - make sure we aren't truncated */
  13069.  
  13070.         CHECK(p,2);
  13071.         rdlen = NTOHSP(p,2);
  13072.  
  13073.         if (p + rdlen > answer.bytes + size)
  13074.             return 0;
  13075.  
  13076.         /*
  13077.          * If this is a TXT record, return the string.  Note that the
  13078.          * string has a 1-byte length in the front
  13079.          */
  13080.         /* XXX What about flagging multiple TXT records as an error?  */
  13081.  
  13082.         if (class == C_IN && type == T_TXT) {
  13083.             len = *p++;
  13084.             if (p + len > answer.bytes + size)
  13085.                 return 0;
  13086.             *retstr = malloc(len + 1);
  13087.             if (*retstr == NULL)
  13088.                 return ENOMEM;
  13089.             strncpy(*retstr, (char *) p, len);
  13090.             (*retstr)[len] = '\0';
  13091.             /* Avoid a common error. */
  13092.             if ( (*retstr)[len-1] == '.' )
  13093.                 (*retstr)[len-1] = '\0';
  13094.             return 1;
  13095.         }
  13096.     }
  13097.  
  13098.     return 0;
  13099. }
  13100. #undef INCR_CHECK
  13101. #undef CHECK
  13102. #undef NTOHSP
  13103. #endif /* CK_DNS_SRV */
  13104.  
  13105. #ifdef TNCODE
  13106. #ifdef CK_FORWARD_X
  13107. #ifdef UNIX
  13108. #include <sys/un.h>
  13109. #define FWDX_UNIX_SOCK
  13110. #ifndef AF_LOCAL
  13111. #define AF_LOCAL AF_UNIX
  13112. #endif
  13113. #ifndef PF_LOCAL
  13114. #define PF_LOCAL PF_UNIX
  13115. #endif
  13116. #ifndef SUN_LEN
  13117. /* Evaluate to actual length of the `sockaddr_un' structure.  */
  13118. #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)         \
  13119.                       + strlen ((ptr)->sun_path))
  13120. #endif
  13121. #endif /* UNIX */
  13122. int
  13123. fwdx_create_listen_socket(screen) int screen; {
  13124. #ifdef NOPUTENV
  13125.     return(-1);
  13126. #else /* NOPUTENV */
  13127.     struct sockaddr_in saddr;
  13128.     int display, port, sock=-1, i;
  13129.     static char env[512];
  13130.  
  13131.     /*
  13132.      * X Windows Servers support multiple displays by listening on
  13133.      * one socket per display.  Display 0 is port 6000; Display 1 is
  13134.      * port 6001; etc.
  13135.      *
  13136.      * We start by trying to open port 6001 so that display 0 is
  13137.      * reserved for the local X Windows Server.
  13138.      */
  13139.  
  13140.     for ( display=1; display < 1000 ; display++  ) {
  13141.  
  13142.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13143.             debug(F111,"fwdx_create_listen_socket()","socket() < 0",sock);
  13144.             return(-1);
  13145.         }
  13146.  
  13147.         port = 6000 + display;
  13148.         bzero((char *)&saddr, sizeof(saddr));
  13149.         saddr.sin_family = AF_INET;
  13150.         saddr.sin_addr.s_addr = inet_addr(myipaddr);
  13151.         saddr.sin_port = htons(port);
  13152.  
  13153.         if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13154.             i = errno;                  /* Save error code */
  13155. #ifdef TCPIPLIB
  13156.             socket_close(sock);
  13157. #else /* TCPIPLIB */
  13158.             close(sock);
  13159. #endif /* TCPIPLIB */
  13160.             sock = -1;
  13161.             debug(F110,"fwdx_create_listen_socket()","bind() < 0",0);
  13162.             continue;
  13163.         }
  13164.  
  13165.         debug(F100,"fdwx_create_listen_socket() bind OK","",0);
  13166.         break;
  13167.     }
  13168.  
  13169.     if ( display > 1000 ) {
  13170.         debug(F100,"fwdx_create_listen_socket() Out of Displays","",0);
  13171.         return(-1);
  13172.     }
  13173.  
  13174.     if (listen(sock, 5) < 0) {
  13175.         i = errno;                  /* Save error code */
  13176. #ifdef TCPIPLIB
  13177.         socket_close(sock);
  13178. #else /* TCPIPLIB */
  13179.         close(sock);
  13180. #endif /* TCPIPLIB */
  13181.         debug(F101,"fdwx_create_listen_socket() listen() errno","",errno);
  13182.         return(-1);
  13183.     }
  13184.     debug(F100,"fwdx_create_listen_socket() listen OK","",0);
  13185.  
  13186.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = sock;
  13187.     if (!myipaddr[0])
  13188.         getlocalipaddr();
  13189.     if ( myipaddr[0] )
  13190.         ckmakxmsg(env,sizeof(env),"DISPLAY=",myipaddr,":",
  13191.                   ckuitoa(display),":",ckuitoa(screen),
  13192.                   NULL,NULL,NULL,NULL,NULL,NULL);
  13193.     else
  13194.         ckmakmsg(env,sizeof(env),"DISPLAY=",ckuitoa(display),":",
  13195.                  ckuitoa(screen));
  13196.     putenv(env);
  13197.     return(0);
  13198. #endif /* NOPUTENV */
  13199. }
  13200.  
  13201.  
  13202. int
  13203. fwdx_open_client_channel(channel) int channel; {
  13204.     char * env;
  13205.     struct sockaddr_in saddr;
  13206. #ifdef FWDX_UNIX_SOCK
  13207.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13208. #endif /* FWDX_UNIX_SOCK */
  13209.     int colon, dot, display, port, sock, i, screen;
  13210.     int family;
  13211.     char buf[256], * host=NULL, * rest=NULL;
  13212. #ifdef TCP_NODELAY
  13213.     int on=1;
  13214. #endif /* TCP_NODELAY */
  13215.  
  13216.     debug(F111,"fwdx_create_client_channel()","channel",channel);
  13217.  
  13218.     for ( i=0; i<MAXFWDX ; i++ ) {
  13219.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel) {
  13220.             /* Already open */
  13221.             debug(F110,"fwdx_create_client_channel()","already open",0);
  13222.             return(0);
  13223.         }
  13224.     }
  13225.  
  13226.     env = getenv("DISPLAY");
  13227.     if ( !env )
  13228.         env = tn_get_display();
  13229.     if ( env )
  13230.         ckstrncpy(buf,env,256);
  13231.     else
  13232.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13233.  
  13234.     bzero((char *)&saddr,sizeof(saddr));
  13235.     saddr.sin_family = AF_INET;
  13236.  
  13237.     if (!fwdx_parse_displayname(buf,
  13238.                 &family,
  13239.                 &host,
  13240.                 &display,
  13241.                 &screen,
  13242.                 &rest
  13243.                 )
  13244.     ) {
  13245.         if ( host ) free(host);
  13246.         if ( rest ) free(rest);
  13247.         return(0);
  13248.     }
  13249.     if (rest) free(rest);
  13250.  
  13251. #ifndef FWDX_UNIX_SOCK
  13252.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13253.    * we change things to use inet sockets on the ip loopback interface instead,
  13254.    * and hope that it works.
  13255.    */
  13256.     if (family == FamilyLocal) {
  13257.         debug(F100,"fwdx_create_client_channel() FamilyLocal","",0);
  13258.     family = FamilyInternet;
  13259.     if (host) free(host);
  13260.     if (host = malloc(strlen("localhost") + 1))
  13261.         strcpy(host, "localhost");
  13262.     else {
  13263.             return(-1);
  13264.     }
  13265.     }
  13266. #else /* FWDX_UNIX_SOCK */
  13267.     if (family == FamilyLocal) {
  13268.         if (host) free(host);
  13269.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13270.         if (sock < 0)
  13271.             return(-1);
  13272.  
  13273.     ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13274.     strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13275.     if (connect(sock,(struct sockaddr *)&saddr_un, SUN_LEN(&saddr_un)) < 0)
  13276.       return(-1);
  13277.     } else
  13278. #endif  /* FWDX_UNIX_SOCK */
  13279.     {
  13280.         /* Otherwise, we are assuming FamilyInternet */
  13281.         if (host) {
  13282.             ckstrncpy(buf,host,sizeof(buf));
  13283.             free(host);
  13284.         } else
  13285.             ckstrncpy(buf,myipaddr,sizeof(buf));
  13286.  
  13287.         debug(F111,"fwdx_create_client_channel()","display",display);
  13288.  
  13289.         port = 6000 + display;
  13290.         saddr.sin_port = htons(port);
  13291.  
  13292.         debug(F110,"fwdx_create_client_channel() ip-address",buf,0);
  13293.         saddr.sin_addr.s_addr = inet_addr(buf);
  13294.         if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13295. #ifdef INADDR_NONE
  13296.              || saddr.sin_addr.s_addr == INADDR_NONE
  13297. #endif /* INADDR_NONE */
  13298.              )
  13299.         {
  13300.             struct hostent *host;
  13301.             host = gethostbyname(buf);
  13302.             if ( host == NULL )
  13303.                 return(-1);
  13304.             host = ck_copyhostent(host);
  13305. #ifdef HADDRLIST
  13306. #ifdef h_addr
  13307.             /* This is for trying multiple IP addresses - see <netdb.h> */
  13308.             if (!(host->h_addr_list))
  13309.                 return(-1);
  13310.             bcopy(host->h_addr_list[0],
  13311.                    (caddr_t)&saddr.sin_addr,
  13312.                    host->h_length
  13313.                    );
  13314. #else
  13315.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13316. #endif /* h_addr */
  13317. #else  /* HADDRLIST */
  13318.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13319. #endif /* HADDRLIST */
  13320.         }
  13321.  
  13322.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13323.             debug(F111,"fwdx_create_client_channel()","socket() < 0",sock);
  13324.             return(-1);
  13325.         }
  13326.  
  13327.         if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13328.             debug(F110,"fwdx_create_client_channel()","connect() failed",0);
  13329. #ifdef TCPIPLIB
  13330.             socket_close(sock);
  13331. #else /* TCPIPLIB */
  13332.             close(sock);
  13333. #endif /* TCPIPLIB */
  13334.             return(-1);
  13335.         }
  13336.  
  13337. #ifdef TCP_NODELAY
  13338.         setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13339. #endif /* TCP_NODELAY */
  13340.     }
  13341.  
  13342.     for (i = 0; i < MAXFWDX; i++) {
  13343.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == -1) {
  13344.      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = sock;
  13345.      TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = channel;
  13346.        TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 1;
  13347.      debug(F111,"fwdx_create_client_channel()","socket",sock);
  13348.      return(0);
  13349.      }
  13350.     }
  13351.     return(-1);
  13352. }
  13353.  
  13354. int
  13355. fwdx_server_avail() {
  13356.     char * env;
  13357.     struct sockaddr_in saddr;
  13358. #ifdef FWDX_UNIX_SOCK
  13359.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13360. #endif  /* FWDX_UNIX_SOCK */
  13361.     int colon, dot, display, port, sock, i, screen;
  13362.     char buf[256], *host=NULL, *rest=NULL;
  13363. #ifdef TCP_NODELAY
  13364.     int on=1;
  13365. #endif /* TCP_NODELAY */
  13366.     int family;
  13367.  
  13368.     env = getenv("DISPLAY");
  13369.     if ( !env )
  13370.         env = tn_get_display();
  13371.     if ( env )
  13372.         ckstrncpy(buf,env,256);
  13373.     else
  13374.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13375.  
  13376.     bzero((char *)&saddr,sizeof(saddr));
  13377.     saddr.sin_family = AF_INET;
  13378.  
  13379.     if (!fwdx_parse_displayname(buf,&family,&host,&display,&screen,&rest)) {
  13380.         if ( host ) free(host);
  13381.         if ( rest ) free(rest);
  13382.         return(0);
  13383.     }
  13384.     if (rest) free(rest);
  13385.  
  13386. #ifndef FWDX_UNIX_SOCK
  13387.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13388.    * we change things to use inet sockets on the ip loopback interface instead,
  13389.    * and hope that it works.
  13390.    */
  13391.     if (family == FamilyLocal) {
  13392.     family = FamilyInternet;
  13393.     if (host) free(host);
  13394.     if (host = malloc(strlen("localhost") + 1))
  13395.         strcpy(host, "localhost");
  13396.     else {
  13397.             return(-1);
  13398.     }
  13399.     }
  13400. #else /* FWDX_UNIX_SOCK */
  13401.     if (family == FamilyLocal) {
  13402.         debug(F100,"fwdx_server_avail() FamilyLocal","",0);
  13403.         if (host) free(host);
  13404.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13405.         if (sock < 0)
  13406.             return(0);
  13407.  
  13408.     ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13409.     strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13410.     if (connect(sock,(struct sockaddr *)&saddr_un,SUN_LEN(&saddr_un)) < 0)
  13411.             return(0);
  13412.         close(sock);
  13413.         return(1);
  13414.     }
  13415. #endif  /* FWDX_UNIX_SOCK */
  13416.  
  13417.     /* Otherwise, we are assuming FamilyInternet */
  13418.     if (host) {
  13419.         ckstrncpy(buf,host,sizeof(buf));
  13420.         free(host);
  13421.     } else
  13422.         ckstrncpy(buf,myipaddr,sizeof(buf));
  13423.  
  13424.     debug(F111,"fwdx_server_avail()","display",display);
  13425.  
  13426.     port = 6000 + display;
  13427.     saddr.sin_port = htons(port);
  13428.  
  13429.     debug(F110,"fwdx_server_avail() ip-address",buf,0);
  13430.     saddr.sin_addr.s_addr = inet_addr(buf);
  13431.     if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13432. #ifdef INADDR_NONE
  13433.          || saddr.sin_addr.s_addr == INADDR_NONE
  13434. #endif /* INADDR_NONE */
  13435.          )
  13436.     {
  13437.         struct hostent *host;
  13438.         host = gethostbyname(buf);
  13439.         if ( host == NULL ) {
  13440.             debug(F110,"fwdx_server_avail() gethostbyname() failed",
  13441.                    myipaddr,0);
  13442.             return(-1);
  13443.         }
  13444.         host = ck_copyhostent(host);
  13445. #ifdef HADDRLIST
  13446. #ifdef h_addr
  13447.         /* This is for trying multiple IP addresses - see <netdb.h> */
  13448.         if (!(host->h_addr_list))
  13449.             return(-1);
  13450.         bcopy(host->h_addr_list[0],
  13451.                (caddr_t)&saddr.sin_addr,
  13452.                host->h_length
  13453.                );
  13454. #else
  13455.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13456. #endif /* h_addr */
  13457. #else  /* HADDRLIST */
  13458.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13459. #endif /* HADDRLIST */
  13460.     }
  13461.  
  13462.     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13463.         debug(F111,"fwdx_server_avail()","socket() < 0",sock);
  13464.         return(0);
  13465.     }
  13466.  
  13467.     if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13468.         debug(F110,"fwdx_server_avail()","connect() failed",0);
  13469. #ifdef TCPIPLIB
  13470.         socket_close(sock);
  13471. #else /* TCPIPLIB */
  13472.         close(sock);
  13473. #endif /* TCPIPLIB */
  13474.         return(0);
  13475.     }
  13476.  
  13477. #ifdef TCPIPLIB
  13478.     socket_close(sock);
  13479. #else /* TCPIPLIB */
  13480.     close(sock);
  13481. #endif /* TCPIPLIB */
  13482.     return(1);
  13483. }
  13484.  
  13485. int
  13486. fwdx_open_server_channel() {
  13487.     int sock, ready_to_accept, sock2,channel,i;
  13488. #ifdef TCP_NODELAY
  13489.     int on=1;
  13490. #endif /* TCP_NODELAY */
  13491. #ifdef UCX50
  13492.     static u_int saddrlen;
  13493. #else
  13494.     static SOCKOPT_T saddrlen;
  13495. #endif /* UCX50 */
  13496.     struct sockaddr_in saddr;
  13497.     char sb[8];
  13498.     extern char tn_msg[];
  13499. #ifdef BSDSELECT
  13500.     fd_set rfds;
  13501.     struct timeval tv;
  13502. #else
  13503. #ifdef BELLSELCT
  13504.     fd_set rfds;
  13505. #else
  13506.     fd_set rfds;
  13507.     struct timeval {
  13508.         long tv_sec;
  13509.         long tv_usec;
  13510.     } tv;
  13511. #endif /* BELLSELECT */
  13512. #endif /* BSDSELECT */
  13513.     unsigned short nchannel;
  13514.     unsigned char * p;
  13515.  
  13516.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket;
  13517.  
  13518.   try_again:
  13519.  
  13520. #ifdef BSDSELECT
  13521.     tv.tv_sec  = tv.tv_usec = 0L;
  13522.     tv.tv_usec = 50;
  13523.     FD_ZERO(&rfds);
  13524.     FD_SET(sock, &rfds);
  13525.     ready_to_accept =
  13526.         ((select(FD_SETSIZE,
  13527. #ifdef HPUX
  13528. #ifdef HPUX1010
  13529.                   (fd_set *)
  13530. #else
  13531.  
  13532.                   (int *)
  13533. #endif /* HPUX1010 */
  13534. #else
  13535. #ifdef __DECC
  13536.                   (fd_set *)
  13537. #endif /* __DECC */
  13538. #endif /* HPUX */
  13539.                   &rfds, NULL, NULL, &tv) > 0) &&
  13540.           FD_ISSET(sock, &rfds));
  13541. #else /* BSDSELECT */
  13542. #ifdef IBMSELECT
  13543.     ready_to_accept = (select(&sock, 1, 0, 0, 50) == 1);
  13544. #else
  13545. #ifdef BELLSELECT
  13546.     FD_ZERO(rfds);
  13547.     FD_SET(sock, rfds);
  13548.     ready_to_accept =
  13549.         ((select(128, rfds, NULL, NULL, 50) > 0) &&
  13550.           FD_ISSET(sock, rfds));
  13551. #else
  13552. /* Try this - what's the worst that can happen... */
  13553.  
  13554.     tv.tv_sec  = tv.tv_usec = 0L;
  13555.     tv.tv_usec = 50;
  13556.     FD_ZERO(&rfds);
  13557.     FD_SET(sock, &rfds);
  13558.     ready_to_accept =
  13559.         ((select(FD_SETSIZE,
  13560.                   (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  13561.           FD_ISSET(sock, &rfds));
  13562. #endif /* BELLSELECT */
  13563. #endif /* IBMSELECT */
  13564. #endif /* BSDSELECT */
  13565.  
  13566.     if ( !ready_to_accept )
  13567.         return(0);
  13568.  
  13569.     if ((sock2 = accept(sock,(struct sockaddr *)&saddr,&saddrlen)) < 0) {
  13570.         int i = errno;                  /* save error code */
  13571.         debug(F101,"tcpsrv_open accept errno","",i);
  13572.         return(-1);
  13573.     }
  13574.  
  13575.     /*
  13576.      * Now we have the open socket.  We must now find a channel to store
  13577.      * it in, and then notify the client.
  13578.      */
  13579.  
  13580.     for ( channel=0;channel<MAXFWDX;channel++ ) {
  13581.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd == -1 )
  13582.             break;
  13583.     }
  13584.  
  13585.     if ( channel == MAXFWDX ) {
  13586. #ifdef TCPIPLIB
  13587.         socket_close(sock2);
  13588. #else /* TCPIPLIB */
  13589.         close(sock2);
  13590. #endif /* TCPIPLIB */
  13591.         return(-1);
  13592.     }
  13593.  
  13594.     if ( fwdx_send_open(channel) < 0 ) {
  13595. #ifdef TCPIPLIB
  13596.         socket_close(sock2);
  13597. #else /* TCPIPLIB */
  13598.         close(sock2);
  13599. #endif /* TCPIPLIB */
  13600.     }
  13601.  
  13602. #ifdef TCP_NODELAY
  13603.     setsockopt(sock2,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13604. #endif /* TCP_NODELAY */
  13605.  
  13606.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd = sock2;
  13607.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].id = channel;
  13608.     goto try_again;
  13609.  
  13610.     return(0);  /* never reached */
  13611. }
  13612.  
  13613. int
  13614. fwdx_close_channel(channel) int channel; {
  13615.     int i,fd;
  13616.  
  13617.     for ( i=0; i<MAXFWDX ; i++ ) {
  13618.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13619.             break;
  13620.     }
  13621.     if ( i == MAXFWDX )
  13622.         return(-1);
  13623.  
  13624.     fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13625.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = -1;
  13626.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = -1;
  13627.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 0;
  13628.  
  13629. #ifdef TCPIPLIB
  13630.     socket_close(fd);
  13631. #else /* TCPIPLIB */
  13632.     close(fd);
  13633. #endif /* TCPIPLIB */
  13634.     return(0);
  13635. }
  13636.  
  13637. int
  13638. fwdx_close_all() {
  13639.     int x,fd;
  13640.  
  13641.     debug(F111,"fwdx_close_all()",
  13642.           "TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket",
  13643.           TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13644.  
  13645.     if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1 ) {
  13646. #ifdef TCPIPLIB
  13647.         socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13648. #else /* TCPIPLIB */
  13649.         close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13650. #endif /* TCPIPLIB */
  13651.         TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = -1;
  13652.     }
  13653.  
  13654.     for (x = 0; x < MAXFWDX; x++) {
  13655.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  13656.       fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13657.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd = -1;
  13658.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id = -1;
  13659.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].need_to_send_xauth = 0;
  13660.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend = 0;
  13661. #ifdef TCPIPLIB
  13662.       socket_close(fd);
  13663. #else /* TCPIPLIB */
  13664.       close(fd);
  13665. #endif /* TCPIPLIB */
  13666.      }
  13667.     }
  13668.     return(0);
  13669. }
  13670.  
  13671. /* The following definitions are for Unix */
  13672. #ifndef socket_write
  13673. #define socket_write(f,s,n)    write(f,s,n)
  13674. #endif /* socket_write */
  13675. #ifndef socket_read
  13676. #define socket_read(f,s,n)     read(f,s,n)
  13677. #endif /* socket_read */
  13678.  
  13679. int
  13680. fwdx_write_data_to_channel(channel, data, len)
  13681.     int channel; char * data; int len;
  13682. {
  13683.     int sock, count, try=0, length = len, i;
  13684.  
  13685.     if ( len <= 0 )
  13686.         return(0);
  13687.  
  13688.     for ( i=0; i<MAXFWDX ; i++ ) {
  13689.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13690.             break;
  13691.     }
  13692.     if ( i == MAXFWDX ) {
  13693.         debug(F110,"fwdx_write_data_to_channel",
  13694.                "attempting to write to closed channel",0);
  13695.         return(-1);
  13696.     }
  13697.  
  13698.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13699.     debug(F111,"fwdx_write_data_to_channel","socket",sock);
  13700.     hexdump("fwdx_write_data_to_channel",data,len);
  13701.  
  13702.   fwdx_write_data_to_channel_retry:
  13703.  
  13704.     if ((count = socket_write(sock,data,len)) < 0) {
  13705.         int s_errno = socket_errno; /* maybe a function */
  13706.         debug(F101,"fwdx_write_data_to_channel socket_write error","",s_errno);
  13707. #ifdef BETATEST
  13708.         printf("fwdx_write_data_to_channel error\r\n");
  13709. #endif /* BETATEST */
  13710. #ifdef OS2
  13711.         if (os2socketerror(s_errno) < 0)
  13712.             return(-2);
  13713. #endif /* OS2 */
  13714.         return(-1);                 /* Call it an i/o error */
  13715.     }
  13716.     if (count < len) {
  13717.         debug(F111,"fwdx_write_data_to_channel socket_write",data,count);
  13718.         if (count > 0) {
  13719.             data += count;
  13720.             len -= count;
  13721.         }
  13722.         debug(F111,"fwdx_write_data_to_channel retry",data,len);
  13723.         if ( len > 0 )
  13724.             goto fwdx_write_data_to_channel_retry;
  13725.     }
  13726.  
  13727.     debug(F111,"fwdx_write_data_to_channel complete",data,length);
  13728.     return(length); /* success - return total length */
  13729. }
  13730.  
  13731. VOID
  13732. fwdx_check_sockets(fd_set *ibits)
  13733. {
  13734.     int x, sock, channel, bytes;
  13735.     static char buffer[32000];
  13736.  
  13737.     debug(F100,"fwdx_check_sockets()","",0);
  13738.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  13739.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  13740.         debug(F110,"fwdx_check_sockets()","TELOPT_FORWARD_X not negotiated",0);
  13741.         return;
  13742.     }
  13743.  
  13744.     for (x = 0; x < MAXFWDX; x++) {
  13745.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd == -1 ||
  13746.              TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend )
  13747.             continue;
  13748.  
  13749.         sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13750.         if (FD_ISSET(sock, ibits))
  13751.         {
  13752.             channel = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id;
  13753.             debug(F111,"fwdx_check_sockets()","channel set",channel);
  13754.  
  13755.             bytes = socket_read(sock, buffer, sizeof(buffer));
  13756.             if (bytes > 0)
  13757.                 fwdx_send_data_from_channel(channel, buffer, bytes);
  13758.             else if (bytes == 0) {
  13759.                 fwdx_close_channel(channel);
  13760.                 fwdx_send_close(channel);
  13761.             }
  13762.         }
  13763.     }
  13764. }
  13765.  
  13766. int
  13767. fwdx_init_fd_set(fd_set *ibits)
  13768. {
  13769.     int x,set=0,cnt=0;
  13770.  
  13771.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  13772.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  13773.         debug(F110,"fwdx_init_fd_set()","TELOPT_FORWARD_X not negotiated",0);
  13774.         return(0);
  13775.     }
  13776.  
  13777.     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1) {
  13778.         set++;
  13779.         FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket, ibits);
  13780.     }
  13781.     for (x = 0; x < MAXFWDX; x++) {
  13782.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  13783.             cnt++;
  13784.             if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend)
  13785.                 continue;
  13786.             set++;
  13787.             FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd, ibits);
  13788.         }
  13789.     }
  13790.     if (set + cnt == 0) {
  13791.         return(-1);
  13792.     } else {
  13793.         return(set);
  13794.     }
  13795. }
  13796.  
  13797. #ifdef NT
  13798. VOID
  13799. fwdx_thread( VOID * dummy )
  13800. {
  13801.     fd_set ifds;
  13802.     struct timeval tv;
  13803.     extern int priority;
  13804.     int n;
  13805.  
  13806.     setint();
  13807.     SetThreadPrty(priority,isWin95() ? 3 : 11);
  13808.  
  13809.     while ( !sstelnet && TELOPT_U(TELOPT_FORWARD_X) ||
  13810.             sstelnet && TELOPT_ME(TELOPT_FORWARD_X))
  13811.     {
  13812.         FD_ZERO(&ifds);
  13813.         n = fwdx_init_fd_set(&ifds);
  13814.         if (n > 0) {
  13815.             tv.tv_sec = 0;
  13816.             tv.tv_usec = 2500;
  13817.             if ( select(FD_SETSIZE, &ifds, NULL, NULL, &tv) > 0 )
  13818.                 fwdx_check_sockets(&ifds);
  13819.  
  13820.         } else if (n < 0) {
  13821.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.thread_started = 0;
  13822.             ckThreadEnd(NULL);
  13823.         } else {
  13824.             sleep(1);
  13825.         }
  13826.     }
  13827. }
  13828. #endif /* NT */
  13829. #endif /* CK_FORWARD_X */
  13830. #endif /* TNCODE */
  13831. #endif /* NETCONN */
  13832.