home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / cku206.zip / ckcnet.c < prev    next >
C/C++ Source or Header  |  2002-10-31  |  453KB  |  14,079 lines

  1. char *cknetv = "Network support, 8.0.271, 24 Oct 2002";
  2.  
  3. /*  C K C N E T  --  Network support  */
  4.  
  5. /*
  6.   Copyright (C) 1985, 2002,
  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. _PROTOTYP( int rlog_ctrl, (CHAR *, int) );
  289. _PROTOTYP( static int rlog_oob, (CHAR *, int) );
  290. #ifndef TCPIPLIB
  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. int rlog_inband = 0;
  299. #endif /* RLOGCODE */
  300.  
  301. #ifndef NOICP
  302. extern int doconx;                      /* CONNECT-class command active */
  303. #endif /* NOICP */
  304.  
  305. #ifdef IBMX25
  306. /* This variable should probably be generalised for true client/server
  307.  * support - ie: the fd of the listening server, accepted calls should
  308.  * be forked or at least handled via a second fd (for IBM's X.25 -
  309.  * ttyfd always holds the active fd - ie the server becomes inactive
  310.  * as long as a client is connected, and becomes active again when the
  311.  * connection is closed)
  312.  */
  313. int x25serverfd = 0;            /* extern in ckcnet.h */
  314. int x25seqno = 0;               /* Connection sequence number */
  315. int x25lastmsg = -1;            /* A cheapskate's state table */
  316.  
  317. #define X25_CLOSED      0       /* Default state: no connection, no STREAM */
  318. #define X25_SETUP       1       /* X.25 has been set up (no connection) */
  319. #define X25_CONNECTED   2       /* X.25 connection has been established */
  320. int x25_state = X25_CLOSED;     /* Default state */
  321. #endif /* IBMX25 */
  322.  
  323. #ifndef DEBUG
  324. #define deblog 0
  325. #endif /* DEBUG */
  326.  
  327. #ifdef CK_NAWS                          /* Negotiate About Window Size */
  328. #ifdef RLOGCODE
  329. _PROTOTYP( int rlog_naws, (void) );
  330. #endif /* RLOGCODE */
  331. #endif /* CK_NAWS */
  332.  
  333. #ifdef OS2                              /* For terminal type name string */
  334. #include "ckuusr.h"
  335. #ifndef NT
  336. #include <os2.h>
  337. #undef COMMENT
  338. #endif /* NT */
  339. #include "ckocon.h"
  340. extern int tt_type, max_tt;
  341. extern struct tt_info_rec tt_info[];
  342. extern char ttname[];
  343. #else
  344. #ifdef CK_AUTHENTICATION
  345. #include "ckuusr.h"
  346. #endif /* CK_AUTHENTICATION */
  347. #endif /* OS2 */
  348.  
  349. #ifdef NT
  350. extern int winsock_version;
  351. #endif /* NT */
  352.  
  353. #ifdef CK_AUTHENTICATION
  354. #include "ckuath.h"
  355. #endif /* CK_AUTHENTICATION */
  356.  
  357. #include "ckcsig.h"
  358.  
  359. #ifndef OS2                             /* For timeout longjumps */
  360. static ckjmpbuf njbuf;
  361. #endif /* OS2 */
  362.  
  363. #define NAMECPYL 1024                   /* Local copy of hostname */
  364. char namecopy[NAMECPYL];                /* Referenced by ckctel.c */
  365. char namecopy2[NAMECPYL];        /* Referenced by ckctel.c */
  366. #ifndef NOHTTP
  367. char http_host_port[NAMECPYL];          /* orig host/port necessary for http */
  368. char http_ip[20] = { '\0' };            /* ip address of host */
  369. char http_port = 0;
  370. int  http_ssl = 0;
  371. int  httpfd = -1;                       /* socket for http connections */
  372. int  http_code = 0;
  373. #define HTTPBUFLEN  1024
  374. char http_reply_str[HTTPBUFLEN] = "";
  375. #endif /* NOHTTP */
  376.  
  377. char ipaddr[20] = { '\0' };             /* Global copy of IP address */
  378. unsigned long myxipaddr = 0L;           /* Ditto as a number */
  379. #endif /* NETCONN */
  380.  
  381. char *tcp_address = NULL;               /* Preferred IP Address */
  382. extern char uidbuf[];                   /* User ID buffer */
  383. extern char pwbuf[];                    /* Password buffer */
  384.  
  385. #ifndef NOHTTP
  386. char * tcp_http_proxy = NULL;           /* Name[:port] of http proxy server */
  387. int    tcp_http_proxy_errno = 0;
  388. char * tcp_http_proxy_user = NULL;
  389. char * tcp_http_proxy_pwd  = NULL;
  390. #define HTTPCPYL 1024
  391. static char proxycopy[HTTPCPYL];
  392. #endif /* NOHTTP */
  393.  
  394. #ifdef OS2
  395. extern int tt_rows[], tt_cols[];
  396. extern int tt_status[VNUM];
  397. #else /* OS2 */
  398. extern int tt_rows, tt_cols;            /* Everybody has this */
  399. #endif /* OS2 */
  400.  
  401. extern int cmd_cols, cmd_rows;
  402.  
  403. #ifdef STREAMING                        /* Use blocking writes for streaming */
  404. extern int streaming;
  405. #endif /* STREAMING */
  406.  
  407. #ifdef NT
  408. extern int WSASafeToCancel;
  409. int win95selectbug = 0;                 /* For TCP/IP stacks whose select() */
  410. /* always fails on write requests such as Cisco and Quarterdeck */
  411. #define stricmp _stricmp
  412. #endif /* NT */
  413.  
  414. #ifndef NOTCPOPTS
  415.  
  416. /* Skip all this if NOTCPOPTS specified. */
  417.  
  418. #ifdef SOL_SOCKET
  419.  
  420. #ifdef TCP_NODELAY
  421. int tcp_nodelay = 0;                    /* Nagle algorithm TCP_NODELAY */
  422. #endif /* TCP_NODELAY */
  423.  
  424. #ifdef SO_DONTROUTE
  425. int tcp_dontroute = 0;
  426. #endif /* SO_DONTROUTE */
  427.  
  428. #ifdef SO_LINGER
  429. int tcp_linger  = 0;                    /* SO_LINGER */
  430. int tcp_linger_tmo = 0;                 /* SO_LINGER timeout */
  431. #endif /* SO_LINGER */
  432.  
  433. #ifdef HPUX                             /* But the data structures */
  434. #ifndef HPUX8                           /* needed for linger are not */
  435. #ifndef HPUX9                           /* defined in HP-UX versions */
  436. #ifndef HPUX10                          /* prior to 8.00. */
  437. #ifdef SO_LINGER
  438. #undef SO_LINGER
  439. #endif /* SO_LINGER */
  440. #endif /* HPUX10 */
  441. #endif /* HPUX9 */
  442. #endif /* HPUX8 */
  443. #endif /* HPUX */
  444.  
  445. #ifndef SO_OOBINLINE                    /* Hopefully only HP-UX 7.0 */
  446. #define SO_OOBINLINE 0x0100
  447. #endif /* SO_OOBINLINE */
  448.  
  449. #ifndef TCPSNDBUFSIZ
  450. #ifdef VMS
  451. #ifdef __alpha
  452. #define TCPSNDBUFSIZ 16384
  453. #endif /* __alpha */
  454. #endif /* VMS */
  455. #endif /* TCPSNDBUFSIZ */
  456.  
  457. #ifndef TCPSNDBUFSIZ
  458. #define TCPSNDBUFSIZ -1
  459. #endif /* TCPSNDBUFSIZ */
  460.  
  461. #ifdef SO_SNDBUF
  462. int tcp_sendbuf = TCPSNDBUFSIZ;
  463. #endif /* SO_SNDBUF */
  464.  
  465. #ifdef SO_RCVBUF
  466. int tcp_recvbuf = -1;
  467. #endif /* SO_RCVBUF */
  468.  
  469. #ifdef SO_KEEPALIVE
  470. int tcp_keepalive = 1;
  471. #endif /* SO_KEEPALIVE */
  472.  
  473. #endif /* SOL_SOCKET */
  474. #endif /* NOTCPOPTS */
  475.  
  476. #ifndef NETCONN
  477. /*
  478.   Network support not defined.
  479.   Dummy functions here in case #ifdef's forgotten elsewhere.
  480. */
  481. int                                     /* Open network connection */
  482. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  483.     return(-1);
  484. }
  485. int                                     /* Close network connection */
  486. netclos() {
  487.     return(-1);
  488. }
  489. int                                     /* Check network input buffer */
  490. nettchk() {
  491.     return(-1);
  492. }
  493. int                                     /* Flush network input buffer */
  494. netflui() {
  495.     return(-1);
  496. }
  497. int                                     /* Send network BREAK */
  498. netbreak() {
  499.     return(-1);
  500. }
  501. int                                     /* Input character from network */
  502. netinc(timo) int timo; {
  503.     return(-1);
  504. }
  505. int                                     /* Output character to network */
  506. #ifdef CK_ANSIC
  507. nettoc(CHAR c)
  508. #else
  509. nettoc(c) CHAR c;
  510. #endif /* CK_ANSIC */
  511. /* nettoc */ {
  512.     return(-1);
  513. }
  514. int
  515. nettol(s,n) CHAR *s; int n; {
  516.     return(-1);
  517. }
  518.  
  519. #else /* NETCONN is defined (much of this module...) */
  520.  
  521. #ifdef NETLEBUF
  522. VOID
  523. le_init() {                             /* LocalEchoInit() */
  524.     int i;
  525.     for (i = 0; i < LEBUFSIZ; i++)
  526.       le_buf[i] = '\0';
  527.     le_start = 0;
  528.     le_end = 0;
  529.     le_data = 0;
  530.     tt_push_inited = 1;
  531. }
  532.  
  533. VOID
  534. le_clean() {                            /* LocalEchoCleanup() */
  535.     le_init();
  536.     return;
  537. }
  538.  
  539. int
  540. le_inbuf() {
  541.     int rc = 0;
  542.     if (le_start != le_end) {
  543.         rc = (le_end -
  544.               le_start +
  545.               LEBUFSIZ) % LEBUFSIZ;
  546.     }
  547.     return(rc);
  548. }
  549.  
  550. int
  551. #ifdef CK_ANSIC
  552. le_putchar(CHAR ch)
  553. #else
  554. le_putchar(ch) CHAR ch;
  555. #endif /* CK_ANSIC */
  556. /* le_putchar */ {
  557.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  558.         debug(F110,"le_putchar","buffer is full",0);
  559.         return(-1);
  560.     }
  561.     le_buf[le_end++] = ch;
  562.     if (le_end == LEBUFSIZ)
  563.       le_end = 0;
  564.     le_data = 1;
  565.     return(0);
  566. }
  567.  
  568. int
  569. #ifdef CK_ANSIC
  570. le_puts(CHAR * s, int n)
  571. #else
  572. le_puts(s,n) CHAR * s; int n;
  573. #endif /* CK_ANSIC */
  574. /* le_puts */ {
  575.     int rc = 0;
  576.     int i = 0;
  577.     CHAR * p = (CHAR *)"le_puts";
  578.     hexdump(p,s,n);
  579.     for (i = 0; i < n; i++)
  580.       rc = le_putchar((char)s[i]);
  581.     debug(F101,"le_puts","",rc);
  582.     return(rc);
  583. }
  584.  
  585. int
  586. #ifdef CK_ANSIC
  587. le_putstr(CHAR * s)
  588. #else
  589. le_putstr(s) CHAR * s;
  590. #endif /* CK_ANSIC */
  591. /* le_puts */ {
  592.     CHAR * p;
  593.     int rc = 0;
  594.     p = (CHAR *)"le_putstr";
  595.     hexdump(p,s,(int)strlen((char *)s));
  596.     for (p = s; *p && !rc; p++)
  597.       rc = le_putchar(*p);
  598.     return(rc);
  599. }
  600.  
  601. int
  602. #ifdef CK_ANSIC
  603. le_getchar(CHAR * pch)
  604. #else /* CK_ANSIC */
  605. le_getchar(pch) CHAR * pch;
  606. #endif /* CK_ANSIC */
  607. /* le_gatchar */ {
  608.     int rc = 0;
  609.     if (le_start != le_end) {
  610.         *pch = le_buf[le_start];
  611.         le_buf[le_start] = 0;
  612.         le_start++;
  613.  
  614.         if (le_start == LEBUFSIZ)
  615.           le_start = 0;
  616.  
  617.         if (le_start == le_end) {
  618.             le_data = 0;
  619.         }
  620.         rc++;
  621.     } else {
  622.         *pch = 0;
  623.     }
  624.     return(rc);
  625. }
  626. #endif /* NETLEBUF */
  627.  
  628. #ifdef VMS
  629. /*
  630.   In edit 190, we moved tn_ini() to be called from within netopen().
  631.   But tn_ini() calls ttol(), and ttol() checks to see if it's a net
  632.   connection, but the flag for that isn't set until after netopen()
  633.   is finished.  Since, in this module, we are always doing network
  634.   output anyway, we just call nettol() directly, instead of going thru
  635.   ttol().  Only needed for VMS, since UNIX, AOS/VS, and VOS can handle
  636.   net connections just like regular connections in ttol(), and OS/2
  637.   has a special routine for this.
  638. */
  639. #define ttol nettol
  640. #endif /* VMS */
  641.  
  642. int tcpsrfd = -1;
  643.  
  644. #ifdef CK_KERBEROS
  645.  
  646. char * krb5_d_principal = NULL;         /* Default principal */
  647. char * krb5_d_instance = NULL;          /* Default instance */
  648. char * krb5_d_realm = NULL;             /* Default realm */
  649. char * krb5_d_cc = NULL;                /* Default credentials cache */
  650. char * krb5_d_srv   = NULL;             /* Default Service */
  651. int    krb5_d_lifetime = 600;           /* Default lifetime (10 hours) */
  652. int    krb5_d_forwardable = 0;          /* creds not forwardable */
  653. int    krb5_d_proxiable = 0;            /* creds not proxiable */
  654. int    krb5_d_renewable = 0;            /* creds not renewable (0 min) */
  655. int    krb5_autoget = 1;                /* Autoget TGTs */
  656. int    krb5_autodel = 0;                /* Auto delete TGTs */
  657. int    krb5_d_getk4 = 0;                /* K5 Kinit gets K4 TGTs */
  658. int    krb5_checkaddrs = 1;             /* Check TGT Addrs */
  659. int    krb5_d_no_addresses = 0;         /* Do not include IP Addresses */
  660. char * krb5_d_addrs[KRB5_NUM_OF_ADDRS+1]={NULL,NULL}; /* Addrs to include */
  661. int    krb5_errno = 0;                  /* Last K5 errno */
  662. char * krb5_errmsg = NULL;              /* Last K5 errmsg */
  663. char * k5_keytab = NULL;
  664.  
  665. char * krb4_d_principal = NULL;         /* Default principal */
  666. char * krb4_d_realm = NULL;             /* Default realm */
  667. char * krb4_d_srv   = NULL;             /* Default Service */
  668. int    krb4_d_lifetime = 600;           /* Default lifetime (10 hours) */
  669. int    krb4_d_preauth = 1;              /* Use preauth requests */
  670. char * krb4_d_instance = NULL;          /* Default instance */
  671. int    krb4_autoget = 1;                /* Autoget TGTs */
  672. int    krb4_autodel = 0;                /* Auto delete TGTs */
  673. int    krb4_checkaddrs = 1;             /* Check TGT Addrs */
  674. char * k4_keytab = NULL;
  675.  
  676. int    krb4_errno = 0;                  /* Last K4 errno */
  677. char * krb4_errmsg = NULL;              /* Last K4 errmsg */
  678.  
  679. struct krb_op_data krb_op = {           /* Operational data structure */
  680.     0, NULL                             /* (version, cachefile) */
  681. };
  682.  
  683. struct krb4_init_data krb4_init = {     /* Kerberos 4 INIT data structure */
  684.     0, NULL, NULL, NULL, NULL
  685. };
  686.  
  687. struct krb5_init_data krb5_init = {     /* Kerberos 5 INIT data structure */
  688.     0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0,
  689.     { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  690.       NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
  691.     0
  692. };
  693.  
  694. struct krb5_list_cred_data krb5_lc = {  /* List Credentials data structure */
  695.     0, 0, 0
  696. };
  697.  
  698. int krb_action = -1;                    /* Kerberos action to perform */
  699.  
  700. #ifndef CK_AUTHENTICATION
  701. char *
  702. ck_krb4_getrealm() {
  703.     return("");
  704. }
  705. char *
  706. ck_krb5_getrealm(cc) char * cc; {
  707.     return("");
  708. }
  709. char *
  710. ck_krb4_getprincipal() {
  711.     return("");
  712. }
  713. char *
  714. ck_krb5_getprincipal(cc) char * cc; {
  715.     return("");
  716. }
  717. #endif /* CK_AUTHENTICATION */
  718.  
  719. /*  I N I _ K E R B  --  Initialize Kerberos data  */
  720.  
  721. VOID
  722. ini_kerb() {
  723.     int i;
  724.  
  725.     krb_action = -1;                    /* No action specified */
  726.  
  727.     krb_op.version = 0;                 /* Kerberos version (none) */
  728.     krb_op.cache = NULL;                /* Cache file (none) */
  729.  
  730. /* Kerberos 5 */
  731.  
  732.     krb5_init.forwardable = krb5_d_forwardable; /* Init switch values... */
  733.     krb5_init.proxiable   = krb5_d_proxiable;
  734.     krb5_init.lifetime    = krb5_d_lifetime;
  735.     krb5_init.renew       = 0;
  736.     krb5_init.renewable   = krb5_d_renewable;
  737.     krb5_init.validate    = 0;
  738.     krb5_init.no_addresses = krb5_d_no_addresses;
  739.     if (krb5_init.postdate) {
  740.         free(krb5_init.postdate);
  741.         krb5_init.postdate = NULL;
  742.     }
  743.     if (krb5_init.service) {
  744.         free(krb5_init.service);
  745.         krb5_init.service = NULL;
  746.     }
  747.     if (!krb5_d_cc || !krb5_d_cc[0]) {  /* Set default cache */
  748.         char * p;
  749.         p = ck_krb5_get_cc_name();
  750.         makestr(&krb5_d_cc,(p && p[0]) ? p : NULL);
  751.     }
  752.     if (!krb5_d_realm || !krb5_d_realm[0]) { /* Set default realm */
  753.         char * p;
  754.         p = ck_krb5_getrealm(krb5_d_cc);
  755.         makestr(&krb5_d_realm,(p && p[0]) ? p : NULL);
  756.     }
  757.     makestr(&krb5_init.instance,krb5_d_instance);
  758.     makestr(&krb5_init.realm,krb5_d_realm); /* Set realm from default */
  759.     if (krb5_init.password) {
  760.         memset(krb5_init.password,0xFF,strlen(krb5_init.password));
  761.         free(krb5_init.password);
  762.         krb5_init.password = NULL;
  763.     }
  764.     if (!krb5_d_principal) {            /* Default principal */
  765.         /* a Null principal indicates the user should be prompted */
  766.         char * p = ck_krb5_getprincipal(krb5_d_cc);
  767.         if (!p || !(*p))
  768.           p = (char *)uidbuf;           /* Principal = user */
  769.                 makestr(&krb5_d_principal,(p && p[0]) ? p : NULL);
  770.     }
  771.     makestr(&krb5_init.principal,krb5_d_principal);
  772.     for (i = 0; i <= KRB5_NUM_OF_ADDRS; i++) {
  773.         if (krb5_init.addrs[i])
  774.           free(krb5_init.addrs[i]);
  775.         krb5_init.addrs[i] = NULL;
  776.     }
  777.     for (i = 0; i <= KRB5_NUM_OF_ADDRS && krb5_d_addrs[i]; i++) {
  778.         makestr(&krb5_init.addrs[i],krb5_d_addrs[i]);
  779.     }
  780.  
  781.     /* Kerberos 4 */
  782.  
  783.     krb4_init.lifetime = krb4_d_lifetime;
  784.     krb4_init.preauth  = krb4_d_preauth;
  785.     makestr(&krb4_init.instance,krb4_d_instance);
  786.     if (!krb4_d_realm || !krb4_d_realm[0]) {/* Set default realm */
  787.         char * p;
  788.         p = ck_krb4_getrealm();
  789.                 makestr(&krb4_d_realm,(p && p[0]) ? p : NULL);
  790.     }
  791.     makestr(&krb4_init.realm,krb4_d_realm);
  792.     if (krb4_init.password) {
  793.         memset(krb4_init.password,0xFF,strlen(krb4_init.password));
  794.         free(krb4_init.password);
  795.         krb4_init.password = NULL;
  796.     }
  797.     if (!krb4_d_principal) {            /* Default principal */
  798.         /* a Null principal indicates the user should be prompted */
  799.         char * p = ck_krb4_getprincipal();
  800.         if (!p || !(*p))
  801.           p = (char *)uidbuf;           /* Principal = user */
  802.         makestr(&(krb4_d_principal),(p && p[0]) ? p : NULL);
  803.     }
  804.     makestr(&(krb4_init.principal),krb4_d_principal);
  805. }
  806.  
  807. /*  D O A U T H  --  AUTHENTICATE action routine  */
  808.  
  809. int
  810. doauth(cx) int cx; {                    /* AUTHENTICATE action routine */
  811.     int rc = 0;                         /* Return code */
  812.  
  813. #ifdef CK_AUTHENTICATION
  814. #ifdef OS2
  815.     if (!ck_security_loaddll())         /* Load various DLLs */
  816.       return(rc);
  817. #endif /* OS2 */
  818.     if (krb_op.version == 4) {          /* Version = 4 */
  819. #ifdef COMMENT
  820.         sho_auth(AUTHTYPE_KERBEROS_V4);
  821. #endif /* COMMENT */
  822.         if (!ck_krb4_is_installed()) {
  823.             printf("?Kerberos 4 is not installed\n");
  824.             return(0);
  825.         }
  826.         switch (krb_action) {           /* Perform V4 functions */
  827.           case KRB_A_IN:                /* INIT */
  828.             rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
  829.             break;
  830.           case KRB_A_DE:                /* DESTROY */
  831.             rc |= !(ck_krb4_destroy(&krb_op) < 0);
  832.             break;
  833.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  834.             rc |= !(ck_krb4_list_creds(&krb_op) < 0);
  835.             break;
  836.         }
  837.     }
  838.     if (krb_op.version == 5) {          /* V5 functions */
  839. #ifdef COMMENT
  840.         sho_auth(AUTHTYPE_KERBEROS_V5);
  841. #endif /* COMMENT */
  842.         if (!ck_krb5_is_installed()) {
  843.             printf("?Kerberos 5 is not installed\n");
  844.             return(0);
  845.         }
  846.         switch (krb_action) {
  847.           case KRB_A_IN:                /* INIT */
  848.             rc |= !(ck_krb5_initTGT(&krb_op,&krb5_init,
  849.                                      krb5_init.getk4 ? &krb4_init : 0) < 0);
  850.             break;
  851.           case KRB_A_DE:                /* DESTROY */
  852.             rc |= !(ck_krb5_destroy(&krb_op) < 0);
  853.             break;
  854.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  855.             if (krb_op.version == 0)
  856.               printf("\n");
  857.             rc |= !(ck_krb5_list_creds(&krb_op,&krb5_lc) < 0);
  858.             break;
  859.         }
  860.     }
  861. #else
  862. #ifndef NOICP
  863. #ifndef NOSHOW
  864.     rc = sho_auth(0);                   /* Show all */
  865. #endif /* NOSHOW */
  866. #endif /* NOICP */
  867. #endif /* CK_AUTHENTICATION */
  868.     return(rc);
  869. }
  870. #endif /* CK_KERBEROS */
  871.  
  872. #ifdef TCPSOCKET
  873. #ifndef OS2
  874. #ifndef NOLISTEN                        /* For incoming connections */
  875.  
  876. #ifndef INADDR_ANY
  877. #define INADDR_ANY 0
  878. #endif /* INADDR_ANY */
  879.  
  880. _PROTOTYP( int ttbufr, ( VOID ) );
  881. _PROTOTYP( int tcpsrv_open, (char *, int *, int, int ) );
  882.  
  883. static unsigned short tcpsrv_port = 0;
  884.  
  885. #endif /* NOLISTEN */
  886. #endif /* OS2 */
  887.  
  888. static char svcbuf[80];                 /* TCP service string */
  889. static int svcnum = 0;                  /* TCP port number */
  890.  
  891. #endif /* TCPSOCKET */
  892.  
  893. /*
  894.   TCPIPLIB means use separate socket calls for i/o, while on UNIX the
  895.   normal file system calls are used for TCP/IP sockets too.
  896.   Means "DEC_TCPIP or MULTINET or WINTCP or OS2 or BEBOX" (see ckcnet.h),
  897. */
  898.  
  899. #ifdef TCPIPLIB
  900.  
  901. /* For buffered network reads... */
  902. /*
  903.   If the buffering code is written right, it shouldn't matter
  904.   how long this buffer is.
  905. */
  906. #ifdef OS2
  907. #ifdef NT
  908. #define TTIBUFL 64240                   /* 44 * 1460 (MSS) */
  909. #else
  910. #define TTIBUFL 32120                   /* 22 * 1460 (MSS) */
  911. #endif /* NT */
  912. #else /* OS2 */
  913. #define TTIBUFL 8191                    /* Let's use 8K. */
  914. #endif /* OS2 */
  915.  
  916. CHAR ttibuf[TTIBUFL+1];
  917.  
  918. /*
  919.   select() is used in preference to alarm()/signal(), but different systems
  920.   use different forms of select()...
  921. */
  922. #ifndef NOSELECT         /* Option to override BSDSELECT */
  923. #ifdef BELLV10
  924. /*
  925.   Note: Although BELLV10 does have TCP/IP support, and does use the unique
  926.   form of select() that is evident in this module (and in ckutio.c), it does
  927.   not have a sockets library and so we can't build Kermit TCP/IP support for
  928.   it.  For this, somebody would have to write TCP/IP streams code.
  929. */
  930. #define BELLSELECT
  931. #ifndef FD_SETSIZE
  932. #define FD_SETSIZE 128
  933. #endif /* FD_SETSIZE */
  934. #else
  935. #ifdef WINTCP                           /* VMS with Wollongong WIN/TCP */
  936. #ifndef OLD_TWG                         /* TWG 3.2 has only select(read) */
  937. #define BSDSELECT
  938. #endif /* OLD_TWG */
  939. #else
  940. #ifdef CMU_TCPIP                        /* LIBCMU can do select */
  941. #define BSDSELECT
  942. #else
  943. #ifdef DEC_TCPIP
  944. #define BSDSELECT
  945. #else
  946. #ifdef OS2                              /* OS/2 with TCP/IP */
  947. #ifdef NT
  948. #define BSDSELECT
  949. #else /* NT */
  950. #define IBMSELECT
  951. #endif /* NT */
  952. #endif /* OS2 */
  953. #endif /* DEC_TCPIP */
  954. #endif /* CMU_TCPIP */
  955. #endif /* WINTCP */
  956. #endif /* BELLV10 */
  957. #endif /* NOSELECT */
  958. /*
  959.   Others (TGV, TCPware, ...) use alarm()/signal().  The BSDSELECT case does not
  960.   compile at all; the IBMSELECT case compiles and links but crashes at runtime.
  961.   NOTE: If any of these can be converted to select(), they should be for two
  962.   reasons: (1) It's a lot faster; (2) certain sockets libraries do not like
  963.   their socket_read() calls to be interrupted; subsequent socket_read()'s tend
  964.   to fail with EBUSY.  This happened in the UCX case before it was converted
  965.   to use select().
  966. */
  967. #ifndef OS2
  968. #ifndef VMS
  969. static                                  /* These are used in CKVTIO.C */
  970. #endif /* VMS */                        /* And in CKONET.C            */
  971. #endif /* OS2 */
  972. int
  973.   ttibp = 0,
  974.   ttibn = 0;
  975. /*
  976.   Read bytes from network into internal buffer ttibuf[].
  977.   To be called when input buffer is empty, i.e. when ttibn == 0.
  978.  
  979.   Other network reading routines, like ttinc, ttinl, ttxin, should check the
  980.   internal buffer first, and call this routine for a refill if necessary.
  981.  
  982.   Returns -1 on error, 0 if nothing happens.  When data is read successfully,
  983.   returns number of bytes read, and sets global ttibn to that number and
  984.   ttibp (the buffer pointer) to zero.
  985. */
  986. _PROTOTYP( int ttbufr, ( VOID ) );
  987. int
  988. ttbufr() {                              /* TT Buffer Read */
  989.     int count;
  990.  
  991.     if (ttnet != NET_TCPB)              /* First make sure current net is */
  992.       return(-1);                       /* TCP/IP; if not, do nothing. */
  993.  
  994. #ifdef OS2
  995.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  996. #endif /* OS2 */
  997.  
  998.     if (ttibn > 0) {                    /* Our internal buffer is not empty, */
  999. #ifdef OS2
  1000.         ReleaseTCPIPMutex();
  1001. #endif /* OS2 */
  1002.         return(ttibn);                  /* so keep using it. */
  1003.     }
  1004.  
  1005.     if (ttyfd == -1) {                  /* No connection, error */
  1006. #ifdef OS2
  1007.         ReleaseTCPIPMutex();
  1008. #endif /* OS2 */
  1009.         return(-2);
  1010.     }
  1011.  
  1012.     ttibp = 0;                          /* Else reset pointer to beginning */
  1013.  
  1014. #ifdef WINTCP
  1015.     count = 512;                        /* This works for WIN/TCP */
  1016. #else
  1017. #ifdef DEC_TCPIP
  1018.     count = 512;                        /* UCX */
  1019. #else
  1020. #ifdef OS2
  1021.     count = TTIBUFL;
  1022. #else                                   /* Multinet, etc. */
  1023.     count = ttchk();                    /* Check network input buffer, */
  1024.     if (ttibn > 0) {                    /* which can put a char there! */
  1025.         debug(F111,"ttbufr","ttchk() returns",count);
  1026. #ifdef OS2
  1027.         ReleaseTCPIPMutex();
  1028. #endif /* OS2 */
  1029.         return(ttibn);
  1030.     }
  1031.     if (count < 0) {                     /* Read error - connection closed */
  1032. #ifdef OS2
  1033.         ReleaseTCPIPMutex();
  1034. #endif /* OS2 */
  1035.         return(-2);
  1036.     }
  1037.     else if (count > TTIBUFL)           /* Too many to read */
  1038.       count = TTIBUFL;
  1039.     else if (count == 0)                /* None, so force blocking read */
  1040.       count = 1;
  1041. #endif /* OS2 */
  1042. #endif /* DEC_TCPIP */
  1043. #endif /* WINTCP */
  1044.     debug(F101,"ttbufr count 1","",count);
  1045.  
  1046. #ifdef CK_SSL
  1047.     if (ssl_active_flag || tls_active_flag) {
  1048.         int error;
  1049.         if (ssl_active_flag)
  1050.           count = SSL_read(ssl_con, ttibuf, count);
  1051.         else
  1052.           count = SSL_read(tls_con, ttibuf, count);
  1053.         error = SSL_get_error(ssl_active_flag?ssl_con:tls_con,count);
  1054.         switch (error) {
  1055.           case SSL_ERROR_NONE:
  1056.             debug(F111,"ttbufr SSL_ERROR_NONE","count",count);
  1057.             if (count > 0) {
  1058.                 ttibp = 0;              /* Reset buffer pointer. */
  1059.                 ttibn = count;
  1060. #ifdef OS2
  1061.                 ReleaseTCPIPMutex();
  1062. #endif /* OS2 */
  1063.                 return(ttibn);          /* Return buffer count. */
  1064.             } else if (count < 0) {
  1065. #ifdef OS2
  1066.                 ReleaseTCPIPMutex();
  1067. #endif /* OS2 */
  1068.                 return(-1);
  1069.             } else {
  1070.                 netclos();
  1071. #ifdef OS2
  1072.                 ReleaseTCPIPMutex();
  1073. #endif /* OS2 */
  1074.                 return(-2);
  1075.             }
  1076.           case SSL_ERROR_WANT_WRITE:
  1077.             debug(F100,"ttbufr SSL_ERROR_WANT_WRITE","",0);
  1078. #ifdef OS2
  1079.               ReleaseTCPIPMutex();
  1080. #endif /* OS2 */
  1081.             return(-1);
  1082.           case SSL_ERROR_WANT_READ:
  1083.             debug(F100,"ttbufr SSL_ERROR_WANT_READ","",0);
  1084. #ifdef OS2
  1085.               ReleaseTCPIPMutex();
  1086. #endif /* OS2 */
  1087.             return(-1);
  1088.           case SSL_ERROR_SYSCALL:
  1089.               if ( count == 0 ) { /* EOF */
  1090.                   netclos();
  1091. #ifdef OS2
  1092.                   ReleaseTCPIPMutex();
  1093. #endif /* OS2 */
  1094.                   return(-2);
  1095.               } else {
  1096.                   int rc = -1;
  1097. #ifdef NT
  1098.                   int gle = GetLastError();
  1099.                   debug(F111,"ttbufr SSL_ERROR_SYSCALL",
  1100.                          "GetLastError()",gle);
  1101.                   rc = os2socketerror(gle);
  1102.                   if (rc == -1)
  1103.                       rc = -2;
  1104.                   else if ( rc == -2 )
  1105.                       return -1;
  1106. #endif /* NT */
  1107. #ifdef OS2
  1108.                   ReleaseTCPIPMutex();
  1109. #endif /* OS2 */
  1110.                   return(rc);
  1111.               }
  1112.           case SSL_ERROR_WANT_X509_LOOKUP:
  1113.             debug(F100,"ttbufr SSL_ERROR_WANT_X509_LOOKUP","",0);
  1114.             netclos();
  1115. #ifdef OS2
  1116.               ReleaseTCPIPMutex();
  1117. #endif /* OS2 */
  1118.             return(-2);
  1119.           case SSL_ERROR_SSL:
  1120.               if (bio_err!=NULL) {
  1121.                   int len;
  1122.                   extern char ssl_err[];
  1123.                   BIO_printf(bio_err,"ttbufr SSL_ERROR_SSL\n");
  1124.                   ERR_print_errors(bio_err);
  1125.                   len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
  1126.                   ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
  1127.                   debug(F110,"ttbufr SSL_ERROR_SSL",ssl_err,0);
  1128.                   if (ssl_debug_flag)                  
  1129.                       printf(ssl_err);
  1130.               } else if (ssl_debug_flag) {
  1131.                   debug(F100,"ttbufr SSL_ERROR_SSL","",0);
  1132.                   fflush(stderr);
  1133.                   fprintf(stderr,"ttbufr SSL_ERROR_SSL\n");
  1134.                   ERR_print_errors_fp(stderr);
  1135.               }
  1136. #ifdef COMMENT
  1137.             netclos();
  1138. #endif /* COMMENT */
  1139. #ifdef OS2
  1140.               ReleaseTCPIPMutex();
  1141. #endif /* OS2 */
  1142.             return(-2);
  1143.           case SSL_ERROR_ZERO_RETURN:
  1144.             debug(F100,"ttbufr SSL_ERROR_ZERO_RETURN","",0);
  1145.             netclos();
  1146. #ifdef OS2
  1147.               ReleaseTCPIPMutex();
  1148. #endif /* OS2 */
  1149.             return(-2);
  1150.           default:
  1151.               debug(F100,"ttbufr SSL_ERROR_?????","",0);
  1152.               netclos();
  1153. #ifdef OS2
  1154.               ReleaseTCPIPMutex();
  1155. #endif /* OS2 */
  1156.               return(-2);
  1157.           }
  1158.     }
  1159. #endif /* CK_SSL */
  1160.  
  1161. #ifdef COMMENT
  1162. /*
  1163.  This is for nonblocking reads, which we don't do any more.  This code didn't
  1164.  work anyway, in the sense that a broken connection was never sensed.
  1165. */
  1166.     if ((count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count)) < 1) {
  1167.         if (count == -1 && socket_errno == EWOULDBLOCK) {
  1168.             debug(F100,"ttbufr finds nothing","",0);
  1169. #ifdef OS2
  1170.             ReleaseTCPIPMutex();
  1171. #endif /* OS2 */
  1172.             return(0);
  1173.         } else {
  1174.             debug(F101,"ttbufr socket_read error","",socket_errno);
  1175. #ifdef OS2
  1176.             ReleaseTCPIPMutex();
  1177. #endif /* OS2 */
  1178.             return(-1);
  1179.         }
  1180.  
  1181.     } else if (count == 0) {
  1182.         debug(F100,"ttbufr socket eof","",0);
  1183. #ifdef OS2
  1184.         ReleaseTCPIPMutex();
  1185. #endif /* OS2 */
  1186.         return(-1);
  1187.     }
  1188. #else /* COMMENT */
  1189.  
  1190. /* This is for blocking reads */
  1191.  
  1192. #ifndef VMS
  1193. #ifdef SO_OOBINLINE
  1194.     {
  1195.         int outofband = 0;
  1196. #ifdef BELLSELECT
  1197.         if (select(128, NULL, NULL, efds, 0) > 0 && FD_ISSET(ttyfd, efds))
  1198.           outofband = 1;
  1199. #else
  1200. #ifdef BSDSELECT
  1201.         fd_set efds;
  1202.         struct timeval tv;
  1203.         FD_ZERO(&efds);
  1204.         FD_SET(ttyfd, &efds);
  1205.         tv.tv_sec  = tv.tv_usec = 0L;
  1206.         debug(F100,"Out-of-Band BSDSELECT","",0);
  1207. #ifdef NT
  1208.         WSASafeToCancel = 1;
  1209. #endif /* NT */
  1210.         if (select(FD_SETSIZE, NULL, NULL, &efds, &tv) > 0 &&
  1211.             FD_ISSET(ttyfd, &efds))
  1212.           outofband = 1;
  1213. #ifdef NT
  1214.         WSASafeToCancel = 0;
  1215. #endif /* NT */
  1216. #else /* !BSDSELECT */
  1217. #ifdef IBMSELECT
  1218. /* Is used by OS/2 ... */
  1219. /* ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set */
  1220. /* and timeval stuff since this is the only place where it is used. */
  1221.         int socket = ttyfd;
  1222.         debug(F100,"Out-of-Band IBMSELECT","",0);
  1223.         if ((select(&socket, 0, 0, 1, 0L) == 1) && (socket == ttyfd))
  1224.           outofband = 1;
  1225. #else /* !IBMSELECT */
  1226. /*
  1227.   If we can't use select(), then we use the regular alarm()/signal()
  1228.   timeout mechanism.
  1229. */
  1230.       debug(F101,"Out-of-Band data not supported","",0);
  1231.       outofband = 0;
  1232.  
  1233. #endif /* IBMSELECT */
  1234. #endif /* BSDSELECT */
  1235. #endif /* BELLSELECT */
  1236.       if (outofband) {
  1237.          /* Get the Urgent Data */
  1238.          /* if OOBINLINE is disabled this should be only a single byte      */
  1239.          /* MS Winsock has a bug in Windows 95.  Extra bytes are delivered  */
  1240.          /* That were never sent.                                           */
  1241. #ifdef OS2
  1242.           RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1243. #endif /* OS2 */
  1244.           count = socket_recv(ttyfd,&ttibuf[ttibp+ttibn],count,MSG_OOB);
  1245. #ifdef OS2
  1246.           ReleaseTCPIPMutex();
  1247. #endif /* OS2 */
  1248.           if (count <= 0) {
  1249.               int s_errno = socket_errno;
  1250.               debug(F101, "ttbufr socket_recv MSG_OOB","",count);
  1251.               debug(F101, "ttbufr socket_errno","",s_errno);
  1252. #ifdef OS2ONLY
  1253.               if (count < 0 && (s_errno == 0 || s_errno == 23)) {
  1254.                   /* These appear in OS/2 - don't know why   */
  1255.                   /* ignore it and read as normal data       */
  1256.                   /* and break, then we will attempt to read */
  1257.                   /* the port using normal read() techniques */
  1258.                   debug(F100,"ttbufr handing as in-band data","",0);
  1259.                   count = 1;
  1260.               } else {
  1261.                   netclos();                    /* *** *** */
  1262. #ifdef OS2
  1263.                   ReleaseTCPIPMutex();
  1264. #endif /* OS2 */
  1265.                   return(-2);
  1266.               }
  1267. #else /* OS2ONLY */
  1268.               netclos();                        /* *** *** */
  1269. #ifdef OS2
  1270.               ReleaseTCPIPMutex();
  1271. #endif /* OS2 */
  1272.               return(-2);
  1273. #endif /* OS2ONLY */
  1274.           } else {                      /* we got out-of-band data */
  1275.               hexdump("ttbufr out-of-band chars",&ttibuf[ttibp+ttibn],count);
  1276. #ifdef BETADEBUG
  1277.               bleep(BP_NOTE);
  1278. #endif /* BETADEBUG */
  1279. #ifdef RLOGCODE                         /* blah */
  1280.               if (ttnproto == NP_RLOGIN  ||
  1281.                   ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  1282.                   ((ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) && 
  1283.                   !rlog_inband)
  1284.                    )
  1285.               {
  1286.                   /*
  1287.                     When urgent data is read with MSG_OOB and not OOBINLINE
  1288.                     then urgent data and normal data are not mixed.  So
  1289.                     treat the entire buffer as urgent data.
  1290.                   */
  1291.                   rlog_oob(&ttibuf[ttibp+ttibn], count);
  1292. #ifdef OS2
  1293.                   ReleaseTCPIPMutex();
  1294. #endif /* OS2 */
  1295.                   return ttbufr();
  1296.               } else
  1297. #endif /* RLOGCODE */ /* blah */
  1298. #ifdef COMMENT
  1299.             /*
  1300.                I haven't written this yet, nor do I know what it should do
  1301.              */
  1302.                 if (ttnproto == NP_TELNET) {
  1303.                     tn_oob();
  1304. #ifdef OS2
  1305.                     ReleaseTCPIPMutex();
  1306. #endif /* OS2 */
  1307.                     return 0;
  1308.               } else
  1309. #endif /* COMMENT */
  1310.               {
  1311.                   /* For any protocols we don't have a special out-of-band  */
  1312.                   /* handler for, just put the bytes in the normal buffer   */
  1313.                   /* and return                                             */
  1314.  
  1315.                   ttibp += 0;       /* Reset buffer pointer. */
  1316.                   ttibn += count;
  1317. #ifdef DEBUG
  1318.                   /* Got some bytes. */
  1319.                   debug(F101,"ttbufr count 2","",count);
  1320.                   if (count > 0)
  1321.                       ttibuf[ttibp+ttibn] = '\0';
  1322.                   debug(F111,"ttbufr ttibuf",ttibuf,ttibp);
  1323. #endif /* DEBUG */
  1324. #ifdef OS2
  1325.                   ReleaseTCPIPMutex();
  1326. #endif /* OS2 */
  1327.                   return(ttibn);    /* Return buffer count. */
  1328.               }
  1329.           }
  1330.       }
  1331.     }
  1332. #endif /* SO_OOBINLINE */
  1333. #endif /* VMS */
  1334.  
  1335.     count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count);
  1336.     if (count <= 0) {
  1337.         int s_errno = socket_errno;
  1338.         debug(F101,"ttbufr socket_read","",count);
  1339.         debug(F101,"ttbufr socket_errno","",s_errno);
  1340. #ifdef OS2
  1341.         if (count == 0 || os2socketerror(s_errno) < 0) {
  1342.             netclos();
  1343.             ReleaseTCPIPMutex();
  1344.             return(-2);
  1345.         }
  1346.         ReleaseTCPIPMutex();
  1347.         return(-1);
  1348. #else /* OS2 */
  1349.         netclos();                      /* *** *** */
  1350.         return(-2);
  1351. #endif /* OS2 */
  1352.     }
  1353. #endif /* COMMENT */ /* (blocking vs nonblock reads...) */
  1354.     else {
  1355.         ttibp = 0;                      /* Reset buffer pointer. */
  1356.         ttibn += count;
  1357. #ifdef DEBUG
  1358.         debug(F101,"ttbufr count 2","",count); /* Got some bytes. */
  1359.         if (count > 0)
  1360.           ttibuf[ttibp+ttibn] = '\0';
  1361.         debug(F111,"ttbufr ttibuf",&ttibuf[ttibp],ttibn);
  1362. #endif /* DEBUG */
  1363.  
  1364. #ifdef OS2
  1365.         ReleaseTCPIPMutex();
  1366. #endif /* OS2 */
  1367.         return(ttibn);                  /* Return buffer count. */
  1368.     }
  1369. }
  1370. #endif /* TCPIPLIB */
  1371.  
  1372. #ifndef IBMSELECT
  1373. #ifndef BELLSELECT
  1374. #ifndef BSDSELECT               /* Non-TCPIPLIB case */
  1375. #ifdef SELECT
  1376. #define BSDSELECT
  1377. #endif /* SELECT */
  1378. #endif /* BSDSELECT */
  1379. #endif /* BELLSELECT */
  1380. #endif /* IBMSELECT */
  1381.  
  1382. #define TELNET_PORT 23          /* Should do lookup, but it won't change */
  1383. #define RLOGIN_PORT 513
  1384. #define KERMIT_PORT 1649
  1385. #define KLOGIN_PORT 543
  1386. #define EKLOGIN_PORT 2105
  1387.  
  1388. #ifndef NONET
  1389. /*
  1390.   C-Kermit network open/close functions for BSD-sockets.
  1391.   Much of this code shared by SunLink X.25, which also uses the socket library.
  1392. */
  1393.  
  1394. /*  N E T O P N  --  Open a network connection.  */
  1395. /*
  1396.   Call with:
  1397.     name of host (or host:service),
  1398.     lcl - local-mode flag to be set if this function succeeds,
  1399.     network type - value defined in ckunet.h.
  1400. */
  1401. #ifdef TCPSOCKET
  1402. struct hostent *
  1403. #ifdef CK_ANSIC
  1404. ck_copyhostent(struct hostent * h)
  1405. #else /* CK_ANSIC */
  1406. ck_copyhostent(h) struct hostent * h;
  1407. #endif /* CK_ANSIC */
  1408. {
  1409.     /*
  1410.      *  The hostent structure is dynamic in nature.
  1411.      *  struct  hostent {
  1412.      *  char    * h_name;
  1413.      *  char    * * h_aliases;
  1414.      *  short   h_addrtype;
  1415.      *  short   h_length;
  1416.      *  char    * * h_addr_list;
  1417.      *  #define h_addr  h_addr_list[0]
  1418.      */
  1419. #define HOSTENTCNT 5
  1420.     static struct hostent hosts[HOSTENTCNT] = {{NULL,NULL,0,0,NULL},
  1421.                                                {NULL,NULL,0,0,NULL},
  1422.                                                {NULL,NULL,0,0,NULL},
  1423.                                                {NULL,NULL,0,0,NULL},
  1424.                                                {NULL,NULL,0,0,NULL}};
  1425.     static int    next = 0;
  1426.     int    i,cnt;
  1427.     char ** pp;
  1428.  
  1429.     if ( h == NULL )
  1430.         return(NULL);
  1431.  
  1432.     if (next == HOSTENTCNT)
  1433.         next = 0;
  1434.  
  1435.     if ( hosts[next].h_name ) {
  1436.         free(hosts[next].h_name);
  1437.         hosts[next].h_name = NULL;
  1438.     }
  1439.     if ( hosts[next].h_aliases ) {
  1440.         pp = hosts[next].h_aliases;
  1441.         while ( *pp ) {
  1442.             free(*pp);
  1443.             pp++;
  1444.         }
  1445.         free(hosts[next].h_aliases);
  1446.     }
  1447. #ifdef HADDRLIST
  1448.     if ( hosts[next].h_addr_list ) {
  1449.         pp = hosts[next].h_addr_list;
  1450.         while ( *pp ) {
  1451.             free(*pp);
  1452.             pp++;
  1453.         }
  1454.         free(hosts[next].h_addr_list);
  1455.     }
  1456. #endif /* HADDRLIST */
  1457.  
  1458.     makestr(&hosts[next].h_name,h->h_name);
  1459.     if (h->h_aliases) {
  1460.         for ( cnt=0,pp=h->h_aliases; pp && *pp; pp++,cnt++) ;
  1461.         /* The following can give warnings in non-ANSI builds */
  1462.         hosts[next].h_aliases = (char **) malloc(sizeof(char *) * (cnt+1));
  1463.         for ( i=0; i<cnt; i++) {
  1464.             hosts[next].h_aliases[i] = NULL;
  1465.             makestr(&hosts[next].h_aliases[i],h->h_aliases[i]);
  1466.         }
  1467.         hosts[next].h_aliases[i] = NULL;
  1468.     } else
  1469.         hosts[next].h_aliases = NULL;
  1470.  
  1471.     hosts[next].h_addrtype = h->h_addrtype;
  1472.     hosts[next].h_length = h->h_length;
  1473.  
  1474. #ifdef HADDRLIST
  1475. #ifdef h_addr
  1476.     if (h->h_addr_list) {
  1477.         for ( cnt=0,pp=h->h_addr_list; pp && *pp; pp++,cnt++) ;
  1478.         /* The following can give warnings non-ANSI builds */
  1479.         hosts[next].h_addr_list = (char **) malloc(sizeof(char *) * (cnt+1));
  1480.         for ( i=0; i<cnt; i++) {
  1481.             hosts[next].h_addr_list[i] = malloc(h->h_length);
  1482.             bcopy(h->h_addr_list[i],hosts[next].h_addr_list[i],h->h_length);
  1483.         }
  1484.         hosts[next].h_addr_list[i] = NULL;
  1485.     } else
  1486.         hosts[next].h_addr_list = NULL;
  1487. #else
  1488.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1489. #endif /* h_addr */
  1490. #else /* HADDRLIST */
  1491.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1492. #endif /* HADDRLIST */
  1493.  
  1494.     return(&hosts[next++]);
  1495. }
  1496.  
  1497. #ifdef EXCELAN
  1498. /*
  1499.   Most other BSD sockets implementations define these in header files
  1500.   and libraries.
  1501. */
  1502. struct servent {
  1503.     unsigned short s_port;
  1504. };
  1505.  
  1506. struct hostent {
  1507.     short h_addrtype;
  1508.     struct in_addr h_addr;
  1509.     int h_length;
  1510. };
  1511.  
  1512. struct servent *
  1513. getservbyname(service, connection) char *service,*connection; {
  1514.     static struct servent servrec;
  1515.     int port;
  1516.  
  1517.     port = 0;
  1518.     if (strcmp(service, "telnet") == 0) port = 23;
  1519.     else if (strcmp(service, "smtp") == 0) port = 25;
  1520.     else port = atoi(service);
  1521.  
  1522.     debug(F101,"getservbyname return port ","",port);
  1523.  
  1524.     if (port > 0) {
  1525.         servrec.s_port = htons(port);
  1526.         return(&servrec);
  1527.     }
  1528.     return((struct servent *) NULL);
  1529. }
  1530.  
  1531. struct hostent *
  1532. gethostbyname(hostname) char *hostname; {
  1533.     return((struct hostent *) NULL);
  1534. }
  1535.  
  1536. unsigned long
  1537. inet_addr(name) char *name; {
  1538.     unsigned long addr;
  1539.  
  1540.     addr = rhost(&name);
  1541.     debug(F111,"inet_addr ",name,(int)addr);
  1542.     return(addr);
  1543. }
  1544.  
  1545. char *
  1546. inet_ntoa(in) struct in_addr in; {
  1547.     static char name[80];
  1548.     ckmakxmsg(name, ckuitoa(in.s_net),".",ckuitoa(in.s_host),".",
  1549.                ckuitoa(in.s_lh),".", ckuitoa(in.s_impno));
  1550.     return(name);
  1551. }
  1552. #else
  1553. #ifdef DEC_TCPIP                        /* UCX */
  1554.  
  1555. int ucx_port_bug = 0;                   /* Explained below */
  1556.  
  1557. #ifndef __DECC                          /* VAXC or GCC */
  1558.  
  1559. #define getservbyname my_getservbyname
  1560.  
  1561. #ifdef CK_ANSIC
  1562. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1563. extern void C$$TRANSLATE();
  1564. extern void C$$SOCK_TRANSLATE();
  1565. #else
  1566. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1567. extern VOID C$$TRANSLATE();
  1568. extern VOID C$$SOCK_TRANSLATE();
  1569. #endif /* CK_ANSIC */
  1570.  
  1571. struct servent *
  1572. my_getservbyname (service, proto) char *service, *proto; {
  1573.     static struct servent sent;
  1574.     struct iosb {
  1575.         union {
  1576.             unsigned long status;
  1577.             unsigned short st[2];
  1578.         } sb;
  1579.         unsigned long spare;
  1580.     } s;
  1581.     struct {
  1582.         struct iosb *s;
  1583.         char *serv;
  1584.         char *prot;
  1585.     } par;
  1586.     unsigned long e;
  1587.     char sbuf[30], pbuf[30];
  1588.     char *p;
  1589.  
  1590.     debug(F111,"UCX getservbyname",service,(int)C$$GA_UCX_GETSERVBYNAME);
  1591.  
  1592.     p = sbuf;
  1593.     ckstrncpy(p, service, 29);
  1594.     while (*p = toupper(*p), *p++) {}
  1595.     p = pbuf;
  1596.     ckstrncpy(p, proto, 29);
  1597.     while (*p = toupper(*p), *p++) {}
  1598.  
  1599.     par.s = &s;
  1600.  
  1601.     par.serv = "";
  1602.     par.prot = "";
  1603.     /* reset file pointer or something like that!?!? */
  1604.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1605.     par.serv = sbuf;
  1606.     par.prot = pbuf;            /* that is don't care */
  1607.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1608.     if ((long)e == -1L)
  1609.       return NULL;
  1610.     if ((e & 1) == 0L) {
  1611.         C$$TRANSLATE(e);
  1612.         return NULL;
  1613.     }
  1614.     if ((s.sb.st[0] & 1) == 0) {
  1615.         C$$SOCK_TRANSLATE(&s.sb.st[0]);
  1616.         return NULL;
  1617.     }
  1618. /*
  1619.   sent.s_port is supposed to be returned by UCX in network byte order.
  1620.   However, UCX 2.0 through 2.0C did not do this; 2.0D and later do it.
  1621.   But there is no way of knowing which UCX version, so we have a user-settable
  1622.   runtime variable.  Note: UCX 2.0 was only for the VAX.
  1623. */
  1624.     debug(F101,"UCX getservbyname port","",sent.s_port);
  1625.     debug(F101,"UCX getservbyname ntohs(port)","",ntohs(sent.s_port));
  1626.     if (ucx_port_bug) {
  1627.         sent.s_port = htons(sent.s_port);
  1628.         debug(F100,"UCX-PORT-BUG ON: swapping bytes","",0);
  1629.         debug(F101,"UCX swapped port","",sent.s_port);
  1630.         debug(F101,"UCX swapped ntohs(port)","",ntohs(sent.s_port));
  1631.     }
  1632.     return &sent;
  1633. }
  1634. #endif /* __DECC */
  1635. #endif /* DEC_TCPIP */
  1636. #endif /* EXCELAN */
  1637. #endif /* TCPSOCKET */
  1638.  
  1639. #ifndef NOTCPOPTS
  1640. #ifndef datageneral
  1641. int
  1642. ck_linger(sock, onoff, timo) int sock; int onoff; int timo; {
  1643. /*
  1644.   The following, from William Bader, turns off the socket linger parameter,
  1645.   which makes a close() block until all data is sent.  "I don't think that
  1646.   disabling linger can ever cause kermit to lose data, but you telnet to a
  1647.   flaky server (or to our modem server when the modem is in use), disabling
  1648.   linger prevents kermit from hanging on the close if you try to exit."
  1649.  
  1650.   Modified by Jeff Altman to be generally useful.
  1651. */
  1652. #ifdef SOL_SOCKET
  1653. #ifdef SO_LINGER
  1654.     struct linger set_linger_opt;
  1655.     struct linger get_linger_opt;
  1656.     SOCKOPT_T x;
  1657.  
  1658. #ifdef IKSD
  1659.     if (!inserver)
  1660. #endif /* IKSD */
  1661.       if (sock == -1 ||
  1662.         nettype != NET_TCPA && nettype != NET_TCPB &&
  1663.         nettype != NET_SSH || ttmdm >= 0) {
  1664.         tcp_linger = onoff;
  1665.         tcp_linger_tmo = timo;
  1666.         return(1);
  1667.     }
  1668.     x = sizeof(get_linger_opt);
  1669.     if (getsockopt(sock, SOL_SOCKET, SO_LINGER,
  1670.                     (char *)&get_linger_opt, &x)) {
  1671.         debug(F111,"TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1672.     } else if (x != sizeof(get_linger_opt)) {
  1673. #ifdef OS2
  1674.         struct _linger16 {
  1675.             short s_linger;
  1676.             short s_onoff;
  1677.         } get_linger_opt16, set_linger_opt16;
  1678.         if ( x == sizeof(get_linger_opt16) ) {
  1679.             debug(F111,"TCP setlinger warning: SO_LINGER","len is 16-bit",x);
  1680.             if (getsockopt(sock,
  1681.                            SOL_SOCKET, SO_LINGER,
  1682.                            (char *)&get_linger_opt16, &x)
  1683.                 ) {
  1684.                 debug(F111,
  1685.                       "TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1686.             } else if (get_linger_opt16.s_onoff != onoff ||
  1687.                        get_linger_opt16.s_linger != timo)
  1688.             {
  1689.                 set_linger_opt16.s_onoff  = onoff;
  1690.                 set_linger_opt16.s_linger = timo;
  1691.                 if (setsockopt(sock,
  1692.                                SOL_SOCKET,
  1693.                                SO_LINGER,
  1694.                                (char *)&set_linger_opt16,
  1695.                                sizeof(set_linger_opt16))
  1696.                     ) {
  1697.                     debug(F111,
  1698.                           "TCP ck_linger can't set SO_LINGER",
  1699.                           ck_errstr(),
  1700.                           errno
  1701.                           );
  1702.                     tcp_linger = get_linger_opt16.s_onoff;
  1703.                     tcp_linger_tmo = get_linger_opt16.s_linger;
  1704.                 } else {
  1705.                     debug(F101,
  1706.                           "TCP ck_linger new SO_LINGER","",
  1707.                           set_linger_opt16.s_onoff);
  1708.                     tcp_linger = set_linger_opt16.s_onoff;
  1709.                     tcp_linger_tmo = set_linger_opt16.s_linger;
  1710.                     return 1;
  1711.                 }
  1712.             } else {
  1713.                 debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1714.                        get_linger_opt16.s_onoff);
  1715.                 tcp_linger = get_linger_opt16.s_onoff;
  1716.                 tcp_linger_tmo = get_linger_opt16.s_linger;
  1717.                 return 1;
  1718.             }
  1719.             return(0);
  1720.         }
  1721. #endif /* OS2 */
  1722.         debug(F111,"TCP ck_linger error: SO_LINGER","len",x);
  1723.         debug(F111,"TCP ck_linger SO_LINGER",
  1724.               "expected len",sizeof(get_linger_opt));
  1725.         debug(F111,"TCP ck_linger SO_LINGER","linger_opt.l_onoff",
  1726.               get_linger_opt.l_onoff);
  1727.         debug(F111,"TCP linger SO_LINGER","linger_opt.l_linger",
  1728.                get_linger_opt.l_linger);
  1729.     } else if (get_linger_opt.l_onoff != onoff ||
  1730.                get_linger_opt.l_linger != timo) {
  1731.         set_linger_opt.l_onoff  = onoff;
  1732.         set_linger_opt.l_linger = timo;
  1733.         if (setsockopt(sock,
  1734.                        SOL_SOCKET,
  1735.                        SO_LINGER,
  1736.                        (char *)&set_linger_opt,
  1737.                        sizeof(set_linger_opt))) {
  1738.             debug(F111,"TCP ck_linger can't set SO_LINGER",ck_errstr(),errno);
  1739.             tcp_linger = get_linger_opt.l_onoff;
  1740.             tcp_linger_tmo = get_linger_opt.l_linger;
  1741.          } else {
  1742.              debug(F101,
  1743.                    "TCP ck_linger new SO_LINGER",
  1744.                    "",
  1745.                    set_linger_opt.l_onoff
  1746.                    );
  1747.              tcp_linger = set_linger_opt.l_onoff;
  1748.              tcp_linger_tmo = set_linger_opt.l_linger;
  1749.              return 1;
  1750.          }
  1751.     } else {
  1752.         debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1753.               get_linger_opt.l_onoff);
  1754.         tcp_linger = get_linger_opt.l_onoff;
  1755.         tcp_linger_tmo = get_linger_opt.l_linger;
  1756.         return 1;
  1757.     }
  1758. #else
  1759.     debug(F100,"TCP ck_linger SO_LINGER not defined","",0);
  1760. #endif /* SO_LINGER */
  1761. #else
  1762.     debug(F100,"TCP ck_linger SO_SOCKET not defined","",0);
  1763. #endif /* SOL_SOCKET */
  1764.     return(0);
  1765. }
  1766.  
  1767. int
  1768. sendbuf(sock,size) int sock; int size; {
  1769. /*
  1770.   The following, from William Bader, allows changing of socket buffer sizes,
  1771.   in case that might affect performance.
  1772.  
  1773.   Modified by Jeff Altman to be generally useful.
  1774. */
  1775. #ifdef SOL_SOCKET
  1776. #ifdef SO_SNDBUF
  1777.     int i, j;
  1778.     SOCKOPT_T x;
  1779.  
  1780. #ifdef IKSD
  1781.     if (!inserver)
  1782. #endif /* IKSD */
  1783.       if (sock == -1 ||
  1784.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  1785.                 || ttmdm >= 0) {
  1786.         tcp_sendbuf = size;
  1787.         return 1;
  1788.     }
  1789.     x = sizeof(i);
  1790.     if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&i, &x)) {
  1791.         debug(F111,"TCP sendbuf can't get SO_SNDBUF",ck_errstr(),errno);
  1792.     } else if (x != sizeof(i)) {
  1793. #ifdef OS2
  1794.         short i16,j16;
  1795.         if (x == sizeof(i16)) {
  1796.             debug(F111,"TCP sendbuf warning: SO_SNDBUF","len is 16-bit",x);
  1797.             if (getsockopt(sock,
  1798.                            SOL_SOCKET, SO_SNDBUF,
  1799.                            (char *)&i16, &x)
  1800.                 ) {
  1801.                 debug(F111,"TCP sendbuf can't get SO_SNDBUF",
  1802.                       ck_errstr(),errno);
  1803.             } else if (size <= 0) {
  1804.                 tcp_sendbuf = i16;
  1805.                 debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i16);
  1806.                 return 1;
  1807.             } else if (i16 != size) {
  1808.                 j16 = size;
  1809.                 if (setsockopt(sock,
  1810.                                SOL_SOCKET,
  1811.                                SO_SNDBUF,
  1812.                                (char *)&j16,
  1813.                                sizeof(j16))
  1814.                     ) {
  1815.                     debug(F111,"TCP sendbuf can't set SO_SNDBUF",
  1816.                           ck_errstr(),errno);
  1817.                 } else {
  1818.                     debug(F101,"TCP sendbuf old SO_SNDBUF","",i16);
  1819.                     debug(F101,"TCP sendbuf new SO_SNDBUF","",j16);
  1820.                     tcp_sendbuf = size;
  1821.                     return 1;
  1822.                 }
  1823.             } else {
  1824.                 debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i16);
  1825.                 tcp_sendbuf = size;
  1826.                 return 1;
  1827.             }
  1828.             return(0);
  1829.         }
  1830. #endif /* OS2 */
  1831.         debug(F111,"TCP sendbuf error: SO_SNDBUF","len",x);
  1832.         debug(F111,"TCP sendbuf SO_SNDBUF","expected len",sizeof(i));
  1833.         debug(F111,"TCP sendbuf SO_SNDBUF","i",i);
  1834.     } else if (size <= 0) {
  1835.         tcp_sendbuf = i;
  1836.         debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i);
  1837.         return 1;
  1838.     } else if (i != size) {
  1839.         j = size;
  1840.         if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&j, sizeof(j))) {
  1841.             debug(F111,"TCP sendbuf can't set SO_SNDBUF",ck_errstr(),errno);
  1842.             tcp_sendbuf = i;
  1843.         } else {
  1844.             debug(F101,"TCP sendbuf old SO_SNDBUF","",i);
  1845.             debug(F101,"TCP sendbuf new SO_SNDBUF","",j);
  1846.             tcp_sendbuf = size;
  1847.             return 1;
  1848.         }
  1849.     } else {
  1850.         debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i);
  1851.         tcp_sendbuf = size;
  1852.         return 1;
  1853.     }
  1854. #else
  1855.     debug(F100,"TCP sendbuf SO_SNDBUF not defined","",0);
  1856. #endif /* SO_SNDBUF */
  1857. #else
  1858.     debug(F100,"TCP sendbuf SO_SOCKET not defined","",0);
  1859. #endif /* SOL_SOCKET */
  1860.     return(0);
  1861. }
  1862.  
  1863. int
  1864. recvbuf(sock,size) int sock; int size; {
  1865. /*
  1866.   The following, from William Bader, allows changing of socket buffer sizes,
  1867.   in case that might affect performance.
  1868.  
  1869.   Modified by Jeff Altman to be generally useful.
  1870. */
  1871. #ifdef SOL_SOCKET
  1872. #ifdef SO_RCVBUF
  1873.     int i, j;
  1874.     SOCKOPT_T x;
  1875.  
  1876. #ifdef IKSD
  1877.     if (!inserver)
  1878. #endif /* IKSD */
  1879.       if (sock == -1 ||
  1880.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH || ttmdm >= 0) {
  1881.         tcp_recvbuf = size;
  1882.         return(1);
  1883.     }
  1884.     x = sizeof(i);
  1885.     if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&i, &x)) {
  1886.         debug(F111,"TCP recvbuf can't get SO_RCVBUF",ck_errstr(),errno);
  1887.     } else if (x != sizeof(i)) {
  1888. #ifdef OS2
  1889.         short i16,j16;
  1890.         if ( x == sizeof(i16) ) {
  1891.             debug(F111,"TCP recvbuf warning: SO_RCVBUF","len is 16-bit",x);
  1892.             if (getsockopt(sock,
  1893.                            SOL_SOCKET, SO_RCVBUF,
  1894.                            (char *)&i16, &x)
  1895.                 ) {
  1896.                 debug(F111,"TCP recvbuf can't get SO_RCVBUF",
  1897.                       ck_errstr(),errno);
  1898.             } else if (size <= 0) {
  1899.                 tcp_recvbuf = i16;
  1900.                 debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i16);
  1901.                 return 1;
  1902.             } else if (i16 != size) {
  1903.                 j16 = size;
  1904.                 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j16,
  1905.                                sizeof(j16))) {
  1906.                     debug(F111,"TCP recvbuf can' set SO_RCVBUF",
  1907.                           ck_errstr(),errno);
  1908.                 } else {
  1909.                     debug(F101,"TCP recvbuf old SO_RCVBUF","",i16);
  1910.                     debug(F101,"TCP recvbuf new SO_RCVBUF","",j16);
  1911.                     tcp_recvbuf = size;
  1912.                     return 1;
  1913.                 }
  1914.             } else {
  1915.                 debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i16);
  1916.                 tcp_recvbuf = size;
  1917.                 return 1;
  1918.             }
  1919.             return(0);
  1920.         }
  1921. #endif /* OS2 */
  1922.         debug(F111,"TCP recvbuf error: SO_RCVBUF","len",x);
  1923.         debug(F111,"TCP recvbuf SO_RCVBUF","expected len",sizeof(i));
  1924.         debug(F111,"TCP recvbuf SO_RCVBUF","i",i);
  1925.     } else if (size <= 0) {
  1926.         tcp_recvbuf = i;
  1927.         debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i);
  1928.         return 1;
  1929.     } else if (i != size) {
  1930.         j = size;
  1931.         if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j, sizeof(j))) {
  1932.             debug(F111,"TCP recvbuf can't set SO_RCVBUF",ck_errstr(),errno);
  1933.             tcp_recvbuf = i;
  1934.         } else {
  1935.             debug(F101,"TCP recvbuf old SO_RCVBUF","",i);
  1936.             debug(F101,"TCP recvbuf new SO_RCVBUF","",j);
  1937.             tcp_recvbuf = size;
  1938.             return 1;
  1939.         }
  1940.     } else {
  1941.         debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i);
  1942.         tcp_recvbuf = size;
  1943.         return 1;
  1944.     }
  1945. #else
  1946.     debug(F100,"TCP recvbuf SO_RCVBUF not defined","",0);
  1947. #endif /* SO_RCVBUF */
  1948. #else
  1949.     debug(F100,"TCP recvbuf SO_SOCKET not defined","",0);
  1950. #endif /* SOL_SOCKET */
  1951.     return 0;
  1952. }
  1953.  
  1954. int
  1955. keepalive(sock,onoff) int sock; int onoff; {
  1956. #ifdef SOL_SOCKET
  1957. #ifdef SO_KEEPALIVE
  1958.     int get_keepalive_opt;
  1959.     int set_keepalive_opt;
  1960.     SOCKOPT_T x;
  1961.  
  1962.     debug(F111,"TCP keepalive","sock",sock);
  1963.     debug(F111,"TCP keepalive","nettype",nettype);
  1964.     debug(F111,"TCP keepalive","ttmdm",ttmdm);
  1965.  
  1966. #ifdef IKSD
  1967.     if (!inserver)
  1968. #endif /* IKSD */
  1969.       if (sock == -1 ||
  1970.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  1971.                 || ttmdm >= 0) {
  1972.         tcp_keepalive = onoff;
  1973.         return 1;
  1974.     }
  1975.     x = sizeof(get_keepalive_opt);
  1976.     if (getsockopt(sock,
  1977.                    SOL_SOCKET, SO_KEEPALIVE, (char *)&get_keepalive_opt, &x)) {
  1978.         debug(F111,"TCP keepalive can't get SO_KEEPALIVE",ck_errstr(),errno);
  1979.     } else if (x != sizeof(get_keepalive_opt)) {
  1980. #ifdef OS2
  1981.         short get_keepalive_opt16;
  1982.         short set_keepalive_opt16;
  1983.         if (x == sizeof(get_keepalive_opt16)) {
  1984.             debug(F111,"TCP keepalive warning: SO_KEEPALIVE",
  1985.                   "len is 16-bit",x);
  1986.             if (getsockopt(sock,
  1987.                            SOL_SOCKET, SO_KEEPALIVE,
  1988.                            (char *)&get_keepalive_opt16, &x)
  1989.                 ) {
  1990.                 debug(F111,
  1991.                       "TCP keepalive can't get SO_KEEPALIVE",
  1992.                       ck_errstr(),
  1993.                       errno
  1994.                       );
  1995.             } else if (get_keepalive_opt16 != onoff) {
  1996.                 set_keepalive_opt16 = onoff;
  1997.                 if (setsockopt(sock,
  1998.                                SOL_SOCKET,
  1999.                                SO_KEEPALIVE,
  2000.                                (char *)&set_keepalive_opt16,
  2001.                                sizeof(set_keepalive_opt16))
  2002.                     ) {
  2003.                     debug(F111,
  2004.                           "TCP keepalive can't clear SO_KEEPALIVE",
  2005.                           ck_errstr(),
  2006.                           errno
  2007.                           );
  2008.                     tcp_keepalive = get_keepalive_opt16;
  2009.                 } else {
  2010.                     debug(F101,
  2011.                           "TCP keepalive new SO_KEEPALIVE","",
  2012.                           set_keepalive_opt16);
  2013.                     tcp_keepalive = set_keepalive_opt16;
  2014.                     return 1;
  2015.                 }
  2016.             } else {
  2017.                 debug(F101,"TCP keepalive SO_KEEPALIVE unchanged","",
  2018.                       get_keepalive_opt16);
  2019.                 tcp_keepalive = onoff;
  2020.                 return 1;
  2021.             }
  2022.             return(0);
  2023.         }
  2024. #endif /* OS2 */
  2025.         debug(F111,"TCP keepalive error: SO_KEEPALIVE","len",x);
  2026.         debug(F111,
  2027.               "TCP keepalive SO_KEEPALIVE",
  2028.               "expected len",
  2029.               sizeof(get_keepalive_opt)
  2030.               );
  2031.         debug(F111,
  2032.               "TCP keepalive SO_KEEPALIVE",
  2033.               "keepalive_opt",
  2034.               get_keepalive_opt
  2035.               );
  2036.     } else if (get_keepalive_opt != onoff) {
  2037.             set_keepalive_opt = onoff;
  2038.             if (setsockopt(sock,
  2039.                             SOL_SOCKET,
  2040.                             SO_KEEPALIVE,
  2041.                             (char *)&set_keepalive_opt,
  2042.                             sizeof(set_keepalive_opt))
  2043.                 ) {
  2044.                 debug(F111,
  2045.                       "TCP keepalive can't clear SO_KEEPALIVE",
  2046.                       ck_errstr(),
  2047.                       errno
  2048.                       );
  2049.                 tcp_keepalive = get_keepalive_opt;
  2050.             } else {
  2051.                 debug(F101,
  2052.                       "TCP keepalive new SO_KEEPALIVE",
  2053.                       "",
  2054.                       set_keepalive_opt
  2055.                       );
  2056.                 tcp_keepalive = onoff;
  2057.                 return 1;
  2058.             }
  2059.         } else {
  2060.             debug(F101,"TCP keepalive SO_KEEPALIVE unchanged",
  2061.                   "",
  2062.                   get_keepalive_opt
  2063.                   );
  2064.             tcp_keepalive = onoff;
  2065.             return 1;
  2066.     }
  2067. #else
  2068.     debug(F100,"TCP keepalive SO_KEEPALIVE not defined","",0);
  2069. #endif /* SO_KEEPALIVE */
  2070. #else
  2071.     debug(F100,"TCP keepalive SO_SOCKET not defined","",0);
  2072. #endif /* SOL_SOCKET */
  2073.     return(0);
  2074. }
  2075.  
  2076. int
  2077. dontroute(sock,onoff) int sock; int onoff; {
  2078. #ifdef SOL_SOCKET
  2079. #ifdef SO_DONTROUTE
  2080.     int get_dontroute_opt;
  2081.     int set_dontroute_opt;
  2082.     SOCKOPT_T x;
  2083.  
  2084. #ifdef IKSD
  2085.     if (!inserver)
  2086. #endif /* IKSD */
  2087.       if (sock == -1 ||
  2088.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  2089.                 || ttmdm >= 0) {
  2090.         tcp_dontroute = onoff;
  2091.         return 1;
  2092.     }
  2093.     x = sizeof(get_dontroute_opt);
  2094.     if (getsockopt(sock,
  2095.                    SOL_SOCKET, SO_DONTROUTE, (char *)&get_dontroute_opt, &x)) {
  2096.         debug(F111,"TCP dontroute can't get SO_DONTROUTE",ck_errstr(),errno);
  2097.     } else if (x != sizeof(get_dontroute_opt)) {
  2098. #ifdef OS2
  2099.         short get_dontroute_opt16;
  2100.         short set_dontroute_opt16;
  2101.         if (x == sizeof(get_dontroute_opt16)) {
  2102.             debug(F111,"TCP dontroute warning: SO_DONTROUTE",
  2103.                   "len is 16-bit",x);
  2104.             if (getsockopt(sock,
  2105.                            SOL_SOCKET, SO_DONTROUTE,
  2106.                            (char *)&get_dontroute_opt16, &x)
  2107.                 ) {
  2108.                 debug(F111,
  2109.                       "TCP dontroute can't get SO_DONTROUTE",
  2110.                       ck_errstr(),
  2111.                       errno
  2112.                       );
  2113.             } else if (get_dontroute_opt16 != onoff) {
  2114.                 set_dontroute_opt16 = onoff;
  2115.                 if (setsockopt(sock,
  2116.                                SOL_SOCKET,
  2117.                                SO_DONTROUTE,
  2118.                                (char *)&set_dontroute_opt16,
  2119.                                sizeof(set_dontroute_opt16))
  2120.                     ) {
  2121.                     debug(F111,
  2122.                           "TCP dontroute can't clear SO_DONTROUTE",
  2123.                           ck_errstr(),
  2124.                           errno
  2125.                           );
  2126.                     tcp_dontroute = get_dontroute_opt16;
  2127.                 } else {
  2128.                     debug(F101,
  2129.                           "TCP dontroute new SO_DONTROUTE","",
  2130.                           set_dontroute_opt16);
  2131.                     tcp_dontroute = set_dontroute_opt16;
  2132.                     return 1;
  2133.                 }
  2134.             } else {
  2135.                 debug(F101,"TCP dontroute SO_DONTROUTE unchanged","",
  2136.                       get_dontroute_opt16);
  2137.                 tcp_dontroute = onoff;
  2138.                 return 1;
  2139.             }
  2140.             return(0);
  2141.         }
  2142. #endif /* OS2 */
  2143.         debug(F111,"TCP dontroute error: SO_DONTROUTE","len",x);
  2144.         debug(F111,
  2145.               "TCP dontroute SO_DONTROUTE",
  2146.               "expected len",
  2147.               sizeof(get_dontroute_opt)
  2148.               );
  2149.         debug(F111,
  2150.               "TCP dontroute SO_DONTROUTE",
  2151.               "dontroute_opt",
  2152.               get_dontroute_opt
  2153.               );
  2154.     } else if (get_dontroute_opt != onoff) {
  2155.             set_dontroute_opt = onoff;
  2156.             if (setsockopt(sock,
  2157.                             SOL_SOCKET,
  2158.                             SO_DONTROUTE,
  2159.                             (char *)&set_dontroute_opt,
  2160.                             sizeof(set_dontroute_opt))
  2161.                 ) {
  2162.                 debug(F111,
  2163.                       "TCP dontroute can't clear SO_DONTROUTE",
  2164.                       ck_errstr(),
  2165.                       errno
  2166.                       );
  2167.                 tcp_dontroute = get_dontroute_opt;
  2168.             } else {
  2169.                 debug(F101,
  2170.                       "TCP dontroute new SO_DONTROUTE",
  2171.                       "",
  2172.                       set_dontroute_opt
  2173.                       );
  2174.                 tcp_dontroute = onoff;
  2175.                 return 1;
  2176.             }
  2177.         } else {
  2178.             debug(F101,"TCP dontroute SO_DONTROUTE unchanged",
  2179.                   "",
  2180.                   get_dontroute_opt
  2181.                   );
  2182.             tcp_dontroute = onoff;
  2183.             return 1;
  2184.     }
  2185. #else
  2186.     debug(F100,"TCP dontroute SO_DONTROUTE not defined","",0);
  2187. #endif /* SO_DONTROUTE */
  2188. #else
  2189.     debug(F100,"TCP dontroute SO_SOCKET not defined","",0);
  2190. #endif /* SOL_SOCKET */
  2191.     return(0);
  2192. }
  2193.  
  2194. int
  2195. no_delay(sock,onoff)  int sock; int onoff; {
  2196. #ifdef SOL_SOCKET
  2197. #ifdef TCP_NODELAY
  2198.     int get_nodelay_opt;
  2199.     int set_nodelay_opt;
  2200.     SOCKOPT_T x;
  2201.  
  2202. #ifdef IKSD
  2203.     if (!inserver)
  2204. #endif /* IKSD */
  2205.       if (sock == -1 ||
  2206.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  2207.                 || ttmdm >= 0) {
  2208.         tcp_nodelay = onoff;
  2209.         return(1);
  2210.     }
  2211.     x = sizeof(get_nodelay_opt);
  2212.     if (getsockopt(sock,IPPROTO_TCP,TCP_NODELAY,
  2213.                    (char *)&get_nodelay_opt,&x)) {
  2214.         debug(F111,
  2215.               "TCP no_delay can't get TCP_NODELAY",
  2216.               ck_errstr(),
  2217.               errno);
  2218.     } else if (x != sizeof(get_nodelay_opt)) {
  2219. #ifdef OS2
  2220.         short get_nodelay_opt16;
  2221.         short set_nodelay_opt16;
  2222.         if (x == sizeof(get_nodelay_opt16)) {
  2223.             debug(F111,"TCP no_delay warning: TCP_NODELAY","len is 16-bit",x);
  2224.             if (getsockopt(sock,
  2225.                            IPPROTO_TCP, TCP_NODELAY,
  2226.                            (char *)&get_nodelay_opt16, &x)
  2227.                 ) {
  2228.                 debug(F111,
  2229.                       "TCP no_delay can't get TCP_NODELAY",
  2230.                       ck_errstr(),
  2231.                       errno);
  2232.             } else if (get_nodelay_opt16 != onoff) {
  2233.                 set_nodelay_opt16 = onoff;
  2234.                 if (setsockopt(sock,
  2235.                                IPPROTO_TCP,
  2236.                                TCP_NODELAY,
  2237.                                (char *)&set_nodelay_opt16,
  2238.                                sizeof(set_nodelay_opt16))
  2239.                     ) {
  2240.                     debug(F111,
  2241.                           "TCP no_delay can't clear TCP_NODELAY",
  2242.                           ck_errstr(),
  2243.                           errno);
  2244.                     tcp_nodelay = get_nodelay_opt16;
  2245.                 } else {
  2246.                     debug(F101,
  2247.                           "TCP no_delay new TCP_NODELAY",
  2248.                           "",
  2249.                           set_nodelay_opt16);
  2250.                     tcp_nodelay = onoff;
  2251.                     return 1;
  2252.                 }
  2253.             } else {
  2254.                 debug(F101,"TCP no_delay TCP_NODELAY unchanged","",
  2255.                       get_nodelay_opt16);
  2256.                 tcp_nodelay = onoff;
  2257.                 return 1;
  2258.             }
  2259.             return(0);
  2260.         }
  2261. #endif /* OS2 */
  2262.         debug(F111,"TCP no_delay error: TCP_NODELAY","len",x);
  2263.         debug(F111,"TCP no_delay TCP_NODELAY","expected len",
  2264.               sizeof(get_nodelay_opt));
  2265.         debug(F111,"TCP no_delay TCP_NODELAY","nodelay_opt",get_nodelay_opt);
  2266.     } else if (get_nodelay_opt != onoff) {
  2267.         set_nodelay_opt = onoff;
  2268.         if (setsockopt(sock,
  2269.                        IPPROTO_TCP,
  2270.                        TCP_NODELAY,
  2271.                        (char *)&set_nodelay_opt,
  2272.                        sizeof(set_nodelay_opt))) {
  2273.             debug(F111,
  2274.                   "TCP no_delay can't clear TCP_NODELAY",
  2275.                   ck_errstr(),
  2276.                   errno
  2277.                   );
  2278.             tcp_nodelay = get_nodelay_opt;
  2279.         } else {
  2280.             debug(F101,"TCP no_delay new TCP_NODELAY","",set_nodelay_opt);
  2281.             tcp_nodelay = onoff;
  2282.             return 1;
  2283.         }
  2284.     } else {
  2285.         debug(F101,"TCP no_delay TCP_NODELAY unchanged","",get_nodelay_opt);
  2286.         tcp_nodelay = onoff;
  2287.         return(1);
  2288.     }
  2289. #else
  2290.     debug(F100,"TCP no_delay TCP_NODELAY not defined","",0);
  2291. #endif /* TCP_NODELAY */
  2292. #else
  2293.     debug(F100,"TCP no_delay SO_SOCKET not defined","",0);
  2294. #endif /* SOL_SOCKET */
  2295.     return 0;
  2296. }
  2297. #endif /* datageneral */
  2298. #endif /* NOTCPOPTS */
  2299.  
  2300. #ifdef SUNX25
  2301. #ifndef X25_WR_FACILITY
  2302. /* For Solaris 2.3 / SunLink 8.x - see comments in ckcnet.h */
  2303. void
  2304. bzero(s,n) char *s; int n; {
  2305.     memset(s,0,n);
  2306. }
  2307. #endif /* X25_WR_FACILITY */
  2308. #endif /* SUNX25 */
  2309.  
  2310. #ifdef TCPSOCKET
  2311. #ifndef OS2
  2312. #ifndef NOLISTEN
  2313.  
  2314. #ifdef BSDSELECT
  2315. #ifndef VMS
  2316. #ifndef BELLV10
  2317. #ifndef datageneral
  2318. #ifdef hp9000s500                       /* HP-9000/500 HP-U 5.21 */
  2319. #include <time.h>
  2320. #else
  2321.  
  2322. /****** THIS SECTION ADDED BY STEVE RANCE - OS9 NETWORK SERVER
  2323. *       ------------------------------------------------------
  2324. *
  2325. *       Due to OS9's Lack of a select() call, the following seems to be
  2326. *       enough to fool the rest of the code into compiling. The only
  2327. *       effect that I can see is using control L to refresh the status
  2328. *       display gets qued up until some network packets arrive.
  2329. *
  2330. *       This solution is by no means elegant but works enough to be
  2331. *       a (the) solution.
  2332. *
  2333. *       Also with the defines I had specified in my makefile I had to
  2334. *       have an #endif right at the end of the file when compiling.
  2335. *       I did not bother speding time to find out why.
  2336. *
  2337. *       COPTS   = -to=osk -d=OSK -d=TCPSOCKET -d=SELECT -d=VOID=void -d=SIG_V \
  2338. *          -d=DYNAMIC -d=PARSENSE -d=KANJI -d=MYCURSES -d=ZFCDAT \
  2339. *          -d=CK_APC -d=CK_REDIR -d=RENAME -d=CK_TTYFD -d=NOOLDMODEMS \
  2340. *          -d=CK_ANSIC -d=CK_XYZ -tp=68040d -l=netdb.l -l=socklib.l \
  2341. *          -l=termlib.l -l=math.l -l=sys_clib.l
  2342. *
  2343. *       stever@ozemail.com.au
  2344. */
  2345.  
  2346. #ifdef  OSK
  2347. #define BSDSELECT                       /* switch on BSD select code */
  2348. #define FD_SETSIZE 32                   /* Max # of paths in OS9 */
  2349. #define FD_ZERO(p)                      ((*p)=0)
  2350. #define FD_SET(n,b)                     ((*b)|=(1<<(n)))
  2351. #define FD_ISSET(n,b)           1       /* always say data is ready */
  2352. #define select(a,b,c,d,e)       1       /* always say 1 path has data */
  2353. typedef int     fd_set;                 /* keep BSD Code Happy */
  2354. struct timeval {int tv_sec,tv_usec;};   /* keep BSD Code Happy */
  2355.  
  2356. /****** END OF OS9 MODS FROM STEVE RANCE **************************/
  2357. #endif /* OSK */
  2358.  
  2359. #include <sys/time.h>
  2360. #endif /* hp9000s500 */
  2361. #endif /* datageneral */
  2362. #endif /* BELLV10 */
  2363. #endif /* VMS */
  2364. #ifdef SELECT_H
  2365. #include <sys/select.h>
  2366. #endif /* SELECT_H */
  2367. #endif /* BSDSELECT */
  2368.  
  2369. #ifdef SELECT
  2370. #ifdef CK_SCOV5
  2371. #include <sys/select.h>
  2372. #endif /* CK_SCOV5 */
  2373. #endif /* SELECT */
  2374.  
  2375. #ifdef NOTUSED
  2376. /* T C P S O C K E T _ O P E N -- Open a preexisting socket number */
  2377.  
  2378. int
  2379. tcpsocket_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo {
  2380.     int on = 1;
  2381.     static struct servent *service, servrec;
  2382.     static struct hostent *host;
  2383.     static struct sockaddr_in saddr;
  2384.     static
  2385. #ifdef UCX50
  2386.       unsigned
  2387. #endif /* UCX50 */
  2388.       int saddrlen;
  2389. #ifdef BSDSELECT
  2390.     fd_set rfds;
  2391.     struct timeval tv;
  2392. #else
  2393. #ifdef BELLSELECT
  2394.     fd_set rfds;
  2395. #else
  2396.     fd_set rfds;
  2397.     fd_set rfds;
  2398.     struct timeval {
  2399.         long tv_sec;
  2400.         long tv_usec;
  2401.     } tv;
  2402. #endif /* BELLSELECT */
  2403. #endif /* BSDSELECT */
  2404.  
  2405.     debug(F101,"tcpsocket_open nett","",nett);
  2406.     *ipaddr = '\0';
  2407.  
  2408.     if (nett != NET_TCPB)
  2409.       return(-1);                       /* BSD socket support */
  2410.  
  2411.     netclos();                          /* Close any previous connection. */
  2412.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2413.     if (ttnproto != NP_TCPRAW)
  2414.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2415.     debug(F110,"tcpsocket_open namecopy",namecopy,0);
  2416.  
  2417.     /* Assign the socket number to ttyfd and then fill in tcp structures */
  2418.     ttyfd = atoi(&name[1]);
  2419.     debug(F111,"tcpsocket_open","ttyfd",ttyfd);
  2420.  
  2421. #ifndef NOTCPOPTS
  2422. #ifdef SOL_SOCKET
  2423.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2424.  
  2425. #ifndef datageneral
  2426. #ifdef TCP_NODELAY
  2427.     no_delay(ttyfd,tcp_nodelay);
  2428. #endif /* TCP_NODELAY */
  2429. #ifdef SO_KEEPALIVE
  2430.     keepalive(ttyfd,tcp_keepalive);
  2431. #endif /* SO_KEEPALIVE */
  2432. #ifdef SO_LINGER
  2433.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  2434. #endif /* SO_LINGER */
  2435. #ifdef SO_SNDBUF
  2436.     sendbuf(ttyfd,tcp_sendbuf);
  2437. #endif /* SO_SNDBUF */
  2438. #ifdef SO_RCVBUF
  2439.     recvbuf(ttyfd,tcp_recvbuf);
  2440. #endif /* SO_RCVBUF */
  2441. #endif /* datageneral */
  2442. #endif /* SOL_SOCKET */
  2443. #endif /* NOTCPOPTS */
  2444.  
  2445. #ifdef NT_TCP_OVERLAPPED
  2446.     OverlappedWriteInit();
  2447.     OverlappedReadInit();
  2448. #endif /* NT_TCP_OVERLAPPED */
  2449.  
  2450.  
  2451.     /* Get the name of the host we are connected to */
  2452.  
  2453.     saddrlen = sizeof(saddr);
  2454.     getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen);
  2455.  
  2456.     ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2457.  
  2458.     if (tcp_rdns == SET_ON
  2459. #ifdef CK_KERBEROS
  2460.         || tcp_rdns == SET_AUTO &&
  2461.          (ck_krb5_is_installed() || ck_krb4_is_installed())
  2462. #endif /* CK_KERBEROS */
  2463. #ifndef NOHTTP
  2464.           && (tcp_http_proxy == NULL)
  2465. #endif /* NOHTTP */
  2466. #ifdef CK_SSL
  2467.           && !(ssl_only_flag || tls_only_flag)
  2468. #endif /* CK_SSL */
  2469.          ) {                            /* Reverse DNS */
  2470.         if (!quiet) {
  2471.             printf(" Reverse DNS Lookup... ");
  2472.             fflush(stdout);
  2473.         }
  2474.         host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET);
  2475.         debug(F110,"tcpsocket_open gethostbyaddr",host ? "OK" : "FAILED",0);
  2476.         if (host) {
  2477.             host = ck_copyhostent(host);
  2478.             debug(F100,"tcpsocket_open gethostbyaddr != NULL","",0);
  2479.             if (!quiet) {
  2480.                 printf("(OK)\n");
  2481.                 fflush(stdout);
  2482.             }
  2483.             ckstrncpy(name, host->h_name, 80);
  2484.             ckstrncat(name, ":", 80);
  2485.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)), 80);
  2486.             if (!quiet
  2487. #ifndef NOICP
  2488.                 && !doconx
  2489. #endif /* NOICP */
  2490.                 )
  2491.               printf("%s connected on port %d\n",
  2492.                    host->h_name,
  2493.                    ntohs(saddr.sin_port)
  2494.                    );
  2495.         } else if (!quiet)
  2496.           printf("Failed\n");
  2497.     } else if (!quiet)
  2498.       printf("(OK)\n");
  2499.  
  2500.     if (tcp_rdns != SET_ON || !host) {
  2501.         ckstrncpy(name,ipaddr,80);
  2502.         ckstrncat(name,":",80);
  2503.         ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  2504.         if (!quiet
  2505. #ifdef NOICP
  2506.             && !doconx
  2507. #endif /* NOICP */
  2508.             )
  2509.           printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2510.     }
  2511.     if (!quiet) fflush(stdout);
  2512.     ttnet = nett;                       /* TCP/IP (sockets) network */
  2513.  
  2514. #ifdef RLOGCODE
  2515.     if (ntohs(saddr.sin_port) == 513)
  2516.         ttnproto = NP_LOGIN;
  2517.     else
  2518. #endif /* RLOGCODE */
  2519.     /* Assume the service is TELNET. */
  2520.     if (ttnproto != NP_TCPRAW)
  2521.         ttnproto = NP_TELNET;           /* Yes, set global flag. */
  2522. #ifdef CK_SECURITY
  2523.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2524.     ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2525.                 host->h_name : ipaddr,
  2526.                 ipaddr,
  2527.                 uidbuf,
  2528.                 ttyfd
  2529.                 );
  2530. #endif /* CK_SECURITY */
  2531.     if (tn_ini() < 0)                   /* Start/Reset TELNET negotiations */
  2532.       if (ttchk() < 0)                  /* Did it fail due to connect loss? */
  2533.         return(-1);
  2534.  
  2535.     if (*lcl < 0) *lcl = 1;             /* Local mode. */
  2536.  
  2537.     return(0);                          /* Done. */
  2538. }
  2539. #endif /* NOTUSED */
  2540.  
  2541. /*  T C P S R V _ O P E N  --  Open a TCP/IP Server connection  */
  2542. /*
  2543.   Calling conventions same as ttopen(), except third argument is network
  2544.   type rather than modem type.
  2545. */
  2546. int
  2547. tcpsrv_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo; {
  2548.     char *p;
  2549.     int i, x;
  2550.     SOCKOPT_T on = 1;
  2551.     int ready_to_accept = 0;
  2552.     static struct servent *service, *service2, servrec;
  2553.     static struct hostent *host;
  2554.     static struct sockaddr_in saddr;
  2555.     struct sockaddr_in l_addr;
  2556.     GSOCKNAME_T l_slen;
  2557. #ifdef UCX50
  2558.     static u_int saddrlen;
  2559. #else
  2560.     static SOCKOPT_T saddrlen;
  2561. #endif /* UCX50 */
  2562.  
  2563. #ifdef BSDSELECT
  2564.     fd_set rfds;
  2565.     struct timeval tv;
  2566. #else
  2567. #ifdef BELLSELCT
  2568.     fd_set rfds;
  2569. #else
  2570.     fd_set rfds;
  2571.     struct timeval {
  2572.         long tv_sec;
  2573.         long tv_usec;
  2574.     } tv;
  2575. #endif /* BELLSELECT */
  2576. #endif /* BSDSELECT */
  2577. #ifdef CK_SSL
  2578.     int ssl_failed = 0;
  2579. #endif /* CK_SSL */
  2580.  
  2581.     debug(F101,"tcpsrv_open nett","",nett);
  2582.     *ipaddr = '\0';
  2583.  
  2584.     if (nett != NET_TCPB)
  2585.       return(-1);                       /* BSD socket support */
  2586.  
  2587.     netclos();                          /* Close any previous connection. */
  2588.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2589. #ifdef COMMENT
  2590.     /* Don't do this. */
  2591.     if (ttnproto != NP_TCPRAW)
  2592.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2593. #endif /* COMMENT */
  2594.     debug(F110,"tcpsrv_open namecopy",namecopy,0);
  2595.  
  2596.     p = namecopy;                       /* Was a service requested? */
  2597.     while (*p != '\0' && *p != ':')
  2598.       p++; /* Look for colon */
  2599.     if (*p == ':') {                    /* Have a colon */
  2600.         *p++ = '\0';                    /* Get service name or number */
  2601.     } else {                            /* Otherwise use kermit */
  2602.         p = "kermit";
  2603.     }
  2604.     debug(F110,"tcpsrv_open service requested",p,0);
  2605.     if (isdigit(*p)) {                  /* Use socket number without lookup */
  2606.         service = &servrec;
  2607.         service->s_port = htons((unsigned short)atoi(p));
  2608.     } else {                            /* Otherwise lookup the service name */
  2609.         service = getservbyname(p, "tcp");
  2610.     }
  2611.     if (!service && !strcmp("kermit",p)) { /* Use Kermit service port */
  2612.         service = &servrec;
  2613.         service->s_port = htons(1649);
  2614.     }
  2615. #ifdef RLOGCODE
  2616.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  2617.         fprintf(stderr,
  2618.                 "  Warning: login service on port %d instead of port 513\n",
  2619.                  ntohs(service->s_port));
  2620.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  2621.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  2622.     }
  2623. #endif /* RLOGCODE */
  2624.     if (!service) {
  2625.         fprintf(stderr, "Cannot find port for service: %s\n", p);
  2626.         debug(F111,"tcpsrv_open can't get service",p,errno);
  2627.         errno = 0;                      /* rather than mislead */
  2628.         return(-1);
  2629.     }
  2630.  
  2631.     /* If we currently have a listen active but port has changed then close */
  2632.  
  2633.     debug(F101,"tcpsrv_open checking previous connection","",tcpsrfd);
  2634.     debug(F101,"tcpsrv_open previous tcpsrv_port","",tcpsrv_port);
  2635.     if (tcpsrfd != -1 &&
  2636.         tcpsrv_port != ntohs((unsigned short)service->s_port)) {
  2637.         debug(F100,"tcpsrv_open closing previous connection","",0);
  2638. #ifdef TCPIPLIB
  2639.         socket_close(tcpsrfd);
  2640. #else
  2641.         close(tcpsrfd);
  2642. #endif /* TCPIPLIB */
  2643.         tcpsrfd = -1;
  2644.     }
  2645.     debug(F100,"tcpsrv_open tcpsrfd","",tcpsrfd);
  2646.     if (tcpsrfd == -1) {
  2647.  
  2648.         /* Set up socket structure and get host address */
  2649.  
  2650.         bzero((char *)&saddr, sizeof(saddr));
  2651.         debug(F100,"tcpsrv_open bzero ok","",0);
  2652.         saddr.sin_family = AF_INET;
  2653.         if (tcp_address) {
  2654. #ifdef INADDRX
  2655.             inaddrx = inet_addr(tcp_address);
  2656.             saddr.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  2657. #else
  2658.             saddr.sin_addr.s_addr = inet_addr(tcp_address);
  2659. #endif /* INADDRX */
  2660.         } else
  2661.           saddr.sin_addr.s_addr = INADDR_ANY;
  2662.  
  2663.         /* Get a file descriptor for the connection. */
  2664.  
  2665.         saddr.sin_port = service->s_port;
  2666.         ipaddr[0] = '\0';
  2667.  
  2668.         debug(F100,"tcpsrv_open calling socket","",0);
  2669.         if ((tcpsrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  2670.             perror("TCP socket error");
  2671.             debug(F101,"tcpsrv_open socket error","",errno);
  2672.             return (-1);
  2673.         }
  2674.         errno = 0;
  2675.  
  2676.         /* Specify the Port may be reused */
  2677.  
  2678.         debug(F100,"tcpsrv_open calling setsockopt","",0);
  2679.         x = setsockopt(tcpsrfd,
  2680.                        SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof on);
  2681.         debug(F101,"tcpsrv_open setsockopt","",x);
  2682.  
  2683.        /* Now bind to the socket */
  2684.         printf("\nBinding socket to port %d ...\n",
  2685.                ntohs((unsigned short)service->s_port));
  2686.         if (bind(tcpsrfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  2687.             i = errno;                  /* Save error code */
  2688. #ifdef TCPIPLIB
  2689.             socket_close(tcpsrfd);
  2690. #else /* TCPIPLIB */
  2691.             close(tcpsrfd);
  2692. #endif /* TCPIPLIB */
  2693.             tcpsrfd = -1;
  2694.             tcpsrv_port = 0;
  2695.             ttyfd = -1;
  2696.             wasclosed = 1;
  2697.             errno = i;                  /* and report this error */
  2698.             debug(F101,"tcpsrv_open bind errno","",errno);
  2699.             printf("?Unable to bind to socket (errno = %d)\n",errno);
  2700.             return(-1);
  2701.         }
  2702.         debug(F100,"tcpsrv_open bind OK","",0);
  2703.         printf("Listening ...\n");
  2704.         if (listen(tcpsrfd, 15) < 0) {
  2705.             i = errno;                  /* Save error code */
  2706. #ifdef TCPIPLIB
  2707.             socket_close(tcpsrfd);
  2708. #else /* TCPIPLIB */
  2709.             close(tcpsrfd);
  2710. #endif /* TCPIPLIB */
  2711.             tcpsrfd = -1;
  2712.             tcpsrv_port = 0;
  2713.             ttyfd = -1;
  2714.             wasclosed = 1;
  2715.             errno = i;                  /* And report this error */
  2716.             debug(F101,"tcpsrv_open listen errno","",errno);
  2717.             return(-1);
  2718.         }
  2719.         debug(F100,"tcpsrv_open listen OK","",0);
  2720.         tcpsrv_port = ntohs((unsigned short)service->s_port);
  2721.     }
  2722.  
  2723. #ifdef CK_SSL
  2724.     if (ck_ssleay_is_installed()) {
  2725.         if (!ssl_tn_init(SSL_SERVER)) {
  2726.             ssl_failed = 1;
  2727.             if (bio_err!=NULL) {
  2728.                 BIO_printf(bio_err,"do_ssleay_init() failed\n");
  2729.                 ERR_print_errors(bio_err);
  2730.             } else {
  2731.                 fflush(stderr);
  2732.                 fprintf(stderr,"do_ssleay_init() failed\n");
  2733.                 ERR_print_errors_fp(stderr);
  2734.             }
  2735.             if (tls_only_flag || ssl_only_flag) {
  2736. #ifdef TCPIPLIB
  2737.                 socket_close(ttyfd);
  2738.                 socket_close(tcpsrfd);
  2739. #else /* TCPIPLIB */
  2740.                 close(ttyfd);
  2741.                 close(tcpsrfd);
  2742. #endif /* TCPIPLIB */
  2743.                 ttyfd = -1;
  2744.                 wasclosed = 1;
  2745.                 tcpsrfd = -1;
  2746.                 tcpsrv_port = 0;
  2747.                 return(-1);
  2748.             }
  2749.             /* we will continue to accept the connection   */
  2750.             /* without SSL or TLS support unless required. */
  2751.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2752.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2753.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2754.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2755.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2756.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2757.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2758.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2759.         }
  2760.     }
  2761. #endif /* CK_SSL */
  2762.  
  2763.     printf("\nWaiting to Accept a TCP/IP connection on port %d ...\n",
  2764.            ntohs((unsigned short)service->s_port));
  2765.     saddrlen = sizeof(saddr);
  2766.  
  2767. #ifdef BSDSELECT
  2768.     tv.tv_sec  = tv.tv_usec = 0L;
  2769.     if (timo < 0)
  2770.       tv.tv_usec = (long) -timo * 10000L;
  2771.     else
  2772.       tv.tv_sec = timo;
  2773.     debug(F101,"tcpsrv_open BSDSELECT","",timo);
  2774. #else
  2775.     debug(F101,"tcpsrv_open not BSDSELECT","",timo);
  2776. #endif /* BSDSELECT */
  2777.  
  2778.     if (timo) {
  2779.         while (!ready_to_accept) {
  2780. #ifdef BSDSELECT
  2781.             FD_ZERO(&rfds);
  2782.             FD_SET(tcpsrfd, &rfds);
  2783.             ready_to_accept =
  2784.               ((select(FD_SETSIZE,
  2785. #ifdef HPUX
  2786. #ifdef HPUX1010
  2787.                        (fd_set *)
  2788. #else
  2789.  
  2790.                        (int *)
  2791. #endif /* HPUX1010 */
  2792. #else
  2793. #ifdef __DECC
  2794.                        (fd_set *)
  2795. #endif /* __DECC */
  2796. #endif /* HPUX */
  2797.                        &rfds, NULL, NULL, &tv) > 0) &&
  2798.                FD_ISSET(tcpsrfd, &rfds));
  2799. #else /* BSDSELECT */
  2800. #ifdef IBMSELECT
  2801. #define ck_sleepint 250
  2802.             ready_to_accept =
  2803.               (select(&tcpsrfd, 1, 0, 0,
  2804.                       timo < 0 ? -timo :
  2805.                       (timo > 0 ? timo * 1000L : ck_sleepint)) == 1
  2806.                );
  2807. #else
  2808. #ifdef BELLSELECT
  2809.             FD_ZERO(rfds);
  2810.             FD_SET(tcpsrfd, rfds);
  2811.             ready_to_accept =
  2812.               ((select(128, rfds, NULL, NULL, timo < 0 ? -timo :
  2813.                       (timo > 0 ? timo * 1000L)) > 0) &&
  2814.                FD_ISSET(tcpsrfd, rfds));
  2815. #else
  2816. /* Try this - what's the worst that can happen... */
  2817.  
  2818.             FD_ZERO(&rfds);
  2819.             FD_SET(tcpsrfd, &rfds);
  2820.             ready_to_accept =
  2821.               ((select(FD_SETSIZE,
  2822.                        (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  2823.                FD_ISSET(tcpsrfd, &rfds));
  2824.  
  2825. #endif /* BELLSELECT */
  2826. #endif /* IBMSELECT */
  2827. #endif /* BSDSELECT */
  2828.         }
  2829.     }
  2830.     if (ready_to_accept || timo == 0) {
  2831.         if ((ttyfd = accept(tcpsrfd,
  2832.                             (struct sockaddr *)&saddr,&saddrlen)) < 0) {
  2833.             i = errno;                  /* save error code */
  2834. #ifdef TCPIPLIB
  2835.             socket_close(tcpsrfd);
  2836. #else /* TCPIPLIB */
  2837.             close(tcpsrfd);
  2838. #endif /* TCPIPLIB */
  2839.             ttyfd = -1;
  2840.             wasclosed = 1;
  2841.             tcpsrfd = -1;
  2842.             tcpsrv_port = 0;
  2843.             errno = i;                  /* and report this error */
  2844.             debug(F101,"tcpsrv_open accept errno","",errno);
  2845.             return(-1);
  2846.         }
  2847.         setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2848.  
  2849. #ifndef NOTCPOPTS
  2850. #ifndef datageneral
  2851. #ifdef SOL_SOCKET
  2852. #ifdef TCP_NODELAY
  2853.         no_delay(ttyfd,tcp_nodelay);
  2854.         debug(F101,"tcpsrv_open no_delay","",tcp_nodelay);
  2855. #endif /* TCP_NODELAY */
  2856. #ifdef SO_KEEPALIVE
  2857.         keepalive(ttyfd,tcp_keepalive);
  2858.         debug(F101,"tcpsrv_open keepalive","",tcp_keepalive);
  2859. #endif /* SO_KEEPALIVE */
  2860. #ifdef SO_LINGER
  2861.         ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  2862.         debug(F101,"tcpsrv_open linger","",tcp_linger_tmo);
  2863. #endif /* SO_LINGER */
  2864. #ifdef SO_SNDBUF
  2865.         sendbuf(ttyfd,tcp_sendbuf);
  2866. #endif /* SO_SNDBUF */
  2867. #ifdef SO_RCVBUF
  2868.         recvbuf(ttyfd,tcp_recvbuf);
  2869. #endif /* SO_RCVBUF */
  2870. #endif /* SOL_SOCKET */
  2871. #endif /* datageneral */
  2872. #endif /* NOTCPOPTS */
  2873.  
  2874.         ttnet = nett;                   /* TCP/IP (sockets) network */
  2875.         tcp_incoming = 1;               /* This is an incoming connection */
  2876.         sstelnet = 1;                   /* Do server-side Telnet protocol */
  2877.  
  2878.         /* See if the service is TELNET. */
  2879.         x = (unsigned short)service->s_port;
  2880.         service2 = getservbyname("telnet", "tcp");
  2881.         if (service2 && x == service2->s_port) {
  2882.             if (ttnproto != NP_TCPRAW)  /* Yes and if raw port not requested */
  2883.               ttnproto = NP_TELNET;     /* Set protocol to TELNET. */
  2884.         }
  2885. #ifdef CK_SECURITY
  2886.         /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2887.         ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2888.                      (char *)host->h_name : ipaddr,
  2889.                      ipaddr,
  2890.                      uidbuf,
  2891.                      ttyfd
  2892.                      );
  2893. #endif /* CK_SECURITY */
  2894.  
  2895. #ifdef CK_SSL
  2896.         if (ck_ssleay_is_installed() && !ssl_failed) {
  2897.             if (ck_ssl_incoming(ttyfd) < 0) {
  2898. #ifdef TCPIPLIB
  2899.                     socket_close(ttyfd);
  2900.                     socket_close(tcpsrfd);
  2901. #else /* TCPIPLIB */
  2902.                     close(ttyfd);
  2903.                     close(tcpsrfd);
  2904. #endif /* TCPIPLIB */
  2905.                     ttyfd = -1;
  2906.                     wasclosed = 1;
  2907.                     tcpsrfd = -1;
  2908.                     tcpsrv_port = 0;
  2909.                     return(-1);
  2910.             }
  2911.         }
  2912. #endif /* CK_SSL */
  2913.  
  2914. #ifndef datageneral
  2915.         /* Find out our own IP address. */
  2916.         l_slen = sizeof(l_addr);
  2917.         bzero((char *)&l_addr, l_slen);
  2918. #ifndef EXCELAN
  2919.         if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  2920.             char * s = (char *)inet_ntoa(l_addr.sin_addr);
  2921.             ckstrncpy(myipaddr, s,20);
  2922.             debug(F110,"getsockname",myipaddr,0);
  2923.         }
  2924. #endif /* EXCELAN */
  2925. #endif /* datageneral */
  2926.  
  2927.         if (tn_ini() < 0)               /* Start TELNET negotiations. */
  2928.           if (ttchk() < 0) {            /* Disconnected? */
  2929.               i = errno;                /* save error code */
  2930. #ifdef TCPIPLIB
  2931.               socket_close(tcpsrfd);
  2932. #else /* TCPIPLIB */
  2933.               close(tcpsrfd);
  2934. #endif /* TCPIPLIB */
  2935.               ttyfd = -1;
  2936.               wasclosed = 1;
  2937.               tcpsrfd = -1;
  2938.               tcpsrv_port = 0;
  2939.               errno = i;                /* and report this error */
  2940.               debug(F101,"tcpsrv_open accept errno","",errno);
  2941.               return(-1);
  2942.           }
  2943.         debug(F101,"tcpsrv_open service","",x);
  2944.         if (*lcl < 0)                   /* Set local mode. */
  2945.           *lcl = 1;
  2946.  
  2947. #ifdef CK_KERBEROS
  2948. #ifdef KRB5_U2U
  2949.         if ( ttnproto == NP_K5U2U ) {
  2950.             if (k5_user_to_user_server_auth() != 0) {
  2951.                 i = errno;                /* save error code */
  2952. #ifdef TCPIPLIB
  2953.                 socket_close(tcpsrfd);
  2954. #else /* TCPIPLIB */
  2955.                 close(tcpsrfd);
  2956. #endif /* TCPIPLIB */
  2957.                 ttyfd = -1;
  2958.                 wasclosed = 1;
  2959.                 tcpsrfd = -1;
  2960.                 tcpsrv_port = 0;
  2961.                 errno = i;                /* and report this error */
  2962.                 debug(F101,"tcpsrv_open accept errno","",errno);
  2963.                 return(-1);
  2964.             }
  2965.         }
  2966. #endif /* KRB5_U2U */
  2967. #endif /* CK_KERBEROS */
  2968.  
  2969.         ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2970.         if (tcp_rdns) {
  2971.             if (!quiet) {
  2972.                 printf(" Reverse DNS Lookup... ");
  2973.                 fflush(stdout);
  2974.             }
  2975.             if (host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET)) {
  2976.                 host = ck_copyhostent(host);
  2977.                 debug(F100,"tcpsrv_open gethostbyaddr != NULL","",0);
  2978.                 if (!quiet) {
  2979.                     printf("(OK)\n");
  2980.                     fflush(stdout);
  2981.                 }
  2982.                 name[0] = '*';
  2983.                 ckstrncpy(&name[1],host->h_name,78);
  2984.                 strncat(name,":",80-strlen(name));
  2985.                 strncat(name,p,80-strlen(name));
  2986.                 if (!quiet
  2987. #ifndef NOICP
  2988.                     && !doconx
  2989. #endif /* NOICP */
  2990.                     )
  2991.                   printf("%s connected on port %s\n",host->h_name,p);
  2992.             } else {
  2993.                 if (!quiet) printf("Failed.\n");
  2994.             }
  2995.         } else if (!quiet) printf("(OK)\n");
  2996.  
  2997.         if (!tcp_rdns || !host) {
  2998.             ckstrncpy(name,ipaddr,80);
  2999.             ckstrncat(name,":",80);
  3000.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  3001.             if (!quiet
  3002. #ifndef NOICP
  3003.                 && !doconx
  3004. #endif /* NOICP */
  3005.                 )
  3006.               printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  3007.         }
  3008.         if (!quiet) fflush(stdout);
  3009.         return(0);                      /* Done. */
  3010.     } else {
  3011.         i = errno;                      /* save error code */
  3012. #ifdef TCPIPLIB
  3013.         socket_close(tcpsrfd);
  3014. #else /* TCPIPLIB */
  3015.         close(tcpsrfd);
  3016. #endif /* TCPIPLIB */
  3017.         ttyfd = -1;
  3018.         wasclosed = 1;
  3019.         tcpsrfd = -1;
  3020.         tcpsrv_port = 0;
  3021.         errno = i;                      /* and report this error */
  3022.         debug(F101,"tcpsrv_open accept errno","",errno);
  3023.         return(-1);
  3024.     }
  3025. }
  3026. #endif /* NOLISTEN */
  3027. #endif /* OS2 */
  3028. #endif /* TCPSOCKET */
  3029. #endif /* NONET */
  3030.  
  3031. #ifdef TCPSOCKET
  3032. char *
  3033. ckname2addr(name) char * name;
  3034. {
  3035. #ifdef HPUX5
  3036.     return("");
  3037. #else
  3038.     struct hostent *host;
  3039.  
  3040.     if (name == NULL || *name == '\0')
  3041.         return("");
  3042.  
  3043.     host = gethostbyname(name);
  3044.     if ( host ) {
  3045.         host = ck_copyhostent(host);
  3046.         return(inet_ntoa(*((struct in_addr *) host->h_addr)));
  3047.     }
  3048.     return("");
  3049. #endif /* HPUX5 */
  3050. }
  3051.  
  3052. char *
  3053. ckaddr2name(addr) char * addr;
  3054. {
  3055. #ifdef HPUX5
  3056.     return("");
  3057. #else
  3058.     struct hostent *host;
  3059.     struct in_addr sin_addr;
  3060.  
  3061.     if (addr == NULL || *addr == '\0')
  3062.         return("");
  3063.  
  3064.     sin_addr.s_addr = inet_addr(addr);
  3065.     host = gethostbyaddr((char *)&sin_addr,4,AF_INET);
  3066.     if (host) {
  3067.         host = ck_copyhostent(host);
  3068.         return((char *)host->h_name);
  3069.     }
  3070.     return("");
  3071. #endif /* HPUX5 */
  3072. }
  3073. #endif /* TCPSOCKET */
  3074.  
  3075. unsigned long peerxipaddr = 0L;
  3076.  
  3077. char *
  3078. ckgetpeer() {
  3079. #ifdef TCPSOCKET
  3080.     static char namebuf[256];
  3081.     static struct hostent *host;
  3082.     static struct sockaddr_in saddr;
  3083. #ifdef PTX
  3084.     static size_t saddrlen;
  3085. #else
  3086. #ifdef AIX42
  3087.     /* It's size_t in 4.2 but int in 4.1 and earlier. */
  3088.     /* Note: the 4.2 man page lies; believe socket.h. */
  3089.     static size_t saddrlen;
  3090. #else
  3091. #ifdef UNIXWARE
  3092.     static size_t saddrlen;
  3093. #else  /* UNIXWARE */
  3094. #ifdef DEC_TCPIP
  3095.     static unsigned int saddrlen;
  3096. #else
  3097.     static int saddrlen;
  3098. #endif /* VMS */
  3099. #endif /* UNIXWARE */
  3100. #endif /* AIX42 */
  3101. #endif /* PTX */
  3102.     saddrlen = sizeof(saddr);
  3103.     if (getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen) < 0) {
  3104.         debug(F111,"ckgetpeer failure",ckitoa(ttyfd),errno);
  3105.         return(NULL);
  3106.     }
  3107.     host = gethostbyaddr((char *)&saddr.sin_addr,4,AF_INET);
  3108.     if (host) {
  3109.         host = ck_copyhostent(host);
  3110.         ckstrncpy(namebuf,(char *)host->h_name,80);
  3111.     } else {
  3112.         ckstrncpy(namebuf,(char *)inet_ntoa(saddr.sin_addr),80);
  3113.     }
  3114.     peerxipaddr = ntohl(saddr.sin_addr.s_addr);
  3115.     debug(F111,"ckgetpeer",namebuf,peerxipaddr);
  3116.     return(namebuf);
  3117. #else
  3118.     return(NULL);
  3119. #endif /* TCPSOCKET */
  3120. }
  3121.  
  3122. /* Get fully qualified IP hostname */
  3123.  
  3124. #ifndef NONET
  3125. char *
  3126. #ifdef CK_ANSIC
  3127. ckgetfqhostname(char * name)
  3128. #else
  3129. ckgetfqhostname(name) char * name;
  3130. #endif /* CK_ANSIC */
  3131. {
  3132. #ifdef NOCKGETFQHOST
  3133.  
  3134.     return(name);
  3135.  
  3136. #else /* If the following code dumps core, define NOCKGETFQHOST and rebuild. */
  3137.  
  3138.     static char namebuf[256];
  3139.     struct hostent *host=NULL;
  3140.     struct sockaddr_in r_addr;
  3141.     int i;
  3142.  
  3143.     debug(F110,"ckgetfqhn()",name,0);
  3144.  
  3145.     ckstrncpy(namebuf,name,256);
  3146.     namebuf[255] = '\0';
  3147.     i = ckindex(":",namebuf,0,0,0);
  3148.     if (i)
  3149.       namebuf[i-1] = '\0';
  3150.  
  3151.     bzero((char *)&r_addr, sizeof(r_addr));
  3152.  
  3153.     host = gethostbyname(namebuf);
  3154.     if (host) {
  3155.         host = ck_copyhostent(host);
  3156.         debug(F100,"ckgetfqhn() gethostbyname != NULL","",0);
  3157.         r_addr.sin_family = host->h_addrtype;
  3158. #ifdef HADDRLIST
  3159. #ifdef h_addr
  3160.         /* This is for trying multiple IP addresses - see <netdb.h> */
  3161.         if (!(host->h_addr_list))
  3162.           goto exit_func;
  3163.         bcopy(host->h_addr_list[0],
  3164.               (caddr_t)&r_addr.sin_addr,
  3165.               host->h_length
  3166.               );
  3167. #else
  3168.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3169. #endif /* h_addr */
  3170. #else  /* HADDRLIST */
  3171.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3172. #endif /* HADDRLIST */
  3173. #ifndef EXCELAN
  3174.         debug(F111,"BCOPY","host->h_addr",host->h_addr);
  3175. #endif /* EXCELAN */
  3176.         debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  3177.               (caddr_t)&r_addr.sin_addr);
  3178.         debug(F111,"BCOPY","host->h_length",host->h_length);
  3179.  
  3180. #ifdef NT
  3181.         /* Windows 95/98 requires a 1 second wait between calls to Microsoft */
  3182.         /* provided DNS functions.  Otherwise, the TTL of the DNS response */
  3183.         /* is ignored. */
  3184.         if (isWin95())
  3185.           sleep(1);
  3186. #endif /* NT */
  3187.         host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET);
  3188.         if (host) {
  3189.             host = ck_copyhostent(host);
  3190.             debug(F100,"ckgetfqhn() gethostbyaddr != NULL","",0);
  3191.             ckstrncpy(namebuf, host->h_name, 256);
  3192.         }
  3193.     }
  3194.  
  3195. #ifdef HADDRLIST
  3196. #ifdef h_addr
  3197.   exit_func:
  3198. #endif /* h_addr */
  3199. #endif /* HADDRLIST */
  3200.  
  3201.     if (i > 0)
  3202.       strncat(namebuf,&name[i-1],256-strlen(namebuf)-strlen(&name[i-1]));
  3203.     debug(F110,"ckgetfqhn()",namebuf,0);
  3204.     return(namebuf);
  3205. #endif /* NOCKGETFQHOST */
  3206. }
  3207.  
  3208. VOID
  3209. #ifdef CK_ANSIC
  3210. setnproto(char * p)
  3211. #else
  3212. setnproto(p) char * p;
  3213. #endif /* CK_ANSIC */
  3214. {
  3215.     if (!isdigit(*p)) {
  3216.         if (!strcmp("kermit",p))
  3217.           ttnproto = NP_KERMIT;
  3218.         else if (!strcmp("telnet",p))
  3219.           ttnproto = NP_TELNET;
  3220.         else if (!strcmp("http",p))
  3221.           ttnproto = NP_TCPRAW;
  3222. #ifdef RLOGCODE
  3223.         else if (!strcmp("login",p))
  3224.           ttnproto = NP_RLOGIN;
  3225. #endif /* RLOGCODE */
  3226. #ifdef CK_SSL
  3227.         /* Commonly used SSL ports (might not be in services file) */
  3228.         else if (!strcmp("https",p)) {
  3229.           ttnproto = NP_SSL;
  3230.           ssl_only_flag = 1;
  3231.         } else if (!strcmp("ssl-telnet",p)) {
  3232.           ttnproto = NP_TELNET;
  3233.           ssl_only_flag = 1;
  3234.         } else if (!strcmp("telnets",p)) {
  3235.           ttnproto = NP_TELNET;
  3236.           ssl_only_flag = 1;
  3237.         }
  3238. #endif /* CK_SSL */
  3239. #ifdef CK_KERBEROS
  3240. #ifdef RLOGCODE
  3241.         else if (!strcmp("klogin",p)) {
  3242.             if (ck_krb5_is_installed())
  3243.               ttnproto = NP_K5LOGIN;
  3244.             else if (ck_krb4_is_installed())
  3245.               ttnproto = NP_K4LOGIN;
  3246.             else
  3247.               ttnproto = NP_RLOGIN;
  3248.         } else if (!strcmp("eklogin",p)) {
  3249.             if (ck_krb5_is_installed())
  3250.               ttnproto = NP_EK5LOGIN;
  3251.             else if (ck_krb4_is_installed())
  3252.               ttnproto = NP_EK4LOGIN;
  3253.             else
  3254.               ttnproto = NP_RLOGIN;
  3255.         }
  3256. #endif /* RLOGCODE */
  3257. #endif /* CK_KERBEROS */
  3258.         else
  3259.           ttnproto = NP_NONE;
  3260.     } else {
  3261.         switch (atoi(p)) {
  3262.           case 23:                      /* Telnet */
  3263.             ttnproto = NP_TELNET;
  3264.             break;
  3265.           case 513:
  3266.             ttnproto = NP_RLOGIN;
  3267.             break;
  3268.           case 1649:
  3269.             ttnproto = NP_KERMIT;
  3270.             break;
  3271. #ifdef CK_SSL
  3272.           case 443:
  3273.             ttnproto = NP_SSL;
  3274.             ssl_only_flag = 1;
  3275.             break;
  3276.           case 151:
  3277.           case 992:
  3278.             ttnproto = NP_TELNET;
  3279.             ssl_only_flag = 1;
  3280.             break;
  3281. #endif /* CK_SSL */
  3282. #ifdef CK_KERBEROS
  3283.           case 543:
  3284.             if (ck_krb5_is_installed())
  3285.               ttnproto = NP_K5LOGIN;
  3286.             else if (ck_krb4_is_installed())
  3287.               ttnproto = NP_K4LOGIN;
  3288.             else
  3289.               ttnproto = NP_RLOGIN;
  3290.             break;
  3291.           case 2105:
  3292.             if (ck_krb5_is_installed())
  3293.               ttnproto = NP_EK5LOGIN;
  3294.             else if (ck_krb4_is_installed())
  3295.               ttnproto = NP_EK4LOGIN;
  3296.             else
  3297.               ttnproto = NP_RLOGIN;
  3298.             break;
  3299. #endif /* CK_KERBEROS */
  3300.           case 80:                      /* HTTP */
  3301.             ttnproto = NP_TCPRAW;
  3302.             break;
  3303.           default:
  3304.             ttnproto = NP_NONE;
  3305.             break;
  3306.         }
  3307.     }
  3308. }
  3309.  
  3310. /* ckgetservice() is used to determine the port number for a given */
  3311. /* service taking into account the use of DNS SRV records.         */
  3312.  
  3313. static struct servent servrec;
  3314. static struct servent *
  3315. ckgetservice(hostname, servicename, ip, iplen)
  3316.     char *hostname; char * servicename; char * ip; int iplen;
  3317. {
  3318.     struct servent * service = NULL;
  3319. #ifdef CK_DNS_SRV
  3320.     struct sockaddr * dns_addrs = NULL;
  3321.     int dns_naddrs = 0;
  3322. #endif /* CK_DNS_SRV */
  3323.  
  3324.     if (isdigit(*servicename)) {        /* Use socket number without lookup */
  3325.         service = &servrec;
  3326.         service->s_port = htons((unsigned short)atoi(servicename));
  3327.     } else {                            /* Otherwise lookup the service name */
  3328. #ifdef CK_DNS_SRV
  3329.         if (tcp_dns_srv && !quiet) {
  3330.             printf(" DNS SRV Lookup... ");
  3331.             fflush(stdout);
  3332.         }
  3333.         if (tcp_dns_srv &&
  3334.             locate_srv_dns(hostname,
  3335.                            servicename,
  3336.                            "tcp",
  3337.                            &dns_addrs,
  3338.                            &dns_naddrs
  3339.                            )
  3340.             ) {
  3341.             /* Use the first one.  Eventually we should cycle through all */
  3342.             /* the returned IP addresses and port numbers. */
  3343.             struct sockaddr_in *sin = NULL;
  3344. #ifdef BETADEBUG
  3345.             int i;
  3346.             printf("\r\n");
  3347.             for ( i=0;i<dns_naddrs;i++ ) {
  3348.                 sin = (struct sockaddr_in *) &dns_addrs[i];
  3349.                 printf("dns_addrs[%d] = %s %d\r\n", i,
  3350.                         (char *)inet_ntoa(sin->sin_addr),
  3351.                         ntohs(sin->sin_port));
  3352.             }
  3353. #endif /* BETADEBUG */
  3354.             sin = (struct sockaddr_in *) &dns_addrs[0];
  3355.             if ( ip && iplen > 0 )
  3356.                 ckstrncpy(ip,(char *)inet_ntoa(sin->sin_addr),iplen);
  3357.             service = &servrec;
  3358.             service->s_port = sin->sin_port;
  3359.  
  3360.             free(dns_addrs);
  3361.             dns_addrs = NULL;
  3362.             dns_naddrs = 0;
  3363.         } else
  3364. #endif /* CK_DNS_SRV */
  3365.             service = getservbyname(servicename, "tcp");
  3366.     }
  3367.     if (!service) {
  3368.         if (!ckstrcmp("kermit",servicename,-1,0)) { /* Kermit service port */
  3369.             service = &servrec;
  3370.             service->s_port = htons(1649);
  3371.         } else if (!ckstrcmp("telnet",servicename,-1,0)) { /* Telnet port */
  3372.             service = &servrec;
  3373.             service->s_port = htons(23);
  3374.         } else if (!ckstrcmp("http",servicename,-1,0)) {
  3375.             service = &servrec;
  3376.             service->s_port = htons(80);
  3377.         }
  3378. #ifdef RLOGCODE
  3379.         else if (!ckstrcmp("login",servicename,-1,0)) {
  3380.             service = &servrec;
  3381.             service->s_port = htons(513);
  3382.         }
  3383. #endif /* RLOGCODE */
  3384. #ifdef CK_SSL
  3385.         /* Commonly used SSL ports (might not be in services file) */
  3386.         else if (!ckstrcmp("https",servicename,-1,0)) {
  3387.             service = &servrec;
  3388.             service->s_port = htons(443);
  3389.         } else if (!ckstrcmp("ssl-telnet",servicename,-1,0)) {
  3390.             service = &servrec;
  3391.             service->s_port = htons(151);
  3392.         } else if (!ckstrcmp("telnets",servicename,-1,0)) {
  3393.             service = &servrec;
  3394.             service->s_port = htons(992);
  3395.         }
  3396. #endif /* CK_SSL */
  3397. #ifdef CK_KERBEROS
  3398. #ifdef RLOGCODE
  3399.         else if (!ckstrcmp("klogin",servicename,-1,0)) {
  3400.             service = &servrec;
  3401.             service->s_port = htons(543);
  3402.         } else if (!ckstrcmp("eklogin",servicename,-1,0)) {
  3403.             service = &servrec;
  3404.             service->s_port = htons(2105);
  3405.         }
  3406. #endif /* RLOGCODE */
  3407. #endif /* CK_KERBEROS */
  3408.     }
  3409.     return(service);
  3410. }
  3411.  
  3412. /*  N E T O P E N  --  Open a network connection  */
  3413. /*
  3414.   Calling conventions same as ttopen(), except third argument is network
  3415.   type rather than modem type.  Designed to be called from within ttopen.
  3416. */
  3417.  
  3418. int
  3419. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  3420.     char *p;
  3421.     int i, x, dns = 0;
  3422. #ifdef TCPSOCKET
  3423.     int isconnect = 0;
  3424. #ifdef SO_OOBINLINE
  3425.     int on = 1;
  3426. #endif /* SO_OOBINLINE */
  3427.     struct servent *service=NULL;
  3428.     struct hostent *host=NULL;
  3429.     struct sockaddr_in r_addr;
  3430.     struct sockaddr_in sin;
  3431.     struct sockaddr_in l_addr;
  3432.     GSOCKNAME_T l_slen;
  3433. #ifdef EXCELAN
  3434.     struct sockaddr_in send_socket;
  3435. #endif /* EXCELAN */
  3436.  
  3437. #ifdef INADDRX
  3438. /* inet_addr() is of type struct in_addr */
  3439. #ifdef datageneral
  3440.     extern struct in_addr inet_addr();
  3441. #else
  3442. #ifdef HPUX5WINTCP
  3443.     extern struct in_addr inet_addr();
  3444. #endif /* HPUX5WINTCP */
  3445. #endif /* datageneral */
  3446.     struct in_addr iax;
  3447. #else
  3448. #ifdef INADDR_NONE
  3449.     struct in_addr iax;
  3450. #else /* INADDR_NONE */
  3451.     long iax;
  3452. #endif /* INADDR_NONE */
  3453. #endif /* INADDRX */
  3454. #endif /* TCPSOCKET */
  3455.  
  3456. #ifdef COMMENT
  3457. /* This causes big trouble */
  3458. #ifndef INADDR_NONE
  3459. #define INADDR_NONE 0xffffffff
  3460. #endif /* INADDR_NONE */
  3461. #endif /* COMMENT */
  3462.  
  3463. #ifdef SUNX25                           /* Code for SunLink X.25 support */
  3464. #define X29PID 1                        /* X.29 Protocol ID */
  3465. _PROTOTYP(SIGTYP x25oobh, (int) );
  3466.     CONN_DB x25host;
  3467. #ifndef X25_WR_FACILITY
  3468.     FACILITY x25facil;
  3469. #else
  3470.     FACILITY_DB x25facil;
  3471. #endif /* X25_WR_FACILITY */
  3472.     static int needh = 1;
  3473.     PID_T pid;
  3474.     extern int linkid, lcn, x25ver;
  3475. #endif /* SUNX25 */
  3476. #ifdef ANYX25
  3477.     extern int revcall, closgr, cudata;
  3478.     extern char udata[];
  3479. #endif /* ANYX25 */
  3480.  
  3481. #ifdef IBMX25                           /* Variables for IBM X25 */
  3482.     extern int x25port;                 /* Logical port to use */
  3483.     extern x25addr_t local_nua;         /* Local X.25 address */
  3484.     extern x25addr_t remote_nua;        /* Remote X.25 address */
  3485.     extern char x25name[];              /* X25 device name (sx25a0) */
  3486.     extern char x25dev[];               /* X25 device file /dev/x25pkt */
  3487.     ulong bind_flags = 0;               /* Flags for binding the X25 stream */
  3488.     ulong token = 0;                    /* Temporary return code */
  3489. #endif /* IBMX25 */
  3490.  
  3491.     debug(F101,"netopen nett","",nett);
  3492.     *ipaddr = '\0';                     /* Initialize IP address string */
  3493.  
  3494. #ifdef SUNX25
  3495.     if (nett == NET_SX25) {             /* If network type is X.25 */
  3496.         netclos();                      /* Close any previous net connection */
  3497.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3498.  
  3499.         /* Set up host structure */
  3500.         bzero((char *)&x25host,sizeof(x25host));
  3501.         if ((x25host.hostlen = pkx121(name,x25host.host)) < 0) {
  3502.             fprintf (stderr,"Invalid X.121 host address %s\n",name);
  3503.             errno = 0;
  3504.             return (-1);
  3505.         }
  3506.         x25host.datalen = X29PIDLEN;
  3507.         x25host.data[0] = X29PID;
  3508.  
  3509.         /* Set call user data if specified */
  3510.         if (cudata) {
  3511.             ckstrncpy((char *)x25host.data+X29PIDLEN,udata,(int)strlen(udata));
  3512.             x25host.datalen += (int)strlen(udata);
  3513.         }
  3514.  
  3515.         /* Open SunLink X.25 socket */
  3516.         if (!quiet && *name) {
  3517.             printf(" Trying %s... ", name);
  3518.             fflush(stdout);
  3519.         }
  3520.         if ((ttyfd = socket(AF_X25, SOCK_STREAM, 0)) < 0) {
  3521.             debug(F101,"netopen socket error","",errno);
  3522.             perror ("X.25 socket error");
  3523.             return (-1);
  3524.         }
  3525.  
  3526.         /* Setting X.25 out-of-band data handler */
  3527.         pid = getpid();
  3528.         if (ioctl(ttyfd,SIOCSPGRP,&pid)) {
  3529.             perror("X.25 set process group id error");
  3530.             return(-1);
  3531.         }
  3532.         (VOID) signal(SIGURG,x25oobh);
  3533.  
  3534.         /* Set reverse charge call and closed user group if requested */
  3535.         bzero ((char *)&x25facil,sizeof(x25facil));
  3536.  
  3537. #ifndef X25_WR_FACILITY
  3538. /*  New SunLink (7.0 or 8.0, not sure which)... */
  3539.         x25facil.type = T_REVERSE_CHARGE; /* Reverse Charge */
  3540.         x25facil.f_reverse_charge = revcall ? 1 : 0;
  3541.         if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3542.             perror ("Setting X.25 reverse charge");
  3543.             return (-1);
  3544.         }
  3545.         if (closgr > -1) {              /* Closed User Group (Outgoing) */
  3546.             bzero ((char *)&x25facil,sizeof(x25facil));
  3547.             x25facil.type = T_CUG;
  3548.             x25facil.f_cug_req = CUG_REQ_ACS;
  3549.             x25facil.f_cug_index = closgr;
  3550.             if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3551.                 perror ("Setting X.25 closed user group");
  3552.                 return (-1);
  3553.             }
  3554.         }
  3555. #else
  3556. /*  Old SunLink 6.0 (or 7.0?)... */
  3557.         if (revcall) x25facil.reverse_charge = revcall;
  3558.         if (closgr > -1) {
  3559.             x25facil.cug_req = 1;
  3560.             x25facil.cug_index = closgr;
  3561.         }
  3562.         if (ioctl(ttyfd,X25_WR_FACILITY,&x25facil) < 0) {
  3563.             perror ("Setting X.25 facilities");
  3564.             return (-1);
  3565.         }
  3566. #endif /* X25_WR_FACILITY */
  3567.  
  3568.         /*  Need X.25 header with bits Q and M */
  3569.         if (ioctl (ttyfd,X25_HEADER,&needh) < 0) {
  3570.             perror ("Setting X.25 header");
  3571.             return (-1);
  3572.         }
  3573.  
  3574.         /* Connects to remote host via SunLink X.25 */
  3575.         if (connect(ttyfd,(struct sockaddr *)&x25host,sizeof(x25host)) < 0) {
  3576.             i = errno;
  3577.             debug(F101,"netopen connect errno","",i);
  3578.             if (i) {
  3579.                 perror("netopen x25 connect");
  3580.                 x25diag();
  3581.             }
  3582.             (VOID) netclos();
  3583.             ttyfd = -1;
  3584.             wasclosed = 1;
  3585.             ttnproto = NP_NONE;
  3586.             errno = i;
  3587.             return (-1);
  3588.         }
  3589.  
  3590.         /* Get X.25 link identification used for the connection */
  3591.         if (ioctl(ttyfd,X25_GET_LINK,&linkid) < 0) {
  3592.             perror ("Getting X.25 link id");
  3593.             return (-1);
  3594.         }
  3595.  
  3596.         /* Get X.25 logical channel number used for the connection */
  3597.         if (ioctl(ttyfd,X25_RD_LCGN,&lcn) < 0) {
  3598.             perror ("Getting X.25 lcn");
  3599.             return (-1);
  3600.         }
  3601.  
  3602.         /* Get SunLink X.25 version */
  3603.         if (ioctl(ttyfd,X25_VERSION,&x25ver) < 0) {
  3604.             perror ("Getting SunLink X.25 version");
  3605.             return (-1);
  3606.         }
  3607.         ttnet = nett;                   /* Sunlink X.25 network */
  3608.         ttnproto = NP_X3;               /* PAD X.3, X.28, X.29 protocol */
  3609.         if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3610.         return(0);
  3611.     } else /* Note that SUNX25 support can coexist with TCP/IP support. */
  3612. #endif /* SUNX25 */
  3613.  
  3614. #ifdef IBMX25
  3615.     /* riehm */
  3616.     if (nett == NET_IX25) {             /* IBM AIX X.25 */
  3617.         netclos();                      /* Close any previous net connection */
  3618.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3619.  
  3620.         /* find out who we are - this is not so easy on AIX */
  3621.         /* riehm: need to write the code that finds this out
  3622.          * automatically, or at least allow it to be configured
  3623.          * somehow
  3624.          */
  3625.         if (!local_nua[0] && !x25local_nua(local_nua)) {
  3626.             return(-1);
  3627.         }
  3628.  
  3629.         /* Initialise the X25 API (once per process? once per connection?) */
  3630.  
  3631.         debug(F110, "Opening ", x25dev, 0 );
  3632.         /* set O_NDELAY to allow polling? */
  3633.         if ((ttyfd = open(x25dev, O_RDWR)) < 0) {
  3634.             perror ("X.25 device open error");
  3635.             debug(F101,"netopen: device open error","",errno);
  3636.             return (-1);
  3637.         }
  3638.  
  3639.         /* push the NPI onto the STREAM */
  3640.         if (ioctl(ttyfd,I_PUSH,"npi") < 0 ) {
  3641.             close(ttyfd);
  3642.             ttyfd = -1;
  3643.             wasclosed = 1;
  3644.             perror( "kermit: netopen(): couldn't push npi on the X25 stream" );
  3645.             debug(F101,"netopen: can't push npi on the X25 stream","",errno);
  3646.             return (-1);
  3647.         }
  3648.  
  3649.         /* set up server mode - bind the x25 port and wait for
  3650.          * incoming connections
  3651.          */
  3652.         if (name[0] == '*') {           /* Server */
  3653.             /* set up a server - see the warning in x25bind() */
  3654.             bind_flags |= TOKEN_REQUEST;
  3655.  
  3656.             /* bind kermit to the local X25 address */
  3657.             token = x25bind(ttyfd,
  3658.                             local_nua,
  3659.                             udata,
  3660.                             (int)strlen( udata ),
  3661.                             1,
  3662.                             x25port,
  3663.                             bind_flags
  3664.                             );
  3665.             if (token < 0) {
  3666.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3667.                 netclos();
  3668.                 return(-1);
  3669.             }
  3670.             /* Currently not connected to a remote host */
  3671.  
  3672.             remote_nua[0] = '\0';
  3673.  
  3674.             /* store the fd so that incoming calls can have their own fd
  3675.              * This is almost support for a true server (ie: a'la ftpd)
  3676.              * but we're not quite there yet.
  3677.              * used in netclos()
  3678.              */
  3679.             x25serverfd = ttyfd;
  3680.             /*
  3681.              * wait for an incoming call
  3682.              * this should happen in the "server" command and not in
  3683.              * the "set host *" command.
  3684.              */
  3685.             if ((ttyfd = x25getcall(ttyfd)) < 0) {
  3686.                 netclos();
  3687.                 return(-1);
  3688.             }
  3689.         } else {                        /* Client */
  3690.             /* Bind kermit to the local X25 address */
  3691.             token = x25bind(
  3692.                             ttyfd,
  3693.                             local_nua,
  3694.                             (char *)NULL,
  3695.                             0,
  3696.                             0,
  3697.                             x25port,
  3698.                             bind_flags
  3699.                             );
  3700.             if (token < 0) {
  3701.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3702.                 netclos();
  3703.                 return(-1);
  3704.             }
  3705. /* riehm: this should be done via the CONNECT command, not HOST! */
  3706.             {
  3707.                 x25serverfd = 0;
  3708.                 /* call the remote host */
  3709.                 /* name == address of remote host as char* */
  3710.                 if (x25call(ttyfd, name, udata) < 0 ) {
  3711.                     debug(F100,
  3712.                           "netopen: couldn't connect to remote X25 address",
  3713.                           "", 0);
  3714.                     netclos();
  3715.                     return(-1);
  3716.                 }
  3717.                 strcpy(remote_nua, name);
  3718.             }
  3719.         }
  3720.         ttnet = nett;                   /* AIX X.25 network */
  3721.         if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3722.         return(0);
  3723.  
  3724.     } else /* Note that IBMX25 support can coexist with TCP/IP support. */
  3725. #endif /* IBMX25 */
  3726.  
  3727. /*   Add support for other networks here. */
  3728.  
  3729.       if (nett != NET_TCPB) return(-1); /* BSD socket support */
  3730.  
  3731. #ifdef TCPSOCKET
  3732.     netclos();                          /* Close any previous connection. */
  3733.     ckstrncpy(namecopy, name, NAMECPYL);        /* Copy the hostname. */
  3734.     debug(F110,"netopen namecopy",namecopy,0);
  3735.  
  3736. #ifndef NOLISTEN
  3737.     if (name[0] == '*')
  3738.       return(tcpsrv_open(name, lcl, nett, 0));
  3739. #endif /* NOLISTEN */
  3740.  
  3741.     p = namecopy;                       /* Was a service requested? */
  3742.     while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3743.     if (*p == ':') {                    /* Have a colon */
  3744.         debug(F110,"netopen name has colon",namecopy,0);
  3745.         *p++ = '\0';                    /* Get service name or number */
  3746. #ifdef CK_URL
  3747.         /*
  3748.            Here we have to check for various popular syntaxes:
  3749.            host:port (our original syntax)
  3750.            URL such as telnet:host or telnet://host/
  3751.            Or even telnet://user:password@host:port/path/
  3752.            Or a malformed URL such as generated by Netscape 4.0 like:
  3753.            telnet:telnet or telnet::host.
  3754.         */
  3755.  
  3756.         /*
  3757.          * REPLACE THIS CODE WITH urlparse() but not on the day of the
  3758.          * C-Kermit 8.0 RELEASE.
  3759.          */
  3760.  
  3761.         if (*p == ':')                  /* a second colon */
  3762.           *p++ = '\0';                  /* get rid of that one too */
  3763.         while (*p == '/') *p++ = '\0';  /* and slashes */
  3764.         x = strlen(p);                  /* Length of remainder */
  3765.         if (p[x-1] == '/')              /* If there is a trailing slash */
  3766.           p[x-1] = '\0';                /* remove it. */
  3767.         debug(F110,"netopen namecopy after stripping",namecopy,0);
  3768.         debug(F110,"netopen p after stripping",p,0);
  3769.         service = getservbyname(namecopy,"tcp");
  3770.         if (service ||
  3771. #ifdef RLOGCODE
  3772.             !ckstrcmp("rlogin",namecopy,NAMECPYL,0) ||
  3773. #endif /* RLOGCODE */
  3774. #ifdef CK_SSL
  3775.             !ckstrcmp("telnets",namecopy,NAMECPYL,0) ||
  3776. #endif /* CK_SSL */
  3777.             !ckstrcmp("iksd",namecopy,NAMECPYL,0)
  3778.             ) {
  3779.             char temphost[256], tempservice[80], temppath[256];
  3780.             char * q = p, *r = p, *w = p;
  3781.             int uidfound=0;
  3782.             extern char pwbuf[];
  3783.             extern int pwflg, pwcrypt;
  3784.  
  3785.             if (ttnproto == NP_DEFAULT)
  3786.               setnproto(namecopy);
  3787.  
  3788.             /* Check for userid and possibly password */
  3789.             while (*p != '\0' && *p != '@')
  3790.                 p++; /* look for @ */
  3791.             if (*p == '@') {
  3792.                 /* found username and perhaps password */
  3793.                 debug(F110,"netopen namecopy found @","",0);
  3794.                 *p = '\0';
  3795.                 p++;
  3796.                 while (*w != '\0' && *w != ':')
  3797.                   w++;
  3798.                 if (*w == ':')
  3799.                   *w++ = '\0';
  3800.                 /* r now points to username, save it and the password */
  3801.                 debug(F110,"netopen namecopy username",r,0);
  3802.                 debug(F110,"netopen namecopy password",w,0);
  3803.                 uidfound=1;
  3804.                 if ( strcmp(uidbuf,r) || *w )
  3805.                     ckstrncpy(pwbuf,w,PWBUFL+1);
  3806.                 ckstrncpy(uidbuf,r,UIDBUFLEN);
  3807.                 pwflg = 1;
  3808.                 pwcrypt = 0;
  3809.                 q = p;                  /* Host after user and pwd */
  3810.             } else {
  3811.                 p = q;                  /* No username or password */
  3812.             }
  3813.             /* Now we must look for the optional port. */
  3814.             debug(F110,"netopen x p",p,0);
  3815.             debug(F110,"netopen x q",q,0);
  3816.  
  3817.             /* Look for the port/service or a file/directory path */
  3818.             while (*p != '\0' && *p != ':' && *p != '/')
  3819.               p++;
  3820.             if (*p == ':') {
  3821.                 debug(F110,"netopen found port",q,0);
  3822.                 *p++ = '\0';            /* Found a port name or number */
  3823.                 r = p;
  3824.  
  3825.                 /* Look for the end of port/service or a file/directory path */
  3826.                 while (*p != '\0' && *p != '/')
  3827.                     p++;
  3828.                 if (*p == '/')
  3829.                     *p++ = '\0';
  3830.  
  3831.                 debug(F110,"netopen port",r,0);
  3832.                 ckstrncpy(tempservice,r,80);
  3833.                 ckstrncpy(temphost,q,256);
  3834.                 ckstrncpy(temppath,p,256);
  3835.                 ckstrncpy(namecopy,temphost,NAMECPYL);
  3836.                 debug(F110,"netopen tempservice",tempservice,0);
  3837.                 debug(F110,"netopen temphost",temphost,0);
  3838.                 debug(F110,"netopen temppath",temppath,0);
  3839.  
  3840.                 /* move port/service to a buffer that won't go away */
  3841.                 x = strlen(namecopy);
  3842.                 p = namecopy + x + 1;
  3843.                 ckstrncpy(p, tempservice, NAMECPYL - x);
  3844.             } else {
  3845.                 /* Handle a path if we found one */
  3846.                 if (*p == '/')
  3847.                     *p++ = '\0';
  3848.                 ckstrncpy(temppath,p,256);
  3849.  
  3850.                 /* We didn't find another port, but if q is a service */
  3851.                 /* then assume that namecopy is actually a host.      */
  3852.                 if (getservbyname(q,"tcp")) {
  3853.                     p = q;
  3854.                 } else {
  3855. #ifdef RLOGCODE
  3856.                     /* rlogin is not a valid service */
  3857.                     if (!ckstrcmp("rlogin",namecopy,6,0)) {
  3858.                         ckstrncpy(namecopy,"login",NAMECPYL);
  3859.                     }
  3860. #endif /* RLOGCODE */
  3861.                     /* iksd is not a valid service */
  3862.                     if (!ckstrcmp("iksd",namecopy,6,0)) {
  3863.                         ckstrncpy(namecopy,"kermit",NAMECPYL);
  3864.                     }
  3865.                     /* Reconstruct namecopy */
  3866.                     ckstrncpy(tempservice,namecopy,80);
  3867.                     ckstrncpy(temphost,q,256);
  3868.                     ckstrncpy(namecopy,temphost,NAMECPYL);
  3869.                     debug(F110,"netopen tempservice",tempservice,0);
  3870.                     debug(F110,"netopen temphost",temphost,0);
  3871.                     debug(F110,"netopen temppath",temppath,0);
  3872.  
  3873.                     /* move port/service to a buffer that won't go away */
  3874.                     x = strlen(namecopy);
  3875.                     p = namecopy + x + 1;
  3876.                     ckstrncpy(p, tempservice, NAMECPYL - x - 1);
  3877.                 }
  3878.             }
  3879.             debug(F110,"netopen URL result: host",namecopy,0);
  3880.             debug(F110,"netopen URL result: service",p,0);
  3881.             debug(F110,"netopen URL result: path",temppath,0);
  3882.  
  3883. #ifdef IKS_GET
  3884.             /* If we have set a path specified, we need to try to GET it */
  3885.             /* But we have another problem, we have to login first.  How */
  3886.             /* do we specify that a login must be done before the GET?   */
  3887.             /* The user's name if specified is in 'userid' and the       */
  3888.             /* password if any is in 'pwbuf'.                            */
  3889.             if ( temppath[0] ) {
  3890.                 extern int action;
  3891.                 extern char * cmarg;
  3892.  
  3893.                 if ( !uidfound ) {
  3894.                     /* If no userid was specified as part of the URL but
  3895.                      * a path was specified, then we
  3896.                      * set the user name to anonymous and the password
  3897.                      * to the current userid.
  3898.                      */
  3899.                     ckstrncpy(pwbuf,uidbuf,PWBUFL);
  3900.                     ckstrncat(pwbuf,"@",PWBUFL);
  3901.                     pwflg = 1;
  3902.                     pwcrypt = 0;
  3903.                     ckstrncpy(uidbuf,"anonymous",UIDBUFLEN);
  3904.                 }
  3905.  
  3906.                 /*
  3907.                  * If a file path was specified we perform the GET
  3908.                  * operation and then terminate the connection.
  3909.                  *
  3910.                  * If a directory was given instead of a file, then
  3911.                  * we should REMOTE CD to the directory and list its
  3912.                  * contents.  But how do we tell the difference?
  3913.                  */
  3914.                 makestr(&cmarg,temppath);
  3915.                 action = 'r';
  3916.             }
  3917. #endif /* IKS_GET */
  3918.         }
  3919. #endif /* CK_URL */
  3920.     } else {                            /* Otherwise use telnet */
  3921.         p = "telnet";
  3922.     }
  3923. /*
  3924.   By the time we get here, namecopy[] should hold the null-terminated
  3925.   hostname or address, and p should point to the service name or number.
  3926. */
  3927.     debug(F110,"netopen host",namecopy,0);
  3928.     debug(F110,"netopen service requested",p,0);
  3929.  
  3930.    /* Use the service port to set the default protocol type if necessary */
  3931.     if (ttnproto == NP_DEFAULT)
  3932.        setnproto(p);
  3933.  
  3934.     ckstrncpy(namecopy2,namecopy,NAMECPYL);
  3935.     service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3936.     if (!service) {
  3937.         fprintf(stderr, "Can't find port for service %s\n", p);
  3938. #ifdef TGVORWIN
  3939.         debug(F101,"netopen can't get service","",socket_errno);
  3940. #else
  3941.         debug(F101,"netopen can't get service","",errno);
  3942. #endif /* TGVORWIN */
  3943.         errno = 0;                  /* (rather than mislead) */
  3944.         return(-1);
  3945.     } else {
  3946.         if (!ckstrcmp(namecopy,namecopy2,-1,0))
  3947.       namecopy2[0] = '\0';
  3948.         ckstrncpy(svcbuf,ckuitoa(ntohs(service->s_port)),sizeof(svcbuf));
  3949.         debug(F110,"netopen service ok",svcbuf,0);
  3950.     }
  3951.  
  3952. #ifdef RLOGCODE
  3953.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  3954.         fprintf(stderr,
  3955.                 "  Warning: login service on port %d instead of port 513\n",
  3956.                  ntohs(service->s_port)
  3957.                 );
  3958.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  3959.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  3960.     }
  3961. #endif /* RLOGCODE */
  3962.  
  3963. #ifndef NOHTTP
  3964.    /* For HTTP connections we must preserve the original hostname and */
  3965.    /* service requested so we can include them in the Host header.    */
  3966.     ckmakmsg(http_host_port,sizeof(http_host_port),namecopy,":",
  3967.               ckitoa(ntohs(service->s_port)),NULL);
  3968.  
  3969.     /* 'namecopy' contains the name of the host to which we want to connect */
  3970.     /* 'svcbuf'   contains the service name                                 */
  3971.     /* 'service->s_port' contains the port number in network byte order     */
  3972.  
  3973.     /* If we are using an http proxy, we need to create a buffer containing */
  3974.     /*   hostname:port-number                                               */
  3975.     /* to pass to the http_connect() function.  Then we need to replace     */
  3976.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  3977.     /* with the port number of the proxy (default port 80).                 */
  3978.  
  3979.     if ( tcp_http_proxy ) {
  3980.         ckmakmsg(proxycopy,sizeof(proxycopy),namecopy,":",
  3981.                  ckuitoa(ntohs(service->s_port)),NULL);
  3982.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  3983.  
  3984.         p = namecopy;                       /* Was a service requested? */
  3985.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3986.         if (*p == ':') {                    /* Have a colon */
  3987.             debug(F110,"netopen name has colon",namecopy,0);
  3988.             *p++ = '\0';                    /* Get service name or number */
  3989.         } else {
  3990.             strcpy(++p,"http");
  3991.         }
  3992.  
  3993.         service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3994.         if (!service) {
  3995.             fprintf(stderr, "Can't find port for service %s\n", p);
  3996. #ifdef TGVORWIN
  3997.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  3998. #else
  3999.             debug(F101,"netopen can't get service for proxy","",errno);
  4000. #endif /* TGVORWIN */
  4001.             errno = 0;                  /* (rather than mislead) */
  4002.             return(-1);
  4003.         }
  4004.         ckstrncpy(p,ckuitoa(ntohs(service->s_port)),NAMECPYL-(p-namecopy));
  4005.  
  4006.     }
  4007. #endif /* NOHTTP */
  4008.  
  4009.     /* Set up socket structure and get host address */
  4010.  
  4011.     bzero((char *)&r_addr, sizeof(r_addr));
  4012.     debug(F100,"netopen bzero ok","",0);
  4013. /*
  4014.    NOTE: Originally the inet_addr() check was #ifdef NT, but is enabled for
  4015.    all as of 20 Sep 97, to allow people to "set host" to a specific numeric IP
  4016.    address without going through the multihomed host sequence and winding up
  4017.    at a different place than the one requested.
  4018. */
  4019. #ifdef INADDR_NONE
  4020.     debug(F101,"netopen INADDR_NONE defined","",INADDR_NONE);
  4021. #else /* INADDR_NONE */
  4022.     debug(F100,"netopen INADDR_NONE not defined","",0);
  4023. #endif /* INADDR_NONE */
  4024. #ifdef INADDRX
  4025.     debug(F100,"netopen INADDRX defined","",0);
  4026. #else /* INADDRX */
  4027.     debug(F100,"netopen INADDRX not defined","",0);
  4028. #endif /* INADDRX */
  4029.  
  4030. #ifndef NOMHHOST
  4031. #ifdef INADDRX
  4032.     iax = inet_addr(namecopy);
  4033.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  4034. #else /* INADDRX */
  4035. #ifdef INADDR_NONE
  4036.     iax.s_addr = inet_addr(namecopy);
  4037.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  4038. #else /* INADDR_NONE */
  4039. #ifndef datageneral
  4040.     iax = (unsigned int) inet_addr(namecopy);
  4041. #else
  4042.     iax = -1L;
  4043. #endif /* datageneral */
  4044.     debug(F111,"netopen inet_addr",namecopy,iax);
  4045. #endif /* INADDR_NONE */
  4046. #endif /* INADDRX */
  4047.  
  4048.     dns = 0;
  4049.     if (
  4050. #ifdef INADDR_NONE
  4051.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  4052. #else /* INADDR_NONE */
  4053.         iax < 0
  4054. #endif /* INADDR_NONE */
  4055.         ) {
  4056.         if (!quiet) {
  4057.             printf(" DNS Lookup... ");
  4058.             fflush(stdout);
  4059.         }
  4060.         if ((host = gethostbyname(namecopy)) != NULL) {
  4061.             debug(F100,"netopen gethostbyname != NULL","",0);
  4062.             host = ck_copyhostent(host);
  4063.             dns = 1;                    /* Remember we performed dns lookup */
  4064.             r_addr.sin_family = host->h_addrtype;
  4065.             if (host->h_name && host->h_name[0]
  4066. #ifndef NOHTTP
  4067.                  && (tcp_http_proxy == NULL)
  4068. #endif /* NOHTTP */
  4069.                  ) {                   /* Copying into our argument? */
  4070.                 ckstrncpy(name,host->h_name,80);  /* Bad Bad Bad */
  4071.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4072.                     strncat(name,":",80-strlen(name));
  4073.                     strncat(name,svcbuf,80-strlen(name));
  4074.                 }
  4075.             }
  4076.  
  4077. #ifdef HADDRLIST
  4078. #ifdef h_addr
  4079.             /* This is for trying multiple IP addresses - see <netdb.h> */
  4080.             if (!(host->h_addr_list))
  4081.               return(-1);
  4082.             bcopy(host->h_addr_list[0],
  4083.                   (caddr_t)&r_addr.sin_addr,
  4084.                   host->h_length
  4085.                   );
  4086. #else
  4087.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4088. #endif /* h_addr */
  4089. #else  /* HADDRLIST */
  4090.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4091. #endif /* HADDRLIST */
  4092. #ifndef EXCELAN
  4093.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  4094. #endif /* EXCELAN */
  4095.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  4096.                   (caddr_t)&r_addr.sin_addr);
  4097.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  4098.                   r_addr.sin_addr.s_addr);
  4099.             debug(F111,"BCOPY","host->h_length",host->h_length);
  4100.         }
  4101.     }
  4102. #endif /* NOMHHOST */
  4103.  
  4104.     if (!dns) {
  4105. #ifdef INADDRX
  4106. /* inet_addr() is of type struct in_addr */
  4107.         struct in_addr ina;
  4108.         unsigned long uu;
  4109.         debug(F100,"netopen gethostbyname == NULL: INADDRX","",0);
  4110.         ina = inet_addr(namecopy);
  4111.         uu = *(unsigned int *)&ina;
  4112. #else /* Not INADDRX */
  4113. /* inet_addr() is unsigned long */
  4114.         unsigned long uu;
  4115.         debug(F100,"netopen gethostbyname == NULL: Not INADDRX","",0);
  4116.         uu = inet_addr(namecopy);
  4117. #endif /* INADDRX */
  4118.         debug(F101,"netopen uu","",uu);
  4119.         if (
  4120. #ifdef INADDR_NONE
  4121.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  4122. #else   /* INADDR_NONE */
  4123.             uu != ((unsigned long)-1)
  4124. #endif /* INADDR_NONE */
  4125.             ) {
  4126.             r_addr.sin_addr.s_addr = uu;
  4127.             r_addr.sin_family = AF_INET;
  4128.         } else {
  4129. #ifdef VMS
  4130.             fprintf(stdout, "\r\n");    /* complete any previous message */
  4131. #endif /* VMS */
  4132.             fprintf(stderr, "Can't get address for %s\n", namecopy);
  4133. #ifdef TGVORWIN
  4134.             debug(F101,"netopen can't get address","",socket_errno);
  4135. #else
  4136.             debug(F101,"netopen can't get address","",errno);
  4137. #endif /* TGVORWIN */
  4138.             errno = 0;                  /* Rather than mislead */
  4139.             return(-1);
  4140.         }
  4141.     }
  4142.  
  4143.     /* Get a file descriptor for the connection. */
  4144.  
  4145.     r_addr.sin_port = service->s_port;
  4146.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4147.     debug(F110,"netopen trying",ipaddr,0);
  4148.     if (!quiet && *ipaddr) {
  4149.         printf(" Trying %s... ", ipaddr);
  4150.         fflush(stdout);
  4151.     }
  4152.  
  4153.     /* Loop to try additional IP addresses, if any. */
  4154.  
  4155.     do {
  4156. #ifdef EXCELAN
  4157.         send_socket.sin_family = AF_INET;
  4158.         send_socket.sin_addr.s_addr = 0;
  4159.         send_socket.sin_port = 0;
  4160.         if ((ttyfd = socket(SOCK_STREAM, (struct sockproto *)0,
  4161.                             &send_socket, SO_REUSEADDR)) < 0)
  4162. #else  /* EXCELAN */
  4163. #ifdef NT
  4164. #ifdef COMMENT_X
  4165.        /*
  4166.          Must make sure that all sockets are opened in
  4167.          Non-overlapped mode since we use the standard
  4168.          C RTL functions to read and write data.
  4169.          But it doesn't seem to work as planned.
  4170.        */
  4171.           {
  4172.               int optionValue = SO_SYNCHRONOUS_NONALERT;
  4173.               if (setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
  4174.                              (char *) &optionValue, sizeof(optionValue))
  4175.                   != NO_ERROR)
  4176.                 return(-1);
  4177.           }
  4178. #endif /* COMMENT */
  4179. #endif /* NT */
  4180.  
  4181.         if ((ttyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  4182. #endif /* EXCELAN */
  4183.             {
  4184. #ifdef EXCELAN
  4185.                 experror("TCP socket error");
  4186. #else
  4187. #ifdef VMS
  4188.                 fprintf(stdout, "\r\n"); /* complete any previous stdout */
  4189. #endif /* VMS */
  4190. #ifdef TGVORWIN
  4191. #ifdef OLD_TWG
  4192.                 errno = socket_errno;
  4193. #endif /* OLD_TWG */
  4194.                 socket_perror("TCP socket error");
  4195.                 debug(F101,"netopen socket error","",socket_errno);
  4196. #else
  4197.                 perror("TCP socket error");
  4198.                 debug(F101,"netopen socket error","",errno);
  4199. #endif /* TGVORWIN */
  4200. #endif /* EXCELAN */
  4201.                 return (-1);
  4202.             }
  4203.         errno = 0;
  4204.  
  4205. #ifdef RLOGCODE
  4206.        /* Not part of the RLOGIN RFC, but the BSD implementation     */
  4207.        /* requires that the client port be a priviliged port (<1024) */
  4208.        /* on a Unix system this would require SuperUser permissions  */
  4209.        /* thereby saying that the root of the Unix system has given  */
  4210.        /* permission for this connection to be created               */
  4211.        if (service->s_port == htons((unsigned short)RLOGIN_PORT)) {
  4212.            static unsigned short lport = 1024;  /* max reserved port */
  4213. #ifdef OS2
  4214.            int s_errno;
  4215. #endif /* OS2 */
  4216.  
  4217.            lport--;                     /* Make sure we do not reuse a port */
  4218.            if (lport == 512)
  4219.              lport = 1023;
  4220.  
  4221.            sin.sin_family = AF_INET;
  4222.            if (tcp_address) {
  4223. #ifdef INADDRX
  4224.                inaddrx = inet_addr(tcp_address);
  4225.                sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4226. #else
  4227.                sin.sin_addr.s_addr = inet_addr(tcp_address);
  4228. #endif /* INADDRX */
  4229.            } else
  4230.              sin.sin_addr.s_addr = INADDR_ANY;
  4231.            while (1) {
  4232.                sin.sin_port = htons(lport);
  4233.                if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
  4234.                  break;
  4235. #ifdef OS2
  4236.                s_errno = socket_errno;
  4237.                if (s_errno && /* OS2 bind fails with 0, if already in use */
  4238. #ifdef NT
  4239.                    s_errno != WSAEADDRINUSE
  4240. #else
  4241.                    s_errno != SOCEADDRINUSE &&
  4242.                    s_errno != (SOCEADDRINUSE - SOCBASEERR)
  4243. #endif /* NT */
  4244.                    )
  4245. #else /* OS2 */
  4246. #ifdef TGVORWIN
  4247.                  if (socket_errno != EADDRINUSE)
  4248. #else
  4249.                  if (errno != EADDRINUSE)
  4250. #endif /* TGVORWIN */
  4251. #endif /* OS2 */
  4252.                    {
  4253. #ifdef COMMENT
  4254.                        printf("\nBind failed with errno %d  for port %d.\n",
  4255. #ifdef OS2
  4256.                               s_errno
  4257. #else
  4258. #ifdef TGVORWIN
  4259.                               socket_errno
  4260. #else
  4261.                               errno
  4262. #endif /* TGVORWIN */
  4263. #endif /* OS2 */
  4264.                               , lport
  4265.                               );
  4266. #ifdef OS2
  4267.                        debug(F101,"rlogin bind failed","",s_errno);
  4268. #else
  4269. #ifdef TGVORWIN
  4270.                        debug(F101,"rlogin bind failed","",socket_errno);
  4271. #ifdef OLD_TWG
  4272.                        errno = socket_errno;
  4273. #endif /* OLD_TWG */
  4274.                        socket_perror("rlogin bind");
  4275. #else
  4276.                        debug(F101,"rlogin bind failed","",errno);
  4277.                        perror("rlogin bind");
  4278. #endif /* TGVORWIN */
  4279. #endif /* OS2 */
  4280. #else  /* COMMENT */
  4281. #ifdef OS2
  4282.                        debug(F101,"rlogin bind s_errno","",s_errno);
  4283.                        perror("rlogin bind");
  4284. #else
  4285. #ifdef VMS
  4286.                        printf("\r\n");  /* complete any previous message */
  4287. #endif /* VMS */
  4288. #ifdef TGVORWIN
  4289.                        debug(F101,"rlogin bind socket_errno","",socket_errno);
  4290. #ifdef OLD_TWG
  4291.                        errno = socket_errno;
  4292. #endif /* OLD_TWG */
  4293.                        socket_perror("rlogin bind");
  4294. #else
  4295.                        debug(F101,"rlogin bind errno","",errno);
  4296.                        perror("rlogin bind");
  4297. #endif /* TGVORWIN */
  4298. #endif /* OS2 */
  4299.                        debug(F101,"rlogin local port","",lport);
  4300. #endif /* COMMENT */
  4301.                        netclos();
  4302.                        return -1;
  4303.                    }
  4304.                lport--;
  4305.                if (lport == 512 /* lowest reserved port to use */ ) {
  4306.                    printf("\nNo reserved ports available.\n");
  4307.                    netclos();
  4308.                    return -1;
  4309.                }
  4310.            }
  4311.            debug(F101,"rlogin lport","",lport);
  4312.            ttnproto = NP_RLOGIN;
  4313.        } else
  4314. #endif /* RLOGCODE  */
  4315.  
  4316.        /* If a specific TCP address on the local host is desired we */
  4317.        /* must bind it to the socket.                               */
  4318. #ifndef datageneral
  4319.          if (tcp_address) {
  4320.              int s_errno;
  4321.  
  4322.              debug(F110,"netopen binding socket to",tcp_address,0);
  4323.              bzero((char *)&sin,sizeof(sin));
  4324.              sin.sin_family = AF_INET;
  4325. #ifdef INADDRX
  4326.              inaddrx = inet_addr(tcp_address);
  4327.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4328. #else
  4329.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  4330. #endif /* INADDRX */
  4331.              sin.sin_port = 0;
  4332.              if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  4333.                  s_errno = socket_errno; /* Save error code */
  4334. #ifdef TCPIPLIB
  4335.                  socket_close(ttyfd);
  4336. #else /* TCPIPLIB */
  4337.                  close(ttyfd);
  4338. #endif /* TCPIPLIB */
  4339.                  ttyfd = -1;
  4340.                  wasclosed = 1;
  4341.                  errno = s_errno;       /* and report this error */
  4342.                  debug(F101,"netopen bind errno","",errno);
  4343.                  return(-1);
  4344.              }
  4345.          }
  4346. #endif /* datageneral */
  4347.  
  4348. /* Now connect to the socket on the other end. */
  4349.  
  4350. #ifdef EXCELAN
  4351.         if (connect(ttyfd, &r_addr) < 0)
  4352. #else
  4353. #ifdef NT
  4354.           WSASafeToCancel = 1;
  4355. #endif /* NT */
  4356.         if (connect(ttyfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  4357. #endif /* EXCELAN */
  4358.           {
  4359. #ifdef NT
  4360.               WSASafeToCancel = 0;
  4361. #endif /* NT */
  4362. #ifdef OS2
  4363.               i = socket_errno;
  4364. #else /* OS2 */
  4365. #ifdef TGVORWIN
  4366.               i = socket_errno;
  4367. #else
  4368.               i = errno;                /* Save error code */
  4369. #endif /* TGVORWIN */
  4370. #endif /* OS2 */
  4371. #ifdef RLOGCODE
  4372.               if (
  4373. #ifdef OS2
  4374.                  i && /* OS2 bind fails with 0, if already in use */
  4375. #ifdef NT
  4376.                  i == WSAEADDRINUSE
  4377. #else
  4378.                  (i == SOCEADDRINUSE ||
  4379.                  i == (SOCEADDRINUSE - SOCBASEERR))
  4380. #endif /* NT */
  4381. #else /* OS2 */
  4382. #ifdef TGVORWIN
  4383.                   socket_errno == EADDRINUSE
  4384. #else
  4385.                   errno == EADDRINUSE
  4386. #endif /* TGVORWIN */
  4387. #endif /* OS2 */
  4388.                   && ttnproto == NP_RLOGIN) {
  4389. #ifdef TCPIPLIB
  4390.                    socket_close(ttyfd); /* Close it. */
  4391. #else
  4392.                    close(ttyfd);
  4393. #endif /* TCPIPLIB */
  4394.                    continue;            /* Try a different lport */
  4395.                }
  4396. #endif /* RLOGCODE */
  4397. #ifdef HADDRLIST
  4398. #ifdef h_addr
  4399.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  4400.                   perror("");
  4401.                   host->h_addr_list++;
  4402.                   bcopy(host->h_addr_list[0],
  4403.                         (caddr_t)&r_addr.sin_addr,
  4404.                         host->h_length);
  4405.  
  4406.                   ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4407.                   debug(F110,"netopen h_addr_list",ipaddr,0);
  4408.                   if (!quiet && *ipaddr) {
  4409.                       printf(" Trying %s... ", ipaddr);
  4410.                       fflush(stdout);
  4411.                   }
  4412. #ifdef TCPIPLIB
  4413.                   socket_close(ttyfd); /* Close it. */
  4414. #else
  4415.                   close(ttyfd);
  4416. #endif /* TCPIPLIB */
  4417.                   continue;
  4418.               }
  4419. #endif /* h_addr */
  4420. #endif  /* HADDRLIST */
  4421.               netclos();
  4422.               ttyfd = -1;
  4423.               wasclosed = 1;
  4424.               ttnproto = NP_NONE;
  4425.               errno = i;                /* And report this error */
  4426. #ifdef EXCELAN
  4427.               if (errno) experror("netopen connect");
  4428. #else
  4429. #ifdef TGVORWIN
  4430.               debug(F101,"netopen connect error","",socket_errno);
  4431.               /* if (errno) socket_perror("netopen connect"); */
  4432. #ifdef OLD_TWG
  4433.               errno = socket_errno;
  4434. #endif /* OLD_TWG */
  4435.               if (!quiet)
  4436.                 socket_perror("netopen connect");
  4437. #else /* TGVORWIN */
  4438.               debug(F101,"netopen connect errno","",errno);
  4439. #ifdef VMS
  4440.               if (!quiet)
  4441.                 perror("\r\nFailed");
  4442. #else
  4443.               if (!quiet)
  4444.                 perror("Failed");
  4445. #endif /* VMS */
  4446. #ifdef DEC_TCPIP
  4447.               if (!quiet)
  4448.                 perror("netopen connect");
  4449. #endif /* DEC_TCPIP */
  4450. #ifdef CMU_TCPIP
  4451.               if (!quiet)
  4452.                 perror("netopen connect");
  4453. #endif /* CMU_TCPIP */
  4454. #endif /* TGVORWIN */
  4455. #endif /* EXCELAN */
  4456.               return(-1);
  4457.           }
  4458. #ifdef NT
  4459.         WSASafeToCancel = 0;
  4460. #endif /* NT */
  4461.         isconnect = 1;
  4462.     } while (!isconnect);
  4463.  
  4464. #ifdef NON_BLOCK_IO
  4465.     on = 1;
  4466.     x = socket_ioctl(ttyfd,FIONBIO,&on);
  4467.     debug(F101,"netopen FIONBIO","",x);
  4468. #endif /* NON_BLOCK_IO */
  4469.  
  4470. #ifdef NT_TCP_OVERLAPPED
  4471.     OverlappedWriteInit();
  4472.     OverlappedReadInit();
  4473. #endif /* NT_TCP_OVERLAPPED */
  4474.  
  4475.     ttnet = nett;                       /* TCP/IP (sockets) network */
  4476.  
  4477. #ifndef NOHTTP
  4478.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  4479.     /* need to attempt to connect through the proxy to the actual host */
  4480.     /* If that is successful, we have to pretend that we made a direct */
  4481.     /* connection to the actual host.                                  */
  4482.  
  4483.     if ( tcp_http_proxy ) {
  4484. #ifdef OS2
  4485.         char * agent = "Kermit 95";             /* Default user agent */
  4486. #else
  4487.         char * agent = "C-Kermit";
  4488. #endif /* OS2 */
  4489.  
  4490.         if (http_connect(ttyfd,agent,NULL,
  4491.                          tcp_http_proxy_user,
  4492.                          tcp_http_proxy_pwd,
  4493.                          0,
  4494.                          proxycopy
  4495.                          ) < 0) {
  4496.             netclos();
  4497.             return(-1);
  4498.         }
  4499.  
  4500.         ckstrncpy(namecopy,proxycopy,NAMECPYL);
  4501.         p = namecopy;                       /* Was a service requested? */
  4502.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  4503.         *p = '\0';
  4504.     }
  4505. #endif /* NOHTTP */
  4506.  
  4507.     /* Jeff - Does this next block of code that set's the protocol */
  4508.     /* need to be here anymore?  5/10/2000                         */
  4509.  
  4510.     /* There are certain magic port numbers that when used require */
  4511.     /* the use of specific protocols.  Check this now before we    */
  4512.     /* set the SO_OOBINLINE state or we might get it wrong.        */
  4513.     x = ntohs((unsigned short)service->s_port);
  4514.     svcnum = x;
  4515.     /* See if the service is TELNET. */
  4516.     if (x == TELNET_PORT) {
  4517.         /* Yes, so if raw port not requested */
  4518.         if (ttnproto != NP_TCPRAW && ttnproto != NP_NONE)
  4519.           ttnproto = NP_TELNET;         /* Select TELNET protocol. */
  4520.     }
  4521. #ifdef RLOGCODE
  4522.     else if (x == RLOGIN_PORT) {
  4523.         ttnproto = NP_RLOGIN;
  4524.     }
  4525. #ifdef CK_KERBEROS
  4526.     /* There is no good way to do this.  If the user didn't tell    */
  4527.     /* which one to use up front.  We may guess wrong if the user   */
  4528.     /* has both Kerberos versions installed and valid TGTs for each */
  4529.     else if (x == KLOGIN_PORT &&
  4530.              ttnproto != NP_K4LOGIN &&
  4531.              ttnproto != NP_K5LOGIN) {
  4532.         if (ck_krb5_is_installed() &&
  4533.             ck_krb5_is_tgt_valid())
  4534.           ttnproto = NP_K5LOGIN;
  4535.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4536.           ttnproto = NP_K4LOGIN;
  4537.         else
  4538.           ttnproto = NP_K4LOGIN;
  4539.     } else if (x == EKLOGIN_PORT &&
  4540.                ttnproto != NP_EK4LOGIN &&
  4541.                ttnproto != NP_EK5LOGIN) {
  4542.         if (ck_krb5_is_installed() && ck_krb5_is_tgt_valid())
  4543.           ttnproto = NP_EK5LOGIN;
  4544.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4545.           ttnproto = NP_EK4LOGIN;
  4546.         else
  4547.           ttnproto = NP_EK4LOGIN;
  4548.     }
  4549. #endif /* CK_KERBEROS */
  4550. #endif /* RLOGCODE */
  4551. #ifdef IKS_OPTION
  4552.     else if (x == KERMIT_PORT) {        /* IKS uses Telnet protocol */
  4553.         if (ttnproto == NP_NONE)
  4554.           ttnproto = NP_KERMIT;
  4555.     }
  4556. #endif /* IKS_OPTION */
  4557.  
  4558. #ifdef SO_OOBINLINE
  4559. /*
  4560.   The symbol SO_OOBINLINE is not known to Ultrix 2.0.
  4561.   It means "leave out of band data inline".  The normal value is 0x0100,
  4562.   but don't try this on systems where the symbol is undefined.
  4563. */
  4564. /*
  4565.   Note from Jeff Altman: 12/13/95
  4566.   In implementing rlogin protocol I have come to the conclusion that it is
  4567.   a really bad idea to read out-of-band data inline.
  4568.   At least Windows and OS/2 does not handle this well.
  4569.   And if you need to know that data is out-of-band, then it becomes
  4570.   absolutely pointless.
  4571.  
  4572.   Therefore, at least on OS2 and Windows (NT) I have changed the value of
  4573.   on to 0, so that out-of-band data stays out-of-band.
  4574.  
  4575.   12/18/95
  4576.   Actually, OOB data should be read inline when possible.  Especially with
  4577.   protocols that don't care about the Urgent flag.  This is true with Telnet.
  4578.   With Rlogin, you need to be able to catch OOB data.  However, the best
  4579.   way to do this is to set a signal handler on SIGURG.  This isn't possible
  4580.   on OS/2 and Windows.  But it is in UNIX.  We will also need OOB data for
  4581.   FTP so better create a general mechanism.
  4582.  
  4583.   The reason for making OOB data be inline is that the standard ttinc/ttoc
  4584.   calls can be used for reading that data on UNIX systems.  If we didn't
  4585.   have the OOBINLINE option set then we would have to use recv(,MSG_OOB)
  4586.   to read it.
  4587. */
  4588. #ifdef RLOGCODE
  4589. #ifdef TCPIPLIB
  4590.     if (ttnproto == NP_RLOGIN
  4591. #ifdef CK_KERBEROS
  4592.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4593.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4594. #endif /* CK_KERBEROS */
  4595.       )
  4596.       on = 0;
  4597. #else /* TCPIPLIB */
  4598.     if (ttnproto == NP_RLOGIN
  4599. #ifdef CK_KERBEROS
  4600.          || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4601.          || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4602. #endif /* CK_KERBEROS */
  4603.          ) {
  4604.         debug(F100,"Installing rlogoobh on SIGURG","",0);
  4605.         signal(SIGURG, rlogoobh);
  4606.         on = 0;
  4607.     } else {
  4608.         debug(F100,"Ignoring SIGURG","",0);
  4609.         signal(SIGURG, SIG_DFL);
  4610.     }
  4611. #endif /* TCPIPLIB */
  4612. #endif /* RLOGCODE */
  4613.  
  4614. #ifdef datageneral
  4615.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4616. #else
  4617. #ifdef BSD43
  4618.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4619. #else
  4620. #ifdef OSF1
  4621.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4622. #else
  4623. #ifdef POSIX
  4624.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4625. #else
  4626. #ifdef MOTSV88R4
  4627.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4628. #else
  4629. #ifdef SOLARIS
  4630. /*
  4631.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  4632.   compiling and working fine on all the others, so best not to change it.
  4633. */
  4634.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4635. #else
  4636. #ifdef OSK
  4637.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4638. #else
  4639. #ifdef OS2
  4640.     {
  4641.         int rc;
  4642.         rc = setsockopt(ttyfd,
  4643.                         SOL_SOCKET,
  4644.                         SO_OOBINLINE,
  4645.                         (char *) &on,
  4646.                         sizeof on
  4647.                         );
  4648.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  4649.     }
  4650. #else
  4651. #ifdef VMS /* or, at least, VMS with gcc */
  4652.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4653. #else
  4654. #ifdef CLIX
  4655.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4656. #else
  4657.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  4658. #endif /* CLIX */
  4659. #endif /* VMS */
  4660. #endif /* OS2 */
  4661. #endif /* OSK */
  4662. #endif /* SOLARIS */
  4663. #endif /* MOTSV88R4 */
  4664. #endif /* POSIX */
  4665. #endif /* BSD43 */
  4666. #endif /* OSF1 */
  4667. #endif /* datageneral */
  4668. #endif /* SO_OOBINLINE */
  4669.  
  4670. #ifndef NOTCPOPTS
  4671. #ifndef datageneral
  4672. #ifdef SOL_SOCKET
  4673. #ifdef TCP_NODELAY
  4674.     no_delay(ttyfd,tcp_nodelay);
  4675. #endif /* TCP_NODELAY */
  4676. #ifdef SO_KEEPALIVE
  4677.     keepalive(ttyfd,tcp_keepalive);
  4678. #endif /* SO_KEEPALIVE */
  4679. #ifdef SO_LINGER
  4680.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  4681. #endif /* SO_LINGER */
  4682. #ifdef SO_SNDBUF
  4683.     sendbuf(ttyfd,tcp_sendbuf);
  4684. #endif /* SO_SNDBUF */
  4685. #ifdef SO_RCVBUF
  4686.     recvbuf(ttyfd,tcp_recvbuf);
  4687. #endif /* SO_RCVBUF */
  4688. #endif /* SOL_SOCKET */
  4689. #endif /* datageneral */
  4690. #endif /* NOTCPOPTS */
  4691.  
  4692. #ifndef datageneral
  4693.     /* Find out our own IP address. */
  4694.     /* We need the l_addr structure for [E]KLOGIN. */
  4695.     l_slen = sizeof(l_addr);
  4696.     bzero((char *)&l_addr, l_slen);
  4697. #ifndef EXCELAN
  4698.     if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  4699.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  4700.         ckstrncpy(myipaddr, s, 20);
  4701.         debug(F110,"getsockname",myipaddr,0);
  4702.     }
  4703. #endif /* EXCELAN */
  4704. #endif /* datageneral */
  4705.  
  4706. /*
  4707.   This is really only needed for Kerberos IV but is useful information in any
  4708.   case.  If we connect to a name that is really a pool, we need to get the
  4709.   name of the machine we are actually connecting to for K4 to authenticate
  4710.   properly.  This way we also update the names properly.
  4711.  
  4712.   However, it is a security hole when used with insecure DNS.
  4713.  
  4714.   Note: This does not work on Windows 95 or Windows NT 3.5x.  This is because
  4715.   of the Microsoft implementation of gethostbyaddr() in both Winsock 1.1
  4716.   and Winsock 2.0 on those platforms.  Their algorithm is:
  4717.  
  4718.   1. Check the HOSTENT cache.
  4719.   2. Check the HOSTS file at %SystemRoot%\System32\DRIVERS\ETC.
  4720.   3. Do a DNS query if the DNS server is configured for name resolution.
  4721.   4. Do an additional NetBIOS remote adapter status to an IP address for its
  4722.      NetBIOS name table. This step is specific only to the Windows NT version
  4723.      3.51 implementation.
  4724.  
  4725.   The problem is the use of the HOSTENT cache.  It means that gethostbyaddr()
  4726.   can not be used to resolve the real name of machine if it was originally
  4727.   accessed by an alias used to represent a cluster.
  4728. */
  4729.      if ((tcp_rdns && dns || tcp_rdns == SET_ON
  4730. #ifdef CK_KERBEROS
  4731.          || tcp_rdns == SET_AUTO &&
  4732.           (ck_krb5_is_installed() || ck_krb4_is_installed())
  4733. #endif /* CK_KERBEROS */
  4734.          )
  4735. #ifndef NOHTTP
  4736.           && (tcp_http_proxy == NULL)
  4737. #endif /* NOHTTP */
  4738. #ifdef CK_SSL
  4739.           && !(ssl_only_flag || tls_only_flag)
  4740. #endif /* CK_SSL */
  4741.          ) {
  4742. #ifdef NT
  4743.         if (isWin95())
  4744.           sleep(1);
  4745. #endif /* NT */
  4746.         if (!quiet) {
  4747.             printf(" Reverse DNS Lookup... ");
  4748.             fflush(stdout);
  4749.         }
  4750.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  4751.             char * s;
  4752.             host = ck_copyhostent(host);
  4753.             debug(F100,"netopen gethostbyname != NULL","",0);
  4754.             if (!quiet) {
  4755.                 printf("(OK)\n");
  4756.                 fflush(stdout);
  4757.             }
  4758.             s = host->h_name;
  4759.             if (!s) {                   /* This can happen... */
  4760.                 debug(F100,"netopen host->h_name is NULL","",0);
  4761.                 s = "";
  4762.             }
  4763.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  4764.             /* The compiler says "Integral value implicitly converted to */
  4765.             /* pointer in assignment."  The prototype is right there */
  4766.             /* in <arpa/inet.h> so what's the problem? */
  4767.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  4768.             if (!*s) {                  /* No name so substitute the address */
  4769.                 debug(F100,"netopen host->h_name is empty","",0);
  4770.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  4771.                 if (!s)                 /* Trust No 1 */
  4772.                   s = "";
  4773.                 if (*s) {               /* If it worked, use this string */
  4774.                     ckstrncpy(ipaddr,s,20);
  4775.                 }
  4776.                 s = ipaddr;             /* Otherwise stick with the IP */
  4777.                 if (!*s)                /* or failing that */
  4778.                   s = namecopy;         /* the name we were called with. */
  4779.             }
  4780.             if (*s) {                   /* Copying into our argument? */
  4781.                 ckstrncpy(name,s,80);   /* Bad Bad Bad */
  4782.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4783.                     strncat(name,":",80-strlen(name));
  4784.                     strncat(name,svcbuf,80-strlen(name));
  4785.                 }
  4786.             }
  4787.             if (!quiet && *s
  4788. #ifndef NOICP
  4789.                 && !doconx
  4790. #endif /* NOICP */
  4791.                 ) {
  4792.                 printf(" %s connected on port %s\n",s,p);
  4793. #ifdef BETADEBUG
  4794.                 /* This is simply for testing the DNS entries */
  4795.                 if (host->h_aliases) {
  4796.                     char ** a = host->h_aliases;
  4797.                     while (*a) {
  4798.                         printf(" alias => %s\n",*a);
  4799.                         a++;
  4800.                     }
  4801.                 }
  4802. #endif /* BETADEBUG */
  4803.             }
  4804.         } else {
  4805.             if (!quiet) printf("Failed.\n");
  4806.         }
  4807.     } else if (!quiet) printf("(OK)\n");
  4808.     if (!quiet) fflush(stdout);
  4809.  
  4810.     /* This should already have been done but just in case */
  4811.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4812.  
  4813. #ifdef CK_SECURITY
  4814.  
  4815.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  4816. #ifndef NOHTTP
  4817.     if (tcp_http_proxy) {
  4818.         for (i=strlen(proxycopy); i >= 0 ; i--)
  4819.             if ( proxycopy[i] == ':' )
  4820.                 proxycopy[i] = '\0';
  4821.     }
  4822. #endif /* NOHTTP */
  4823.     ck_auth_init(
  4824. #ifndef NOHTTP
  4825.                  tcp_http_proxy ? proxycopy :
  4826. #endif /* NOHTTP */
  4827.                  (host && host->h_name && host->h_name[0]) ?
  4828.                  (char *)host->h_name : (namecopy2[0] ? namecopy2 : 
  4829.                                         (namecopy[0] ? namecopy : ipaddr)),
  4830.                  ipaddr,
  4831.                  uidbuf,
  4832.                  ttyfd
  4833.                  );
  4834. #endif /* CK_SECURITY */
  4835. #ifdef CK_SSL
  4836.     if (ck_ssleay_is_installed()) {
  4837.         if (!ssl_tn_init(SSL_CLIENT)) {
  4838.             debug(F100,"netopen ssl_tn_init() failed","",0);
  4839.             if (bio_err!=NULL) {
  4840.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  4841.                 ERR_print_errors(bio_err);
  4842.             } else {
  4843.                 fflush(stderr);
  4844.                 fprintf(stderr,"ssl_tn_init() failed\n");
  4845.                 ERR_print_errors_fp(stderr);
  4846.             }
  4847.             if (tls_only_flag || ssl_only_flag) {
  4848.                 debug(F100,"netopen ssl/tls required","",0);
  4849.                 netclos();
  4850.                 return(-1);
  4851.             }
  4852.  
  4853.             /* we will continue to accept the connection   */
  4854.             /* without SSL or TLS support unless required. */
  4855.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4856.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4857.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4858.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4859.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4860.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4861.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4862.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4863.         } else if ( ck_ssl_outgoing(ttyfd) < 0 ) {
  4864.             debug(F100,"ck_ssl_outgoing() failed","",0);
  4865.             netclos();
  4866.             return(-1);
  4867.         }
  4868.     }
  4869. #endif /* CK_SSL */
  4870.  
  4871. #ifdef RLOGCODE
  4872.     if (ttnproto == NP_RLOGIN
  4873. #ifdef CK_KERBEROS
  4874.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4875.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4876. #endif /* CK_KERBEROS */
  4877.         ) {                             /* Similar deal for rlogin */
  4878.         if (rlog_ini(((host && host->h_name && host->h_name[0]) ?
  4879.                       (CHAR *)host->h_name : (CHAR *)ipaddr),
  4880.                      service->s_port,
  4881.                      &l_addr,&r_addr
  4882.                      ) < 0) {
  4883.             debug(F100,"rlogin initialization failed","",0);
  4884.             netclos();
  4885.             return(-1);
  4886.         }
  4887.     } else
  4888. #endif /* RLOGCODE */
  4889.     if (tn_ini() < 0) {                 /* Start Telnet negotiations. */
  4890.         netclos();
  4891.         return(-1);                     /* Gone, so open failed.  */
  4892.     }
  4893.     if (ttchk() < 0) {
  4894.         netclos();
  4895.         return(-1);
  4896.     }
  4897. #ifdef CK_KERBEROS
  4898. #ifdef KRB5_U2U
  4899.    if ( ttnproto == NP_K5U2U ) {
  4900.        if (k5_user_to_user_client_auth()) {
  4901.            netclos();
  4902.            return(-1);
  4903.        }
  4904.    }
  4905. #endif /* KRB5_U2U */
  4906. #endif /* CK_KERBEROS */
  4907.  
  4908.     debug(F101,"netopen service","",svcnum);
  4909.     debug(F110,"netopen name",name,0);
  4910.  
  4911.     if (lcl) if (*lcl < 0)              /* Local mode. */
  4912.       *lcl = 1;
  4913. #endif /* TCPSOCKET */
  4914.     return(0);                          /* Done. */
  4915. }
  4916.  
  4917. /*  N E T C L O S  --  Close current network connection.  */
  4918.  
  4919. #ifndef NOLOCAL
  4920. _PROTOTYP(VOID slrestor,(VOID));
  4921. #ifdef CK_SSL
  4922. int tls_norestore = 0;
  4923. #endif /* CK_SSL */
  4924. #endif /* NOLOCAL */
  4925.  
  4926. int
  4927. netclos() {
  4928.     static int close_in_progress = 0;
  4929.     int x = 0;
  4930.     debug(F101,"netclos","",ttyfd);
  4931.  
  4932. #ifdef NETLEBUF
  4933.     if (!tt_push_inited)
  4934.       le_init();
  4935. #endif /* NETLEBUF */
  4936.  
  4937.     if (ttyfd == -1)                    /* Was open? */
  4938.       return(0);                        /* Wasn't. */
  4939.  
  4940.     if (close_in_progress)
  4941.       return(0);
  4942.     close_in_progress = 1;              /* Remember */
  4943.  
  4944. #ifndef NOLOCAL
  4945.     /* This function call should not be here since this is a direct call */
  4946.     /* from an I/O routine to a user interface level function.  However, */
  4947.     /* the reality is that we do not have pure interfaces.  If we ever   */
  4948.     /* decide to clean this up the UI level should assign this function  */
  4949.     /* via a pointer assignment.  - Jeff 9/10/1999                       */
  4950. #ifdef CK_SSL
  4951.     if (!tls_norestore)
  4952. #endif /* CK_SSL */
  4953.       slrestor();
  4954. #endif /* NOLOCAL */
  4955. #ifndef OS2
  4956.     if (ttyfd > -1)                     /* Was. */
  4957. #endif /* OS2 */
  4958.       {
  4959. #ifdef TNCODE
  4960.           if (ttnproto == NP_TELNET) {
  4961.             tn_push();                    /* Place any waiting data into input*/
  4962.             tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  4963.             TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  4964.           }
  4965. #endif /* TNCODE */
  4966. #ifdef CK_SSL
  4967.           if (ssl_active_flag) {
  4968.               if (ssl_debug_flag)
  4969.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4970.               SSL_shutdown(ssl_con);
  4971.               ssl_active_flag = 0;
  4972.           }
  4973.           if (tls_active_flag) {
  4974.               if (ssl_debug_flag)
  4975.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4976.               SSL_shutdown(tls_con);
  4977.               tls_active_flag = 0;
  4978.           }
  4979. #endif /* CK_SSL */
  4980. #ifdef VMS
  4981.           ck_cancio();                  /* Cancel any outstanding reads. */
  4982. #endif /* VMS */
  4983. #ifdef TCPIPLIB
  4984.           x = socket_close(ttyfd);      /* Close it. */
  4985. #else
  4986. #ifndef OS2
  4987. #ifdef IBMX25
  4988.         if (ttnet == NET_IX25) {
  4989.             /* riehm: should send a disc_req - but only if link is still OK */
  4990.             x = x25clear();
  4991.             close(ttyfd);
  4992.             if (x25serverfd) {
  4993.                   /* we were the passive client of a server, now we
  4994.                    * go back to being the normal client.
  4995.                    * I hope that kermit can cope with the logic that
  4996.                    * there can still be a connection after netclos
  4997.                    * has been called.
  4998.                    */
  4999.                   ttyfd = x25serverfd;
  5000.                   x25serverfd = 0;
  5001.                   /*
  5002.                    * need to close the server connection too - because
  5003.                    * all file descriptors connected to the NPI have the
  5004.                    * same status.
  5005.                    *
  5006.                    * The problem is that any waiting connections get
  5007.                    * lost, the client doesn't realise, and hangs.
  5008.                    */
  5009.                   netclos();
  5010.               }
  5011.             x25_state = X25_CLOSED;     /* riehm: dead code? */
  5012.         } else
  5013. #endif /* IBMX25 */
  5014.           x = close(ttyfd);
  5015. #endif /* OS2 */
  5016. #endif /* TCPIPLIB */
  5017.       }
  5018.     ttyfd = -1;                         /* Mark it as closed. */
  5019.     wasclosed = 1;
  5020. #ifdef TNCODE
  5021. #ifdef CK_FORWARD_X
  5022.     fwdx_close_all();                   /* Shut down any Forward X sockets */
  5023. #endif /* CK_FORWARD_X */
  5024.     tn_reset();                   /* The Reset Telnet Option table.  */
  5025.     debug(F100,"netclose setting tn_init = 0","",0);
  5026.     tn_init = 0;                        /* Remember about telnet protocol... */
  5027.     sstelnet = 0;                       /* Client-side Telnet */
  5028. #endif /* TNCODE */
  5029.     *ipaddr = '\0';                     /* Zero the IP address string */
  5030.     tcp_incoming = 0;                   /* No longer incoming */
  5031.     /* Don't reset ttnproto so that we can remember which protocol is in use */
  5032.  
  5033. #ifdef TCPIPLIB
  5034. /*
  5035.   Empty the internal buffers so they won't be used as invalid input on
  5036.   the next connect attempt (rlogin).
  5037. */
  5038.     ttibp = 0;
  5039.     ttibn = 0;
  5040. #endif /* TCPIPLIB */
  5041. #ifdef CK_KERBEROS
  5042.     /* If we are automatically destroying Kerberos credentials on Close */
  5043.     /* do it now. */
  5044. #ifdef KRB4
  5045.     if (krb4_autodel == KRB_DEL_CL) {
  5046.         extern struct krb_op_data krb_op;
  5047.         krb_op.version = 4;
  5048.         krb_op.cache = NULL;
  5049.         ck_krb4_destroy(&krb_op);
  5050.     }
  5051. #endif /* KRB4 */
  5052. #ifdef KRB5
  5053.     if (krb5_autodel == KRB_DEL_CL) {
  5054.         extern struct krb_op_data krb_op;
  5055.         extern char * krb5_d_cc;
  5056.         krb_op.version = 5;
  5057.         krb_op.cache = krb5_d_cc;
  5058.         ck_krb5_destroy(&krb_op);
  5059.     }
  5060. #endif /* KRB5 */
  5061. #endif /* CK_KERBEROS */
  5062.     close_in_progress = 0;              /* Remember we are done. */
  5063.     return(x);
  5064. }
  5065.  
  5066. #ifdef OS2
  5067. int
  5068. os2socketerror( int s_errno ) {
  5069. #ifdef OS2ONLY
  5070.     if (s_errno > 0 && s_errno <= SOCBASEERR) {
  5071.         /* in OS/2, there is a problem with threading in that
  5072.          * the value of errno is not thread safe.  It can be
  5073.          * set to a value from a previous library call and if
  5074.          * it was not cleared it will appear here.  Only treat
  5075.          * valid socket error codes as errors in this function.
  5076.          */
  5077.         debug(F100,"os2socketerror errno.h","",0);
  5078.         socket_errno = 0;
  5079.         return(0);
  5080.     }
  5081. #endif /* OS2ONLY */
  5082.  
  5083.     switch (s_errno) {
  5084.       case 0:                           /* NO ERROR */
  5085.         debug(F100,"os2socketerror NOERROR","",0);
  5086.         return(0);
  5087. #ifdef NT
  5088.       case WSAECONNRESET:
  5089. #else /* NT */
  5090.       case SOCECONNRESET:
  5091.       case SOCECONNRESET - SOCBASEERR:
  5092. #endif /* NT */
  5093.         debug(F100,"os2socketerror ECONRESET","",0);
  5094.         tn_debug("ECONRESET");
  5095.         netclos();              /* *** *** */
  5096.         return(-1);             /* Connection is broken. */
  5097. #ifdef NT
  5098.       case WSAECONNABORTED:
  5099. #else /* NT */
  5100.       case SOCECONNABORTED:
  5101.       case SOCECONNABORTED - SOCBASEERR:
  5102. #endif /* NT */
  5103.         debug(F100,"os2socketerror ECONNABORTED","",0);
  5104.         tn_debug("ECONNABORTED");
  5105.         netclos();              /* *** *** */
  5106.         return(-1);             /* Connection is broken. */
  5107. #ifdef NT
  5108.       case WSAENETRESET:
  5109. #else /* NT */
  5110.       case SOCENETRESET:
  5111.       case SOCENETRESET - SOCBASEERR:
  5112. #endif /* NT */
  5113.         debug(F100,"os2socketerror ENETRESET","",0);
  5114.         tn_debug("ENETRESET");
  5115.         netclos();              /* *** *** */
  5116.         return(-1);             /* Connection is broken. */
  5117. #ifdef NT
  5118.       case WSAENOTCONN:
  5119. #else /* NT */
  5120.       case SOCENOTCONN:
  5121.       case SOCENOTCONN - SOCBASEERR:
  5122. #endif /* NT */
  5123.         debug(F100,"os2socketerror ENOTCONN","",0);
  5124.         tn_debug("ENOTCONN");
  5125.         netclos();                      /* *** *** */
  5126.         return(-1);                     /* Connection is broken. */
  5127. #ifdef NT
  5128.       case WSAESHUTDOWN:
  5129.         debug(F100,"os2socketerror ESHUTDOWN","",0);
  5130.         tn_debug("ESHUTDOWN");
  5131.         netclos();                      /* *** *** */
  5132.         return(-1);                     /* Connection is broken. */
  5133. #endif /* NT */
  5134. #ifdef NT
  5135.       case WSAEWOULDBLOCK:
  5136. #else
  5137.       case SOCEWOULDBLOCK:
  5138.       case SOCEWOULDBLOCK - SOCBASEERR:
  5139. #endif /* NT */
  5140.         debug(F100,"os2socketerror EWOULDBLOCK","",0);
  5141.         return(0);
  5142. #ifdef NT
  5143.       case ERROR_IO_INCOMPLETE:
  5144.       case ERROR_IO_PENDING:
  5145.       case ERROR_OPERATION_ABORTED:
  5146.         return(0);
  5147. #endif /* NT */
  5148.       default:
  5149.         return(-2);
  5150.     }
  5151.     return(0);
  5152. }
  5153. #endif /* OS2 */
  5154.  
  5155. /*  N E T T C H K  --  Check if network up, and how many bytes can be read */
  5156. /*
  5157.   Returns number of bytes waiting, or -1 if connection has been dropped.
  5158. */
  5159. int                                     /* Check how many bytes are ready */
  5160. nettchk() {                             /* for reading from network */
  5161. #ifdef TCPIPLIB
  5162.     long count = 0;
  5163.     int x = 0;
  5164.     long y;
  5165.     char c;
  5166.     int rc;
  5167. #ifdef NT
  5168.     extern int ionoblock;               /* For Overlapped I/O */
  5169. #endif /* NT */
  5170.  
  5171.     debug(F101,"nettchk entry ttibn","",ttibn);
  5172.     debug(F101,"nettchk entry ttibp","",ttibp);
  5173.  
  5174. #ifdef NETLEBUF
  5175.     {
  5176.         int n = 0;
  5177.         if (ttpush >= 0)
  5178.           n++;
  5179.         n += le_inbuf();
  5180.         if (n > 0)
  5181.           return(n);
  5182.     }
  5183. #endif /* NETLEBUF */
  5184.  
  5185. #ifndef OS2
  5186. #ifndef BEBOX
  5187.     socket_errno = 0; /* This is a function call in NT, and BeOS */
  5188. #endif /* BEBOX */
  5189. #endif /* OS2 */
  5190.  
  5191.     if (ttyfd == -1) {
  5192.         debug(F100,"nettchk socket is closed","",0);
  5193.         return(-1);
  5194.     }
  5195. /*
  5196.   Note: this socket_ioctl() call does NOT return an error if the
  5197.   connection has been broken.  (At least not in MultiNet.)
  5198. */
  5199. #ifdef COMMENT
  5200. /*  Another trick that can be tried here is something like this: */
  5201.  
  5202.     if (ttnet == NET_TCPB) {
  5203.         char dummy;
  5204.         x = read(ttyfd,&dummy,0);       /* Try to read nothing */
  5205.         if (x < 0) {                    /* "Connection reset by peer" */
  5206.             perror("TCP/IP");           /* or somesuch... */
  5207.             ttclos(0);                  /* Close our end too. */
  5208.             return(-1);
  5209.         }
  5210.     }
  5211. #endif /* COMMENT */
  5212.  
  5213.  
  5214. #ifdef CK_SSL
  5215.     if (ssl_active_flag) {
  5216. #ifndef IKSDONLY
  5217.         if ( IsConnectMode() ) {
  5218.             debug(F101,"nettchk (ssl_active_flag) returns","",count);
  5219.             return(0);
  5220.         }
  5221. #endif /* IKSDONLY */
  5222.         count = SSL_pending(ssl_con);
  5223.         if (count < 0) {
  5224.             debug(F111,"nettchk","SSL_pending error",count);
  5225.             netclos();
  5226.             return(-1);
  5227.         }
  5228.         if ( count > 0 )
  5229.             return(count);                  /* Don't perform a read */
  5230.     } else if (tls_active_flag) {
  5231. #ifndef IKSDONLY
  5232.         if ( IsConnectMode() ) {
  5233.             debug(F101,"nettchk (tls_active_flag) returns","",count);
  5234.             return(0);
  5235.         }
  5236. #endif /* IKSDONLY */
  5237.         count = SSL_pending(tls_con);
  5238.         if (count < 0) {
  5239.             debug(F111,"nettchk","TLS_pending error",count);
  5240.             netclos();
  5241.             return(-1);
  5242.         }
  5243.         if ( count > 0 )
  5244.             return(count);                  /* Don't perform a read */
  5245.     } else
  5246. #endif /* CK_SSL */
  5247.  
  5248.     if (socket_ioctl(ttyfd,FIONREAD,
  5249. #ifdef COMMENT
  5250.     /* Now we've changed the ioctl(..,..,x) prototype for DECC to (void *) */
  5251. #ifdef __DECC
  5252.     /* NOTE: "&count" might need to be "(char *)&count" in some settings. */
  5253.                      /* Cast needed for DECC 4.1 & later? */
  5254.                      /* Maybe, but __DECC_VER only exists in 5.0 and later */
  5255.                      (char *)
  5256. #endif /* __DECC */
  5257. #endif /* COMMENT */
  5258.                      &count
  5259.                      ) < 0) {
  5260.         debug(F101,"nettchk socket_ioctl error","",socket_errno);
  5261.         /* If the connection is gone, the connection is gone. */
  5262.         netclos();
  5263. #ifdef NT_TCP_OVERLAPPED
  5264.         /* Is there anything in the overlapped I/O buffers? */
  5265.         count += OverlappedDataWaiting();
  5266. #endif /* NT_TCP_OVERLAPPED */
  5267.         count += ttibn;
  5268.         return(count>0?count:-1);
  5269.     }
  5270.     debug(F101,"nettchk count","",count);
  5271. #ifdef NT_TCP_OVERLAPPED
  5272.     /* Is there anything in the overlapped I/O buffers? */
  5273.     count += OverlappedDataWaiting();
  5274.     debug(F101,"nettchk count w/overlapped","",count);
  5275. #endif /* NT_TCP_OVERLAPPED */
  5276.  
  5277. #ifdef OS2
  5278. #ifndef IKSDONLY
  5279.     if ( IsConnectMode() ) {
  5280.         debug(F101,"nettchk (FIONREAD) returns","",count);
  5281.         return(count);
  5282.     }
  5283. #endif /* IKSDONLY */
  5284. #endif /* OS2 */
  5285.  
  5286. /* For the sake of efficiency, if there is still data in the ttibuf */
  5287. /* do not go to the bother of checking to see of the connection is  */
  5288. /* still valid.  The handle is still good, so just return the count */
  5289. /* of the bytes that we already have left to process.               */
  5290. #ifdef OS2
  5291.     if ( count > 0 || ttibn > 0 ) {
  5292.         count+=ttibn;
  5293.         debug(F101,"nettchk (count+ttibn > 0) returns","",count);
  5294.         return(count);
  5295.     } else {
  5296.         RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5297.         if ( ttibn == 0 )
  5298.             ttibp = 0;      /* reset for next read */
  5299.     }
  5300. #else /* OS2 */
  5301.     if ( count > 0 || ttibn > 0 ) {
  5302.         debug(F101,"nettchk returns","",count+ttibn);
  5303.         return(count+ttibn);
  5304.     }
  5305. #endif /* OS2 */
  5306.  
  5307. /*
  5308.   The following code works well in most settings, but messes things up in
  5309.   others, including CMU/Tek TCP/IP and UCX 2.0, where it somehow manages to
  5310.   make it impossible to ever make a new connection to the same host again with
  5311.   CONNECT, once it has been logged out from the first time.  Not even if you
  5312.   HANGUP first, or SET HOST<CR>, or SET LINE<CR>.  Reportedly, however, it
  5313.   does work OK in later releases of UCX.  But there is no way we can
  5314.   accommodate both old and new -- we might have static linking or dynamic
  5315.   linking, etc etc.  If we have static, I only have access to 2.0, where this
  5316.   doesn't work, etc etc blah blah.
  5317.  
  5318.   In the following lines, we define a symbol NOCOUNT for builds where we want
  5319.   to omit this code.  By default, it is omitted for CMU/Tek.  You can force
  5320.   omission of it for other combinations by defining NOCOUNT in CFLAGS.  You
  5321.   can force inclusion of this code, even for CMU/Tek, by including NONOCOUNT
  5322.   in CFLAGS.
  5323. */
  5324. #ifdef NONOCOUNT
  5325. #ifdef NOCOUNT
  5326. #undef NOCOUNT
  5327. #endif /* NOCOUNT */
  5328. #else
  5329. #ifndef NOCOUNT
  5330. #ifdef CMU_TCPIP
  5331. #define NOCOUNT
  5332. #endif /* CMU_TCPIP */
  5333. #endif /* NOCOUNT */
  5334. #endif /* NONOCOUNT */
  5335.  
  5336.  
  5337.     /* From this point forward we have a possible race condition in K95
  5338.      * due to its use of multiple threads.  Therefore, we must ensure
  5339.      * that only one thread attempt to read/write from the socket at a
  5340.      * time.  Otherwise, it is possible for a buffer to be overwritten.
  5341.      */
  5342.     /* we know now that count >= 0 and that ttibn == 0 */
  5343.  
  5344.     if (count == 0
  5345. #ifdef RLOGCODE
  5346. #ifdef CK_KERBEROS
  5347.         && ttnproto != NP_EK4LOGIN && ttnproto != NP_EK5LOGIN
  5348. #endif /* CK_KERBEROS */
  5349. #endif /* RLOGCODE */
  5350.         ) {
  5351.         int s_errno = 0;
  5352. #ifndef NOCOUNT
  5353. /*
  5354.   Here we need to tell the difference between a 0 count on an active
  5355.   connection, and a 0 count because the remote end of the socket broke the
  5356.   connection.  There is no mechanism in TGV MultiNet (or WIN/TCP?) to query
  5357.   the status of the connection, so we have to do a read.  -1 means there was
  5358.   no data available (socket_errno == EWOULDBLOCK), 0 means the connection is
  5359.   down.  But if, by chance, we actually get a character, we have to put it
  5360.   where it won't be lost.
  5361. */
  5362. #ifndef NON_BLOCK_IO
  5363. #ifdef OS2
  5364. #ifdef CK_SSL
  5365.         RequestSSLMutex(SEM_INDEFINITE_WAIT);
  5366. #endif /* CK_SSL */
  5367. #endif /* OS2 */
  5368.         y = 1;                          /* Turn on nonblocking reads */
  5369.         x = socket_ioctl(ttyfd,FIONBIO,&y);
  5370.         debug(F101,"nettchk FIONBIO","",x);
  5371. #ifdef OS2
  5372. #ifdef CK_SSL
  5373.         ReleaseSSLMutex();
  5374. #endif /* CK_SSL */
  5375. #endif /* OS2 */
  5376. #endif /* NON_BLOCK_IO */
  5377. #ifdef NT_TCP_OVERLAPPED
  5378.         ionoblock = 1;                  /* For Overlapped I/O */
  5379. #endif /* NT_TCP_OVERLAPPED */
  5380. #ifdef CK_SSL
  5381.         if ( ssl_active_flag || tls_active_flag ) {
  5382.             x = SSL_read( ssl_active_flag?ssl_con:tls_con,
  5383.                           &ttibuf[ttibp+ttibn],
  5384.                           TTIBUFL-ttibp-ttibn );
  5385.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  5386.             case SSL_ERROR_NONE:
  5387.                 debug(F111,"nettchk SSL_ERROR_NONE","count",count);
  5388.                 break;
  5389.             case SSL_ERROR_WANT_WRITE:
  5390.                 debug(F100,"nettchk SSL_ERROR_WANT_WRITE","",0);
  5391.                 x = -1;
  5392.                 break;
  5393.             case SSL_ERROR_WANT_READ:
  5394.                 debug(F100,"nettchk SSL_ERROR_WANT_READ","",0);
  5395.                 x = -1;
  5396.                 break;
  5397.             case SSL_ERROR_SYSCALL:
  5398.                 if ( x == 0 ) { /* EOF */
  5399.                     netclos();
  5400.                     rc = -1;
  5401.                     goto nettchk_return;
  5402.               } else {
  5403. #ifdef NT
  5404.                   int gle = GetLastError();
  5405.                   debug(F111,"nettchk SSL_ERROR_SYSCALL",
  5406.                          "GetLastError()",gle);
  5407.                   rc = os2socketerror(gle);
  5408.                   if (rc == -1)
  5409.                       rc = -2;
  5410.                   else if ( rc == -2 )
  5411.                       return -1;
  5412. #endif /* NT */
  5413.                   break;
  5414.               }
  5415.           case SSL_ERROR_WANT_X509_LOOKUP:
  5416.                 debug(F100,"nettchk SSL_ERROR_WANT_X509_LOOKUP","",0);
  5417.                 break;
  5418.             case SSL_ERROR_SSL:
  5419.                 if (bio_err!=NULL) {
  5420.                     int len;
  5421.                     extern char ssl_err[];
  5422.                     BIO_printf(bio_err,"nettchk() SSL_ERROR_SSL\n");
  5423.                     ERR_print_errors(bio_err);
  5424.                     len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
  5425.                     ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
  5426.                     debug(F110,"nettchk SSL_ERROR_SSL",ssl_err,0);
  5427.                     if (ssl_debug_flag)
  5428.                         printf(ssl_err);
  5429.                 } else if (ssl_debug_flag) {
  5430.                     debug(F100,"nettchk SSL_ERROR_SSL","",0);
  5431.                     fflush(stderr);
  5432.                     fprintf(stderr,"nettchk() SSL_ERROR_SSL\n");
  5433.                     ERR_print_errors_fp(stderr);
  5434.                 }
  5435. #ifdef COMMENT
  5436.                 netclos();
  5437.                 rc = -1;
  5438. #else
  5439.                 x = -1;
  5440. #endif
  5441.                 goto nettchk_return;
  5442.           case SSL_ERROR_ZERO_RETURN:
  5443.                 debug(F100,"nettchk SSL_ERROR_ZERO_RETURN","",0);
  5444.                 netclos();
  5445.                 rc = -1;
  5446.                 goto nettchk_return;
  5447.             default:
  5448.                 debug(F100,"nettchk SSL_ERROR_?????","",0);
  5449.                 netclos();
  5450.                 rc = -1;
  5451.                 goto nettchk_return;
  5452.             }
  5453.         } else
  5454. #endif /* CK_SSL */
  5455.         {
  5456. #ifdef OS2
  5457.         x = socket_read(ttyfd,&ttibuf[ttibp+ttibn],
  5458.                          TTIBUFL-ttibp-ttibn);  /* Returns -1 if no data */
  5459. #else /* OS2 */
  5460.         x = socket_read(ttyfd,&c,1);    /* Returns -1 if no data */
  5461. #endif /* OS2 */
  5462.         }
  5463.         s_errno = socket_errno;         /* socket_errno may be a function */
  5464.         debug(F101,"nettchk socket_read","",x);
  5465.  
  5466. #ifndef NON_BLOCK_IO
  5467.         y = 0;                          /* Turn them back off */
  5468.         socket_ioctl(ttyfd,FIONBIO,&y);
  5469. #endif /* NON_BLOCK_IO */
  5470. #ifdef NT_TCP_OVERLAPPED
  5471.         ionoblock = 0;                  /* For Overlapped I/O */
  5472. #endif /* NT_TCP_OVERLAPPED */
  5473.  
  5474.         if (x == -1) {
  5475.             debug(F101,"nettchk socket_read errno","",s_errno);
  5476. #ifdef OS2
  5477.             if (os2socketerror(s_errno) < 0) {
  5478.                 rc = -1;
  5479.                 goto nettchk_return;
  5480.             }
  5481. #endif /* OS2 */
  5482.         } else if (x == 0) {
  5483.             debug(F100,"nettchk connection closed","",0);
  5484.             netclos();                  /* *** *** */
  5485.             rc = -1;
  5486.             goto nettchk_return;
  5487.         }
  5488.         if (x >= 1) {                   /* Oops, actually got a byte? */
  5489. #ifdef OS2
  5490.             /* In OS/2 we read directly into ttibuf[] */
  5491.             hexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
  5492.             ttibn += x;
  5493. #else /* OS2 */
  5494.             debug(F101,"nettchk socket_read char","",c);
  5495.             debug(F101,"nettchk ttibp","",ttibp);
  5496.             debug(F101,"nettchk ttibn","",ttibn);
  5497. /*
  5498.   In the case of Overlapped I/O the character would have come from
  5499.   the beginning of the buffer, so put it back.
  5500. */
  5501.             if (ttibp > 0) {
  5502.                 ttibp--;
  5503.                 ttibuf[ttibp] = c;
  5504.                 ttibn++;
  5505.             } else {
  5506.                 ttibuf[ttibp+ttibn] = c;
  5507.                 ttibn++;
  5508.             }
  5509. #endif /* OS2 */
  5510.         }
  5511. #else /* NOCOUNT */
  5512.         if (ttnet == NET_TCPB) {
  5513.             char dummy;
  5514.             x = read(ttyfd,&dummy,0);   /* Try to read nothing */
  5515.             if (x < 0) {                /* "Connection reset by peer" */
  5516.                 perror("TCP/IP");       /* or somesuch... */
  5517.                 ttclos(0);              /* Close our end too. */
  5518.                 rc = -1;
  5519.                 goto nettchk_return;
  5520.             }
  5521.         }
  5522. #endif /* NOCOUNT */
  5523.     }
  5524. #ifdef CK_KERBEROS
  5525. #ifdef KRB4
  5526. #ifdef RLOGCODE
  5527.     if (ttnproto == NP_EK4LOGIN)
  5528.       count += krb4_des_avail(ttyfd);
  5529. #endif /* RLOGCODE */
  5530. #endif /* KRB4 */
  5531. #ifdef KRB5
  5532. #ifdef RLOGCODE
  5533.     if (ttnproto == NP_EK5LOGIN)
  5534.       count += krb5_des_avail(ttyfd);
  5535. #endif /* RLOGCODE */
  5536. #ifdef KRB5_U2U
  5537.     if (ttnproto == NP_K5U2U)
  5538.       count += krb5_u2u_avail(ttyfd);
  5539. #endif /* KRB5_U2U */
  5540. #endif /* KRB5 */
  5541. #endif /* CK_KERBEROS */
  5542.  
  5543.     debug(F101,"nettchk returns","",count+ttibn);
  5544.     rc = count + ttibn;
  5545.  
  5546.   nettchk_return:
  5547. #ifdef OS2
  5548.     ReleaseTCPIPMutex();
  5549. #endif /* OS2 */
  5550.     return(rc);
  5551.  
  5552. #else /* Not TCPIPLIB */
  5553. /*
  5554.   UNIX just uses ttchk(), in which the ioctl() calls on the file descriptor
  5555.   seem to work OK.
  5556. */
  5557.     return(ttchk());
  5558. #endif /* TCPIPLIB */
  5559. /*
  5560.   But what about X.25?
  5561. */
  5562. }
  5563.  
  5564. #ifndef OS2
  5565. VOID
  5566. nettout(i) int i; {                     /* Catch the alarm interrupts */
  5567.     debug(F100,"nettout caught timeout","",0);
  5568.     ttimoff();
  5569.     cklongjmp(njbuf, -1);
  5570. }
  5571. #endif /* !OS2 */
  5572.  
  5573. #ifdef TCPIPLIB
  5574.  
  5575. VOID
  5576. #ifdef CK_ANSIC
  5577. donetinc(void * threadinfo)
  5578. #else /* CK_ANSIC */
  5579. donetinc(threadinfo) VOID * threadinfo;
  5580. #endif /* CK_ANSIC */
  5581. /* donetinc */ {
  5582. #ifdef NTSIG
  5583.     extern int TlsIndex;
  5584.     setint();
  5585.     if (threadinfo) {                   /* Thread local storage... */
  5586.         TlsSetValue(TlsIndex,threadinfo);
  5587.     }
  5588. #endif /* NTSIG */
  5589. #ifdef CK_LOGIN
  5590. #ifdef NT
  5591. #ifdef IKSD
  5592.     if (inserver)
  5593.       setntcreds();
  5594. #endif /* IKSD */
  5595. #endif /* NT */
  5596. #endif /* CK_LOGIN */
  5597.     while (1) {
  5598.         if (ttbufr() < 0)               /* Keep trying to refill it. */
  5599.           break;                        /* Till we get an error. */
  5600.         if (ttibn > 0)                  /* Or we get a character. */
  5601.           break;
  5602.     }
  5603. }
  5604. #endif /* TCPIPLIB */
  5605.  
  5606. VOID
  5607. #ifdef CK_ANSIC
  5608. failnetinc(void * threadinfo)
  5609. #else /* CK_ANSIC */
  5610. failnetinc(threadinfo) VOID * threadinfo;
  5611. #endif /* CK_ANSIC */
  5612. /* failnetinc */ {
  5613.     ; /* Nothing to do on an error */
  5614. }
  5615.  
  5616. /* N E T X I N -- Input block of characters from network */
  5617.  
  5618. int
  5619. netxin(n,buf) int n; CHAR * buf; {
  5620.     int len, i, j;
  5621. #ifdef TCPIPLIB
  5622.     int rc;
  5623. #endif /* TCPIPLIB */
  5624.  
  5625.     if (ttyfd == -1) {
  5626.         debug(F100,"netxin socket is closed","",0);
  5627.         return(-2);
  5628.     }
  5629. #ifdef CK_KERBEROS
  5630. #ifdef KRB4
  5631. #ifdef RLOGCODE
  5632.     if (ttnproto == NP_EK4LOGIN) {
  5633.         if ((len = krb4_des_read(ttyfd,buf,n)) < 0)
  5634.           return(-1);
  5635.         else
  5636.           return(len);
  5637.     }
  5638. #endif /* RLOGCODE */
  5639. #endif /* KRB4 */
  5640. #ifdef KRB5
  5641. #ifdef RLOGCODE
  5642.     if (ttnproto == NP_EK5LOGIN) {
  5643.         if ((len = krb5_des_read(ttyfd,buf,n,0)) < 0)
  5644.           return(-1);
  5645.         else
  5646.           return(len);
  5647.     }
  5648. #endif /* RLOGCODE */
  5649. #ifdef KRB5_U2U
  5650.     if (ttnproto == NP_K5U2U) {
  5651.         if ((len = krb5_u2u_read(ttyfd,buf,n)) < 0)
  5652.           return(-1);
  5653.         else
  5654.           return(len);
  5655.     }
  5656. #endif /* KRB5_U2U */
  5657. #endif /* KRB5 */
  5658. #endif /* CK_KERBEROS */
  5659.  
  5660. #ifdef TCPIPLIB
  5661. #ifdef OS2
  5662.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5663. #endif /* OS2 */
  5664.     if (ttibn == 0)
  5665.       if ((rc = ttbufr()) <= 0) {
  5666. #ifdef OS2
  5667.         ReleaseTCPIPMutex();
  5668. #endif /* OS2 */
  5669.         return(rc);
  5670.       }
  5671.  
  5672.     if (ttibn <= n) {
  5673.         len = ttibn;
  5674.         memcpy(buf,&ttibuf[ttibp],len);         /* safe */
  5675.         ttibp += len;
  5676.         ttibn = 0;
  5677.     } else {
  5678.         memcpy(buf,&ttibuf[ttibp],n);           /* safe */
  5679.         ttibp += n;
  5680.         ttibn -= n;
  5681.         len = n;
  5682.     }
  5683. #ifdef OS2
  5684.     ReleaseTCPIPMutex();
  5685. #endif /* OS2 */
  5686. #else /* TCPIPLIB */
  5687.     for (i = 0; i < n; i++) {
  5688.         if ((j = netinc(0)) < 0) {
  5689.             if (j < -1)
  5690.               return(j);
  5691.             else
  5692.               break;
  5693.         }
  5694.         buf[i] = j;
  5695.     }
  5696.     len = i;
  5697. #endif /* TCPIPLIB */
  5698.  
  5699. #ifdef COMMENT
  5700. #ifdef CK_ENCRYPTION
  5701.     /* This would be great if it worked.  But what if the buffer we read  */
  5702.     /* contains a telnet negotiation that changes the state of the        */
  5703.     /* encryption.  If so, we would be either decrypting unencrypted text */
  5704.     /* or not decrypting encrypted text.  So we must move this call to    */
  5705.     /* all functions that call ttxin().  In OS2 that means os2_netxin()   */
  5706.     /* where the Telnet Negotiations are handled.                         */
  5707.     if (u_encrypt)
  5708.       ck_tn_decrypt(buf,len);
  5709. #endif /* CK_ENCRYPTION */
  5710. #endif /* COMMENT */
  5711.  
  5712.     return(len);
  5713. }
  5714.  
  5715. /*  N E T I N C --  Input character from network */
  5716.  
  5717. #ifdef NETLEBUF
  5718. #define LEBUF
  5719. #endif /* NETLEBUF */
  5720. #ifdef TTLEBUF
  5721. #define LEBUF
  5722. #endif /* TTLEBUF */
  5723. #ifndef LEBUF
  5724. #ifdef OS2
  5725. #define LEBUF
  5726. #endif /* OS2 */
  5727. #endif /* LEBUF */
  5728.  
  5729. int
  5730. netinc(timo) int timo; {
  5731. #ifdef TCPIPLIB
  5732.     int x; unsigned char c;             /* The locals. */
  5733.  
  5734. #ifdef NETLEBUF
  5735.     if (ttpush >= 0) {
  5736.         debug(F111,"netinc","ttpush",ttpush);
  5737.         c = ttpush;
  5738.         ttpush = -1;
  5739.         return(c);
  5740.     }
  5741.     if (le_data) {
  5742.         if (le_getchar((CHAR *)&c) > 0) {
  5743.             debug(F111,"netinc le_getchar","c",c);
  5744.             return(c);
  5745.         }
  5746.     }
  5747. #endif /* NETLEBUF */
  5748.  
  5749.     if (ttyfd == -1) {
  5750.         debug(F100,"netinc socket is closed","",0);
  5751.         return(-2);
  5752.     }
  5753.  
  5754. #ifdef CK_KERBEROS
  5755. #ifdef KRB4
  5756. #ifdef RLOGCODE
  5757.     if (ttnproto == NP_EK4LOGIN) {
  5758.         if ((x = krb4_des_read(ttyfd,&c,1)) == 0)
  5759.           return(-1);
  5760.         else if (x < 0)
  5761.           return(-2);
  5762.         else
  5763.           return(c);
  5764.     }
  5765. #endif /* RLOGCODE */
  5766. #endif /* KRB4 */
  5767. #ifdef KRB5
  5768. #ifdef RLOGCODE
  5769.     if (ttnproto == NP_EK5LOGIN) {
  5770.         if ((x = krb5_des_read(ttyfd,&c,1,0)) == 0)
  5771.           return(-1);
  5772.         else if (x < 0)
  5773.           return(-2);
  5774.         else
  5775.           return(c);
  5776.     }
  5777. #endif /* RLOGCODE */
  5778. #ifdef KRB5_U2U
  5779.     if (ttnproto == NP_K5U2U) {
  5780.         if ((x = krb5_u2u_read(ttyfd,&c,1)) == 0)
  5781.           return(-1);
  5782.         else if (x < 0)
  5783.           return(-2);
  5784.         else
  5785.           return(c);
  5786.     }
  5787. #endif /* KRB5_U2U */
  5788. #endif /* KRB5 */
  5789. #endif /* CK_KERBEROS */
  5790.  
  5791. #ifdef OS2
  5792.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5793. #endif /* OS2 */
  5794.     if (ttibn > 0) {                    /* Something in internal buffer? */
  5795. #ifdef COMMENT
  5796.         debug(F100,"netinc char in buf","",0); /* Yes. */
  5797. #endif /* COMMENT */
  5798.         x = 0;                          /* Success. */
  5799.     } else {                            /* Else must read from network. */
  5800.         x = -1;                         /* Assume failure. */
  5801. #ifdef DEBUG
  5802.         debug(F101,"netinc goes to net, timo","",timo);
  5803. #endif /* DEBUG */
  5804. #ifdef CK_SSL
  5805.         /*
  5806.          * In the case of OpenSSL, it is possible that there is still
  5807.          * data waiting in the SSL session buffers that has not yet
  5808.          * been read by Kermit.  If this is the case we must process
  5809.          * it without calling select() because select() will not return
  5810.          * with an indication that there is data to be read from the
  5811.          * socket.  If there is no data pending in the SSL session
  5812.          * buffers then fall through to the select() code and wait for
  5813.          * some data to arrive.
  5814.          */
  5815.         if (ssl_active_flag) {
  5816.             x = SSL_pending(ssl_con);
  5817.             if (x < 0) {
  5818.                 debug(F111,"netinc","SSL_pending error",x);
  5819.                 netclos();
  5820. #ifdef OS2
  5821.                 ReleaseTCPIPMutex();
  5822. #endif /* OS2 */
  5823.                 return(-1);
  5824.             } else if ( x > 0 ) {
  5825.                 if ( ttbufr() >= 0 ) {
  5826.                     x = netinc(timo);
  5827. #ifdef OS2
  5828.                     ReleaseTCPIPMutex();
  5829. #endif /* OS2 */
  5830.                     return(x);
  5831.                 }
  5832.             }
  5833.             x = -1;
  5834.         } else if (tls_active_flag) {
  5835.             x = SSL_pending(tls_con);
  5836.             if (x < 0) {
  5837.                 debug(F111,"netinc","TLS_pending error",x);
  5838.                 netclos();
  5839. #ifdef OS2
  5840.                 ReleaseTCPIPMutex();
  5841. #endif /* OS2 */
  5842.                 return(-1);
  5843.             } else if ( x > 0 ) {
  5844.                 if ( ttbufr() >= 0 ) {
  5845.                     x = netinc(timo);
  5846. #ifdef OS2
  5847.                     ReleaseTCPIPMutex();
  5848. #endif /* OS2 */
  5849.                     return(x);
  5850.                 }
  5851.             }
  5852.             x = -1;
  5853.         }
  5854. #endif /* CK_SSL */
  5855. #ifndef LEBUF
  5856.         if (timo == 0) {                /* Untimed case. */
  5857.             while (1) {                 /* Wait forever if necessary. */
  5858.                 if (ttbufr() < 0)       /* Refill buffer. */
  5859.                   break;                /* Error, fail. */
  5860.                 if (ttibn > 0) {        /* Success. */
  5861.                     x = 0;
  5862.                     break;
  5863.                 }
  5864.             }
  5865.         } else                          /* Timed case... */
  5866. #endif /* LEBUF */
  5867.           {
  5868. #ifdef NT_TCP_OVERLAPPED
  5869.             /* This code is for use on NT when we are using */
  5870.             /* Overlapped I/O to handle reads.  In the case */
  5871.             /* of outstanding reads select() doesn't work   */
  5872.  
  5873.             if (WaitForOverlappedReadData(timo)) {
  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.             }
  5883. #else /* NT_TCP_OVERLAPPED */
  5884. #ifdef BSDSELECT
  5885.             fd_set rfds;
  5886.             struct timeval tv;
  5887.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5888.             debug(F101,"netinc BSDSELECT","",timo);
  5889.  
  5890.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5891.                 int rc;
  5892.                 debug(F111,"netinc","timeout",timeout);
  5893.                 /* Don't move select() initialization out of the loop. */
  5894.                 FD_ZERO(&rfds);
  5895.                 FD_SET(ttyfd, &rfds);
  5896.                 tv.tv_sec  = tv.tv_usec = 0L;
  5897.                 if (timo)
  5898.                   tv.tv_usec = (long) 100000L;
  5899.                 else
  5900.                   tv.tv_sec = 30;
  5901. #ifdef NT
  5902.                 WSASafeToCancel = 1;
  5903. #endif /* NT */
  5904.                 rc = select(FD_SETSIZE,
  5905. #ifndef __DECC
  5906.                             (fd_set *)
  5907. #endif /* __DECC */
  5908.                             &rfds, NULL, NULL, &tv);
  5909.                 if (rc < 0) {
  5910.                     int s_errno = socket_errno;
  5911.                     debug(F111,"netinc","select",rc);
  5912.                     debug(F111,"netinc","socket_errno",s_errno);
  5913.                     if (s_errno) {
  5914. #ifdef OS2
  5915.                         ReleaseTCPIPMutex();
  5916. #endif /* OS2 */
  5917.                         return(-1);
  5918.                     }
  5919.                 }
  5920.                 debug(F111,"netinc","select",rc);
  5921. #ifdef NT
  5922.                 WSASafeToCancel = 0;
  5923. #endif /* NT */
  5924.                 if (!FD_ISSET(ttyfd, &rfds)) {
  5925. #ifdef LEBUF
  5926.                     if (le_inbuf() > 0) {
  5927.                         timeout = -1;
  5928.                         break;
  5929.                     }
  5930. #endif /* LEBUF */
  5931.                     /* If waiting forever we have no way of knowing if the */
  5932.                     /* socket closed so try writing a 0-length TCP packet  */
  5933.                     /* which should force an error if the socket is closed */
  5934.                     if (!timo) {
  5935.                         if ((rc = socket_write(ttyfd,"",0)) < 0) {
  5936.                             int s_errno = socket_errno;
  5937.                             debug(F101,"netinc socket_write error","",s_errno);
  5938. #ifdef OS2
  5939.                             if (os2socketerror(s_errno) < 0) {
  5940.                               ReleaseTCPIPMutex();
  5941.                               return(-2);
  5942.                             }
  5943.                             ReleaseTCPIPMutex();
  5944. #endif /* OS2 */
  5945.                             return(-1); /* Call it an i/o error */
  5946.                         }
  5947.                     }
  5948.                     continue;
  5949.                 }
  5950.                 while (1) {
  5951.                     if (ttbufr() < 0) { /* Keep trying to refill it. */
  5952.                         timeout = -1;
  5953.                         break;          /* Till we get an error. */
  5954.                     }
  5955.                     if (ttibn > 0) {    /* Or we get a character. */
  5956.                         x = 0;
  5957.                         timeout = -1;
  5958.                         break;
  5959.                     }
  5960.                 }
  5961.             }
  5962. #ifdef NT
  5963.             WSASafeToCancel = 0;
  5964. #endif /* NT */
  5965. #else /* !BSDSELECT */
  5966. #ifdef IBMSELECT
  5967. /*
  5968.   Was used by OS/2, currently not used, but might come in handy some day...
  5969.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  5970.   and timeval stuff since this is the only place where it is used.
  5971. */
  5972.             int socket = ttyfd;
  5973.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5974.  
  5975.             debug(F101,"netinc IBMSELECT","",timo);
  5976.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5977.                 if (select(&socket, 1, 0, 0, 100L) == 1) {
  5978.                     while (1) {
  5979.                         if (ttbufr() < 0) { /* Keep trying to refill it. */
  5980.                             timeout = -1;
  5981.                             break;      /* Till we get an error. */
  5982.                         }
  5983.                         if (ttibn > 0) { /* Or we get a character. */
  5984.                             x = 0;
  5985.                             timeout = -1;
  5986.                             break;
  5987.                         }
  5988.                     }
  5989.                 }
  5990. #ifdef LEBUF
  5991.                 else if (le_inbuf() > 0)  {
  5992.                     timeout = -1;
  5993.                     break;
  5994.                 }
  5995. #endif /* LEBUF */
  5996.             }
  5997. #else /* !IBMSELECT */
  5998. #ifdef WINSOCK
  5999.        /* Actually, under WinSock we have a better mechanism than select() */
  6000.        /* for setting timeouts (SO_RCVTIMEO, SO_SNDTIMEO) */
  6001.             SOCKET socket = ttyfd;
  6002.             debug(F101,"netinc NTSELECT","",timo);
  6003.             if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timo,
  6004.                             sizeof(timo))  == NO_ERROR)
  6005.               while (1) {
  6006.                   if (ttbufr() < 0)     /* Keep trying to refill it. */
  6007.                     break;              /* Till we get an error. */
  6008.                   if (ttibn > 0) {      /* Or we get a character. */
  6009.                       x = 0;
  6010.                       break;
  6011.                   }
  6012.               }
  6013. #else /* WINSOCK */
  6014. /*
  6015.   If we can't use select(), then we use the regular alarm()/signal()
  6016.   timeout mechanism.
  6017. */
  6018.             debug(F101,"netinc alarm","",timo);
  6019.             x = alrm_execute(ckjaddr(njbuf),timo,nettout,donetinc,failnetinc);
  6020.             ttimoff();                  /* Timer off. */
  6021. #endif /* WINSOCK */
  6022. #endif /* IBMSELECT */
  6023. #endif /* BSDSELECT */
  6024. #endif /* NT_TCP_OVERLAPPED */
  6025.         }
  6026.     }
  6027.  
  6028. #ifdef LEBUF
  6029.     if (le_inbuf() > 0) {               /* If data was inserted into the */
  6030.         if (le_getchar((CHAR *)&c) > 0) {/* Local Echo buffer while the   */
  6031. #ifdef OS2                               /* was taking place do not mix   */
  6032.           ReleaseTCPIPMutex();           /* the le data with the net data */
  6033. #endif /* OS2 */
  6034.           return(c);
  6035.         }
  6036.     }
  6037. #endif /* LEBUF */
  6038.     if (x < 0) {                        /* Return -1 if we failed. */
  6039.         debug(F100,"netinc timed out","",0);
  6040. #ifdef OS2
  6041.         ReleaseTCPIPMutex();
  6042. #endif /* OS2 */
  6043.         return(-1);
  6044.     } else {                            /* Otherwise */
  6045.         c = ttibuf[ttibp];              /* Return the first char in ttibuf[] */
  6046.         if (deblog) {
  6047. #ifndef COMMENT
  6048.             debug(F101,"netinc returning","",c);
  6049. #endif /* COMMENT */
  6050.             if (c == 0) {
  6051.                 debug(F101,"netinc 0 ttibn","",ttibn);
  6052.                 debug(F101,"netinc 0 ttibp","",ttibp);
  6053. #ifdef BETADEBUG
  6054.                 {
  6055. #ifdef OS2
  6056.                     extern int tt_type_mode;
  6057.                     if ( !ISVTNT(tt_type_mode) )
  6058. #endif /* OS2 */
  6059.                     hexdump("netinc &ttbuf[ttibp]",&ttibuf[ttibp],ttibn);
  6060.                 }
  6061. #endif /* BETADEBUG */
  6062.             }
  6063.         }
  6064.         ttibp++;
  6065.         ttibn--;
  6066. #ifdef OS2
  6067.         ReleaseTCPIPMutex();
  6068. #endif /* OS2 */
  6069. #ifdef CK_ENCRYPTION
  6070.         if (TELOPT_U(TELOPT_ENCRYPTION))
  6071.           ck_tn_decrypt(&c,1);
  6072. #endif /* CK_ENCRYPTION */
  6073.         return(c);
  6074.     }
  6075. #else /* Not using TCPIPLIB */
  6076.     return(-1);
  6077. #endif /* TCPIPLIB */
  6078. }
  6079.  
  6080. /*  N E T T O L  --  Output a string of bytes to the network  */
  6081. /*
  6082.   Call with s = pointer to string, n = length.
  6083.   Returns number of bytes actually written on success, or
  6084.   -1 on i/o error, -2 if called improperly.
  6085. */
  6086.  
  6087. int
  6088. nettol(s,n) CHAR *s; int n; {
  6089. #ifdef TCPIPLIB
  6090.     int count = 0;
  6091.     int len = n;
  6092.     int try = 0;
  6093.  
  6094.     if (ttyfd == -1) {
  6095.         debug(F100,"nettol socket is closed","",0);
  6096.         return -1;
  6097.     }
  6098.     debug(F101,"nettol TCPIPLIB ttnet","",ttnet);
  6099. #ifdef COMMENT
  6100.     hexdump("nettol",s,n);
  6101. #endif /* COMMENT */
  6102.  
  6103. #ifdef CK_KERBEROS
  6104. #ifdef KRB4
  6105. #ifdef RLOGCODE
  6106.     if (ttnproto == NP_EK4LOGIN) {
  6107.         return(krb4_des_write(ttyfd,s,n));
  6108.     }
  6109. #endif /* RLOGCODE */
  6110. #endif /* KRB4 */
  6111. #ifdef KRB5
  6112. #ifdef RLOGCODE
  6113.     if (ttnproto == NP_EK5LOGIN) {
  6114.         return(krb5_des_write(ttyfd,s,n,0));
  6115.     }
  6116. #endif /* RLOGCODE */
  6117. #ifdef KRB5_U2U
  6118.     if (ttnproto == NP_K5U2U) {
  6119.         return(krb5_u2u_write(ttyfd,s,n));
  6120.     }
  6121. #endif /* KRB5_U2U */
  6122. #endif /* KRB5 */
  6123. #endif /* CK_KERBEROS */
  6124.  
  6125. #ifdef CK_ENCRYPTION
  6126.     if (TELOPT_ME(TELOPT_ENCRYPTION))
  6127.       ck_tn_encrypt(s,n);
  6128. #endif /* CK_ENCRYPTION */
  6129.  
  6130. #ifdef CK_SSL
  6131.     if (ssl_active_flag || tls_active_flag) {
  6132.         int error, r;
  6133.         /* Write using SSL */
  6134.       ssl_retry:
  6135.         if (ssl_active_flag)
  6136.           r = SSL_write(ssl_con, s, len /* >1024?1024:len */);
  6137.         else
  6138.           r = SSL_write(tls_con, s, len /* >1024?1024:len */);
  6139.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,r)) {
  6140.           case SSL_ERROR_NONE:
  6141.             debug(F111,"nettol","SSL_write",r);
  6142.             if ( r == len )
  6143.                 return(n);
  6144.              s += r;
  6145.              len -= r;
  6146.              goto ssl_retry;
  6147.           case SSL_ERROR_WANT_WRITE:
  6148.             debug(F100,"nettol SSL_ERROR_WANT_WRITE","",0);
  6149.             return(-1);
  6150.           case SSL_ERROR_WANT_READ:
  6151.             debug(F100,"nettol SSL_ERROR_WANT_READ","",0);
  6152.             return(-1);
  6153.           case SSL_ERROR_SYSCALL:
  6154.               if ( r == 0 ) { /* EOF */
  6155.                   netclos();
  6156.                   return(-2);
  6157.               } else {
  6158.                   int rc = -1;
  6159. #ifdef NT
  6160.                   int gle = GetLastError();
  6161.                   debug(F111,"nettol SSL_ERROR_SYSCALL",
  6162.                          "GetLastError()",gle);
  6163.                   rc = os2socketerror(gle);
  6164.                   if (rc == -1)
  6165.                       rc = -2;
  6166.                   else if ( rc == -2 )
  6167.                       return -1;
  6168. #endif /* NT */
  6169.                   return(rc);
  6170.               }
  6171.           case SSL_ERROR_WANT_X509_LOOKUP:
  6172.             debug(F100,"nettol SSL_ERROR_WANT_X509_LOOKUP","",0);
  6173.             netclos();
  6174.             return(-2);
  6175.           case SSL_ERROR_SSL:
  6176.             debug(F100,"nettol SSL_ERROR_SSL","",0);
  6177.               if (bio_err!=NULL) {
  6178.                   int len;
  6179.                   extern char ssl_err[];
  6180.                   BIO_printf(bio_err,"nettol() SSL_ERROR_SSL\n");
  6181.                   ERR_print_errors(bio_err);
  6182.                   len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
  6183.                   ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
  6184.                   debug(F110,"nettol SSL_ERROR_SSL",ssl_err,0);
  6185.                   if (ssl_debug_flag)
  6186.                       printf(ssl_err);
  6187.               } else if (ssl_debug_flag) {
  6188.                   debug(F100,"nettol SSL_ERROR_SSL","",0);
  6189.                   fflush(stderr);
  6190.                   fprintf(stderr,"nettol() SSL_ERROR_SSL\n");
  6191.                   ERR_print_errors_fp(stderr);
  6192.               }
  6193. #ifdef COMMENT
  6194.               netclos();
  6195.               return(-2);
  6196. #else
  6197.               return(-1);
  6198. #endif
  6199.           case SSL_ERROR_ZERO_RETURN:
  6200.             debug(F100,"nettol SSL_ERROR_ZERO_RETURN","",0);
  6201.             netclos();
  6202.             return(-2);
  6203.           default:
  6204.             debug(F100,"nettol SSL_ERROR_?????","",0);
  6205.             netclos();
  6206.             return(-2);
  6207.         }
  6208.     }
  6209. #endif /* CK_SSL */
  6210.  
  6211.   nettol_retry:
  6212.     try++;                              /* Increase the try counter */
  6213.  
  6214.     if (ttnet == NET_TCPB) {
  6215. #ifdef BSDSELECT
  6216.         fd_set wfds;
  6217.         struct timeval tv;
  6218.  
  6219.         debug(F101,"nettol BSDSELECT","",0);
  6220.         tv.tv_usec = 0L;
  6221.         tv.tv_sec=30;
  6222. #ifdef NT
  6223.         WSASafeToCancel = 1;
  6224. #endif /* NT */
  6225. #ifdef STREAMING
  6226.       do_select:
  6227. #endif /* STREAMING */
  6228.         FD_ZERO(&wfds);
  6229.         FD_SET(ttyfd, &wfds);
  6230.         if (select(FD_SETSIZE, NULL,
  6231. #ifdef __DECC
  6232. #ifndef __DECC_VER
  6233.                     (int *)
  6234. #endif /* __DECC_VER */
  6235. #endif /* __DECC */
  6236.                    &wfds, NULL, &tv) < 0) {
  6237.             int s_errno = socket_errno;
  6238.             debug(F101,"nettol select failed","",s_errno);
  6239. #ifdef BETADEBUG
  6240.             printf("nettol select failed: %d\n", s_errno);
  6241. #endif /* BETADEBUG */
  6242. #ifdef NT
  6243.             WSASafeToCancel = 0;
  6244.             if (!win95selectbug)
  6245. #endif /* NT */
  6246.               return(-1);
  6247.         }
  6248.         if (!FD_ISSET(ttyfd, &wfds)) {
  6249. #ifdef STREAMING
  6250.             if (streaming)
  6251.               goto do_select;
  6252. #endif /* STREAMING */
  6253.             debug(F111,"nettol","!FD_ISSET",ttyfd);
  6254. #ifdef NT
  6255.             WSASafeToCancel = 0;
  6256.             if (!win95selectbug)
  6257. #endif /* NT */
  6258.               return(-1);
  6259.         }
  6260. #ifdef NT
  6261.         WSASafeToCancel = 0;
  6262. #endif /* NT */
  6263. #else /* BSDSELECT */
  6264. #ifdef IBMSELECT
  6265.         {
  6266.             int tries = 0;
  6267.             debug(F101,"nettol IBMSELECT","",0);
  6268.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6269.                 int count;
  6270.                 if (tries++ >= 60) {
  6271.                     /* if after 60 seconds we can't get permission to write */
  6272.                     debug(F101,"nettol select failed","",socket_errno);
  6273.                     return(-1);
  6274.                 }
  6275.                 if ((count = nettchk()) < 0) {
  6276.                     debug(F111,"nettol","nettchk()",count);
  6277.                     return(count);
  6278.                 }
  6279.             }
  6280.         }
  6281. #endif /* IBMSELECT */
  6282. #endif /* BSDSELECT */
  6283.         if ((count = socket_write(ttyfd,s,n)) < 0) {
  6284.             int s_errno = socket_errno; /* maybe a function */
  6285.             debug(F101,"nettol socket_write error","",s_errno);
  6286. #ifdef OS2
  6287.             if (os2socketerror(s_errno) < 0)
  6288.               return(-2);
  6289. #endif /* OS2 */
  6290.             return(-1);                 /* Call it an i/o error */
  6291.         }
  6292.         if (count < n) {
  6293.             debug(F111,"nettol socket_write",s,count);
  6294.             if (try > 25) {
  6295.                 /* don't try more than 25 times */
  6296.                 debug(F100,"nettol tried more than 25 times","",0);
  6297.                 return(-1);
  6298.             }
  6299.             if (count > 0) {
  6300.                 s += count;
  6301.                 n -= count;
  6302.             }
  6303.             debug(F111,"nettol retry",s,n);
  6304.             goto nettol_retry;
  6305.         } else {
  6306.             debug(F111,"nettol socket_write",s,count);
  6307.             return(len); /* success - return total length */
  6308.         }
  6309.     } else
  6310.       return(-2);
  6311. #else
  6312.     debug(F100,"nettol TCPIPLIB not defined","",0);
  6313.     return(-2);
  6314. #endif /* TCPIPLIB */
  6315. }
  6316.  
  6317. /*  N E T T O C  --   Output character to network */
  6318. /*
  6319.   Call with character to be transmitted.
  6320.   Returns 0 if transmission was successful, or
  6321.   -1 upon i/o error, or -2 if called improperly.
  6322. */
  6323. int
  6324. #ifdef CK_ANSIC
  6325. nettoc(CHAR c)
  6326. #else
  6327. nettoc(c) CHAR c;
  6328. #endif /* CK_ANSIC */
  6329. /* nettoc */ {
  6330. #ifdef UNIX
  6331.     return(ttoc(c));
  6332. #else
  6333. #ifdef TCPIPLIB
  6334.     unsigned char cc;
  6335.     if (ttyfd == -1) {
  6336.         debug(F100,"nettoc socket is closed","",0);
  6337.         return -1;
  6338.     }
  6339.     cc = c;
  6340.     debug(F101,"nettoc cc","",cc);
  6341.  
  6342. #ifdef CK_KERBEROS
  6343. #ifdef KRB4
  6344. #ifdef RLOGCODE
  6345.     if (ttnproto == NP_EK4LOGIN) {
  6346.         return(krb4_des_write(ttyfd,&cc,1)==1?0:-1);
  6347.     }
  6348. #endif /* RLOGCODE */
  6349. #endif /* KRB4 */
  6350. #ifdef KRB5
  6351. #ifdef RLOGCODE
  6352.     if (ttnproto == NP_EK5LOGIN) {
  6353.         return(krb5_des_write(ttyfd,&cc,1,0)==1?0:-1);
  6354.     }
  6355. #endif /* RLOGCODE */
  6356. #ifdef KRB5_U2U
  6357.     if (ttnproto == NP_K5U2U) {
  6358.         return(krb5_u2u_write(ttyfd,&cc,1)==1?0:-1);
  6359.     }
  6360. #endif /* KRB5_U2U */
  6361. #endif /* KRB5 */
  6362. #endif /* CK_KERBEROS */
  6363.  
  6364. #ifdef CK_ENCRYPTION
  6365.         if ( TELOPT_ME(TELOPT_ENCRYPTION) )
  6366.             ck_tn_encrypt(&cc,1);
  6367. #endif /* CK_ENCRYPTION */
  6368. #ifdef CK_SSL
  6369.     if (ssl_active_flag || tls_active_flag) {
  6370.         int len, error;
  6371.         /* Write using SSL */
  6372.         if (ssl_active_flag)
  6373.           len = SSL_write(ssl_con, &cc, 1);
  6374.         else
  6375.           len = SSL_write(tls_con, &cc, 1);
  6376.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
  6377.           case SSL_ERROR_NONE:
  6378.             debug(F111,"nettoc","SSL_write",len);
  6379.             return(len == 1 ? 0 : -1);
  6380.           case SSL_ERROR_WANT_WRITE:
  6381.           case SSL_ERROR_WANT_READ:
  6382.             return(-1);
  6383.           case SSL_ERROR_SYSCALL:
  6384.               if ( len == 0 ) { /* EOF */
  6385.                   netclos();
  6386.                   return(-2);
  6387.               } else {
  6388.                   int rc = -1;
  6389. #ifdef NT
  6390.                   int gle = GetLastError();
  6391.                   debug(F111,"nettoc SSL_ERROR_SYSCALL",
  6392.                          "GetLastError()",gle);
  6393.                   rc = os2socketerror(gle);
  6394.                   if (rc == -1)
  6395.                       rc = -2;
  6396.                   else if ( rc == -2 )
  6397.                       return -1;
  6398. #endif /* NT */
  6399.                   return(rc);
  6400.               }
  6401.         case SSL_ERROR_SSL:
  6402.               if (bio_err!=NULL) {
  6403.                   int len;
  6404.                   extern char ssl_err[];
  6405.                   BIO_printf(bio_err,"nettoc() SSL_ERROR_SSL\n");
  6406.                   ERR_print_errors(bio_err);
  6407.                   len = BIO_read(bio_err,ssl_err,SSL_ERR_BFSZ);
  6408.                   ssl_err[len < SSL_ERR_BFSZ ? len : SSL_ERR_BFSZ] = '\0';
  6409.                   debug(F110,"nettoc SSL_ERROR_SSL",ssl_err,0);
  6410.                   if (ssl_debug_flag)
  6411.                       printf(ssl_err);
  6412.               } else if (ssl_debug_flag) {
  6413.                   debug(F100,"nettoc SSL_ERROR_SSL","",0);
  6414.                   fflush(stderr);
  6415.                   fprintf(stderr,"nettoc() SSL_ERROR_SSL\n");
  6416.                   ERR_print_errors_fp(stderr);
  6417.               }
  6418.               return(-1);
  6419.               break;
  6420.           case SSL_ERROR_WANT_X509_LOOKUP:
  6421.           case SSL_ERROR_ZERO_RETURN:
  6422.           default:
  6423.             netclos();
  6424.             return(-2);
  6425.         }
  6426.     }
  6427. #endif /* CK_SSL */
  6428.     if (ttnet == NET_TCPB) {
  6429. #ifdef BSDSELECT
  6430.         fd_set wfds;
  6431.         struct timeval tv;
  6432.  
  6433.         debug(F101,"nettoc BSDSELECT","",0);
  6434.         tv.tv_usec = 0L;
  6435.         tv.tv_sec = 30;
  6436.  
  6437. #ifdef STREAMING
  6438.       do_select:
  6439. #endif /* STREAMING */
  6440.  
  6441.         FD_ZERO(&wfds);
  6442.         FD_SET(ttyfd, &wfds);
  6443.         if (select(FD_SETSIZE, NULL,
  6444. #ifdef __DECC
  6445. #ifndef __DECC_VER
  6446.                    (int *)
  6447. #endif /* __DECC_VER */
  6448. #endif /* __DECC */
  6449.                    &wfds, NULL, &tv) < 0) {
  6450.             int s_errno = socket_errno;
  6451.             debug(F101,"nettoc select failed","",s_errno);
  6452. #ifdef BETADEBUG
  6453.             printf("nettoc select failed: %d\n", s_errno);
  6454. #endif /* BETADEBUG */
  6455. #ifdef NT
  6456.             WSASafeToCancel = 0;
  6457.             if (!win95selectbug)
  6458. #endif /* NT */
  6459.               return(-1);
  6460.         }
  6461.         if (!FD_ISSET(ttyfd, &wfds)) {
  6462. #ifdef STREAMING
  6463.             if (streaming)
  6464.               goto do_select;
  6465. #endif /* STREAMING */
  6466.             debug(F111,"nettoc","!FD_ISSET",ttyfd);
  6467. #ifdef NT
  6468.             WSASafeToCancel = 0;
  6469.             if (!win95selectbug)
  6470. #endif /* NT */
  6471.               return(-1);
  6472.         }
  6473. #ifdef NT
  6474.         WSASafeToCancel = 0;
  6475. #endif /* NT */
  6476. #else /* BSDSELECT */
  6477. #ifdef IBMSELECT
  6478.         {
  6479.             int tries = 0;
  6480.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6481.                 int count;
  6482.                 if (tries++ >= 60) {
  6483.                     /* if after 60 seconds we can't get permission to write */
  6484.                     debug(F101,"nettoc select failed","",socket_errno);
  6485.                     return(-1);
  6486.                 }
  6487.                 if ((count = nettchk()) < 0) {
  6488.                     debug(F111,"nettoc","nettchk()",count);
  6489.                     return(count);
  6490.                 }
  6491.             }
  6492.         }
  6493. #endif /* IBMSELECT */
  6494. #endif /* BSDSELECT */
  6495.         if (socket_write(ttyfd,&cc,1) < 1) {
  6496.             int s_errno = socket_errno;         /* maybe a function */
  6497.             debug(F101,"nettoc socket_write error","",s_errno);
  6498. #ifdef OS2
  6499.             if (os2socketerror(s_errno) < 0)
  6500.               return(-2);
  6501. #endif /* OS2 */
  6502.             return(-1);
  6503.         }
  6504.         debug(F101,"nettoc socket_write","", cc);
  6505.         return(0);
  6506.     } else return(-2);
  6507. #else
  6508.     return(-2);
  6509. #endif /* TCPIPLIB */
  6510. #endif /* UNIX */
  6511. }
  6512.  
  6513. /*  N E T F L U I  --  Flush network input buffer  */
  6514.  
  6515. #ifdef TNCODE
  6516. static int
  6517. #ifdef CK_ANSIC
  6518. netgetc(int timo)                       /* Input function to point to... */
  6519. #else  /* CK_ANSIC */
  6520. netgetc(timo) int timo;
  6521. #endif /* CK_ANSIC */
  6522. {                                       /* ...in the tn_doop() call */
  6523. #ifdef TCPIPLIB
  6524.     return netinc(timo);
  6525. #else /* TCPIPLIB */
  6526.     return ttinc(timo);
  6527. #endif /* TCPIPLIB */
  6528. }
  6529. #endif /* TNCODE */
  6530.  
  6531. int
  6532. netflui() {
  6533.     int n;
  6534.     int ch;
  6535. #ifdef NETLEBUF
  6536.     ttpush = -1;                        /* Clear the peek-ahead char */
  6537.     while (le_data && (le_inbuf() > 0)) {
  6538.         CHAR ch = '\0';
  6539.         if (le_getchar(&ch) > 0) {
  6540.             debug(F101,"ttflui le_inbuf ch","",ch);
  6541.         }
  6542.     }
  6543. #endif /* NETLEBUF */
  6544.  
  6545. #ifdef TCPIPLIB
  6546. #ifdef OS2
  6547.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  6548. #endif /* OS2 */
  6549. #ifdef TNCODE
  6550.     if (ttnproto == NP_TELNET) {
  6551.         /* Netflui must process Telnet negotiations or get out of sync */
  6552.         if ((n = nettchk()) <= 0)
  6553.           goto exit_flui;
  6554.         while (n-- > 0) {
  6555.             ch = netinc(1);
  6556.             if (ch == IAC) {
  6557.                 extern int duplex;  /* this really shouldn't be here but ... */
  6558.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6559.                 if (tx == 1) duplex = 1;
  6560.                 else if (tx == 2) duplex = 0;
  6561.                 n = nettchk();
  6562.             }
  6563.         }
  6564.     } else
  6565. #endif /* TNCODE */
  6566.     {
  6567.         ttibuf[ttibp+ttibn] = '\0';
  6568.         debug(F111,"netflui 1",ttibuf,ttibn);
  6569. #ifdef CK_ENCRYPTION
  6570.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6571.             ck_tn_decrypt(&ttibuf[ttibp],ttibn);
  6572.         }
  6573. #endif /* CK_ENCRYPTION */
  6574.         ttibn = ttibp = 0;              /* Flush internal buffer *FIRST* */
  6575.         if (ttyfd < 1)
  6576.           goto exit_flui;
  6577.         if ((n = nettchk()) > 0) {      /* Now see what's waiting on the net */
  6578.             if (n > TTIBUFL) n = TTIBUFL;       /* and sponge it up */
  6579.             debug(F101,"netflui 2","",n);       /* ... */
  6580.             n = socket_read(ttyfd,ttibuf,n); /* into our buffer */
  6581.             if (n >= 0) ttibuf[n] = '\0';
  6582.             debug(F111,"netflui 3",ttibuf,n);
  6583. #ifdef CK_ENCRYPTION
  6584.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6585.                 ck_tn_decrypt(&ttibuf[ttibp],n);
  6586.             }
  6587. #endif /* CK_ENCRYPTION */
  6588.             ttibuf[0] = '\0';
  6589.         }
  6590.     }
  6591. #else  /* !TCPIPLIB */
  6592.     if (ttyfd < 1)
  6593.       goto exit_flui;
  6594. #ifdef TNCODE
  6595.     if (ttnproto == NP_TELNET) {
  6596.         if ((n = ttchk()) <= 0)
  6597.           goto exit_flui;
  6598.         while (n-- >= 0) {
  6599.             /* Netflui must process Telnet negotiations or get out of sync */
  6600.             ch = ttinc(1);
  6601.             if (ch == IAC) {
  6602.                 extern int duplex;  /* this really shouldn't be here but ... */
  6603.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6604.                 if (tx == 1) duplex = 1;
  6605.                 else if (tx == 2) duplex = 0;
  6606.                 n = ttchk();
  6607.             }
  6608.         };
  6609.     } else
  6610. #endif /* TNCODE */
  6611.     if ((n = ttchk()) > 0) {
  6612.         debug(F101,"netflui non-TCPIPLIB","",n);
  6613.         while ((n--) && ttinc(1) > -1)  /* Don't worry, ttinc() is buffered */
  6614.           ;                             /* and it handles the decryption... */
  6615.     }
  6616. #endif /* TCPIPLIB */
  6617.   exit_flui:
  6618. #ifdef OS2
  6619.     ReleaseTCPIPMutex();
  6620. #endif /* OS2 */
  6621.     return(0);
  6622. }
  6623.  
  6624. #ifdef CK_KERBEROS
  6625. /* The following two functions are required for encrypted rlogin */
  6626. /* They are called with nettoc() or nettol() are transmitting    */
  6627. /* encrypted data.  They call a function to encrypt the data     */
  6628. /* and that function needs to be able to write to/read from the  */
  6629. /* network in an unimpeded manner.  Hence, these two simple fns. */
  6630. int
  6631. net_write(fd, buf, len)
  6632.     int fd;
  6633.     register const char *buf;
  6634.     int len;
  6635. {
  6636.     int cc;
  6637.     register int wrlen = len;
  6638.     do {
  6639. #ifdef TCPIPLIB
  6640.         cc = socket_write(fd, buf, wrlen);
  6641. #else
  6642.         cc = write(fd,buf,wrlen);
  6643. #endif /* TCPIPLIB */
  6644.         if (cc < 0) {
  6645.             int s_errno = socket_errno;
  6646.             debug(F101,"net_write error","",s_errno);
  6647. #ifdef OS2
  6648.             if (os2socketerror(s_errno) < 0)
  6649.                 return(-1);
  6650.             else
  6651.                 continue;
  6652. #else /* OS2 */
  6653.             if (errno == EINTR)
  6654.                 continue;
  6655.             return(-1);
  6656. #endif /* OS2 */
  6657.         }
  6658.         else {
  6659.             buf += cc;
  6660.             wrlen -= cc;
  6661.         }
  6662.     } while (wrlen > 0);
  6663.     return(len);
  6664. }
  6665. int
  6666. net_read(fd, buf, len)
  6667.     int fd;
  6668.     register char *buf;
  6669.     register int len;
  6670. {
  6671.     int cc, len2 = 0;
  6672.  
  6673.     do {
  6674. #ifdef TCPIPLIB
  6675.         cc = socket_read(fd, buf, len);
  6676. #else
  6677.         cc = read(fd,buf,len);
  6678. #endif
  6679.         if (cc < 0) {
  6680.             int s_errno = socket_errno;
  6681.             debug(F101,"net_read error","",s_errno);
  6682. #ifdef OS2
  6683.             if (os2socketerror(s_errno) < 0)
  6684.                 return(-1);
  6685. #endif /* OS2 */
  6686.             return(cc);          /* errno is already set */
  6687.         }
  6688.         else if (cc == 0) {
  6689.             netclos();
  6690.             return(len2);
  6691.         } else {
  6692.             buf += cc;
  6693.             len2 += cc;
  6694.             len -= cc;
  6695.         }
  6696.     } while (len > 0);
  6697.     return(len2);
  6698. }
  6699. #endif /* CK_KERBEROS */
  6700. #endif /* NONET */
  6701.  
  6702. /* getlocalipaddr() attempts to resolve an IP Address for the local machine.
  6703.  *   If the host is multi-homed it returns only one address.
  6704.  *
  6705.  * Two techniques are used.
  6706.  * (1) get the local host name and perform a DNS lookup, then take
  6707.  *     the first entry;
  6708.  * (2) open a UDP socket, use it to connect to a fictitious host (it's OK,
  6709.  *    no data is sent), then retrieve the local address from the socket.
  6710.  * Note: the second technique won't work on Microsoft systems.  See
  6711.  * Article ID: Q129065 PRB: Getsockname() Returns IP Address 0.0.0.0 for UDP
  6712.  */
  6713.  
  6714. /* Technique number one cannot work reliably if the machine is a laptop
  6715.  * and the hostname is associated with a physical adapter which is not
  6716.  * installed and a PPP connection is being used instead.  This is because
  6717.  * the hostname DNS lookup will succeed for the physical adapter even though
  6718.  * it would be impossible to use it.  In NT4 SP4, the gethostbyname()
  6719.  * when given the result of gethostname() returns not the real DNS entries
  6720.  * for that name+domain.  Instead it returns all of the static and dynamic
  6721.  * IP addresses assigned to any physical or virtual adapter defined in the
  6722.  * system regardless of whether or not it is installed.  The order of the
  6723.  * addresses is fixed according to the binding order in the NT registry.
  6724.  */
  6725.  
  6726. /*
  6727.  * It appears that calling gethostbyname(NULL) is more reliable than
  6728.  * calling gethostbyname(gethostname()) on Windows.  So on Windows we will
  6729.  * only call gethostbyname(NULL).
  6730.  */
  6731.  
  6732. int
  6733. getlocalipaddr() {
  6734. #ifndef datageneral
  6735.     struct sockaddr_in l_sa;
  6736.     struct sockaddr_in r_sa;
  6737.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6738.     int sock;
  6739.     int rc;
  6740.     struct in_addr laddr;
  6741.  
  6742.     /* if still not resolved, then try second strategy */
  6743.     /* This second strategy does not work on Windows */
  6744.  
  6745.     memset(&l_sa,0,slen);
  6746.     memset(&r_sa,0,slen);
  6747.  
  6748.     /* get a UDP socket */
  6749.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  6750.     if (sock != -1) {
  6751.         /* connect to arbirary port and address (NOT loopback) */
  6752.         r_sa.sin_family = AF_INET;
  6753.         r_sa.sin_port = htons(IPPORT_ECHO);
  6754.  
  6755.         /* The following is an "illegal conversion" in AOS/VS */
  6756.         /* (and who knows where else) */
  6757.  
  6758. #ifdef INADDRX
  6759.         inaddrx = inet_addr("128.127.50.1");
  6760.         r_sa.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  6761. #else
  6762.         r_sa.sin_addr.s_addr = inet_addr("128.127.50.1");
  6763. #endif /* INADDRX */
  6764.         rc = connect(sock, (struct sockaddr *) &r_sa, sizeof(struct sockaddr));
  6765.         if (!rc) {                      /* get local address */
  6766.             getsockname(sock,(struct sockaddr *)&l_sa,&slen);
  6767. #ifdef TCPIPLIB
  6768.             socket_close(sock);         /* We're done with the socket */
  6769. #else
  6770.             close(sock);
  6771. #endif /* TCPIPLIB */
  6772.             if (l_sa.sin_addr.s_addr != INADDR_ANY) {
  6773.                 myxipaddr = ntohl(l_sa.sin_addr.s_addr);
  6774.                 ckstrncpy(myipaddr,(char *)inet_ntoa(l_sa.sin_addr),20);
  6775.                 debug(F110,"getlocalipaddr setting buf to",myipaddr,0);
  6776.                 return(0);
  6777.             }
  6778.         }
  6779.     }
  6780.     return getlocalipaddrs(myipaddr,sizeof(myipaddr),0);
  6781. #else /* datageneral */
  6782.     return(-1);
  6783. #endif /* datageneral */
  6784. }
  6785.  
  6786. int
  6787. getlocalipaddrs(buf,bufsz,index)
  6788.     char * buf;
  6789.     int    bufsz;
  6790.     int    index;
  6791. /* getlocalipaddrs */ {
  6792. #ifndef datageneral
  6793.     char localhost[256];
  6794.     struct hostent * host=NULL;
  6795.     struct sockaddr_in l_sa;
  6796.     struct sockaddr_in r_sa;
  6797.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6798.     int rc;
  6799. #ifdef COMMENT
  6800.     int sock;
  6801.     char messageBuf[60];
  6802.     struct in_addr laddr;
  6803. #endif /* COMMENT */
  6804.  
  6805.     memset(&l_sa,0,slen);
  6806.     memset(&r_sa,0,slen);
  6807.  
  6808.     /* init local address (to zero) */
  6809.     l_sa.sin_addr.s_addr = INADDR_ANY;
  6810.  
  6811. #ifdef CKGHNLHOST
  6812.     rc = gethostname(localhost, 256);
  6813.     debug(F110,"getlocalipaddrs localhost",localhost,0);
  6814. #else
  6815.     /* This doesn't work on some platforms, e.g. Solaris */
  6816.     rc = 0;
  6817.     localhost[0] = '\0';
  6818. #ifdef NT
  6819.     if ( winsock_version < 20 ) {
  6820.         rc = gethostname(localhost, 256);
  6821.         debug(F110,"getlocalipaddrs localhost",localhost,0);
  6822.     }
  6823. #endif /* NT */
  6824. #endif /* CKGHNLHOST */
  6825.     if (!rc) {
  6826.         /* resolve host name for local address */
  6827.         debug(F110,"getlocalipaddrs","calling gethostbyname()",0);
  6828.         host = gethostbyname(localhost);
  6829.         debug(F111,"getlocalipaddrs","gethostbyname() returned",host);
  6830.         if (host) {
  6831. #ifdef HADDRLIST
  6832.             host = ck_copyhostent(host);
  6833.             if ( index < 0 || index > 63 || !host->h_addr_list[index] ) {
  6834.                 buf[0] = '\0';
  6835.                 return(-1);
  6836.             }
  6837.             l_sa.sin_addr.s_addr =
  6838.               *((unsigned long *) (host->h_addr_list[index]));
  6839.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),20);
  6840.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6841.  
  6842. #ifdef COMMENT
  6843.             /* This is for reporting multiple IP Address */
  6844.             while (host->h_addr_list && host->h_addr_list[0]) {
  6845.                 l_sa.sin_addr.s_addr =
  6846.                   *((unsigned long *) (host->h_addr_list[0]));
  6847.                 ckstrncpy(messageBuf,
  6848.                         (char *)inet_ntoa(l_sa.sin_addr),60);
  6849.                 if (tcp_address) {
  6850.                     if (!strcmp(messageBuf,tcp_address))
  6851.                       ckstrncpy(myipaddr,tcp_address,20);
  6852.                 }
  6853.                 debug(F110,"getlocalipaddrs ip address list", messageBuf, 0);
  6854.                 host->h_addr_list++;
  6855.             }
  6856. #endif /* COMMENT */
  6857. #else   /* HADDRLIST */
  6858.             if (index != 0) {
  6859.                 buf[0] = '\0';
  6860.                 return(-1);
  6861.             }
  6862.             l_sa.sin_addr.s_addr = *((unsigned long *) (host->h_addr));
  6863.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),bufsz);
  6864.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6865. #endif  /* HADDRLIST */
  6866.             return(0);
  6867.         } else debug(F110,
  6868.                      "getlocalipaddrs: gethostbyname() failed",
  6869.                      localhost,
  6870.                      0
  6871.                      );
  6872.     }
  6873. #endif /* datageneral */
  6874.     return(-1);
  6875. }
  6876.  
  6877. #ifdef RLOGCODE                 /* TCP/IP RLOGIN protocol support code */
  6878. int
  6879. rlog_naws() {
  6880.     struct rlog_naws {
  6881.         unsigned char id[4];
  6882.         unsigned short rows, cols, ypix, xpix;
  6883.     } nawsbuf;
  6884.  
  6885.     if (ttnet != NET_TCPB)
  6886.       return 0;
  6887.     if (ttnproto != NP_RLOGIN
  6888. #ifdef CK_KERBEROS
  6889.         && ttnproto != NP_K4LOGIN
  6890.         && ttnproto != NP_EK4LOGIN
  6891.         && ttnproto != NP_K5LOGIN
  6892.         && ttnproto != NP_EK5LOGIN
  6893. #endif /* CK_KERBEROS */
  6894.          )
  6895.       return 0;
  6896.     if (!TELOPT_ME(TELOPT_NAWS))
  6897.       return 0;
  6898.  
  6899.     debug(F100,"rlogin Window Size sent","",0);
  6900.  
  6901.     nawsbuf.id[0] = nawsbuf.id[1] = 0377;
  6902.     nawsbuf.id[2] = nawsbuf.id[3] = 's';
  6903. #ifdef OS2
  6904.     nawsbuf.rows = htons((unsigned short) (VscrnGetHeight(VTERM)
  6905.                           -(tt_status[VTERM]?1:0)));
  6906.     nawsbuf.cols = htons((unsigned short) VscrnGetWidth(VTERM));
  6907. #else /* OS2 */
  6908.     nawsbuf.rows = htons((unsigned short) tt_rows);
  6909.     nawsbuf.cols = htons((unsigned short) tt_cols);
  6910. #endif /* OS2 */
  6911.     nawsbuf.ypix = htons(0);            /* y pixels */
  6912.  
  6913.     nawsbuf.xpix = htons(0);            /* x pixels */
  6914.     if (ttol((CHAR *)(&nawsbuf), sizeof(nawsbuf)) < 0)
  6915.       return(-1);
  6916.     return(0);
  6917. }
  6918.  
  6919. #ifdef OS2ORUNIX
  6920. #define RLOGOUTBUF
  6921. #endif /* OS2 */
  6922. static int
  6923. #ifdef CK_ANSIC
  6924. rlog_ini(CHAR * hostname, int port,
  6925.          struct sockaddr_in * l_addr, struct sockaddr_in * r_addr)
  6926. #else /* CK_ANSIC */
  6927. rlog_ini(hostname, port, l_addr, r_addr)
  6928.     CHAR * hostname;
  6929.     int port;
  6930.     struct sockaddr_in * l_addr;
  6931.     struct sockaddr_in * r_addr;
  6932. #endif /* CK_ANSIC */
  6933. /* rlog_ini */ {
  6934.  
  6935. #ifdef RLOGOUTBUF
  6936.     char outbuf[512];
  6937.     int  outbytes=0;
  6938. #endif /* RLOGOUTBUF */
  6939.     int flag = 0;
  6940. #define TERMLEN 16
  6941. #define CONSPDLEN 16
  6942.     CHAR localuser[UIDBUFLEN+1];
  6943.     CHAR remoteuser[UIDBUFLEN+1];
  6944.     int userlen = 0;
  6945.     CHAR term_speed[TERMLEN+CONSPDLEN+1];
  6946. #ifdef CONGSPD
  6947.     long conspd = -1L;
  6948. #endif /* CONGSPD */
  6949. #ifdef OS2
  6950.     extern int tt_type, max_tt;
  6951.     extern struct tt_info_rec tt_info[];
  6952. #endif /* OS2 */
  6953.     int i, n;
  6954.  
  6955.     int rc = 0;
  6956.     tn_reset();                 /* This call will reset all of the Telnet */
  6957.                                 /* options and then quit.  We need to do  */
  6958.                                 /* this since we use the Telnet options   */
  6959.                                 /* to hold various state information      */
  6960.     duplex = 0;                 /* Rlogin is always remote echo */
  6961.     rlog_inband = 0;
  6962.  
  6963. #ifdef CK_TTGWSIZ
  6964. /*
  6965.   But compute the values anyway before the first read since the out-
  6966.   of-band NAWS request would arrive before the first data byte (NULL).
  6967. */
  6968. #ifdef OS2
  6969.     /* Console terminal screen rows and columns */
  6970.     debug(F101,"rlog_ini tt_rows 1","",VscrnGetHeight(VTERM)
  6971.            -(tt_status[VTERM]?1:0));
  6972.     debug(F101,"rlog_ini tt_cols 1","",VscrnGetWidth(VTERM));
  6973.     /* Not known yet */
  6974.     if (VscrnGetWidth(VTERM) < 0 ||
  6975.         VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0) < 0) {
  6976.         ttgwsiz();                      /* Try to get screen dimensions */
  6977.     }
  6978.     debug(F101,
  6979.           "rlog_ini tt_rows 2",
  6980.           "",
  6981.           VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0)
  6982.           );
  6983.     debug(F101,"rlog_ini tt_cols 2","",VscrnGetWidth(VTERM));
  6984. #else /* OS2 */
  6985.     debug(F101,"rlog_ini tt_rows 1","",tt_rows);
  6986.     debug(F101,"rlog_ini tt_cols 1","",tt_cols);
  6987.     if (tt_rows < 0 || tt_cols < 0) {   /* Not known yet */
  6988.         ttgwsiz();                      /* Try to find out */
  6989.     }
  6990.     debug(F101,"rlog_ini tt_rows 2","",tt_rows);
  6991.     debug(F101,"rlog_ini tt_cols 2","",tt_cols);
  6992. #endif /* OS2 */
  6993. #endif /* CK_TTGWSIZ */
  6994.  
  6995.     ttflui();                           /* Start by flushing the buffers */
  6996.  
  6997.     rlog_mode = RL_COOKED;
  6998.  
  6999.     /* Determine the user's local username ... */
  7000.  
  7001.     localuser[0] = '\0';
  7002. #ifdef NT
  7003.     {
  7004.         char localuid[UIDBUFLEN+1];
  7005.         ckstrncpy((char *)localuser,(char *)GetLocalUser(),UIDBUFLEN);
  7006.     }
  7007.  
  7008.     if ( !localuser[0] )
  7009. #endif /* NT */
  7010.     {
  7011.         char * user = getenv("USER");
  7012.         if (!user)
  7013.           user = "";
  7014.         userlen = strlen(user);
  7015.         debug(F111,"rlogin getenv(USER)",user,userlen);
  7016.         ckstrncpy((char *)localuser,user,UIDBUFLEN);
  7017.         debug(F110,"rlog_ini localuser 1",localuser,0);
  7018.     }
  7019.     if ( !localuser[0] )
  7020.         strcpy((char *)localuser,"unknown");
  7021.     else if (ck_lcname) {
  7022.         cklower((char *)localuser);
  7023.         debug(F110,"rlog_ini localuser 2",localuser,0);
  7024.     }
  7025.  
  7026.     /* And the username to login with */
  7027.     if (uidbuf[0]) {
  7028.         ckstrncpy((char *)remoteuser,uidbuf,UIDBUFLEN);
  7029.         debug(F110,"rlog_ini remoteuser 1",remoteuser,0);
  7030.     } else if (localuser[0]) {
  7031.         ckstrncpy((char *)remoteuser,(char *)localuser,UIDBUFLEN);
  7032.         debug(F110,"rlog_ini remoteuser 2",remoteuser,0);
  7033.     } else {
  7034.         remoteuser[0] = '\0';
  7035.         debug(F110,"rlog_ini remoteuser 3",remoteuser,0);
  7036.     }
  7037.     if (ck_lcname)
  7038.       cklower((char *)remoteuser);
  7039.     debug(F110,"rlog_ini remoteuser 4",remoteuser,0);
  7040.  
  7041.     /* The command to issue is the terminal type and speed */
  7042.     term_speed[0] = '\0';
  7043.     if (tn_term) {                      /* SET TELNET TERMINAL-TYPE value */
  7044.         if (*tn_term) {                 /* (if any) takes precedence. */
  7045.             ckstrncpy((char *)term_speed, tn_term, TERMLEN);
  7046.             flag = 1;
  7047.         }
  7048.     } else {                            /* Otherwise the local terminal type */
  7049. #ifdef OS2
  7050.         /* In terminal-emulating versions, it's the SET TERM TYPE value */
  7051.         ckstrncpy(term_speed, (tt_type >= 0 && tt_type <= max_tt) ?
  7052.                 tt_info[tt_type].x_name : "network", TERMLEN);
  7053. #else
  7054.         /* In the others, we just look at the TERM environment variable */
  7055.         {
  7056.             char *p = getenv("TERM");
  7057.             if (p)
  7058.               ckstrncpy((char *)term_speed,p,TERMLEN);
  7059.             else
  7060.               term_speed[0] = '\0';
  7061. #ifdef VMS
  7062.             for (p = (char *) term_speed; *p; p++) {
  7063.                 if (*p == '-' && (!strcmp(p,"-80") || !strcmp(p,"-132")))
  7064.                   break;
  7065.                 else if (isupper(*p))
  7066.                   *p = tolower(*p);
  7067.             }
  7068.             *p = '\0';
  7069. #endif /* VMS */
  7070.         }
  7071. #endif /* OS2 */
  7072.     }
  7073.     n = strlen((char *)term_speed);
  7074.     if (n > 0) {                        /* We have a terminal type */
  7075.         if (!flag) {                    /* If not user-specified */
  7076.             for (i = 0; i < n; i++)     /* then lowercase it.    */
  7077.               if (isupper(term_speed[i]))
  7078.                 term_speed[i] = tolower(term_speed[i]);
  7079.         }
  7080.         debug(F110,"rlog_ini term_speed 1",term_speed,0);
  7081.  
  7082. #ifdef CONGSPD
  7083.         /* conspd() is not yet defined in all ck*tio.c modules */
  7084.         conspd = congspd();
  7085.         if (conspd > 0L) {
  7086.             ckstrncat((char *)term_speed,"/",sizeof(term_speed));
  7087.             ckstrncat((char *)term_speed,ckltoa(conspd),sizeof(term_speed));
  7088.         } else
  7089. #endif /* CONGSPD */
  7090.           ckstrncat((char *)term_speed,"/19200",sizeof(term_speed));
  7091.         debug(F110,"rlog_ini term_speed 2",term_speed,0);
  7092.     } else {
  7093.         term_speed[0] = '\0';
  7094.         debug(F110,"rlog_ini term_speed 3",term_speed,0);
  7095.     }
  7096.  
  7097. #ifdef CK_KERBEROS
  7098.     if (ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  7099.         ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) {
  7100.         int kver, encrypt, rc;
  7101.         switch (ttnproto) {
  7102.           case NP_K4LOGIN:
  7103.             kver = 4;
  7104.             encrypt = 0;
  7105.             break;
  7106.           case NP_EK4LOGIN:
  7107.             kver = 4;
  7108.             encrypt = 1;
  7109.             break;
  7110.           case NP_K5LOGIN:
  7111.             kver = 5;
  7112.             encrypt = 0;
  7113.             break;
  7114.           case NP_EK5LOGIN:
  7115.             kver = 5;
  7116.             encrypt = 1;
  7117.             break;
  7118.         default:
  7119.             kver = 0;
  7120.             encrypt = 0;
  7121.         }
  7122.         rc = ck_krb_rlogin(hostname, port,
  7123.                            localuser, remoteuser, term_speed,
  7124.                            l_addr, r_addr, kver, encrypt);
  7125.         if (!rc) {                      /* success */
  7126.             TELOPT_ME(TELOPT_NAWS) = 1;
  7127.             rc = rlog_naws();
  7128.         }
  7129.         return(rc);
  7130.     } else
  7131. #endif /* CK_KERBEROS */
  7132.     if (ttnproto == NP_RLOGIN) {
  7133. #ifdef RLOGOUTBUF
  7134.         /*
  7135.          *  The rcmds start the connection with a series of init data:
  7136.          *
  7137.          *    a port number upon which client is listening for stderr data
  7138.          *    the user's name on the client machine
  7139.          *    the user's name on the server machine
  7140.          *    the terminal_type/speed or command to execute
  7141.          */
  7142.         outbuf[outbytes++] = 0;
  7143.         strcpy((char *)outbuf+outbytes,(char *)localuser);
  7144.         outbytes += strlen((char *)localuser) + 1;
  7145.         strcpy((char *)outbuf+outbytes,(char *)remoteuser);
  7146.         outbytes += strlen((char *)remoteuser) + 1;
  7147.         strcpy((char *)outbuf+outbytes,(char *)term_speed);
  7148.         outbytes += strlen((char *)term_speed) + 1;
  7149.         rc = ttol((CHAR *)outbuf,outbytes);
  7150. #else /* RLOGOUTBUF */
  7151.         ttoc(0);                        /* Send an initial NUL as wake-up */
  7152.         /* Send each variable with the trailing NUL */
  7153.         rc = ttol(localuser,strlen((char *)localuser)+1);
  7154.         if (rc > 0)
  7155.           rc = ttol(remoteuser,strlen((char *)remoteuser)+1);
  7156.         if (rc > 0)
  7157.           rc = ttol(term_speed,strlen((char *)term_speed)+1);
  7158. #endif /* RLOGOUTBUF */
  7159.  
  7160.         /* Now we are supposed to get back a single NUL as confirmation */
  7161.         errno = 0;
  7162.         rc = ttinc(60);
  7163.         debug(F101,"rlogin first ttinc","",rc);
  7164.         if (rc > 0) {
  7165.             debug(F101,"rlogin ttinc 1","",rc);
  7166.             printf(
  7167.                "Rlogin protocol error - 0x%x received instead of 0x00\n", rc);
  7168.             return(-1);
  7169.         } else if (rc < 0) {
  7170.             debug(F101,"rlogin ttinc errno","",errno);
  7171.             /* printf("Network error: %d\n", errno); */
  7172.             return(-1);
  7173.         }
  7174.     }
  7175.     return(0);
  7176. }
  7177.  
  7178. /* two control messages are defined:
  7179.  
  7180.    a double flag byte of 'o' indicates a one-byte message which is
  7181.    identical to what was once carried out of band.
  7182.  
  7183.    a double flag byte of 'q' indicates a zero-byte message.  This
  7184.    message is interpreted as two \377 data bytes.  This is just a
  7185.    quote rule so that binary data from the server does not confuse the
  7186.    client.  */
  7187.  
  7188. int 
  7189. rlog_ctrl(cp, n)
  7190.      unsigned char *cp;
  7191.      int n;
  7192. {
  7193.     if ((n >= 5) && (cp[2] == 'o') && (cp[3] == 'o')) {
  7194.         if (rlog_oob(&cp[4],1))
  7195.             return(-5);
  7196.         return(5);
  7197.     } else if ((n >= 4) && (cp[2] == 'q') && (cp[3] == 'q')) {
  7198.         /* this is somewhat of a hack */
  7199.         cp[2] = '\377';
  7200.         cp[3] = '\377';
  7201.         return(2);
  7202.     }
  7203.     return(0);
  7204. }
  7205.  
  7206. static int
  7207. rlog_oob(oobdata, count) CHAR * oobdata; int count; {
  7208.     int i;
  7209.     int flush = 0;
  7210.  
  7211.     debug(F111,"rlogin out_of_band","count",count);
  7212.  
  7213.     for (i = 0; i<count; i++)   {
  7214.         debug(F101,"rlogin out_of_band","",oobdata[i]);
  7215.                 if (oobdata[i] & 0x01)
  7216.                         continue;
  7217.  
  7218.         if (oobdata[i] & 0x02) { /* Flush Buffered Data not yet displayed */
  7219.             debug(F101,"rlogin Flush Buffered Data command","",oobdata[i]);
  7220.  
  7221.             /* Only flush the data if in fact we are in a mode that won't */
  7222.             /* get out of sync.  Ie, not when we are in protocol mode.    */
  7223.             switch ( what ) {
  7224.             case W_NOTHING:
  7225.             case W_CONNECT:
  7226.             case W_COMMAND:
  7227.                 if ( rlog_inband )
  7228.                     flush = 1;
  7229.                 else
  7230.                     ttflui();
  7231.                 break;
  7232.             }
  7233.         }
  7234.         if (oobdata[i] & 0x10) {        /* Switch to RAW mode */
  7235.             debug(F101,"rlogin Raw Mode command","",oobdata[i]);
  7236.             rlog_mode = RL_RAW;
  7237.         }
  7238.  
  7239.         if (oobdata[i] & 0x20) {        /* Switch to COOKED mode */
  7240.             debug(F101,"rlogin Cooked Mode command","",oobdata[i]);
  7241.             rlog_mode = RL_COOKED;
  7242.         }
  7243.         if (oobdata[i] & 0x80)
  7244.         {        /* Send Window Size Info */
  7245.             debug(F101,"rlogin Window Size command","",oobdata[i]);
  7246.             /* Remember to send WS Info when Window Size changes */
  7247.             if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7248.                 TELOPT_ME(TELOPT_NAWS) = 1;
  7249.                 rlog_naws();
  7250.             }
  7251.         }
  7252.     }
  7253.     return(flush);
  7254. }
  7255. #ifndef TCPIPLIB
  7256. static SIGTYP
  7257. rlogoobh(sig) int sig; {
  7258. #ifdef SOLARIS
  7259.     char                                /* Or should it be char for all? */
  7260. #else
  7261.     CHAR
  7262. #endif /* SOLARIS */
  7263.       oobdata;
  7264.  
  7265.     /* int  count = 0; */ /* (not used) */
  7266.  
  7267.     while (recv(ttyfd, &oobdata, 1, MSG_OOB) < 0) {
  7268.       /*
  7269.        * We need to do some special processing here.
  7270.        * Just in case the socket is blocked for input
  7271.        *
  7272.        */
  7273.         switch (errno) {
  7274.           case EWOULDBLOCK:
  7275.             break;
  7276.           default:
  7277.             return;
  7278.         }
  7279.     }
  7280.     debug(F101,"rlogin out_of_band","",oobdata);
  7281.     if (oobdata == 0x02) {      /* Flush Buffered Data not yet displayed */
  7282.         debug(F101,"rlogin Flush Buffered Data command","",oobdata);
  7283.         netflui();
  7284.     }
  7285.     if (oobdata & 0x10) {               /* Switch to raw mode */
  7286.         debug(F101,"rlogin Raw Mode command","",oobdata);
  7287.         rlog_mode = RL_RAW;
  7288.     }
  7289.     if (oobdata & 0x20) {               /* Switch to cooked mode */
  7290.         debug(F101,"rlogin Cooked Mode command","",oobdata);
  7291.         rlog_mode = RL_COOKED;
  7292.     }
  7293.     if (oobdata & 0x80) {                 /* Send Window Size Info */
  7294.         debug(F101,"rlogin Window Size command","",oobdata);
  7295.         /* Remember to send WS Info when Window Size changes */
  7296.         if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7297.             TELOPT_ME(TELOPT_NAWS) = 1;
  7298.             rlog_naws();
  7299.         }
  7300.     }
  7301. }
  7302. #endif /* TCPIPLIB */
  7303. #endif /* RLOGCODE */
  7304.  
  7305. /* Send network BREAK */
  7306. /*
  7307.   Returns -1 on error, 0 if nothing happens, 1 if BREAK sent successfully.
  7308. */
  7309. int
  7310. netbreak() {
  7311.     CHAR buf[3];
  7312.     if (ttnet == NET_TCPB) {
  7313.         if (ttnproto == NP_TELNET) {
  7314. #ifdef TNCODE
  7315.             buf[0] = (CHAR) IAC; buf[1] = (CHAR) BREAK; buf[2] = (CHAR) 0;
  7316.             if (
  7317. #ifdef OS2
  7318.                 nettol((char *) buf, 2)
  7319. #else
  7320.                 ttol(buf, 2)
  7321. #endif /* OS2 */
  7322.                 < 2)
  7323.               return(-1);
  7324.             if (tn_deb || debses || deblog) {
  7325.                 extern char tn_msg[];
  7326.                 ckmakmsg(tn_msg,TN_MSG_LEN,"TELNET SENT ",TELCMD(BREAK),
  7327.                           NULL,NULL);
  7328.                 debug(F101,tn_msg,"",BREAK);
  7329.                 if (debses || tn_deb) tn_debug(tn_msg);
  7330.             }
  7331.             return(1);
  7332. #else
  7333.             debug(F100,"netbreak no TNCODE","",0);
  7334.             return(0);
  7335. #endif /* TNCODE */
  7336.         }
  7337.         /* Insert other TCP/IP protocols here */
  7338.     }
  7339.     /* Insert other networks here */
  7340.     return(0);
  7341. }
  7342. #endif /* NETCONN */
  7343.  
  7344.  
  7345. #ifdef NETCONN
  7346. #ifdef SUNX25
  7347. /*
  7348.   SunLink X.25 support by Marcello Frutig, Catholic University,
  7349.   Rio de Janeiro, Brazil, 1990.
  7350. */
  7351.  
  7352. /* PAD X.3, X.28 and X.29 support */
  7353.  
  7354. static CHAR x29err[MAXPADPARMS+3] = { X29_ERROR, INVALID_PAD_PARM, '\0' };
  7355.  
  7356. /* Initialize PAD */
  7357.  
  7358. extern CHAR padparms[];
  7359.  
  7360. VOID
  7361. initpad() {
  7362.   padparms[PAD_BREAK_CHARACTER]        = 0;  /* Break character */
  7363.   padparms[PAD_ESCAPE]                 = 1;  /* Escape permitted */
  7364.   padparms[PAD_ECHO]                   = 1;  /* Kermit PAD does echo */
  7365.   padparms[PAD_DATA_FORWARD_CHAR]      = 2;  /* forward character CR */
  7366.   padparms[PAD_DATA_FORWARD_TIMEOUT]   = 0;  /* no timeout forward condition */
  7367.   padparms[PAD_FLOW_CONTROL_BY_PAD]    = 0;  /* not used */
  7368.   padparms[PAD_SUPPRESSION_OF_SIGNALS] = 1;  /* allow PAD service signals */
  7369.   padparms[PAD_BREAK_ACTION]           = 21; /* brk action: INT pk + brk ind*/
  7370.   padparms[PAD_SUPPRESSION_OF_DATA]    = 0;  /* no supression of user data */
  7371.   padparms[PAD_PADDING_AFTER_CR]       = 0;  /* no padding after CR */
  7372.   padparms[PAD_LINE_FOLDING]           = 0;  /* no line fold */
  7373.   padparms[PAD_LINE_SPEED]             = 0;  /* line speed - don't care */
  7374.   padparms[PAD_FLOW_CONTROL_BY_USER]   = 0;  /* flow cont of PAD - not used */
  7375.   padparms[PAD_LF_AFTER_CR]            = 0;  /* no LF insertion after CR */
  7376.   padparms[PAD_PADDING_AFTER_LF]       = 0;  /* no padding after LF */
  7377.   padparms[PAD_EDITING]                = 1;  /* can edit */
  7378.   padparms[PAD_CHAR_DELETE_CHAR]       = 8;  /* character delete character */
  7379.   padparms[PAD_BUFFER_DELETE_CHAR]     = 21; /* buffer delete character */
  7380.   padparms[PAD_BUFFER_DISPLAY_CHAR]    = 18; /* buffer display character */
  7381. }
  7382.  
  7383. /* Set PAD parameters */
  7384.  
  7385. VOID
  7386. setpad(s,n) CHAR *s; int n; {
  7387.     int i;
  7388.     CHAR *ps = s;
  7389.  
  7390.     if (n < 1) {
  7391.         initpad();
  7392.     } else {
  7393.         for (i = 0; i < n; i++) {
  7394.             if (*ps > MAXPADPARMS)
  7395.               x29err[i+2] = *ps;
  7396.             else
  7397.               padparms[*ps] = *(ps+1);
  7398.             ps += 2;
  7399.         }
  7400.     }
  7401. }
  7402.  
  7403. /* Read PAD parameters */
  7404.  
  7405. VOID
  7406. readpad(s,n,r) CHAR *s; int n; CHAR *r; {
  7407.     int i;
  7408.     CHAR *ps = s;
  7409.     CHAR *pr = r;
  7410.  
  7411.     *pr++ = X29_PARAMETER_INDICATION;
  7412.     if (n > 0) {
  7413.         for (i = 0; i < n; i++, ps++) {
  7414.             if (*ps > MAXPADPARMS) {
  7415.                 x29err[i+2] = *ps++;
  7416.             } else {
  7417.                 *pr++ = *ps;
  7418.                 *pr++ = padparms[*ps++];
  7419.             }
  7420.         }
  7421.     } else {
  7422.         for (i = 1; i < MAXPADPARMS; i++) {
  7423.             *pr++ = i;
  7424.             *pr++ = padparms[i];
  7425.         }
  7426.     }
  7427. }
  7428.  
  7429. int
  7430. qbitpkt(s,n) CHAR *s; int n; {
  7431.     CHAR *ps = s;
  7432.     int x29cmd = *ps;
  7433.     CHAR *psa = s+1;
  7434.     CHAR x29resp[(MAXPADPARMS*2)+1];
  7435.  
  7436.     switch (x29cmd) {
  7437.  
  7438.         case X29_SET_PARMS:
  7439.             setpad (ps+1,n/2);
  7440.             if ((int)strlen((char *)x29err) > 2) {
  7441.                 ttol(x29err,(int)strlen((char *)x29err));
  7442.                 x29err[2] = '\0';
  7443.             }
  7444.             return (-2);
  7445.         case X29_READ_PARMS:
  7446.             readpad (ps+1,n/2,x29resp);
  7447.             setqbit ();
  7448.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7449.             if ((int)strlen((char *)x29err) > 2) {
  7450.                 ttol(x29err,(int)strlen((char *)x29err));
  7451.                 x29err[2] = '\0';
  7452.             }
  7453.             resetqbit();
  7454.             break;
  7455.         case X29_SET_AND_READ_PARMS:
  7456.             setpad (ps+1,n/2);
  7457.             readpad (ps+1,n/2,x29resp);
  7458.             setqbit();
  7459.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7460.             if ((int)strlen((char *)x29err) > 2) {
  7461.                 ttol (x29err,(int)strlen((char *)x29err));
  7462.                 x29err [2] = '\0';
  7463.             }
  7464.             resetqbit();
  7465.             return (-2);
  7466.         case X29_INVITATION_TO_CLEAR:
  7467.             (VOID) x25clear();
  7468.             return (-1);
  7469.         case X29_INDICATION_OF_BREAK:
  7470.             break;
  7471.     }
  7472.     return (0);
  7473. }
  7474.  
  7475. /* PAD break action processor */
  7476.  
  7477. VOID
  7478. breakact() {
  7479.     extern char x25obuf[MAXOX25];
  7480.     extern int obufl;
  7481.     extern int active;
  7482.     extern unsigned char tosend;
  7483.     static CHAR indbrk[3] = {
  7484.         X29_INDICATION_OF_BREAK,
  7485.         PAD_SUPPRESSION_OF_DATA,
  7486.         1
  7487.     };
  7488.     CHAR intudat, cause, diag;
  7489.  
  7490.     if (x25stat() < 0) return;  /* Ignore if no virtual call established */
  7491.  
  7492.     if (padparms[PAD_BREAK_ACTION] != 0) /* Forward condition */
  7493.         if (ttol((CHAR *)x25obuf,obufl) < 0) {
  7494.             perror ("\r\nCan't send characters");
  7495.             active = 0;
  7496.         } else {
  7497.             bzero (x25obuf,sizeof(x25obuf));
  7498.             obufl = 0;
  7499.             tosend = 0;
  7500.         };
  7501.  
  7502.     switch (padparms[PAD_BREAK_ACTION]) {
  7503.  
  7504.        case 0 : break;                  /* do nothing */
  7505.        case 1 : /* send interrupt packet with interrupt user data field = 1 */
  7506.                 intudat = 1;
  7507.                 x25intr (intudat);
  7508.                 break;
  7509.        case 2 : /* send reset packet with cause and diag = 0 */
  7510.                 cause = diag = 0;
  7511.                 x25reset (cause,diag);
  7512.                 break;
  7513.        case 5 : /* send interrupt packet with interrupt user data field = 0 */
  7514.                 intudat = 0;
  7515.                 x25intr (intudat);
  7516.                 setqbit ();
  7517.                 /* send indication of break without a parameter field */
  7518.                 ttoc(X29_INDICATION_OF_BREAK);
  7519.                 resetqbit ();
  7520.                 break;
  7521.        case 8 : active = 0;             /* leave data transfer */
  7522.                 conol ("\r\n");
  7523.                 break;
  7524.        case 21: /* send interrupt packet with interrupt user data field = 0 */
  7525.                 intudat = 0;
  7526.                 x25intr (intudat);
  7527.                 setpad (indbrk+1,2);    /* set pad to discard input */
  7528.                 setqbit ();
  7529.                 /* send indication of break with parameter field */
  7530.                 ttol (indbrk,sizeof(indbrk));
  7531.                 resetqbit ();
  7532.                 break;
  7533.      }
  7534. }
  7535.  
  7536. /* X.25 support functions */
  7537.  
  7538. X25_CAUSE_DIAG diag;
  7539.  
  7540. /*
  7541.   Convert a null-terminated string representing an X.121 address
  7542.   to a packed BCD form.
  7543. */
  7544. int
  7545. pkx121(str,bcd) char *str; CHAR *bcd; {
  7546.     int i, j;
  7547.     u_char c;
  7548.  
  7549.     i = j = 0;
  7550.     while (str[i]) {
  7551.         if (i >= 15 || str [i] < '0' || str [i] > '9')
  7552.           return (-1);
  7553.         c = str [i] - '0';
  7554.         if (i & 1)
  7555.           bcd [j++] |= c;
  7556.         else
  7557.           bcd [j] = c << 4;
  7558.         i++;
  7559.     }
  7560.     return (i);
  7561. }
  7562.  
  7563. /* Reads and prints X.25 diagnostic */
  7564.  
  7565. int
  7566. x25diag () {
  7567.     int i;
  7568.  
  7569.     bzero ((char *)&diag,sizeof(diag));
  7570.     if (ioctl(ttyfd,X25_RD_CAUSE_DIAG,&diag)) {
  7571.         perror ("Reading X.25 diagnostic");
  7572.         return(-1);
  7573.     }
  7574.     if (diag.datalen > 0) {
  7575.         printf ("X.25 Diagnostic :");
  7576.         for (i = 0; i < (int)diag.datalen; i++)
  7577.           printf(" %02h",diag.data[i])+
  7578.         printf ("\r\n");
  7579.     }
  7580.     return(0);
  7581. }
  7582.  
  7583. /* X.25 Out-of-Band Signal Handler */
  7584.  
  7585. SIGTYP
  7586. x25oobh(foo) int foo; {
  7587.     int oobtype;
  7588.     u_char oobdata;
  7589.     int t;
  7590.  
  7591.     (VOID) signal(SIGURG,x25oobh);
  7592.     do {
  7593.         if (ioctl(ttyfd,X25_OOB_TYPE,&oobtype)) {
  7594.             perror ("Getting signal type");
  7595.             return;
  7596.         }
  7597.         switch (oobtype) {
  7598.           case INT_DATA:
  7599.             if (recv(ttyfd,(char *)&oobdata,1,MSG_OOB) < 0) {
  7600.                 perror ("Receiving X.25 interrupt data");
  7601.                 return;
  7602.             }
  7603.             t = oobdata;
  7604.             printf ("\r\nInterrupt received, data = %d\r\n", t);
  7605.             break;
  7606.           case VC_RESET:
  7607.             printf ("\r\nVirtual circuit reset\r\n");
  7608.             x25diag ();
  7609.             break;
  7610.           case N_RESETS:
  7611.             printf ("\r\nReset timeout\r\n");
  7612.             break;
  7613.           case N_CLEARS:
  7614.             printf ("\r\nClear timeout\r\n");
  7615.             break;
  7616.           case MSG_TOO_LONG:
  7617.             printf ("\r\nMessage discarded, too long\r\n");
  7618.             break;
  7619.           default:
  7620.             if (oobtype) printf("\r\nUnknown oob type %d\r\n",oobtype);
  7621.             break;
  7622.         }
  7623.     } while (oobtype);
  7624. }
  7625.  
  7626. /* Send a X.25 interrupt packet */
  7627.  
  7628. int
  7629. #ifdef CK_ANSIC
  7630. x25intr(char intr)
  7631. #else
  7632. x25intr(intr) char intr;
  7633. #endif /* CK_ANSIC */
  7634. /* x25intr */ {
  7635.     if (send(ttyfd,&intr,1,MSG_OOB) < 0) return(-1);
  7636.     debug(F100,"X.25 intr","",0);
  7637.     return(0);
  7638. }
  7639.  
  7640. /* Reset X.25 virtual circuit */
  7641. int
  7642. #ifdef CK_ANSIC
  7643. x25reset(char cause, char diagn)
  7644. #else
  7645. x25reset(cause, diagn) char cause; char diagn;
  7646. #endif /* CK_ANSIC */
  7647. /* x25reset */ {
  7648.     bzero ((char *)&diag,sizeof(diag));
  7649.     diag.flags   = 0;
  7650.     diag.datalen = 2;
  7651.     diag.data[0] = cause;
  7652.     diag.data[1] = diagn;
  7653.     if (ioctl(ttyfd,X25_WR_CAUSE_DIAG,&diag) < 0)
  7654.       return(-1);
  7655.     debug(F100,"X.25 reset","",0);
  7656.     return(0);
  7657. }
  7658.  
  7659. /* Clear X.25 virtual circuit */
  7660. int
  7661. x25clear() {
  7662.     int i;
  7663.     debug(F100,"X.25 clear","",0);
  7664.     bzero ((char *)&diag,sizeof(diag));
  7665.     diag.flags = (1 << DIAG_TYPE);
  7666.     diag.datalen = 2;
  7667.     diag.data[0] = 0;
  7668.     diag.data[1] = 0;
  7669.     ioctl (ttyfd,X25_WR_CAUSE_DIAG,&diag); /* Send Clear Request */
  7670.     return(ttclos(0));                  /* Close socket */
  7671. }
  7672.  
  7673. /* X.25 status */
  7674. int
  7675. x25stat() {
  7676.     if (ttyfd == -1) return (-1);
  7677.     return(0);
  7678. }
  7679.  
  7680. /* Set Q_BIT on */
  7681. VOID
  7682. setqbit() {
  7683.     static int qbiton = 1 << Q_BIT;
  7684.     ioctl (ttyfd,X25_SEND_TYPE,&qbiton);
  7685. }
  7686.  
  7687. /* Set Q_BIT off */
  7688. VOID
  7689. resetqbit() {
  7690.     static int qbitoff = 0;
  7691.     ioctl (ttyfd,X25_SEND_TYPE,&qbitoff);
  7692. }
  7693.  
  7694. /* Read n characters from X.25 circuit into buf */
  7695.  
  7696. int
  7697. x25xin(n,buf) int n; CHAR *buf; {
  7698.     register int x, c;
  7699.     int qpkt;
  7700.  
  7701.     do {
  7702.         x = read(ttyfd,buf,n);
  7703.         if (buf[0] & (1 << Q_BIT)) { /* If Q_BIT packet, process it */
  7704.             /* If return -1 : invitation to clear; -2 : PAD changes */
  7705.             if ((c=qbitpkt(buf+1,x-2)) < 0) return(c);
  7706.             qpkt = 1;
  7707.         } else qpkt = 0;
  7708.     } while (qpkt);
  7709.  
  7710. #ifdef COMMENT                  /* Disabled by Stephen Riehm 19.12.97 */
  7711.     /* BUG!
  7712.      * if buf[] is full, then this null lands in nirvana!
  7713.      * I was unable to find any code which needs a trailing null in buf[]
  7714.      */
  7715.     if (x > 0) buf[x] = '\0';
  7716. #endif /* COMMENT */
  7717.     if (x < 1) x = -1;
  7718.     debug(F101,"x25xin x","",x);
  7719.  
  7720.     return(x);
  7721. }
  7722.  
  7723. #ifdef COMMENT /* NO LONGER NEEDED! */
  7724. /* X.25 read a line */
  7725.  
  7726. int
  7727. #ifdef PARSENSE
  7728. #ifdef CK_ANSIC
  7729. x25inl(CHAR *dest, int max,int timo, CHAR eol, CHAR start)
  7730. #else
  7731. x25inl(dest,max,timo,eol,start) int max,timo; CHAR *dest, eol, start;
  7732. #endif /* CK_ANSIC */
  7733. #else /* not PARSENSE */
  7734. #ifdef CK_ANSIC
  7735. x25inl(CHAR *dest, int max,int timo, CHAR eol)
  7736. #else
  7737. x25inl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  7738. #endif /* __SDTC__ */
  7739. #endif /*PARSENSE */
  7740.  /* x25inl */ {
  7741.     CHAR *pdest;
  7742.     int pktype, goteol, rest, n;
  7743.     int i, flag = 0;
  7744.     extern int ttprty, ttpflg;
  7745.     int ttpmsk;
  7746.  
  7747.     ttpmsk = (ttprty) ? 0177 : 0377;    /* Set parity stripping mask */
  7748.  
  7749.     debug(F101,"x25inl max","",max);
  7750.     debug(F101,"x25inl eol","",eol);
  7751.     pdest  = dest;
  7752.     rest   = max;
  7753.     goteol = 0;
  7754.     do {
  7755.         n = read(ttyfd,pdest,rest);
  7756.         n--;
  7757.         pktype = *pdest & 0x7f;
  7758.         switch (pktype) {
  7759.           case 1 << Q_BIT:
  7760.             if (qbitpkt(pdest+1,--n) < 0) return(-2);
  7761.             break;
  7762.           default:
  7763.             if (flag == 0) { /* if not in packet, search start */
  7764.                 for (i = 1; (i < n) &&
  7765.                      !(flag = ((dest[i] & 0x7f) == start));
  7766.                      i++);
  7767.                 if (flag == 0) { /* not found, discard junk */
  7768.                     debug(F101,"x25inl skipping","",n);
  7769.                     continue;
  7770.                 } else {                /* found, discard junk before start */
  7771.                     int k;
  7772.                     n = n - i + 1;
  7773.                     for (k = 1; k <= n; k++, i++) dest[k] = dest[i];
  7774.                 }
  7775.             }
  7776.             for (i = 0; (i < n) && /* search for eol */
  7777.                  !(goteol=(((*pdest = *(pdest+1)&ttpmsk)&0x7f)== eol));
  7778.                  i++,pdest++);
  7779.             *pdest = '\0';
  7780.             rest -= n;
  7781.         }
  7782.     } while ((rest > 0) && (!goteol));
  7783.  
  7784.     if (goteol) {
  7785.         n = max - rest;
  7786.         debug (F111,"x25inl X.25 got",(char *) dest,n);
  7787.         if (timo) ttimoff();
  7788.         if (ttpflg++ == 0 && ttprty == 0) {
  7789.             if ((ttprty = parchk(dest,start,n)) > 0) {
  7790.                 int j;
  7791.                 debug(F101,"x25inl senses parity","",ttprty);
  7792.                 debug(F110,"x25inl packet before",(char *)dest,0);
  7793.                 ttpmsk = 0x7f;
  7794.                 for (j = 0; j < n; j++)
  7795.                   dest[j] &= 0x7f; /* Strip parity from packet */
  7796.                 debug(F110,"x25inl packet after ",dest,0);
  7797.             } else {
  7798.                 debug(F101,"parchk","",ttprty);
  7799.                 if (ttprty < 0) { ttprty = 0; n = -1; }
  7800.             }
  7801.         }
  7802.         ttimoff();
  7803.         return(n);
  7804.     }
  7805.     ttimoff();
  7806.     return(-1);
  7807. }
  7808. #endif /* COMMENT */
  7809. #endif /* SUNX25 */
  7810.  
  7811. #ifdef IBMX25
  7812. /*
  7813.  * IBM X25 support - using the NPI streams interface
  7814.  * written by Stephen Riehm, pc-plus, Munich Germany
  7815.  */
  7816.  
  7817. /* riehm: missing functions / TODO list */
  7818.  
  7819. /*
  7820.   x25intr() - Send an interrupt packet
  7821. */
  7822.  
  7823. /* return an error message depending on packet type */
  7824. char *
  7825. x25err(n) int n; {
  7826.     static char buf[30];
  7827.     switch (n) {
  7828.       case NBADADDR:     return "invalid address";
  7829.       case NBADOPT:      return "invalid options";
  7830.       case NACCESS:      return "no permission";
  7831.       case NNOADDR:      return "unable to allocate address";
  7832.       case NOUTSTATE:    return "invalid state";
  7833.       case NBADSEQ:      return "invalid sequence number";
  7834.       case NSYSERR:      return "system error";
  7835.       case NBADDATA:     return "invalid data size";
  7836.       case NBADFLAG:     return "invalid flag";
  7837.       case NNOTSUPPORT:  return "unsupported primitive";
  7838.       case NBOUND:       return "address in use";
  7839.       case NBADQOSPARAM: return "bad QOS parameters";
  7840.       case NBADQOSTYPE:  return "bad QOS type";
  7841.       case NBADTOKEN:    return "bad token value";
  7842.       case NNOPROTOID:   return "protocol id could not be allocated";
  7843.       case NODDCUD:      return "odd length call user data";
  7844.       default:
  7845.         ckmakmsg(buf,sizeof(buf),"Unknown NPI error ",ckitoa(n),NULL,NULL);
  7846.         return buf;
  7847.     }
  7848. }
  7849.  
  7850. /* turn a meaningless primitive number into a meaningful primitive name */
  7851. char *
  7852. x25prim(n) int n; {
  7853.     static char buf[30];
  7854.     switch(n) {
  7855.       case N_BIND_ACK:     return "N_BIND_ACK";
  7856.       case N_BIND_REQ:     return "N_BIND_REQ";
  7857.       case N_CONN_CON:     return "N_CONN_CON";
  7858.       case N_CONN_IND:     return "N_CONN_IND";
  7859.       case N_CONN_REQ:     return "N_CONN_REQ";
  7860.       case N_CONN_RES:     return "N_CONN_RES";
  7861.       case N_DATACK_IND:   return "N_DATAACK_IND";
  7862.       case N_DATACK_REQ:   return "N_DATAACK_REQ";
  7863.       case N_DATA_IND:     return "N_DATA_IND";
  7864.       case N_DATA_REQ:     return "N_DATA_REQ";
  7865.       case N_DISCON_IND:   return "N_DISCON_IND";
  7866.       case N_DISCON_REQ:   return "N_DISCON_REQ";
  7867.       case N_ERROR_ACK:    return "N_ERROR_ACK";
  7868.       case N_EXDATA_IND:   return "N_EXDATA_IND";
  7869.       case N_EXDATA_REQ:   return "N_EXDATA_REQ";
  7870.       case N_INFO_ACK:     return "N_INFO_ACK";
  7871.       case N_INFO_REQ:     return "N_INFO_REQ";
  7872.       case N_OK_ACK:       return "N_OK_ACK";
  7873.       case N_OPTMGMT_REQ:  return "N_OPTMGMT_REQ";
  7874.       case N_RESET_CON:    return "N_RESET_CON";
  7875.       case N_RESET_IND:    return "N_RESET_IND";
  7876.       case N_RESET_REQ:    return "N_RESET_REQ";
  7877.       case N_RESET_RES:    return "N_RESET_RES";
  7878.       case N_UDERROR_IND:  return "N_UDERROR_IND";
  7879.       case N_UNBIND_REQ:   return "N_UNBIND_REQ";
  7880.       case N_UNITDATA_REQ: return "N_UNITDATA_REQ";
  7881.       case N_UNITDATA_IND: return "N_UNITDATA_IND";
  7882.       default:
  7883.         ckmakmsg(buf,sizeof(buf),"UNKNOWN (",ckitoa(n),")",NULL);
  7884.         return buf;
  7885.     }
  7886. }
  7887.  
  7888. /*****************************************************************************
  7889.  * Function: x25getmsg()
  7890.  * Description: get a STREAMS message, and check it for errors
  7891.  *
  7892.  * Parameters:
  7893.  * fd           - file descriptor to x25 device (opened)
  7894.  * control      - control buffer (pre-allocated)
  7895.  * ctl_size     - size of control buffer
  7896.  * data         - data buffer (pre-allocated)
  7897.  * data_size    - size of data buffer
  7898.  * flags        - flags for getmsg()
  7899.  * expected     - expected Primitive type
  7900.  *
  7901.  * Return Value:
  7902.  *      >= 0    OK (size of data returned)
  7903.  *      -1      error
  7904.  *
  7905.  */
  7906. int
  7907. x25getmsg( fd, control, ctl_size, data, data_size, get_flags, expected )
  7908.     int                 fd;             /* X25 device (opened) */
  7909.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  7910.     int                 ctl_size;       /* size of control buffer */
  7911.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  7912.     int                 data_size;      /* size of data buffer */
  7913.     int                 *get_flags;     /* getmsg() flags */
  7914.     int                 expected;       /* expected primitive type */
  7915. /* x25getmsg */ {
  7916.     int                 rc = 0;         /* return code */
  7917.     struct strbuf       *get_ctl=NULL;  /* getmsg control */
  7918.     struct strbuf       *get_data=NULL; /* getmsg data */
  7919.     int                 more = 0;       /* flag for more data etc */
  7920.     int                 file_status = -1; /* file async status */
  7921.     N_npi_ctl_t         * result;       /* pointer to simplify switch() */
  7922.     int                 packet_type = -1; /* unknown packet thus far */
  7923.  
  7924. #ifdef TRACE
  7925.     printf( "TRACE: entering x25getmsg\n" );
  7926. #endif /* TRACE */
  7927.  
  7928.     debug( F110, "x25getmsg waiting for packet ", x25prim( expected ), 0);
  7929.     /* prepare the control structures for getmsg */
  7930.     if (control) {
  7931.         if ((get_ctl = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7932.           {
  7933.               perror("kermit x25getmsg(): get_ctl malloc failed\n");
  7934.               debug( F100, "x25getmsg malloc failed for get_ctl\n", "", 0);
  7935.               return(-1);
  7936.           }
  7937.         /* allow getmsg to return an unexpected packet type (which may be
  7938.          * larger than the expected one)
  7939.          */
  7940.         get_ctl->maxlen = NPI_MAX_CTL;
  7941.         get_ctl->len = 0;
  7942.         get_ctl->buf = (char *)control;
  7943.     } else {
  7944.         printf(
  7945.  "kermit x25getmsg(): internal error. control buffer MUST be pre-allocated!\n"
  7946.                );
  7947.         debug(F100,"x25getmsg internal error. no buffer pre-allocated","",0);
  7948.         return( -1 );
  7949.     }
  7950.     if (data) {
  7951.         if ((get_data = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7952.           {
  7953.             perror("kermit x25getmsg(): get_data malloc failed\n");
  7954.             debug( F100, "x25getmsg malloc failed for get_data\n", "", 0);
  7955.             return(-1);
  7956.         }
  7957.         get_data->maxlen = (NPI_MAX_DATA < data_size ) ?
  7958.           NPI_MAX_DATA :
  7959.             data_size;
  7960.         get_data->len = 0;
  7961.         get_data->buf = (char *)data;
  7962.     }
  7963.  
  7964.     /* get an X.25 packet -
  7965.      * it may be any kind of packet, so check for special cases
  7966.      * it may be split into multiple parts - so loop if necessary
  7967.      */
  7968.     do {
  7969. #ifdef DEBUG
  7970.         printf( "kermit: x25getmsg(): getting a message\n" );
  7971. #endif /* DEBUG */
  7972.         errno = 0;
  7973.         if ((more = getmsg(fd, get_ctl, get_data, get_flags)) < 0) {
  7974. #ifdef DEBUG
  7975.             printf( "kermit: x25getmsg(): getmsg returned an error\n" );
  7976.             perror( "getmsg error was" );
  7977. #endif /* DEBUG */
  7978.             debug(F101, "x25getmsg getmsg returned an error\n", "", errno);
  7979.             if ((errno == EAGAIN) && (get_data && (get_data->len > 0)) ) {
  7980.                 /* was in non-blocking mode, nothing to get, but we're
  7981.                  * already waiting for the rest of the packet -
  7982.                  * switch to blocking mode for the next read.
  7983.                  * file_status used to reset file status before returning
  7984.                  */
  7985.                 if ((file_status = fcntl(fd, F_GETFL, 0)) < 0
  7986.                     || fcntl(fd, F_SETFL, file_status & ~O_NDELAY) < 0)
  7987.                   {
  7988.                       perror("x25getmsg(): couldn't change x25 blocking mode");
  7989.                       debug(F101,
  7990.                             "x25getmsg fcntl returned an error\n", "", errno);
  7991.                       /* netclos(); */
  7992.                       rc = -1;
  7993.                       break;
  7994.                   } else {
  7995.                       /* loop again into a blocking getmsg() */
  7996.                       continue;
  7997.                   }
  7998.             } else {
  7999.                 /* no data to get in non-blocking mode - return empty handed */
  8000.                 perror( "x25getmsg(): getmsg failed" );
  8001.                 debug(F101,"x25getmsg getmsg returned an error\n", "", errno);
  8002.                 rc = -1;
  8003.                 break;
  8004.             }
  8005.         } else if (more & MORECTL) {
  8006.             /* panic - the control information was larger than the
  8007.              * maximum control buffer size!
  8008.              */
  8009.             /* riehm: close connection? */
  8010. #ifdef DEBUG
  8011.             printf("x25getmsg(): received partial control packet - panic\n");
  8012. #endif /* DEBUG */
  8013.             debug( F101, "x25getmsg getmsg bad control block\n", "", errno);
  8014.             rc = -1;
  8015.             break;
  8016.         }
  8017.  
  8018.         if (result = (N_npi_ctl_t *)control) {
  8019.             packet_type = result->bind_ack.PRIM_type;
  8020.             if (packet_type != N_OK_ACK) {
  8021.                 x25lastmsg = packet_type;
  8022.             }
  8023.         }
  8024. #ifdef DEBUG
  8025.         /* printf( "kermit: x25getmsg(): getting " ); */
  8026.         if (get_ctl->len > 0) {
  8027.             x25dump_prim(result);
  8028.         }
  8029.         debug(F110,
  8030.               "x25getmsg got packet ",
  8031.               x25prim( result->bind_ack.PRIM_type ),
  8032.               0
  8033.               );
  8034. #endif /* DEBUG */
  8035.  
  8036.         if (get_ctl->len >= (int)sizeof(result->bind_ack.PRIM_type)) {
  8037.             /* not as pretty as a switch(), but switch can't handle
  8038.              * runtime variable values :-(
  8039.              */
  8040.             if (packet_type == expected ) {
  8041.                 /* got what we wanted, special case for DATA_IND
  8042.                  * packets though */
  8043.                 /* riehm: check Q-bit ? */
  8044. #ifdef DEBUG
  8045.                 printf("x25getmsg(): got expected packet\nrc is %d\n", rc);
  8046. #endif /* DEBUG */
  8047.                 if (packet_type == N_DATA_IND ) {
  8048.                     /* data received. May be incomplete, even though
  8049.                      * getmsg returned OK
  8050.                      */
  8051.                     if (result->data_ind.DATA_xfer_flags & N_MORE_DATA_FLAG)
  8052.                         more |= MOREDATA;
  8053.                     if (result->data_ind.DATA_xfer_flags & N_RC_FLAG)
  8054.                         printf( "x25getmsg(): data packet wants ack\n" );
  8055.                 }
  8056.             } else if( packet_type == N_DISCON_IND) {
  8057.                 printf( "X25 diconnected\n" );
  8058.                 /* riehm: need to acknowledge a disconnection? */
  8059.                 x25clear();
  8060.                 /* x25unbind( ttyfd ); */
  8061.                 rc = -1;
  8062.             } else if( packet_type == N_ERROR_ACK) {
  8063.                 errno = result->error_ack.UNIX_error;
  8064.                 perror( "X25 error received" );
  8065.                 rc = -1;
  8066.             } else {
  8067.                 printf("x25getmsg(): failed %s\n", x25err(packet_type));
  8068.                 rc = -1;
  8069.             }
  8070.         }
  8071. #ifdef COMMENT
  8072.         else {
  8073.             /* Panic - no control data */
  8074.             printf( "kermit: x25getmsg(): no control data with packet\n" );
  8075.             rc = -1;
  8076.         }
  8077. #endif /* COMMENT */
  8078.  
  8079.         if (get_data && (get_data->len >= 0)) {
  8080.             get_data->buf += get_data->len;
  8081.             get_data->maxlen -= get_data->len;
  8082.         }
  8083.     } while ((rc == 0)
  8084.              && (get_data && (get_data->maxlen > 0))
  8085.              && (more & MOREDATA)
  8086.              );
  8087.  
  8088.     /* return the file status to its original value, unless its still
  8089.      * set to -1, or one of the fcntl's failed */
  8090.     if ((file_status >= 0) && fcntl(fd, F_SETFL, file_status) < 0)
  8091.         rc = -1;
  8092.  
  8093.     /*
  8094.      * Verify that we received an expected primitive
  8095.      * there is apparantly an error case where the primitive is set
  8096.      * correctly, but there is not enough data in the control structure
  8097.      */
  8098.     if ((packet_type != expected) && (get_ctl->len >= ctl_size) ) {
  8099.         fprintf(stderr,
  8100.                 "x25getmsg(): %s NOT received. Primitive received was %s\n",
  8101.                 x25prim( expected ), x25prim( packet_type ));
  8102.         debug(F110, "x25getmsg got an unexpected packet ",
  8103.               x25prim(packet_type),
  8104.               0
  8105.               );
  8106.         rc = -1;
  8107.     }
  8108.  
  8109.     if (rc == 0) {
  8110.         if (get_data && ( get_data->len >= 0)) {
  8111.             rc = get_data->len;
  8112.         }
  8113.     }
  8114.  
  8115.     if (get_ctl)  { free(get_ctl); get_ctl = NULL; }
  8116.     if (get_data) { free(get_data); get_data = NULL; }
  8117.  
  8118. #ifdef COMMENT
  8119. #ifdef DEBUG
  8120.     printf( "kermit x25getmsg(): returning %d\n", rc );
  8121. #endif /* DEBUG */
  8122. #endif /* COMMENT */
  8123.     debug(F110, "x25getmsg returning packet ", x25prim( packet_type ), 0);
  8124.  
  8125. #ifdef TRACE
  8126.     printf( "TRACE: leaving x25getmsg\n" );
  8127. #endif /* TRACE */
  8128.     return(rc);
  8129. }
  8130.  
  8131. /*****************************************************************************
  8132.  * Function: x25putmsg()
  8133.  *
  8134.  * Description:
  8135.  *      send a message to a X25 STREAM
  8136.  *
  8137.  * Parameters:
  8138.  *      fd              - file descriptor to x25 device (opened)
  8139.  *      control         - control buffer (pre-allocated)
  8140.  *      data            - data buffer (pre-allocated)
  8141.  *      data_len        - length of data to be transmitted
  8142.  *      put_flags       - flags for putmsg()
  8143.  *
  8144.  * Return Value:
  8145.  *      >= 0    number of bytes transmitted
  8146.  *      -1      error
  8147.  */
  8148. int
  8149. x25putmsg(fd, control, data, data_len, put_flags)
  8150.     int                 fd;             /* X25 device (opened) */
  8151.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  8152.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  8153.     int                 data_len;       /* length of data (not the size of
  8154.                                            the buffer) */
  8155.     int                 *put_flags;     /* putmsg() flags */
  8156. /* x25putmsg */ {
  8157.     int                 rc = 0;         /* return code */
  8158.     ulong               type;           /* primitive type */
  8159.     struct strbuf       *put_ctl = NULL; /* putmsg control */
  8160.     struct strbuf       *put_data = NULL; /* putmsg data */
  8161.  
  8162. #ifdef TRACE
  8163.     printf( "TRACE: entering x25putmsg\n" );
  8164. #endif /* TRACE */
  8165.  
  8166. #ifdef DEBUG
  8167.     printf( "kermit: x25putmsg(): putting " );
  8168.     x25dump_prim( control );
  8169.     printf( "\tdata:\t\t" );
  8170.     x25dump_data( data, 0, data_len );
  8171.     debug(F110,"x25putmsg: putting packet ",x25prim(control->PRIM_type),0);
  8172. #endif /* DEBUG */
  8173.  
  8174.     if (control) {
  8175.         put_ctl = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  8176.         if (put_ctl == NULL) {
  8177.             perror("kermit x25putmsg(): put_ctl malloc failed\n");
  8178.             return(-1);
  8179.         }
  8180.         put_ctl->maxlen = 0;                    /* unused by putmsg */
  8181.         put_ctl->len = NPI_MAX_CTL;
  8182.         put_ctl->buf = (char *)control;
  8183.     }
  8184.     if (data && ( data_len > 0)) {
  8185.         put_data = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  8186.         if( put_data == NULL) {
  8187.             perror("kermit x25putmsg(): put_data malloc failed\n");
  8188.             return(-1);
  8189.         }
  8190.         put_data->maxlen = 0;                   /* unused by putmsg */
  8191.         put_data->len = data_len;
  8192.         put_data->buf = (char *)data;
  8193.     }
  8194.  
  8195.     errno = 0;
  8196.     rc = putmsg (fd, put_ctl, put_data, 0);
  8197.     if (rc < 0) {
  8198.         printf("x25putmsg(): couldn't put %s\n",x25prim(control->PRIM_type));
  8199.         perror("kermit: x25putmsg(): putmsg failed");
  8200.         return(-1);
  8201.     }
  8202.  
  8203.     /* riehm: this should perhaps be discounted! */
  8204.     x25lastmsg = control->PRIM_type;
  8205.  
  8206. #ifdef COMMENT
  8207. #ifdef DEBUG
  8208.     printf( "kermit debug: x25putmsg() returning %d\n", data_len );
  8209. #endif /* DEBUG */
  8210. #endif /* COMMENT */
  8211.     debug( F101, "x25putmsg block size put ", "", data_len);
  8212.  
  8213. #ifdef TRACE
  8214.     printf( "TRACE: leaving x25putmsg\n" );
  8215. #endif /* TRACE */
  8216.  
  8217.     return( data_len );
  8218. }
  8219.  
  8220. /*****************************************************************************
  8221. * Function: x25bind
  8222. * Description:  The bind submitted to NPI provides the information required
  8223. *               by the packet layer for it to listen for suitable incoming
  8224. *               calls.
  8225. *
  8226. * WARNING:
  8227. *
  8228. * This routine needs to be called in a completely different manner for
  8229. * the client and server side. When starting a client, the
  8230. * num_waiting_calls and CUD information should all be set to 0! The
  8231. * client's CUD must be inserted in the CONN_REQ data block.
  8232. * When starting a server, the CUD must be set to a CUD pattern, and
  8233. * the number of waiting calls should be set to a number other than 0.
  8234. * (num waiting calls is the number of incomming calls which are to be
  8235. * put on hold while the server is servicing another client.)
  8236. *
  8237. * Who invented this crap?
  8238. *
  8239. * Parameters:
  8240. *       fd              - X25 device (opened)
  8241. *       addr            - local address
  8242. *       cud             - User Data (null terminated)
  8243. *       cud_len         - User Data length
  8244. *       num_waiting_calls - number of outstanding calls allowed on this stream
  8245. *       line            - logical port number (1)
  8246. *       flags           - 0, DEFAULT_LISTENER or TOKEN_REQUEST
  8247. *
  8248. * Return Value:
  8249. *       if binding is successful, 0 is returned for a client, and a token is
  8250. *       returned for a server
  8251. *
  8252. * Return code: 0 if successful
  8253. *              -1 if unsuccessful
  8254. *****************************************************************************/
  8255.  
  8256. ulong
  8257. x25bind(fd, addr, cud, cud_len, num_waiting_calls, line, bind_flags)
  8258.     int fd;                             /* X25 device (opened) */
  8259.     char * addr;                        /* local address */
  8260.     char * cud;                         /* Call User Data (null terminated) */
  8261.     int cud_len;                        /* User Data length */
  8262.     int num_waiting_calls;              /* Outstanding calls allowed */
  8263.     int line;                           /* logical port number */
  8264.     ulong bind_flags;           /* 0, DEFAULT_LISTENER or TOKEN_REQUEST */
  8265. /* x25bind */ {
  8266.     ulong rc;                           /* return code */
  8267.     int get_flags;                      /* priority flag passed to getmsg */
  8268.     int put_flags = 0;                  /* output flags for putmsg, always 0 */
  8269.     ulong type;                         /* primitive type */
  8270.     N_bind_req_t *bind_req;             /* pointer to N_BIND_REQ primitive */
  8271.     N_bind_ack_t *bind_ack;             /* pointer to N_BIND_ACK primitive */
  8272.     char *addtl_info;                   /* pointer to info in addition to
  8273.                                          * the N_BIND_REQ primitive that is
  8274.                                          * passed in the control structure
  8275.                                          * to putmsg */
  8276.     int addr_len = 0;                   /* length of address string */
  8277.     ulong bind_req_t_size;              /* for debugging only */
  8278.  
  8279. #ifdef TRACE
  8280.     printf("TRACE: entering x25bind\n" );
  8281. #endif /* TRACE */
  8282.  
  8283. #ifdef DEBUG
  8284.     printf("TRACE: x25bind( %d, %s, %s, %d, %d )\n",
  8285.            fd, addr, cud, line, bind_flags
  8286.            );
  8287. #endif /* DEBUG */
  8288.  
  8289.     /*
  8290.      * Allocate  and zero out space to hold the control portion of the
  8291.      * message passed to putmsg. This will contain the N_BIND_REQ
  8292.      * primitive and any additional info required for that.
  8293.      *
  8294.      * Note: allocated space is the size of the union typedef
  8295.      * N_npi_ctl_t to allow the use fo the generic x25putmsg routine.
  8296.      */
  8297.     bind_req = (N_bind_req_t *) malloc(sizeof( N_npi_ctl_t));
  8298.     if (bind_req == NULL) {
  8299.         perror("kermit: x25bind(): bind_req malloc failed");
  8300.         debug(F100, "x25bind bind_req malloc failed", "", 0);
  8301.         return(-1);
  8302.     }
  8303.     bzero((char *)bind_req, sizeof(N_npi_ctl_t));
  8304.  
  8305.     /* Build the Bind Request Primitive */
  8306.     bind_req->PRIM_type = (ulong) N_BIND_REQ;
  8307.  
  8308.     /* Note that the address length is n+2 and NOT n. Two bytes MUST preceed
  8309.      * the actual address in an N_BIND_REQ. The first byte contains the
  8310.      * line number being used with this address, and the second byte is the
  8311.      * X.121 address prefix, which must be zero.
  8312.      */
  8313.     addr_len = strlen(addr);
  8314.     bind_req->ADDR_length = (ulong) (addr_len + 2);
  8315.     bind_req->ADDR_offset = (ulong)(sizeof(N_bind_req_t));
  8316.     bind_req->CONIND_number = (ulong)num_waiting_calls; /* server only */
  8317.     bind_req->BIND_flags = (ulong) bind_flags; /* 0 in client */
  8318.     bind_req->PROTOID_length = (ulong) cud_len; /* 0 in client */
  8319.     if (cud_len == 0) {
  8320.         bind_req->PROTOID_offset = (ulong) 0;
  8321.     } else {
  8322.         /* need to remember the trailing NULL in the address - not
  8323.          * counted in the address length
  8324.          */
  8325.         bind_req->PROTOID_offset
  8326.           = (ulong) (sizeof(N_bind_req_t) + bind_req->ADDR_length);
  8327.     }
  8328.  
  8329.     /*
  8330.      * Now fill in the additional information required with this primitive
  8331.      * (address and protocol information (Call User Data))
  8332.      */
  8333.     addtl_info = (char *) ((void *)bind_req + bind_req->ADDR_offset);
  8334.     /*
  8335.      * The bitwise "&" ensures that the line number is only one byte long
  8336.      */
  8337.     *addtl_info++ = (char) line & 0xff;
  8338.     *addtl_info++ = (char) 0; /* X.121 format */
  8339.     bcopy( addr, addtl_info, addr_len ); /* include trailing null */
  8340.     addtl_info += addr_len;
  8341.     if (cud_len > 0)
  8342.       bcopy( cud, addtl_info, cud_len );
  8343.     /*
  8344.      * Call putmsg() to put the bind request message on the stream
  8345.      */
  8346.     if (x25putmsg(fd,
  8347.                   (N_npi_ctl_t*)bind_req,
  8348.                   (N_npi_data_t *)NULL,
  8349.                   0,
  8350.                   &put_flags
  8351.                   ) < 0) {
  8352.         printf( "kermit: x25bind(): x25putmsg failed\n" );
  8353.         return(-1);
  8354.     }
  8355.  
  8356.     /*
  8357.      * Allocate and zero out space for the N_BIND_ACK primitive
  8358.      */
  8359.     bind_ack = (N_bind_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8360.     if (bind_ack == NULL){
  8361.         perror("kermit: x25bind(): bind_ack malloc failed");
  8362.         return(-1);
  8363.     }
  8364.     bzero(bind_ack, sizeof(N_npi_ctl_t));
  8365.     /*
  8366.      * Initialize the control structure and flag variable sent to getmsg
  8367.      */
  8368.     get_flags=0;
  8369.  
  8370.     /* get the ACK for the bind */
  8371. #ifdef DEBUG
  8372.     printf( "kermit: x25bind() trying to get a BIND_ACK\n" );
  8373. #endif /* DEBUG */
  8374.     rc = (ulong)x25getmsg( fd, (N_npi_ctl_t*)bind_ack,
  8375.             (int)sizeof( N_bind_ack_t ), (N_npi_data_t*)NULL, 0, &get_flags,
  8376.             N_BIND_ACK );
  8377.  
  8378.     /* turn quantitive return code into a qualitative one */
  8379.     if (rc > 0) rc = 0;
  8380.  
  8381.     /* if all went well, get the token from the acknowledgement packet */
  8382.     if ((bind_flags & TOKEN_REQUEST ) && ( rc >= 0)) {
  8383.         rc = bind_ack->TOKEN_value;
  8384.     }
  8385.  
  8386.     /* free up the memory we allocated earlier */
  8387.     free(bind_req);
  8388.     free(bind_ack);
  8389.  
  8390. #ifdef TRACE
  8391.     printf( "TRACE: leaving x25bind\n" );
  8392. #endif /* TRACE */
  8393.  
  8394.     return( rc );
  8395. }
  8396.  
  8397. /*****************************************************************************
  8398. * Function: x25call
  8399. * Description:  This routine builds and sends an N_CONN_REQ primitive, then
  8400. *               checks for an N_CONN_CON primitive in return.
  8401. *
  8402. * Parameters:
  8403. * fd    - file descriptor of stream
  8404. * caddr - called address (remote address)
  8405. *
  8406. * Functions Referenced:
  8407. * malloc()
  8408. * bzero()
  8409. * getmsg()
  8410. * putmsg()
  8411. *
  8412. * Return code:
  8413. * 0 - if successful
  8414. * -1 if not successful
  8415. *****************************************************************************/
  8416. int
  8417. x25call(fd, remote_nua, cud)
  8418.     int fd;                             /* X25 device (opened) */
  8419.     char * remote_nua;                  /* remote address to call */
  8420.     char * cud;                         /* call user data */
  8421. /* x25call */ {
  8422.     int rc;                             /* return code */
  8423.     int flags;                          /* Connection flags */
  8424.     int get_flags;                      /* priority flags for getmsg */
  8425.     ulong type;                         /* primitive type */
  8426.     N_conn_req_t *connreq_ctl;          /* pointer to N_CONN_REQ primitive */
  8427.     N_npi_data_t *connreq_data;         /* pointer to N_CONN_REQ data (CUD) */
  8428.     int connreq_data_len;               /* length of filled data buffer */
  8429.     N_conn_con_t *conncon_ctl;          /* pointer to N_CONN_CON primitive */
  8430.     N_npi_data_t *conncon_data;         /* pointer to any data associated with
  8431.                                          * the N_CONN_CON primitive */
  8432.     char *addtl_info;                   /* pointer to additional info needed
  8433.                                          * for N_CONN_REQ primitive */
  8434.     int addr_len;                       /* length of address */
  8435.  
  8436. #ifdef TRACE
  8437.     printf( "TRACE: entering x25call\n" );
  8438. #endif /* TRACE */
  8439.  
  8440. #ifdef DEBUG
  8441.     printf( "x25call( %d, %s )\n", fd, remote_nua );
  8442.     printf( "connecting to %s on fd %d\n", remote_nua, fd );
  8443. #endif /* DEBUG */
  8444.  
  8445.     /*
  8446.      * Allocate and zero out space for the N_CONN_REQ primitive
  8447.      * use the size of the generic NPI primitive control buffer
  8448.      */
  8449.     connreq_ctl  = (N_conn_req_t *) malloc(sizeof(N_npi_ctl_t));
  8450.     if (connreq_ctl == NULL){
  8451.         perror("kermit: x25call(): connreq_ctl malloc failed");
  8452.         return(-1);
  8453.     }
  8454.     bzero(connreq_ctl,sizeof(N_npi_ctl_t));
  8455.     /*
  8456.      * Build the Connection Request Primitive
  8457.      */
  8458.     flags = 0;
  8459.     connreq_ctl->PRIM_type = (ulong) N_CONN_REQ;
  8460.  
  8461.     /* Note that the address length is nchai+1 and not n+2. The line number
  8462.      * is only passed with the address for the bind. The first byte of
  8463.      * the address for the N_CONN primitives contains the X.121
  8464.      * address prefix, which must be zero. The remaining bytes are the
  8465.      * address itself.
  8466.      */
  8467.     addr_len = strlen( remote_nua );
  8468.     connreq_ctl->DEST_length = (ulong) (addr_len + 1);
  8469.     connreq_ctl->DEST_offset = (ulong) sizeof(N_conn_req_t);
  8470.     /* connreq_ctl->CONN_flags = (ulong)EX_DATA_OPT | REC_CONF_OPT; */
  8471.     connreq_ctl->CONN_flags = (ulong) 0;
  8472.     connreq_ctl->QOS_length = (ulong) 0;        /* unsupported in AIX 4.1 */
  8473.     connreq_ctl->QOS_offset = (ulong) 0;        /* unsupported in AIX 4.1 */
  8474.  
  8475.     addtl_info = (char *) ((void*)connreq_ctl + connreq_ctl->DEST_offset);
  8476.     *addtl_info++ = (char) 0; /* X.121 format */
  8477.     bcopy( remote_nua, addtl_info, addr_len );
  8478.  
  8479.     /*
  8480.      * setup the data buffer for the connection request
  8481.      */
  8482.     connreq_data  = (N_npi_data_t *) malloc(sizeof(N_npi_data_t));
  8483.     if (connreq_data == NULL){
  8484.         perror("kermit: x25call(): connreq_data malloc failed");
  8485.         return(-1);
  8486.     }
  8487.     bzero(connreq_data,sizeof(N_npi_data_t));
  8488.  
  8489.     /* facility selection needs to be put in the front of connreq_data */
  8490.     connreq_data_len = 0;
  8491.     connreq_data_len += x25facilities( (char *)connreq_data );
  8492.     if (cud && *cud) {
  8493.         bcopy(cud,
  8494.               (char *)((char *)connreq_data + connreq_data_len),
  8495.               strlen(cud)
  8496.               );
  8497.         connreq_data_len += strlen( cud );
  8498.         }
  8499.  
  8500.     /*
  8501.      * Call putmsg() to put the connection request message on the stream
  8502.      */
  8503.     rc = x25putmsg( fd, (N_npi_ctl_t*)connreq_ctl, connreq_data,
  8504.             connreq_data_len, &flags );
  8505.     if (rc < 0) {
  8506.         return(-1);
  8507.     }
  8508.  
  8509.     /*
  8510.      * Allocate and zero out space for the N_CONN_CON primitive
  8511.      */
  8512.     if ((conncon_ctl = (N_conn_con_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8513.         perror("kermit: x25call(): conncon_ctl malloc failed");
  8514.         return(-1);
  8515.     }
  8516.     bzero(conncon_ctl, sizeof(N_npi_ctl_t));
  8517.  
  8518.     /*
  8519.      * Allocate and zero out space for any data associated with N_CONN_CON
  8520.      */
  8521.     if ( (conncon_data = (N_npi_data_t *) malloc(NPI_MAX_DATA)) == NULL) {
  8522.         perror("kermit: x25call(): conncon_data malloc failed");
  8523.         return(-1);
  8524.     }
  8525.     bzero(conncon_data, NPI_MAX_DATA);
  8526.  
  8527.     /* Initialize and build the structures for getmsg */
  8528.     get_flags=0;
  8529.  
  8530.     rc = x25getmsg( fd, (N_npi_ctl_t*)conncon_ctl, (int)sizeof( N_conn_con_t ),
  8531.             conncon_data, NPI_MAX_DATA, &get_flags, N_CONN_CON );
  8532.  
  8533.     /* turn quantitive return code into a qualitative one */
  8534.     if (rc > 0) rc = 0;
  8535.  
  8536.     /* Free the space that we no longer need */
  8537.     if (connreq_ctl) { free(connreq_ctl); connreq_ctl = NULL; }
  8538.     if (conncon_ctl) { free(conncon_ctl); conncon_ctl = NULL; }
  8539.     if (conncon_data) { free(conncon_data); conncon_data = NULL; }
  8540.  
  8541. #ifdef TRACE
  8542.     printf( "TRACE: leaving x25call\n" );
  8543. #endif /* TRACE */
  8544.  
  8545.     return(rc);
  8546. }
  8547.  
  8548. /*****************************************************************************
  8549.  * Function: x25getcall
  8550.  *
  8551.  * Description: This routine checks for an incomming call, verified
  8552.  * that it is a CONNIND (connection indication) message, and then
  8553.  * accepts the call and returns the file descriptor of the new stream
  8554.  *
  8555.  * Parameters:
  8556.  * fd   - file descriptor of listening stream
  8557.  *
  8558.  * Return Codes:
  8559.  * callfd       - file descriptor of connected incomming call.
  8560.  *              - set to -1 if an error occured
  8561.  *
  8562.  *****************************************************************************/
  8563. int
  8564. x25getcall(fd) int fd; {
  8565.     int x25callfd;                      /* fd of incomming call */
  8566.     N_conn_ind_t *connind_ctl;          /* connind controll buffer */
  8567.     N_npi_data_t *connind_data;         /* connind data buffer */
  8568.     int get_flags;                      /* flags for getmsg */
  8569.     ulong flags;                        /* connection flags */
  8570.     int rc;                             /* return code */
  8571.  
  8572.     extern x25addr_t remote_nua;        /* remote X.25 addr global var */
  8573.  
  8574. #ifdef TRACE
  8575.     printf( "TRACE: entering x25getcall\n" );
  8576. #endif /* TRACE */
  8577.  
  8578.     /* allocate space for connection indication buffers */
  8579.     if ((connind_ctl = (N_conn_ind_t *)malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8580.         perror("kermit: x25getcall(): connind_ctl malloc failed");
  8581.         return (-1);
  8582.     }
  8583.     bzero(connind_ctl, sizeof(N_npi_ctl_t));
  8584.  
  8585.     if ((connind_data = (N_npi_data_t *)malloc(NPI_MAX_DATA)) == NULL) {
  8586.         perror("kermit: x25getcall(): connind_data malloc failed");
  8587.         return (-1);
  8588.     }
  8589.     bzero(connind_data, NPI_MAX_DATA);
  8590.  
  8591.     /* initialise control structures */
  8592.     get_flags = 0;
  8593.  
  8594.     /* call getmsg to check for a connection indication */
  8595.     if (x25getmsg(fd,
  8596.                   (N_npi_ctl_t*)connind_ctl,
  8597.                   (int)sizeof(N_conn_ind_t),
  8598.                   connind_data,
  8599.                   NPI_MAX_DATA,
  8600.                   &get_flags,
  8601.                   N_CONN_IND
  8602.                   ) < 0) {
  8603. #ifdef DEBUG
  8604.         printf( "x25getcall(): errno is: %d\n", errno );
  8605. #endif /* DEBUG */
  8606.         perror ("x25getcall(): getmsg failed");
  8607.         return(-1);
  8608.     }
  8609.  
  8610.     /* a connection indication was received
  8611.      * - pull it to bits and answer the call
  8612.      */
  8613.     x25seqno = connind_ctl->SEQ_number;
  8614.     flags = connind_ctl->CONN_flags;
  8615. #ifdef DEBUG
  8616.     printf( "setting remote_nua to a new value due to incomming call\n" );
  8617. #endif /* DEBUG */
  8618.     /*
  8619.      * no guarantee that the address is null terminated, ensure that
  8620.      * after copying that it is (assumption: remote_nua is longer than
  8621.      * the address + 1)
  8622.      */
  8623.     bzero(remote_nua, sizeof(remote_nua));
  8624.     /* note: connind_ctl contains a x121 address, which has a null as
  8625.      * the FIRST character - strip it off!
  8626.      */
  8627.     ckstrncpy(remote_nua,
  8628.             (char*)((char*)connind_ctl + connind_ctl->SRC_offset + 1),
  8629.             connind_ctl->SRC_length - 1
  8630.             );
  8631. #ifdef DEBUG
  8632.     printf( "remote_nua set to new value of %s\n", remote_nua );
  8633. #endif /* DEBUG */
  8634.  
  8635.     /* errors handled by callee */
  8636.     x25callfd = x25accept(x25seqno, flags);
  8637.  
  8638.     /* free the malloc'd buffers */
  8639.     if (connind_ctl) { free(connind_ctl); connind_ctl = NULL; }
  8640.     if (connind_data) { free(connind_data); connind_data = NULL; }
  8641.  
  8642. #ifdef TRACE
  8643.     printf( "TRACE: leaving x25getcall\n" );
  8644. #endif /* TRACE */
  8645.  
  8646.     /* return the file descriptor (or error if < 0) */
  8647.     return( x25callfd );
  8648. }
  8649.  
  8650. /*****************************************************************************
  8651.  * Function: x25accept
  8652.  *
  8653.  * Description: accept an incomming call
  8654.  *              This essentially means opening a new STREAM and sending
  8655.  *              an acknowledge back to the caller.
  8656.  *
  8657.  * Parameters:
  8658.  *      seqno   - sequence number for acknowledgement
  8659.  *      flags   - flags passed to us by the caller
  8660.  *
  8661.  * Return Codes:
  8662.  *      fd      - file descriptor of new STREAM
  8663.  *                set to -1 if an error occured
  8664.  *
  8665.  *****************************************************************************/
  8666. int
  8667. x25accept(seqno,flags)
  8668.     ulong seqno;                        /* connection sequence number */
  8669.     ulong flags;                        /* connection flags */
  8670. /* x25accept */ {
  8671.     int x25callfd;                      /* fd for incomming call */
  8672.     int get_flags;                      /* priority flags for getmsg */
  8673.     int put_flags = 0;                  /* flags for putmsg, always 0 */
  8674.     int addr_len;                       /* length of local address */
  8675.     ulong token;                        /* connection token */
  8676.     N_conn_res_t *conn_res;             /* N_CONN_RES primitive */
  8677.     N_ok_ack_t *ok_ack;                 /* N_OK_ACK primitive */
  8678.     char *addtl_info;                   /* temp pointer */
  8679.     int rc;                             /* temporary return code */
  8680.  
  8681. /* global variables from ckcmai.c */
  8682.     extern int revcall, closgr, cudata;
  8683.     extern char udata[];
  8684.     extern x25addr_t local_nua;         /* local X.25 address */
  8685.     extern char x25name[];              /* x25 device name (sx25a0) */
  8686.     extern char x25dev[];               /* x25 device file /dev/x25pkt */
  8687.     extern int x25port;                 /* logical port to use */
  8688.     ulong bind_flags = 0;               /* flags for binding the X25 stream */
  8689.  
  8690. #ifdef TRACE
  8691.     printf( "TRACE: entering x25accept\n" );
  8692. #endif /* TRACE */
  8693.  
  8694.     /* open a new packet level stream */
  8695.     if ((x25callfd = open(x25dev, O_RDWR)) < 0) {
  8696.         perror ("kermit: x25accept(): X.25 device open error");
  8697.         debug(F101,"x25accept() device open error","",errno);
  8698.         return(-1);
  8699.     }
  8700.  
  8701.     /* push the NPI onto the STREAM */
  8702.     if (ioctl(x25callfd,I_PUSH,"npi") < 0) {
  8703.         perror( "kermit: x25accept(): couldn't push npi on the X25 stream" );
  8704.         debug(F101,"x25accept can't push npi on the X25 stream","",errno);
  8705.         return (-1);
  8706.     }
  8707.  
  8708.     /* bind kermit server to the local X25 address */
  8709.     /* taken from /usr/samples/sx25/npi/npiserver.c (AIX 4) */
  8710.     bind_flags |= TOKEN_REQUEST;
  8711.     token = x25bind(x25callfd,local_nua,(char *)NULL,0,0,x25port,bind_flags);
  8712.     if (token < 0) {
  8713.         printf( "kermit: x25accept(): couldn't bind to local X25 address\n" );
  8714.         netclos();
  8715.         return(-1);
  8716.     }
  8717.  
  8718.     /* allocate connection response primitive */
  8719.     if ((conn_res = (N_conn_res_t *)malloc( NPI_MAX_CTL )) == NULL) {
  8720.         perror("kermit: x25accept(): conn_res malloc failed");
  8721.         return (-1);
  8722.     }
  8723.     bzero((char *)conn_res, NPI_MAX_CTL);
  8724.  
  8725.     /* setup connection response primitive */
  8726.     addr_len = strlen( local_nua );
  8727.     conn_res->PRIM_type = (ulong)N_CONN_RES;
  8728.     conn_res->TOKEN_value = token;
  8729.     /* note address length is n+1 to accomodate the X.121 address prefix */
  8730.     conn_res->RES_length = (ulong)(addr_len + 1);
  8731.     conn_res->RES_offset = (ulong)sizeof( N_conn_res_t );
  8732.     conn_res->SEQ_number = seqno;
  8733.     conn_res->CONN_flags = 0;
  8734.     conn_res->QOS_length = 0;           /* unsupported - must be 0 (!?) */
  8735.     conn_res->QOS_offset = 0;
  8736.  
  8737.     addtl_info = (char *)((char *)conn_res + conn_res->RES_offset);
  8738.     *addtl_info++ = (char)0;    /* X.121 address prefix */
  8739.     bcopy( local_nua, addtl_info, addr_len );
  8740.  
  8741.     /*
  8742.      * send off the connect response
  8743.      */
  8744.     if (x25putmsg(x25callfd,
  8745.                   (N_npi_ctl_t*)conn_res,
  8746.                   (N_npi_data_t *)NULL,
  8747.                   0,
  8748.                   &put_flags
  8749.                   ) < 0 ) {
  8750.         perror("kermit: x25accept(): putmsg connect response failed");
  8751.         return(-1);
  8752.     }
  8753.  
  8754.     /*
  8755.      * Allocate and zero out space for the OK_ACK primitive
  8756.      */
  8757.     if ((ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8758.         perror("kermit: x25call(): ok_ack malloc failed");
  8759.         return(-1);
  8760.     }
  8761.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8762.  
  8763.     /* Initialize and build the structures for getmsg */
  8764.     get_flags=0;
  8765.  
  8766.     rc = (int)x25getmsg(x25callfd,
  8767.                         (N_npi_ctl_t*)ok_ack,
  8768.                         (int)sizeof(N_ok_ack_t),
  8769.                         (N_npi_data_t*)NULL,
  8770.                         0,
  8771.                         &get_flags,
  8772.                         N_OK_ACK
  8773.                         );
  8774.     if (rc == 0) {
  8775.         /* sequence number is only for disconnecting when not connected !? */
  8776.         x25seqno = 0;
  8777.     }
  8778.  
  8779.     /* free up malloc'ed buffer space */
  8780.     if (conn_res) { free(conn_res); conn_res = NULL; }
  8781.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8782.  
  8783. #ifdef TRACE
  8784.     printf( "TRACE: leaving x25accept\n" );
  8785. #endif /* TRACE */
  8786.  
  8787.     return( ( rc >= 0 ) ? x25callfd : -1 );
  8788. }
  8789.  
  8790. /*****************************************************************************
  8791.  * Function: x25unbind
  8792.  *
  8793.  * Description:  This subroutine builds and sends an unbind request and gets
  8794.  * the acknowledgement for it.
  8795.  *
  8796.  * Parameters:
  8797.  * fd - File descriptor of the stream
  8798.  *
  8799.  * Functions Referenced:
  8800.  * getmsg()
  8801.  * putmsg()
  8802.  * malloc()
  8803.  * bzero()
  8804.  *
  8805.  * Return code:
  8806.  * 0 - if successful
  8807.  * -1 - if not successful
  8808.  *****************************************************************************/
  8809. int
  8810. x25unbind(fd) int fd; {                 /* X25 device (opened) */
  8811.     int rc;                             /* return code */
  8812.     int flags;                          /* bind flags */
  8813.     int get_flags;                      /* priority flag for getmsg */
  8814.     ulong type;                         /* primitive type */
  8815.     N_unbind_req_t *unbind_req;         /* pointer to N_UNBIND_REQ */
  8816.     N_ok_ack_t *ok_ack;                 /* pointer to N_OK_ACK */
  8817.  
  8818. #ifdef TRACE
  8819.     printf( "TRACE: entering x25unbind\n" );
  8820. #endif /* TRACE */
  8821.  
  8822. #ifdef DEBUG
  8823.     /* printf( "x25unbind( %d )\n", fd ); */
  8824. #endif /* DEBUG */
  8825.     debug(F101,"x25unbind closing x25 connection #","",fd);
  8826.  
  8827.     /* Allocate and zero out space to hold the N_UNBIND_REQ primitive */
  8828.     unbind_req = (N_unbind_req_t *) malloc(sizeof(N_npi_ctl_t));
  8829.     if (unbind_req == NULL) {
  8830.         perror("kermit: x25unbind(): unbind_req malloc failed");
  8831.         return(-1);
  8832.     }
  8833.     bzero(unbind_req, sizeof(N_npi_ctl_t));
  8834.  
  8835.     /*
  8836.      * Build the Unbind Request Primitive
  8837.      */
  8838.     flags = 0;
  8839.     unbind_req->PRIM_type = (ulong) N_UNBIND_REQ;
  8840.  
  8841.     /*
  8842.      * Call putmsg() to put the bind request message on the stream
  8843.      */
  8844.     if (x25putmsg(fd,
  8845.                   (N_npi_ctl_t*)unbind_req,
  8846.                   (N_npi_data_t *)NULL,
  8847.                   0,
  8848.                   &flags
  8849.                   ) < 0) {
  8850.         perror ("kermit: x25unbind(): putmsg failed");
  8851.         return(-1);
  8852.     }
  8853.  
  8854.     /* Allocate and Zero out space for the N_OK_ACK primitive */
  8855.     ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8856.     if (ok_ack == NULL) {
  8857.         perror("kermit x25unbind(): ok_ack malloc failed\n");
  8858.         return(-1);
  8859.     }
  8860.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8861.  
  8862.     /* Initialize and build the control structure for getmsg */
  8863.     get_flags=0;
  8864.  
  8865.     /* Call getmsg() to check for an acknowledgement */
  8866.     rc = x25getmsg(fd,
  8867.                    (N_npi_ctl_t*)ok_ack,
  8868.                    (int)sizeof(N_ok_ack_t),
  8869.                    (N_npi_data_t*)NULL,
  8870.                    0,
  8871.                    &get_flags,
  8872.                    N_OK_ACK
  8873.                    );
  8874.     if (rc < 0) {
  8875.         perror ("kermit: x25unbind: getmsg failed");
  8876.         return(-1);
  8877.     }
  8878.  
  8879.     /* Free up the space that we no longer need */
  8880.     if (unbind_req) { free(unbind_req); unbind_req = NULL; }
  8881.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8882.  
  8883. #ifdef TRACE
  8884.     printf( "TRACE: leaving x25unbind\n" );
  8885. #endif /* TRACE */
  8886.  
  8887.     return(0);
  8888. }
  8889.  
  8890. /*****************************************************************************
  8891.  * Function: x25xin
  8892.  *
  8893.  * Description:
  8894.  *      Read n characters from X.25 circuit into buf (AIX only)
  8895.  *
  8896.  * Parameters:
  8897.  *      data_buf_len    maximum size of data buffer
  8898.  *      data_buf        pointer to pre-allocated buffer space
  8899.  *
  8900.  * Return Value:
  8901.  *      the number of characters actually read
  8902.  */
  8903. int
  8904. x25xin(data_buf_len,data_buf) int data_buf_len; CHAR *data_buf; {
  8905.     struct strbuf getmsg_ctl;           /* streams control structure */
  8906.     struct strbuf getmsg_data;          /* streams data structure */
  8907.     int rc = 0;                         /* return code */
  8908.     int getmsg_flags;                   /* packet priority flags */
  8909.     char * ctl_buf;                     /* npi control buffer */
  8910.     N_npi_ctl_t * result;               /* pointer to simplify switch() */
  8911.  
  8912. #ifdef TRACE
  8913.     printf( "TRACE: entering x25xin\n" );
  8914. #endif /* TRACE */
  8915.  
  8916.     /* ensure that no maximum's are overridden */
  8917.     data_buf_len = (NPI_MAX_DATA < data_buf_len) ? NPI_MAX_DATA : data_buf_len;
  8918.  
  8919.     /* allocate space for packet control info */
  8920.     if ((ctl_buf = (char *)malloc(NPI_MAX_CTL)) == NULL) {
  8921.         perror( "kermit: x25xin(): ctl_buf malloc" );
  8922.         return(-1);
  8923.     }
  8924. #ifdef COMMENT
  8925.     /* riehm: need zeroed buffer for getmsg? */
  8926.     bzero( ctl_buf, NPI_MAX_CTL );
  8927.     /* clear data buffer */
  8928.     bzero( data_buf, data_buf_len );
  8929. #endif /* COMMENT */
  8930.  
  8931.     getmsg_flags = 0;                   /* get the first packet available */
  8932.  
  8933.     rc = x25getmsg(ttyfd,
  8934.                    ctl_buf,
  8935.                    NPI_MAX_CTL,
  8936.                    data_buf,
  8937.                    data_buf_len,
  8938.                    &getmsg_flags,
  8939.                    N_DATA_IND
  8940.                    );
  8941. #ifdef COMMENT
  8942. #ifdef DEBUG
  8943.     if (rc >= 0) {
  8944.         printf( "kermit: x25xin(): got " );
  8945.         x25dump_data( data_buf, 0, rc );
  8946.     } else {
  8947.         printf( "x25xin(): attempt to get data resulted in an error\n" );
  8948.     }
  8949. #endif /* DEBUG */
  8950. #endif /* COMMENT */
  8951.  
  8952.     /* free buffers */
  8953.     if (ctl_buf) { free(ctl_buf); ctl_buf = NULL; }
  8954.  
  8955. #ifdef TRACE
  8956.     printf( "TRACE: leaving x25xi\n" );
  8957. #endif /* TRACE */
  8958.  
  8959.     return(rc);
  8960. }
  8961.  
  8962. /*****************************************************************************
  8963.  * Function: x25write
  8964.  *
  8965.  * Description:
  8966.  *      write a block of characters to the X25 STREAM (AIX)
  8967.  *
  8968.  * Parameters:
  8969.  *      fd              file descriptor to write to
  8970.  *      databuf         buffer containing data to write
  8971.  *      databufsize             size of the buffer to write
  8972.  *
  8973.  * Return Value:
  8974.  *      size            the number of bytes actually transmitted
  8975.  */
  8976. int
  8977. x25write(fd, databuf, databufsize)
  8978.     int         fd;                  /* X25 STREAMS file descriptor (ttyfd) */
  8979.     char        *databuf;               /* buffer to write */
  8980.     int         databufsize;            /* buffer size */
  8981. /* x25write */ {
  8982.     N_data_req_t *data_req_ctl;
  8983.     int rc;                             /* return code (size transmitted) */
  8984.     int write_flags = 0;                /* always 0 !? */
  8985.  
  8986. #ifdef TRACE
  8987.     printf( "TRACE: entering x25write\n" );
  8988. #endif /* TRACE */
  8989.  
  8990.     if ((data_req_ctl = (N_data_req_t *)malloc(NPI_MAX_CTL) ) == NULL) {
  8991.         perror( "kermit: x25write(): data_req_ctl malloc" );
  8992.         return(-1);
  8993.     }
  8994.     data_req_ctl->PRIM_type = N_DATA_REQ;
  8995.     data_req_ctl->DATA_xfer_flags = 0;
  8996.  
  8997.     /* riehm: possible extension
  8998.      * possibly need to think about splitting up the data buffer
  8999.      * into multiple parts if databufsize > NPI_MAX_DATA
  9000.      */
  9001.  
  9002. #ifdef COMMENT
  9003. #ifdef DEBUG
  9004.     printf( "kermit: x25write(): writing data to x25 stream\n" );
  9005.     printf( "\tdata:\t" );
  9006.     x25dump_data(databuf, 0, databufsize);
  9007. #endif /* DEBUG */
  9008. #endif /* COMMENT */
  9009.     rc = x25putmsg(fd,
  9010.                    (N_npi_ctl_t*)data_req_ctl,
  9011.                    (N_npi_data_t*)databuf,
  9012.                    databufsize,
  9013.                    &write_flags
  9014.                    );
  9015.     if (data_req) { free(data_req_ctl);  data_req = NULL; }
  9016.  
  9017. #ifdef TRACE
  9018.     printf( "TRACE: leaving x25write\n" );
  9019. #endif /* TRACE */
  9020.  
  9021.     return(rc);
  9022. }
  9023.  
  9024. /*****************************************************************************
  9025.  * Function: x25local_nua
  9026.  *
  9027.  * Description:
  9028.  *      This routine is only interesting for IBM computers. In order
  9029.  *      to set up a connection (see x25bind()) you need to know the
  9030.  *      local NUA (x25 address). Unfortunately, you need all this code
  9031.  *      to find that out, I just hope this works for everyone else!
  9032.  *
  9033.  * Parameters:
  9034.  *      a pre-allocated character buffer, long enough to hold an X.25 address
  9035.  *      and the tailing null.
  9036.  *
  9037.  * Return Value:
  9038.  *      the length of the address string.
  9039.  *      0 = error
  9040.  */
  9041. int
  9042. x25local_nua(char *buf) {
  9043.     struct CuAt *response;      /* structure to fill with info from ODM */
  9044.     CLASS_SYMBOL retClass;      /* ODM class */
  9045.     char query[64];             /* odm database query */
  9046.     int rc = 0;                 /* return value (length of local NUA) */
  9047.     extern char x25name[];      /* x25 device name (sx25a0) */
  9048.  
  9049. #ifdef TRACE
  9050.     printf( "TRACE: entering x25local_nua\n" );
  9051. #endif /* TRACE */
  9052.  
  9053.     /* set up query string */
  9054.     if (x25name[0] == '\0') {
  9055. #ifdef DEBUG
  9056.         printf( "kermit: x25local_nua(): No x25 device set, trying sx25a0\n" );
  9057. #endif /* DEBUG */
  9058.         strcpy( x25name, "sx25a0" );
  9059.     }
  9060.     ckmakmsg(query, sizeof(query), "name like ",x25name,
  9061.              " and attribute like local_nua");
  9062.  
  9063.     /* initialise ODM database */
  9064.     odmerrno = 0;
  9065.     if (odm_initialize() == -1) {
  9066.         printf( "x25local_nua(): can't initialize ODM database");
  9067.         switch (odmerrno) {
  9068.           case ODMI_INVALID_PATH:
  9069.             printf( "invalid path\n" );
  9070.             break;
  9071.           case ODMI_MALLOC_ERR:
  9072.             printf( "malloc failed\n" );
  9073.             break;
  9074.           default:
  9075.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  9076.         }
  9077.         return(rc);
  9078.     }
  9079.  
  9080.     /* open the CuAt class */
  9081.     retClass = odm_open_class(CuAt_CLASS);
  9082.     if (((int)retClass) == -1) {
  9083.         printf( "kermit: x25local_nua(): can't open CuAt class in odm. " );
  9084.         switch (odmerrno) {
  9085.           case ODMI_CLASS_DNE:
  9086.             printf( "CuAt class doesn't exist\n" );
  9087.             break;
  9088.           case ODMI_CLASS_PERMS:
  9089.             printf( "permission to CuAt class file denied\n" );
  9090.             break;
  9091.           case ODMI_MAGICNO_ERR:
  9092.             printf( "CuAt is an invalid ODM object class\n" );
  9093.             break;
  9094.           case ODMI_OPEN_ERR:
  9095.             printf( "cannot open CuAt class - and don't know why!\n" );
  9096.             break;
  9097.           case ODMI_INVALID_PATH:
  9098.             printf( "invalid path\n" );
  9099.             break;
  9100.           case ODMI_TOOMANYCLASSES:
  9101.             printf( "too many object classes have been opened\n" );
  9102.             break;
  9103.           default:
  9104.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  9105.         }
  9106.         return(rc);
  9107.     }
  9108.  
  9109. #ifdef DEBUG
  9110.     printf("retClass= %d\n", retClass);
  9111. #endif /* DEBUG */
  9112.  
  9113.     response = (struct CuAt *)odm_get_first( retClass, query, NULL );
  9114.     if (((int)response) == -1) {
  9115.         printf( "kermit: x25local_nua(): odm query failed " );
  9116.         switch (odmerrno) {
  9117.           case ODMI_BAD_CRIT:           /* Programming error */
  9118.             printf( "bad search criteria\n" );
  9119.             break;
  9120.           case ODMI_CLASS_DNE:
  9121.             printf( "CuAt class doesn't exist\n" );
  9122.             break;
  9123.           case ODMI_CLASS_PERMS:
  9124.             printf( "permission to CuAt class file denied\n" );
  9125.             break;
  9126.           case ODMI_INTERNAL_ERR:
  9127.             printf("odm internal error\nPlease contact your administrator\n" );
  9128.             break;
  9129.           case ODMI_INVALID_CLXN:
  9130.             printf("CuAt is invalid or inconsistent odm class collection\n");
  9131.             break;
  9132.           case ODMI_INVALID_PATH:
  9133.             printf( "invalid path\n" );
  9134.             break;
  9135.           case ODMI_MAGICNO_ERR:
  9136.             printf( "CuAt is an invalid ODM object class\n" );
  9137.             break;
  9138.           case ODMI_MALLOC_ERR:
  9139.             printf( "malloc failed\n" );
  9140.             break;
  9141.           case ODMI_OPEN_ERR:
  9142.             printf( "cannot open CuAt class - and don't know why!\n" );
  9143.             break;
  9144.           case ODMI_TOOMANYCLASSES:
  9145.             printf( "too many object classes have been opened\n" );
  9146.             break;
  9147.           default:
  9148.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  9149.         }
  9150.         return(rc);
  9151.     }
  9152.  
  9153.     /* check for a meaningfull response */
  9154.     if (response != NULL) {
  9155.         if (response->value != NULL) {
  9156.             strcpy(buf, response->value);
  9157.             rc = strlen( buf );
  9158. #ifdef DEBUG
  9159. /*
  9160.             printf( "attribute name is: %s\n", (char *)response->attribute );
  9161.             printf( "I think my address is %s\n", (char*)response->value );
  9162. */
  9163. #endif /* DEBUG */
  9164.         } else {
  9165.             printf( "kermit: x25local_nua(): couldn't find the local NUA\n" );
  9166.         }
  9167.     } else {
  9168.         switch (odmerrno) {
  9169.           case ODMI_BAD_CRIT:
  9170.             printf( "Error: ODMI_BAD_CRIT - bad criteria\n" );
  9171.             break;
  9172.           case ODMI_CLASS_DNE:
  9173.             printf( "Error: ODMI_CLASS_DNE - class doesn't exist\n" );
  9174.             break;
  9175.           case ODMI_CLASS_PERMS:
  9176.             printf( "Error: ODMI_CLASS_PERMS - class permissions\n" );
  9177.             break;
  9178.           case ODMI_INTERNAL_ERR:
  9179.             printf( "Error: ODMI_INTERNAL_ERR - panic\n" );
  9180.             break;
  9181.           case ODMI_INVALID_CLXN:
  9182.             printf( "Error: ODMI_INVALID_CLXN - invalid collection\n" );
  9183.             break;
  9184.           case ODMI_INVALID_PATH:
  9185.             printf( "Error: ODMI_INVALID_PATH - invalid path - what path?\n" );
  9186.             break;
  9187.           case ODMI_MAGICNO_ERR:
  9188.             printf( "Error: ODMI_MAGICNO_ERR - invalid object magic\n" );
  9189.             break;
  9190.           case ODMI_MALLOC_ERR:
  9191.             printf( "Error: ODMI_MALLOC_ERR - malloc failed\n" );
  9192.             break;
  9193.           case ODMI_OPEN_ERR:
  9194.             printf( "Error: ODMI_OPEN_ERR - cannot open class\n" );
  9195.             break;
  9196.           case ODMI_TOOMANYCLASSES:
  9197.             printf( "Error: ODMI_TOOMANYCLASSES - too many classes\n" );
  9198.             break;
  9199.           default:
  9200.             printf( "Unknown error!\n" );
  9201.         }
  9202.         return(rc);
  9203.     }
  9204.  
  9205.     /* close the database again */
  9206.     odm_close_class( retClass );
  9207.  
  9208.     /* forget about ODM all together */
  9209.     odm_terminate();
  9210.  
  9211. #ifdef TRACE
  9212.     printf( "TRACE: leaving x25local_nua\n" );
  9213. #endif /* TRACE */
  9214.  
  9215.     debug(F110, "x25local_nua local address is ", buf, 0);
  9216.     return(rc);
  9217. }
  9218.  
  9219. /*****************************************************************************
  9220.  * Function: x25facilities
  9221.  *
  9222.  * Description:
  9223.  *      build up the facilities data packet for a connection request
  9224.  *
  9225.  * Parameters:
  9226.  *      a pre-allocated char buffer, normally NPI_MAX_DATA big.
  9227.  *
  9228.  * Return Value:
  9229.  *      the number of characters inserted into the buffer
  9230.  */
  9231. int
  9232. x25facilities(buffer) char *buffer; {
  9233.     extern int revcall;
  9234.     extern int closgr;
  9235.     char *p;                            /* temp pointer */
  9236.     char *start;                        /* temp pointer */
  9237.  
  9238. #ifdef TRACE
  9239.     printf( "TRACE: entering x25facilities\n" );
  9240. #endif /* TRACE */
  9241.  
  9242.     p = buffer + 1;
  9243.     start = p;
  9244.  
  9245. #ifdef DEBUG
  9246.     printf( "kermit: x25facilities(): getting X25 facilities\n" );
  9247. #endif /* DEBUG */
  9248.  
  9249.     if (revcall != 0) {
  9250. #ifdef DEBUG
  9251.         printf("reverse charge: %d\n", revcall );
  9252. #endif /* DEBUG */
  9253.         *++p = 0x01;
  9254.         *++p = revcall;
  9255.     }
  9256.     if (closgr > 0) {
  9257. #ifdef DEBUG
  9258.         printf("closed user group: %d\n", closgr );
  9259. #endif /* DEBUG */
  9260.         *++p = 0x03;
  9261.         *++p = closgr;
  9262.     }
  9263.  
  9264. #ifdef DEBUG
  9265.     if (p == start) {
  9266.         printf( "no facilities\n" );
  9267.     }
  9268. #endif /* DEBUG */
  9269.  
  9270.     /* set the size of the facilities buffer */
  9271.     *buffer = (char)( p - start ) & 0xff;
  9272.  
  9273. #ifdef DEBUG
  9274.     printf( "kermit: x25facilities(): returning %d\n", (int)(p - buffer)  );
  9275. #endif /* DEBUG */
  9276.  
  9277. #ifdef TRACE
  9278.     printf( "TRACE: leaving x25facilities\n" );
  9279. #endif /* TRACE */
  9280.  
  9281.     /* return the size of the facilities with size byte */
  9282.     /* 1 == no facilities, 0 byte returned as facilities size */
  9283.     return( (int)(p - buffer) );
  9284. }
  9285.  
  9286. /*
  9287.  * reset the connection
  9288.  */
  9289. int
  9290. x25reset(cause, diagn) char cause; char diagn; {
  9291.     /* not implemented */
  9292.  
  9293. #ifdef TRACE
  9294.     printf( "TRACE: entering x25reset\n" );
  9295. #endif /* TRACE */
  9296.  
  9297. #ifdef TRACE
  9298.     printf( "TRACE: leaving x25reset\n" );
  9299. #endif /* TRACE */
  9300.  
  9301.     return(0);
  9302. }
  9303.  
  9304. /*
  9305.  * clear the x25 connection - ie: hang up
  9306.  */
  9307. int
  9308. x25clear() {
  9309.     int get_flags = 0;                  /* priority flag for getmsg */
  9310.     int put_flags = 0;                  /* send flags, always 0 */
  9311.     ulong type;                         /* primitive type */
  9312.     N_discon_req_t *discon_req;         /* pointer to N_DISCON_REQ */
  9313.     N_discon_ind_t *discon_ind;         /* pointer to N_DISCON_IND */
  9314.     N_npi_data_t *discon_data;          /* pointer to N_DISCON_IND data */
  9315.     int rc = 0;                         /* return code */
  9316.  
  9317. #ifdef TRACE
  9318.     printf( "TRACE: entering x25clear\n" );
  9319. #endif /* TRACE */
  9320.  
  9321. #ifdef DEBUG
  9322.     /* printf( "x25clear(): checking last msg: %s\n", x25prim(x25lastmsg)); */
  9323. #endif /* DEBUG */
  9324.  
  9325.     /*
  9326.     * The following checks are used to ensure that we don't disconnect
  9327.     * or unbind twice - this seems to throw the NPI interface right out of
  9328.     * kilter.
  9329.     */
  9330.     switch(x25lastmsg) {
  9331.       case N_BIND_ACK:
  9332.       case N_CONN_CON:
  9333.       case N_CONN_REQ:
  9334.       case N_DATA_REQ:
  9335.       case N_DATA_IND:
  9336.         {
  9337. #ifdef DEBUG
  9338.             /* printf("x25clear(): actively disconnecting\n"); */
  9339. #endif /* DEBUG */
  9340.  
  9341.                 discon_req = (N_discon_req_t *)malloc(NPI_MAX_CTL);
  9342.                 if (discon_req == NULL) {
  9343.                     perror("kermit x25clear(): discon_req malloc failed\n");
  9344.                     /* fallthrough, try to unbind the NPI anyway */
  9345.                 } else {
  9346.                     discon_req->PRIM_type = N_DISCON_REQ;
  9347.                     discon_req->DISCON_reason = 0;      /* not used by AIX */
  9348.                     discon_req->RES_length = 0;
  9349.                     discon_req->RES_offset = (ulong)(sizeof(N_discon_req_t));
  9350.                     discon_req->SEQ_number = x25seqno;  /* global */
  9351.  
  9352.                     if (x25putmsg(ttyfd,
  9353.                                   (N_npi_ctl_t*)discon_req,
  9354.                                   (N_npi_data_t*)NULL,
  9355.                                   0,
  9356.                                   &put_flags
  9357.                                   ) < 0) {
  9358.                         perror("x25putmsg failed in x25clear()");
  9359.                     }
  9360.                     discon_ind = (N_discon_ind_t *)malloc(NPI_MAX_CTL);
  9361.                     discon_data = (N_npi_data_t *)malloc(NPI_MAX_DATA);
  9362.                     if((discon_ind == NULL) || (discon_data == NULL)) {
  9363.                         perror("x25clear(): discon_ind malloc failed\n");
  9364.                         /* fallthrough, try to unbind the NPI anyway */
  9365.                     } else {
  9366.                         if(x25getmsg(ttyfd,
  9367.                                      (N_npi_ctl_t*)discon_ind,
  9368.                                      NPI_MAX_CTL,
  9369.                                      (N_npi_data_t*)discon_data,
  9370.                                      NPI_MAX_DATA,
  9371.                                      &get_flags,
  9372.                                      N_OK_ACK
  9373.                                      ) < 0 ) {
  9374.                             perror("x25getmsg failed in x25clear()");
  9375.                             /* fallthrough, try to unbind the NPI anyway */
  9376.                         }
  9377.                     }
  9378.                 }
  9379.                 break;
  9380.             }
  9381.     }
  9382.  
  9383.     if (x25lastmsg != N_UNBIND_REQ) {
  9384.         rc = x25unbind(ttyfd);
  9385.     }
  9386.  
  9387. #ifdef TRACE
  9388.     printf( "TRACE: leaving x25clear\n" );
  9389. #endif /* TRACE */
  9390.  
  9391.     return(rc);
  9392. }
  9393.  
  9394. #ifdef DEBUG
  9395. /*
  9396.  * only for debugging
  9397.  *
  9398.  * turn the internal representation of a datablock into something
  9399.  * half-way readable. Because the length is known, we can print
  9400.  * the string including null's etc (important, because the first(!)
  9401.  * byte of an X121 address is a null! (X121 addr == 0 + X25 addr)
  9402.  */
  9403. x25dump_data(char *addr, ulong offset, ulong length) {
  9404.     char *ptr = addr + offset;
  9405.     ulong i = length;
  9406.     /* allocate enough memory for all unprintable chars */
  9407.     char *buf = (char *)malloc( length * 4 );
  9408.     char *bptr = buf;   /* pointer to current place in the print buffer */
  9409.  
  9410.     while (i > 0) {
  9411.         if (isprint(*ptr)) {
  9412.             *bptr++ = *ptr;
  9413.         } else {
  9414.             *bptr++ = '[';
  9415.             strcpy(bptr,ckctox(*ptr,1)); bptr += 2;
  9416.             *bptr++ = ']';
  9417.         }
  9418.         ptr++;
  9419.         i--;
  9420.     }
  9421.     if (length > 0) {
  9422.         *bptr = '\0';
  9423.         printf( "%s", buf );
  9424.     }
  9425.     printf( " (%d+%d)\n", offset, length );
  9426.  
  9427.     if (buf) { free(buf); buf = NULL; }
  9428.     return;
  9429. }
  9430.  
  9431. /*
  9432.  * only for debugging
  9433.  * print as much useful information about a packet as possible
  9434.  */
  9435. x25dump_prim(primitive)    N_npi_ctl_t *primitive; {
  9436.     printf("Primitive");
  9437.     switch (primitive->PRIM_type) {
  9438.       case N_BIND_ACK:
  9439.         printf( "\tN_BIND_ACK\n\taddress:\t" );
  9440.         x25dump_data( (char *)primitive,
  9441.                      primitive->bind_ack.ADDR_offset,
  9442.                      primitive->bind_ack.ADDR_length );
  9443.         printf( "\tproto id:\t" );
  9444.         x25dump_data( (char *)primitive,
  9445.                      primitive->bind_ack.PROTOID_offset,
  9446.                      primitive->bind_ack.PROTOID_length );
  9447.         printf( "\tconnind:\t%d\n\ttoken:\t\t%d\n",
  9448.                primitive->bind_ack.CONIND_number,
  9449.                primitive->bind_ack.TOKEN_value );
  9450.         break;
  9451.  
  9452.       case N_BIND_REQ:
  9453.         printf( "\tN_BIND_REQ\n\taddress:\t" );
  9454.         x25dump_data( (char *)primitive,
  9455.                      primitive->bind_req.ADDR_offset,
  9456.                      primitive->bind_req.ADDR_length );
  9457.         printf( "\tproto id:\t" );
  9458.         x25dump_data( (char *)primitive,
  9459.                      primitive->bind_req.PROTOID_offset,
  9460.                      primitive->bind_req.PROTOID_length );
  9461.         printf( "\tconnind:\t%d\n\tflags:\t\t%d\n",
  9462.                primitive->bind_req.CONIND_number,
  9463.                primitive->bind_req.BIND_flags );
  9464.         break;
  9465.  
  9466.       case N_CONN_CON:
  9467.         printf( "\tN_CONN_CON\n" );
  9468.         printf( "\tRES\t\t" );
  9469.         x25dump_data( (char *)primitive,
  9470.                      primitive->conn_con.RES_offset,
  9471.                      primitive->conn_con.RES_length );
  9472.         printf( "\tflags:\t%d\n", primitive->conn_con.CONN_flags );
  9473.         break;
  9474.  
  9475.       case N_CONN_IND:
  9476.         printf( "\tN_CONN_IND\n" );
  9477.         printf( "\tsource:\t\t" );
  9478.         x25dump_data( (char *)primitive,
  9479.                      primitive->conn_ind.SRC_offset,
  9480.                      primitive->conn_ind.SRC_length );
  9481.         printf( "\tdestination:\t" );
  9482.         x25dump_data( (char *)primitive,
  9483.                      primitive->conn_ind.DEST_offset,
  9484.                      primitive->conn_ind.DEST_length );
  9485.         printf( "\tSEQ_number:\t%d\n", primitive->conn_ind.SEQ_number );
  9486.         printf( "\tflags:\t%d\n", primitive->conn_ind.CONN_flags );
  9487.         break;
  9488.  
  9489.       case N_CONN_REQ:
  9490.         printf( "\tN_CONN_REQ\n\tdestination:\t" );
  9491.         x25dump_data( (char *)primitive,
  9492.                      primitive->conn_req.DEST_offset,
  9493.                      primitive->conn_req.DEST_length );
  9494.         printf( "\tflags:\t%d\n", primitive->conn_req.CONN_flags );
  9495.         break;
  9496.  
  9497.       case N_CONN_RES:
  9498.         printf( "\tN_CONN_RES\n" );
  9499.         printf( "\tTOKEN_value\t%d\n", primitive->conn_res.TOKEN_value );
  9500.         printf( "\tSEQ_number\t%d\n", primitive->conn_res.SEQ_number );
  9501.         printf( "\tCONN_flags\t%d\n", primitive->conn_res.CONN_flags );
  9502.         printf( "\tRES\t\t" );
  9503.         x25dump_data( (char *)primitive,
  9504.                      primitive->conn_res.RES_offset,
  9505.                      primitive->conn_res.RES_length );
  9506.         break;
  9507.  
  9508.       case N_DATACK_IND:
  9509.         printf( "\tN_DATACK_IND\n" );
  9510.         break;
  9511.  
  9512.       case N_DATACK_REQ:
  9513.         printf( "\tN_DATACK_REQ\n" );
  9514.         printf( "\tflags:\t%d\n", primitive->data_req.DATA_xfer_flags );
  9515.         break;
  9516.  
  9517.       case N_DATA_IND:
  9518.         printf( "\tN_DATA_IND\n" );
  9519.         printf( "\tflags:\t%d\n", primitive->data_ind.DATA_xfer_flags );
  9520.         break;
  9521.  
  9522.       case N_DATA_REQ:
  9523.         printf( "\tN_DATA_REQ\n" );
  9524.         break;
  9525.  
  9526.       case N_DISCON_IND:
  9527.         printf( "\tN_DISCON_IND\n" );
  9528.         printf( "\torigin:\t%d\n", primitive->discon_ind.DISCON_orig );
  9529.         printf( "\treason:\t\t%d\n", primitive->discon_ind.DISCON_reason );
  9530.         printf( "\tseq no:\t\t%d\n", primitive->discon_ind.SEQ_number );
  9531.         printf( "\tRES:\t" );
  9532.         x25dump_data( (char *)primitive,
  9533.                      primitive->discon_ind.RES_offset,
  9534.                      primitive->discon_ind.RES_length );
  9535.         break;
  9536.  
  9537.       case N_DISCON_REQ:
  9538.         printf( "\tN_DISCON_REQ\n" );
  9539.         printf( "\tDISCON_reason:\t%d\n",
  9540.                primitive->discon_req.DISCON_reason );
  9541.         printf( "\tRES:\t" );
  9542.         x25dump_data( (char *)primitive,
  9543.                      primitive->discon_req.RES_offset,
  9544.                      primitive->discon_req.RES_length );
  9545.         printf( "\tSEQ_number:\t%d\n", primitive->discon_req.SEQ_number );
  9546.         break;
  9547.  
  9548.       case N_ERROR_ACK:
  9549.         printf( "\tN_ERROR_ACK\n" );
  9550.         printf( "\tCaused by:\t%s\n",
  9551.                x25prim( primitive->error_ack.ERROR_prim ) );
  9552.         printf( "\tNPI error:\t%s\n",
  9553.                x25err( primitive->error_ack.NPI_error ));
  9554.         errno = primitive->error_ack.UNIX_error;
  9555.         perror( "\t" );
  9556.         break;
  9557.  
  9558.       case N_EXDATA_IND:
  9559.         printf( "\tN_EXDATA_ACK\n" );
  9560.         break;
  9561.  
  9562.       case N_EXDATA_REQ:
  9563.         printf( "\tN_EXDATA_REQ\n" );
  9564.         break;
  9565.  
  9566.       case N_INFO_ACK:
  9567.         printf( "\tN_INFO_ACK\n" );
  9568.         printf( "\tNSDU size:\t%d\n", primitive->info_ack.NSDU_size );
  9569.         printf( "\tENSDU size:\t%d\n", primitive->info_ack.ENSDU_size );
  9570.         printf( "\tCDATA size:\t%d\n", primitive->info_ack.CDATA_size );
  9571.         printf( "\tDDATA size:\t%d\n", primitive->info_ack.DDATA_size );
  9572.         printf( "\tADDR size:\t%d\n", primitive->info_ack.ADDR_size );
  9573.         printf( "\tNIDU size:\t%d\n", primitive->info_ack.NIDU_size );
  9574.         break;
  9575.  
  9576.       case N_INFO_REQ:
  9577.         printf( "\tN_INFO_REQ\n" );
  9578.         break;
  9579.  
  9580.       case N_OK_ACK:
  9581.         printf( "\tN_OK_ACK\n" );
  9582.         break;
  9583.  
  9584.       case N_OPTMGMT_REQ:
  9585.         printf( "\tN_OPTMGMT_REQ\n" );
  9586.         break;
  9587.  
  9588.       case N_RESET_CON:
  9589.         printf( "\tN_RESET_CON\n" );
  9590.         break;
  9591.  
  9592.       case N_RESET_IND:
  9593.         printf( "\tN_RESET_IND\n" );
  9594.         printf( "\treason:\t\t%d\n", primitive->reset_ind.RESET_reason );
  9595.         printf( "\torigin:\t\t%d\n", primitive->reset_ind.RESET_orig );
  9596.         break;
  9597.  
  9598.       case N_RESET_REQ:
  9599.         printf( "\tN_RESET_REQ\n" );
  9600.         printf( "\treason:\t\t%d\n", primitive->reset_req.RESET_reason );
  9601.         break;
  9602.  
  9603.       case N_RESET_RES:
  9604.         printf( "\tN_RESET_RES\n" );
  9605.         break;
  9606.  
  9607.       case N_UDERROR_IND:
  9608.         printf( "\tN_UDERROR_IND\n" );
  9609.         break;
  9610.  
  9611.       case N_UNBIND_REQ:
  9612.         printf( "\tN_UNBIND_REQ\n" );
  9613.         break;
  9614.  
  9615.       case N_UNITDATA_REQ:
  9616.         printf( "\tN_UNITDATA_REQ\n" );
  9617.         break;
  9618.  
  9619.       case N_UNITDATA_IND:
  9620.         printf( "\tN_UNITDATA_IND\n" );
  9621.         break;
  9622.  
  9623.       default:
  9624.         (void) printf( "Unknown NPI error %d", primitive->PRIM_type );
  9625.         return 0;
  9626.     }
  9627. }
  9628. #endif /* DEBUG */
  9629.  
  9630. /* it looks like signal handling is not needed with streams! */
  9631. /* x25oobh()    - handle SIGURG signals - take from isode ? */
  9632.  
  9633. #endif /* IBMX25 */
  9634.  
  9635. #ifndef NOHTTP
  9636. /*
  9637.   Which time.h files to include... See ckcdeb.h for defaults.
  9638.   Note that 0, 1, 2, or all 3 of these can be included according to
  9639.   the symbol definitions.
  9640. */
  9641. #ifndef NOTIMEH
  9642. #ifdef TIMEH
  9643. #include <time.h>
  9644. #endif /* TIMEH */
  9645. #endif /* NOTIMEH */
  9646.  
  9647. #ifndef NOSYSTIMEH
  9648. #ifdef SYSTIMEH
  9649. #include <sys/time.h>
  9650. #endif /* SYSTIMEH */
  9651. #endif /* NOSYSTIMEH */
  9652.  
  9653. #ifndef NOSYSTIMEBH
  9654. #ifdef SYSTIMEBH
  9655. #include <sys/timeb.h>
  9656. #endif /* SYSTIMEBH */
  9657. #endif /* NOSYSTIMEBH */
  9658.  
  9659. #ifndef TIMEH
  9660. #ifndef SYSTIMEH
  9661. #ifndef SYSTIMEBH
  9662. #ifdef Plan9
  9663. #include <sys/time.h>
  9664. #else
  9665. #ifdef AIX41
  9666. #include <time.h>
  9667. #else
  9668. #ifdef SUNOS4
  9669. #include <sys/time.h>
  9670. #else
  9671. #ifdef SYSTIMEH
  9672. #include <sys/time.h>
  9673. #else
  9674. #ifdef POSIX
  9675. #include <posix/time.h>
  9676. #else
  9677. #ifdef CLIX
  9678. #include <sys/time.h>
  9679. #else
  9680. #ifdef OS2
  9681. #include <time.h>
  9682. #else
  9683. #include <time.h>
  9684. /* #include <utime.h> */
  9685. #endif /* OS2 */
  9686. #endif /* CLIX */
  9687. #endif /* POSIX */
  9688. #endif /* SYSTIMEH */
  9689. #endif /* SUNOS4 */
  9690. #endif /* AIX41 */
  9691. #endif /* Plan9 */
  9692. #endif
  9693. #endif
  9694. #endif
  9695.  
  9696. #ifdef OS2
  9697. #include <sys/utime.h>
  9698. #ifdef NT
  9699. #define utimbuf _utimbuf
  9700. #endif /* NT */
  9701. #define utime   _utime
  9702. #else
  9703. #ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
  9704. #include <sys/utime.h>                  /* for extra fields required by */
  9705. #else                                   /* 88Open spec. */
  9706. #ifdef UTIMEH                           /* or <utime.h> if requested */
  9707. #include <utime.h>                      /* (SVR4, POSIX) */
  9708. #define SYSUTIMEH                       /* Use this for both cases. */
  9709. #endif /* UTIMEH */
  9710. #endif /* SYSUTIMEH */
  9711. #endif /* OS2 */
  9712.  
  9713. #ifndef HTTP_VERSION
  9714. #define HTTP_VERSION "HTTP/1.1"
  9715. #endif /* HTTP_VERSION */
  9716.  
  9717. #ifdef CMDATE2TM
  9718. time_t
  9719. #ifdef CK_ANSIC
  9720. http_date(char * date)
  9721. #else
  9722. http_date(date) char * date;
  9723. #endif /* CK_ANSIC */
  9724. /* http_date */ {
  9725.     /* HTTP dates are of the form:  "Sun, 06 Oct 1997 20:11:47 GMT" */
  9726.     /* There are two older formats which we are required to parse
  9727.      * that we currently do not:
  9728.      *
  9729.      * RFC 850:   "Sunday, 06-Oct-97 20:11:47 GMT"
  9730.      * asctime(): "Sun Nov  6 20:11:47 1997"
  9731.      *
  9732.      * However, it is required that all dates be sent in the form we
  9733.      * do accept.  The other two formats are for compatibility with
  9734.      * really old servers.
  9735.      */
  9736.     extern char cmdatebuf[18];
  9737.     struct tm t_tm;
  9738.     time_t t;
  9739.     char ldate[32];
  9740.     int j;
  9741.  
  9742.     j = ckindex(",",date,0,0,0);
  9743.     ckstrncpy(ldate,&date[j+1],25);
  9744.  
  9745.     {   /*
  9746.            cmcvtate() date changed to return a string pointer.
  9747.            fdc, 12 Aug 2001.
  9748.         */
  9749.         char * dp;
  9750.         dp = (char *)cmcvtdate(ldate,0); /* Convert to normal form */
  9751.         if (!dp)
  9752.           return(0);
  9753.         t_tm = *cmdate2tm(dp,1);
  9754.     }
  9755. /*
  9756.   From Lucas Hart, 5 Dec 2001:
  9757.   "On the systems to which I have access (SunOS 4.1.1, Solaris 8, and Tru64),
  9758.   setting tm_isdst to -1 maintains the correct timezone offsets, i.e., writes
  9759.   the specified (GMT) time if the buffer size is 21, or the contemporaneous
  9760.   localtime if the buffer size is 25.  Perhaps tm_isdst should be set in
  9761.   cmdate2tm(), rather than only in http_date."
  9762. */
  9763. #ifndef NOTM_ISDST                      /* For platforms where */
  9764.     t_tm.tm_isdst = -1;                 /* tm_isdst doesn't exist. */
  9765. #endif /* NOTM_ISDST */
  9766.  
  9767.     t = mktime(&t_tm);                  /* NOT PORTABLE */
  9768.  
  9769. #ifdef XX_TIMEZONE
  9770.     t -= _timezone;
  9771. #endif /* XX_TIMEZONE */
  9772.  
  9773.     return(t);
  9774. }
  9775. #endif /* CMDATE2TM */
  9776.  
  9777. char *
  9778. http_now() {
  9779.     static char nowstr[32];
  9780. #ifdef CMDATE2TM
  9781.     struct tm  *gmt;
  9782.     time_t ltime;                       /* NOT PORTABLE */
  9783.  
  9784.     time(<ime);
  9785.  
  9786.     gmt = gmtime(<ime);               /* PROBABLY NOT PORTABLE */
  9787.     strftime(nowstr,32,"%a, %d %b %Y %H:%M:%S GMT",gmt); /* NOT PORTABLE */
  9788.     /* not only is it not portable but it's locale-dependent */
  9789. #else
  9790. /*
  9791.   This is hopeless.  First of all, it seems that HTTP wants Day and Month
  9792.   NAMES?  In English?  Whose idea was that?  Even worse, the date/time must be
  9793.   expressed in Zulu (UTC (GMT)), and converting from local time to GMT is a
  9794.   nightmare.  Every platform does it differently, if at all -- even if we
  9795.   restrict ourselves to UNIX.  For example (quoting from recent C-Kermit edit
  9796.   history), "Fixed a longstanding bug in the BSDI version, in which incoming
  9797.   file dates were set in GMT rather than local time.  It seems in 4.4BSD,
  9798.   localtime() does not return the local time, but rather Zero Meridian (Zulu)
  9799.   time (GMT), and must be adjusted by the tm_gmtoff value."  Swell.  For
  9800.   greater appreciation of the scope of the problem, just take a look at the
  9801.   time-related #ifdefs in ckutio.c.  The only right way to do this is to add
  9802.   our own portable API for converting between local time and GMT/UTC/Zulu
  9803.   that shields us not only from UNIXisms like time_t and struct tm, but also
  9804.   the unbelievable amount of differences in time-related APIs -- e.g. is
  9805.   "timezone" an external variable or a function; which header file(s) do we
  9806.   include, etc etc etc.  It's a major project.
  9807. */
  9808.     int x;
  9809.     x = cmcvtdate("",1);
  9810.  
  9811. Evidently this code is not used -- if it is, it must be fixed to use
  9812. new (aug 2001) cmcvtdate() calling conventions.
  9813.  
  9814.     if (x < 0)
  9815.       return("");
  9816. /*  yyyymmdd hh:mm:ss */
  9817. /*  01234567890123456 */
  9818.     nowstr[0]  = 'X';                   /* 1st letter of day */
  9819.     nowstr[1]  = 'x';                   /* 2nd letter of day */
  9820.     nowstr[2]  = 'x';                   /* 3rd letter of day */
  9821.     nowstr[3]  = ',';
  9822.     nowstr[4]  = ' ';
  9823.     nowstr[5]  = cmdate[6];
  9824.     nowstr[6]  = cmdate[7];
  9825.     nowstr[7]  = ' ';
  9826.     nowstr[8]  = ' ';                   /* first letter of month */
  9827.     nowstr[9]  = ' ';                   /* second letter of month */
  9828.     nowstr[10] = ' ';                   /* third letter of month */
  9829.     nowstr[11] = ' ';
  9830.     nowstr[12] = cmdate[0];
  9831.     nowstr[13] = cmdate[1];
  9832.     nowstr[14] = cmdate[2];
  9833.     nowstr[15] = cmdate[3];
  9834.     nowstr[16] = ' ';
  9835.     nowstr[17] = cmdate[9];
  9836.     nowstr[18] = cmdate[10];
  9837.     nowstr[19] = cmdate[11];
  9838.     nowstr[20] = cmdate[12];
  9839.     nowstr[21] = cmdate[13];
  9840.     nowstr[22] = cmdate[14];
  9841.     nowstr[23] = cmdate[15];
  9842.     nowstr[24] = cmdate[16];
  9843.     nowstr[25] = ' ';
  9844.     nowstr[26] = 'G';
  9845.     nowstr[27] = 'M';
  9846.     nowstr[28] = 'T';
  9847.     nowstr[29] = '\0';
  9848. #endif /* CMDATE2TM */
  9849.     return(nowstr);
  9850. }
  9851.  
  9852. #ifndef OS2
  9853. #ifndef CK_AUTHENTICATION
  9854. /* from ckuusr.h, which this module normally doesn't include */
  9855. _PROTOTYP( int dclarray, (char, int) );
  9856. #endif /* CK_AUTHENTICATION */
  9857. #endif /* OS2 */
  9858. /*
  9859.   Assign http response pairs to given array.
  9860.   For best results, response pairs should contain no spaces.
  9861.  
  9862.   Call with:
  9863.     resp  =  pointer to response list.
  9864.     n     =  size of response list.
  9865.     array =  array letter.
  9866.   Returns:
  9867.     0 on failure.
  9868.     >= 1, size of array, on success.
  9869. */
  9870. static int
  9871. #ifdef CK_ANSIC
  9872. http_mkarray(char ** resp, int n, char array)
  9873. #else
  9874. http_mkarray(resp, n, array) char ** resp; int n; char array;
  9875. #endif /* CK_ANSIC */
  9876. {
  9877. #ifndef NOSPL
  9878.     int i, x;
  9879.     char ** ap;
  9880.     extern char ** a_ptr[];
  9881.     extern int a_dim[];
  9882.  
  9883.     if (!array || n <= 0)
  9884.       return(0);
  9885.     if ((x = dclarray(array,n)) < 0) {
  9886.         printf("?Array declaration failure\n");
  9887.         return(-9);
  9888.     }
  9889.     /* Note: argument array is 0-based but Kermit array is 1-based */
  9890.     ap = a_ptr[x];
  9891.     ap[0] = NULL;                       /* 0th element is empty */
  9892.     for (i = 1; i <= n; i++) {
  9893.         ap[i] = resp[i-1];              /* If resp elements were malloc'd */
  9894.         resp[i-1] = NULL;
  9895.     }
  9896.     a_dim[x] = n;
  9897.     return(n);
  9898. #else
  9899.     return(0);
  9900. #endif /* NOSPL */
  9901. }
  9902.  
  9903. #define HTTPHEADCNT 64
  9904. int
  9905. http_get_chunk_len()
  9906. {
  9907.     int len = 0;
  9908.     int i = 0, j = -1;
  9909.     char buf[24];
  9910.     int ch;
  9911.  
  9912.     while ((ch = http_inc(0)) >= 0 && i < 24) {
  9913.         buf[i] = ch;
  9914.         if ( buf[i] == ';' )            /* Find chunk-extension (if any) */
  9915.             j = i;
  9916.         if ( buf[i] == 10 ) {           /* found end of line */
  9917.             if (i > 0 && buf[i-1] == 13)
  9918.                 i--;
  9919.             buf[i] = '\0';
  9920.             break;
  9921.         }
  9922.         i++;
  9923.     }
  9924.     if ( i < 24 ) {                     /* buf now contains len in Hex */
  9925.         len = hextoulong(buf, j == -1 ? i : j-1);
  9926.     }
  9927.  
  9928.     return(len);
  9929. }
  9930.  
  9931. int
  9932. http_isconnected()
  9933. {
  9934.     return(httpfd != -1);
  9935. }
  9936.  
  9937. char *
  9938. http_host()
  9939. {
  9940.     return(httpfd != -1 ? http_host_port : "");
  9941. }
  9942.  
  9943. char *
  9944. http_security()
  9945. {
  9946.     if ( httpfd == -1 )
  9947.         return("NULL");
  9948. #ifdef CK_SSL
  9949.     if (tls_http_active_flag) {
  9950.         SSL_CIPHER * cipher;
  9951.         const char *cipher_list;
  9952.         static char buf[128];
  9953.         buf[0] = NUL;
  9954.         cipher = SSL_get_current_cipher(tls_http_con);
  9955.         cipher_list = SSL_CIPHER_get_name(cipher);
  9956.         SSL_CIPHER_description(cipher,buf,sizeof(buf));
  9957.         return(buf);
  9958.     }
  9959. #endif /* CK_SSL */
  9960.     return("NULL");
  9961. }
  9962.  
  9963. int
  9964. http_reopen()
  9965. {
  9966.     int rc = 0;
  9967.     char * s = NULL;                    /* strdup is not portable */
  9968.     makestr(&s,(char *)http_ip);
  9969.     rc = http_open(s,ckuitoa(http_port),http_ssl,NULL,0);
  9970.     free(s);
  9971.     return(rc);
  9972. }
  9973.  
  9974.  
  9975. int
  9976. #ifdef CK_ANSIC
  9977. http_open(char * hostname, char * svcname, int use_ssl, char * rdns_name,
  9978.           int rdns_len)
  9979. #else /* CK_ANSIC */
  9980. http_open(hostname, svcname, use_ssl, rdns_name, rdns_len)
  9981.     char * hostname;
  9982.     char * svcname;
  9983.     int    use_ssl;
  9984.     char * rdns_name;
  9985.     int    rdns_len;
  9986. #endif /* CK_ANSIC */
  9987. {
  9988.     char *p;
  9989.     int i, x, dns = 0;
  9990. #ifdef TCPSOCKET
  9991.     int isconnect = 0;
  9992. #ifdef SO_OOBINLINE
  9993.     int on = 1;
  9994. #endif /* SO_OOBINLINE */
  9995.     struct servent *service=NULL;
  9996.     struct hostent *host=NULL;
  9997.     struct sockaddr_in r_addr;
  9998.     struct sockaddr_in sin;
  9999.     struct sockaddr_in l_addr;
  10000.     GSOCKNAME_T l_slen;
  10001. #ifdef EXCELAN
  10002.     struct sockaddr_in send_socket;
  10003. #endif /* EXCELAN */
  10004.  
  10005. #ifdef INADDRX
  10006. /* inet_addr() is of type struct in_addr */
  10007. #ifdef datageneral
  10008.     extern struct in_addr inet_addr();
  10009. #else
  10010. #ifdef HPUX5WINTCP
  10011.     extern struct in_addr inet_addr();
  10012. #endif /* HPUX5WINTCP */
  10013. #endif /* datageneral */
  10014.     struct in_addr iax;
  10015. #else
  10016. #ifdef INADDR_NONE
  10017.     struct in_addr iax;
  10018. #else /* INADDR_NONE */
  10019.     long iax;
  10020. #endif /* INADDR_NONE */
  10021. #endif /* INADDRX */
  10022.  
  10023.     if ( rdns_name == NULL || rdns_len < 0 )
  10024.         rdns_len = 0;
  10025.  
  10026.     *http_ip = '\0';                     /* Initialize IP address string */
  10027.  
  10028. #ifdef DEBUG
  10029.     if (deblog) {
  10030.         debug(F110,"http_open hostname",hostname,0);
  10031.         debug(F110,"http_open svcname",svcname,0);
  10032.     }
  10033. #endif /* DEBUG */
  10034.     if (!hostname) hostname = "";
  10035.     if (!svcname) svcname = "";
  10036.     if (!*hostname || !*svcname) return(-1);
  10037.  
  10038.     service = ckgetservice(hostname,svcname,http_ip,20);
  10039.  
  10040.     if (service == NULL) {
  10041.         if ( !quiet )
  10042.             printf("?Invalid service: %s\r\n",svcname);
  10043.         return(-1);
  10044.     }
  10045.  
  10046.     /* For HTTP connections we must preserve the original hostname and */
  10047.     /* service requested so we can include them in the Host header.    */
  10048.     ckmakmsg(http_host_port,sizeof(http_host_port),hostname,":",
  10049.               ckuitoa(ntohs(service->s_port)),NULL);
  10050.     http_port = ntohs(service->s_port);
  10051.     http_ssl = use_ssl;
  10052.     debug(F111,"http_open",http_host_port,http_port);
  10053.  
  10054.     /* 'http_ip' contains the IP address to which we want to connect        */
  10055.     /* 'svcnam'   contains the service name                                 */
  10056.     /* 'service->s_port' contains the port number in network byte order     */
  10057.  
  10058.     /* If we are using an http proxy, we need to create a buffer containing */
  10059.     /*   hostname:port-number                                               */
  10060.     /* to pass to the http_connect() function.  Then we need to replace     */
  10061.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  10062.     /* with the port number of the proxy (default port 80).                 */
  10063.  
  10064.     if ( tcp_http_proxy ) {
  10065.         char namecopy[NAMECPYL];
  10066.  
  10067.         ckmakmsg(proxycopy,sizeof(proxycopy),hostname,":",
  10068.                  ckuitoa(ntohs(service->s_port)),NULL);
  10069.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  10070.  
  10071.         p = namecopy;                       /* Was a service requested? */
  10072.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  10073.         if (*p == ':') {                    /* Have a colon */
  10074.             debug(F110,"netopen name has colon",namecopy,0);
  10075.             *p++ = '\0';                    /* Get service name or number */
  10076.         } else {
  10077.             strcpy(++p,"http");
  10078.         }
  10079.  
  10080.         service = ckgetservice(namecopy,p,http_ip,20);
  10081.         if (!service) {
  10082.             fprintf(stderr, "Can't find port for service %s\n", p);
  10083. #ifdef TGVORWIN
  10084.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  10085. #else
  10086.             debug(F101,"netopen can't get service for proxy","",errno);
  10087. #endif /* TGVORWIN */
  10088.             errno = 0;                  /* (rather than mislead) */
  10089.             return(-1);
  10090.         }
  10091.     }
  10092.  
  10093.     /* Set up socket structure and get host address */
  10094.     bzero((char *)&r_addr, sizeof(r_addr));
  10095.     debug(F100,"http_open bzero ok","",0);
  10096.  
  10097. #ifdef INADDR_NONE
  10098.     debug(F101,"http_open INADDR_NONE defined","",INADDR_NONE);
  10099. #else /* INADDR_NONE */
  10100.     debug(F100,"http_open INADDR_NONE not defined","",0);
  10101. #endif /* INADDR_NONE */
  10102. #ifdef INADDRX
  10103.     debug(F100,"http_open INADDRX defined","",0);
  10104. #else /* INADDRX */
  10105.     debug(F100,"http_open INADDRX not defined","",0);
  10106. #endif /* INADDRX */
  10107.  
  10108. #ifndef NOMHHOST
  10109. #ifdef INADDRX
  10110.     iax = inet_addr(http_ip[0]?http_ip:hostname);
  10111.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  10112. #else /* INADDRX */
  10113. #ifdef INADDR_NONE
  10114.     iax.s_addr = inet_addr(http_ip[0]?http_ip:hostname);
  10115.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  10116. #else /* INADDR_NONE */
  10117. #ifndef datageneral
  10118.     iax = (unsigned int) inet_addr(http_ip[0]?http_ip:hostname);
  10119. #else
  10120.     iax = -1L;
  10121. #endif /* datageneral */
  10122.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax);
  10123. #endif /* INADDR_NONE */
  10124. #endif /* INADDRX */
  10125.  
  10126.     dns = 0;
  10127.     if (
  10128. #ifdef INADDR_NONE
  10129.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  10130. #else /* INADDR_NONE */
  10131.         iax < 0
  10132. #endif /* INADDR_NONE */
  10133.         ) {
  10134.         if (!quiet) {
  10135.             printf(" DNS Lookup... ");
  10136.             fflush(stdout);
  10137.         }
  10138.         if ((host = gethostbyname(http_ip[0] ? http_ip : hostname)) != NULL) {
  10139.             debug(F100,"http_open gethostbyname != NULL","",0);
  10140.             host = ck_copyhostent(host);
  10141.             dns = 1;                    /* Remember we performed dns lookup */
  10142.             r_addr.sin_family = host->h_addrtype;
  10143.             if (host->h_name && host->h_name[0] && (rdns_len > 0)
  10144.                  && (tcp_http_proxy == NULL)
  10145.                  )
  10146.                 ckmakmsg(rdns_name,rdns_len,host->h_name,":",svcname,NULL);
  10147.  
  10148. #ifdef HADDRLIST
  10149. #ifdef h_addr
  10150.             /* This is for trying multiple IP addresses - see <netdb.h> */
  10151.             if (!(host->h_addr_list))
  10152.               return(-1);
  10153.             bcopy(host->h_addr_list[0],
  10154.                   (caddr_t)&r_addr.sin_addr,
  10155.                   host->h_length
  10156.                   );
  10157. #else
  10158.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  10159. #endif /* h_addr */
  10160. #else  /* HADDRLIST */
  10161.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  10162. #endif /* HADDRLIST */
  10163. #ifndef EXCELAN
  10164.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  10165. #endif /* EXCELAN */
  10166.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  10167.                   (caddr_t)&r_addr.sin_addr);
  10168.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  10169.                   r_addr.sin_addr.s_addr);
  10170.             debug(F111,"BCOPY","host->h_length",host->h_length);
  10171.         }
  10172.     }
  10173. #endif /* NOMHHOST */
  10174.  
  10175.     if (!dns) {
  10176. #ifdef INADDRX
  10177. /* inet_addr() is of type struct in_addr */
  10178.         struct in_addr ina;
  10179.         unsigned long uu;
  10180.         debug(F100,"http_open gethostbyname == NULL: INADDRX","",0);
  10181.         ina = inet_addr(http_ip[0]?http_ip:hostname);
  10182.         uu = *(unsigned int *)&ina;
  10183. #else /* Not INADDRX */
  10184. /* inet_addr() is unsigned long */
  10185.         unsigned long uu;
  10186.         debug(F100,"http_open gethostbyname == NULL: Not INADDRX","",0);
  10187.         uu = inet_addr(http_ip[0]?http_ip:hostname);
  10188. #endif /* INADDRX */
  10189.         debug(F101,"http_open uu","",uu);
  10190.         if (
  10191. #ifdef INADDR_NONE
  10192.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  10193. #else   /* INADDR_NONE */
  10194.             uu != ((unsigned long)-1)
  10195. #endif /* INADDR_NONE */
  10196.             ) {
  10197.             r_addr.sin_addr.s_addr = uu;
  10198.             r_addr.sin_family = AF_INET;
  10199.         } else {
  10200. #ifdef VMS
  10201.             fprintf(stdout, "\r\n");    /* complete any previous message */
  10202. #endif /* VMS */
  10203.             fprintf(stderr, "Can't get address for %s\n",
  10204.                      http_ip[0]?http_ip:hostname);
  10205. #ifdef TGVORWIN
  10206.             debug(F101,"http_open can't get address","",socket_errno);
  10207. #else
  10208.             debug(F101,"http_open can't get address","",errno);
  10209. #endif /* TGVORWIN */
  10210.             errno = 0;                  /* Rather than mislead */
  10211.             return(-1);
  10212.         }
  10213.     }
  10214.  
  10215.     /* Get a file descriptor for the connection. */
  10216.  
  10217.     r_addr.sin_port = service->s_port;
  10218.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10219.     debug(F110,"http_open trying",http_ip,0);
  10220.     if (!quiet && *http_ip) {
  10221.         printf(" Trying %s... ", http_ip);
  10222.         fflush(stdout);
  10223.     }
  10224.  
  10225.     /* Loop to try additional IP addresses, if any. */
  10226.  
  10227.     do {
  10228. #ifdef EXCELAN
  10229.         send_socket.sin_family = AF_INET;
  10230.         send_socket.sin_addr.s_addr = 0;
  10231.         send_socket.sin_port = 0;
  10232.         if ((httpfd = socket(SOCK_STREAM, (struct sockproto *)0,
  10233.                             &send_socket, SO_REUSEADDR)) < 0)
  10234. #else  /* EXCELAN */
  10235.         if ((httpfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  10236. #endif /* EXCELAN */
  10237.             {
  10238. #ifdef EXCELAN
  10239.                 experror("TCP socket error");
  10240. #else
  10241. #ifdef TGVORWIN
  10242. #ifdef OLD_TWG
  10243.                 errno = socket_errno;
  10244. #endif /* OLD_TWG */
  10245.                 socket_perror("TCP socket error");
  10246.                 debug(F101,"http_open socket error","",socket_errno);
  10247. #else
  10248.                 perror("TCP socket error");
  10249.                 debug(F101,"http_open socket error","",errno);
  10250. #endif /* TGVORWIN */
  10251. #endif /* EXCELAN */
  10252.                 return (-1);
  10253.             }
  10254.         errno = 0;
  10255.  
  10256.        /* If a specific TCP address on the local host is desired we */
  10257.        /* must bind it to the socket.                               */
  10258. #ifndef datageneral
  10259.          if (tcp_address) {
  10260.              int s_errno;
  10261.  
  10262.              debug(F110,"http_open binding socket to",tcp_address,0);
  10263.              bzero((char *)&sin,sizeof(sin));
  10264.              sin.sin_family = AF_INET;
  10265. #ifdef INADDRX
  10266.              inaddrx = inet_addr(tcp_address);
  10267.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  10268. #else
  10269.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  10270. #endif /* INADDRX */
  10271.              sin.sin_port = 0;
  10272.              if (bind(httpfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  10273.                  s_errno = socket_errno; /* Save error code */
  10274. #ifdef TCPIPLIB
  10275.                  socket_close(httpfd);
  10276. #else /* TCPIPLIB */
  10277.                  close(httpfd);
  10278. #endif /* TCPIPLIB */
  10279.                  httpfd = -1;
  10280.                  errno = s_errno;       /* and report this error */
  10281.                  debug(F101,"http_open bind errno","",errno);
  10282.                  return(-1);
  10283.              }
  10284.          }
  10285. #endif /* datageneral */
  10286.  
  10287. /* Now connect to the socket on the other end. */
  10288.  
  10289. #ifdef EXCELAN
  10290.         if (connect(httpfd, &r_addr) < 0)
  10291. #else
  10292. #ifdef NT
  10293.           WSASafeToCancel = 1;
  10294. #endif /* NT */
  10295.         if (connect(httpfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  10296. #endif /* EXCELAN */
  10297.           {
  10298. #ifdef NT
  10299.               WSASafeToCancel = 0;
  10300. #endif /* NT */
  10301. #ifdef OS2
  10302.               i = socket_errno;
  10303. #else /* OS2 */
  10304. #ifdef TGVORWIN
  10305.               i = socket_errno;
  10306. #else
  10307.               i = errno;                /* Save error code */
  10308. #endif /* TGVORWIN */
  10309. #endif /* OS2 */
  10310. #ifdef HADDRLIST
  10311. #ifdef h_addr
  10312.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  10313.                   perror("");
  10314.                   host->h_addr_list++;
  10315.                   bcopy(host->h_addr_list[0],
  10316.                         (caddr_t)&r_addr.sin_addr,
  10317.                         host->h_length);
  10318.  
  10319.                   ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10320.                   debug(F110,"http_open h_addr_list",http_ip,0);
  10321.                   if (!quiet && *http_ip) {
  10322.                       printf(" Trying %s... ", http_ip);
  10323.                       fflush(stdout);
  10324.                   }
  10325. #ifdef TCPIPLIB
  10326.                   socket_close(httpfd); /* Close it. */
  10327. #else
  10328.                   close(httpfd);
  10329. #endif /* TCPIPLIB */
  10330.                   continue;
  10331.               }
  10332. #endif /* h_addr */
  10333. #endif  /* HADDRLIST */
  10334.               http_close();
  10335.               httpfd = -1;
  10336.               errno = i;                /* And report this error */
  10337. #ifdef EXCELAN
  10338.               if (errno) experror("http_open connect");
  10339. #else
  10340. #ifdef TGVORWIN
  10341.               debug(F101,"http_open connect error","",socket_errno);
  10342.               /* if (errno) socket_perror("http_open connect"); */
  10343. #ifdef OLD_TWG
  10344.               errno = socket_errno;
  10345. #endif /* OLD_TWG */
  10346.               if (!quiet)
  10347.                 socket_perror("http_open connect");
  10348. #else /* TGVORWIN */
  10349.               debug(F101,"http_open connect errno","",errno);
  10350. #ifdef VMS
  10351.               if (!quiet)
  10352.                 perror("\r\nFailed");
  10353. #else
  10354.               if (!quiet)
  10355.                 perror("Failed");
  10356. #endif /* VMS */
  10357. #ifdef DEC_TCPIP
  10358.               if (!quiet)
  10359.                 perror("http_open connect");
  10360. #endif /* DEC_TCPIP */
  10361. #ifdef CMU_TCPIP
  10362.               if (!quiet)
  10363.                 perror("http_open connect");
  10364. #endif /* CMU_TCPIP */
  10365. #endif /* TGVORWIN */
  10366. #endif /* EXCELAN */
  10367.               return(-1);
  10368.           }
  10369. #ifdef NT
  10370.         WSASafeToCancel = 0;
  10371. #endif /* NT */
  10372.         isconnect = 1;
  10373.     } while (!isconnect);
  10374.  
  10375. #ifdef NON_BLOCK_IO
  10376.     on = 1;
  10377.     x = socket_ioctl(httpfd,FIONBIO,&on);
  10378.     debug(F101,"http_open FIONBIO","",x);
  10379. #endif /* NON_BLOCK_IO */
  10380.  
  10381.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  10382.     /* need to attempt to connect through the proxy to the actual host */
  10383.     /* If that is successful, we have to pretend that we made a direct */
  10384.     /* connection to the actual host.                                  */
  10385.  
  10386.     if ( tcp_http_proxy ) {
  10387. #ifdef OS2
  10388.         char * agent = "Kermit 95";             /* Default user agent */
  10389. #else
  10390.         char * agent = "C-Kermit";
  10391. #endif /* OS2 */
  10392.  
  10393.         if (http_connect(httpfd,agent,NULL,
  10394.                          tcp_http_proxy_user,
  10395.                          tcp_http_proxy_pwd,
  10396.                          0,
  10397.                          proxycopy
  10398.                          ) < 0) {
  10399.             http_close();
  10400.             return(-1);
  10401.         }
  10402.     }
  10403.  
  10404. #ifdef SO_OOBINLINE
  10405.     /* See note on SO_OOBINLINE in netopen() */
  10406. #ifdef datageneral
  10407.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10408. #else
  10409. #ifdef BSD43
  10410.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10411. #else
  10412. #ifdef OSF1
  10413.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10414. #else
  10415. #ifdef POSIX
  10416.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10417. #else
  10418. #ifdef MOTSV88R4
  10419.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10420. #else
  10421. #ifdef SOLARIS
  10422. /*
  10423.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  10424.   compiling and working fine on all the others, so best not to change it.
  10425. */
  10426.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10427. #else
  10428. #ifdef OSK
  10429.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10430. #else
  10431. #ifdef OS2
  10432.     {
  10433.         int rc;
  10434.         rc = setsockopt(httpfd,
  10435.                         SOL_SOCKET,
  10436.                         SO_OOBINLINE,
  10437.                         (char *) &on,
  10438.                         sizeof on
  10439.                         );
  10440.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  10441.     }
  10442. #else
  10443. #ifdef VMS /* or, at least, VMS with gcc */
  10444.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10445. #else
  10446. #ifdef CLIX
  10447.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10448. #else
  10449.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  10450. #endif /* CLIX */
  10451. #endif /* VMS */
  10452. #endif /* OS2 */
  10453. #endif /* OSK */
  10454. #endif /* SOLARIS */
  10455. #endif /* MOTSV88R4 */
  10456. #endif /* POSIX */
  10457. #endif /* BSD43 */
  10458. #endif /* OSF1 */
  10459. #endif /* datageneral */
  10460. #endif /* SO_OOBINLINE */
  10461.  
  10462. #ifndef NOTCPOPTS
  10463. #ifndef datageneral
  10464. #ifdef SOL_SOCKET
  10465. #ifdef TCP_NODELAY
  10466.     no_delay(ttyfd,tcp_nodelay);
  10467. #endif /* TCP_NODELAY */
  10468. #ifdef SO_KEEPALIVE
  10469.     keepalive(ttyfd,tcp_keepalive);
  10470. #endif /* SO_KEEPALIVE */
  10471. #ifdef SO_LINGER
  10472.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  10473. #endif /* SO_LINGER */
  10474. #ifdef SO_SNDBUF
  10475.     sendbuf(ttyfd,tcp_sendbuf);
  10476. #endif /* SO_SNDBUF */
  10477. #ifdef SO_RCVBUF
  10478.     recvbuf(ttyfd,tcp_recvbuf);
  10479. #endif /* SO_RCVBUF */
  10480. #endif /* SOL_SOCKET */
  10481. #endif /* datageneral */
  10482. #endif /* NOTCPOPTS */
  10483.  
  10484. #ifndef datageneral
  10485.     /* Find out our own IP address. */
  10486.     /* We need the l_addr structure for [E]KLOGIN. */
  10487.     l_slen = sizeof(l_addr);
  10488.     bzero((char *)&l_addr, l_slen);
  10489. #ifndef EXCELAN
  10490.     if (!getsockname(httpfd, (struct sockaddr *)&l_addr, &l_slen)) {
  10491.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  10492.         ckstrncpy(myipaddr, s, 20);
  10493.         debug(F110,"getsockname",myipaddr,0);
  10494.     }
  10495. #endif /* EXCELAN */
  10496. #endif /* datageneral */
  10497.  
  10498. /* See note in netopen() on Reverse DNS lookups */
  10499.      if (tcp_rdns == SET_ON) {
  10500. #ifdef NT
  10501.         if (isWin95())
  10502.           sleep(1);
  10503. #endif /* NT */
  10504.         if (!quiet) {
  10505.             printf(" Reverse DNS Lookup... ");
  10506.             fflush(stdout);
  10507.         }
  10508.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  10509.             char * s;
  10510.             host = ck_copyhostent(host);
  10511.             debug(F100,"http_open gethostbyname != NULL","",0);
  10512.             if (!quiet) {
  10513.                 printf("(OK)\n");
  10514.                 fflush(stdout);
  10515.             }
  10516.             s = host->h_name;
  10517.             if (!s) {                   /* This can happen... */
  10518.                 debug(F100,"http_open host->h_name is NULL","",0);
  10519.                 s = "";
  10520.             }
  10521.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  10522.             /* The compiler says "Integral value implicitly converted to */
  10523.             /* pointer in assignment."  The prototype is right there */
  10524.             /* in <arpa/inet.h> so what's the problem? */
  10525.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  10526.             if (!*s) {                  /* No name so substitute the address */
  10527.                 debug(F100,"http_open host->h_name is empty","",0);
  10528.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  10529.                 if (!s)                 /* Trust No 1 */
  10530.                   s = "";
  10531.                 if (*s) {               /* If it worked, use this string */
  10532.                     ckstrncpy(http_ip,s,20);
  10533.                 }
  10534.                 s = http_ip;             /* Otherwise stick with the IP */
  10535.                 if (!*s)                 /* or failing that */
  10536.                   s = http_host_port;    /* the name we were called with. */
  10537.             }
  10538.             if (*s)                     /* return the rdns name */
  10539.                 ckmakmsg(rdns_name,rdns_len,s,":",svcname,NULL);
  10540.  
  10541.             if (!quiet && *s
  10542. #ifndef NOICP
  10543.                 && !doconx
  10544. #endif /* NOICP */
  10545.                 ) {
  10546.                 printf(" %s connected on port %s\n",s,
  10547.                        ckuitoa(ntohs(service->s_port)));
  10548. #ifdef BETADEBUG
  10549.                 /* This is simply for testing the DNS entries */
  10550.                 if (host->h_aliases) {
  10551.                     char ** a = host->h_aliases;
  10552.                     while (*a) {
  10553.                         printf(" alias => %s\n",*a);
  10554.                         a++;
  10555.                     }
  10556.                 }
  10557. #endif /* BETADEBUG */
  10558.             }
  10559.         } else {
  10560.             if (!quiet) printf("Failed.\n");
  10561.         }
  10562.     } else if (!quiet) printf("(OK)\n");
  10563.     if (!quiet) fflush(stdout);
  10564.  
  10565.     /* This should already have been done but just in case */
  10566.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10567.  
  10568. #ifdef CK_SSL
  10569.     if (use_ssl && ck_ssleay_is_installed()) {
  10570.         if (!ssl_http_init(hostname)) {
  10571.             if (bio_err!=NULL) {
  10572.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  10573.                 ERR_print_errors(bio_err);
  10574.             } else {
  10575.                 fflush(stderr);
  10576.                 fprintf(stderr,"ssl_tn_init() failed\n");
  10577.                 ERR_print_errors_fp(stderr);
  10578.             }
  10579.             http_close();
  10580.             return(-1);
  10581.         } else if ( ck_ssl_http_client(httpfd,hostname) < 0 ) {
  10582.             http_close();
  10583.             return(-1);
  10584.         }
  10585.     }
  10586. #endif /* CK_SSL */
  10587. #endif /* TCPSOCKET */
  10588.     return(0);                          /* Done. */
  10589. }
  10590.  
  10591. int
  10592. #ifdef CK_ANSIC
  10593. http_close(VOID)
  10594. #else /* CK_ANSIC */
  10595. http_close()
  10596. #endif /* CK_ANSIC */
  10597. {
  10598.     int x = 0;
  10599.     debug(F101,"http_close","",httpfd);
  10600.  
  10601.     if (httpfd == -1)                    /* Was open? */
  10602.       return(0);                        /* Wasn't. */
  10603.  
  10604. #ifndef OS2
  10605.     if (httpfd > -1)                     /* Was. */
  10606. #endif /* OS2 */
  10607.       {
  10608. #ifdef CK_SSL
  10609.           if (tls_http_active_flag) {
  10610.               if (ssl_debug_flag)
  10611.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  10612.               SSL_shutdown(tls_http_con);
  10613.               tls_http_active_flag = 0;
  10614.           }
  10615. #endif /* CK_SSL */
  10616. #ifdef TCPIPLIB
  10617.           x = socket_close(httpfd);      /* Close it. */
  10618. #else
  10619. #ifndef OS2
  10620.           x = close(httpfd);
  10621. #endif /* OS2 */
  10622. #endif /* TCPIPLIB */
  10623.       }
  10624.     httpfd = -1;                          /* Mark it as closed. */
  10625.     /* do not erase http_host_port, http_ip, http_port so they */
  10626.     /* can be used by http_reopen() */
  10627.     return(x);
  10628. }
  10629.  
  10630.  
  10631. /* http_tol()
  10632.  * Call with s = pointer to string, n = length.
  10633.  * Returns number of bytes actually written on success, or
  10634.  * -1 on i/o error, -2 if called improperly.
  10635.  */
  10636.  
  10637. int
  10638. http_tol(s,n) CHAR *s; int n; {
  10639.     int count = 0;
  10640.     int len = n;
  10641.     int try = 0;
  10642.  
  10643.     if (httpfd == -1) {
  10644.         debug(F100,"http_tol socket is closed","",0);
  10645.         return -1;
  10646.     }
  10647.     debug(F101,"http_tol TCPIPLIB ttnet","",ttnet);
  10648. #ifdef COMMENT
  10649.     hexdump("http_tol",s,n);
  10650. #endif /* COMMENT */
  10651.  
  10652. #ifdef CK_SSL
  10653.     if (tls_http_active_flag) {
  10654.         int error, r;
  10655.         /* Write using SSL */
  10656.       ssl_retry:
  10657.           r = SSL_write(tls_http_con, s, len /* >1024?1024:len */);
  10658.         switch (SSL_get_error(tls_http_con,r)) {
  10659.           case SSL_ERROR_NONE:
  10660.             debug(F111,"http_tol","SSL_write",r);
  10661.             if ( r == len )
  10662.                 return(n);
  10663.              s += r;
  10664.              len -= r;
  10665.              goto ssl_retry;
  10666.           case SSL_ERROR_WANT_WRITE:
  10667.             debug(F100,"http_tol SSL_ERROR_WANT_WRITE","",0);
  10668.             return(-1);
  10669.           case SSL_ERROR_WANT_READ:
  10670.             debug(F100,"http_tol SSL_ERROR_WANT_READ","",0);
  10671.             return(-1);
  10672.           case SSL_ERROR_SYSCALL:
  10673.               if ( r == 0 ) { /* EOF */
  10674.                   http_close();
  10675.                   return(-2);
  10676.               } else {
  10677.                   int rc = -1;
  10678. #ifdef NT
  10679.                   int gle = GetLastError();
  10680.                   debug(F111,"http_tol SSL_ERROR_SYSCALL",
  10681.                          "GetLastError()",gle);
  10682.                   rc = os2socketerror(gle);
  10683.                   if (rc == -1)
  10684.                       rc = -2;
  10685.                   else if ( rc == -2 )
  10686.                       return -1;
  10687. #endif /* NT */
  10688.                   return(rc);
  10689.               }
  10690.           case SSL_ERROR_WANT_X509_LOOKUP:
  10691.             debug(F100,"http_tol SSL_ERROR_WANT_X509_LOOKUP","",0);
  10692.             http_close();
  10693.             return(-2);
  10694.           case SSL_ERROR_SSL:
  10695.             debug(F100,"http_tol SSL_ERROR_SSL","",0);
  10696.             http_close();
  10697.             return(-2);
  10698.           case SSL_ERROR_ZERO_RETURN:
  10699.             debug(F100,"http_tol SSL_ERROR_ZERO_RETURN","",0);
  10700.             http_close();
  10701.             return(-2);
  10702.           default:
  10703.             debug(F100,"http_tol SSL_ERROR_?????","",0);
  10704.             http_close();
  10705.             return(-2);
  10706.         }
  10707.     }
  10708. #endif /* CK_SSL */
  10709.  
  10710.   http_tol_retry:
  10711.     try++;                              /* Increase the try counter */
  10712.  
  10713.     {
  10714. #ifdef BSDSELECT
  10715.         fd_set wfds;
  10716.         struct timeval tv;
  10717.  
  10718.         debug(F101,"http_tol BSDSELECT","",0);
  10719.         tv.tv_usec = 0L;
  10720.         tv.tv_sec=30;
  10721. #ifdef NT
  10722.         WSASafeToCancel = 1;
  10723. #endif /* NT */
  10724. #ifdef STREAMING
  10725.       do_select:
  10726. #endif /* STREAMING */
  10727.         FD_ZERO(&wfds);
  10728.         FD_SET(httpfd, &wfds);
  10729.         if (select(FD_SETSIZE, NULL,
  10730. #ifdef __DECC
  10731. #ifndef __DECC_VER
  10732.                     (int *)
  10733. #endif /* __DECC_VER */
  10734. #endif /* __DECC */
  10735.                    &wfds, NULL, &tv) < 0) {
  10736.             int s_errno = socket_errno;
  10737.             debug(F101,"http_tol select failed","",s_errno);
  10738. #ifdef BETADEBUG
  10739.             printf("http_tol select failed: %d\n", s_errno);
  10740. #endif /* BETADEBUG */
  10741. #ifdef NT
  10742.             WSASafeToCancel = 0;
  10743.             if (!win95selectbug)
  10744. #endif /* NT */
  10745.               return(-1);
  10746.         }
  10747.         if (!FD_ISSET(httpfd, &wfds)) {
  10748. #ifdef STREAMING
  10749.             if (streaming)
  10750.               goto do_select;
  10751. #endif /* STREAMING */
  10752.             debug(F111,"http_tol","!FD_ISSET",ttyfd);
  10753. #ifdef NT
  10754.             WSASafeToCancel = 0;
  10755.             if (!win95selectbug)
  10756. #endif /* NT */
  10757.               return(-1);
  10758.         }
  10759. #ifdef NT
  10760.         WSASafeToCancel = 0;
  10761. #endif /* NT */
  10762. #else /* BSDSELECT */
  10763. #ifdef IBMSELECT
  10764.         {
  10765.             int tries = 0;
  10766.             debug(F101,"http_tol IBMSELECT","",0);
  10767.             while (select(&httpfd, 0, 1, 0, 1000) != 1) {
  10768.                 int count;
  10769.                 if (tries++ >= 60) {
  10770.                     /* if after 60 seconds we can't get permission to write */
  10771.                     debug(F101,"http_tol select failed","",socket_errno);
  10772.                     return(-1);
  10773.                 }
  10774. #ifdef COMMENT
  10775.                 if ((count = http_tchk()) < 0) {
  10776.                     debug(F111,"http_tol","http_tchk()",count);
  10777.                     return(count);
  10778.                 }
  10779. #endif /* COMMENT */
  10780.             }
  10781.         }
  10782. #endif /* IBMSELECT */
  10783. #endif /* BSDSELECT */
  10784. #ifdef TCPIPLIB
  10785.         if ((count = socket_write(httpfd,s,n)) < 0) {
  10786.             int s_errno = socket_errno; /* maybe a function */
  10787.             debug(F101,"http_tol socket_write error","",s_errno);
  10788. #ifdef OS2
  10789.             if (os2socketerror(s_errno) < 0)
  10790.               return(-2);
  10791. #endif /* OS2 */
  10792.             return(-1);                 /* Call it an i/o error */
  10793.         }
  10794. #else /* TCPIPLIB */
  10795.         if ((count = write(httpfd,s,n)) < 0) {
  10796.             debug(F101,"http_tol socket_write error","",errno);
  10797.             return(-1);                 /* Call it an i/o error */
  10798.         }
  10799. #endif /* TCPIPLIB */
  10800.         if (count < n) {
  10801.             debug(F111,"http_tol socket_write",s,count);
  10802.             if (try > 25) {
  10803.                 /* don't try more than 25 times */
  10804.                 debug(F100,"http_tol tried more than 25 times","",0);
  10805.                 return(-1);
  10806.             }
  10807.             if (count > 0) {
  10808.                 s += count;
  10809.                 n -= count;
  10810.             }
  10811.             debug(F111,"http_tol retry",s,n);
  10812.             goto http_tol_retry;
  10813.         } else {
  10814.             debug(F111,"http_tol socket_write",s,count);
  10815.             return(len); /* success - return total length */
  10816.         }
  10817.     }
  10818. }
  10819.  
  10820.  
  10821. int
  10822. http_inc(timo) int timo; {
  10823.     int x=-1; unsigned char c;             /* The locals. */
  10824.  
  10825.     if (httpfd == -1) {
  10826.         debug(F100,"http_inc socket is closed","",0);
  10827.         return(-2);
  10828.     }
  10829.  
  10830. #ifdef CK_SSL
  10831.     /*
  10832.      * In the case of OpenSSL, it is possible that there is still
  10833.      * data waiting in the SSL session buffers that has not yet
  10834.      * been read by Kermit.  If this is the case we must process
  10835.      * it without calling select() because select() will not return
  10836.      * with an indication that there is data to be read from the
  10837.      * socket.  If there is no data pending in the SSL session
  10838.      * buffers then fall through to the select() code and wait for
  10839.      * some data to arrive.
  10840.      */
  10841.     if (tls_http_active_flag) {
  10842.         int error;
  10843.  
  10844.         x = SSL_pending(tls_http_con);
  10845.         if (x < 0) {
  10846.             debug(F111,"http_inc","SSL_pending error",x);
  10847.             http_close();
  10848.             return(-1);
  10849.         } else if ( x > 0 ) {
  10850.             x = SSL_read(tls_http_con, &c, 1);
  10851.             error = SSL_get_error(tls_http_con,x);
  10852.             switch (error) {
  10853.             case SSL_ERROR_NONE:
  10854.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  10855.                 if (x > 0) {
  10856. #ifdef OS2
  10857.                     ReleaseTCPIPMutex();
  10858. #endif /* OS2 */
  10859.                     return(c);          /* Return character. */
  10860.                 } else if (x < 0) {
  10861. #ifdef OS2
  10862.                     ReleaseTCPIPMutex();
  10863. #endif /* OS2 */
  10864.                     return(-1);
  10865.                 } else {
  10866.                     http_close();
  10867. #ifdef OS2
  10868.                     ReleaseTCPIPMutex();
  10869. #endif /* OS2 */
  10870.                     return(-2);
  10871.                 }
  10872.             case SSL_ERROR_WANT_WRITE:
  10873.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  10874. #ifdef OS2
  10875.                 ReleaseTCPIPMutex();
  10876. #endif /* OS2 */
  10877.                 return(-1);
  10878.             case SSL_ERROR_WANT_READ:
  10879.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  10880. #ifdef OS2
  10881.                 ReleaseTCPIPMutex();
  10882. #endif /* OS2 */
  10883.                 return(-1);
  10884.             case SSL_ERROR_SYSCALL:
  10885.                 if ( x == 0 ) { /* EOF */
  10886.                     http_close();
  10887. #ifdef OS2
  10888.                     ReleaseTCPIPMutex();
  10889. #endif /* OS2 */
  10890.                     return(-2);
  10891.                 } else {
  10892.                     int rc = -1;
  10893. #ifdef NT
  10894.                     int gle = GetLastError();
  10895.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  10896.                            "GetLastError()",gle);
  10897.                     rc = os2socketerror(gle);
  10898.                     if (rc == -1)
  10899.                         rc = -2;
  10900.                     else if ( rc == -2 )
  10901.                         return -1;
  10902. #endif /* NT */
  10903. #ifdef OS2
  10904.                     ReleaseTCPIPMutex();
  10905. #endif /* OS2 */
  10906.                     return(rc);
  10907.                 }
  10908.             case SSL_ERROR_WANT_X509_LOOKUP:
  10909.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  10910.                 http_close();
  10911. #ifdef OS2
  10912.                 ReleaseTCPIPMutex();
  10913. #endif /* OS2 */
  10914.                 return(-2);
  10915.             case SSL_ERROR_SSL:
  10916.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  10917. #ifdef COMMENT
  10918.                 http_close();
  10919. #endif /* COMMENT */
  10920. #ifdef OS2
  10921.                 ReleaseTCPIPMutex();
  10922. #endif /* OS2 */
  10923.                 return(-2);
  10924.             case SSL_ERROR_ZERO_RETURN:
  10925.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  10926.                 http_close();
  10927. #ifdef OS2
  10928.                 ReleaseTCPIPMutex();
  10929. #endif /* OS2 */
  10930.                 return(-2);
  10931.             default:
  10932.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  10933.                 http_close();
  10934. #ifdef OS2
  10935.                 ReleaseTCPIPMutex();
  10936. #endif /* OS2 */
  10937.                 return(-2);
  10938.             }
  10939.         }
  10940.     }
  10941. #endif /* CK_SSL */
  10942.     {
  10943. #ifdef BSDSELECT
  10944.         fd_set rfds;
  10945.         struct timeval tv;
  10946.         int timeout = timo < 0 ? -timo : 1000 * timo;
  10947.         debug(F101,"http_inc BSDSELECT","",timo);
  10948.  
  10949.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  10950.             int rc;
  10951.             debug(F111,"http_inc","timeout",timeout);
  10952.             /* Don't move select() initialization out of the loop. */
  10953.             FD_ZERO(&rfds);
  10954.             FD_SET(httpfd, &rfds);
  10955.             tv.tv_sec  = tv.tv_usec = 0L;
  10956.             if (timo)
  10957.                 tv.tv_usec = (long) 100000L;
  10958.             else
  10959.                 tv.tv_sec = 30;
  10960. #ifdef NT
  10961.             WSASafeToCancel = 1;
  10962. #endif /* NT */
  10963.             rc = select(FD_SETSIZE,
  10964. #ifndef __DECC
  10965.                          (fd_set *)
  10966. #endif /* __DECC */
  10967.                          &rfds, NULL, NULL, &tv);
  10968.             if (rc < 0) {
  10969.                 int s_errno = socket_errno;
  10970.                 debug(F111,"http_inc","select",rc);
  10971.                 debug(F111,"http_inc","socket_errno",s_errno);
  10972.                 if (s_errno)
  10973.                     return(-1);
  10974.             }
  10975.             debug(F111,"http_inc","select",rc);
  10976. #ifdef NT
  10977.             WSASafeToCancel = 0;
  10978. #endif /* NT */
  10979.             if (FD_ISSET(httpfd, &rfds)) {
  10980.                 x = 0;
  10981.                 break;
  10982.             } else {
  10983.                 /* If waiting forever we have no way of knowing if the */
  10984.                 /* socket closed so try writing a 0-length TCP packet  */
  10985.                 /* which should force an error if the socket is closed */
  10986.                 if (!timo) {
  10987. #ifdef TCPIPLIB
  10988.                     if ((rc = socket_write(httpfd,"",0)) < 0) {
  10989.                         int s_errno = socket_errno;
  10990.                         debug(F101,"http_inc socket_write error","",s_errno);
  10991. #ifdef OS2
  10992.                         if (os2socketerror(s_errno) < 0)
  10993.                             return(-2);
  10994. #endif /* OS2 */
  10995.                         return(-1); /* Call it an i/o error */
  10996.                     }
  10997. #else /* TCPIPLIB */
  10998.                     if ((rc = write(httpfd,"",0)) < 0) {
  10999.                         debug(F101,"http_inc socket_write error","",errno);
  11000.                         return(-1); /* Call it an i/o error */
  11001.                     }
  11002. #endif /* TCPIPLIB */
  11003.                 }
  11004.                 continue;
  11005.             }
  11006.         }
  11007. #ifdef NT
  11008.         WSASafeToCancel = 0;
  11009. #endif /* NT */
  11010. #else /* !BSDSELECT */
  11011. #ifdef IBMSELECT
  11012.  /*
  11013.   Was used by OS/2, currently not used, but might come in handy some day...
  11014.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  11015.   and timeval stuff since this is the only place where it is used.
  11016.  */
  11017.         int socket = httpfd;
  11018.         int timeout = timo < 0 ? -timo : 1000 * timo;
  11019.  
  11020.         debug(F101,"http_inc IBMSELECT","",timo);
  11021.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  11022.             if (select(&socket, 1, 0, 0, 100L) == 1) {
  11023.                 x = 0;
  11024.                 break;
  11025.             }
  11026.         }
  11027. #else /* !IBMSELECT */
  11028.         SELECT is required for this code
  11029. #endif /* IBMSELECT */
  11030. #endif /* BSDSELECT */
  11031.     }
  11032.  
  11033.     if (timo && x < 0) {        /* select() timed out */
  11034.         debug(F100,"http_inc select() timed out","",0);
  11035.         return(-1); /* Call it an i/o error */
  11036.     }
  11037.  
  11038. #ifdef CK_SSL
  11039.         if ( tls_http_active_flag ) {
  11040.             int error;
  11041.  
  11042.             x = SSL_read(tls_http_con, &c, 1);
  11043.             error = SSL_get_error(tls_http_con,x);
  11044.             switch (error) {
  11045.             case SSL_ERROR_NONE:
  11046.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  11047.                 if (x > 0) {
  11048. #ifdef OS2
  11049.                     ReleaseTCPIPMutex();
  11050. #endif /* OS2 */
  11051.                     return(c);          /* Return character. */
  11052.                 } else if (x < 0) {
  11053. #ifdef OS2
  11054.                     ReleaseTCPIPMutex();
  11055. #endif /* OS2 */
  11056.                     return(-1);
  11057.                 } else {
  11058.                     http_close();
  11059. #ifdef OS2
  11060.                     ReleaseTCPIPMutex();
  11061. #endif /* OS2 */
  11062.                     return(-2);
  11063.                 }
  11064.             case SSL_ERROR_WANT_WRITE:
  11065.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  11066. #ifdef OS2
  11067.                 ReleaseTCPIPMutex();
  11068. #endif /* OS2 */
  11069.                 return(-1);
  11070.             case SSL_ERROR_WANT_READ:
  11071.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  11072. #ifdef OS2
  11073.                 ReleaseTCPIPMutex();
  11074. #endif /* OS2 */
  11075.                 return(-1);
  11076.             case SSL_ERROR_SYSCALL:
  11077.                 if ( x == 0 ) { /* EOF */
  11078.                     http_close();
  11079. #ifdef OS2
  11080.                     ReleaseTCPIPMutex();
  11081. #endif /* OS2 */
  11082.                     return(-2);
  11083.                 } else {
  11084.                     int rc = -1;
  11085. #ifdef NT
  11086.                     int gle = GetLastError();
  11087.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  11088.                            "GetLastError()",gle);
  11089.                     rc = os2socketerror(gle);
  11090.                     if (rc == -1)
  11091.                         rc = -2;
  11092.                     else if ( rc == -2 )
  11093.                         return -1;
  11094. #endif /* NT */
  11095. #ifdef OS2
  11096.                     ReleaseTCPIPMutex();
  11097. #endif /* OS2 */
  11098.                     return(rc);
  11099.                 }
  11100.             case SSL_ERROR_WANT_X509_LOOKUP:
  11101.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  11102.                 http_close();
  11103. #ifdef OS2
  11104.                 ReleaseTCPIPMutex();
  11105. #endif /* OS2 */
  11106.                 return(-2);
  11107.             case SSL_ERROR_SSL:
  11108.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  11109. #ifdef COMMENT
  11110.                 http_close();
  11111. #endif /* COMMENT */
  11112. #ifdef OS2
  11113.                 ReleaseTCPIPMutex();
  11114. #endif /* OS2 */
  11115.                 return(-2);
  11116.             case SSL_ERROR_ZERO_RETURN:
  11117.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  11118.                 http_close();
  11119. #ifdef OS2
  11120.                 ReleaseTCPIPMutex();
  11121. #endif /* OS2 */
  11122.                 return(-2);
  11123.             default:
  11124.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  11125.                 http_close();
  11126. #ifdef OS2
  11127.                 ReleaseTCPIPMutex();
  11128. #endif /* OS2 */
  11129.                 return(-2);
  11130.             }
  11131.         }
  11132. #endif /* CK_SSL */
  11133. #ifdef TCPIPLIB
  11134.         x = socket_read(httpfd,&c,1);
  11135. #else
  11136.         x = read(httpfd,&c,1);
  11137. #endif
  11138.  
  11139.         if (x <= 0) {
  11140.             int s_errno = socket_errno;
  11141.             debug(F101,"ttbufr socket_read","",x);
  11142.             debug(F101,"ttbufr socket_errno","",s_errno);
  11143. #ifdef OS2
  11144.             if (x == 0 || os2socketerror(s_errno) < 0) {
  11145.                 http_close();
  11146.                 ReleaseTCPIPMutex();
  11147.                 return(-2);
  11148.             }
  11149.             ReleaseTCPIPMutex();
  11150.             return(-1);
  11151. #else /* OS2 */
  11152.             http_close();                      /* *** *** */
  11153.             return(-2);
  11154. #endif /* OS2 */
  11155.         }
  11156.         return(c);
  11157. }
  11158.  
  11159. void
  11160. #ifdef CK_ANSIC
  11161. http_set_code_reply(char * msg)
  11162. #else
  11163. http_set_code_reply(msg)
  11164.     char * msg;
  11165. #endif /* CK_ANSIC */
  11166. {
  11167.     char * p = msg;
  11168.     char buf[16];
  11169.     int i=0;
  11170.  
  11171.     while ( *p != SP && *p != NUL ) {
  11172.         buf[i] = *p;
  11173.         p++;
  11174.         i++;
  11175.     }
  11176.  
  11177.     http_code = atoi(buf);
  11178.  
  11179.     while ( *p == SP )
  11180.         p++;
  11181.  
  11182.     ckstrncpy(http_reply_str,p,HTTPBUFLEN);
  11183. }
  11184.  
  11185. int
  11186. #ifdef CK_ANSIC
  11187. http_get(char * agent, char ** hdrlist, char * user,
  11188.          char * pwd, char array, char * local, char * remote,
  11189.          int stdio)
  11190. #else
  11191. http_get(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11192.     char * agent; char ** hdrlist; char * user;
  11193.     char * pwd; char array; char * local; char * remote;
  11194.     int stdio;
  11195. #endif /* CK_ANSIC */
  11196. {
  11197.     char * request = NULL;
  11198.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11199.     int    ch;
  11200.     int    http_fnd = 0;
  11201.     char   buf[HTTPBUFLEN], *p;
  11202.     int    nullline;
  11203. #ifdef OS2
  11204.     struct utimbuf u_t;
  11205. #else /* OS2 */
  11206. #ifdef SYSUTIMEH
  11207.     struct utimbuf u_t;
  11208. #else
  11209.     struct utimbuf {
  11210.         time_t atime;
  11211.         time_t mtime;
  11212.     } u_t;
  11213. #endif /* SYSUTIMH */
  11214. #endif /* OS2 */
  11215.     time_t mod_t = 0;
  11216.     time_t srv_t = 0;
  11217.     time_t local_t = 0;
  11218.     char passwd[64];
  11219.     char b64in[128];
  11220.     char b64out[256];
  11221.     char * headers[HTTPHEADCNT];
  11222.     int closecon = 0;
  11223.     int chunked = 0;
  11224.     int zfile = 0;
  11225.     int first = 1;
  11226.  
  11227. #ifdef DEBUG
  11228.     if (deblog) {
  11229.         debug(F101,"http_get httpfd","",httpfd);
  11230.         debug(F110,"http_agent",agent,0);
  11231.         debug(F110,"http_user",user,0);
  11232.         debug(F110,"http_local",local,0);
  11233.         debug(F110,"http_remote",remote,0);
  11234.     }
  11235. #endif /* DEBUG */
  11236.     if (!remote) remote = "";
  11237.  
  11238.     if (httpfd == -1)
  11239.       return(-1);
  11240.  
  11241.     if (array) {
  11242.         for (i = 0; i < HTTPHEADCNT; i++)
  11243.           headers[i] = NULL;
  11244.     }
  11245.     len = 8;                            /* GET */
  11246.     len += strlen(HTTP_VERSION);
  11247.     len += strlen(remote);
  11248.     len += 16;
  11249.  
  11250.     if (hdrlist) {
  11251.         for (i = 0; hdrlist[i]; i++)
  11252.             len += strlen(hdrlist[i]) + 2;
  11253.     }
  11254.     len += (int) strlen(http_host_port) + 8;
  11255.  
  11256.     if (agent)
  11257.       len += 13 + strlen(agent);
  11258.     if (user) {
  11259.         if (!pwd) {
  11260.             readpass("Password: ",passwd,64);
  11261.             pwd = passwd;
  11262.         }
  11263.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11264.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11265.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11266.         if (j < 0)
  11267.           return(-1);
  11268.         b64out[j] = '\0';
  11269.         len += j + 24;
  11270.     }
  11271. #ifdef HTTP_CLOSE
  11272.     len += 19;                          /* Connection: close */
  11273. #endif
  11274.     len += 3;                           /* blank line + null */
  11275.  
  11276.     request = malloc(len);
  11277.     if (!request)
  11278.       return(-1);
  11279.  
  11280.     sprintf(request,"GET %s %s\r\n",remote,HTTP_VERSION);       /* safe */
  11281.     ckstrncat(request,"Host: ", len);
  11282.     ckstrncat(request,http_host_port, len);
  11283.     ckstrncat(request,"\r\n",len);
  11284.     if (agent) {
  11285.         ckstrncat(request,"User-agent: ",len);
  11286.         ckstrncat(request,agent,len);
  11287.         ckstrncat(request,"\r\n",len);
  11288.     }
  11289.     if (user) {
  11290.         ckstrncat(request,"Authorization: Basic ",len);
  11291.         ckstrncat(request,b64out,len);
  11292.         ckstrncat(request,"\r\n",len);
  11293.     }
  11294.     if ( hdrlist ) {
  11295.         for (i = 0; hdrlist[i]; i++) {
  11296.             ckstrncat(request,hdrlist[i],len);
  11297.             ckstrncat(request,"\r\n",len);
  11298.         }
  11299.     }
  11300. #ifdef HTTP_CLOSE
  11301.     ckstrncat(request,"Connection: close\r\n",len);
  11302. #endif
  11303.     ckstrncat(request,"\r\n",len);
  11304.  
  11305.   getreq:
  11306.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11307.     {
  11308.         http_close();
  11309.         if ( first ) {
  11310.             first--;
  11311.             http_reopen();
  11312.             goto getreq;
  11313.         }
  11314.         rc = -1;
  11315.         goto getexit;
  11316.     }
  11317.  
  11318.     /* Process the headers */
  11319.     local_t = time(NULL);
  11320.     nullline = 0;
  11321.     i = 0;
  11322.     len = -1;
  11323.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11324.         buf[i] = ch;
  11325.         if ( buf[i] == 10 ) { /* found end of line */
  11326.             if (i > 0 && buf[i-1] == 13)
  11327.               i--;
  11328.             if (i < 1)
  11329.               nullline = 1;
  11330.             buf[i] = '\0';
  11331.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11332.               makestr(&headers[hdcnt++],buf);
  11333.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11334.                 http_fnd = 1;
  11335.                 j = ckindex(" ",buf,0,0,0);
  11336.                 p = &buf[j];
  11337.                 while ( isspace(*p) )
  11338.                   p++;
  11339.                 switch ( p[0] ) {
  11340.                   case '1':             /* Informational message */
  11341.                     break;
  11342.                   case '2':             /* Success */
  11343.                     break;
  11344.                   case '3':             /* Redirection */
  11345.                   case '4':             /* Client failure */
  11346.                   case '5':             /* Server failure */
  11347.                   default:              /* Unknown */
  11348.                     if (!quiet)
  11349.                       printf("Failure: Server reports %s\n",p);
  11350.                     rc = -1;
  11351.                     local = NULL;
  11352.                 }
  11353.                 http_set_code_reply(p);
  11354. #ifdef CMDATE2TM
  11355.             } else if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11356.                 mod_t = http_date(&buf[15]);
  11357.             } else if (!ckstrcmp(buf,"Date",4,0)) {
  11358.                 srv_t = http_date(&buf[4]);
  11359. #endif /* CMDATE2TM */
  11360.             } else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11361.                 if ( ckindex("close",buf,11,0,0) != 0 )
  11362.                     closecon = 1;
  11363.             } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11364.                 len = atoi(&buf[16]);
  11365.             } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11366.                 if ( ckindex("chunked",buf,18,0,0) != 0 )
  11367.                     chunked = 1;
  11368.             }
  11369.             i = 0;
  11370.         } else {
  11371.             i++;
  11372.         }
  11373.     }
  11374.     if (ch < 0 && first) {
  11375.         first--;
  11376.         http_close();
  11377.         http_reopen();
  11378.         goto getreq;
  11379.     }
  11380.     if (http_fnd == 0) {
  11381.         rc = -1;
  11382.         closecon = 1;
  11383.         goto getexit;
  11384.     }
  11385.  
  11386.     /* Now we have the contents of the file */
  11387.     if ( local && local[0] ) {
  11388.         if (zopeno(ZOFILE,local,NULL,NULL))
  11389.             zfile = 1;
  11390.         else
  11391.             rc = -1;
  11392.     }
  11393.  
  11394.     if ( chunked ) {
  11395.         while ((len = http_get_chunk_len()) > 0) {
  11396.             while (len && (ch = http_inc(0)) >= 0) {
  11397.                 len--;
  11398.                 if ( zfile )
  11399.                     zchout(ZOFILE,(CHAR)ch);
  11400.                 if ( stdio )
  11401.                     conoc((CHAR)ch);
  11402.             }
  11403.             if ((ch = http_inc(0)) != CR)
  11404.                 break;
  11405.             if ((ch = http_inc(0)) != LF)
  11406.                 break;
  11407.         }
  11408.     } else {
  11409.         while (len && (ch = http_inc(0)) >= 0) {
  11410.             len--;
  11411.             if ( zfile )
  11412.                 zchout(ZOFILE,(CHAR)ch);
  11413.             if ( stdio )
  11414.                 conoc((CHAR)ch);
  11415.         }
  11416.     }
  11417.  
  11418.     if ( zfile )
  11419.         zclose(ZOFILE);
  11420.  
  11421.     if ( chunked ) {            /* Parse Trailing Headers */
  11422.         nullline = 0;
  11423.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11424.             buf[i] = ch;
  11425.             if ( buf[i] == 10 ) { /* found end of line */
  11426.                 if (i > 0 && buf[i-1] == 13)
  11427.                   i--;
  11428.                 if (i < 1)
  11429.                   nullline = 1;
  11430.                 buf[i] = '\0';
  11431.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11432.                     makestr(&headers[hdcnt++],buf);
  11433. #ifdef CMDATE2TM
  11434.                 if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11435.                     mod_t = http_date(&buf[15]);
  11436.                 } else if (!ckstrcmp(buf,"Date",4,0)) {
  11437.                     srv_t = http_date(&buf[4]);
  11438.                 }
  11439. #endif /* CMDATE2TM */
  11440.                 else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11441.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11442.                         closecon = 1;
  11443.                 }
  11444.                 i = 0;
  11445.             } else {
  11446.                 i++;
  11447.             }
  11448.         }
  11449.     }
  11450.  
  11451.     if ( zfile ) {              /* Set timestamp */
  11452. #ifdef CMDATE2TM
  11453. #ifdef OS2
  11454.         u_t.actime = srv_t ? srv_t : local_t;
  11455.         u_t.modtime = mod_t ? mod_t : local_t;
  11456. #else /* OS2 */
  11457. #ifdef SYSUTIMEH
  11458.         u_t.actime = srv_t ? srv_t : local_t;
  11459.         u_t.modtime = mod_t ? mod_t : local_t;
  11460. #else
  11461. #ifdef BSD44
  11462.         u_t[0].tv_sec = srv_t ? srv_t : local_t;
  11463.         u_t[1].tv_sec = mod_t ? mod_t : local_t;
  11464. #else
  11465.         u_t.mtime = srv_t ? srv_t : local_t;
  11466.         u_t.atime = mod_t ? mod_t : local_t;
  11467. #endif /* BSD44 */
  11468. #endif /* SYSUTIMEH */
  11469. #endif /* OS2 */
  11470.             utime(local,&u_t);
  11471. #endif /* CMDATE2TM */
  11472.     }
  11473.  
  11474.   getexit:
  11475.     if (array)
  11476.       http_mkarray(headers,hdcnt,array);
  11477.  
  11478.     if ( closecon )
  11479.         http_close();
  11480.     free(request);
  11481.     for (i = 0; i < hdcnt; i++) {
  11482.         if (headers[i])
  11483.           free(headers[i]);
  11484.     }
  11485.     return(rc);
  11486. }
  11487.  
  11488. int
  11489. #ifdef CK_ANSIC
  11490. http_head(char * agent, char ** hdrlist, char * user,
  11491.           char * pwd, char array, char * local, char * remote,
  11492.           int stdio)
  11493. #else
  11494. http_head(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11495.     char * agent; char ** hdrlist; char * user;
  11496.     char * pwd; char array; char * local; char * remote;
  11497.     int stdio;
  11498. #endif /* CK_ANSIC */
  11499. {
  11500.     char * request = NULL;
  11501.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11502.     int    ch;
  11503.     int    http_fnd = 0;
  11504.     char   buf[HTTPBUFLEN], *p;
  11505.     int    nullline;
  11506.     time_t mod_t;
  11507.     time_t srv_t;
  11508.     time_t local_t;
  11509.     char passwd[64];
  11510.     char b64in[128];
  11511.     char b64out[256];
  11512.     char * headers[HTTPHEADCNT];
  11513.     int  closecon = 0;
  11514.     int  first = 1;
  11515.  
  11516.     if (httpfd == -1)
  11517.       return(-1);
  11518.  
  11519.     if (array) {
  11520.         for (i = 0; i < HTTPHEADCNT; i++)
  11521.           headers[i] = NULL;
  11522.     }
  11523.     len = 9;                            /* HEAD */
  11524.     len += strlen(HTTP_VERSION);
  11525.     len += strlen(remote);
  11526.     len += 16;
  11527.  
  11528.     if ( hdrlist ) {
  11529.         for (i = 0; hdrlist[i]; i++)
  11530.             len += strlen(hdrlist[i]) + 2;
  11531.     }
  11532.     len += strlen(http_host_port) + 8;
  11533.  
  11534.     if (agent)
  11535.       len += 13 + strlen(agent);
  11536.     if (user) {
  11537.         if (!pwd) {
  11538.             readpass("Password: ",passwd,64);
  11539.             pwd = passwd;
  11540.         }
  11541.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11542.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11543.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11544.         if (j < 0)
  11545.           return(-1);
  11546.         b64out[j] = '\0';
  11547.         len += j + 24;
  11548.     }
  11549. #ifdef HTTP_CLOSE
  11550.     len += 19;                          /* Connection: close */
  11551. #endif
  11552.     len += 3;                           /* blank line + null */
  11553.  
  11554.     request = (char *)malloc(len);
  11555.     if (!request)
  11556.       return(-1);
  11557.  
  11558.     sprintf(request,"HEAD %s %s\r\n",remote,HTTP_VERSION);
  11559.     ckstrncat(request,"Host: ", len);
  11560.     ckstrncat(request,http_host_port, len);
  11561.     ckstrncat(request,"\r\n",len);
  11562.     if (agent) {
  11563.         ckstrncat(request,"User-agent: ",len);
  11564.         ckstrncat(request,agent,len);
  11565.         ckstrncat(request,"\r\n",len);
  11566.     }
  11567.     if (user) {
  11568.         ckstrncat(request,"Authorization: Basic ",len);
  11569.         ckstrncat(request,b64out,len);
  11570.         ckstrncat(request,"\r\n",len);
  11571.     }
  11572.     if ( hdrlist ) {
  11573.         for (i = 0; hdrlist[i]; i++) {
  11574.             ckstrncat(request,hdrlist[i],len);
  11575.             ckstrncat(request,"\r\n",len);
  11576.         }
  11577.     }
  11578. #ifdef HTTP_CLOSE
  11579.     ckstrncat(request,"Connection: close\r\n",len);
  11580. #endif
  11581.     ckstrncat(request,"\r\n",len);
  11582.  
  11583.     if ( local && local[0] ) {
  11584.         if (!zopeno(ZOFILE,local,NULL,NULL)) {
  11585.             free(request);
  11586.             return(-1);
  11587.         }
  11588.     }
  11589.  
  11590.   headreq:
  11591.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11592.     {
  11593.         http_close();
  11594.         if ( first ) {
  11595.             first--;
  11596.             http_reopen();
  11597.             goto headreq;
  11598.         }
  11599.         rc = -1;
  11600.         goto headexit;
  11601.     }
  11602.  
  11603.     /* Process the headers */
  11604.  
  11605.     local_t = time(NULL);
  11606.     nullline = 0;
  11607.     i = 0;
  11608.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11609.         buf[i] = ch;
  11610.         if (buf[i] == 10) {             /* found end of line */
  11611.             if (i > 0 && buf[i-1] == 13)
  11612.               i--;
  11613.             if (i < 1)
  11614.               nullline = 1;
  11615.             buf[i] = '\0';
  11616.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11617.               makestr(&headers[hdcnt++],buf);
  11618.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11619.                 http_fnd = 1;
  11620.                 j = ckindex(" ",buf,0,0,0);
  11621.                 p = &buf[j];
  11622.                 while (isspace(*p))
  11623.                   p++;
  11624.                 switch (p[0]) {
  11625.                   case '1':             /* Informational message */
  11626.                     break;
  11627.                   case '2':             /* Success */
  11628.                     break;
  11629.                   case '3':             /* Redirection */
  11630.                   case '4':             /* Client failure */
  11631.                   case '5':             /* Server failure */
  11632.                   default:              /* Unknown */
  11633.                     if (!quiet)
  11634.                       printf("Failure: Server reports %s\n",p);
  11635.                     rc = -1;
  11636.                 }
  11637.                 http_set_code_reply(p);
  11638.             } else {
  11639.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11640.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11641.                         closecon = 1;
  11642.                 }
  11643.                 if ( local && local[0] ) {
  11644.                     zsout(ZOFILE,buf);
  11645.                     zsout(ZOFILE,"\r\n");
  11646.                 }
  11647.                 if (stdio)
  11648.                     printf("%s\r\n",buf);
  11649.             }
  11650.             i = 0;
  11651.         } else {
  11652.             i++;
  11653.         }
  11654.     }
  11655.     if (ch < 0 && first) {
  11656.         first--;
  11657.         http_close();
  11658.         http_reopen();
  11659.         goto headreq;
  11660.     }
  11661.     if ( http_fnd == 0 )
  11662.         rc = -1;
  11663.  
  11664.     if (array)
  11665.       http_mkarray(headers,hdcnt,array);
  11666.  
  11667.   headexit:
  11668.     if ( local && local[0] )
  11669.         zclose(ZOFILE);
  11670.     if (closecon)
  11671.         http_close();
  11672.     free(request);
  11673.     for (i = 0; i < hdcnt; i++) {
  11674.         if (headers[i])
  11675.           free(headers[i]);
  11676.     }
  11677.     return(rc);
  11678. }
  11679.  
  11680. int
  11681. #ifdef CK_ANSIC
  11682. http_index(char * agent, char ** hdrlist, char * user, char * pwd,
  11683.              char array, char * local, char * remote, int stdio)
  11684. #else
  11685. http_index(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11686.     char * agent; char ** hdrlist; char * user; char * pwd;
  11687.     char array; char * local; char * remote; int stdio;
  11688. #endif /* CK_ANSIC */
  11689. {
  11690.     char * request = NULL;
  11691.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11692.     int    ch;
  11693.     int    http_fnd = 0;
  11694.     char   buf[HTTPBUFLEN], *p;
  11695.     int    nullline;
  11696.     time_t mod_t;
  11697.     time_t srv_t;
  11698.     time_t local_t;
  11699.     char passwd[64];
  11700.     char b64in[128];
  11701.     char b64out[256];
  11702.     char * headers[HTTPHEADCNT];
  11703.     int  closecon = 0;
  11704.     int  chunked = 0;
  11705.     int  zfile = 0;
  11706.     int  first = 1;
  11707.  
  11708.     if (httpfd == -1)
  11709.       return(-1);
  11710.  
  11711.     if (array) {
  11712.         for (i = 0; i < HTTPHEADCNT; i++)
  11713.           headers[i] = NULL;
  11714.     }
  11715.     len = 10;                            /* INDEX */
  11716.     len += strlen(HTTP_VERSION);
  11717.     len += strlen(remote);
  11718.     len += 16;
  11719.  
  11720.     if ( hdrlist ) {
  11721.         for (i = 0; hdrlist[i]; i++)
  11722.             len += strlen(hdrlist[i]) + 2;
  11723.     }
  11724.     len += strlen(http_host_port) + 8;
  11725.  
  11726.     if (agent)
  11727.         len += 13 + strlen(agent);
  11728.     if (user) {
  11729.         if (!pwd) {
  11730.             readpass("Password: ",passwd,64);
  11731.             pwd = passwd;
  11732.         }
  11733.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11734.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11735.         memset(pwd,0,strlen(pwd));
  11736.         if (j < 0)
  11737.           return(-1);
  11738.         b64out[j] = '\0';
  11739.         len += j + 24;
  11740.     }
  11741. #ifdef HTTP_CLOSE
  11742.     len += 19;                          /* Connection: close */
  11743. #endif
  11744.     len += 3;                           /* blank line + null */
  11745.  
  11746.     request = malloc(len);
  11747.     if (!request)
  11748.       return(-1);
  11749.  
  11750.     sprintf(request,"INDEX %s\r\n",HTTP_VERSION);
  11751.     ckstrncat(request,"Host: ", len);
  11752.     ckstrncat(request,http_host_port, len);
  11753.     ckstrncat(request,"\r\n",len);
  11754.     if (agent) {
  11755.         ckstrncat(request,"User-agent: ",len);
  11756.         ckstrncat(request,agent,len);
  11757.         ckstrncat(request,"\r\n",len);
  11758.     }
  11759.     if (user) {
  11760.         ckstrncat(request,"Authorization: Basic ",len);
  11761.         ckstrncat(request,b64out,len);
  11762.         ckstrncat(request,"\r\n",len);
  11763.     }
  11764.     if ( hdrlist ) {
  11765.         for (i = 0; hdrlist[i]; i++) {
  11766.             ckstrncat(request,hdrlist[i],len);
  11767.             ckstrncat(request,"\r\n",len);
  11768.         }
  11769.     }
  11770. #ifdef HTTP_CLOSE
  11771.     ckstrncat(request,"Connection: close\r\n",len);
  11772. #endif
  11773.     ckstrncat(request,"\r\n",len);
  11774.   indexreq:
  11775.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11776.     {
  11777.         http_close();
  11778.         if ( first ) {
  11779.             first--;
  11780.             http_reopen();
  11781.             goto indexreq;
  11782.         }
  11783.         rc = -1;
  11784.         goto indexexit;
  11785.     }
  11786.  
  11787.     /* Process the headers */
  11788.     local_t = time(NULL);
  11789.     nullline = 0;
  11790.     i = 0;
  11791.     len = -1;
  11792.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11793.         buf[i] = ch;
  11794.         if (buf[i] == 10) {             /* found end of line */
  11795.             if (i > 0 && buf[i-1] == 13)
  11796.               i--;
  11797.             if (i < 1)
  11798.               nullline = 1;
  11799.             buf[i] = '\0';
  11800.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11801.               makestr(&headers[hdcnt++],buf);
  11802.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11803.                 http_fnd = 1;
  11804.                 j = ckindex(" ",buf,0,0,0);
  11805.                 p = &buf[j];
  11806.                 while (isspace(*p))
  11807.                   p++;
  11808.                 switch ( p[0] ) {
  11809.                   case '1':             /* Informational message */
  11810.                     break;
  11811.                   case '2':             /* Success */
  11812.                     break;
  11813.                   case '3':             /* Redirection */
  11814.                   case '4':             /* Client failure */
  11815.                   case '5':             /* Server failure */
  11816.                   default:              /* Unknown */
  11817.                     if (!quiet)
  11818.                       printf("Failure: Server reports %s\n",p);
  11819.                     rc = -1;
  11820.                 }
  11821.                 http_set_code_reply(p);
  11822.             } else if ( !nullline ) {
  11823.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11824.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11825.                         closecon = 1;
  11826.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11827.                     len = atoi(&buf[16]);
  11828.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11829.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  11830.                         chunked = 1;
  11831.                 }
  11832.                 printf("%s\n",buf);
  11833.             }
  11834.             i = 0;
  11835.         } else {
  11836.             i++;
  11837.         }
  11838.     }
  11839.  
  11840.     if (ch < 0 && first) {
  11841.         first--;
  11842.         http_close();
  11843.         http_reopen();
  11844.         goto indexreq;
  11845.     }
  11846.     if ( http_fnd == 0 ) {
  11847.         rc = -1;
  11848.         closecon = 1;
  11849.         goto indexexit;
  11850.     }
  11851.  
  11852.     /* Now we have the contents of the file */
  11853.     if ( local && local[0] ) {
  11854.         if (zopeno(ZOFILE,local,NULL,NULL))
  11855.             zfile = 1;
  11856.         else
  11857.             rc = -1;
  11858.     }
  11859.  
  11860.     if ( chunked ) {
  11861.         while ((len = http_get_chunk_len()) > 0) {
  11862.             while (len && (ch = http_inc(0)) >= 0) {
  11863.                 len--;
  11864.                 if ( zfile )
  11865.                     zchout(ZOFILE,(CHAR)ch);
  11866.                 if ( stdio )
  11867.                     conoc((CHAR)ch);
  11868.             }
  11869.             if ((ch = http_inc(0)) != CR)
  11870.                 break;
  11871.             if ((ch = http_inc(0)) != LF)
  11872.                 break;
  11873.         }
  11874.     } else {
  11875.         while (len && (ch = http_inc(0)) >= 0) {
  11876.             len--;
  11877.             if ( zfile )
  11878.                 zchout(ZOFILE,(CHAR)ch);
  11879.             if ( stdio )
  11880.                 conoc((CHAR)ch);
  11881.         }
  11882.     }
  11883.  
  11884.     if ( zfile )
  11885.         zclose(ZOFILE);
  11886.  
  11887.     if ( chunked ) {            /* Parse Trailing Headers */
  11888.         nullline = 0;
  11889.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11890.             buf[i] = ch;
  11891.             if ( buf[i] == 10 ) { /* found end of line */
  11892.                 if (i > 0 && buf[i-1] == 13)
  11893.                   i--;
  11894.                 if (i < 1)
  11895.                   nullline = 1;
  11896.                 buf[i] = '\0';
  11897.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11898.                     makestr(&headers[hdcnt++],buf);
  11899.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11900.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11901.                         closecon = 1;
  11902.                 }
  11903.                 i = 0;
  11904.             } else {
  11905.                 i++;
  11906.             }
  11907.         }
  11908.     }
  11909.     rc = 0;
  11910.  
  11911.   indexexit:
  11912.     if (array)
  11913.       http_mkarray(headers,hdcnt,array);
  11914.  
  11915.     if (closecon)
  11916.         http_close();
  11917.     free(request);
  11918.     for (i = 0; i < hdcnt; i++) {
  11919.         if (headers[i])
  11920.           free(headers[i]);
  11921.     }
  11922.     return(rc);
  11923. }
  11924.  
  11925. int
  11926. #ifdef CK_ANSIC
  11927. http_put(char * agent, char ** hdrlist, char * mime, char * user,
  11928.          char * pwd, char array, char * local, char * remote,
  11929.          char * dest, int stdio)
  11930. #else
  11931. http_put(agent, hdrlist, mime, user, pwd, array, local, remote, dest, stdio)
  11932.     char * agent; char ** hdrlist; char * mime; char * user;
  11933.     char * pwd; char array; char * local; char * remote; char * dest;
  11934.     int stdio;
  11935. #endif /* CK_ANSIC */
  11936. {
  11937.     char * request=NULL;
  11938.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11939.     int    ch;
  11940.     int    http_fnd = 0;
  11941.     char   buf[HTTPBUFLEN], *p;
  11942.     int    nullline;
  11943.     time_t mod_t;
  11944.     time_t srv_t;
  11945.     time_t local_t;
  11946.     char passwd[64];
  11947.     char b64in[128];
  11948.     char b64out[256];
  11949.     int  filelen;
  11950.     char * headers[HTTPHEADCNT];
  11951.     int  closecon = 0;
  11952.     int  chunked = 0;
  11953.     int  first = 1;
  11954.     int  zfile = 0;
  11955.  
  11956.     if (httpfd == -1)
  11957.       return(-1);
  11958.     if (!mime) mime = "";
  11959.     if (!remote) remote = "";
  11960.     if (!local) local = "";
  11961.     if (!*local) return(-1);
  11962.  
  11963.     if (array) {
  11964.         for (i = 0; i < HTTPHEADCNT; i++)
  11965.           headers[i] = NULL;
  11966.     }
  11967.     filelen = zchki(local);
  11968.     if (filelen < 0)
  11969.       return(-1);
  11970.  
  11971.     /* Compute length of request header */
  11972.     len = 8;                            /* PUT */
  11973.     len += strlen(HTTP_VERSION);
  11974.     len += strlen(remote);
  11975.     len += 16;
  11976.  
  11977.     if ( hdrlist ) {
  11978.         for (i = 0; hdrlist[i]; i++)
  11979.             len += strlen(hdrlist[i]) + 2;
  11980.     }
  11981.     len += strlen(http_host_port) + 8;
  11982.  
  11983.     if (agent)
  11984.       len += 13 + strlen(agent);
  11985.     if (user) {
  11986.         if (!pwd) {
  11987.             readpass("Password: ",passwd,64);
  11988.             pwd = passwd;
  11989.         }
  11990.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11991.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11992.         memset(pwd,0,strlen(pwd));
  11993.         if (j < 0)
  11994.           return(-1);
  11995.         b64out[j] = '\0';
  11996.         len += j + 24;
  11997.     }
  11998.     len += 16 + strlen(mime);           /* Content-type: */
  11999.     len += 32;                          /* Content-length: */
  12000.     len += 32;                          /* Date: */
  12001. #ifdef HTTP_CLOSE
  12002.     len += 19;                          /* Connection: close */
  12003. #endif
  12004.     len += 3;                           /* blank line + null */
  12005.  
  12006.     request = malloc(len);
  12007.     if (!request)
  12008.       return(-1);
  12009.  
  12010.     sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
  12011.     ckstrncat(request,"Date: ",len);
  12012. #ifdef CMDATE2TM
  12013.     ckstrncat(request,http_now(),len);
  12014. #else
  12015.     strcat(request,...);
  12016. #endif /* CMDATE2TM */
  12017.     ckstrncat(request,"\r\n",len);
  12018.     ckstrncat(request,"Host: ", len);
  12019.     ckstrncat(request,http_host_port, len);
  12020.     ckstrncat(request,"\r\n",len);
  12021.     if (agent) {
  12022.         ckstrncat(request,"User-agent: ",len);
  12023.         ckstrncat(request,agent,len);
  12024.         ckstrncat(request,"\r\n",len);
  12025.     }
  12026.     if (user) {
  12027.         ckstrncat(request,"Authorization: Basic ",len);
  12028.         ckstrncat(request,b64out,len);
  12029.         ckstrncat(request,"\r\n",len);
  12030.     }
  12031.     if ( hdrlist ) {
  12032.         for (i = 0; hdrlist[i]; i++) {
  12033.             ckstrncat(request,hdrlist[i],len);
  12034.             ckstrncat(request,"\r\n",len);
  12035.         }
  12036.     }
  12037.     ckstrncat(request,"Content-type: ",len);
  12038.     ckstrncat(request,mime,len);
  12039.     ckstrncat(request,"\r\n",len);
  12040.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  12041.     ckstrncat(request,buf,len);
  12042. #ifdef HTTP_CLOSE
  12043.     ckstrncat(request,"Connection: close\r\n",len);
  12044. #endif
  12045.     ckstrncat(request,"\r\n",len);
  12046.  
  12047.     /* Now we have the contents of the file */
  12048.     if (zopeni(ZIFILE,local)) {
  12049.  
  12050.       putreq:
  12051.         if (http_tol((CHAR *)request,strlen(request)) <= 0) { /* Send request */
  12052.             http_close();
  12053.             if ( first ) {
  12054.                 first--;
  12055.                 http_reopen();
  12056.                 goto putreq;
  12057.             }
  12058.             zclose(ZIFILE);
  12059.             rc = -1;
  12060.             goto putexit;
  12061.         }
  12062.         /* Request headers have been sent */
  12063.  
  12064.         i = 0;
  12065.         while (zchin(ZIFILE,&ch) == 0) {
  12066.             buf[i++] = ch;
  12067.             if (i == HTTPBUFLEN) {
  12068.                 if (http_tol((CHAR *)buf,HTTPBUFLEN) <= 0) {
  12069.                     http_close();
  12070.                     if ( first ) {
  12071.                         first--;
  12072.                         http_reopen();
  12073.                         goto putreq;
  12074.                     }
  12075.                 }
  12076.                 i = 0;
  12077.             }
  12078.         }
  12079.         if (i > 0) {
  12080.             if (http_tol((CHAR *)buf,i) < 0) {
  12081.                 http_close();
  12082.                 if ( first ) {
  12083.                     first--;
  12084.                     http_reopen();
  12085.                     goto putreq;
  12086.                 }
  12087.             }
  12088.         }
  12089.         zclose(ZIFILE);
  12090.  
  12091.         /* Process the response headers */
  12092.         local_t = time(NULL);
  12093.         nullline = 0;
  12094.         i = 0;
  12095.         len = -1;
  12096.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12097.             buf[i] = ch;
  12098.             if (buf[i] == 10) {         /* found end of line */
  12099.                 if (i > 0 && buf[i-1] == 13)
  12100.                   i--;
  12101.                 if (i < 1)
  12102.                   nullline = 1;
  12103.                 buf[i] = '\0';
  12104.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12105.                   makestr(&headers[hdcnt++],buf);
  12106.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  12107.                     http_fnd = 1;
  12108.                     j = ckindex(" ",buf,0,0,0);
  12109.                     p = &buf[j];
  12110.                     while (isspace(*p))
  12111.                       p++;
  12112.                     switch (p[0]) {
  12113.                       case '1':         /* Informational message */
  12114.                         break;
  12115.                       case '2':         /* Success */
  12116.                         break;
  12117.                       case '3':         /* Redirection */
  12118.                       case '4':         /* Client failure */
  12119.                       case '5':         /* Server failure */
  12120.                       default:          /* Unknown */
  12121.                         if (!quiet)
  12122.                           printf("Failure: Server reports %s\n",p);
  12123.                         rc = -1;
  12124.                     }
  12125.                     http_set_code_reply(p);
  12126.                 } else {
  12127.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12128.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12129.                             closecon = 1;
  12130.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12131.                         len = atoi(&buf[16]);
  12132.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12133.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  12134.                             chunked = 1;
  12135.                     }
  12136.                     if ( stdio )
  12137.                         printf("%s\n",buf);
  12138.                 }
  12139.                 i = 0;
  12140.             } else {
  12141.                 i++;
  12142.             }
  12143.         }
  12144.         if (ch < 0 && first) {
  12145.             first--;
  12146.             http_close();
  12147.             http_reopen();
  12148.             goto putreq;
  12149.         }
  12150.         if ( http_fnd == 0 ) {
  12151.             closecon = 1;
  12152.             rc = -1;
  12153.             goto putexit;
  12154.         }
  12155.  
  12156.         /* Any response data? */
  12157.         if ( dest && dest[0] ) {
  12158.             if (zopeno(ZOFILE,dest,NULL,NULL))
  12159.                 zfile = 1;
  12160.             else
  12161.                 rc = -1;
  12162.         }
  12163.  
  12164.         if ( chunked ) {
  12165.             while ((len = http_get_chunk_len()) > 0) {
  12166.                 while (len && (ch = http_inc(0)) >= 0) {
  12167.                     len--;
  12168.                     if ( zfile )
  12169.                         zchout(ZOFILE,(CHAR)ch);
  12170.                     if ( stdio )
  12171.                         conoc((CHAR)ch);
  12172.                 }
  12173.                 if ((ch = http_inc(0)) != CR)
  12174.                     break;
  12175.                 if ((ch = http_inc(0)) != LF)
  12176.                     break;
  12177.             }
  12178.         } else {
  12179.             while (len && (ch = http_inc(0)) >= 0) {
  12180.                 len--;
  12181.                 if ( zfile )
  12182.                     zchout(ZOFILE,(CHAR)ch);
  12183.                 if ( stdio )
  12184.                     conoc((CHAR)ch);
  12185.             }
  12186.         }
  12187.  
  12188.         if ( zfile )
  12189.             zclose(ZOFILE);
  12190.  
  12191.         if ( chunked ) {            /* Parse Trailing Headers */
  12192.             nullline = 0;
  12193.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12194.                 buf[i] = ch;
  12195.                 if ( buf[i] == 10 ) { /* found end of line */
  12196.                     if (i > 0 && buf[i-1] == 13)
  12197.                       i--;
  12198.                     if (i < 1)
  12199.                       nullline = 1;
  12200.                     buf[i] = '\0';
  12201.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  12202.                         makestr(&headers[hdcnt++],buf);
  12203.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12204.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12205.                             closecon = 1;
  12206.                     }
  12207.                     i = 0;
  12208.                 } else {
  12209.                     i++;
  12210.                 }
  12211.             }
  12212.         }
  12213.     } else {
  12214.         rc = -1;
  12215.     }
  12216.  
  12217.   putexit:
  12218.     if ( array )
  12219.         http_mkarray(headers,hdcnt,array);
  12220.  
  12221.     if (closecon)
  12222.         http_close();
  12223.     free(request);
  12224.     for (i = 0; i < hdcnt; i++) {
  12225.         if (headers[i])
  12226.           free(headers[i]);
  12227.     }
  12228.     return(rc);
  12229. }
  12230.  
  12231. int
  12232. #ifdef CK_ANSIC
  12233. http_delete(char * agent, char ** hdrlist, char * user,
  12234.           char * pwd, char array, char * remote)
  12235. #else
  12236. http_delete(agent, hdrlist, user, pwd, array, remote)
  12237.     char * agent; char ** hdrlist; char * user;
  12238.     char * pwd; char array; char * remote;
  12239. #endif /* CK_ANSIC */
  12240. {
  12241.     char * request=NULL;
  12242.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12243.     int    ch;
  12244.     int    http_fnd = 0;
  12245.     char   buf[HTTPBUFLEN], *p;
  12246.     int    nullline;
  12247.     time_t mod_t;
  12248.     time_t srv_t;
  12249.     time_t local_t;
  12250.     char passwd[64];
  12251.     char b64in[128];
  12252.     char b64out[256];
  12253.     char * headers[HTTPHEADCNT];
  12254.     int  closecon = 0;
  12255.     int  chunked = 0;
  12256.     int  first = 1;
  12257.  
  12258.     if (httpfd == -1)
  12259.       return(-1);
  12260.  
  12261.     if (array) {
  12262.         for (i = 0; i < HTTPHEADCNT; i++)
  12263.           headers[i] = NULL;
  12264.     }
  12265.  
  12266.     /* Compute length of request header */
  12267.     len = 11;                            /* DELETE */
  12268.     len += strlen(HTTP_VERSION);
  12269.     len += strlen(remote);
  12270.     len += 16;
  12271.  
  12272.     if ( hdrlist ) {
  12273.         for (i = 0; hdrlist[i]; i++)
  12274.             len += strlen(hdrlist[i]) + 2;
  12275.     }
  12276.     len += strlen(http_host_port) + 8;
  12277.  
  12278.     if (agent)
  12279.       len += 13 + strlen(agent);
  12280.     if (user) {
  12281.         if (!pwd) {
  12282.             readpass("Password: ",passwd,64);
  12283.             pwd = passwd;
  12284.         }
  12285.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12286.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12287.         memset(pwd,0,strlen(pwd));
  12288.         if (j < 0)
  12289.           return(-1);
  12290.         b64out[j] = '\0';
  12291.         len += j + 24;
  12292.     }
  12293.     len += 32;                          /* Date: */
  12294. #ifdef HTTP_CLOSE
  12295.     len += 19;                          /* Connection: close */
  12296. #endif
  12297.     len += 3;                           /* blank line + null */
  12298.  
  12299.     request = malloc(len);
  12300.     if (!request)
  12301.       return(-1);
  12302.  
  12303.     sprintf(request,"DELETE %s %s\r\n",remote,HTTP_VERSION);
  12304.     ckstrncat(request,"Date: ",len);
  12305. #ifdef CMDATE2TM
  12306.     ckstrncat(request,http_now(),len);
  12307. #else
  12308.     strcat(request,...);
  12309. #endif /* CMDATE2TM */
  12310.     ckstrncat(request,"\r\n",len);
  12311.     ckstrncat(request,"Host: ", len);
  12312.     ckstrncat(request,http_host_port, len);
  12313.     ckstrncat(request,"\r\n",len);
  12314.     if (agent) {
  12315.         ckstrncat(request,"User-agent: ",len);
  12316.         ckstrncat(request,agent,len);
  12317.         ckstrncat(request,"\r\n",len);
  12318.     }
  12319.     if (user) {
  12320.         ckstrncat(request,"Authorization: Basic ",len);
  12321.         ckstrncat(request,b64out,len);
  12322.         ckstrncat(request,"\r\n",len);
  12323.     }
  12324.     if ( hdrlist ) {
  12325.         for (i = 0; hdrlist[i]; i++) {
  12326.             ckstrncat(request,hdrlist[i],len);
  12327.             ckstrncat(request,"\r\n",len);
  12328.         }
  12329.     }
  12330. #ifdef HTTP_CLOSE
  12331.     ckstrncat(request,"Connection: close\r\n",len);
  12332. #endif
  12333.     ckstrncat(request,"\r\n",len);
  12334.   delreq:
  12335.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  12336.     {
  12337.         http_close();
  12338.         if ( first ) {
  12339.             first--;
  12340.             http_reopen();
  12341.             goto delreq;
  12342.         }
  12343.         rc = -1;
  12344.         goto delexit;
  12345.     }
  12346.  
  12347.     /* Process the response headers */
  12348.     local_t = time(NULL);
  12349.     nullline = 0;
  12350.     i = 0;
  12351.     len = -1;
  12352.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12353.         buf[i] = ch;
  12354.         if (buf[i] == 10) {         /* found end of line */
  12355.             if (i > 0 && buf[i-1] == 13)
  12356.               i--;
  12357.             if (i < 1)
  12358.               nullline = 1;
  12359.             buf[i] = '\0';
  12360.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12361.                 makestr(&headers[hdcnt++],buf);
  12362.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12363.                 http_fnd = 1;
  12364.                 j = ckindex(" ",buf,0,0,0);
  12365.                 p = &buf[j];
  12366.                 while (isspace(*p))
  12367.                   p++;
  12368.                 switch (p[0]) {
  12369.                   case '1':             /* Informational message */
  12370.                     break;
  12371.                   case '2':             /* Success */
  12372.                     break;
  12373.                   case '3':             /* Redirection */
  12374.                   case '4':             /* Client failure */
  12375.                   case '5':             /* Server failure */
  12376.                   default:              /* Unknown */
  12377.                     if (!quiet)
  12378.                       printf("Failure: Server reports %s\n",p);
  12379.                     rc = -1;
  12380.                 }
  12381.                 http_set_code_reply(p);
  12382.             } else {
  12383.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12384.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12385.                         closecon = 1;
  12386.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12387.                     len = atoi(&buf[16]);
  12388.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12389.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  12390.                         chunked = 1;
  12391.                 }
  12392.                 printf("%s\n",buf);
  12393.             }
  12394.             i = 0;
  12395.         } else {
  12396.             i++;
  12397.         }
  12398.     }
  12399.     if (ch < 0 && first) {
  12400.         first--;
  12401.         http_close();
  12402.         http_reopen();
  12403.         goto delreq;
  12404.     }
  12405.     if ( http_fnd == 0 ) {
  12406.         rc = -1;
  12407.         closecon = 1;
  12408.         goto delexit;
  12409.     }
  12410.  
  12411.     /* Any response data? */
  12412.     if ( chunked ) {
  12413.         while ((len = http_get_chunk_len()) > 0) {
  12414.             while (len && (ch = http_inc(0)) >= 0) {
  12415.                 len--;
  12416.                 conoc((CHAR)ch);
  12417.             }
  12418.             if ((ch = http_inc(0)) != CR)
  12419.                 break;
  12420.             if ((ch = http_inc(0)) != LF)
  12421.                 break;
  12422.         }
  12423.     } else {
  12424.         while (len && (ch = http_inc(0)) >= 0) {
  12425.             len--;
  12426.             conoc((CHAR)ch);
  12427.         }
  12428.     }
  12429.  
  12430.     if ( chunked ) {            /* Parse Trailing Headers */
  12431.         nullline = 0;
  12432.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12433.             buf[i] = ch;
  12434.             if ( buf[i] == 10 ) { /* found end of line */
  12435.                 if (i > 0 && buf[i-1] == 13)
  12436.                   i--;
  12437.                 if (i < 1)
  12438.                   nullline = 1;
  12439.                 buf[i] = '\0';
  12440.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12441.                     makestr(&headers[hdcnt++],buf);
  12442.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12443.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12444.                         closecon = 1;
  12445.                 }
  12446.                 i = 0;
  12447.             } else {
  12448.                 i++;
  12449.             }
  12450.         }
  12451.     }
  12452.  
  12453.   delexit:
  12454.     if (array)
  12455.         http_mkarray(headers,hdcnt,array);
  12456.  
  12457.     if (closecon)
  12458.         http_close();
  12459.     free(request);
  12460.     for (i = 0; i < hdcnt; i++) {
  12461.         if (headers[i])
  12462.           free(headers[i]);
  12463.     }
  12464.     return(rc);
  12465. }
  12466.  
  12467. int
  12468. #ifdef CK_ANSIC
  12469. http_post(char * agent, char ** hdrlist, char * mime, char * user,
  12470.           char * pwd, char array, char * local, char * remote,
  12471.           char * dest, int stdio)
  12472. #else
  12473. http_post(agent, hdrlist, mime, user, pwd, array, local, remote, dest,
  12474.           stdio)
  12475.     char * agent; char ** hdrlist; char * mime; char * user;
  12476.     char * pwd; char array; char * local; char * remote; char * dest;
  12477.     int stdio;
  12478. #endif /* CK_ANSIC */
  12479. {
  12480.     char * request=NULL;
  12481.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12482.     int    ch;
  12483.     int    http_fnd = 0;
  12484.     char   buf[HTTPBUFLEN], *p;
  12485.     int    nullline;
  12486.     time_t mod_t;
  12487.     time_t srv_t;
  12488.     time_t local_t;
  12489.     char passwd[64];
  12490.     char b64in[128];
  12491.     char b64out[256];
  12492.     int  filelen;
  12493.     char * headers[HTTPHEADCNT];
  12494.     int  closecon = 0;
  12495.     int  chunked = 0;
  12496.     int  zfile = 0;
  12497.     int  first = 1;
  12498.  
  12499.     if (httpfd == -1)
  12500.       return(-1);
  12501.  
  12502.     if (array) {
  12503.         for (i = 0; i < HTTPHEADCNT; i++)
  12504.           headers[i] = NULL;
  12505.     }
  12506.     filelen = zchki(local);
  12507.     if (filelen < 0)
  12508.       return(-1);
  12509.  
  12510.     /* Compute length of request header */
  12511.     len = 9;                            /* POST */
  12512.     len += strlen(HTTP_VERSION);
  12513.     len += strlen(remote);
  12514.     len += 16;
  12515.  
  12516.     if ( hdrlist ) {
  12517.         for (i = 0; hdrlist[i]; i++)
  12518.             len += strlen(hdrlist[i]) + 2;
  12519.     }
  12520.     len += strlen(http_host_port) + 8;
  12521.  
  12522.     if (agent)
  12523.       len += 13 + strlen(agent);
  12524.     if (user) {
  12525.         if (!pwd) {
  12526.             readpass("Password: ",passwd,64);
  12527.             pwd = passwd;
  12528.         }
  12529.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12530.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12531.         memset(pwd,0,strlen(pwd));
  12532.         if (j < 0)
  12533.           return(-1);
  12534.         b64out[j] = '\0';
  12535.         len += j + 24;
  12536.     }
  12537.     len += 16 + strlen(mime);           /* Content-type: */
  12538.     len += 32;                          /* Content-length: */
  12539.     len += 32;                          /* Date: */
  12540. #ifdef HTTP_CLOSE
  12541.     len += 19;                          /* Connection: close */
  12542. #endif
  12543.     len += 3;                           /* blank line + null */
  12544.  
  12545.     request = malloc(len);
  12546.     if (!request)
  12547.       return(-1);
  12548.  
  12549.     sprintf(request,"POST %s %s\r\n",remote,HTTP_VERSION);
  12550.     ckstrncat(request,"Date: ",len);
  12551.     ckstrncat(request,http_now(),len);
  12552.     ckstrncat(request,"\r\n",len);
  12553.     ckstrncat(request,"Host: ", len);
  12554.     ckstrncat(request,http_host_port, len);
  12555.     ckstrncat(request,"\r\n",len);
  12556.     if (agent) {
  12557.         ckstrncat(request,"User-agent: ",len);
  12558.         ckstrncat(request,agent,len);
  12559.         ckstrncat(request,"\r\n",len);
  12560.     }
  12561.     if (user) {
  12562.         ckstrncat(request,"Authorization: Basic ",len);
  12563.         ckstrncat(request,b64out,len);
  12564.         ckstrncat(request,"\r\n",len);
  12565.     }
  12566.     if ( hdrlist ) {
  12567.         for (i = 0; hdrlist[i]; i++) {
  12568.             ckstrncat(request,hdrlist[i],len);
  12569.             ckstrncat(request,"\r\n",len);
  12570.         }
  12571.     }
  12572.     ckstrncat(request,"Content-type: ",len);
  12573.     ckstrncat(request,mime,len);
  12574.     ckstrncat(request,"\r\n",len);
  12575. #ifdef HTTP_CLOSE
  12576.     ckstrncat(request,"Connection: close\r\n",len);
  12577. #endif
  12578.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  12579.     ckstrncat(request,buf,len);
  12580.     ckstrncat(request,"\r\n",len);
  12581.     ckstrncat(request,"\r\n",len);
  12582.  
  12583.     /* Now we have the contents of the file */
  12584.   postopen:
  12585.     if (zopeni(ZIFILE,local)) {
  12586.       postreq:
  12587.         if (http_tol((CHAR *)request,strlen(request)) < 0)
  12588.         {
  12589.             http_close();
  12590.             if ( first ) {
  12591.                 first--;
  12592.                 http_reopen();
  12593.                 goto postreq;
  12594.             }
  12595.             rc = -1;
  12596.             zclose(ZIFILE);
  12597.             goto postexit;
  12598.         }
  12599.  
  12600.         i = 0;
  12601.         while (zchin(ZIFILE,&ch) == 0) {
  12602.             buf[i++] = ch;
  12603.             if (i == HTTPBUFLEN) {
  12604.                 http_tol((CHAR *)buf,HTTPBUFLEN);
  12605.                 i = 0;
  12606.             }
  12607.         }
  12608.         if (i > 0)
  12609.           http_tol((CHAR *)buf,HTTPBUFLEN);
  12610.         zclose(ZIFILE);
  12611.  
  12612.         /* Process the response headers */
  12613.         local_t = time(NULL);
  12614.         nullline = 0;
  12615.         i = 0;
  12616.         len = -1;
  12617.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12618.             buf[i] = ch;
  12619.             if (buf[i] == 10) {         /* found end of line */
  12620.                 if (i > 0 && buf[i-1] == 13)
  12621.                   i--;
  12622.                 if (i < 1)
  12623.                   nullline = 1;
  12624.                 buf[i] = '\0';
  12625.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12626.                   makestr(&headers[hdcnt++],buf);
  12627.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  12628.                     http_fnd = 1;
  12629.                     j = ckindex(" ",buf,0,0,0);
  12630.                     p = &buf[j];
  12631.                     while (isspace(*p))
  12632.                       p++;
  12633.                     switch (p[0]) {
  12634.                       case '1':         /* Informational message */
  12635.                         break;
  12636.                       case '2':         /* Success */
  12637.                         break;
  12638.                       case '3':         /* Redirection */
  12639.                       case '4':         /* Client failure */
  12640.                       case '5':         /* Server failure */
  12641.                       default:          /* Unknown */
  12642.                         if (!quiet)
  12643.                           printf("Failure: Server reports %s\n",p);
  12644.                         rc = -1;
  12645.                     }
  12646.                     http_set_code_reply(p);
  12647.                 } else {
  12648.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12649.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12650.                             closecon = 1;
  12651.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12652.                         len = atoi(&buf[16]);
  12653.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12654.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  12655.                             chunked = 1;
  12656.                     }
  12657.                     if (stdio)
  12658.                         printf("%s\n",buf);
  12659.                 }
  12660.                 i = 0;
  12661.             } else {
  12662.                 i++;
  12663.             }
  12664.         }
  12665.         if (ch < 0 && first) {
  12666.             first--;
  12667.             http_close();
  12668.             http_reopen();
  12669.             goto postopen;
  12670.         }
  12671.         if (http_fnd == 0) {
  12672.             rc = -1;
  12673.             closecon = 1;
  12674.             goto postexit;
  12675.         }
  12676.  
  12677.         /* Any response data? */
  12678.         if ( dest && dest[0] ) {
  12679.             if (zopeno(ZOFILE,dest,NULL,NULL))
  12680.                 zfile = 1;
  12681.             else
  12682.                 rc = -1;
  12683.         }
  12684.  
  12685.         if ( chunked ) {
  12686.             while ((len = http_get_chunk_len()) > 0) {
  12687.                 while (len && (ch = http_inc(0)) >= 0) {
  12688.                     len--;
  12689.                     if ( zfile )
  12690.                         zchout(ZOFILE,(CHAR)ch);
  12691.                     if ( stdio )
  12692.                         conoc((CHAR)ch);
  12693.                 }
  12694.                 if ((ch = http_inc(0)) != CR)
  12695.                     break;
  12696.                 if ((ch = http_inc(0)) != LF)
  12697.                     break;
  12698.             }
  12699.         } else {
  12700.             while (len && (ch = http_inc(0)) >= 0) {
  12701.                 len--;
  12702.                 if ( zfile )
  12703.                     zchout(ZOFILE,(CHAR)ch);
  12704.                 if ( stdio )
  12705.                     conoc((CHAR)ch);
  12706.             }
  12707.         }
  12708.  
  12709.         if ( zfile )
  12710.             zclose(ZOFILE);
  12711.  
  12712.         if ( chunked ) {            /* Parse Trailing Headers */
  12713.             nullline = 0;
  12714.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12715.                 buf[i] = ch;
  12716.                 if ( buf[i] == 10 ) { /* found end of line */
  12717.                     if (i > 0 && buf[i-1] == 13)
  12718.                       i--;
  12719.                     if (i < 1)
  12720.                       nullline = 1;
  12721.                     buf[i] = '\0';
  12722.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  12723.                         makestr(&headers[hdcnt++],buf);
  12724.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12725.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12726.                             closecon = 1;
  12727.                     }
  12728.                     i = 0;
  12729.                 } else {
  12730.                     i++;
  12731.                 }
  12732.             }
  12733.         }
  12734.     } else {
  12735.         rc = -1;
  12736.     }
  12737.  
  12738.   postexit:
  12739.     if (array)
  12740.         http_mkarray(headers,hdcnt,array);
  12741.     if (closecon)
  12742.         http_close();
  12743.     free(request);
  12744.     for (i = 0; i < hdcnt; i++) {
  12745.         if (headers[i])
  12746.           free(headers[i]);
  12747.     }
  12748.     return(rc);
  12749. }
  12750.  
  12751. int
  12752. #ifdef CK_ANSIC
  12753. http_connect(int socket, char * agent, char ** hdrlist, char * user,
  12754.              char * pwd, char array, char * host_port)
  12755. #else
  12756. http_connect(socket, agent, hdrlist, user, pwd, array, host_port)
  12757.     int socket;
  12758.     char * agent; char ** hdrlist; char * user;
  12759.     char * pwd; char array; char * host_port;
  12760. #endif /* CK_ANSIC */
  12761. {
  12762.     char * request=NULL;
  12763.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12764.     int    http_fnd = 0;
  12765.     char   buf[HTTPBUFLEN], *p, ch;
  12766.     int    nullline;
  12767.     time_t mod_t;
  12768.     time_t srv_t;
  12769.     time_t local_t;
  12770.     char passwd[64];
  12771.     char b64in[128];
  12772.     char b64out[256];
  12773.     char * headers[HTTPHEADCNT];
  12774.     int    connected = 0;
  12775.     int    chunked = 0;
  12776.  
  12777.     tcp_http_proxy_errno = 0;
  12778.  
  12779.     if (socket == -1)
  12780.       return(-1);
  12781.  
  12782.     if (array) {
  12783.         for (i = 0; i < HTTPHEADCNT; i++)
  12784.           headers[i] = NULL;
  12785.     }
  12786.  
  12787.     /* Compute length of request header */
  12788.     len = 12;                            /* CONNECT */
  12789.     len += strlen(HTTP_VERSION);
  12790.     len += strlen(host_port);
  12791.     len += (int) strlen(http_host_port) + 8;
  12792.     len += 16;
  12793.     len += strlen("Proxy-Connection: Keep-Alive\r\n");
  12794.     if ( hdrlist ) {
  12795.         for (i = 0; hdrlist[i]; i++)
  12796.             len += strlen(hdrlist[i]) + 2;
  12797.     }
  12798.     if (agent)
  12799.       len += 13 + strlen(agent);
  12800.     if (user) {
  12801.         if (!pwd) {
  12802.             readpass("Password: ",passwd,64);
  12803.             pwd = passwd;
  12804.         }
  12805.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12806.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12807.         memset(pwd,0,strlen(pwd));
  12808.         if (j < 0)
  12809.           return(-1);
  12810.         b64out[j] = '\0';
  12811.         len += j + 72;
  12812.     }
  12813.     len += 32;                          /* Date: */
  12814.     len += 3;                           /* blank line + null */
  12815.  
  12816.     request = malloc(len);
  12817.     if (!request)
  12818.       return(-1);
  12819.  
  12820.     sprintf(request,"CONNECT %s %s\r\n",host_port,HTTP_VERSION);
  12821.     ckstrncat(request,"Date: ",len);
  12822. #ifdef CMDATE2TM
  12823.     ckstrncat(request,http_now(),len);
  12824. #else
  12825.     strcat(request,...);
  12826. #endif /* CMDATE2TM */
  12827.     ckstrncat(request,"\r\n",len);
  12828.     ckstrncat(request,"Host: ", len);
  12829.     ckstrncat(request,http_host_port, len);
  12830.     ckstrncat(request,"\r\n",len);
  12831.     if (agent) {
  12832.         ckstrncat(request,"User-agent: ",len);
  12833.         ckstrncat(request,agent,len);
  12834.         ckstrncat(request,"\r\n",len);
  12835.     }
  12836.     if (user) {
  12837.         ckstrncat(request,"Proxy-authorization: Basic ",len);
  12838.         ckstrncat(request,b64out,len);
  12839.         ckstrncat(request,"\r\n",len);
  12840.         ckstrncat(request,"Extension: Security/Remote-Passphrase\r\n",len);
  12841.     }
  12842.     ckstrncat(request,"Proxy-Connection: Keep-Alive\r\n",len);
  12843.     if ( hdrlist ) {
  12844.         for (i = 0; hdrlist[i]; i++) {
  12845.             ckstrncat(request,hdrlist[i],len);
  12846.             ckstrncat(request,"\r\n",len);
  12847.         }
  12848.     }
  12849.     ckstrncat(request,"\r\n",len);
  12850.     len = strlen(request);
  12851.  
  12852. #ifdef TCPIPLIB
  12853.     /* Send request */
  12854.     if (socket_write(socket,(CHAR *)request,strlen(request)) < 0) {
  12855.       rc = -1;
  12856.       goto connexit;
  12857.     }
  12858. #else
  12859.     if (write(socket,(CHAR *)request,strlen(request)) < 0) { /* Send request */
  12860.         rc = -1;
  12861.         goto connexit;
  12862.     }
  12863. #endif /* TCPIPLIB */
  12864.  
  12865.     /* Process the response headers */
  12866.     local_t = time(NULL);
  12867.     nullline = 0;
  12868.     i = 0;
  12869.     while (!nullline &&
  12870. #ifdef TCPIPLIB
  12871.            (socket_read(socket,&ch,1) == 1) &&
  12872. #else
  12873.            (read(socket,&ch,1) == 1) &&
  12874. #endif /* TCPIPLIB */
  12875.            i < HTTPBUFLEN) {
  12876.         buf[i] = ch;
  12877.         if (buf[i] == 10) {         /* found end of line */
  12878.             if (i > 0 && buf[i-1] == 13)
  12879.               i--;
  12880.             if (i < 1)
  12881.               nullline = 1;
  12882.             buf[i] = '\0';
  12883.  
  12884.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12885.                 makestr(&headers[hdcnt++],buf);
  12886.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12887.                 http_fnd = 1;
  12888.                 j = ckindex(" ",buf,0,0,0);
  12889.                 p = &buf[j];
  12890.                 while (isspace(*p))
  12891.                   p++;
  12892.                 tcp_http_proxy_errno = atoi(p);
  12893.                 switch (p[0]) {
  12894.                   case '1':             /* Informational message */
  12895.                     break;
  12896.                   case '2':             /* Success */
  12897.                     connected = 1;
  12898.                     break;
  12899.                   case '3':             /* Redirection */
  12900.                   case '4':             /* Client failure */
  12901.                   case '5':             /* Server failure */
  12902.                   default:              /* Unknown */
  12903.                     if (!quiet)
  12904.                       printf("Failure: Server reports %s\n",p);
  12905.                     rc = -1;
  12906.                 }
  12907.                 http_set_code_reply(p);
  12908.             } else {
  12909.                 printf("%s\n",buf);
  12910.             }
  12911.             i = 0;
  12912.         } else {
  12913.             i++;
  12914.         }
  12915.     }
  12916.     if ( http_fnd == 0 )
  12917.         rc = -1;
  12918.  
  12919.     if (array)
  12920.         http_mkarray(headers,hdcnt,array);
  12921.  
  12922.   connexit:
  12923.     if ( !connected ) {
  12924.         if ( socket == ttyfd ) {
  12925.             ttclos(0);
  12926.         }
  12927.         else if ( socket == httpfd ) {
  12928.             http_close();
  12929.         }
  12930.     }
  12931.  
  12932.     free(request);
  12933.     for (i = 0; i < hdcnt; i++) {
  12934.         if (headers[i])
  12935.           free(headers[i]);
  12936.     }
  12937.     return(rc);
  12938. }
  12939. #endif /* NOHTTP */
  12940.  
  12941. #ifdef CK_DNS_SRV
  12942.  
  12943. #define INCR_CHECK(x,y) x += y; if (x > size + answer.bytes) goto dnsout
  12944. #define CHECK(x,y) if (x + y > size + answer.bytes) goto dnsout
  12945. #define NTOHSP(x,y) x[0] << 8 | x[1]; x += y
  12946.  
  12947. #ifndef CKQUERYTYPE
  12948. #ifdef UNIXWARE
  12949. #ifndef UW7
  12950. #define CKQUERYTYPE CHAR
  12951. #endif /* UW7 */
  12952. #endif /* UNIXWARE */
  12953. #endif /* CKQUERYTYPE */
  12954.  
  12955. #ifndef CKQUERYTYPE
  12956. #define CKQUERYTYPE char
  12957. #endif /* CKQUERYTYPE */
  12958.  
  12959. /* 1 is success, 0 is failure */
  12960. int
  12961. locate_srv_dns(host, service, protocol, addr_pp, naddrs)
  12962.     char *host;
  12963.     char *service;
  12964.     char *protocol;
  12965.     struct sockaddr **addr_pp;
  12966.     int *naddrs;
  12967. {
  12968.     int nout, j, count;
  12969.     union {
  12970.         unsigned char bytes[2048];
  12971.         HEADER hdr;
  12972.     } answer;
  12973.     unsigned char *p=NULL;
  12974.     CKQUERYTYPE query[MAX_DNS_NAMELEN];
  12975. #ifdef CK_ANSIC
  12976.     const char * h;
  12977. #else
  12978.     char * h;
  12979. #endif /* CK_ANSIC */
  12980.     struct sockaddr *addr = NULL;
  12981.     struct sockaddr_in *sin = NULL;
  12982.     struct hostent *hp = NULL;
  12983.     int type, class;
  12984.     int priority, weight, size, len, numanswers, numqueries, rdlen;
  12985.     unsigned short port;
  12986. #ifdef CK_ANSIC
  12987.     const
  12988. #endif /* CK_ANSIC */
  12989.       int hdrsize = sizeof(HEADER);
  12990.     struct srv_dns_entry {
  12991.         struct srv_dns_entry *next;
  12992.         int priority;
  12993.         int weight;
  12994.         unsigned short port;
  12995.         char *host;
  12996.     };
  12997.     struct srv_dns_entry *head = NULL;
  12998.     struct srv_dns_entry *srv = NULL, *entry = NULL;
  12999.     char * s = NULL;
  13000.  
  13001.     nout = 0;
  13002.     addr = (struct sockaddr *) malloc(sizeof(struct sockaddr));
  13003.     if (addr == NULL)
  13004.       return 0;
  13005.  
  13006.     count = 1;
  13007.  
  13008.     /*
  13009.      * First build a query of the form:
  13010.      *
  13011.      *   service.protocol.host
  13012.      *
  13013.      * which will most likely be something like:
  13014.      *
  13015.      *   _telnet._tcp.host
  13016.      *
  13017.      */
  13018.     if (((int)strlen(service) + strlen(protocol) + strlen(host) + 5)
  13019.         > MAX_DNS_NAMELEN
  13020.         )
  13021.       goto dnsout;
  13022.  
  13023.     /* Realm names don't (normally) end with ".", but if the query
  13024.        doesn't end with "." and doesn't get an answer as is, the
  13025.        resolv code will try appending the local domain.  Since the
  13026.        realm names are absolutes, let's stop that.
  13027.  
  13028.        But only if a name has been specified.  If we are performing
  13029.        a search on the prefix alone then the intention is to allow
  13030.        the local domain or domain search lists to be expanded.
  13031.     */
  13032.     h = host + strlen (host);
  13033.     ckmakxmsg(query, sizeof(query), "_",service,"._",protocol,".", host,
  13034.               ((h > host) && (h[-1] != '.')?".":NULL),
  13035.                NULL,NULL,NULL,NULL,NULL);
  13036.  
  13037.     size = res_search(query, C_IN, T_SRV, answer.bytes, sizeof(answer.bytes));
  13038.  
  13039.     if (size < hdrsize)
  13040.       goto dnsout;
  13041.  
  13042.     /* We got a reply - See how many answers it contains. */
  13043.  
  13044.     p = answer.bytes;
  13045.  
  13046.     numqueries = ntohs(answer.hdr.qdcount);
  13047.     numanswers = ntohs(answer.hdr.ancount);
  13048.  
  13049.     p += sizeof(HEADER);
  13050.  
  13051.     /*
  13052.      * We need to skip over all of the questions, so we have to iterate
  13053.      * over every query record.  dn_expand() is able to tell us the size
  13054.      * of compressed DNS names, so we use it.
  13055.      */
  13056.     while (numqueries--) {
  13057.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  13058.         if (len < 0)
  13059.           goto dnsout;
  13060.         INCR_CHECK(p, len + 4);
  13061.     }
  13062.  
  13063.     /*
  13064.      * We're now pointing at the answer records.  Only process them if
  13065.      * they're actually T_SRV records (they might be CNAME records,
  13066.      * for instance).
  13067.      *
  13068.      * But in a DNS reply, if you get a CNAME you always get the associated
  13069.      * "real" RR for that CNAME.  RFC 1034, 3.6.2:
  13070.      *
  13071.      * CNAME RRs cause special action in DNS software.  When a name server
  13072.      * fails to find a desired RR in the resource set associated with the
  13073.      * domain name, it checks to see if the resource set consists of a CNAME
  13074.      * record with a matching class.  If so, the name server includes the CNAME
  13075.      * record in the response and restarts the query at the domain name
  13076.      * specified in the data field of the CNAME record.  The one exception to
  13077.      * this rule is that queries which match the CNAME type are not restarted.
  13078.      *
  13079.      * In other words, CNAMEs do not need to be expanded by the client.
  13080.      */
  13081.     while (numanswers--) {
  13082.  
  13083.         /* First is the name; use dn_expand() to get the compressed size. */
  13084.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  13085.         if (len < 0)
  13086.           goto dnsout;
  13087.         INCR_CHECK(p, len);
  13088.  
  13089.         CHECK(p,2);                     /* Query type */
  13090.         type = NTOHSP(p,2);
  13091.  
  13092.         CHECK(p, 6);                    /* Query class */
  13093.         class = NTOHSP(p,6);            /* Also skip over 4-byte TTL */
  13094.  
  13095.         CHECK(p,2);                     /* Record data length */
  13096.         rdlen = NTOHSP(p,2);
  13097.         /*
  13098.          * If this is an SRV record, process it.  Record format is:
  13099.          *
  13100.          * Priority
  13101.          * Weight
  13102.          * Port
  13103.          * Server name
  13104.          */
  13105.         if (class == C_IN && type == T_SRV) {
  13106.             CHECK(p,2);
  13107.             priority = NTOHSP(p,2);
  13108.             CHECK(p, 2);
  13109.             weight = NTOHSP(p,2);
  13110.             CHECK(p, 2);
  13111.             port = NTOHSP(p,2);
  13112.             len = dn_expand(answer.
  13113.                             bytes,
  13114.                             answer.bytes + size,
  13115.                             p,
  13116.                             query,
  13117.                             sizeof(query)
  13118.                             );
  13119.             if (len < 0)
  13120.               goto dnsout;
  13121.             INCR_CHECK(p, len);
  13122.             /*
  13123.              * We got everything.  Insert it into our list, but make sure
  13124.              * it's in the right order.  Right now we don't do anything
  13125.              * with the weight field
  13126.              */
  13127.             srv = (struct srv_dns_entry *)malloc(sizeof(struct srv_dns_entry));
  13128.             if (srv == NULL)
  13129.               goto dnsout;
  13130.  
  13131.             srv->priority = priority;
  13132.             srv->weight = weight;
  13133.             srv->port = port;
  13134.             makestr(&s,(char *)query);  /* strdup() is not portable */
  13135.             srv->host = s;
  13136.  
  13137.             if (head == NULL || head->priority > srv->priority) {
  13138.                 srv->next = head;
  13139.                 head = srv;
  13140.             } else
  13141.                 /*
  13142.                  * Confusing.  Insert an entry into this spot only if:
  13143.                  *  . The next person has a higher priority (lower
  13144.                  *    priorities are preferred), or:
  13145.                  *  . There is no next entry (we're at the end)
  13146.                  */
  13147.               for (entry = head; entry != NULL; entry = entry->next)
  13148.                 if ((entry->next &&
  13149.                      entry->next->priority > srv->priority) ||
  13150.                     entry->next == NULL) {
  13151.                     srv->next = entry->next;
  13152.                     entry->next = srv;
  13153.                     break;
  13154.                 }
  13155.         } else
  13156.           INCR_CHECK(p, rdlen);
  13157.     }
  13158.  
  13159.     /*
  13160.      * Now we've got a linked list of entries sorted by priority.
  13161.      * Start looking up A records and returning addresses.
  13162.      */
  13163.     if (head == NULL)
  13164.       goto dnsout;
  13165.  
  13166.     for (entry = head; entry != NULL; entry = entry->next) {
  13167.         hp = gethostbyname(entry->host);
  13168.         if (hp != 0) {
  13169.  
  13170.             /* Watch out - memset() and memcpy() are not portable... */
  13171.  
  13172.             switch (hp->h_addrtype) {
  13173.               case AF_INET:
  13174.                 for (j = 0; hp->h_addr_list[j]; j++) {
  13175.                     sin = (struct sockaddr_in *) &addr[nout++];
  13176.                     memset ((char *) sin, 0, sizeof (struct sockaddr));
  13177.                     sin->sin_family = hp->h_addrtype;
  13178.                     sin->sin_port = htons(entry->port);
  13179.                     memcpy((char *) &sin->sin_addr,
  13180.                            (char *) hp->h_addr_list[j],
  13181.                            sizeof(struct in_addr));             /* safe */
  13182.                     if (nout + 1 >= count) {
  13183.                         count += 5;
  13184.                         addr = (struct sockaddr *)
  13185.                           realloc((char *) addr,
  13186.                                   sizeof(struct sockaddr) * count);
  13187.                         if (!addr)
  13188.                           goto dnsout;
  13189.                     }
  13190.                 }
  13191.                 break;
  13192.               default:
  13193.                 break;
  13194.             }
  13195.         }
  13196.     }
  13197.     for (entry = head; entry != NULL;) {
  13198.         free(entry->host);
  13199.         entry->host = NULL;
  13200.         srv = entry;
  13201.         entry = entry->next;
  13202.         free(srv);
  13203.         srv = NULL;
  13204.     }
  13205.  
  13206.   dnsout:
  13207.     if (srv)
  13208.       free(srv);
  13209.  
  13210.     if (nout == 0) {                    /* No good servers */
  13211.         if (addr)
  13212.           free(addr);
  13213.         return 0;
  13214.     }
  13215.     *addr_pp = addr;
  13216.     *naddrs = nout;
  13217.     return 1;
  13218. }
  13219. #undef INCR_CHECK
  13220. #undef CHECK
  13221. #undef NTOHSP
  13222.  
  13223. #define INCR_CHECK(x, y) x += y; if (x > size + answer.bytes) \
  13224.                          return 0
  13225. #define CHECK(x, y) if (x + y > size + answer.bytes) \
  13226.                          return 0
  13227. #define NTOHSP(x, y) x[0] << 8 | x[1]; x += y
  13228.  
  13229. int
  13230. locate_txt_rr(prefix, name, retstr)
  13231.     char *prefix, *name;
  13232.     char **retstr;
  13233. {
  13234.     union {
  13235.         unsigned char bytes[2048];
  13236.         HEADER hdr;
  13237.     } answer;
  13238.     unsigned char *p;
  13239.     char host[MAX_DNS_NAMELEN], *h;
  13240.     int size;
  13241.     int type, class, numanswers, numqueries, rdlen, len;
  13242.  
  13243.     /*
  13244.      * Form our query, and send it via DNS
  13245.      */
  13246.  
  13247.     if (name == NULL || name[0] == '\0') {
  13248.         strcpy(host,prefix);
  13249.     } else {
  13250.         if ( strlen(prefix) + strlen(name) + 3 > MAX_DNS_NAMELEN )
  13251.             return 0;
  13252.  
  13253.         /* Realm names don't (normally) end with ".", but if the query
  13254.            doesn't end with "." and doesn't get an answer as is, the
  13255.            resolv code will try appending the local domain.  Since the
  13256.            realm names are absolutes, let's stop that.
  13257.  
  13258.            But only if a name has been specified.  If we are performing
  13259.            a search on the prefix alone then the intention is to allow
  13260.            the local domain or domain search lists to be expanded.
  13261.         */
  13262.         h = host + strlen (host);
  13263.         ckmakmsg(host,sizeof(host),prefix, ".", name,
  13264.                  ((h > host) && (h[-1] != '.'))?".":NULL);
  13265.  
  13266.     }
  13267.     size = res_search(host, C_IN, T_TXT, answer.bytes, sizeof(answer.bytes));
  13268.  
  13269.     if (size < 0)
  13270.         return 0;
  13271.  
  13272.     p = answer.bytes;
  13273.  
  13274.     numqueries = ntohs(answer.hdr.qdcount);
  13275.     numanswers = ntohs(answer.hdr.ancount);
  13276.  
  13277.     p += sizeof(HEADER);
  13278.  
  13279.     /*
  13280.      * We need to skip over the questions before we can get to the answers,
  13281.      * which means we have to iterate over every query record.  We use
  13282.      * dn_expand to tell us how long each compressed name is.
  13283.      */
  13284.  
  13285.     while (numqueries--) {
  13286.         len = dn_expand(answer.bytes, answer.bytes + size, p, host,
  13287.                          sizeof(host));
  13288.         if (len < 0)
  13289.             return 0;
  13290.         INCR_CHECK(p, len + 4);         /* Name plus type plus class */
  13291.     }
  13292.  
  13293.     /*
  13294.      * We're now pointing at the answer records.  Process the first
  13295.      * TXT record we find.
  13296.      */
  13297.  
  13298.     while (numanswers--) {
  13299.  
  13300.         /* First the name; use dn_expand to get the compressed size */
  13301.         len = dn_expand(answer.bytes, answer.bytes + size, p,
  13302.                         host, sizeof(host));
  13303.         if (len < 0)
  13304.             return 0;
  13305.         INCR_CHECK(p, len);
  13306.  
  13307.         /* Next is the query type */
  13308.         CHECK(p, 2);
  13309.         type = NTOHSP(p,2);
  13310.  
  13311.         /* Next is the query class; also skip over 4 byte TTL */
  13312.         CHECK(p,6);
  13313.         class = NTOHSP(p,6);
  13314.  
  13315.         /* Record data length - make sure we aren't truncated */
  13316.  
  13317.         CHECK(p,2);
  13318.         rdlen = NTOHSP(p,2);
  13319.  
  13320.         if (p + rdlen > answer.bytes + size)
  13321.             return 0;
  13322.  
  13323.         /*
  13324.          * If this is a TXT record, return the string.  Note that the
  13325.          * string has a 1-byte length in the front
  13326.          */
  13327.         /* XXX What about flagging multiple TXT records as an error?  */
  13328.  
  13329.         if (class == C_IN && type == T_TXT) {
  13330.             len = *p++;
  13331.             if (p + len > answer.bytes + size)
  13332.                 return 0;
  13333.             *retstr = malloc(len + 1);
  13334.             if (*retstr == NULL)
  13335.                 return ENOMEM;
  13336.             strncpy(*retstr, (char *) p, len);
  13337.             (*retstr)[len] = '\0';
  13338.             /* Avoid a common error. */
  13339.             if ( (*retstr)[len-1] == '.' )
  13340.                 (*retstr)[len-1] = '\0';
  13341.             return 1;
  13342.         }
  13343.     }
  13344.  
  13345.     return 0;
  13346. }
  13347. #undef INCR_CHECK
  13348. #undef CHECK
  13349. #undef NTOHSP
  13350. #endif /* CK_DNS_SRV */
  13351.  
  13352. #ifdef TNCODE
  13353. #ifdef CK_FORWARD_X
  13354. #ifdef UNIX
  13355. #include <sys/un.h>
  13356. #define FWDX_UNIX_SOCK
  13357. #ifndef AF_LOCAL
  13358. #define AF_LOCAL AF_UNIX
  13359. #endif
  13360. #ifndef PF_LOCAL
  13361. #define PF_LOCAL PF_UNIX
  13362. #endif
  13363. #ifndef SUN_LEN
  13364. /* Evaluate to actual length of the `sockaddr_un' structure.  */
  13365. #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)         \
  13366.                       + strlen ((ptr)->sun_path))
  13367. #endif
  13368. #endif /* UNIX */
  13369. int
  13370. fwdx_create_listen_socket(screen) int screen; {
  13371. #ifdef NOPUTENV
  13372.     return(-1);
  13373. #else /* NOPUTENV */
  13374.     struct sockaddr_in saddr;
  13375.     int display, port, sock=-1, i;
  13376.     static char env[512];
  13377.  
  13378.     /*
  13379.      * X Windows Servers support multiple displays by listening on
  13380.      * one socket per display.  Display 0 is port 6000; Display 1 is
  13381.      * port 6001; etc.
  13382.      *
  13383.      * We start by trying to open port 6001 so that display 0 is
  13384.      * reserved for the local X Windows Server.
  13385.      */
  13386.  
  13387.     for ( display=1; display < 1000 ; display++  ) {
  13388.  
  13389.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13390.             debug(F111,"fwdx_create_listen_socket()","socket() < 0",sock);
  13391.             return(-1);
  13392.         }
  13393.  
  13394.         port = 6000 + display;
  13395.         bzero((char *)&saddr, sizeof(saddr));
  13396.         saddr.sin_family = AF_INET;
  13397.         saddr.sin_addr.s_addr = inet_addr(myipaddr);
  13398.         saddr.sin_port = htons(port);
  13399.  
  13400.         if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13401.             i = errno;                  /* Save error code */
  13402. #ifdef TCPIPLIB
  13403.             socket_close(sock);
  13404. #else /* TCPIPLIB */
  13405.             close(sock);
  13406. #endif /* TCPIPLIB */
  13407.             sock = -1;
  13408.             debug(F110,"fwdx_create_listen_socket()","bind() < 0",0);
  13409.             continue;
  13410.         }
  13411.  
  13412.         debug(F100,"fdwx_create_listen_socket() bind OK","",0);
  13413.         break;
  13414.     }
  13415.  
  13416.     if ( display > 1000 ) {
  13417.         debug(F100,"fwdx_create_listen_socket() Out of Displays","",0);
  13418.         return(-1);
  13419.     }
  13420.  
  13421.     if (listen(sock, 5) < 0) {
  13422.         i = errno;                  /* Save error code */
  13423. #ifdef TCPIPLIB
  13424.         socket_close(sock);
  13425. #else /* TCPIPLIB */
  13426.         close(sock);
  13427. #endif /* TCPIPLIB */
  13428.         debug(F101,"fdwx_create_listen_socket() listen() errno","",errno);
  13429.         return(-1);
  13430.     }
  13431.     debug(F100,"fwdx_create_listen_socket() listen OK","",0);
  13432.  
  13433.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = sock;
  13434.     if (!myipaddr[0])
  13435.         getlocalipaddr();
  13436.     if ( myipaddr[0] )
  13437.         ckmakxmsg(env,sizeof(env),"DISPLAY=",myipaddr,":",
  13438.                   ckuitoa(display),":",ckuitoa(screen),
  13439.                   NULL,NULL,NULL,NULL,NULL,NULL);
  13440.     else
  13441.         ckmakmsg(env,sizeof(env),"DISPLAY=",ckuitoa(display),":",
  13442.                  ckuitoa(screen));
  13443.     putenv(env);
  13444.     return(0);
  13445. #endif /* NOPUTENV */
  13446. }
  13447.  
  13448.  
  13449. int
  13450. fwdx_open_client_channel(channel) int channel; {
  13451.     char * env;
  13452.     struct sockaddr_in saddr;
  13453. #ifdef FWDX_UNIX_SOCK
  13454.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13455. #endif /* FWDX_UNIX_SOCK */
  13456.     int colon, dot, display, port, sock, i, screen;
  13457.     int family;
  13458.     char buf[256], * host=NULL, * rest=NULL;
  13459. #ifdef TCP_NODELAY
  13460.     int on=1;
  13461. #endif /* TCP_NODELAY */
  13462.  
  13463.     debug(F111,"fwdx_create_client_channel()","channel",channel);
  13464.  
  13465.     for ( i=0; i<MAXFWDX ; i++ ) {
  13466.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel) {
  13467.             /* Already open */
  13468.             debug(F110,"fwdx_create_client_channel()","already open",0);
  13469.             return(0);
  13470.         }
  13471.     }
  13472.  
  13473.     env = getenv("DISPLAY");
  13474.     if ( !env )
  13475.         env = tn_get_display();
  13476.     if ( env )
  13477.         ckstrncpy(buf,env,256);
  13478.     else
  13479.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13480.  
  13481.     bzero((char *)&saddr,sizeof(saddr));
  13482.     saddr.sin_family = AF_INET;
  13483.  
  13484.     if (!fwdx_parse_displayname(buf,
  13485.                                 &family,
  13486.                                 &host,
  13487.                                 &display,
  13488.                                 &screen,
  13489.                                 &rest
  13490.                                 )
  13491.         ) {
  13492.         if ( host ) free(host);
  13493.         if ( rest ) free(rest);
  13494.         return(0);
  13495.     }
  13496.     if (rest) free(rest);
  13497.  
  13498. #ifndef FWDX_UNIX_SOCK
  13499.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13500.    * we change things to use inet sockets on the ip loopback interface instead,
  13501.    * and hope that it works.
  13502.    */
  13503.     if (family == FamilyLocal) {
  13504.         debug(F100,"fwdx_create_client_channel() FamilyLocal","",0);
  13505.         family = FamilyInternet;
  13506.         if (host) free(host);
  13507.         if (host = malloc(strlen("localhost") + 1))
  13508.             strcpy(host, "localhost");
  13509.         else {
  13510.             return(-1);
  13511.         }
  13512.     }
  13513. #else /* FWDX_UNIX_SOCK */
  13514.     if (family == FamilyLocal) {
  13515.         if (host) free(host);
  13516.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13517.         if (sock < 0)
  13518.             return(-1);
  13519.  
  13520.         ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13521.         strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13522.         if (connect(sock,(struct sockaddr *)&saddr_un, SUN_LEN(&saddr_un)) < 0)
  13523.           return(-1);
  13524.     } else
  13525. #endif  /* FWDX_UNIX_SOCK */
  13526.     {
  13527.         /* Otherwise, we are assuming FamilyInternet */
  13528.         if (host) {
  13529.             ckstrncpy(buf,host,sizeof(buf));
  13530.             free(host);
  13531.         } else
  13532.             ckstrncpy(buf,myipaddr,sizeof(buf));
  13533.  
  13534.         debug(F111,"fwdx_create_client_channel()","display",display);
  13535.  
  13536.         port = 6000 + display;
  13537.         saddr.sin_port = htons(port);
  13538.  
  13539.         debug(F110,"fwdx_create_client_channel() ip-address",buf,0);
  13540.         saddr.sin_addr.s_addr = inet_addr(buf);
  13541.         if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13542. #ifdef INADDR_NONE
  13543.              || saddr.sin_addr.s_addr == INADDR_NONE
  13544. #endif /* INADDR_NONE */
  13545.              )
  13546.         {
  13547.             struct hostent *host;
  13548.             host = gethostbyname(buf);
  13549.             if ( host == NULL )
  13550.                 return(-1);
  13551.             host = ck_copyhostent(host);
  13552. #ifdef HADDRLIST
  13553. #ifdef h_addr
  13554.             /* This is for trying multiple IP addresses - see <netdb.h> */
  13555.             if (!(host->h_addr_list))
  13556.                 return(-1);
  13557.             bcopy(host->h_addr_list[0],
  13558.                    (caddr_t)&saddr.sin_addr,
  13559.                    host->h_length
  13560.                    );
  13561. #else
  13562.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13563. #endif /* h_addr */
  13564. #else  /* HADDRLIST */
  13565.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13566. #endif /* HADDRLIST */
  13567.         }
  13568.  
  13569.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13570.             debug(F111,"fwdx_create_client_channel()","socket() < 0",sock);
  13571.             return(-1);
  13572.         }
  13573.  
  13574.         if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13575.             debug(F110,"fwdx_create_client_channel()","connect() failed",0);
  13576. #ifdef TCPIPLIB
  13577.             socket_close(sock);
  13578. #else /* TCPIPLIB */
  13579.             close(sock);
  13580. #endif /* TCPIPLIB */
  13581.             return(-1);
  13582.         }
  13583.  
  13584. #ifdef TCP_NODELAY
  13585.         setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13586. #endif /* TCP_NODELAY */
  13587.     }
  13588.  
  13589.     for (i = 0; i < MAXFWDX; i++) {
  13590.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == -1) {
  13591.          TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = sock;
  13592.          TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = channel;
  13593.        TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 1;
  13594.          debug(F111,"fwdx_create_client_channel()","socket",sock);
  13595.          return(0);
  13596.      }
  13597.     }
  13598.     return(-1);
  13599. }
  13600.  
  13601. int
  13602. fwdx_server_avail() {
  13603.     char * env;
  13604.     struct sockaddr_in saddr;
  13605. #ifdef FWDX_UNIX_SOCK
  13606.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13607. #endif  /* FWDX_UNIX_SOCK */
  13608.     int colon, dot, display, port, sock, i, screen;
  13609.     char buf[256], *host=NULL, *rest=NULL;
  13610. #ifdef TCP_NODELAY
  13611.     int on=1;
  13612. #endif /* TCP_NODELAY */
  13613.     int family;
  13614.  
  13615.     env = getenv("DISPLAY");
  13616.     if ( !env )
  13617.         env = tn_get_display();
  13618.     if ( env )
  13619.         ckstrncpy(buf,env,256);
  13620.     else
  13621.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13622.  
  13623.     bzero((char *)&saddr,sizeof(saddr));
  13624.     saddr.sin_family = AF_INET;
  13625.  
  13626.     if (!fwdx_parse_displayname(buf,&family,&host,&display,&screen,&rest)) {
  13627.         if ( host ) free(host);
  13628.         if ( rest ) free(rest);
  13629.         return(0);
  13630.     }
  13631.     if (rest) free(rest);
  13632.  
  13633. #ifndef FWDX_UNIX_SOCK
  13634.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13635.    * we change things to use inet sockets on the ip loopback interface instead,
  13636.    * and hope that it works.
  13637.    */
  13638.     if (family == FamilyLocal) {
  13639.         family = FamilyInternet;
  13640.         if (host) free(host);
  13641.         if (host = malloc(strlen("localhost") + 1))
  13642.             strcpy(host, "localhost");
  13643.         else {
  13644.             return(-1);
  13645.         }
  13646.     }
  13647. #else /* FWDX_UNIX_SOCK */
  13648.     if (family == FamilyLocal) {
  13649.         debug(F100,"fwdx_server_avail() FamilyLocal","",0);
  13650.         if (host) free(host);
  13651.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13652.         if (sock < 0)
  13653.             return(0);
  13654.  
  13655.         ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13656.         strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13657.         if (connect(sock,(struct sockaddr *)&saddr_un,SUN_LEN(&saddr_un)) < 0)
  13658.             return(0);
  13659.         close(sock);
  13660.         return(1);
  13661.     }
  13662. #endif  /* FWDX_UNIX_SOCK */
  13663.  
  13664.     /* Otherwise, we are assuming FamilyInternet */
  13665.     if (host) {
  13666.         ckstrncpy(buf,host,sizeof(buf));
  13667.         free(host);
  13668.     } else
  13669.         ckstrncpy(buf,myipaddr,sizeof(buf));
  13670.  
  13671.     debug(F111,"fwdx_server_avail()","display",display);
  13672.  
  13673.     port = 6000 + display;
  13674.     saddr.sin_port = htons(port);
  13675.  
  13676.     debug(F110,"fwdx_server_avail() ip-address",buf,0);
  13677.     saddr.sin_addr.s_addr = inet_addr(buf);
  13678.     if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13679. #ifdef INADDR_NONE
  13680.          || saddr.sin_addr.s_addr == INADDR_NONE
  13681. #endif /* INADDR_NONE */
  13682.          )
  13683.     {
  13684.         struct hostent *host;
  13685.         host = gethostbyname(buf);
  13686.         if ( host == NULL ) {
  13687.             debug(F110,"fwdx_server_avail() gethostbyname() failed",
  13688.                    myipaddr,0);
  13689.             return(-1);
  13690.         }
  13691.         host = ck_copyhostent(host);
  13692. #ifdef HADDRLIST
  13693. #ifdef h_addr
  13694.         /* This is for trying multiple IP addresses - see <netdb.h> */
  13695.         if (!(host->h_addr_list))
  13696.             return(-1);
  13697.         bcopy(host->h_addr_list[0],
  13698.                (caddr_t)&saddr.sin_addr,
  13699.                host->h_length
  13700.                );
  13701. #else
  13702.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13703. #endif /* h_addr */
  13704. #else  /* HADDRLIST */
  13705.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13706. #endif /* HADDRLIST */
  13707.     }
  13708.  
  13709.     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13710.         debug(F111,"fwdx_server_avail()","socket() < 0",sock);
  13711.         return(0);
  13712.     }
  13713.  
  13714.     if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13715.         debug(F110,"fwdx_server_avail()","connect() failed",0);
  13716. #ifdef TCPIPLIB
  13717.         socket_close(sock);
  13718. #else /* TCPIPLIB */
  13719.         close(sock);
  13720. #endif /* TCPIPLIB */
  13721.         return(0);
  13722.     }
  13723.  
  13724. #ifdef TCPIPLIB
  13725.     socket_close(sock);
  13726. #else /* TCPIPLIB */
  13727.     close(sock);
  13728. #endif /* TCPIPLIB */
  13729.     return(1);
  13730. }
  13731.  
  13732. int
  13733. fwdx_open_server_channel() {
  13734.     int sock, ready_to_accept, sock2,channel,i;
  13735. #ifdef TCP_NODELAY
  13736.     int on=1;
  13737. #endif /* TCP_NODELAY */
  13738. #ifdef UCX50
  13739.     static u_int saddrlen;
  13740. #else
  13741.     static SOCKOPT_T saddrlen;
  13742. #endif /* UCX50 */
  13743.     struct sockaddr_in saddr;
  13744.     char sb[8];
  13745.     extern char tn_msg[];
  13746. #ifdef BSDSELECT
  13747.     fd_set rfds;
  13748.     struct timeval tv;
  13749. #else
  13750. #ifdef BELLSELCT
  13751.     fd_set rfds;
  13752. #else
  13753.     fd_set rfds;
  13754.     struct timeval {
  13755.         long tv_sec;
  13756.         long tv_usec;
  13757.     } tv;
  13758. #endif /* BELLSELECT */
  13759. #endif /* BSDSELECT */
  13760.     unsigned short nchannel;
  13761.     unsigned char * p;
  13762.  
  13763.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket;
  13764.  
  13765.   try_again:
  13766.  
  13767. #ifdef BSDSELECT
  13768.     tv.tv_sec  = tv.tv_usec = 0L;
  13769.     tv.tv_usec = 50;
  13770.     FD_ZERO(&rfds);
  13771.     FD_SET(sock, &rfds);
  13772.     ready_to_accept =
  13773.         ((select(FD_SETSIZE,
  13774. #ifdef HPUX
  13775. #ifdef HPUX1010
  13776.                   (fd_set *)
  13777. #else
  13778.  
  13779.                   (int *)
  13780. #endif /* HPUX1010 */
  13781. #else
  13782. #ifdef __DECC
  13783.                   (fd_set *)
  13784. #endif /* __DECC */
  13785. #endif /* HPUX */
  13786.                   &rfds, NULL, NULL, &tv) > 0) &&
  13787.           FD_ISSET(sock, &rfds));
  13788. #else /* BSDSELECT */
  13789. #ifdef IBMSELECT
  13790.     ready_to_accept = (select(&sock, 1, 0, 0, 50) == 1);
  13791. #else
  13792. #ifdef BELLSELECT
  13793.     FD_ZERO(rfds);
  13794.     FD_SET(sock, rfds);
  13795.     ready_to_accept =
  13796.         ((select(128, rfds, NULL, NULL, 50) > 0) &&
  13797.           FD_ISSET(sock, rfds));
  13798. #else
  13799. /* Try this - what's the worst that can happen... */
  13800.  
  13801.     tv.tv_sec  = tv.tv_usec = 0L;
  13802.     tv.tv_usec = 50;
  13803.     FD_ZERO(&rfds);
  13804.     FD_SET(sock, &rfds);
  13805.     ready_to_accept =
  13806.         ((select(FD_SETSIZE,
  13807.                   (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  13808.           FD_ISSET(sock, &rfds));
  13809. #endif /* BELLSELECT */
  13810. #endif /* IBMSELECT */
  13811. #endif /* BSDSELECT */
  13812.  
  13813.     if ( !ready_to_accept )
  13814.         return(0);
  13815.  
  13816.     if ((sock2 = accept(sock,(struct sockaddr *)&saddr,&saddrlen)) < 0) {
  13817.         int i = errno;                  /* save error code */
  13818.         debug(F101,"tcpsrv_open accept errno","",i);
  13819.         return(-1);
  13820.     }
  13821.  
  13822.     /*
  13823.      * Now we have the open socket.  We must now find a channel to store
  13824.      * it in, and then notify the client.
  13825.      */
  13826.  
  13827.     for ( channel=0;channel<MAXFWDX;channel++ ) {
  13828.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd == -1 )
  13829.             break;
  13830.     }
  13831.  
  13832.     if ( channel == MAXFWDX ) {
  13833. #ifdef TCPIPLIB
  13834.         socket_close(sock2);
  13835. #else /* TCPIPLIB */
  13836.         close(sock2);
  13837. #endif /* TCPIPLIB */
  13838.         return(-1);
  13839.     }
  13840.  
  13841.     if ( fwdx_send_open(channel) < 0 ) {
  13842. #ifdef TCPIPLIB
  13843.         socket_close(sock2);
  13844. #else /* TCPIPLIB */
  13845.         close(sock2);
  13846. #endif /* TCPIPLIB */
  13847.     }
  13848.  
  13849. #ifdef TCP_NODELAY
  13850.     setsockopt(sock2,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13851. #endif /* TCP_NODELAY */
  13852.  
  13853.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd = sock2;
  13854.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].id = channel;
  13855.     goto try_again;
  13856.  
  13857.     return(0);  /* never reached */
  13858. }
  13859.  
  13860. int
  13861. fwdx_close_channel(channel) int channel; {
  13862.     int i,fd;
  13863.  
  13864.     for ( i=0; i<MAXFWDX ; i++ ) {
  13865.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13866.             break;
  13867.     }
  13868.     if ( i == MAXFWDX )
  13869.         return(-1);
  13870.  
  13871.     fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13872.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = -1;
  13873.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = -1;
  13874.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 0;
  13875.  
  13876. #ifdef TCPIPLIB
  13877.     socket_close(fd);
  13878. #else /* TCPIPLIB */
  13879.     close(fd);
  13880. #endif /* TCPIPLIB */
  13881.     return(0);
  13882. }
  13883.  
  13884. int
  13885. fwdx_close_all() {
  13886.     int x,fd;
  13887.  
  13888.     debug(F111,"fwdx_close_all()",
  13889.           "TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket",
  13890.           TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13891.  
  13892.     if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1 ) {
  13893. #ifdef TCPIPLIB
  13894.         socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13895. #else /* TCPIPLIB */
  13896.         close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13897. #endif /* TCPIPLIB */
  13898.         TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = -1;
  13899.     }
  13900.  
  13901.     for (x = 0; x < MAXFWDX; x++) {
  13902.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  13903.       fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13904.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd = -1;
  13905.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id = -1;
  13906.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].need_to_send_xauth = 0;
  13907.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend = 0;
  13908. #ifdef TCPIPLIB
  13909.       socket_close(fd);
  13910. #else /* TCPIPLIB */
  13911.       close(fd);
  13912. #endif /* TCPIPLIB */
  13913.      }
  13914.     }
  13915.     return(0);
  13916. }
  13917.  
  13918. /* The following definitions are for Unix */
  13919. #ifndef socket_write
  13920. #define socket_write(f,s,n)    write(f,s,n)
  13921. #endif /* socket_write */
  13922. #ifndef socket_read
  13923. #define socket_read(f,s,n)     read(f,s,n)
  13924. #endif /* socket_read */
  13925.  
  13926. int
  13927. fwdx_write_data_to_channel(channel, data, len)
  13928.     int channel; char * data; int len;
  13929. {
  13930.     int sock, count, try=0, length = len, i;
  13931.  
  13932.     if ( len <= 0 )
  13933.         return(0);
  13934.  
  13935.     for ( i=0; i<MAXFWDX ; i++ ) {
  13936.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13937.             break;
  13938.     }
  13939.     if ( i == MAXFWDX ) {
  13940.         debug(F110,"fwdx_write_data_to_channel",
  13941.                "attempting to write to closed channel",0);
  13942.         return(-1);
  13943.     }
  13944.  
  13945.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13946.     debug(F111,"fwdx_write_data_to_channel","socket",sock);
  13947.     hexdump("fwdx_write_data_to_channel",data,len);
  13948.  
  13949.   fwdx_write_data_to_channel_retry:
  13950.  
  13951.     if ((count = socket_write(sock,data,len)) < 0) {
  13952.         int s_errno = socket_errno; /* maybe a function */
  13953.         debug(F101,"fwdx_write_data_to_channel socket_write error","",s_errno);
  13954. #ifdef BETATEST
  13955.         printf("fwdx_write_data_to_channel error\r\n");
  13956. #endif /* BETATEST */
  13957. #ifdef OS2
  13958.         if (os2socketerror(s_errno) < 0)
  13959.             return(-2);
  13960. #endif /* OS2 */
  13961.         return(-1);                 /* Call it an i/o error */
  13962.     }
  13963.     if (count < len) {
  13964.         debug(F111,"fwdx_write_data_to_channel socket_write",data,count);
  13965.         if (count > 0) {
  13966.             data += count;
  13967.             len -= count;
  13968.         }
  13969.         debug(F111,"fwdx_write_data_to_channel retry",data,len);
  13970.         if ( len > 0 )
  13971.             goto fwdx_write_data_to_channel_retry;
  13972.     }
  13973.  
  13974.     debug(F111,"fwdx_write_data_to_channel complete",data,length);
  13975.     return(length); /* success - return total length */
  13976. }
  13977.  
  13978. VOID
  13979. fwdx_check_sockets(fd_set *ibits)
  13980. {
  13981.     int x, sock, channel, bytes;
  13982.     static char buffer[32000];
  13983.  
  13984.     debug(F100,"fwdx_check_sockets()","",0);
  13985.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  13986.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  13987.         debug(F110,"fwdx_check_sockets()","TELOPT_FORWARD_X not negotiated",0);
  13988.         return;
  13989.     }
  13990.  
  13991.     for (x = 0; x < MAXFWDX; x++) {
  13992.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd == -1 ||
  13993.              TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend )
  13994.             continue;
  13995.  
  13996.         sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13997.         if (FD_ISSET(sock, ibits))
  13998.         {
  13999.             channel = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id;
  14000.             debug(F111,"fwdx_check_sockets()","channel set",channel);
  14001.  
  14002.             bytes = socket_read(sock, buffer, sizeof(buffer));
  14003.             if (bytes > 0)
  14004.                 fwdx_send_data_from_channel(channel, buffer, bytes);
  14005.             else if (bytes == 0) {
  14006.                 fwdx_close_channel(channel);
  14007.                 fwdx_send_close(channel);
  14008.             }
  14009.         }
  14010.     }
  14011. }
  14012.  
  14013. int
  14014. fwdx_init_fd_set(fd_set *ibits)
  14015. {
  14016.     int x,set=0,cnt=0;
  14017.  
  14018.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  14019.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  14020.         debug(F110,"fwdx_init_fd_set()","TELOPT_FORWARD_X not negotiated",0);
  14021.         return(0);
  14022.     }
  14023.  
  14024.     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1) {
  14025.         set++;
  14026.         FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket, ibits);
  14027.     }
  14028.     for (x = 0; x < MAXFWDX; x++) {
  14029.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  14030.             cnt++;
  14031.             if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend)
  14032.                 continue;
  14033.             set++;
  14034.             FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd, ibits);
  14035.         }
  14036.     }
  14037.     if (set + cnt == 0) {
  14038.         return(-1);
  14039.     } else {
  14040.         return(set);
  14041.     }
  14042. }
  14043.  
  14044. #ifdef NT
  14045. VOID
  14046. fwdx_thread( VOID * dummy )
  14047. {
  14048.     fd_set ifds;
  14049.     struct timeval tv;
  14050.     extern int priority;
  14051.     int n;
  14052.  
  14053.     setint();
  14054.     SetThreadPrty(priority,isWin95() ? 3 : 11);
  14055.  
  14056.     while ( !sstelnet && TELOPT_U(TELOPT_FORWARD_X) ||
  14057.             sstelnet && TELOPT_ME(TELOPT_FORWARD_X))
  14058.     {
  14059.         FD_ZERO(&ifds);
  14060.         n = fwdx_init_fd_set(&ifds);
  14061.         if (n > 0) {
  14062.             tv.tv_sec = 0;
  14063.             tv.tv_usec = 2500;
  14064.             if ( select(FD_SETSIZE, &ifds, NULL, NULL, &tv) > 0 )
  14065.                 fwdx_check_sockets(&ifds);
  14066.  
  14067.         } else if (n < 0) {
  14068.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.thread_started = 0;
  14069.             ckThreadEnd(NULL);
  14070.         } else {
  14071.             sleep(1);
  14072.         }
  14073.     }
  14074. }
  14075. #endif /* NT */
  14076. #endif /* CK_FORWARD_X */
  14077. #endif /* TNCODE */
  14078. #endif /* NETCONN */
  14079.