home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckv201.zip / ckcnet.c < prev    next >
C/C++ Source or Header  |  2002-02-06  |  448KB  |  13,956 lines

  1. char *cknetv = "Network support, 8.0.264, 5 Feb 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. #ifdef TCPIPLIB
  289. _PROTOTYP( static VOID rlog_oob, (CHAR *, int) );
  290. #else
  291. _PROTOTYP( static SIGTYP rlogoobh, ( int ) );
  292. #endif /* TCPIPLIB */
  293. _PROTOTYP( static int rlog_ini, (CHAR *, int,
  294.                                  struct sockaddr_in *,
  295.                                  struct sockaddr_in *) );
  296. int rlog_mode = RL_COOKED;
  297. int rlog_stopped = 0;
  298. #endif /* RLOGCODE */
  299.  
  300. #ifndef NOICP
  301. extern int doconx;                      /* CONNECT-class command active */
  302. #endif /* NOICP */
  303.  
  304. #ifdef IBMX25
  305. /* This variable should probably be generalised for true client/server
  306.  * support - ie: the fd of the listening server, accepted calls should
  307.  * be forked or at least handled via a second fd (for IBM's X.25 -
  308.  * ttyfd always holds the active fd - ie the server becomes inactive
  309.  * as long as a client is connected, and becomes active again when the
  310.  * connection is closed)
  311.  */
  312. int x25serverfd = 0;            /* extern in ckcnet.h */
  313. int x25seqno = 0;               /* Connection sequence number */
  314. int x25lastmsg = -1;            /* A cheapskate's state table */
  315.  
  316. #define X25_CLOSED      0       /* Default state: no connection, no STREAM */
  317. #define X25_SETUP       1       /* X.25 has been set up (no connection) */
  318. #define X25_CONNECTED   2       /* X.25 connection has been established */
  319. int x25_state = X25_CLOSED;     /* Default state */
  320. #endif /* IBMX25 */
  321.  
  322. #ifndef DEBUG
  323. #define deblog 0
  324. #endif /* DEBUG */
  325.  
  326. #ifdef CK_NAWS                          /* Negotiate About Window Size */
  327. #ifdef RLOGCODE
  328. _PROTOTYP( int rlog_naws, (void) );
  329. #endif /* RLOGCODE */
  330. #endif /* CK_NAWS */
  331.  
  332. #ifdef OS2                              /* For terminal type name string */
  333. #include "ckuusr.h"
  334. #ifndef NT
  335. #include <os2.h>
  336. #undef COMMENT
  337. #endif /* NT */
  338. #include "ckocon.h"
  339. extern int tt_type, max_tt;
  340. extern struct tt_info_rec tt_info[];
  341. extern char ttname[];
  342. #else
  343. #ifdef CK_AUTHENTICATION
  344. #include "ckuusr.h"
  345. #endif /* CK_AUTHENTICATION */
  346. #endif /* OS2 */
  347.  
  348. #ifdef NT
  349. extern int winsock_version;
  350. #endif /* NT */
  351.  
  352. #ifdef CK_AUTHENTICATION
  353. #include "ckuath.h"
  354. #endif /* CK_AUTHENTICATION */
  355.  
  356. #include "ckcsig.h"
  357.  
  358. #ifndef OS2                             /* For timeout longjumps */
  359. static ckjmpbuf njbuf;
  360. #endif /* OS2 */
  361.  
  362. #define NAMECPYL 1024                   /* Local copy of hostname */
  363. char namecopy[NAMECPYL];                /* Referenced by ckctel.c */
  364. #ifndef NOHTTP
  365. char http_host_port[NAMECPYL];          /* orig host/port necessary for http */
  366. char http_ip[20] = { '\0' };            /* ip address of host */
  367. char http_port = 0;
  368. int  http_ssl = 0;
  369. int  httpfd = -1;                       /* socket for http connections */
  370. int  http_code = 0;
  371. #define HTTPBUFLEN  1024
  372. char http_reply_str[HTTPBUFLEN] = "";
  373. #endif /* NOHTTP */
  374.  
  375. char ipaddr[20] = { '\0' };             /* Global copy of IP address */
  376. unsigned long myxipaddr = 0L;           /* Ditto as a number */
  377. #endif /* NETCONN */
  378.  
  379. char *tcp_address = NULL;               /* Preferred IP Address */
  380. extern char uidbuf[];                   /* User ID buffer */
  381. extern char pwbuf[];                    /* Password buffer */
  382.  
  383. #ifndef NOHTTP
  384. char * tcp_http_proxy = NULL;           /* Name[:port] of http proxy server */
  385. int    tcp_http_proxy_errno = 0;
  386. char * tcp_http_proxy_user = NULL;
  387. char * tcp_http_proxy_pwd  = NULL;
  388. #define HTTPCPYL 1024
  389. static char proxycopy[HTTPCPYL];
  390. #endif /* NOHTTP */
  391.  
  392. #ifdef OS2
  393. extern int tt_rows[], tt_cols[];
  394. extern int tt_status[VNUM];
  395. #else /* OS2 */
  396. extern int tt_rows, tt_cols;            /* Everybody has this */
  397. #endif /* OS2 */
  398.  
  399. extern int cmd_cols, cmd_rows;
  400.  
  401. #ifdef STREAMING                        /* Use blocking writes for streaming */
  402. extern int streaming;
  403. #endif /* STREAMING */
  404.  
  405. #ifdef NT
  406. extern int WSASafeToCancel;
  407. int win95selectbug = 0;                 /* For TCP/IP stacks whose select() */
  408. /* always fails on write requests such as Cisco and Quarterdeck */
  409. #define stricmp _stricmp
  410. #endif /* NT */
  411.  
  412. #ifndef NOTCPOPTS
  413.  
  414. /* Skip all this if NOTCPOPTS specified. */
  415.  
  416. #ifdef SOL_SOCKET
  417.  
  418. #ifdef TCP_NODELAY
  419. int tcp_nodelay = 0;                    /* Nagle algorithm TCP_NODELAY */
  420. #endif /* TCP_NODELAY */
  421.  
  422. #ifdef SO_DONTROUTE
  423. int tcp_dontroute = 0;
  424. #endif /* SO_DONTROUTE */
  425.  
  426. #ifdef SO_LINGER
  427. int tcp_linger  = 0;                    /* SO_LINGER */
  428. int tcp_linger_tmo = 0;                 /* SO_LINGER timeout */
  429. #endif /* SO_LINGER */
  430.  
  431. #ifdef HPUX                             /* But the data structures */
  432. #ifndef HPUX8                           /* needed for linger are not */
  433. #ifndef HPUX9                           /* defined in HP-UX versions */
  434. #ifndef HPUX10                          /* prior to 8.00. */
  435. #ifdef SO_LINGER
  436. #undef SO_LINGER
  437. #endif /* SO_LINGER */
  438. #endif /* HPUX10 */
  439. #endif /* HPUX9 */
  440. #endif /* HPUX8 */
  441. #endif /* HPUX */
  442.  
  443. #ifndef SO_OOBINLINE                    /* Hopefully only HP-UX 7.0 */
  444. #define SO_OOBINLINE 0x0100
  445. #endif /* SO_OOBINLINE */
  446.  
  447. #ifndef TCPSNDBUFSIZ
  448. #ifdef VMS
  449. #ifdef __alpha
  450. #define TCPSNDBUFSIZ 16384
  451. #endif /* __alpha */
  452. #endif /* VMS */
  453. #endif /* TCPSNDBUFSIZ */
  454.  
  455. #ifndef TCPSNDBUFSIZ
  456. #define TCPSNDBUFSIZ -1
  457. #endif /* TCPSNDBUFSIZ */
  458.  
  459. #ifdef SO_SNDBUF
  460. int tcp_sendbuf = TCPSNDBUFSIZ;
  461. #endif /* SO_SNDBUF */
  462.  
  463. #ifdef SO_RCVBUF
  464. int tcp_recvbuf = -1;
  465. #endif /* SO_RCVBUF */
  466.  
  467. #ifdef SO_KEEPALIVE
  468. int tcp_keepalive = 1;
  469. #endif /* SO_KEEPALIVE */
  470.  
  471. #endif /* SOL_SOCKET */
  472. #endif /* NOTCPOPTS */
  473.  
  474. #ifndef NETCONN
  475. /*
  476.   Network support not defined.
  477.   Dummy functions here in case #ifdef's forgotten elsewhere.
  478. */
  479. int                                     /* Open network connection */
  480. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  481.     return(-1);
  482. }
  483. int                                     /* Close network connection */
  484. netclos() {
  485.     return(-1);
  486. }
  487. int                                     /* Check network input buffer */
  488. nettchk() {
  489.     return(-1);
  490. }
  491. int                                     /* Flush network input buffer */
  492. netflui() {
  493.     return(-1);
  494. }
  495. int                                     /* Send network BREAK */
  496. netbreak() {
  497.     return(-1);
  498. }
  499. int                                     /* Input character from network */
  500. netinc(timo) int timo; {
  501.     return(-1);
  502. }
  503. int                                     /* Output character to network */
  504. #ifdef CK_ANSIC
  505. nettoc(CHAR c)
  506. #else
  507. nettoc(c) CHAR c;
  508. #endif /* CK_ANSIC */
  509. /* nettoc */ {
  510.     return(-1);
  511. }
  512. int
  513. nettol(s,n) CHAR *s; int n; {
  514.     return(-1);
  515. }
  516.  
  517. #else /* NETCONN is defined (much of this module...) */
  518.  
  519. #ifdef NETLEBUF
  520. VOID
  521. le_init() {                             /* LocalEchoInit() */
  522.     int i;
  523.     for (i = 0; i < LEBUFSIZ; i++)
  524.       le_buf[i] = '\0';
  525.     le_start = 0;
  526.     le_end = 0;
  527.     le_data = 0;
  528.     tt_push_inited = 1;
  529. }
  530.  
  531. VOID
  532. le_clean() {                            /* LocalEchoCleanup() */
  533.     le_init();
  534.     return;
  535. }
  536.  
  537. int
  538. le_inbuf() {
  539.     int rc = 0;
  540.     if (le_start != le_end) {
  541.         rc = (le_end -
  542.               le_start +
  543.               LEBUFSIZ) % LEBUFSIZ;
  544.     }
  545.     return(rc);
  546. }
  547.  
  548. int
  549. #ifdef CK_ANSIC
  550. le_putchar(CHAR ch)
  551. #else
  552. le_putchar(ch) CHAR ch;
  553. #endif /* CK_ANSIC */
  554. /* le_putchar */ {
  555.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  556.         debug(F110,"le_putchar","buffer is full",0);
  557.         return(-1);
  558.     }
  559.     le_buf[le_end++] = ch;
  560.     if (le_end == LEBUFSIZ)
  561.       le_end = 0;
  562.     le_data = 1;
  563.     return(0);
  564. }
  565.  
  566. int
  567. #ifdef CK_ANSIC
  568. le_puts(CHAR * s, int n)
  569. #else
  570. le_puts(s,n) CHAR * s; int n;
  571. #endif /* CK_ANSIC */
  572. /* le_puts */ {
  573.     int rc = 0;
  574.     int i = 0;
  575.     CHAR * p = (CHAR *)"le_puts";
  576.     hexdump(p,s,n);
  577.     for (i = 0; i < n; i++)
  578.       rc = le_putchar((char)s[i]);
  579.     debug(F101,"le_puts","",rc);
  580.     return(rc);
  581. }
  582.  
  583. int
  584. #ifdef CK_ANSIC
  585. le_putstr(CHAR * s)
  586. #else
  587. le_putstr(s) CHAR * s;
  588. #endif /* CK_ANSIC */
  589. /* le_puts */ {
  590.     CHAR * p;
  591.     int rc = 0;
  592.     p = (CHAR *)"le_putstr";
  593.     hexdump(p,s,(int)strlen((char *)s));
  594.     for (p = s; *p && !rc; p++)
  595.       rc = le_putchar(*p);
  596.     return(rc);
  597. }
  598.  
  599. int
  600. #ifdef CK_ANSIC
  601. le_getchar(CHAR * pch)
  602. #else /* CK_ANSIC */
  603. le_getchar(pch) CHAR * pch;
  604. #endif /* CK_ANSIC */
  605. /* le_gatchar */ {
  606.     int rc = 0;
  607.     if (le_start != le_end) {
  608.         *pch = le_buf[le_start];
  609.         le_buf[le_start] = 0;
  610.         le_start++;
  611.  
  612.         if (le_start == LEBUFSIZ)
  613.           le_start = 0;
  614.  
  615.         if (le_start == le_end) {
  616.             le_data = 0;
  617.         }
  618.         rc++;
  619.     } else {
  620.         *pch = 0;
  621.     }
  622.     return(rc);
  623. }
  624. #endif /* NETLEBUF */
  625.  
  626. #ifdef VMS
  627. /*
  628.   In edit 190, we moved tn_ini() to be called from within netopen().
  629.   But tn_ini() calls ttol(), and ttol() checks to see if it's a net
  630.   connection, but the flag for that isn't set until after netopen()
  631.   is finished.  Since, in this module, we are always doing network
  632.   output anyway, we just call nettol() directly, instead of going thru
  633.   ttol().  Only needed for VMS, since UNIX, AOS/VS, and VOS can handle
  634.   net connections just like regular connections in ttol(), and OS/2
  635.   has a special routine for this.
  636. */
  637. #define ttol nettol
  638. #endif /* VMS */
  639.  
  640. int tcpsrfd = -1;
  641.  
  642. #ifdef CK_KERBEROS
  643.  
  644. char * krb5_d_principal = NULL;         /* Default principal */
  645. char * krb5_d_instance = NULL;          /* Default instance */
  646. char * krb5_d_realm = NULL;             /* Default realm */
  647. char * krb5_d_cc = NULL;                /* Default credentials cache */
  648. char * krb5_d_srv   = NULL;             /* Default Service */
  649. int    krb5_d_lifetime = 600;           /* Default lifetime (10 hours) */
  650. int    krb5_d_forwardable = 0;          /* creds not forwardable */
  651. int    krb5_d_proxiable = 0;            /* creds not proxiable */
  652. int    krb5_d_renewable = 0;            /* creds not renewable (0 min) */
  653. int    krb5_autoget = 1;                /* Autoget TGTs */
  654. int    krb5_autodel = 0;                /* Auto delete TGTs */
  655. int    krb5_d_getk4 = 0;                /* K5 Kinit gets K4 TGTs */
  656. int    krb5_checkaddrs = 1;             /* Check TGT Addrs */
  657. int    krb5_d_no_addresses = 0;         /* Do not include IP Addresses */
  658. char * krb5_d_addrs[KRB5_NUM_OF_ADDRS+1]={NULL,NULL}; /* Addrs to include */
  659. int    krb5_errno = 0;                  /* Last K5 errno */
  660. char * krb5_errmsg = NULL;              /* Last K5 errmsg */
  661. char * k5_keytab = NULL;
  662.  
  663. char * krb4_d_principal = NULL;         /* Default principal */
  664. char * krb4_d_realm = NULL;             /* Default realm */
  665. char * krb4_d_srv   = NULL;             /* Default Service */
  666. int    krb4_d_lifetime = 600;           /* Default lifetime (10 hours) */
  667. int    krb4_d_preauth = 1;              /* Use preauth requests */
  668. char * krb4_d_instance = NULL;          /* Default instance */
  669. int    krb4_autoget = 1;                /* Autoget TGTs */
  670. int    krb4_autodel = 0;                /* Auto delete TGTs */
  671. int    krb4_checkaddrs = 1;             /* Check TGT Addrs */
  672. char * k4_keytab = NULL;
  673.  
  674. int    krb4_errno = 0;                  /* Last K4 errno */
  675. char * krb4_errmsg = NULL;              /* Last K4 errmsg */
  676.  
  677. struct krb_op_data krb_op = {           /* Operational data structure */
  678.     0, NULL                             /* (version, cachefile) */
  679. };
  680.  
  681. struct krb4_init_data krb4_init = {     /* Kerberos 4 INIT data structure */
  682.     0, NULL, NULL, NULL, NULL
  683. };
  684.  
  685. struct krb5_init_data krb5_init = {     /* Kerberos 5 INIT data structure */
  686.     0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0,
  687.     { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
  688.       NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL },
  689.     0
  690. };
  691.  
  692. struct krb5_list_cred_data krb5_lc = {  /* List Credentials data structure */
  693.     0, 0, 0
  694. };
  695.  
  696. int krb_action = -1;                    /* Kerberos action to perform */
  697.  
  698. #ifndef CK_AUTHENTICATION
  699. char *
  700. ck_krb4_getrealm() {
  701.     return("");
  702. }
  703. char *
  704. ck_krb5_getrealm(cc) char * cc; {
  705.     return("");
  706. }
  707. char *
  708. ck_krb4_getprincipal() {
  709.     return("");
  710. }
  711. char *
  712. ck_krb5_getprincipal(cc) char * cc; {
  713.     return("");
  714. }
  715. #endif /* CK_AUTHENTICATION */
  716.  
  717. /*  I N I _ K E R B  --  Initialize Kerberos data  */
  718.  
  719. VOID
  720. ini_kerb() {
  721.     int i;
  722.  
  723.     krb_action = -1;                    /* No action specified */
  724.  
  725.     krb_op.version = 0;                 /* Kerberos version (none) */
  726.     krb_op.cache = NULL;                /* Cache file (none) */
  727.  
  728. /* Kerberos 5 */
  729.  
  730.     krb5_init.forwardable = krb5_d_forwardable; /* Init switch values... */
  731.     krb5_init.proxiable   = krb5_d_proxiable;
  732.     krb5_init.lifetime    = krb5_d_lifetime;
  733.     krb5_init.renew       = 0;
  734.     krb5_init.renewable   = krb5_d_renewable;
  735.     krb5_init.validate    = 0;
  736.     krb5_init.no_addresses = krb5_d_no_addresses;
  737.     if (krb5_init.postdate) {
  738.         free(krb5_init.postdate);
  739.         krb5_init.postdate = NULL;
  740.     }
  741.     if (krb5_init.service) {
  742.         free(krb5_init.service);
  743.         krb5_init.service = NULL;
  744.     }
  745.     if (!krb5_d_cc || !krb5_d_cc[0]) {  /* Set default cache */
  746.         char * p;
  747.         p = ck_krb5_get_cc_name();
  748.         makestr(&krb5_d_cc,(p && p[0]) ? p : NULL);
  749.     }
  750.     if (!krb5_d_realm || !krb5_d_realm[0]) { /* Set default realm */
  751.         char * p;
  752.         p = ck_krb5_getrealm(krb5_d_cc);
  753.         makestr(&krb5_d_realm,(p && p[0]) ? p : NULL);
  754.     }
  755.     makestr(&krb5_init.instance,krb5_d_instance);
  756.     makestr(&krb5_init.realm,krb5_d_realm); /* Set realm from default */
  757.     if (krb5_init.password) {
  758.         memset(krb5_init.password,0xFF,strlen(krb5_init.password));
  759.         free(krb5_init.password);
  760.         krb5_init.password = NULL;
  761.     }
  762.     if (!krb5_d_principal) {            /* Default principal */
  763.         /* a Null principal indicates the user should be prompted */
  764.         char * p = ck_krb5_getprincipal(krb5_d_cc);
  765.         if (!p || !(*p))
  766.           p = (char *)uidbuf;           /* Principal = user */
  767.                 makestr(&krb5_d_principal,(p && p[0]) ? p : NULL);
  768.     }
  769.     makestr(&krb5_init.principal,krb5_d_principal);
  770.     for (i = 0; i <= KRB5_NUM_OF_ADDRS; i++) {
  771.         if (krb5_init.addrs[i])
  772.           free(krb5_init.addrs[i]);
  773.         krb5_init.addrs[i] = NULL;
  774.     }
  775.     for (i = 0; i <= KRB5_NUM_OF_ADDRS && krb5_d_addrs[i]; i++) {
  776.         makestr(&krb5_init.addrs[i],krb5_d_addrs[i]);
  777.     }
  778.  
  779.     /* Kerberos 4 */
  780.  
  781.     krb4_init.lifetime = krb4_d_lifetime;
  782.     krb4_init.preauth  = krb4_d_preauth;
  783.     makestr(&krb4_init.instance,krb4_d_instance);
  784.     if (!krb4_d_realm || !krb4_d_realm[0]) {/* Set default realm */
  785.         char * p;
  786.         p = ck_krb4_getrealm();
  787.                 makestr(&krb4_d_realm,(p && p[0]) ? p : NULL);
  788.     }
  789.     makestr(&krb4_init.realm,krb4_d_realm);
  790.     if (krb4_init.password) {
  791.         memset(krb4_init.password,0xFF,strlen(krb4_init.password));
  792.         free(krb4_init.password);
  793.         krb4_init.password = NULL;
  794.     }
  795.     if (!krb4_d_principal) {            /* Default principal */
  796.         /* a Null principal indicates the user should be prompted */
  797.         char * p = ck_krb4_getprincipal();
  798.         if (!p || !(*p))
  799.           p = (char *)uidbuf;           /* Principal = user */
  800.         makestr(&(krb4_d_principal),(p && p[0]) ? p : NULL);
  801.     }
  802.     makestr(&(krb4_init.principal),krb4_d_principal);
  803. }
  804.  
  805. /*  D O A U T H  --  AUTHENTICATE action routine  */
  806.  
  807. int
  808. doauth(cx) int cx; {                    /* AUTHENTICATE action routine */
  809.     int rc = 0;                         /* Return code */
  810.  
  811. #ifdef CK_AUTHENTICATION
  812. #ifdef OS2
  813.     if (!ck_security_loaddll())         /* Load various DLLs */
  814.       return(rc);
  815. #endif /* OS2 */
  816.     if (krb_op.version == 4) {          /* Version = 4 */
  817. #ifdef COMMENT
  818.         sho_auth(AUTHTYPE_KERBEROS_V4);
  819. #endif /* COMMENT */
  820.         if (!ck_krb4_is_installed()) {
  821.             printf("?Kerberos 4 is not installed\n");
  822.             return(0);
  823.         }
  824.         switch (krb_action) {           /* Perform V4 functions */
  825.           case KRB_A_IN:                /* INIT */
  826.             rc |= !(ck_krb4_initTGT(&krb_op,&krb4_init) < 0);
  827.             break;
  828.           case KRB_A_DE:                /* DESTROY */
  829.             rc |= !(ck_krb4_destroy(&krb_op) < 0);
  830.             break;
  831.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  832.             rc |= !(ck_krb4_list_creds(&krb_op) < 0);
  833.             break;
  834.         }
  835.     }
  836.     if (krb_op.version == 5) {          /* V5 functions */
  837. #ifdef COMMENT
  838.         sho_auth(AUTHTYPE_KERBEROS_V5);
  839. #endif /* COMMENT */
  840.         if (!ck_krb5_is_installed()) {
  841.             printf("?Kerberos 5 is not installed\n");
  842.             return(0);
  843.         }
  844.         switch (krb_action) {
  845.           case KRB_A_IN:                /* INIT */
  846.             rc |= !(ck_krb5_initTGT(&krb_op,&krb5_init,
  847.                                      krb5_init.getk4 ? &krb4_init : 0) < 0);
  848.             break;
  849.           case KRB_A_DE:                /* DESTROY */
  850.             rc |= !(ck_krb5_destroy(&krb_op) < 0);
  851.             break;
  852.           case KRB_A_LC:                /* LIST-CREDENTIALS */
  853.             if (krb_op.version == 0)
  854.               printf("\n");
  855.             rc |= !(ck_krb5_list_creds(&krb_op,&krb5_lc) < 0);
  856.             break;
  857.         }
  858.     }
  859. #else
  860. #ifndef NOICP
  861. #ifndef NOSHOW
  862.     rc = sho_auth(0);                   /* Show all */
  863. #endif /* NOSHOW */
  864. #endif /* NOICP */
  865. #endif /* CK_AUTHENTICATION */
  866.     return(rc);
  867. }
  868. #endif /* CK_KERBEROS */
  869.  
  870. #ifdef TCPSOCKET
  871. #ifndef OS2
  872. #ifndef NOLISTEN                        /* For incoming connections */
  873.  
  874. #ifndef INADDR_ANY
  875. #define INADDR_ANY 0
  876. #endif /* INADDR_ANY */
  877.  
  878. _PROTOTYP( int ttbufr, ( VOID ) );
  879. _PROTOTYP( int tcpsrv_open, (char *, int *, int, int ) );
  880.  
  881. static unsigned short tcpsrv_port = 0;
  882.  
  883. #endif /* NOLISTEN */
  884. #endif /* OS2 */
  885.  
  886. static char svcbuf[80];                 /* TCP service string */
  887. static int svcnum = 0;                  /* TCP port number */
  888.  
  889. #endif /* TCPSOCKET */
  890.  
  891. /*
  892.   TCPIPLIB means use separate socket calls for i/o, while on UNIX the
  893.   normal file system calls are used for TCP/IP sockets too.
  894.   Means "DEC_TCPIP or MULTINET or WINTCP or OS2 or BEBOX" (see ckcnet.h),
  895. */
  896.  
  897. #ifdef TCPIPLIB
  898.  
  899. /* For buffered network reads... */
  900. /*
  901.   If the buffering code is written right, it shouldn't matter
  902.   how long this buffer is.
  903. */
  904. #ifdef OS2
  905. #ifdef NT
  906. #define TTIBUFL 64240                   /* 44 * 1460 (MSS) */
  907. #else
  908. #define TTIBUFL 32120                   /* 22 * 1460 (MSS) */
  909. #endif /* NT */
  910. #else /* OS2 */
  911. #define TTIBUFL 8191                    /* Let's use 8K. */
  912. #endif /* OS2 */
  913.  
  914. CHAR ttibuf[TTIBUFL+1];
  915.  
  916. /*
  917.   select() is used in preference to alarm()/signal(), but different systems
  918.   use different forms of select()...
  919. */
  920. #ifndef NOSELECT         /* Option to override BSDSELECT */
  921. #ifdef BELLV10
  922. /*
  923.   Note: Although BELLV10 does have TCP/IP support, and does use the unique
  924.   form of select() that is evident in this module (and in ckutio.c), it does
  925.   not have a sockets library and so we can't build Kermit TCP/IP support for
  926.   it.  For this, somebody would have to write TCP/IP streams code.
  927. */
  928. #define BELLSELECT
  929. #ifndef FD_SETSIZE
  930. #define FD_SETSIZE 128
  931. #endif /* FD_SETSIZE */
  932. #else
  933. #ifdef WINTCP                           /* VMS with Wollongong WIN/TCP */
  934. #ifndef OLD_TWG                         /* TWG 3.2 has only select(read) */
  935. #define BSDSELECT
  936. #endif /* OLD_TWG */
  937. #else
  938. #ifdef CMU_TCPIP                        /* LIBCMU can do select */
  939. #define BSDSELECT
  940. #else
  941. #ifdef DEC_TCPIP
  942. #define BSDSELECT
  943. #else
  944. #ifdef OS2                              /* OS/2 with TCP/IP */
  945. #ifdef NT
  946. #define BSDSELECT
  947. #else /* NT */
  948. #define IBMSELECT
  949. #endif /* NT */
  950. #endif /* OS2 */
  951. #endif /* DEC_TCPIP */
  952. #endif /* CMU_TCPIP */
  953. #endif /* WINTCP */
  954. #endif /* BELLV10 */
  955. #endif /* NOSELECT */
  956. /*
  957.   Others (TGV, TCPware, ...) use alarm()/signal().  The BSDSELECT case does not
  958.   compile at all; the IBMSELECT case compiles and links but crashes at runtime.
  959.   NOTE: If any of these can be converted to select(), they should be for two
  960.   reasons: (1) It's a lot faster; (2) certain sockets libraries do not like
  961.   their socket_read() calls to be interrupted; subsequent socket_read()'s tend
  962.   to fail with EBUSY.  This happened in the UCX case before it was converted
  963.   to use select().
  964. */
  965. #ifndef OS2
  966. #ifndef VMS
  967. static                                  /* These are used in CKVTIO.C */
  968. #endif /* VMS */                        /* And in CKONET.C            */
  969. #endif /* OS2 */
  970. int
  971.   ttibp = 0,
  972.   ttibn = 0;
  973. /*
  974.   Read bytes from network into internal buffer ttibuf[].
  975.   To be called when input buffer is empty, i.e. when ttibn == 0.
  976.  
  977.   Other network reading routines, like ttinc, ttinl, ttxin, should check the
  978.   internal buffer first, and call this routine for a refill if necessary.
  979.  
  980.   Returns -1 on error, 0 if nothing happens.  When data is read successfully,
  981.   returns number of bytes read, and sets global ttibn to that number and
  982.   ttibp (the buffer pointer) to zero.
  983. */
  984. _PROTOTYP( int ttbufr, ( VOID ) );
  985. int
  986. ttbufr() {                              /* TT Buffer Read */
  987.     int count;
  988.  
  989.     if (ttnet != NET_TCPB)              /* First make sure current net is */
  990.       return(-1);                       /* TCP/IP; if not, do nothing. */
  991.  
  992. #ifdef OS2
  993.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  994. #endif /* OS2 */
  995.  
  996.     if (ttibn > 0) {                    /* Our internal buffer is not empty, */
  997. #ifdef OS2
  998.         ReleaseTCPIPMutex();
  999. #endif /* OS2 */
  1000.         return(ttibn);                  /* so keep using it. */
  1001.     }
  1002.  
  1003.     if (ttyfd == -1) {                  /* No connection, error */
  1004. #ifdef OS2
  1005.         ReleaseTCPIPMutex();
  1006. #endif /* OS2 */
  1007.         return(-2);
  1008.     }
  1009.  
  1010.     ttibp = 0;                          /* Else reset pointer to beginning */
  1011.  
  1012. #ifdef WINTCP
  1013.     count = 512;                        /* This works for WIN/TCP */
  1014. #else
  1015. #ifdef DEC_TCPIP
  1016.     count = 512;                        /* UCX */
  1017. #else
  1018. #ifdef OS2
  1019.     count = TTIBUFL;
  1020. #else                                   /* Multinet, etc. */
  1021.     count = ttchk();                    /* Check network input buffer, */
  1022.     if (ttibn > 0) {                    /* which can put a char there! */
  1023.         debug(F111,"ttbufr","ttchk() returns",count);
  1024. #ifdef OS2
  1025.         ReleaseTCPIPMutex();
  1026. #endif /* OS2 */
  1027.         return(ttibn);
  1028.     }
  1029.     if (count < 0) {                     /* Read error - connection closed */
  1030. #ifdef OS2
  1031.         ReleaseTCPIPMutex();
  1032. #endif /* OS2 */
  1033.         return(-2);
  1034.     }
  1035.     else if (count > TTIBUFL)           /* Too many to read */
  1036.       count = TTIBUFL;
  1037.     else if (count == 0)                /* None, so force blocking read */
  1038.       count = 1;
  1039. #endif /* OS2 */
  1040. #endif /* DEC_TCPIP */
  1041. #endif /* WINTCP */
  1042.     debug(F101,"ttbufr count 1","",count);
  1043.  
  1044. #ifdef CK_SSL
  1045.     if (ssl_active_flag || tls_active_flag) {
  1046.         int error;
  1047.         if (ssl_active_flag)
  1048.           count = SSL_read(ssl_con, ttibuf, count);
  1049.         else
  1050.           count = SSL_read(tls_con, ttibuf, count);
  1051.         error = SSL_get_error(ssl_active_flag?ssl_con:tls_con,count);
  1052.         switch (error) {
  1053.           case SSL_ERROR_NONE:
  1054.             debug(F111,"ttbufr SSL_ERROR_NONE","count",count);
  1055.             if (count > 0) {
  1056.                 ttibp = 0;              /* Reset buffer pointer. */
  1057.                 ttibn = count;
  1058. #ifdef OS2
  1059.                 ReleaseTCPIPMutex();
  1060. #endif /* OS2 */
  1061.                 return(ttibn);          /* Return buffer count. */
  1062.             } else if (count < 0) {
  1063. #ifdef OS2
  1064.                 ReleaseTCPIPMutex();
  1065. #endif /* OS2 */
  1066.                 return(-1);
  1067.             } else {
  1068.                 netclos();
  1069. #ifdef OS2
  1070.                 ReleaseTCPIPMutex();
  1071. #endif /* OS2 */
  1072.                 return(-2);
  1073.             }
  1074.           case SSL_ERROR_WANT_WRITE:
  1075.             debug(F100,"ttbufr SSL_ERROR_WANT_WRITE","",0);
  1076. #ifdef OS2
  1077.               ReleaseTCPIPMutex();
  1078. #endif /* OS2 */
  1079.             return(-1);
  1080.           case SSL_ERROR_WANT_READ:
  1081.             debug(F100,"ttbufr SSL_ERROR_WANT_READ","",0);
  1082. #ifdef OS2
  1083.               ReleaseTCPIPMutex();
  1084. #endif /* OS2 */
  1085.             return(-1);
  1086.           case SSL_ERROR_SYSCALL:
  1087.               if ( count == 0 ) { /* EOF */
  1088.                   netclos();
  1089. #ifdef OS2
  1090.                   ReleaseTCPIPMutex();
  1091. #endif /* OS2 */
  1092.                   return(-2);
  1093.               } else {
  1094.                   int rc = -1;
  1095. #ifdef NT
  1096.                   int gle = GetLastError();
  1097.                   debug(F111,"ttbufr SSL_ERROR_SYSCALL",
  1098.                          "GetLastError()",gle);
  1099.                   rc = os2socketerror(gle);
  1100.                   if (rc == -1)
  1101.                       rc = -2;
  1102.                   else if ( rc == -2 )
  1103.                       return -1;
  1104. #endif /* NT */
  1105. #ifdef OS2
  1106.                   ReleaseTCPIPMutex();
  1107. #endif /* OS2 */
  1108.                   return(rc);
  1109.               }
  1110.           case SSL_ERROR_WANT_X509_LOOKUP:
  1111.             debug(F100,"ttbufr SSL_ERROR_WANT_X509_LOOKUP","",0);
  1112.             netclos();
  1113. #ifdef OS2
  1114.               ReleaseTCPIPMutex();
  1115. #endif /* OS2 */
  1116.             return(-2);
  1117.           case SSL_ERROR_SSL:
  1118.             debug(F100,"ttbufr SSL_ERROR_SSL","",0);
  1119. #ifdef COMMENT
  1120.             netclos();
  1121. #endif /* COMMENT */
  1122. #ifdef OS2
  1123.               ReleaseTCPIPMutex();
  1124. #endif /* OS2 */
  1125.             return(-2);
  1126.           case SSL_ERROR_ZERO_RETURN:
  1127.             debug(F100,"ttbufr SSL_ERROR_ZERO_RETURN","",0);
  1128.             netclos();
  1129. #ifdef OS2
  1130.               ReleaseTCPIPMutex();
  1131. #endif /* OS2 */
  1132.             return(-2);
  1133.           default:
  1134.               debug(F100,"ttbufr SSL_ERROR_?????","",0);
  1135.               netclos();
  1136. #ifdef OS2
  1137.               ReleaseTCPIPMutex();
  1138. #endif /* OS2 */
  1139.               return(-2);
  1140.           }
  1141.     }
  1142. #endif /* CK_SSL */
  1143.  
  1144. #ifdef COMMENT
  1145. /*
  1146.  This is for nonblocking reads, which we don't do any more.  This code didn't
  1147.  work anyway, in the sense that a broken connection was never sensed.
  1148. */
  1149.     if ((count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count)) < 1) {
  1150.         if (count == -1 && socket_errno == EWOULDBLOCK) {
  1151.             debug(F100,"ttbufr finds nothing","",0);
  1152. #ifdef OS2
  1153.             ReleaseTCPIPMutex();
  1154. #endif /* OS2 */
  1155.             return(0);
  1156.         } else {
  1157.             debug(F101,"ttbufr socket_read error","",socket_errno);
  1158. #ifdef OS2
  1159.             ReleaseTCPIPMutex();
  1160. #endif /* OS2 */
  1161.             return(-1);
  1162.         }
  1163.  
  1164.     } else if (count == 0) {
  1165.         debug(F100,"ttbufr socket eof","",0);
  1166. #ifdef OS2
  1167.         ReleaseTCPIPMutex();
  1168. #endif /* OS2 */
  1169.         return(-1);
  1170.     }
  1171. #else /* COMMENT */
  1172.  
  1173. /* This is for blocking reads */
  1174.  
  1175. #ifndef VMS
  1176. #ifdef SO_OOBINLINE
  1177.     {
  1178.         int outofband = 0;
  1179. #ifdef BELLSELECT
  1180.         if (select(128, NULL, NULL, efds, 0) > 0 && FD_ISSET(ttyfd, efds))
  1181.           outofband = 1;
  1182. #else
  1183. #ifdef BSDSELECT
  1184.         fd_set efds;
  1185.         struct timeval tv;
  1186.         FD_ZERO(&efds);
  1187.         FD_SET(ttyfd, &efds);
  1188.         tv.tv_sec  = tv.tv_usec = 0L;
  1189.         debug(F100,"Out-of-Band BSDSELECT","",0);
  1190. #ifdef NT
  1191.         WSASafeToCancel = 1;
  1192. #endif /* NT */
  1193.         if (select(FD_SETSIZE, NULL, NULL, &efds, &tv) > 0 &&
  1194.             FD_ISSET(ttyfd, &efds))
  1195.           outofband = 1;
  1196. #ifdef NT
  1197.         WSASafeToCancel = 0;
  1198. #endif /* NT */
  1199. #else /* !BSDSELECT */
  1200. #ifdef IBMSELECT
  1201. /* Is used by OS/2 ... */
  1202. /* ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set */
  1203. /* and timeval stuff since this is the only place where it is used. */
  1204.         int socket = ttyfd;
  1205.         debug(F100,"Out-of-Band IBMSELECT","",0);
  1206.         if ((select(&socket, 0, 0, 1, 0L) == 1) && (socket == ttyfd))
  1207.           outofband = 1;
  1208. #else /* !IBMSELECT */
  1209. /*
  1210.   If we can't use select(), then we use the regular alarm()/signal()
  1211.   timeout mechanism.
  1212. */
  1213.       debug(F101,"Out-of-Band data not supported","",0);
  1214.       outofband = 0;
  1215.  
  1216. #endif /* IBMSELECT */
  1217. #endif /* BSDSELECT */
  1218. #endif /* BELLSELECT */
  1219.       if (outofband) {
  1220.          /* Get the Urgent Data */
  1221.          /* if OOBINLINE is disabled this should be only a single byte      */
  1222.          /* MS Winsock has a bug in Windows 95.  Extra bytes are delivered  */
  1223.          /* That were never sent.                                           */
  1224. #ifdef OS2
  1225.           RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  1226. #endif /* OS2 */
  1227.           count = socket_recv(ttyfd,&ttibuf[ttibp+ttibn],count,MSG_OOB);
  1228. #ifdef OS2
  1229.           ReleaseTCPIPMutex();
  1230. #endif /* OS2 */
  1231.           if (count <= 0) {
  1232.               int s_errno = socket_errno;
  1233.               debug(F101, "ttbufr socket_recv MSG_OOB","",count);
  1234.               debug(F101, "ttbufr socket_errno","",s_errno);
  1235. #ifdef OS2ONLY
  1236.               if (count < 0 && (s_errno == 0 || s_errno == 23)) {
  1237.                   /* These appear in OS/2 - don't know why   */
  1238.                   /* ignore it and read as normal data       */
  1239.                   /* and break, then we will attempt to read */
  1240.                   /* the port using normal read() techniques */
  1241.                   debug(F100,"ttbufr handing as in-band data","",0);
  1242.                   count = 1;
  1243.               } else {
  1244.                   netclos();                    /* *** *** */
  1245. #ifdef OS2
  1246.                   ReleaseTCPIPMutex();
  1247. #endif /* OS2 */
  1248.                   return(-2);
  1249.               }
  1250. #else /* OS2ONLY */
  1251.               netclos();                        /* *** *** */
  1252. #ifdef OS2
  1253.               ReleaseTCPIPMutex();
  1254. #endif /* OS2 */
  1255.               return(-2);
  1256. #endif /* OS2ONLY */
  1257.           } else {                      /* we got out-of-band data */
  1258.               hexdump("ttbufr out-of-band chars",&ttibuf[ttibp+ttibn],count);
  1259. #ifdef BETADEBUG
  1260.               bleep(BP_NOTE);
  1261. #endif /* BETADEBUG */
  1262. #ifdef RLOGCODE                         /* blah */
  1263.               if (ttnproto == NP_RLOGIN  ||
  1264.                   ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  1265.                   ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  1266.                    )
  1267.               {
  1268.                   /*
  1269.                     When urgent data is read with MSG_OOB and not OOBINLINE
  1270.                     then urgent data and normal data are not mixed.  So
  1271.                     treat the entire buffer as urgent data.
  1272.                   */
  1273.                   rlog_oob(&ttibuf[ttibp+ttibn], count);
  1274. #ifdef OS2
  1275.                   ReleaseTCPIPMutex();
  1276. #endif /* OS2 */
  1277.                   return ttbufr();
  1278.               } else
  1279. #endif /* RLOGCODE */ /* blah */
  1280. #ifdef COMMENT
  1281.             /*
  1282.                I haven't written this yet, nor do I know what it should do
  1283.              */
  1284.                 if (ttnproto == NP_TELNET) {
  1285.                     tn_oob();
  1286. #ifdef OS2
  1287.                     ReleaseTCPIPMutex();
  1288. #endif /* OS2 */
  1289.                     return 0;
  1290.               } else
  1291. #endif /* COMMENT */
  1292.               {
  1293.                   /* For any protocols we don't have a special out-of-band  */
  1294.                   /* handler for, just put the bytes in the normal buffer   */
  1295.                   /* and return                                             */
  1296.  
  1297.                   ttibp += 0;       /* Reset buffer pointer. */
  1298.                   ttibn += count;
  1299. #ifdef DEBUG
  1300.                   /* Got some bytes. */
  1301.                   debug(F101,"ttbufr count 2","",count);
  1302.                   if (count > 0)
  1303.                       ttibuf[ttibp+ttibn] = '\0';
  1304.                   debug(F111,"ttbufr ttibuf",ttibuf,ttibp);
  1305. #endif /* DEBUG */
  1306. #ifdef OS2
  1307.                   ReleaseTCPIPMutex();
  1308. #endif /* OS2 */
  1309.                   return(ttibn);    /* Return buffer count. */
  1310.               }
  1311.           }
  1312.       }
  1313.     }
  1314. #endif /* SO_OOBINLINE */
  1315. #endif /* VMS */
  1316.  
  1317.     count = socket_read(ttyfd,&ttibuf[ttibp+ttibn],count);
  1318.     if (count <= 0) {
  1319.         int s_errno = socket_errno;
  1320.         debug(F101,"ttbufr socket_read","",count);
  1321.         debug(F101,"ttbufr socket_errno","",s_errno);
  1322. #ifdef OS2
  1323.         if (count == 0 || os2socketerror(s_errno) < 0) {
  1324.             netclos();
  1325.             ReleaseTCPIPMutex();
  1326.             return(-2);
  1327.         }
  1328.         ReleaseTCPIPMutex();
  1329.         return(-1);
  1330. #else /* OS2 */
  1331.         netclos();                      /* *** *** */
  1332.         return(-2);
  1333. #endif /* OS2 */
  1334.     }
  1335. #endif /* COMMENT */ /* (blocking vs nonblock reads...) */
  1336.     else {
  1337.         ttibp = 0;                      /* Reset buffer pointer. */
  1338.         ttibn += count;
  1339. #ifdef DEBUG
  1340.         debug(F101,"ttbufr count 2","",count); /* Got some bytes. */
  1341.         if (count > 0)
  1342.           ttibuf[ttibp+ttibn] = '\0';
  1343.         debug(F111,"ttbufr ttibuf",&ttibuf[ttibp],ttibn);
  1344. #endif /* DEBUG */
  1345. #ifdef OS2
  1346.         ReleaseTCPIPMutex();
  1347. #endif /* OS2 */
  1348.         return(ttibn);                  /* Return buffer count. */
  1349.     }
  1350. }
  1351. #endif /* TCPIPLIB */
  1352.  
  1353. #ifndef IBMSELECT
  1354. #ifndef BELLSELECT
  1355. #ifndef BSDSELECT               /* Non-TCPIPLIB case */
  1356. #ifdef SELECT
  1357. #define BSDSELECT
  1358. #endif /* SELECT */
  1359. #endif /* BSDSELECT */
  1360. #endif /* BELLSELECT */
  1361. #endif /* IBMSELECT */
  1362.  
  1363. #define TELNET_PORT 23          /* Should do lookup, but it won't change */
  1364. #define RLOGIN_PORT 513
  1365. #define KERMIT_PORT 1649
  1366. #define KLOGIN_PORT 543
  1367. #define EKLOGIN_PORT 2105
  1368.  
  1369. #ifndef NONET
  1370. /*
  1371.   C-Kermit network open/close functions for BSD-sockets.
  1372.   Much of this code shared by SunLink X.25, which also uses the socket library.
  1373. */
  1374.  
  1375. /*  N E T O P N  --  Open a network connection.  */
  1376. /*
  1377.   Call with:
  1378.     name of host (or host:service),
  1379.     lcl - local-mode flag to be set if this function succeeds,
  1380.     network type - value defined in ckunet.h.
  1381. */
  1382. #ifdef TCPSOCKET
  1383. struct hostent *
  1384. #ifdef CK_ANSIC
  1385. ck_copyhostent(struct hostent * h)
  1386. #else /* CK_ANSIC */
  1387. ck_copyhostent(h) struct hostent * h;
  1388. #endif /* CK_ANSIC */
  1389. {
  1390.     /*
  1391.      *  The hostent structure is dynamic in nature.
  1392.      *  struct  hostent {
  1393.      *  char    * h_name;
  1394.      *  char    * * h_aliases;
  1395.      *  short   h_addrtype;
  1396.      *  short   h_length;
  1397.      *  char    * * h_addr_list;
  1398.      *  #define h_addr  h_addr_list[0]
  1399.      */
  1400. #define HOSTENTCNT 5
  1401.     static struct hostent hosts[HOSTENTCNT] = {{NULL,NULL,0,0,NULL},
  1402.                                                {NULL,NULL,0,0,NULL},
  1403.                                                {NULL,NULL,0,0,NULL},
  1404.                                                {NULL,NULL,0,0,NULL},
  1405.                                                {NULL,NULL,0,0,NULL}};
  1406.     static int    next = 0;
  1407.     int    i,cnt;
  1408.     char ** pp;
  1409.  
  1410.     if ( h == NULL )
  1411.         return(NULL);
  1412.  
  1413.     if (next == HOSTENTCNT)
  1414.         next = 0;
  1415.  
  1416.     if ( hosts[next].h_name ) {
  1417.         free(hosts[next].h_name);
  1418.         hosts[next].h_name = NULL;
  1419.     }
  1420.     if ( hosts[next].h_aliases ) {
  1421.         pp = hosts[next].h_aliases;
  1422.         while ( *pp ) {
  1423.             free(*pp);
  1424.             pp++;
  1425.         }
  1426.         free(hosts[next].h_aliases);
  1427.     }
  1428. #ifdef HADDRLIST
  1429.     if ( hosts[next].h_addr_list ) {
  1430.         pp = hosts[next].h_addr_list;
  1431.         while ( *pp ) {
  1432.             free(*pp);
  1433.             pp++;
  1434.         }
  1435.         free(hosts[next].h_addr_list);
  1436.     }
  1437. #endif /* HADDRLIST */
  1438.  
  1439.     makestr(&hosts[next].h_name,h->h_name);
  1440.     if (h->h_aliases) {
  1441.         for ( cnt=0,pp=h->h_aliases; pp && *pp; pp++,cnt++) ;
  1442.         /* The following can give warnings in non-ANSI builds */
  1443.         hosts[next].h_aliases = (char **) malloc(sizeof(char *) * (cnt+1));
  1444.         for ( i=0; i<cnt; i++) {
  1445.             hosts[next].h_aliases[i] = NULL;
  1446.             makestr(&hosts[next].h_aliases[i],h->h_aliases[i]);
  1447.         }
  1448.         hosts[next].h_aliases[i] = NULL;
  1449.     } else
  1450.         hosts[next].h_aliases = NULL;
  1451.  
  1452.     hosts[next].h_addrtype = h->h_addrtype;
  1453.     hosts[next].h_length = h->h_length;
  1454.  
  1455. #ifdef HADDRLIST
  1456. #ifdef h_addr
  1457.     if (h->h_addr_list) {
  1458.         for ( cnt=0,pp=h->h_addr_list; pp && *pp; pp++,cnt++) ;
  1459.         /* The following can give warnings non-ANSI builds */
  1460.         hosts[next].h_addr_list = (char **) malloc(sizeof(char *) * (cnt+1));
  1461.         for ( i=0; i<cnt; i++) {
  1462.             hosts[next].h_addr_list[i] = malloc(h->h_length);
  1463.             bcopy(h->h_addr_list[i],hosts[next].h_addr_list[i],h->h_length);
  1464.         }
  1465.         hosts[next].h_addr_list[i] = NULL;
  1466.     } else
  1467.         hosts[next].h_addr_list = NULL;
  1468. #else
  1469.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1470. #endif /* h_addr */
  1471. #else /* HADDRLIST */
  1472.     bcopy(h->h_addr, &hosts[next].h_addr, h->h_length);
  1473. #endif /* HADDRLIST */
  1474.  
  1475.     return(&hosts[next++]);
  1476. }
  1477.  
  1478. #ifdef EXCELAN
  1479. /*
  1480.   Most other BSD sockets implementations define these in header files
  1481.   and libraries.
  1482. */
  1483. struct servent {
  1484.     unsigned short s_port;
  1485. };
  1486.  
  1487. struct hostent {
  1488.     short h_addrtype;
  1489.     struct in_addr h_addr;
  1490.     int h_length;
  1491. };
  1492.  
  1493. struct servent *
  1494. getservbyname(service, connection) char *service,*connection; {
  1495.     static struct servent servrec;
  1496.     int port;
  1497.  
  1498.     port = 0;
  1499.     if (strcmp(service, "telnet") == 0) port = 23;
  1500.     else if (strcmp(service, "smtp") == 0) port = 25;
  1501.     else port = atoi(service);
  1502.  
  1503.     debug(F101,"getservbyname return port ","",port);
  1504.  
  1505.     if (port > 0) {
  1506.         servrec.s_port = htons(port);
  1507.         return(&servrec);
  1508.     }
  1509.     return((struct servent *) NULL);
  1510. }
  1511.  
  1512. struct hostent *
  1513. gethostbyname(hostname) char *hostname; {
  1514.     return((struct hostent *) NULL);
  1515. }
  1516.  
  1517. unsigned long
  1518. inet_addr(name) char *name; {
  1519.     unsigned long addr;
  1520.  
  1521.     addr = rhost(&name);
  1522.     debug(F111,"inet_addr ",name,(int)addr);
  1523.     return(addr);
  1524. }
  1525.  
  1526. char *
  1527. inet_ntoa(in) struct in_addr in; {
  1528.     static char name[80];
  1529.     ckmakxmsg(name, ckuitoa(in.s_net),".",ckuitoa(in.s_host),".",
  1530.                ckuitoa(in.s_lh),".", ckuitoa(in.s_impno));
  1531.     return(name);
  1532. }
  1533. #else
  1534. #ifdef DEC_TCPIP                        /* UCX */
  1535.  
  1536. int ucx_port_bug = 0;                   /* Explained below */
  1537.  
  1538. #ifndef __DECC                          /* VAXC or GCC */
  1539.  
  1540. #define getservbyname my_getservbyname
  1541.  
  1542. #ifdef CK_ANSIC
  1543. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1544. extern void C$$TRANSLATE();
  1545. extern void C$$SOCK_TRANSLATE();
  1546. #else
  1547. globalref int (*C$$GA_UCX_GETSERVBYNAME)();
  1548. extern VOID C$$TRANSLATE();
  1549. extern VOID C$$SOCK_TRANSLATE();
  1550. #endif /* CK_ANSIC */
  1551.  
  1552. struct servent *
  1553. my_getservbyname (service, proto) char *service, *proto; {
  1554.     static struct servent sent;
  1555.     struct iosb {
  1556.         union {
  1557.             unsigned long status;
  1558.             unsigned short st[2];
  1559.         } sb;
  1560.         unsigned long spare;
  1561.     } s;
  1562.     struct {
  1563.         struct iosb *s;
  1564.         char *serv;
  1565.         char *prot;
  1566.     } par;
  1567.     unsigned long e;
  1568.     char sbuf[30], pbuf[30];
  1569.     char *p;
  1570.  
  1571.     debug(F111,"UCX getservbyname",service,(int)C$$GA_UCX_GETSERVBYNAME);
  1572.  
  1573.     p = sbuf;
  1574.     ckstrncpy(p, service, 29);
  1575.     while (*p = toupper(*p), *p++) {}
  1576.     p = pbuf;
  1577.     ckstrncpy(p, proto, 29);
  1578.     while (*p = toupper(*p), *p++) {}
  1579.  
  1580.     par.s = &s;
  1581.  
  1582.     par.serv = "";
  1583.     par.prot = "";
  1584.     /* reset file pointer or something like that!?!? */
  1585.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1586.     par.serv = sbuf;
  1587.     par.prot = pbuf;            /* that is don't care */
  1588.     e = (*C$$GA_UCX_GETSERVBYNAME)(&par, &sent, par.s);
  1589.     if ((long)e == -1L)
  1590.       return NULL;
  1591.     if ((e & 1) == 0L) {
  1592.         C$$TRANSLATE(e);
  1593.         return NULL;
  1594.     }
  1595.     if ((s.sb.st[0] & 1) == 0) {
  1596.         C$$SOCK_TRANSLATE(&s.sb.st[0]);
  1597.         return NULL;
  1598.     }
  1599. /*
  1600.   sent.s_port is supposed to be returned by UCX in network byte order.
  1601.   However, UCX 2.0 through 2.0C did not do this; 2.0D and later do it.
  1602.   But there is no way of knowing which UCX version, so we have a user-settable
  1603.   runtime variable.  Note: UCX 2.0 was only for the VAX.
  1604. */
  1605.     debug(F101,"UCX getservbyname port","",sent.s_port);
  1606.     debug(F101,"UCX getservbyname ntohs(port)","",ntohs(sent.s_port));
  1607.     if (ucx_port_bug) {
  1608.         sent.s_port = htons(sent.s_port);
  1609.         debug(F100,"UCX-PORT-BUG ON: swapping bytes","",0);
  1610.         debug(F101,"UCX swapped port","",sent.s_port);
  1611.         debug(F101,"UCX swapped ntohs(port)","",ntohs(sent.s_port));
  1612.     }
  1613.     return &sent;
  1614. }
  1615. #endif /* __DECC */
  1616. #endif /* DEC_TCPIP */
  1617. #endif /* EXCELAN */
  1618. #endif /* TCPSOCKET */
  1619.  
  1620. #ifndef NOTCPOPTS
  1621. #ifndef datageneral
  1622. int
  1623. ck_linger(sock, onoff, timo) int sock; int onoff; int timo; {
  1624. /*
  1625.   The following, from William Bader, turns off the socket linger parameter,
  1626.   which makes a close() block until all data is sent.  "I don't think that
  1627.   disabling linger can ever cause kermit to lose data, but you telnet to a
  1628.   flaky server (or to our modem server when the modem is in use), disabling
  1629.   linger prevents kermit from hanging on the close if you try to exit."
  1630.  
  1631.   Modified by Jeff Altman to be generally useful.
  1632. */
  1633. #ifdef SOL_SOCKET
  1634. #ifdef SO_LINGER
  1635.     struct linger set_linger_opt;
  1636.     struct linger get_linger_opt;
  1637.     SOCKOPT_T x;
  1638.  
  1639. #ifdef IKSD
  1640.     if (!inserver)
  1641. #endif /* IKSD */
  1642.       if (sock == -1 ||
  1643.         nettype != NET_TCPA && nettype != NET_TCPB &&
  1644.         nettype != NET_SSH || ttmdm >= 0) {
  1645.         tcp_linger = onoff;
  1646.         tcp_linger_tmo = timo;
  1647.         return(1);
  1648.     }
  1649.     x = sizeof(get_linger_opt);
  1650.     if (getsockopt(sock, SOL_SOCKET, SO_LINGER,
  1651.                     (char *)&get_linger_opt, &x)) {
  1652.         debug(F111,"TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1653.     } else if (x != sizeof(get_linger_opt)) {
  1654. #ifdef OS2
  1655.         struct _linger16 {
  1656.             short s_linger;
  1657.             short s_onoff;
  1658.         } get_linger_opt16, set_linger_opt16;
  1659.         if ( x == sizeof(get_linger_opt16) ) {
  1660.             debug(F111,"TCP setlinger warning: SO_LINGER","len is 16-bit",x);
  1661.             if (getsockopt(sock,
  1662.                            SOL_SOCKET, SO_LINGER,
  1663.                            (char *)&get_linger_opt16, &x)
  1664.                 ) {
  1665.                 debug(F111,
  1666.                       "TCP ck_linger can't get SO_LINGER",ck_errstr(),errno);
  1667.             } else if (get_linger_opt16.s_onoff != onoff ||
  1668.                        get_linger_opt16.s_linger != timo)
  1669.             {
  1670.                 set_linger_opt16.s_onoff  = onoff;
  1671.                 set_linger_opt16.s_linger = timo;
  1672.                 if (setsockopt(sock,
  1673.                                SOL_SOCKET,
  1674.                                SO_LINGER,
  1675.                                (char *)&set_linger_opt16,
  1676.                                sizeof(set_linger_opt16))
  1677.                     ) {
  1678.                     debug(F111,
  1679.                           "TCP ck_linger can't set SO_LINGER",
  1680.                           ck_errstr(),
  1681.                           errno
  1682.                           );
  1683.                     tcp_linger = get_linger_opt16.s_onoff;
  1684.                     tcp_linger_tmo = get_linger_opt16.s_linger;
  1685.                 } else {
  1686.                     debug(F101,
  1687.                           "TCP ck_linger new SO_LINGER","",
  1688.                           set_linger_opt16.s_onoff);
  1689.                     tcp_linger = set_linger_opt16.s_onoff;
  1690.                     tcp_linger_tmo = set_linger_opt16.s_linger;
  1691.                     return 1;
  1692.                 }
  1693.             } else {
  1694.                 debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1695.                        get_linger_opt16.s_onoff);
  1696.                 tcp_linger = get_linger_opt16.s_onoff;
  1697.                 tcp_linger_tmo = get_linger_opt16.s_linger;
  1698.                 return 1;
  1699.             }
  1700.             return(0);
  1701.         }
  1702. #endif /* OS2 */
  1703.         debug(F111,"TCP ck_linger error: SO_LINGER","len",x);
  1704.         debug(F111,"TCP ck_linger SO_LINGER",
  1705.               "expected len",sizeof(get_linger_opt));
  1706.         debug(F111,"TCP ck_linger SO_LINGER","linger_opt.l_onoff",
  1707.               get_linger_opt.l_onoff);
  1708.         debug(F111,"TCP linger SO_LINGER","linger_opt.l_linger",
  1709.                get_linger_opt.l_linger);
  1710.     } else if (get_linger_opt.l_onoff != onoff ||
  1711.                get_linger_opt.l_linger != timo) {
  1712.         set_linger_opt.l_onoff  = onoff;
  1713.         set_linger_opt.l_linger = timo;
  1714.         if (setsockopt(sock,
  1715.                        SOL_SOCKET,
  1716.                        SO_LINGER,
  1717.                        (char *)&set_linger_opt,
  1718.                        sizeof(set_linger_opt))) {
  1719.             debug(F111,"TCP ck_linger can't set SO_LINGER",ck_errstr(),errno);
  1720.             tcp_linger = get_linger_opt.l_onoff;
  1721.             tcp_linger_tmo = get_linger_opt.l_linger;
  1722.          } else {
  1723.              debug(F101,
  1724.                    "TCP ck_linger new SO_LINGER",
  1725.                    "",
  1726.                    set_linger_opt.l_onoff
  1727.                    );
  1728.              tcp_linger = set_linger_opt.l_onoff;
  1729.              tcp_linger_tmo = set_linger_opt.l_linger;
  1730.              return 1;
  1731.          }
  1732.     } else {
  1733.         debug(F101,"TCP ck_linger SO_LINGER unchanged","",
  1734.               get_linger_opt.l_onoff);
  1735.         tcp_linger = get_linger_opt.l_onoff;
  1736.         tcp_linger_tmo = get_linger_opt.l_linger;
  1737.         return 1;
  1738.     }
  1739. #else
  1740.     debug(F100,"TCP ck_linger SO_LINGER not defined","",0);
  1741. #endif /* SO_LINGER */
  1742. #else
  1743.     debug(F100,"TCP ck_linger SO_SOCKET not defined","",0);
  1744. #endif /* SOL_SOCKET */
  1745.     return(0);
  1746. }
  1747.  
  1748. int
  1749. sendbuf(sock,size) int sock; int size; {
  1750. /*
  1751.   The following, from William Bader, allows changing of socket buffer sizes,
  1752.   in case that might affect performance.
  1753.  
  1754.   Modified by Jeff Altman to be generally useful.
  1755. */
  1756. #ifdef SOL_SOCKET
  1757. #ifdef SO_SNDBUF
  1758.     int i, j;
  1759.     SOCKOPT_T x;
  1760.  
  1761. #ifdef IKSD
  1762.     if (!inserver)
  1763. #endif /* IKSD */
  1764.       if (sock == -1 ||
  1765.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  1766.                 || ttmdm >= 0) {
  1767.         tcp_sendbuf = size;
  1768.         return 1;
  1769.     }
  1770.     x = sizeof(i);
  1771.     if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&i, &x)) {
  1772.         debug(F111,"TCP sendbuf can't get SO_SNDBUF",ck_errstr(),errno);
  1773.     } else if (x != sizeof(i)) {
  1774. #ifdef OS2
  1775.         short i16,j16;
  1776.         if (x == sizeof(i16)) {
  1777.             debug(F111,"TCP sendbuf warning: SO_SNDBUF","len is 16-bit",x);
  1778.             if (getsockopt(sock,
  1779.                            SOL_SOCKET, SO_SNDBUF,
  1780.                            (char *)&i16, &x)
  1781.                 ) {
  1782.                 debug(F111,"TCP sendbuf can't get SO_SNDBUF",
  1783.                       ck_errstr(),errno);
  1784.             } else if (size <= 0) {
  1785.                 tcp_sendbuf = i16;
  1786.                 debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i16);
  1787.                 return 1;
  1788.             } else if (i16 != size) {
  1789.                 j16 = size;
  1790.                 if (setsockopt(sock,
  1791.                                SOL_SOCKET,
  1792.                                SO_SNDBUF,
  1793.                                (char *)&j16,
  1794.                                sizeof(j16))
  1795.                     ) {
  1796.                     debug(F111,"TCP sendbuf can't set SO_SNDBUF",
  1797.                           ck_errstr(),errno);
  1798.                 } else {
  1799.                     debug(F101,"TCP sendbuf old SO_SNDBUF","",i16);
  1800.                     debug(F101,"TCP sendbuf new SO_SNDBUF","",j16);
  1801.                     tcp_sendbuf = size;
  1802.                     return 1;
  1803.                 }
  1804.             } else {
  1805.                 debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i16);
  1806.                 tcp_sendbuf = size;
  1807.                 return 1;
  1808.             }
  1809.             return(0);
  1810.         }
  1811. #endif /* OS2 */
  1812.         debug(F111,"TCP sendbuf error: SO_SNDBUF","len",x);
  1813.         debug(F111,"TCP sendbuf SO_SNDBUF","expected len",sizeof(i));
  1814.         debug(F111,"TCP sendbuf SO_SNDBUF","i",i);
  1815.     } else if (size <= 0) {
  1816.         tcp_sendbuf = i;
  1817.         debug(F101,"TCP sendbuf SO_SNDBUF retrieved","",i);
  1818.         return 1;
  1819.     } else if (i != size) {
  1820.         j = size;
  1821.         if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&j, sizeof(j))) {
  1822.             debug(F111,"TCP sendbuf can't set SO_SNDBUF",ck_errstr(),errno);
  1823.             tcp_sendbuf = i;
  1824.         } else {
  1825.             debug(F101,"TCP sendbuf old SO_SNDBUF","",i);
  1826.             debug(F101,"TCP sendbuf new SO_SNDBUF","",j);
  1827.             tcp_sendbuf = size;
  1828.             return 1;
  1829.         }
  1830.     } else {
  1831.         debug(F101,"TCP sendbuf SO_SNDBUF unchanged","",i);
  1832.         tcp_sendbuf = size;
  1833.         return 1;
  1834.     }
  1835. #else
  1836.     debug(F100,"TCP sendbuf SO_SNDBUF not defined","",0);
  1837. #endif /* SO_SNDBUF */
  1838. #else
  1839.     debug(F100,"TCP sendbuf SO_SOCKET not defined","",0);
  1840. #endif /* SOL_SOCKET */
  1841.     return(0);
  1842. }
  1843.  
  1844. int
  1845. recvbuf(sock,size) int sock; int size; {
  1846. /*
  1847.   The following, from William Bader, allows changing of socket buffer sizes,
  1848.   in case that might affect performance.
  1849.  
  1850.   Modified by Jeff Altman to be generally useful.
  1851. */
  1852. #ifdef SOL_SOCKET
  1853. #ifdef SO_RCVBUF
  1854.     int i, j;
  1855.     SOCKOPT_T x;
  1856.  
  1857. #ifdef IKSD
  1858.     if (!inserver)
  1859. #endif /* IKSD */
  1860.       if (sock == -1 ||
  1861.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH || ttmdm >= 0) {
  1862.         tcp_recvbuf = size;
  1863.         return(1);
  1864.     }
  1865.     x = sizeof(i);
  1866.     if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&i, &x)) {
  1867.         debug(F111,"TCP recvbuf can't get SO_RCVBUF",ck_errstr(),errno);
  1868.     } else if (x != sizeof(i)) {
  1869. #ifdef OS2
  1870.         short i16,j16;
  1871.         if ( x == sizeof(i16) ) {
  1872.             debug(F111,"TCP recvbuf warning: SO_RCVBUF","len is 16-bit",x);
  1873.             if (getsockopt(sock,
  1874.                            SOL_SOCKET, SO_RCVBUF,
  1875.                            (char *)&i16, &x)
  1876.                 ) {
  1877.                 debug(F111,"TCP recvbuf can't get SO_RCVBUF",
  1878.                       ck_errstr(),errno);
  1879.             } else if (size <= 0) {
  1880.                 tcp_recvbuf = i16;
  1881.                 debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i16);
  1882.                 return 1;
  1883.             } else if (i16 != size) {
  1884.                 j16 = size;
  1885.                 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j16,
  1886.                                sizeof(j16))) {
  1887.                     debug(F111,"TCP recvbuf can' set SO_RCVBUF",
  1888.                           ck_errstr(),errno);
  1889.                 } else {
  1890.                     debug(F101,"TCP recvbuf old SO_RCVBUF","",i16);
  1891.                     debug(F101,"TCP recvbuf new SO_RCVBUF","",j16);
  1892.                     tcp_recvbuf = size;
  1893.                     return 1;
  1894.                 }
  1895.             } else {
  1896.                 debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i16);
  1897.                 tcp_recvbuf = size;
  1898.                 return 1;
  1899.             }
  1900.             return(0);
  1901.         }
  1902. #endif /* OS2 */
  1903.         debug(F111,"TCP recvbuf error: SO_RCVBUF","len",x);
  1904.         debug(F111,"TCP recvbuf SO_RCVBUF","expected len",sizeof(i));
  1905.         debug(F111,"TCP recvbuf SO_RCVBUF","i",i);
  1906.     } else if (size <= 0) {
  1907.         tcp_recvbuf = i;
  1908.         debug(F101,"TCP recvbuf SO_RCVBUF retrieved","",i);
  1909.         return 1;
  1910.     } else if (i != size) {
  1911.         j = size;
  1912.         if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&j, sizeof(j))) {
  1913.             debug(F111,"TCP recvbuf can't set SO_RCVBUF",ck_errstr(),errno);
  1914.             tcp_recvbuf = i;
  1915.         } else {
  1916.             debug(F101,"TCP recvbuf old SO_RCVBUF","",i);
  1917.             debug(F101,"TCP recvbuf new SO_RCVBUF","",j);
  1918.             tcp_recvbuf = size;
  1919.             return 1;
  1920.         }
  1921.     } else {
  1922.         debug(F101,"TCP recvbuf SO_RCVBUF unchanged","",i);
  1923.         tcp_recvbuf = size;
  1924.         return 1;
  1925.     }
  1926. #else
  1927.     debug(F100,"TCP recvbuf SO_RCVBUF not defined","",0);
  1928. #endif /* SO_RCVBUF */
  1929. #else
  1930.     debug(F100,"TCP recvbuf SO_SOCKET not defined","",0);
  1931. #endif /* SOL_SOCKET */
  1932.     return 0;
  1933. }
  1934.  
  1935. int
  1936. keepalive(sock,onoff) int sock; int onoff; {
  1937. #ifdef SOL_SOCKET
  1938. #ifdef SO_KEEPALIVE
  1939.     int get_keepalive_opt;
  1940.     int set_keepalive_opt;
  1941.     SOCKOPT_T x;
  1942.  
  1943.     debug(F111,"TCP keepalive","sock",sock);
  1944.     debug(F111,"TCP keepalive","nettype",nettype);
  1945.     debug(F111,"TCP keepalive","ttmdm",ttmdm);
  1946.  
  1947. #ifdef IKSD
  1948.     if (!inserver)
  1949. #endif /* IKSD */
  1950.       if (sock == -1 ||
  1951.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  1952.                 || ttmdm >= 0) {
  1953.         tcp_keepalive = onoff;
  1954.         return 1;
  1955.     }
  1956.     x = sizeof(get_keepalive_opt);
  1957.     if (getsockopt(sock,
  1958.                    SOL_SOCKET, SO_KEEPALIVE, (char *)&get_keepalive_opt, &x)) {
  1959.         debug(F111,"TCP keepalive can't get SO_KEEPALIVE",ck_errstr(),errno);
  1960.     } else if (x != sizeof(get_keepalive_opt)) {
  1961. #ifdef OS2
  1962.         short get_keepalive_opt16;
  1963.         short set_keepalive_opt16;
  1964.         if (x == sizeof(get_keepalive_opt16)) {
  1965.             debug(F111,"TCP keepalive warning: SO_KEEPALIVE",
  1966.                   "len is 16-bit",x);
  1967.             if (getsockopt(sock,
  1968.                            SOL_SOCKET, SO_KEEPALIVE,
  1969.                            (char *)&get_keepalive_opt16, &x)
  1970.                 ) {
  1971.                 debug(F111,
  1972.                       "TCP keepalive can't get SO_KEEPALIVE",
  1973.                       ck_errstr(),
  1974.                       errno
  1975.                       );
  1976.             } else if (get_keepalive_opt16 != onoff) {
  1977.                 set_keepalive_opt16 = onoff;
  1978.                 if (setsockopt(sock,
  1979.                                SOL_SOCKET,
  1980.                                SO_KEEPALIVE,
  1981.                                (char *)&set_keepalive_opt16,
  1982.                                sizeof(set_keepalive_opt16))
  1983.                     ) {
  1984.                     debug(F111,
  1985.                           "TCP keepalive can't clear SO_KEEPALIVE",
  1986.                           ck_errstr(),
  1987.                           errno
  1988.                           );
  1989.                     tcp_keepalive = get_keepalive_opt16;
  1990.                 } else {
  1991.                     debug(F101,
  1992.                           "TCP keepalive new SO_KEEPALIVE","",
  1993.                           set_keepalive_opt16);
  1994.                     tcp_keepalive = set_keepalive_opt16;
  1995.                     return 1;
  1996.                 }
  1997.             } else {
  1998.                 debug(F101,"TCP keepalive SO_KEEPALIVE unchanged","",
  1999.                       get_keepalive_opt16);
  2000.                 tcp_keepalive = onoff;
  2001.                 return 1;
  2002.             }
  2003.             return(0);
  2004.         }
  2005. #endif /* OS2 */
  2006.         debug(F111,"TCP keepalive error: SO_KEEPALIVE","len",x);
  2007.         debug(F111,
  2008.               "TCP keepalive SO_KEEPALIVE",
  2009.               "expected len",
  2010.               sizeof(get_keepalive_opt)
  2011.               );
  2012.         debug(F111,
  2013.               "TCP keepalive SO_KEEPALIVE",
  2014.               "keepalive_opt",
  2015.               get_keepalive_opt
  2016.               );
  2017.     } else if (get_keepalive_opt != onoff) {
  2018.             set_keepalive_opt = onoff;
  2019.             if (setsockopt(sock,
  2020.                             SOL_SOCKET,
  2021.                             SO_KEEPALIVE,
  2022.                             (char *)&set_keepalive_opt,
  2023.                             sizeof(set_keepalive_opt))
  2024.                 ) {
  2025.                 debug(F111,
  2026.                       "TCP keepalive can't clear SO_KEEPALIVE",
  2027.                       ck_errstr(),
  2028.                       errno
  2029.                       );
  2030.                 tcp_keepalive = get_keepalive_opt;
  2031.             } else {
  2032.                 debug(F101,
  2033.                       "TCP keepalive new SO_KEEPALIVE",
  2034.                       "",
  2035.                       set_keepalive_opt
  2036.                       );
  2037.                 tcp_keepalive = onoff;
  2038.                 return 1;
  2039.             }
  2040.         } else {
  2041.             debug(F101,"TCP keepalive SO_KEEPALIVE unchanged",
  2042.                   "",
  2043.                   get_keepalive_opt
  2044.                   );
  2045.             tcp_keepalive = onoff;
  2046.             return 1;
  2047.     }
  2048. #else
  2049.     debug(F100,"TCP keepalive SO_KEEPALIVE not defined","",0);
  2050. #endif /* SO_KEEPALIVE */
  2051. #else
  2052.     debug(F100,"TCP keepalive SO_SOCKET not defined","",0);
  2053. #endif /* SOL_SOCKET */
  2054.     return(0);
  2055. }
  2056.  
  2057. int
  2058. dontroute(sock,onoff) int sock; int onoff; {
  2059. #ifdef SOL_SOCKET
  2060. #ifdef SO_DONTROUTE
  2061.     int get_dontroute_opt;
  2062.     int set_dontroute_opt;
  2063.     SOCKOPT_T x;
  2064.  
  2065. #ifdef IKSD
  2066.     if (!inserver)
  2067. #endif /* IKSD */
  2068.       if (sock == -1 ||
  2069.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  2070.                 || ttmdm >= 0) {
  2071.         tcp_dontroute = onoff;
  2072.         return 1;
  2073.     }
  2074.     x = sizeof(get_dontroute_opt);
  2075.     if (getsockopt(sock,
  2076.                    SOL_SOCKET, SO_DONTROUTE, (char *)&get_dontroute_opt, &x)) {
  2077.         debug(F111,"TCP dontroute can't get SO_DONTROUTE",ck_errstr(),errno);
  2078.     } else if (x != sizeof(get_dontroute_opt)) {
  2079. #ifdef OS2
  2080.         short get_dontroute_opt16;
  2081.         short set_dontroute_opt16;
  2082.         if (x == sizeof(get_dontroute_opt16)) {
  2083.             debug(F111,"TCP dontroute warning: SO_DONTROUTE",
  2084.                   "len is 16-bit",x);
  2085.             if (getsockopt(sock,
  2086.                            SOL_SOCKET, SO_DONTROUTE,
  2087.                            (char *)&get_dontroute_opt16, &x)
  2088.                 ) {
  2089.                 debug(F111,
  2090.                       "TCP dontroute can't get SO_DONTROUTE",
  2091.                       ck_errstr(),
  2092.                       errno
  2093.                       );
  2094.             } else if (get_dontroute_opt16 != onoff) {
  2095.                 set_dontroute_opt16 = onoff;
  2096.                 if (setsockopt(sock,
  2097.                                SOL_SOCKET,
  2098.                                SO_DONTROUTE,
  2099.                                (char *)&set_dontroute_opt16,
  2100.                                sizeof(set_dontroute_opt16))
  2101.                     ) {
  2102.                     debug(F111,
  2103.                           "TCP dontroute can't clear SO_DONTROUTE",
  2104.                           ck_errstr(),
  2105.                           errno
  2106.                           );
  2107.                     tcp_dontroute = get_dontroute_opt16;
  2108.                 } else {
  2109.                     debug(F101,
  2110.                           "TCP dontroute new SO_DONTROUTE","",
  2111.                           set_dontroute_opt16);
  2112.                     tcp_dontroute = set_dontroute_opt16;
  2113.                     return 1;
  2114.                 }
  2115.             } else {
  2116.                 debug(F101,"TCP dontroute SO_DONTROUTE unchanged","",
  2117.                       get_dontroute_opt16);
  2118.                 tcp_dontroute = onoff;
  2119.                 return 1;
  2120.             }
  2121.             return(0);
  2122.         }
  2123. #endif /* OS2 */
  2124.         debug(F111,"TCP dontroute error: SO_DONTROUTE","len",x);
  2125.         debug(F111,
  2126.               "TCP dontroute SO_DONTROUTE",
  2127.               "expected len",
  2128.               sizeof(get_dontroute_opt)
  2129.               );
  2130.         debug(F111,
  2131.               "TCP dontroute SO_DONTROUTE",
  2132.               "dontroute_opt",
  2133.               get_dontroute_opt
  2134.               );
  2135.     } else if (get_dontroute_opt != onoff) {
  2136.             set_dontroute_opt = onoff;
  2137.             if (setsockopt(sock,
  2138.                             SOL_SOCKET,
  2139.                             SO_DONTROUTE,
  2140.                             (char *)&set_dontroute_opt,
  2141.                             sizeof(set_dontroute_opt))
  2142.                 ) {
  2143.                 debug(F111,
  2144.                       "TCP dontroute can't clear SO_DONTROUTE",
  2145.                       ck_errstr(),
  2146.                       errno
  2147.                       );
  2148.                 tcp_dontroute = get_dontroute_opt;
  2149.             } else {
  2150.                 debug(F101,
  2151.                       "TCP dontroute new SO_DONTROUTE",
  2152.                       "",
  2153.                       set_dontroute_opt
  2154.                       );
  2155.                 tcp_dontroute = onoff;
  2156.                 return 1;
  2157.             }
  2158.         } else {
  2159.             debug(F101,"TCP dontroute SO_DONTROUTE unchanged",
  2160.                   "",
  2161.                   get_dontroute_opt
  2162.                   );
  2163.             tcp_dontroute = onoff;
  2164.             return 1;
  2165.     }
  2166. #else
  2167.     debug(F100,"TCP dontroute SO_DONTROUTE not defined","",0);
  2168. #endif /* SO_DONTROUTE */
  2169. #else
  2170.     debug(F100,"TCP dontroute SO_SOCKET not defined","",0);
  2171. #endif /* SOL_SOCKET */
  2172.     return(0);
  2173. }
  2174.  
  2175. int
  2176. no_delay(sock,onoff)  int sock; int onoff; {
  2177. #ifdef SOL_SOCKET
  2178. #ifdef TCP_NODELAY
  2179.     int get_nodelay_opt;
  2180.     int set_nodelay_opt;
  2181.     SOCKOPT_T x;
  2182.  
  2183. #ifdef IKSD
  2184.     if (!inserver)
  2185. #endif /* IKSD */
  2186.       if (sock == -1 ||
  2187.         nettype != NET_TCPA && nettype != NET_TCPB && nettype != NET_SSH
  2188.                 || ttmdm >= 0) {
  2189.         tcp_nodelay = onoff;
  2190.         return(1);
  2191.     }
  2192.     x = sizeof(get_nodelay_opt);
  2193.     if (getsockopt(sock,IPPROTO_TCP,TCP_NODELAY,
  2194.                    (char *)&get_nodelay_opt,&x)) {
  2195.         debug(F111,
  2196.               "TCP no_delay can't get TCP_NODELAY",
  2197.               ck_errstr(),
  2198.               errno);
  2199.     } else if (x != sizeof(get_nodelay_opt)) {
  2200. #ifdef OS2
  2201.         short get_nodelay_opt16;
  2202.         short set_nodelay_opt16;
  2203.         if (x == sizeof(get_nodelay_opt16)) {
  2204.             debug(F111,"TCP no_delay warning: TCP_NODELAY","len is 16-bit",x);
  2205.             if (getsockopt(sock,
  2206.                            IPPROTO_TCP, TCP_NODELAY,
  2207.                            (char *)&get_nodelay_opt16, &x)
  2208.                 ) {
  2209.                 debug(F111,
  2210.                       "TCP no_delay can't get TCP_NODELAY",
  2211.                       ck_errstr(),
  2212.                       errno);
  2213.             } else if (get_nodelay_opt16 != onoff) {
  2214.                 set_nodelay_opt16 = onoff;
  2215.                 if (setsockopt(sock,
  2216.                                IPPROTO_TCP,
  2217.                                TCP_NODELAY,
  2218.                                (char *)&set_nodelay_opt16,
  2219.                                sizeof(set_nodelay_opt16))
  2220.                     ) {
  2221.                     debug(F111,
  2222.                           "TCP no_delay can't clear TCP_NODELAY",
  2223.                           ck_errstr(),
  2224.                           errno);
  2225.                     tcp_nodelay = get_nodelay_opt16;
  2226.                 } else {
  2227.                     debug(F101,
  2228.                           "TCP no_delay new TCP_NODELAY",
  2229.                           "",
  2230.                           set_nodelay_opt16);
  2231.                     tcp_nodelay = onoff;
  2232.                     return 1;
  2233.                 }
  2234.             } else {
  2235.                 debug(F101,"TCP no_delay TCP_NODELAY unchanged","",
  2236.                       get_nodelay_opt16);
  2237.                 tcp_nodelay = onoff;
  2238.                 return 1;
  2239.             }
  2240.             return(0);
  2241.         }
  2242. #endif /* OS2 */
  2243.         debug(F111,"TCP no_delay error: TCP_NODELAY","len",x);
  2244.         debug(F111,"TCP no_delay TCP_NODELAY","expected len",
  2245.               sizeof(get_nodelay_opt));
  2246.         debug(F111,"TCP no_delay TCP_NODELAY","nodelay_opt",get_nodelay_opt);
  2247.     } else if (get_nodelay_opt != onoff) {
  2248.         set_nodelay_opt = onoff;
  2249.         if (setsockopt(sock,
  2250.                        IPPROTO_TCP,
  2251.                        TCP_NODELAY,
  2252.                        (char *)&set_nodelay_opt,
  2253.                        sizeof(set_nodelay_opt))) {
  2254.             debug(F111,
  2255.                   "TCP no_delay can't clear TCP_NODELAY",
  2256.                   ck_errstr(),
  2257.                   errno
  2258.                   );
  2259.             tcp_nodelay = get_nodelay_opt;
  2260.         } else {
  2261.             debug(F101,"TCP no_delay new TCP_NODELAY","",set_nodelay_opt);
  2262.             tcp_nodelay = onoff;
  2263.             return 1;
  2264.         }
  2265.     } else {
  2266.         debug(F101,"TCP no_delay TCP_NODELAY unchanged","",get_nodelay_opt);
  2267.         tcp_nodelay = onoff;
  2268.         return(1);
  2269.     }
  2270. #else
  2271.     debug(F100,"TCP no_delay TCP_NODELAY not defined","",0);
  2272. #endif /* TCP_NODELAY */
  2273. #else
  2274.     debug(F100,"TCP no_delay SO_SOCKET not defined","",0);
  2275. #endif /* SOL_SOCKET */
  2276.     return 0;
  2277. }
  2278. #endif /* datageneral */
  2279. #endif /* NOTCPOPTS */
  2280.  
  2281. #ifdef SUNX25
  2282. #ifndef X25_WR_FACILITY
  2283. /* For Solaris 2.3 / SunLink 8.x - see comments in ckcnet.h */
  2284. void
  2285. bzero(s,n) char *s; int n; {
  2286.     memset(s,0,n);
  2287. }
  2288. #endif /* X25_WR_FACILITY */
  2289. #endif /* SUNX25 */
  2290.  
  2291. #ifdef TCPSOCKET
  2292. #ifndef OS2
  2293. #ifndef NOLISTEN
  2294.  
  2295. #ifdef BSDSELECT
  2296. #ifndef VMS
  2297. #ifndef BELLV10
  2298. #ifndef datageneral
  2299. #ifdef hp9000s500                       /* HP-9000/500 HP-U 5.21 */
  2300. #include <time.h>
  2301. #else
  2302.  
  2303. /****** THIS SECTION ADDED BY STEVE RANCE - OS9 NETWORK SERVER
  2304. *       ------------------------------------------------------
  2305. *
  2306. *       Due to OS9's Lack of a select() call, the following seems to be
  2307. *       enough to fool the rest of the code into compiling. The only
  2308. *       effect that I can see is using control L to refresh the status
  2309. *       display gets qued up until some network packets arrive.
  2310. *
  2311. *       This solution is by no means elegant but works enough to be
  2312. *       a (the) solution.
  2313. *
  2314. *       Also with the defines I had specified in my makefile I had to
  2315. *       have an #endif right at the end of the file when compiling.
  2316. *       I did not bother speding time to find out why.
  2317. *
  2318. *       COPTS   = -to=osk -d=OSK -d=TCPSOCKET -d=SELECT -d=VOID=void -d=SIG_V \
  2319. *          -d=DYNAMIC -d=PARSENSE -d=KANJI -d=MYCURSES -d=ZFCDAT \
  2320. *          -d=CK_APC -d=CK_REDIR -d=RENAME -d=CK_TTYFD -d=NOOLDMODEMS \
  2321. *          -d=CK_ANSIC -d=CK_XYZ -tp=68040d -l=netdb.l -l=socklib.l \
  2322. *          -l=termlib.l -l=math.l -l=sys_clib.l
  2323. *
  2324. *       stever@ozemail.com.au
  2325. */
  2326.  
  2327. #ifdef  OSK
  2328. #define BSDSELECT                       /* switch on BSD select code */
  2329. #define FD_SETSIZE 32                   /* Max # of paths in OS9 */
  2330. #define FD_ZERO(p)                      ((*p)=0)
  2331. #define FD_SET(n,b)                     ((*b)|=(1<<(n)))
  2332. #define FD_ISSET(n,b)           1       /* always say data is ready */
  2333. #define select(a,b,c,d,e)       1       /* always say 1 path has data */
  2334. typedef int     fd_set;                 /* keep BSD Code Happy */
  2335. struct timeval {int tv_sec,tv_usec;};   /* keep BSD Code Happy */
  2336.  
  2337. /****** END OF OS9 MODS FROM STEVE RANCE **************************/
  2338. #endif /* OSK */
  2339.  
  2340. #include <sys/time.h>
  2341. #endif /* hp9000s500 */
  2342. #endif /* datageneral */
  2343. #endif /* BELLV10 */
  2344. #endif /* VMS */
  2345. #ifdef SELECT_H
  2346. #include <sys/select.h>
  2347. #endif /* SELECT_H */
  2348. #endif /* BSDSELECT */
  2349.  
  2350. #ifdef SELECT
  2351. #ifdef CK_SCOV5
  2352. #include <sys/select.h>
  2353. #endif /* CK_SCOV5 */
  2354. #endif /* SELECT */
  2355.  
  2356. #ifdef NOTUSED
  2357. /* T C P S O C K E T _ O P E N -- Open a preexisting socket number */
  2358.  
  2359. int
  2360. tcpsocket_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo {
  2361.     int on = 1;
  2362.     static struct servent *service, servrec;
  2363.     static struct hostent *host;
  2364.     static struct sockaddr_in saddr;
  2365.     static
  2366. #ifdef UCX50
  2367.       unsigned
  2368. #endif /* UCX50 */
  2369.       int saddrlen;
  2370. #ifdef BSDSELECT
  2371.     fd_set rfds;
  2372.     struct timeval tv;
  2373. #else
  2374. #ifdef BELLSELECT
  2375.     fd_set rfds;
  2376. #else
  2377.     fd_set rfds;
  2378.     fd_set rfds;
  2379.     struct timeval {
  2380.         long tv_sec;
  2381.         long tv_usec;
  2382.     } tv;
  2383. #endif /* BELLSELECT */
  2384. #endif /* BSDSELECT */
  2385.  
  2386.     debug(F101,"tcpsocket_open nett","",nett);
  2387.     *ipaddr = '\0';
  2388.  
  2389.     if (nett != NET_TCPB)
  2390.       return(-1);                       /* BSD socket support */
  2391.  
  2392.     netclos();                          /* Close any previous connection. */
  2393.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2394.     if (ttnproto != NP_TCPRAW)
  2395.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2396.     debug(F110,"tcpsocket_open namecopy",namecopy,0);
  2397.  
  2398.     /* Assign the socket number to ttyfd and then fill in tcp structures */
  2399.     ttyfd = atoi(&name[1]);
  2400.     debug(F111,"tcpsocket_open","ttyfd",ttyfd);
  2401.  
  2402. #ifndef NOTCPOPTS
  2403. #ifdef SOL_SOCKET
  2404.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2405.  
  2406. #ifndef datageneral
  2407. #ifdef TCP_NODELAY
  2408.     no_delay(ttyfd,tcp_nodelay);
  2409. #endif /* TCP_NODELAY */
  2410. #ifdef SO_KEEPALIVE
  2411.     keepalive(ttyfd,tcp_keepalive);
  2412. #endif /* SO_KEEPALIVE */
  2413. #ifdef SO_LINGER
  2414.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  2415. #endif /* SO_LINGER */
  2416. #ifdef SO_SNDBUF
  2417.     sendbuf(ttyfd,tcp_sendbuf);
  2418. #endif /* SO_SNDBUF */
  2419. #ifdef SO_RCVBUF
  2420.     recvbuf(ttyfd,tcp_recvbuf);
  2421. #endif /* SO_RCVBUF */
  2422. #endif /* datageneral */
  2423. #endif /* SOL_SOCKET */
  2424. #endif /* NOTCPOPTS */
  2425.  
  2426. #ifdef NT_TCP_OVERLAPPED
  2427.     OverlappedWriteInit();
  2428.     OverlappedReadInit();
  2429. #endif /* NT_TCP_OVERLAPPED */
  2430.  
  2431.  
  2432.     /* Get the name of the host we are connected to */
  2433.  
  2434.     saddrlen = sizeof(saddr);
  2435.     getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen);
  2436.  
  2437.     ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2438.  
  2439.     if (tcp_rdns == SET_ON
  2440. #ifdef CK_KERBEROS
  2441.         || tcp_rdns == SET_AUTO &&
  2442.          (ck_krb5_is_installed() || ck_krb4_is_installed())
  2443. #endif /* CK_KERBEROS */
  2444. #ifndef NOHTTP
  2445.           && (tcp_http_proxy == NULL)
  2446. #endif /* NOHTTP */
  2447. #ifdef CK_SSL
  2448.           && !(ssl_only_flag || tls_only_flag)
  2449. #endif /* CK_SSL */
  2450.          ) {                            /* Reverse DNS */
  2451.         if (!quiet) {
  2452.             printf(" Reverse DNS Lookup... ");
  2453.             fflush(stdout);
  2454.         }
  2455.         host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET);
  2456.         debug(F110,"tcpsocket_open gethostbyaddr",host ? "OK" : "FAILED",0);
  2457.         if (host) {
  2458.             host = ck_copyhostent(host);
  2459.             debug(F100,"tcpsocket_open gethostbyaddr != NULL","",0);
  2460.             if (!quiet) {
  2461.                 printf("(OK)\n");
  2462.                 fflush(stdout);
  2463.             }
  2464.             ckstrncpy(name, host->h_name, 80);
  2465.             ckstrncat(name, ":", 80);
  2466.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)), 80);
  2467.             if (!quiet
  2468. #ifndef NOICP
  2469.                 && !doconx
  2470. #endif /* NOICP */
  2471.                 )
  2472.               printf("%s connected on port %d\n",
  2473.                    host->h_name,
  2474.                    ntohs(saddr.sin_port)
  2475.                    );
  2476.         } else if (!quiet)
  2477.           printf("Failed\n");
  2478.     } else if (!quiet)
  2479.       printf("(OK)\n");
  2480.  
  2481.     if (tcp_rdns != SET_ON || !host) {
  2482.         ckstrncpy(name,ipaddr,80);
  2483.         ckstrncat(name,":",80);
  2484.         ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  2485.         if (!quiet
  2486. #ifdef NOICP
  2487.             && !doconx
  2488. #endif /* NOICP */
  2489.             )
  2490.           printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2491.     }
  2492.     if (!quiet) fflush(stdout);
  2493.     ttnet = nett;                       /* TCP/IP (sockets) network */
  2494.  
  2495. #ifdef RLOGCODE
  2496.     if (ntohs(saddr.sin_port) == 513)
  2497.         ttnproto = NP_LOGIN;
  2498.     else
  2499. #endif /* RLOGCODE */
  2500.     /* Assume the service is TELNET. */
  2501.     if (ttnproto != NP_TCPRAW)
  2502.         ttnproto = NP_TELNET;           /* Yes, set global flag. */
  2503. #ifdef CK_SECURITY
  2504.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2505.     ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2506.                 host->h_name : ipaddr,
  2507.                 ipaddr,
  2508.                 uidbuf,
  2509.                 ttyfd
  2510.                 );
  2511. #endif /* CK_SECURITY */
  2512.     if (tn_ini() < 0)                   /* Start/Reset TELNET negotiations */
  2513.       if (ttchk() < 0)                  /* Did it fail due to connect loss? */
  2514.         return(-1);
  2515.  
  2516.     if (*lcl < 0) *lcl = 1;             /* Local mode. */
  2517.  
  2518.     return(0);                          /* Done. */
  2519. }
  2520. #endif /* NOTUSED */
  2521.  
  2522. /*  T C P S R V _ O P E N  --  Open a TCP/IP Server connection  */
  2523. /*
  2524.   Calling conventions same as ttopen(), except third argument is network
  2525.   type rather than modem type.
  2526. */
  2527. int
  2528. tcpsrv_open(name,lcl,nett,timo) char * name; int * lcl; int nett; int timo; {
  2529.     char *p;
  2530.     int i, x;
  2531.     SOCKOPT_T on = 1;
  2532.     int ready_to_accept = 0;
  2533.     static struct servent *service, *service2, servrec;
  2534.     static struct hostent *host;
  2535.     static struct sockaddr_in saddr;
  2536.     struct sockaddr_in l_addr;
  2537.     GSOCKNAME_T l_slen;
  2538. #ifdef UCX50
  2539.     static u_int saddrlen;
  2540. #else
  2541.     static SOCKOPT_T saddrlen;
  2542. #endif /* UCX50 */
  2543.  
  2544. #ifdef BSDSELECT
  2545.     fd_set rfds;
  2546.     struct timeval tv;
  2547. #else
  2548. #ifdef BELLSELCT
  2549.     fd_set rfds;
  2550. #else
  2551.     fd_set rfds;
  2552.     struct timeval {
  2553.         long tv_sec;
  2554.         long tv_usec;
  2555.     } tv;
  2556. #endif /* BELLSELECT */
  2557. #endif /* BSDSELECT */
  2558. #ifdef CK_SSL
  2559.     int ssl_failed = 0;
  2560. #endif /* CK_SSL */
  2561.  
  2562.     debug(F101,"tcpsrv_open nett","",nett);
  2563.     *ipaddr = '\0';
  2564.  
  2565.     if (nett != NET_TCPB)
  2566.       return(-1);                       /* BSD socket support */
  2567.  
  2568.     netclos();                          /* Close any previous connection. */
  2569.     ckstrncpy(namecopy, name, NAMECPYL); /* Copy the hostname. */
  2570. #ifdef COMMENT
  2571.     /* Don't do this. */
  2572.     if (ttnproto != NP_TCPRAW)
  2573.       ttnproto = NP_NONE;               /* No protocol selected yet. */
  2574. #endif /* COMMENT */
  2575.     debug(F110,"tcpsrv_open namecopy",namecopy,0);
  2576.  
  2577.     p = namecopy;                       /* Was a service requested? */
  2578.     while (*p != '\0' && *p != ':')
  2579.       p++; /* Look for colon */
  2580.     if (*p == ':') {                    /* Have a colon */
  2581.         *p++ = '\0';                    /* Get service name or number */
  2582.     } else {                            /* Otherwise use kermit */
  2583.         p = "kermit";
  2584.     }
  2585.     debug(F110,"tcpsrv_open service requested",p,0);
  2586.     if (isdigit(*p)) {                  /* Use socket number without lookup */
  2587.         service = &servrec;
  2588.         service->s_port = htons((unsigned short)atoi(p));
  2589.     } else {                            /* Otherwise lookup the service name */
  2590.         service = getservbyname(p, "tcp");
  2591.     }
  2592.     if (!service && !strcmp("kermit",p)) { /* Use Kermit service port */
  2593.         service = &servrec;
  2594.         service->s_port = htons(1649);
  2595.     }
  2596. #ifdef RLOGCODE
  2597.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  2598.         fprintf(stderr,
  2599.                 "  Warning: login service on port %d instead of port 513\n",
  2600.                  ntohs(service->s_port));
  2601.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  2602.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  2603.     }
  2604. #endif /* RLOGCODE */
  2605.     if (!service) {
  2606.         fprintf(stderr, "Cannot find port for service: %s\n", p);
  2607.         debug(F111,"tcpsrv_open can't get service",p,errno);
  2608.         errno = 0;                      /* rather than mislead */
  2609.         return(-1);
  2610.     }
  2611.  
  2612.     /* If we currently have a listen active but port has changed then close */
  2613.  
  2614.     debug(F101,"tcpsrv_open checking previous connection","",tcpsrfd);
  2615.     debug(F101,"tcpsrv_open previous tcpsrv_port","",tcpsrv_port);
  2616.     if (tcpsrfd != -1 &&
  2617.         tcpsrv_port != ntohs((unsigned short)service->s_port)) {
  2618.         debug(F100,"tcpsrv_open closing previous connection","",0);
  2619. #ifdef TCPIPLIB
  2620.         socket_close(tcpsrfd);
  2621. #else
  2622.         close(tcpsrfd);
  2623. #endif /* TCPIPLIB */
  2624.         tcpsrfd = -1;
  2625.     }
  2626.     debug(F100,"tcpsrv_open tcpsrfd","",tcpsrfd);
  2627.     if (tcpsrfd == -1) {
  2628.  
  2629.         /* Set up socket structure and get host address */
  2630.  
  2631.         bzero((char *)&saddr, sizeof(saddr));
  2632.         debug(F100,"tcpsrv_open bzero ok","",0);
  2633.         saddr.sin_family = AF_INET;
  2634.         if (tcp_address) {
  2635. #ifdef INADDRX
  2636.             inaddrx = inet_addr(tcp_address);
  2637.             saddr.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  2638. #else
  2639.             saddr.sin_addr.s_addr = inet_addr(tcp_address);
  2640. #endif /* INADDRX */
  2641.         } else
  2642.           saddr.sin_addr.s_addr = INADDR_ANY;
  2643.  
  2644.         /* Get a file descriptor for the connection. */
  2645.  
  2646.         saddr.sin_port = service->s_port;
  2647.         ipaddr[0] = '\0';
  2648.  
  2649.         debug(F100,"tcpsrv_open calling socket","",0);
  2650.         if ((tcpsrfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  2651.             perror("TCP socket error");
  2652.             debug(F101,"tcpsrv_open socket error","",errno);
  2653.             return (-1);
  2654.         }
  2655.         errno = 0;
  2656.  
  2657.         /* Specify the Port may be reused */
  2658.  
  2659.         debug(F100,"tcpsrv_open calling setsockopt","",0);
  2660.         x = setsockopt(tcpsrfd,
  2661.                        SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof on);
  2662.         debug(F101,"tcpsrv_open setsockopt","",x);
  2663.  
  2664.        /* Now bind to the socket */
  2665.         printf("\nBinding socket to port %d ...\n",
  2666.                ntohs((unsigned short)service->s_port));
  2667.         if (bind(tcpsrfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  2668.             i = errno;                  /* Save error code */
  2669. #ifdef TCPIPLIB
  2670.             socket_close(tcpsrfd);
  2671. #else /* TCPIPLIB */
  2672.             close(tcpsrfd);
  2673. #endif /* TCPIPLIB */
  2674.             tcpsrfd = -1;
  2675.             tcpsrv_port = 0;
  2676.             ttyfd = -1;
  2677.             wasclosed = 1;
  2678.             errno = i;                  /* and report this error */
  2679.             debug(F101,"tcpsrv_open bind errno","",errno);
  2680.             printf("?Unable to bind to socket (errno = %d)\n",errno);
  2681.             return(-1);
  2682.         }
  2683.         debug(F100,"tcpsrv_open bind OK","",0);
  2684.         printf("Listening ...\n");
  2685.         if (listen(tcpsrfd, 15) < 0) {
  2686.             i = errno;                  /* Save error code */
  2687. #ifdef TCPIPLIB
  2688.             socket_close(tcpsrfd);
  2689. #else /* TCPIPLIB */
  2690.             close(tcpsrfd);
  2691. #endif /* TCPIPLIB */
  2692.             tcpsrfd = -1;
  2693.             tcpsrv_port = 0;
  2694.             ttyfd = -1;
  2695.             wasclosed = 1;
  2696.             errno = i;                  /* And report this error */
  2697.             debug(F101,"tcpsrv_open listen errno","",errno);
  2698.             return(-1);
  2699.         }
  2700.         debug(F100,"tcpsrv_open listen OK","",0);
  2701.         tcpsrv_port = ntohs((unsigned short)service->s_port);
  2702.     }
  2703.  
  2704. #ifdef CK_SSL
  2705.     if (ck_ssleay_is_installed()) {
  2706.         if (!ssl_tn_init(SSL_SERVER)) {
  2707.             ssl_failed = 1;
  2708.             if (bio_err!=NULL) {
  2709.                 BIO_printf(bio_err,"do_ssleay_init() failed\n");
  2710.                 ERR_print_errors(bio_err);
  2711.             } else {
  2712.                 fflush(stderr);
  2713.                 fprintf(stderr,"do_ssleay_init() failed\n");
  2714.                 ERR_print_errors_fp(stderr);
  2715.             }
  2716.             if (tls_only_flag || ssl_only_flag) {
  2717. #ifdef TCPIPLIB
  2718.                 socket_close(ttyfd);
  2719.                 socket_close(tcpsrfd);
  2720. #else /* TCPIPLIB */
  2721.                 close(ttyfd);
  2722.                 close(tcpsrfd);
  2723. #endif /* TCPIPLIB */
  2724.                 ttyfd = -1;
  2725.                 wasclosed = 1;
  2726.                 tcpsrfd = -1;
  2727.                 tcpsrv_port = 0;
  2728.                 return(-1);
  2729.             }
  2730.             /* we will continue to accept the connection   */
  2731.             /* without SSL or TLS support unless required. */
  2732.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2733.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2734.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2735.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2736.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2737.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2738.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  2739.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  2740.         }
  2741.     }
  2742. #endif /* CK_SSL */
  2743.  
  2744.     printf("\nWaiting to Accept a TCP/IP connection on port %d ...\n",
  2745.            ntohs((unsigned short)service->s_port));
  2746.     saddrlen = sizeof(saddr);
  2747.  
  2748. #ifdef BSDSELECT
  2749.     tv.tv_sec  = tv.tv_usec = 0L;
  2750.     if (timo < 0)
  2751.       tv.tv_usec = (long) -timo * 10000L;
  2752.     else
  2753.       tv.tv_sec = timo;
  2754.     debug(F101,"tcpsrv_open BSDSELECT","",timo);
  2755. #else
  2756.     debug(F101,"tcpsrv_open not BSDSELECT","",timo);
  2757. #endif /* BSDSELECT */
  2758.  
  2759.     if (timo) {
  2760.         while (!ready_to_accept) {
  2761. #ifdef BSDSELECT
  2762.             FD_ZERO(&rfds);
  2763.             FD_SET(tcpsrfd, &rfds);
  2764.             ready_to_accept =
  2765.               ((select(FD_SETSIZE,
  2766. #ifdef HPUX
  2767. #ifdef HPUX1010
  2768.                        (fd_set *)
  2769. #else
  2770.  
  2771.                        (int *)
  2772. #endif /* HPUX1010 */
  2773. #else
  2774. #ifdef __DECC
  2775.                        (fd_set *)
  2776. #endif /* __DECC */
  2777. #endif /* HPUX */
  2778.                        &rfds, NULL, NULL, &tv) > 0) &&
  2779.                FD_ISSET(tcpsrfd, &rfds));
  2780. #else /* BSDSELECT */
  2781. #ifdef IBMSELECT
  2782. #define ck_sleepint 250
  2783.             ready_to_accept =
  2784.               (select(&tcpsrfd, 1, 0, 0,
  2785.                       timo < 0 ? -timo :
  2786.                       (timo > 0 ? timo * 1000L : ck_sleepint)) == 1
  2787.                );
  2788. #else
  2789. #ifdef BELLSELECT
  2790.             FD_ZERO(rfds);
  2791.             FD_SET(tcpsrfd, rfds);
  2792.             ready_to_accept =
  2793.               ((select(128, rfds, NULL, NULL, timo < 0 ? -timo :
  2794.                       (timo > 0 ? timo * 1000L)) > 0) &&
  2795.                FD_ISSET(tcpsrfd, rfds));
  2796. #else
  2797. /* Try this - what's the worst that can happen... */
  2798.  
  2799.             FD_ZERO(&rfds);
  2800.             FD_SET(tcpsrfd, &rfds);
  2801.             ready_to_accept =
  2802.               ((select(FD_SETSIZE,
  2803.                        (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  2804.                FD_ISSET(tcpsrfd, &rfds));
  2805.  
  2806. #endif /* BELLSELECT */
  2807. #endif /* IBMSELECT */
  2808. #endif /* BSDSELECT */
  2809.         }
  2810.     }
  2811.     if (ready_to_accept || timo == 0) {
  2812.         if ((ttyfd = accept(tcpsrfd,
  2813.                             (struct sockaddr *)&saddr,&saddrlen)) < 0) {
  2814.             i = errno;                  /* save error code */
  2815. #ifdef TCPIPLIB
  2816.             socket_close(tcpsrfd);
  2817. #else /* TCPIPLIB */
  2818.             close(tcpsrfd);
  2819. #endif /* TCPIPLIB */
  2820.             ttyfd = -1;
  2821.             wasclosed = 1;
  2822.             tcpsrfd = -1;
  2823.             tcpsrv_port = 0;
  2824.             errno = i;                  /* and report this error */
  2825.             debug(F101,"tcpsrv_open accept errno","",errno);
  2826.             return(-1);
  2827.         }
  2828.         setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  2829.  
  2830. #ifndef NOTCPOPTS
  2831. #ifndef datageneral
  2832. #ifdef SOL_SOCKET
  2833. #ifdef TCP_NODELAY
  2834.         no_delay(ttyfd,tcp_nodelay);
  2835.         debug(F101,"tcpsrv_open no_delay","",tcp_nodelay);
  2836. #endif /* TCP_NODELAY */
  2837. #ifdef SO_KEEPALIVE
  2838.         keepalive(ttyfd,tcp_keepalive);
  2839.         debug(F101,"tcpsrv_open keepalive","",tcp_keepalive);
  2840. #endif /* SO_KEEPALIVE */
  2841. #ifdef SO_LINGER
  2842.         ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  2843.         debug(F101,"tcpsrv_open linger","",tcp_linger_tmo);
  2844. #endif /* SO_LINGER */
  2845. #ifdef SO_SNDBUF
  2846.         sendbuf(ttyfd,tcp_sendbuf);
  2847. #endif /* SO_SNDBUF */
  2848. #ifdef SO_RCVBUF
  2849.         recvbuf(ttyfd,tcp_recvbuf);
  2850. #endif /* SO_RCVBUF */
  2851. #endif /* SOL_SOCKET */
  2852. #endif /* datageneral */
  2853. #endif /* NOTCPOPTS */
  2854.  
  2855.         ttnet = nett;                   /* TCP/IP (sockets) network */
  2856.         tcp_incoming = 1;               /* This is an incoming connection */
  2857.         sstelnet = 1;                   /* Do server-side Telnet protocol */
  2858.  
  2859.         /* See if the service is TELNET. */
  2860.         x = (unsigned short)service->s_port;
  2861.         service2 = getservbyname("telnet", "tcp");
  2862.         if (service2 && x == service2->s_port) {
  2863.             if (ttnproto != NP_TCPRAW)  /* Yes and if raw port not requested */
  2864.               ttnproto = NP_TELNET;     /* Set protocol to TELNET. */
  2865.         }
  2866. #ifdef CK_SECURITY
  2867.         /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  2868.         ck_auth_init((host && host->h_name && host->h_name[0]) ?
  2869.                      (char *)host->h_name : ipaddr,
  2870.                      ipaddr,
  2871.                      uidbuf,
  2872.                      ttyfd
  2873.                      );
  2874. #endif /* CK_SECURITY */
  2875.  
  2876. #ifdef CK_SSL
  2877.         if (ck_ssleay_is_installed() && !ssl_failed) {
  2878.             if (ck_ssl_incoming(ttyfd) < 0) {
  2879. #ifdef TCPIPLIB
  2880.                     socket_close(ttyfd);
  2881.                     socket_close(tcpsrfd);
  2882. #else /* TCPIPLIB */
  2883.                     close(ttyfd);
  2884.                     close(tcpsrfd);
  2885. #endif /* TCPIPLIB */
  2886.                     ttyfd = -1;
  2887.                     wasclosed = 1;
  2888.                     tcpsrfd = -1;
  2889.                     tcpsrv_port = 0;
  2890.                     return(-1);
  2891.             }
  2892.         }
  2893. #endif /* CK_SSL */
  2894.  
  2895. #ifndef datageneral
  2896.         /* Find out our own IP address. */
  2897.         l_slen = sizeof(l_addr);
  2898.         bzero((char *)&l_addr, l_slen);
  2899. #ifndef EXCELAN
  2900.         if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  2901.             char * s = (char *)inet_ntoa(l_addr.sin_addr);
  2902.             ckstrncpy(myipaddr, s,20);
  2903.             debug(F110,"getsockname",myipaddr,0);
  2904.         }
  2905. #endif /* EXCELAN */
  2906. #endif /* datageneral */
  2907.  
  2908.         if (tn_ini() < 0)               /* Start TELNET negotiations. */
  2909.           if (ttchk() < 0) {            /* Disconnected? */
  2910.               i = errno;                /* save error code */
  2911. #ifdef TCPIPLIB
  2912.               socket_close(tcpsrfd);
  2913. #else /* TCPIPLIB */
  2914.               close(tcpsrfd);
  2915. #endif /* TCPIPLIB */
  2916.               ttyfd = -1;
  2917.               wasclosed = 1;
  2918.               tcpsrfd = -1;
  2919.               tcpsrv_port = 0;
  2920.               errno = i;                /* and report this error */
  2921.               debug(F101,"tcpsrv_open accept errno","",errno);
  2922.               return(-1);
  2923.           }
  2924.         debug(F101,"tcpsrv_open service","",x);
  2925.         if (*lcl < 0)                   /* Set local mode. */
  2926.           *lcl = 1;
  2927.  
  2928. #ifdef CK_KERBEROS
  2929. #ifdef KRB5_U2U
  2930.         if ( ttnproto == NP_K5U2U ) {
  2931.             if (k5_user_to_user_server_auth() != 0) {
  2932.                 i = errno;                /* save error code */
  2933. #ifdef TCPIPLIB
  2934.                 socket_close(tcpsrfd);
  2935. #else /* TCPIPLIB */
  2936.                 close(tcpsrfd);
  2937. #endif /* TCPIPLIB */
  2938.                 ttyfd = -1;
  2939.                 wasclosed = 1;
  2940.                 tcpsrfd = -1;
  2941.                 tcpsrv_port = 0;
  2942.                 errno = i;                /* and report this error */
  2943.                 debug(F101,"tcpsrv_open accept errno","",errno);
  2944.                 return(-1);
  2945.             }
  2946.         }
  2947. #endif /* KRB5_U2U */
  2948. #endif /* CK_KERBEROS */
  2949.  
  2950.         ckstrncpy(ipaddr,(char *)inet_ntoa(saddr.sin_addr),20);
  2951.         if (tcp_rdns) {
  2952.             if (!quiet) {
  2953.                 printf(" Reverse DNS Lookup... ");
  2954.                 fflush(stdout);
  2955.             }
  2956.             if (host = gethostbyaddr((char *)&saddr.sin_addr,4,PF_INET)) {
  2957.                 host = ck_copyhostent(host);
  2958.                 debug(F100,"tcpsrv_open gethostbyaddr != NULL","",0);
  2959.                 if (!quiet) {
  2960.                     printf("(OK)\n");
  2961.                     fflush(stdout);
  2962.                 }
  2963.                 name[0] = '*';
  2964.                 ckstrncpy(&name[1],host->h_name,78);
  2965.                 strncat(name,":",80-strlen(name));
  2966.                 strncat(name,p,80-strlen(name));
  2967.                 if (!quiet
  2968. #ifndef NOICP
  2969.                     && !doconx
  2970. #endif /* NOICP */
  2971.                     )
  2972.                   printf("%s connected on port %s\n",host->h_name,p);
  2973.             } else {
  2974.                 if (!quiet) printf("Failed.\n");
  2975.             }
  2976.         } else if (!quiet) printf("(OK)\n");
  2977.  
  2978.         if (!tcp_rdns || !host) {
  2979.             ckstrncpy(name,ipaddr,80);
  2980.             ckstrncat(name,":",80);
  2981.             ckstrncat(name,ckuitoa(ntohs(saddr.sin_port)),80);
  2982.             if (!quiet
  2983. #ifndef NOICP
  2984.                 && !doconx
  2985. #endif /* NOICP */
  2986.                 )
  2987.               printf("%s connected on port %d\n",ipaddr,ntohs(saddr.sin_port));
  2988.         }
  2989.         if (!quiet) fflush(stdout);
  2990.         return(0);                      /* Done. */
  2991.     } else {
  2992.         i = errno;                      /* save error code */
  2993. #ifdef TCPIPLIB
  2994.         socket_close(tcpsrfd);
  2995. #else /* TCPIPLIB */
  2996.         close(tcpsrfd);
  2997. #endif /* TCPIPLIB */
  2998.         ttyfd = -1;
  2999.         wasclosed = 1;
  3000.         tcpsrfd = -1;
  3001.         tcpsrv_port = 0;
  3002.         errno = i;                      /* and report this error */
  3003.         debug(F101,"tcpsrv_open accept errno","",errno);
  3004.         return(-1);
  3005.     }
  3006. }
  3007. #endif /* NOLISTEN */
  3008. #endif /* OS2 */
  3009. #endif /* TCPSOCKET */
  3010. #endif /* NONET */
  3011.  
  3012. #ifdef TCPSOCKET
  3013. char *
  3014. ckname2addr(name) char * name;
  3015. {
  3016. #ifdef HPUX5
  3017.     return("");
  3018. #else
  3019.     struct hostent *host;
  3020.  
  3021.     if (name == NULL || *name == '\0')
  3022.         return("");
  3023.  
  3024.     host = gethostbyname(name);
  3025.     if ( host ) {
  3026.         host = ck_copyhostent(host);
  3027.         return(inet_ntoa(*((struct in_addr *) host->h_addr)));
  3028.     }
  3029.     return("");
  3030. #endif /* HPUX5 */
  3031. }
  3032.  
  3033. char *
  3034. ckaddr2name(addr) char * addr;
  3035. {
  3036. #ifdef HPUX5
  3037.     return("");
  3038. #else
  3039.     struct hostent *host;
  3040.     struct in_addr sin_addr;
  3041.  
  3042.     if (addr == NULL || *addr == '\0')
  3043.         return("");
  3044.  
  3045.     sin_addr.s_addr = inet_addr(addr);
  3046.     host = gethostbyaddr((char *)&sin_addr,4,AF_INET);
  3047.     if (host) {
  3048.         host = ck_copyhostent(host);
  3049.         return((char *)host->h_name);
  3050.     }
  3051.     return("");
  3052. #endif /* HPUX5 */
  3053. }
  3054. #endif /* TCPSOCKET */
  3055.  
  3056. unsigned long peerxipaddr = 0L;
  3057.  
  3058. char *
  3059. ckgetpeer() {
  3060. #ifdef TCPSOCKET
  3061.     static char namebuf[256];
  3062.     static struct hostent *host;
  3063.     static struct sockaddr_in saddr;
  3064. #ifdef PTX
  3065.     static size_t saddrlen;
  3066. #else
  3067. #ifdef AIX42
  3068.     /* It's size_t in 4.2 but int in 4.1 and earlier. */
  3069.     /* Note: the 4.2 man page lies; believe socket.h. */
  3070.     static size_t saddrlen;
  3071. #else
  3072. #ifdef UNIXWARE
  3073.     static size_t saddrlen;
  3074. #else  /* UNIXWARE */
  3075. #ifdef DEC_TCPIP
  3076.     static unsigned int saddrlen;
  3077. #else
  3078.     static int saddrlen;
  3079. #endif /* VMS */
  3080. #endif /* UNIXWARE */
  3081. #endif /* AIX42 */
  3082. #endif /* PTX */
  3083.     saddrlen = sizeof(saddr);
  3084.     if (getpeername(ttyfd,(struct sockaddr *)&saddr,&saddrlen) < 0) {
  3085.         debug(F111,"ckgetpeer failure",ckitoa(ttyfd),errno);
  3086.         return(NULL);
  3087.     }
  3088.     host = gethostbyaddr((char *)&saddr.sin_addr,4,AF_INET);
  3089.     if (host) {
  3090.         host = ck_copyhostent(host);
  3091.         ckstrncpy(namebuf,(char *)host->h_name,80);
  3092.     } else {
  3093.         ckstrncpy(namebuf,(char *)inet_ntoa(saddr.sin_addr),80);
  3094.     }
  3095.     peerxipaddr = ntohl(saddr.sin_addr.s_addr);
  3096.     debug(F111,"ckgetpeer",namebuf,peerxipaddr);
  3097.     return(namebuf);
  3098. #else
  3099.     return(NULL);
  3100. #endif /* TCPSOCKET */
  3101. }
  3102.  
  3103. #ifndef NONET
  3104.  
  3105. char *
  3106. #ifdef CK_ANSIC
  3107. ckgetfqhostname(char * name)
  3108. #else
  3109. ckgetfqhostname(name) char * name;
  3110. #endif /* CK_ANSIC */
  3111. {
  3112.     static char namebuf[256];
  3113.     struct hostent *host=NULL;
  3114.     struct sockaddr_in r_addr;
  3115.     int i;
  3116.  
  3117.     debug(F110,"ckgetfqhn()",name,0);
  3118.  
  3119.     ckstrncpy(namebuf,name,256);
  3120.     namebuf[255] = '\0';
  3121.     i = ckindex(":",namebuf,0,0,0);
  3122.     if (i)
  3123.       namebuf[i-1] = '\0';
  3124.  
  3125.     bzero((char *)&r_addr, sizeof(r_addr));
  3126.  
  3127.     host = gethostbyname(namebuf);
  3128.     if (host) {
  3129.         host = ck_copyhostent(host);
  3130.         debug(F100,"ckgetfqhn() gethostbyname != NULL","",0);
  3131.         r_addr.sin_family = host->h_addrtype;
  3132. #ifdef HADDRLIST
  3133. #ifdef h_addr
  3134.         /* This is for trying multiple IP addresses - see <netdb.h> */
  3135.         if (!(host->h_addr_list))
  3136.           goto exit_func;
  3137.         bcopy(host->h_addr_list[0],
  3138.               (caddr_t)&r_addr.sin_addr,
  3139.               host->h_length
  3140.               );
  3141. #else
  3142.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3143. #endif /* h_addr */
  3144. #else  /* HADDRLIST */
  3145.         bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  3146. #endif /* HADDRLIST */
  3147. #ifndef EXCELAN
  3148.         debug(F111,"BCOPY","host->h_addr",host->h_addr);
  3149. #endif /* EXCELAN */
  3150.         debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  3151.               (caddr_t)&r_addr.sin_addr);
  3152.         debug(F111,"BCOPY","host->h_length",host->h_length);
  3153.  
  3154. #ifdef NT
  3155.         /* Windows 95/98 requires a 1 second wait between calls to Microsoft */
  3156.         /* provided DNS functions.  Otherwise, the TTL of the DNS response */
  3157.         /* is ignored. */
  3158.         if (isWin95())
  3159.           sleep(1);
  3160. #endif /* NT */
  3161.         host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET);
  3162.         if (host) {
  3163.             host = ck_copyhostent(host);
  3164.             debug(F100,"ckgetfqhn() gethostbyaddr != NULL","",0);
  3165.             ckstrncpy(namebuf, host->h_name, 256);
  3166.         }
  3167.     }
  3168.  
  3169. #ifdef HADDRLIST
  3170. #ifdef h_addr
  3171.   exit_func:
  3172. #endif /* h_addr */
  3173. #endif /* HADDRLIST */
  3174.  
  3175.     if (i > 0)
  3176.       strncat(namebuf,&name[i-1],256-strlen(namebuf)-strlen(&name[i-1]));
  3177.     debug(F110,"ckgetfqhn()",namebuf,0);
  3178.     return(namebuf);
  3179. }
  3180.  
  3181. VOID
  3182. #ifdef CK_ANSIC
  3183. setnproto(char * p)
  3184. #else
  3185. setnproto(p) char * p;
  3186. #endif /* CK_ANSIC */
  3187. {
  3188.     if (!isdigit(*p)) {
  3189.         if (!strcmp("kermit",p))
  3190.           ttnproto = NP_KERMIT;
  3191.         else if (!strcmp("telnet",p))
  3192.           ttnproto = NP_TELNET;
  3193.         else if (!strcmp("http",p))
  3194.           ttnproto = NP_TCPRAW;
  3195. #ifdef RLOGCODE
  3196.         else if (!strcmp("login",p))
  3197.           ttnproto = NP_RLOGIN;
  3198. #endif /* RLOGCODE */
  3199. #ifdef CK_SSL
  3200.         /* Commonly used SSL ports (might not be in services file) */
  3201.         else if (!strcmp("https",p)) {
  3202.           ttnproto = NP_SSL;
  3203.           ssl_only_flag = 1;
  3204.         } else if (!strcmp("ssl-telnet",p)) {
  3205.           ttnproto = NP_TELNET;
  3206.           ssl_only_flag = 1;
  3207.         } else if (!strcmp("telnets",p)) {
  3208.           ttnproto = NP_TELNET;
  3209.           ssl_only_flag = 1;
  3210.         }
  3211. #endif /* CK_SSL */
  3212. #ifdef CK_KERBEROS
  3213. #ifdef RLOGCODE
  3214.         else if (!strcmp("klogin",p)) {
  3215.             if (ck_krb5_is_installed())
  3216.               ttnproto = NP_K5LOGIN;
  3217.             else if (ck_krb4_is_installed())
  3218.               ttnproto = NP_K4LOGIN;
  3219.             else
  3220.               ttnproto = NP_RLOGIN;
  3221.         } else if (!strcmp("eklogin",p)) {
  3222.             if (ck_krb5_is_installed())
  3223.               ttnproto = NP_EK5LOGIN;
  3224.             else if (ck_krb4_is_installed())
  3225.               ttnproto = NP_EK4LOGIN;
  3226.             else
  3227.               ttnproto = NP_RLOGIN;
  3228.         }
  3229. #endif /* RLOGCODE */
  3230. #endif /* CK_KERBEROS */
  3231.         else
  3232.           ttnproto = NP_NONE;
  3233.     } else {
  3234.         switch (atoi(p)) {
  3235.           case 23:                      /* Telnet */
  3236.             ttnproto = NP_TELNET;
  3237.             break;
  3238.           case 513:
  3239.             ttnproto = NP_RLOGIN;
  3240.             break;
  3241.           case 1649:
  3242.             ttnproto = NP_KERMIT;
  3243.             break;
  3244. #ifdef CK_SSL
  3245.           case 443:
  3246.             ttnproto = NP_SSL;
  3247.             ssl_only_flag = 1;
  3248.             break;
  3249.           case 151:
  3250.           case 992:
  3251.             ttnproto = NP_TELNET;
  3252.             ssl_only_flag = 1;
  3253.             break;
  3254. #endif /* CK_SSL */
  3255. #ifdef CK_KERBEROS
  3256.           case 543:
  3257.             if (ck_krb5_is_installed())
  3258.               ttnproto = NP_K5LOGIN;
  3259.             else if (ck_krb4_is_installed())
  3260.               ttnproto = NP_K4LOGIN;
  3261.             else
  3262.               ttnproto = NP_RLOGIN;
  3263.             break;
  3264.           case 2105:
  3265.             if (ck_krb5_is_installed())
  3266.               ttnproto = NP_EK5LOGIN;
  3267.             else if (ck_krb4_is_installed())
  3268.               ttnproto = NP_EK4LOGIN;
  3269.             else
  3270.               ttnproto = NP_RLOGIN;
  3271.             break;
  3272. #endif /* CK_KERBEROS */
  3273.           case 80:                      /* HTTP */
  3274.             ttnproto = NP_TCPRAW;
  3275.             break;
  3276.           default:
  3277.             ttnproto = NP_NONE;
  3278.             break;
  3279.         }
  3280.     }
  3281. }
  3282.  
  3283. /* ckgetservice() is used to determine the port number for a given */
  3284. /* service taking into account the use of DNS SRV records.         */
  3285.  
  3286. static struct servent servrec;
  3287. static struct servent *
  3288. ckgetservice(hostname, servicename, ip, iplen)
  3289.     char *hostname; char * servicename; char * ip; int iplen;
  3290. {
  3291.     struct servent * service = NULL;
  3292. #ifdef CK_DNS_SRV
  3293.     struct sockaddr * dns_addrs = NULL;
  3294.     int dns_naddrs = 0;
  3295. #endif /* CK_DNS_SRV */
  3296.  
  3297.     if (isdigit(*servicename)) {        /* Use socket number without lookup */
  3298.         service = &servrec;
  3299.         service->s_port = htons((unsigned short)atoi(servicename));
  3300.     } else {                            /* Otherwise lookup the service name */
  3301. #ifdef CK_DNS_SRV
  3302.         if (tcp_dns_srv && !quiet) {
  3303.             printf(" DNS SRV Lookup... ");
  3304.             fflush(stdout);
  3305.         }
  3306.         if (tcp_dns_srv &&
  3307.             locate_srv_dns(hostname,
  3308.                            servicename,
  3309.                            "tcp",
  3310.                            &dns_addrs,
  3311.                            &dns_naddrs
  3312.                            )
  3313.             ) {
  3314.             /* Use the first one.  Eventually we should cycle through all */
  3315.             /* the returned IP addresses and port numbers. */
  3316.             struct sockaddr_in *sin = NULL;
  3317. #ifdef BETADEBUG
  3318.             int i;
  3319.             printf("\r\n");
  3320.             for ( i=0;i<dns_naddrs;i++ ) {
  3321.                 sin = (struct sockaddr_in *) &dns_addrs[i];
  3322.                 printf("dns_addrs[%d] = %s %d\r\n", i,
  3323.                         (char *)inet_ntoa(sin->sin_addr),
  3324.                         ntohs(sin->sin_port));
  3325.             }
  3326. #endif /* BETADEBUG */
  3327.             sin = (struct sockaddr_in *) &dns_addrs[0];
  3328.             if ( ip && iplen > 0 )
  3329.                 ckstrncpy(ip,(char *)inet_ntoa(sin->sin_addr),iplen);
  3330.             service = &servrec;
  3331.             service->s_port = sin->sin_port;
  3332.  
  3333.             free(dns_addrs);
  3334.             dns_addrs = NULL;
  3335.             dns_naddrs = 0;
  3336.         } else
  3337. #endif /* CK_DNS_SRV */
  3338.             service = getservbyname(servicename, "tcp");
  3339.     }
  3340.     if (!service) {
  3341.         if (!ckstrcmp("kermit",servicename,-1,0)) { /* Kermit service port */
  3342.             service = &servrec;
  3343.             service->s_port = htons(1649);
  3344.         } else if (!ckstrcmp("telnet",servicename,-1,0)) { /* Telnet port */
  3345.             service = &servrec;
  3346.             service->s_port = htons(23);
  3347.         } else if (!ckstrcmp("http",servicename,-1,0)) {
  3348.             service = &servrec;
  3349.             service->s_port = htons(80);
  3350.         }
  3351. #ifdef RLOGCODE
  3352.         else if (!ckstrcmp("login",servicename,-1,0)) {
  3353.             service = &servrec;
  3354.             service->s_port = htons(513);
  3355.         }
  3356. #endif /* RLOGCODE */
  3357. #ifdef CK_SSL
  3358.         /* Commonly used SSL ports (might not be in services file) */
  3359.         else if (!ckstrcmp("https",servicename,-1,0)) {
  3360.             service = &servrec;
  3361.             service->s_port = htons(443);
  3362.         } else if (!ckstrcmp("ssl-telnet",servicename,-1,0)) {
  3363.             service = &servrec;
  3364.             service->s_port = htons(151);
  3365.         } else if (!ckstrcmp("telnets",servicename,-1,0)) {
  3366.             service = &servrec;
  3367.             service->s_port = htons(992);
  3368.         }
  3369. #endif /* CK_SSL */
  3370. #ifdef CK_KERBEROS
  3371. #ifdef RLOGCODE
  3372.         else if (!ckstrcmp("klogin",servicename,-1,0)) {
  3373.             service = &servrec;
  3374.             service->s_port = htons(543);
  3375.         } else if (!ckstrcmp("eklogin",servicename,-1,0)) {
  3376.             service = &servrec;
  3377.             service->s_port = htons(2105);
  3378.         }
  3379. #endif /* RLOGCODE */
  3380. #endif /* CK_KERBEROS */
  3381.     }
  3382.     return(service);
  3383. }
  3384.  
  3385. /*  N E T O P E N  --  Open a network connection  */
  3386. /*
  3387.   Calling conventions same as ttopen(), except third argument is network
  3388.   type rather than modem type.  Designed to be called from within ttopen.
  3389. */
  3390.  
  3391. int
  3392. netopen(name, lcl, nett) char *name; int *lcl, nett; {
  3393.     char *p;
  3394.     int i, x, dns = 0;
  3395. #ifdef TCPSOCKET
  3396.     int isconnect = 0;
  3397. #ifdef SO_OOBINLINE
  3398.     int on = 1;
  3399. #endif /* SO_OOBINLINE */
  3400.     struct servent *service=NULL;
  3401.     struct hostent *host=NULL;
  3402.     struct sockaddr_in r_addr;
  3403.     struct sockaddr_in sin;
  3404.     struct sockaddr_in l_addr;
  3405.     GSOCKNAME_T l_slen;
  3406. #ifdef EXCELAN
  3407.     struct sockaddr_in send_socket;
  3408. #endif /* EXCELAN */
  3409.  
  3410. #ifdef INADDRX
  3411. /* inet_addr() is of type struct in_addr */
  3412. #ifdef datageneral
  3413.     extern struct in_addr inet_addr();
  3414. #else
  3415. #ifdef HPUX5WINTCP
  3416.     extern struct in_addr inet_addr();
  3417. #endif /* HPUX5WINTCP */
  3418. #endif /* datageneral */
  3419.     struct in_addr iax;
  3420. #else
  3421. #ifdef INADDR_NONE
  3422.     struct in_addr iax;
  3423. #else /* INADDR_NONE */
  3424.     long iax;
  3425. #endif /* INADDR_NONE */
  3426. #endif /* INADDRX */
  3427. #endif /* TCPSOCKET */
  3428.  
  3429. #ifdef COMMENT
  3430. /* This causes big trouble */
  3431. #ifndef INADDR_NONE
  3432. #define INADDR_NONE 0xffffffff
  3433. #endif /* INADDR_NONE */
  3434. #endif /* COMMENT */
  3435.  
  3436. #ifdef SUNX25                           /* Code for SunLink X.25 support */
  3437. #define X29PID 1                        /* X.29 Protocol ID */
  3438. _PROTOTYP(SIGTYP x25oobh, (int) );
  3439.     CONN_DB x25host;
  3440. #ifndef X25_WR_FACILITY
  3441.     FACILITY x25facil;
  3442. #else
  3443.     FACILITY_DB x25facil;
  3444. #endif /* X25_WR_FACILITY */
  3445.     static int needh = 1;
  3446.     PID_T pid;
  3447.     extern int linkid, lcn, x25ver;
  3448. #endif /* SUNX25 */
  3449. #ifdef ANYX25
  3450.     extern int revcall, closgr, cudata;
  3451.     extern char udata[];
  3452. #endif /* ANYX25 */
  3453.  
  3454. #ifdef IBMX25                           /* Variables for IBM X25 */
  3455.     extern int x25port;                 /* Logical port to use */
  3456.     extern x25addr_t local_nua;         /* Local X.25 address */
  3457.     extern x25addr_t remote_nua;        /* Remote X.25 address */
  3458.     extern char x25name[];              /* X25 device name (sx25a0) */
  3459.     extern char x25dev[];               /* X25 device file /dev/x25pkt */
  3460.     ulong bind_flags = 0;               /* Flags for binding the X25 stream */
  3461.     ulong token = 0;                    /* Temporary return code */
  3462. #endif /* IBMX25 */
  3463.  
  3464.     debug(F101,"netopen nett","",nett);
  3465.     *ipaddr = '\0';                     /* Initialize IP address string */
  3466.  
  3467. #ifdef SUNX25
  3468.     if (nett == NET_SX25) {             /* If network type is X.25 */
  3469.         netclos();                      /* Close any previous net connection */
  3470.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3471.  
  3472.         /* Set up host structure */
  3473.         bzero((char *)&x25host,sizeof(x25host));
  3474.         if ((x25host.hostlen = pkx121(name,x25host.host)) < 0) {
  3475.             fprintf (stderr,"Invalid X.121 host address %s\n",name);
  3476.             errno = 0;
  3477.             return (-1);
  3478.         }
  3479.         x25host.datalen = X29PIDLEN;
  3480.         x25host.data[0] = X29PID;
  3481.  
  3482.         /* Set call user data if specified */
  3483.         if (cudata) {
  3484.             ckstrncpy((char *)x25host.data+X29PIDLEN,udata,(int)strlen(udata));
  3485.             x25host.datalen += (int)strlen(udata);
  3486.         }
  3487.  
  3488.         /* Open SunLink X.25 socket */
  3489.         if (!quiet && *name) {
  3490.             printf(" Trying %s... ", name);
  3491.             fflush(stdout);
  3492.         }
  3493.         if ((ttyfd = socket(AF_X25, SOCK_STREAM, 0)) < 0) {
  3494.             debug(F101,"netopen socket error","",errno);
  3495.             perror ("X.25 socket error");
  3496.             return (-1);
  3497.         }
  3498.  
  3499.         /* Setting X.25 out-of-band data handler */
  3500.         pid = getpid();
  3501.         if (ioctl(ttyfd,SIOCSPGRP,&pid)) {
  3502.             perror("X.25 set process group id error");
  3503.             return(-1);
  3504.         }
  3505.         (VOID) signal(SIGURG,x25oobh);
  3506.  
  3507.         /* Set reverse charge call and closed user group if requested */
  3508.         bzero ((char *)&x25facil,sizeof(x25facil));
  3509.  
  3510. #ifndef X25_WR_FACILITY
  3511. /*  New SunLink (7.0 or 8.0, not sure which)... */
  3512.         x25facil.type = T_REVERSE_CHARGE; /* Reverse Charge */
  3513.         x25facil.f_reverse_charge = revcall ? 1 : 0;
  3514.         if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3515.             perror ("Setting X.25 reverse charge");
  3516.             return (-1);
  3517.         }
  3518.         if (closgr > -1) {              /* Closed User Group (Outgoing) */
  3519.             bzero ((char *)&x25facil,sizeof(x25facil));
  3520.             x25facil.type = T_CUG;
  3521.             x25facil.f_cug_req = CUG_REQ_ACS;
  3522.             x25facil.f_cug_index = closgr;
  3523.             if (ioctl(ttyfd,X25_SET_FACILITY,&x25facil) < 0) {
  3524.                 perror ("Setting X.25 closed user group");
  3525.                 return (-1);
  3526.             }
  3527.         }
  3528. #else
  3529. /*  Old SunLink 6.0 (or 7.0?)... */
  3530.         if (revcall) x25facil.reverse_charge = revcall;
  3531.         if (closgr > -1) {
  3532.             x25facil.cug_req = 1;
  3533.             x25facil.cug_index = closgr;
  3534.         }
  3535.         if (ioctl(ttyfd,X25_WR_FACILITY,&x25facil) < 0) {
  3536.             perror ("Setting X.25 facilities");
  3537.             return (-1);
  3538.         }
  3539. #endif /* X25_WR_FACILITY */
  3540.  
  3541.         /*  Need X.25 header with bits Q and M */
  3542.         if (ioctl (ttyfd,X25_HEADER,&needh) < 0) {
  3543.             perror ("Setting X.25 header");
  3544.             return (-1);
  3545.         }
  3546.  
  3547.         /* Connects to remote host via SunLink X.25 */
  3548.         if (connect(ttyfd,(struct sockaddr *)&x25host,sizeof(x25host)) < 0) {
  3549.             i = errno;
  3550.             debug(F101,"netopen connect errno","",i);
  3551.             if (i) {
  3552.                 perror("netopen x25 connect");
  3553.                 x25diag();
  3554.             }
  3555.             (VOID) netclos();
  3556.             ttyfd = -1;
  3557.             wasclosed = 1;
  3558.             ttnproto = NP_NONE;
  3559.             errno = i;
  3560.             return (-1);
  3561.         }
  3562.  
  3563.         /* Get X.25 link identification used for the connection */
  3564.         if (ioctl(ttyfd,X25_GET_LINK,&linkid) < 0) {
  3565.             perror ("Getting X.25 link id");
  3566.             return (-1);
  3567.         }
  3568.  
  3569.         /* Get X.25 logical channel number used for the connection */
  3570.         if (ioctl(ttyfd,X25_RD_LCGN,&lcn) < 0) {
  3571.             perror ("Getting X.25 lcn");
  3572.             return (-1);
  3573.         }
  3574.  
  3575.         /* Get SunLink X.25 version */
  3576.         if (ioctl(ttyfd,X25_VERSION,&x25ver) < 0) {
  3577.             perror ("Getting SunLink X.25 version");
  3578.             return (-1);
  3579.         }
  3580.         ttnet = nett;                   /* Sunlink X.25 network */
  3581.         ttnproto = NP_X3;               /* PAD X.3, X.28, X.29 protocol */
  3582.         if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3583.         return(0);
  3584.     } else /* Note that SUNX25 support can coexist with TCP/IP support. */
  3585. #endif /* SUNX25 */
  3586.  
  3587. #ifdef IBMX25
  3588.     /* riehm */
  3589.     if (nett == NET_IX25) {             /* IBM AIX X.25 */
  3590.         netclos();                      /* Close any previous net connection */
  3591.         ttnproto = NP_NONE;             /* No protocol selected yet */
  3592.  
  3593.         /* find out who we are - this is not so easy on AIX */
  3594.         /* riehm: need to write the code that finds this out
  3595.          * automatically, or at least allow it to be configured
  3596.          * somehow
  3597.          */
  3598.         if (!local_nua[0] && !x25local_nua(local_nua)) {
  3599.             return(-1);
  3600.         }
  3601.  
  3602.         /* Initialise the X25 API (once per process? once per connection?) */
  3603.  
  3604.         debug(F110, "Opening ", x25dev, 0 );
  3605.         /* set O_NDELAY to allow polling? */
  3606.         if ((ttyfd = open(x25dev, O_RDWR)) < 0) {
  3607.             perror ("X.25 device open error");
  3608.             debug(F101,"netopen: device open error","",errno);
  3609.             return (-1);
  3610.         }
  3611.  
  3612.         /* push the NPI onto the STREAM */
  3613.         if (ioctl(ttyfd,I_PUSH,"npi") < 0 ) {
  3614.             close(ttyfd);
  3615.             ttyfd = -1;
  3616.             wasclosed = 1;
  3617.             perror( "kermit: netopen(): couldn't push npi on the X25 stream" );
  3618.             debug(F101,"netopen: can't push npi on the X25 stream","",errno);
  3619.             return (-1);
  3620.         }
  3621.  
  3622.         /* set up server mode - bind the x25 port and wait for
  3623.          * incoming connections
  3624.          */
  3625.         if (name[0] == '*') {           /* Server */
  3626.             /* set up a server - see the warning in x25bind() */
  3627.             bind_flags |= TOKEN_REQUEST;
  3628.  
  3629.             /* bind kermit to the local X25 address */
  3630.             token = x25bind(ttyfd,
  3631.                             local_nua,
  3632.                             udata,
  3633.                             (int)strlen( udata ),
  3634.                             1,
  3635.                             x25port,
  3636.                             bind_flags
  3637.                             );
  3638.             if (token < 0) {
  3639.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3640.                 netclos();
  3641.                 return(-1);
  3642.             }
  3643.             /* Currently not connected to a remote host */
  3644.  
  3645.             remote_nua[0] = '\0';
  3646.  
  3647.             /* store the fd so that incoming calls can have their own fd
  3648.              * This is almost support for a true server (ie: a'la ftpd)
  3649.              * but we're not quite there yet.
  3650.              * used in netclos()
  3651.              */
  3652.             x25serverfd = ttyfd;
  3653.             /*
  3654.              * wait for an incoming call
  3655.              * this should happen in the "server" command and not in
  3656.              * the "set host *" command.
  3657.              */
  3658.             if ((ttyfd = x25getcall(ttyfd)) < 0) {
  3659.                 netclos();
  3660.                 return(-1);
  3661.             }
  3662.         } else {                        /* Client */
  3663.             /* Bind kermit to the local X25 address */
  3664.             token = x25bind(
  3665.                             ttyfd,
  3666.                             local_nua,
  3667.                             (char *)NULL,
  3668.                             0,
  3669.                             0,
  3670.                             x25port,
  3671.                             bind_flags
  3672.                             );
  3673.             if (token < 0) {
  3674.                 debug(F100,"netopen: couldn't bind to local X25 address","",0);
  3675.                 netclos();
  3676.                 return(-1);
  3677.             }
  3678. /* riehm: this should be done via the CONNECT command, not HOST! */
  3679.             {
  3680.                 x25serverfd = 0;
  3681.                 /* call the remote host */
  3682.                 /* name == address of remote host as char* */
  3683.                 if (x25call(ttyfd, name, udata) < 0 ) {
  3684.                     debug(F100,
  3685.                           "netopen: couldn't connect to remote X25 address",
  3686.                           "", 0);
  3687.                     netclos();
  3688.                     return(-1);
  3689.                 }
  3690.                 strcpy(remote_nua, name);
  3691.             }
  3692.         }
  3693.         ttnet = nett;                   /* AIX X.25 network */
  3694.         if (lcl) if (*lcl < 0) *lcl = 1; /* Local mode */
  3695.         return(0);
  3696.  
  3697.     } else /* Note that IBMX25 support can coexist with TCP/IP support. */
  3698. #endif /* IBMX25 */
  3699.  
  3700. /*   Add support for other networks here. */
  3701.  
  3702.       if (nett != NET_TCPB) return(-1); /* BSD socket support */
  3703.  
  3704. #ifdef TCPSOCKET
  3705.     netclos();                          /* Close any previous connection. */
  3706.     ckstrncpy(namecopy, name, NAMECPYL);        /* Copy the hostname. */
  3707.     debug(F110,"netopen namecopy",namecopy,0);
  3708.  
  3709. #ifndef NOLISTEN
  3710.     if (name[0] == '*')
  3711.       return(tcpsrv_open(name, lcl, nett, 0));
  3712. #endif /* NOLISTEN */
  3713.  
  3714.     p = namecopy;                       /* Was a service requested? */
  3715.     while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3716.     if (*p == ':') {                    /* Have a colon */
  3717.         debug(F110,"netopen name has colon",namecopy,0);
  3718.         *p++ = '\0';                    /* Get service name or number */
  3719. #ifdef CK_URL
  3720.         /*
  3721.            Here we have to check for various popular syntaxes:
  3722.            host:port (our original syntax)
  3723.            URL such as telnet:host or telnet://host/
  3724.            Or even telnet://user:password@host:port/path/
  3725.            Or a malformed URL such as generated by Netscape 4.0 like:
  3726.            telnet:telnet or telnet::host.
  3727.         */
  3728.  
  3729.         /*
  3730.          * REPLACE THIS CODE WITH urlparse() but not on the day of the
  3731.          * C-Kermit 8.0 RELEASE.
  3732.          */
  3733.  
  3734.         if (*p == ':')                  /* a second colon */
  3735.           *p++ = '\0';                  /* get rid of that one too */
  3736.         while (*p == '/') *p++ = '\0';  /* and slashes */
  3737.         x = strlen(p);                  /* Length of remainder */
  3738.         if (p[x-1] == '/')              /* If there is a trailing slash */
  3739.           p[x-1] = '\0';                /* remove it. */
  3740.         debug(F110,"netopen namecopy after stripping",namecopy,0);
  3741.         debug(F110,"netopen p after stripping",p,0);
  3742.         service = getservbyname(namecopy,"tcp");
  3743.         if (service ||
  3744. #ifdef RLOGCODE
  3745.             !ckstrcmp("rlogin",namecopy,NAMECPYL,0) ||
  3746. #endif /* RLOGCODE */
  3747. #ifdef CK_SSL
  3748.             !ckstrcmp("telnets",namecopy,NAMECPYL,0) ||
  3749. #endif /* CK_SSL */
  3750.             !ckstrcmp("iksd",namecopy,NAMECPYL,0)
  3751.             ) {
  3752.             char temphost[256], tempservice[80], temppath[256];
  3753.             char * q = p, *r = p, *w = p;
  3754.             int uidfound=0;
  3755.             extern char pwbuf[];
  3756.             extern int pwflg, pwcrypt;
  3757.  
  3758.             if (ttnproto == NP_DEFAULT)
  3759.               setnproto(namecopy);
  3760.  
  3761.             /* Check for userid and possibly password */
  3762.             while (*p != '\0' && *p != '@')
  3763.                 p++; /* look for @ */
  3764.             if (*p == '@') {
  3765.                 /* found username and perhaps password */
  3766.                 debug(F110,"netopen namecopy found @","",0);
  3767.                 *p = '\0';
  3768.                 p++;
  3769.                 while (*w != '\0' && *w != ':')
  3770.                   w++;
  3771.                 if (*w == ':')
  3772.                   *w++ = '\0';
  3773.                 /* r now points to username, save it and the password */
  3774.                 debug(F110,"netopen namecopy username",r,0);
  3775.                 debug(F110,"netopen namecopy password",w,0);
  3776.                 uidfound=1;
  3777.                 if ( strcmp(uidbuf,r) || *w )
  3778.                     ckstrncpy(pwbuf,w,PWBUFL+1);
  3779.                 ckstrncpy(uidbuf,r,UIDBUFLEN);
  3780.                 pwflg = 1;
  3781.                 pwcrypt = 0;
  3782.                 q = p;                  /* Host after user and pwd */
  3783.             } else {
  3784.                 p = q;                  /* No username or password */
  3785.             }
  3786.             /* Now we must look for the optional port. */
  3787.             debug(F110,"netopen x p",p,0);
  3788.             debug(F110,"netopen x q",q,0);
  3789.  
  3790.             /* Look for the port/service or a file/directory path */
  3791.             while (*p != '\0' && *p != ':' && *p != '/')
  3792.               p++;
  3793.             if (*p == ':') {
  3794.                 debug(F110,"netopen found port",q,0);
  3795.                 *p++ = '\0';            /* Found a port name or number */
  3796.                 r = p;
  3797.  
  3798.                 /* Look for the end of port/service or a file/directory path */
  3799.                 while (*p != '\0' && *p != '/')
  3800.                     p++;
  3801.                 if (*p == '/')
  3802.                     *p++ = '\0';
  3803.  
  3804.                 debug(F110,"netopen port",r,0);
  3805.                 ckstrncpy(tempservice,r,80);
  3806.                 ckstrncpy(temphost,q,256);
  3807.                 ckstrncpy(temppath,p,256);
  3808.                 ckstrncpy(namecopy,temphost,NAMECPYL);
  3809.                 debug(F110,"netopen tempservice",tempservice,0);
  3810.                 debug(F110,"netopen temphost",temphost,0);
  3811.                 debug(F110,"netopen temppath",temppath,0);
  3812.  
  3813.                 /* move port/service to a buffer that won't go away */
  3814.                 x = strlen(namecopy);
  3815.                 p = namecopy + x + 1;
  3816.                 ckstrncpy(p, tempservice, NAMECPYL - x);
  3817.             } else {
  3818.                 /* Handle a path if we found one */
  3819.                 if (*p == '/')
  3820.                     *p++ = '\0';
  3821.                 ckstrncpy(temppath,p,256);
  3822.  
  3823.                 /* We didn't find another port, but if q is a service */
  3824.                 /* then assume that namecopy is actually a host.      */
  3825.                 if (getservbyname(q,"tcp")) {
  3826.                     p = q;
  3827.                 } else {
  3828. #ifdef RLOGCODE
  3829.                     /* rlogin is not a valid service */
  3830.                     if (!ckstrcmp("rlogin",namecopy,6,0)) {
  3831.                         ckstrncpy(namecopy,"login",NAMECPYL);
  3832.                     }
  3833. #endif /* RLOGCODE */
  3834.                     /* iksd is not a valid service */
  3835.                     if (!ckstrcmp("iksd",namecopy,6,0)) {
  3836.                         ckstrncpy(namecopy,"kermit",NAMECPYL);
  3837.                     }
  3838.                     /* Reconstruct namecopy */
  3839.                     ckstrncpy(tempservice,namecopy,80);
  3840.                     ckstrncpy(temphost,q,256);
  3841.                     ckstrncpy(namecopy,temphost,NAMECPYL);
  3842.                     debug(F110,"netopen tempservice",tempservice,0);
  3843.                     debug(F110,"netopen temphost",temphost,0);
  3844.                     debug(F110,"netopen temppath",temppath,0);
  3845.  
  3846.                     /* move port/service to a buffer that won't go away */
  3847.                     x = strlen(namecopy);
  3848.                     p = namecopy + x + 1;
  3849.                     ckstrncpy(p, tempservice, NAMECPYL - x - 1);
  3850.                 }
  3851.             }
  3852.             debug(F110,"netopen URL result: host",namecopy,0);
  3853.             debug(F110,"netopen URL result: service",p,0);
  3854.             debug(F110,"netopen URL result: path",temppath,0);
  3855.  
  3856. #ifdef IKS_GET
  3857.             /* If we have set a path specified, we need to try to GET it */
  3858.             /* But we have another problem, we have to login first.  How */
  3859.             /* do we specify that a login must be done before the GET?   */
  3860.             /* The user's name if specified is in 'userid' and the       */
  3861.             /* password if any is in 'pwbuf'.                            */
  3862.             if ( temppath[0] ) {
  3863.                 extern int action;
  3864.                 extern char * cmarg;
  3865.  
  3866.                 if ( !uidfound ) {
  3867.                     /* If no userid was specified as part of the URL but
  3868.                      * a path was specified, then we
  3869.                      * set the user name to anonymous and the password
  3870.                      * to the current userid.
  3871.                      */
  3872.                     ckstrncpy(pwbuf,uidbuf,PWBUFL);
  3873.                     ckstrncat(pwbuf,"@",PWBUFL);
  3874.                     pwflg = 1;
  3875.                     pwcrypt = 0;
  3876.                     ckstrncpy(uidbuf,"anonymous",UIDBUFLEN);
  3877.                 }
  3878.  
  3879.                 /*
  3880.                  * If a file path was specified we perform the GET
  3881.                  * operation and then terminate the connection.
  3882.                  *
  3883.                  * If a directory was given instead of a file, then
  3884.                  * we should REMOTE CD to the directory and list its
  3885.                  * contents.  But how do we tell the difference?
  3886.                  */
  3887.                 makestr(&cmarg,temppath);
  3888.                 action = 'r';
  3889.             }
  3890. #endif /* IKS_GET */
  3891.         }
  3892. #endif /* CK_URL */
  3893.     } else {                            /* Otherwise use telnet */
  3894.         p = "telnet";
  3895.     }
  3896. /*
  3897.   By the time we get here, namecopy[] should hold the null-terminated
  3898.   hostname or address, and p should point to the service name or number.
  3899. */
  3900.     debug(F110,"netopen host",namecopy,0);
  3901.     debug(F110,"netopen service requested",p,0);
  3902.  
  3903.    /* Use the service port to set the default protocol type if necessary */
  3904.     if (ttnproto == NP_DEFAULT)
  3905.        setnproto(p);
  3906.  
  3907.     service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3908.     if (!service) {
  3909.         fprintf(stderr, "Can't find port for service %s\n", p);
  3910. #ifdef TGVORWIN
  3911.         debug(F101,"netopen can't get service","",socket_errno);
  3912. #else
  3913.         debug(F101,"netopen can't get service","",errno);
  3914. #endif /* TGVORWIN */
  3915.         errno = 0;                  /* (rather than mislead) */
  3916.         return(-1);
  3917.     } else {
  3918.         ckstrncpy(svcbuf,ckuitoa(ntohs(service->s_port)),sizeof(svcbuf));
  3919.         debug(F110,"netopen service ok",svcbuf,0);
  3920.     }
  3921.  
  3922. #ifdef RLOGCODE
  3923.     if (service && !strcmp("login",p) && service->s_port != htons(513)) {
  3924.         fprintf(stderr,
  3925.                 "  Warning: login service on port %d instead of port 513\n",
  3926.                  ntohs(service->s_port)
  3927.                 );
  3928.         fprintf(stderr, "  Edit SERVICES file if RLOGIN fails to connect.\n");
  3929.         debug(F101,"tcpsrv_open login on port","",ntohs(service->s_port));
  3930.     }
  3931. #endif /* RLOGCODE */
  3932.  
  3933. #ifndef NOHTTP
  3934.    /* For HTTP connections we must preserve the original hostname and */
  3935.    /* service requested so we can include them in the Host header.    */
  3936.     ckmakmsg(http_host_port,sizeof(http_host_port),namecopy,":",
  3937.               ckitoa(ntohs(service->s_port)),NULL);
  3938. #endif /* NOHTTP */
  3939.  
  3940. #ifndef NOHTTP
  3941.     /* 'namecopy' contains the name of the host to which we want to connect */
  3942.     /* 'svcbuf'   contains the service name                                 */
  3943.     /* 'service->s_port' contains the port number in network byte order     */
  3944.  
  3945.     /* If we are using an http proxy, we need to create a buffer containing */
  3946.     /*   hostname:port-number                                               */
  3947.     /* to pass to the http_connect() function.  Then we need to replace     */
  3948.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  3949.     /* with the port number of the proxy (default port 80).                 */
  3950.  
  3951.     if ( tcp_http_proxy ) {
  3952.         ckmakmsg(proxycopy,sizeof(proxycopy),namecopy,":",
  3953.                  ckuitoa(ntohs(service->s_port)),NULL);
  3954.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  3955.  
  3956.         p = namecopy;                       /* Was a service requested? */
  3957.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  3958.         if (*p == ':') {                    /* Have a colon */
  3959.             debug(F110,"netopen name has colon",namecopy,0);
  3960.             *p++ = '\0';                    /* Get service name or number */
  3961.         } else {
  3962.             strcpy(++p,"http");
  3963.         }
  3964.  
  3965.         service = ckgetservice(namecopy,p,namecopy,NAMECPYL);
  3966.         if (!service) {
  3967.             fprintf(stderr, "Can't find port for service %s\n", p);
  3968. #ifdef TGVORWIN
  3969.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  3970. #else
  3971.             debug(F101,"netopen can't get service for proxy","",errno);
  3972. #endif /* TGVORWIN */
  3973.             errno = 0;                  /* (rather than mislead) */
  3974.             return(-1);
  3975.         }
  3976.         ckstrncpy(p,ckuitoa(ntohs(service->s_port)),NAMECPYL-(p-namecopy));
  3977.  
  3978.     }
  3979. #endif /* NOHTTP */
  3980.  
  3981.     /* Set up socket structure and get host address */
  3982.  
  3983.     bzero((char *)&r_addr, sizeof(r_addr));
  3984.     debug(F100,"netopen bzero ok","",0);
  3985. /*
  3986.    NOTE: Originally the inet_addr() check was #ifdef NT, but is enabled for
  3987.    all as of 20 Sep 97, to allow people to "set host" to a specific numeric IP
  3988.    address without going through the multihomed host sequence and winding up
  3989.    at a different place than the one requested.
  3990. */
  3991. #ifdef INADDR_NONE
  3992.     debug(F101,"netopen INADDR_NONE defined","",INADDR_NONE);
  3993. #else /* INADDR_NONE */
  3994.     debug(F100,"netopen INADDR_NONE not defined","",0);
  3995. #endif /* INADDR_NONE */
  3996. #ifdef INADDRX
  3997.     debug(F100,"netopen INADDRX defined","",0);
  3998. #else /* INADDRX */
  3999.     debug(F100,"netopen INADDRX not defined","",0);
  4000. #endif /* INADDRX */
  4001.  
  4002. #ifndef NOMHHOST
  4003. #ifdef INADDRX
  4004.     iax = inet_addr(namecopy);
  4005.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  4006. #else /* INADDRX */
  4007. #ifdef INADDR_NONE
  4008.     iax.s_addr = inet_addr(namecopy);
  4009.     debug(F111,"netopen inet_addr",namecopy,iax.s_addr);
  4010. #else /* INADDR_NONE */
  4011. #ifndef datageneral
  4012.     iax = (unsigned int) inet_addr(namecopy);
  4013. #else
  4014.     iax = -1L;
  4015. #endif /* datageneral */
  4016.     debug(F111,"netopen inet_addr",namecopy,iax);
  4017. #endif /* INADDR_NONE */
  4018. #endif /* INADDRX */
  4019.  
  4020.     dns = 0;
  4021.     if (
  4022. #ifdef INADDR_NONE
  4023.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  4024. #else /* INADDR_NONE */
  4025.         iax < 0
  4026. #endif /* INADDR_NONE */
  4027.         ) {
  4028.         if (!quiet) {
  4029.             printf(" DNS Lookup... ");
  4030.             fflush(stdout);
  4031.         }
  4032.         if ((host = gethostbyname(namecopy)) != NULL) {
  4033.             debug(F100,"netopen gethostbyname != NULL","",0);
  4034.             host = ck_copyhostent(host);
  4035.             dns = 1;                    /* Remember we performed dns lookup */
  4036.             r_addr.sin_family = host->h_addrtype;
  4037.             if (host->h_name && host->h_name[0]
  4038. #ifndef NOHTTP
  4039.                  && (tcp_http_proxy == NULL)
  4040. #endif /* NOHTTP */
  4041.                  ) {                   /* Copying into our argument? */
  4042.                 ckstrncpy(name,host->h_name,80);  /* Bad Bad Bad */
  4043.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4044.                     strncat(name,":",80-strlen(name));
  4045.                     strncat(name,svcbuf,80-strlen(name));
  4046.                 }
  4047.             }
  4048.  
  4049. #ifdef HADDRLIST
  4050. #ifdef h_addr
  4051.             /* This is for trying multiple IP addresses - see <netdb.h> */
  4052.             if (!(host->h_addr_list))
  4053.               return(-1);
  4054.             bcopy(host->h_addr_list[0],
  4055.                   (caddr_t)&r_addr.sin_addr,
  4056.                   host->h_length
  4057.                   );
  4058. #else
  4059.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4060. #endif /* h_addr */
  4061. #else  /* HADDRLIST */
  4062.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  4063. #endif /* HADDRLIST */
  4064. #ifndef EXCELAN
  4065.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  4066. #endif /* EXCELAN */
  4067.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  4068.                   (caddr_t)&r_addr.sin_addr);
  4069.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  4070.                   r_addr.sin_addr.s_addr);
  4071.             debug(F111,"BCOPY","host->h_length",host->h_length);
  4072.         }
  4073.     }
  4074. #endif /* NOMHHOST */
  4075.  
  4076.     if (!dns) {
  4077. #ifdef INADDRX
  4078. /* inet_addr() is of type struct in_addr */
  4079.         struct in_addr ina;
  4080.         unsigned long uu;
  4081.         debug(F100,"netopen gethostbyname == NULL: INADDRX","",0);
  4082.         ina = inet_addr(namecopy);
  4083.         uu = *(unsigned int *)&ina;
  4084. #else /* Not INADDRX */
  4085. /* inet_addr() is unsigned long */
  4086.         unsigned long uu;
  4087.         debug(F100,"netopen gethostbyname == NULL: Not INADDRX","",0);
  4088.         uu = inet_addr(namecopy);
  4089. #endif /* INADDRX */
  4090.         debug(F101,"netopen uu","",uu);
  4091.         if (
  4092. #ifdef INADDR_NONE
  4093.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  4094. #else   /* INADDR_NONE */
  4095.             uu != ((unsigned long)-1)
  4096. #endif /* INADDR_NONE */
  4097.             ) {
  4098.             r_addr.sin_addr.s_addr = uu;
  4099.             r_addr.sin_family = AF_INET;
  4100.         } else {
  4101. #ifdef VMS
  4102.             fprintf(stdout, "\r\n");    /* complete any previous message */
  4103. #endif /* VMS */
  4104.             fprintf(stderr, "Can't get address for %s\n", namecopy);
  4105. #ifdef TGVORWIN
  4106.             debug(F101,"netopen can't get address","",socket_errno);
  4107. #else
  4108.             debug(F101,"netopen can't get address","",errno);
  4109. #endif /* TGVORWIN */
  4110.             errno = 0;                  /* Rather than mislead */
  4111.             return(-1);
  4112.         }
  4113.     }
  4114.  
  4115.     /* Get a file descriptor for the connection. */
  4116.  
  4117.     r_addr.sin_port = service->s_port;
  4118.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4119.     debug(F110,"netopen trying",ipaddr,0);
  4120.     if (!quiet && *ipaddr) {
  4121.         printf(" Trying %s... ", ipaddr);
  4122.         fflush(stdout);
  4123.     }
  4124.  
  4125.     /* Loop to try additional IP addresses, if any. */
  4126.  
  4127.     do {
  4128. #ifdef EXCELAN
  4129.         send_socket.sin_family = AF_INET;
  4130.         send_socket.sin_addr.s_addr = 0;
  4131.         send_socket.sin_port = 0;
  4132.         if ((ttyfd = socket(SOCK_STREAM, (struct sockproto *)0,
  4133.                             &send_socket, SO_REUSEADDR)) < 0)
  4134. #else  /* EXCELAN */
  4135. #ifdef NT
  4136. #ifdef COMMENT_X
  4137.        /*
  4138.          Must make sure that all sockets are opened in
  4139.          Non-overlapped mode since we use the standard
  4140.          C RTL functions to read and write data.
  4141.          But it doesn't seem to work as planned.
  4142.        */
  4143.           {
  4144.               int optionValue = SO_SYNCHRONOUS_NONALERT;
  4145.               if (setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
  4146.                              (char *) &optionValue, sizeof(optionValue))
  4147.                   != NO_ERROR)
  4148.                 return(-1);
  4149.           }
  4150. #endif /* COMMENT */
  4151. #endif /* NT */
  4152.  
  4153.         if ((ttyfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  4154. #endif /* EXCELAN */
  4155.             {
  4156. #ifdef EXCELAN
  4157.                 experror("TCP socket error");
  4158. #else
  4159. #ifdef VMS
  4160.                 fprintf(stdout, "\r\n"); /* complete any previous stdout */
  4161. #endif /* VMS */
  4162. #ifdef TGVORWIN
  4163. #ifdef OLD_TWG
  4164.                 errno = socket_errno;
  4165. #endif /* OLD_TWG */
  4166.                 socket_perror("TCP socket error");
  4167.                 debug(F101,"netopen socket error","",socket_errno);
  4168. #else
  4169.                 perror("TCP socket error");
  4170.                 debug(F101,"netopen socket error","",errno);
  4171. #endif /* TGVORWIN */
  4172. #endif /* EXCELAN */
  4173.                 return (-1);
  4174.             }
  4175.         errno = 0;
  4176.  
  4177. #ifdef RLOGCODE
  4178.        /* Not part of the RLOGIN RFC, but the BSD implementation     */
  4179.        /* requires that the client port be a priviliged port (<1024) */
  4180.        /* on a Unix system this would require SuperUser permissions  */
  4181.        /* thereby saying that the root of the Unix system has given  */
  4182.        /* permission for this connection to be created               */
  4183.        if (service->s_port == htons((unsigned short)RLOGIN_PORT)) {
  4184.            static unsigned short lport = 1024;  /* max reserved port */
  4185. #ifdef OS2
  4186.            int s_errno;
  4187. #endif /* OS2 */
  4188.  
  4189.            lport--;                     /* Make sure we do not reuse a port */
  4190.            if (lport == 512)
  4191.              lport = 1023;
  4192.  
  4193.            sin.sin_family = AF_INET;
  4194.            if (tcp_address) {
  4195. #ifdef INADDRX
  4196.                inaddrx = inet_addr(tcp_address);
  4197.                sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4198. #else
  4199.                sin.sin_addr.s_addr = inet_addr(tcp_address);
  4200. #endif /* INADDRX */
  4201.            } else
  4202.              sin.sin_addr.s_addr = INADDR_ANY;
  4203.            while (1) {
  4204.                sin.sin_port = htons(lport);
  4205.                if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
  4206.                  break;
  4207. #ifdef OS2
  4208.                s_errno = socket_errno;
  4209.                if (s_errno && /* OS2 bind fails with 0, if already in use */
  4210. #ifdef NT
  4211.                    s_errno != WSAEADDRINUSE
  4212. #else
  4213.                    s_errno != SOCEADDRINUSE &&
  4214.                    s_errno != (SOCEADDRINUSE - SOCBASEERR)
  4215. #endif /* NT */
  4216.                    )
  4217. #else /* OS2 */
  4218. #ifdef TGVORWIN
  4219.                  if (socket_errno != EADDRINUSE)
  4220. #else
  4221.                  if (errno != EADDRINUSE)
  4222. #endif /* TGVORWIN */
  4223. #endif /* OS2 */
  4224.                    {
  4225. #ifdef COMMENT
  4226.                        printf("\nBind failed with errno %d  for port %d.\n",
  4227. #ifdef OS2
  4228.                               s_errno
  4229. #else
  4230. #ifdef TGVORWIN
  4231.                               socket_errno
  4232. #else
  4233.                               errno
  4234. #endif /* TGVORWIN */
  4235. #endif /* OS2 */
  4236.                               , lport
  4237.                               );
  4238. #ifdef OS2
  4239.                        debug(F101,"rlogin bind failed","",s_errno);
  4240. #else
  4241. #ifdef TGVORWIN
  4242.                        debug(F101,"rlogin bind failed","",socket_errno);
  4243. #ifdef OLD_TWG
  4244.                        errno = socket_errno;
  4245. #endif /* OLD_TWG */
  4246.                        socket_perror("rlogin bind");
  4247. #else
  4248.                        debug(F101,"rlogin bind failed","",errno);
  4249.                        perror("rlogin bind");
  4250. #endif /* TGVORWIN */
  4251. #endif /* OS2 */
  4252. #else  /* COMMENT */
  4253. #ifdef OS2
  4254.                        debug(F101,"rlogin bind s_errno","",s_errno);
  4255.                        perror("rlogin bind");
  4256. #else
  4257. #ifdef VMS
  4258.                        printf("\r\n");  /* complete any previous message */
  4259. #endif /* VMS */
  4260. #ifdef TGVORWIN
  4261.                        debug(F101,"rlogin bind socket_errno","",socket_errno);
  4262. #ifdef OLD_TWG
  4263.                        errno = socket_errno;
  4264. #endif /* OLD_TWG */
  4265.                        socket_perror("rlogin bind");
  4266. #else
  4267.                        debug(F101,"rlogin bind errno","",errno);
  4268.                        perror("rlogin bind");
  4269. #endif /* TGVORWIN */
  4270. #endif /* OS2 */
  4271.                        debug(F101,"rlogin local port","",lport);
  4272. #endif /* COMMENT */
  4273.                        netclos();
  4274.                        return -1;
  4275.                    }
  4276.                lport--;
  4277.                if (lport == 512 /* lowest reserved port to use */ ) {
  4278.                    printf("\nNo reserved ports available.\n");
  4279.                    netclos();
  4280.                    return -1;
  4281.                }
  4282.            }
  4283.            debug(F101,"rlogin lport","",lport);
  4284.            ttnproto = NP_RLOGIN;
  4285.        } else
  4286. #endif /* RLOGCODE  */
  4287.  
  4288.        /* If a specific TCP address on the local host is desired we */
  4289.        /* must bind it to the socket.                               */
  4290. #ifndef datageneral
  4291.          if (tcp_address) {
  4292.              int s_errno;
  4293.  
  4294.              debug(F110,"netopen binding socket to",tcp_address,0);
  4295.              bzero((char *)&sin,sizeof(sin));
  4296.              sin.sin_family = AF_INET;
  4297. #ifdef INADDRX
  4298.              inaddrx = inet_addr(tcp_address);
  4299.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  4300. #else
  4301.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  4302. #endif /* INADDRX */
  4303.              sin.sin_port = 0;
  4304.              if (bind(ttyfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  4305.                  s_errno = socket_errno; /* Save error code */
  4306. #ifdef TCPIPLIB
  4307.                  socket_close(ttyfd);
  4308. #else /* TCPIPLIB */
  4309.                  close(ttyfd);
  4310. #endif /* TCPIPLIB */
  4311.                  ttyfd = -1;
  4312.                  wasclosed = 1;
  4313.                  errno = s_errno;       /* and report this error */
  4314.                  debug(F101,"netopen bind errno","",errno);
  4315.                  return(-1);
  4316.              }
  4317.          }
  4318. #endif /* datageneral */
  4319.  
  4320. /* Now connect to the socket on the other end. */
  4321.  
  4322. #ifdef EXCELAN
  4323.         if (connect(ttyfd, &r_addr) < 0)
  4324. #else
  4325. #ifdef NT
  4326.           WSASafeToCancel = 1;
  4327. #endif /* NT */
  4328.         if (connect(ttyfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  4329. #endif /* EXCELAN */
  4330.           {
  4331. #ifdef NT
  4332.               WSASafeToCancel = 0;
  4333. #endif /* NT */
  4334. #ifdef OS2
  4335.               i = socket_errno;
  4336. #else /* OS2 */
  4337. #ifdef TGVORWIN
  4338.               i = socket_errno;
  4339. #else
  4340.               i = errno;                /* Save error code */
  4341. #endif /* TGVORWIN */
  4342. #endif /* OS2 */
  4343. #ifdef RLOGCODE
  4344.               if (
  4345. #ifdef OS2
  4346.                  i && /* OS2 bind fails with 0, if already in use */
  4347. #ifdef NT
  4348.                  i == WSAEADDRINUSE
  4349. #else
  4350.                  (i == SOCEADDRINUSE ||
  4351.                  i == (SOCEADDRINUSE - SOCBASEERR))
  4352. #endif /* NT */
  4353. #else /* OS2 */
  4354. #ifdef TGVORWIN
  4355.                   socket_errno == EADDRINUSE
  4356. #else
  4357.                   errno == EADDRINUSE
  4358. #endif /* TGVORWIN */
  4359. #endif /* OS2 */
  4360.                   && ttnproto == NP_RLOGIN) {
  4361. #ifdef TCPIPLIB
  4362.                    socket_close(ttyfd); /* Close it. */
  4363. #else
  4364.                    close(ttyfd);
  4365. #endif /* TCPIPLIB */
  4366.                    continue;            /* Try a different lport */
  4367.                }
  4368. #endif /* RLOGCODE */
  4369. #ifdef HADDRLIST
  4370. #ifdef h_addr
  4371.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  4372.                   perror("");
  4373.                   host->h_addr_list++;
  4374.                   bcopy(host->h_addr_list[0],
  4375.                         (caddr_t)&r_addr.sin_addr,
  4376.                         host->h_length);
  4377.  
  4378.                   ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4379.                   debug(F110,"netopen h_addr_list",ipaddr,0);
  4380.                   if (!quiet && *ipaddr) {
  4381.                       printf(" Trying %s... ", ipaddr);
  4382.                       fflush(stdout);
  4383.                   }
  4384. #ifdef TCPIPLIB
  4385.                   socket_close(ttyfd); /* Close it. */
  4386. #else
  4387.                   close(ttyfd);
  4388. #endif /* TCPIPLIB */
  4389.                   continue;
  4390.               }
  4391. #endif /* h_addr */
  4392. #endif  /* HADDRLIST */
  4393.               netclos();
  4394.               ttyfd = -1;
  4395.               wasclosed = 1;
  4396.               ttnproto = NP_NONE;
  4397.               errno = i;                /* And report this error */
  4398. #ifdef EXCELAN
  4399.               if (errno) experror("netopen connect");
  4400. #else
  4401. #ifdef TGVORWIN
  4402.               debug(F101,"netopen connect error","",socket_errno);
  4403.               /* if (errno) socket_perror("netopen connect"); */
  4404. #ifdef OLD_TWG
  4405.               errno = socket_errno;
  4406. #endif /* OLD_TWG */
  4407.               if (!quiet)
  4408.                 socket_perror("netopen connect");
  4409. #else /* TGVORWIN */
  4410.               debug(F101,"netopen connect errno","",errno);
  4411. #ifdef VMS
  4412.               if (!quiet)
  4413.                 perror("\r\nFailed");
  4414. #else
  4415.               if (!quiet)
  4416.                 perror("Failed");
  4417. #endif /* VMS */
  4418. #ifdef DEC_TCPIP
  4419.               if (!quiet)
  4420.                 perror("netopen connect");
  4421. #endif /* DEC_TCPIP */
  4422. #ifdef CMU_TCPIP
  4423.               if (!quiet)
  4424.                 perror("netopen connect");
  4425. #endif /* CMU_TCPIP */
  4426. #endif /* TGVORWIN */
  4427. #endif /* EXCELAN */
  4428.               return(-1);
  4429.           }
  4430. #ifdef NT
  4431.         WSASafeToCancel = 0;
  4432. #endif /* NT */
  4433.         isconnect = 1;
  4434.     } while (!isconnect);
  4435.  
  4436. #ifdef NON_BLOCK_IO
  4437.     on = 1;
  4438.     x = socket_ioctl(ttyfd,FIONBIO,&on);
  4439.     debug(F101,"netopen FIONBIO","",x);
  4440. #endif /* NON_BLOCK_IO */
  4441.  
  4442. #ifdef NT_TCP_OVERLAPPED
  4443.     OverlappedWriteInit();
  4444.     OverlappedReadInit();
  4445. #endif /* NT_TCP_OVERLAPPED */
  4446.  
  4447.     ttnet = nett;                       /* TCP/IP (sockets) network */
  4448.  
  4449. #ifndef NOHTTP
  4450.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  4451.     /* need to attempt to connect through the proxy to the actual host */
  4452.     /* If that is successful, we have to pretend that we made a direct */
  4453.     /* connection to the actual host.                                  */
  4454.  
  4455.     if ( tcp_http_proxy ) {
  4456. #ifdef OS2
  4457.         char * agent = "Kermit 95";             /* Default user agent */
  4458. #else
  4459.         char * agent = "C-Kermit";
  4460. #endif /* OS2 */
  4461.  
  4462.         if (http_connect(ttyfd,agent,NULL,
  4463.                          tcp_http_proxy_user,
  4464.                          tcp_http_proxy_pwd,
  4465.                          0,
  4466.                          proxycopy
  4467.                          ) < 0) {
  4468.             netclos();
  4469.             return(-1);
  4470.         }
  4471.  
  4472.         ckstrncpy(namecopy,proxycopy,NAMECPYL);
  4473.         p = namecopy;                       /* Was a service requested? */
  4474.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  4475.         *p = '\0';
  4476.     }
  4477. #endif /* NOHTTP */
  4478.  
  4479.     /* Jeff - Does this next block of code that set's the protocol */
  4480.     /* need to be here anymore?  5/10/2000                         */
  4481.  
  4482.     /* There are certain magic port numbers that when used require */
  4483.     /* the use of specific protocols.  Check this now before we    */
  4484.     /* set the SO_OOBINLINE state or we might get it wrong.        */
  4485.     x = ntohs((unsigned short)service->s_port);
  4486.     svcnum = x;
  4487.     /* See if the service is TELNET. */
  4488.     if (x == TELNET_PORT) {
  4489.         /* Yes, so if raw port not requested */
  4490.         if (ttnproto != NP_TCPRAW && ttnproto != NP_NONE)
  4491.           ttnproto = NP_TELNET;         /* Select TELNET protocol. */
  4492.     }
  4493. #ifdef RLOGCODE
  4494.     else if (x == RLOGIN_PORT) {
  4495.         ttnproto = NP_RLOGIN;
  4496.     }
  4497. #ifdef CK_KERBEROS
  4498.     /* There is no good way to do this.  If the user didn't tell    */
  4499.     /* which one to use up front.  We may guess wrong if the user   */
  4500.     /* has both Kerberos versions installed and valid TGTs for each */
  4501.     else if (x == KLOGIN_PORT &&
  4502.              ttnproto != NP_K4LOGIN &&
  4503.              ttnproto != NP_K5LOGIN) {
  4504.         if (ck_krb5_is_installed() &&
  4505.             ck_krb5_is_tgt_valid())
  4506.           ttnproto = NP_K5LOGIN;
  4507.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4508.           ttnproto = NP_K4LOGIN;
  4509.         else
  4510.           ttnproto = NP_K4LOGIN;
  4511.     } else if (x == EKLOGIN_PORT &&
  4512.                ttnproto != NP_EK4LOGIN &&
  4513.                ttnproto != NP_EK5LOGIN) {
  4514.         if (ck_krb5_is_installed() && ck_krb5_is_tgt_valid())
  4515.           ttnproto = NP_EK5LOGIN;
  4516.         else if (ck_krb4_is_installed() && ck_krb4_is_tgt_valid())
  4517.           ttnproto = NP_EK4LOGIN;
  4518.         else
  4519.           ttnproto = NP_EK4LOGIN;
  4520.     }
  4521. #endif /* CK_KERBEROS */
  4522. #endif /* RLOGCODE */
  4523. #ifdef IKS_OPTION
  4524.     else if (x == KERMIT_PORT) {        /* IKS uses Telnet protocol */
  4525.         if (ttnproto == NP_NONE)
  4526.           ttnproto = NP_KERMIT;
  4527.     }
  4528. #endif /* IKS_OPTION */
  4529.  
  4530. #ifdef SO_OOBINLINE
  4531. /*
  4532.   The symbol SO_OOBINLINE is not known to Ultrix 2.0.
  4533.   It means "leave out of band data inline".  The normal value is 0x0100,
  4534.   but don't try this on systems where the symbol is undefined.
  4535. */
  4536. /*
  4537.   Note from Jeff Altman: 12/13/95
  4538.   In implementing rlogin protocol I have come to the conclusion that it is
  4539.   a really bad idea to read out-of-band data inline.
  4540.   At least Windows and OS/2 does not handle this well.
  4541.   And if you need to know that data is out-of-band, then it becomes
  4542.   absolutely pointless.
  4543.  
  4544.   Therefore, at least on OS2 and Windows (NT) I have changed the value of
  4545.   on to 0, so that out-of-band data stays out-of-band.
  4546.  
  4547.   12/18/95
  4548.   Actually, OOB data should be read inline when possible.  Especially with
  4549.   protocols that don't care about the Urgent flag.  This is true with Telnet.
  4550.   With Rlogin, you need to be able to catch OOB data.  However, the best
  4551.   way to do this is to set a signal handler on SIGURG.  This isn't possible
  4552.   on OS/2 and Windows.  But it is in UNIX.  We will also need OOB data for
  4553.   FTP so better create a general mechanism.
  4554.  
  4555.   The reason for making OOB data be inline is that the standard ttinc/ttoc
  4556.   calls can be used for reading that data on UNIX systems.  If we didn't
  4557.   have the OOBINLINE option set then we would have to use recv(,MSG_OOB)
  4558.   to read it.
  4559. */
  4560. #ifdef RLOGCODE
  4561. #ifdef TCPIPLIB
  4562.     if (ttnproto == NP_RLOGIN
  4563. #ifdef CK_KERBEROS
  4564.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4565.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4566. #endif /* CK_KERBEROS */
  4567.       )
  4568.       on = 0;
  4569. #else /* TCPIPLIB */
  4570.     if (ttnproto == NP_RLOGIN
  4571. #ifdef CK_KERBEROS
  4572.          || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4573.          || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4574. #endif /* CK_KERBEROS */
  4575.          ) {
  4576.         debug(F100,"Installing rlogoobh on SIGURG","",0);
  4577.         signal(SIGURG, rlogoobh);
  4578.         on = 0;
  4579.     } else {
  4580.         debug(F100,"Ignoring SIGURG","",0);
  4581.         signal(SIGURG, SIG_DFL);
  4582.     }
  4583. #endif /* TCPIPLIB */
  4584. #endif /* RLOGCODE */
  4585.  
  4586. #ifdef datageneral
  4587.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4588. #else
  4589. #ifdef BSD43
  4590.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4591. #else
  4592. #ifdef OSF1
  4593.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4594. #else
  4595. #ifdef POSIX
  4596.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4597. #else
  4598. #ifdef MOTSV88R4
  4599.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4600. #else
  4601. #ifdef SOLARIS
  4602. /*
  4603.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  4604.   compiling and working fine on all the others, so best not to change it.
  4605. */
  4606.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4607. #else
  4608. #ifdef OSK
  4609.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4610. #else
  4611. #ifdef OS2
  4612.     {
  4613.         int rc;
  4614.         rc = setsockopt(ttyfd,
  4615.                         SOL_SOCKET,
  4616.                         SO_OOBINLINE,
  4617.                         (char *) &on,
  4618.                         sizeof on
  4619.                         );
  4620.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  4621.     }
  4622. #else
  4623. #ifdef VMS /* or, at least, VMS with gcc */
  4624.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4625. #else
  4626. #ifdef CLIX
  4627.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  4628. #else
  4629.     setsockopt(ttyfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  4630. #endif /* CLIX */
  4631. #endif /* VMS */
  4632. #endif /* OS2 */
  4633. #endif /* OSK */
  4634. #endif /* SOLARIS */
  4635. #endif /* MOTSV88R4 */
  4636. #endif /* POSIX */
  4637. #endif /* BSD43 */
  4638. #endif /* OSF1 */
  4639. #endif /* datageneral */
  4640. #endif /* SO_OOBINLINE */
  4641.  
  4642. #ifndef NOTCPOPTS
  4643. #ifndef datageneral
  4644. #ifdef SOL_SOCKET
  4645. #ifdef TCP_NODELAY
  4646.     no_delay(ttyfd,tcp_nodelay);
  4647. #endif /* TCP_NODELAY */
  4648. #ifdef SO_KEEPALIVE
  4649.     keepalive(ttyfd,tcp_keepalive);
  4650. #endif /* SO_KEEPALIVE */
  4651. #ifdef SO_LINGER
  4652.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  4653. #endif /* SO_LINGER */
  4654. #ifdef SO_SNDBUF
  4655.     sendbuf(ttyfd,tcp_sendbuf);
  4656. #endif /* SO_SNDBUF */
  4657. #ifdef SO_RCVBUF
  4658.     recvbuf(ttyfd,tcp_recvbuf);
  4659. #endif /* SO_RCVBUF */
  4660. #endif /* SOL_SOCKET */
  4661. #endif /* datageneral */
  4662. #endif /* NOTCPOPTS */
  4663.  
  4664. #ifndef datageneral
  4665.     /* Find out our own IP address. */
  4666.     /* We need the l_addr structure for [E]KLOGIN. */
  4667.     l_slen = sizeof(l_addr);
  4668.     bzero((char *)&l_addr, l_slen);
  4669. #ifndef EXCELAN
  4670.     if (!getsockname(ttyfd, (struct sockaddr *)&l_addr, &l_slen)) {
  4671.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  4672.         ckstrncpy(myipaddr, s, 20);
  4673.         debug(F110,"getsockname",myipaddr,0);
  4674.     }
  4675. #endif /* EXCELAN */
  4676. #endif /* datageneral */
  4677.  
  4678. /*
  4679.   This is really only needed for Kerberos IV but is useful information in any
  4680.   case.  If we connect to a name that is really a pool, we need to get the
  4681.   name of the machine we are actually connecting to for K4 to authenticate
  4682.   properly.  This way we also update the names properly.
  4683.  
  4684.   However, it is a security hole when used with insecure DNS.
  4685.  
  4686.   Note: This does not work on Windows 95 or Windows NT 3.5x.  This is because
  4687.   of the Microsoft implementation of gethostbyaddr() in both Winsock 1.1
  4688.   and Winsock 2.0 on those platforms.  Their algorithm is:
  4689.  
  4690.   1. Check the HOSTENT cache.
  4691.   2. Check the HOSTS file at %SystemRoot%\System32\DRIVERS\ETC.
  4692.   3. Do a DNS query if the DNS server is configured for name resolution.
  4693.   4. Do an additional NetBIOS remote adapter status to an IP address for its
  4694.      NetBIOS name table. This step is specific only to the Windows NT version
  4695.      3.51 implementation.
  4696.  
  4697.   The problem is the use of the HOSTENT cache.  It means that gethostbyaddr()
  4698.   can not be used to resolve the real name of machine if it was originally
  4699.   accessed by an alias used to represent a cluster.
  4700. */
  4701.      if ((tcp_rdns && dns || tcp_rdns == SET_ON
  4702. #ifdef CK_KERBEROS
  4703.          || tcp_rdns == SET_AUTO &&
  4704.           (ck_krb5_is_installed() || ck_krb4_is_installed())
  4705. #endif /* CK_KERBEROS */
  4706.          )
  4707. #ifndef NOHTTP
  4708.           && (tcp_http_proxy == NULL)
  4709. #endif /* NOHTTP */
  4710. #ifdef CK_SSL
  4711.           && !(ssl_only_flag || tls_only_flag)
  4712. #endif /* CK_SSL */
  4713.          ) {
  4714. #ifdef NT
  4715.         if (isWin95())
  4716.           sleep(1);
  4717. #endif /* NT */
  4718.         if (!quiet) {
  4719.             printf(" Reverse DNS Lookup... ");
  4720.             fflush(stdout);
  4721.         }
  4722.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  4723.             char * s;
  4724.             host = ck_copyhostent(host);
  4725.             debug(F100,"netopen gethostbyname != NULL","",0);
  4726.             if (!quiet) {
  4727.                 printf("(OK)\n");
  4728.                 fflush(stdout);
  4729.             }
  4730.             s = host->h_name;
  4731.             if (!s) {                   /* This can happen... */
  4732.                 debug(F100,"netopen host->h_name is NULL","",0);
  4733.                 s = "";
  4734.             }
  4735.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  4736.             /* The compiler says "Integral value implicitly converted to */
  4737.             /* pointer in assignment."  The prototype is right there */
  4738.             /* in <arpa/inet.h> so what's the problem? */
  4739.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  4740.             if (!*s) {                  /* No name so substitute the address */
  4741.                 debug(F100,"netopen host->h_name is empty","",0);
  4742.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  4743.                 if (!s)                 /* Trust No 1 */
  4744.                   s = "";
  4745.                 if (*s) {               /* If it worked, use this string */
  4746.                     ckstrncpy(ipaddr,s,20);
  4747.                 }
  4748.                 s = ipaddr;             /* Otherwise stick with the IP */
  4749.                 if (!*s)                /* or failing that */
  4750.                   s = namecopy;         /* the name we were called with. */
  4751.             }
  4752.             if (*s) {                   /* Copying into our argument? */
  4753.                 ckstrncpy(name,s,80);   /* Bad Bad Bad */
  4754.                 if ( (80-strlen(name)) > (strlen(svcbuf)+1) ) {
  4755.                     strncat(name,":",80-strlen(name));
  4756.                     strncat(name,svcbuf,80-strlen(name));
  4757.                 }
  4758.             }
  4759.             if (!quiet && *s
  4760. #ifndef NOICP
  4761.                 && !doconx
  4762. #endif /* NOICP */
  4763.                 ) {
  4764.                 printf(" %s connected on port %s\n",s,p);
  4765. #ifdef BETADEBUG
  4766.                 /* This is simply for testing the DNS entries */
  4767.                 if (host->h_aliases) {
  4768.                     char ** a = host->h_aliases;
  4769.                     while (*a) {
  4770.                         printf(" alias => %s\n",*a);
  4771.                         a++;
  4772.                     }
  4773.                 }
  4774. #endif /* BETADEBUG */
  4775.             }
  4776.         } else {
  4777.             if (!quiet) printf("Failed.\n");
  4778.         }
  4779.     } else if (!quiet) printf("(OK)\n");
  4780.     if (!quiet) fflush(stdout);
  4781.  
  4782.     /* This should already have been done but just in case */
  4783.     ckstrncpy(ipaddr,(char *)inet_ntoa(r_addr.sin_addr),20);
  4784.  
  4785. #ifdef CK_SECURITY
  4786.  
  4787.     /* Before Initialization Telnet/Rlogin Negotiations Init Kerberos */
  4788. #ifndef NOHTTP
  4789.     if (tcp_http_proxy) {
  4790.         for (i=strlen(proxycopy); i >= 0 ; i--)
  4791.             if ( proxycopy[i] == ':' )
  4792.                 proxycopy[i] = '\0';
  4793.     }
  4794. #endif /* NOHTTP */
  4795.     ck_auth_init(
  4796. #ifndef NOHTTP
  4797.                  tcp_http_proxy ? proxycopy :
  4798. #endif /* NOHTTP */
  4799.                  (host && host->h_name && host->h_name[0]) ?
  4800.                  (char *)host->h_name : (namecopy[0] ? namecopy : ipaddr),
  4801.                  ipaddr,
  4802.                  uidbuf,
  4803.                  ttyfd
  4804.                  );
  4805. #endif /* CK_SECURITY */
  4806. #ifdef CK_SSL
  4807.     if (ck_ssleay_is_installed()) {
  4808.         if (!ssl_tn_init(SSL_CLIENT)) {
  4809.             debug(F100,"netopen ssl_tn_init() failed","",0);
  4810.             if (bio_err!=NULL) {
  4811.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  4812.                 ERR_print_errors(bio_err);
  4813.             } else {
  4814.                 fflush(stderr);
  4815.                 fprintf(stderr,"ssl_tn_init() failed\n");
  4816.                 ERR_print_errors_fp(stderr);
  4817.             }
  4818.             if (tls_only_flag || ssl_only_flag) {
  4819.                 debug(F100,"netopen ssl/tls required","",0);
  4820.                 netclos();
  4821.                 return(-1);
  4822.             }
  4823.  
  4824.             /* we will continue to accept the connection   */
  4825.             /* without SSL or TLS support unless required. */
  4826.             if ( TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4827.                 TELOPT_DEF_S_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4828.             if ( TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4829.                 TELOPT_DEF_S_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4830.             if ( TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4831.                 TELOPT_DEF_C_ME_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4832.             if ( TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) != TN_NG_MU )
  4833.                 TELOPT_DEF_C_U_MODE(TELOPT_START_TLS) = TN_NG_RF;
  4834.         } else if ( ck_ssl_outgoing(ttyfd) < 0 ) {
  4835.             debug(F100,"ck_ssl_outgoing() failed","",0);
  4836.             netclos();
  4837.             return(-1);
  4838.         }
  4839.     }
  4840. #endif /* CK_SSL */
  4841.  
  4842. #ifdef RLOGCODE
  4843.     if (ttnproto == NP_RLOGIN
  4844. #ifdef CK_KERBEROS
  4845.         || ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN
  4846.         || ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN
  4847. #endif /* CK_KERBEROS */
  4848.         ) {                             /* Similar deal for rlogin */
  4849.         if (rlog_ini(((host && host->h_name && host->h_name[0]) ?
  4850.                       (CHAR *)host->h_name : (CHAR *)ipaddr),
  4851.                      service->s_port,
  4852.                      &l_addr,&r_addr
  4853.                      ) < 0) {
  4854.             debug(F100,"rlogin initialization failed","",0);
  4855.             netclos();
  4856.             return(-1);
  4857.         }
  4858.     } else
  4859. #endif /* RLOGCODE */
  4860.     if (tn_ini() < 0) {                 /* Start Telnet negotiations. */
  4861.         netclos();
  4862.         return(-1);                     /* Gone, so open failed.  */
  4863.     }
  4864.     if (ttchk() < 0) {
  4865.         netclos();
  4866.         return(-1);
  4867.     }
  4868. #ifdef CK_KERBEROS
  4869. #ifdef KRB5_U2U
  4870.    if ( ttnproto == NP_K5U2U ) {
  4871.        if (k5_user_to_user_client_auth()) {
  4872.            netclos();
  4873.            return(-1);
  4874.        }
  4875.    }
  4876. #endif /* KRB5_U2U */
  4877. #endif /* CK_KERBEROS */
  4878.  
  4879.     debug(F101,"netopen service","",svcnum);
  4880.     debug(F110,"netopen name",name,0);
  4881.  
  4882.     if (lcl) if (*lcl < 0)              /* Local mode. */
  4883.       *lcl = 1;
  4884. #endif /* TCPSOCKET */
  4885.     return(0);                          /* Done. */
  4886. }
  4887.  
  4888. /*  N E T C L O S  --  Close current network connection.  */
  4889.  
  4890. #ifndef NOLOCAL
  4891. _PROTOTYP(VOID slrestor,(VOID));
  4892. #ifdef CK_SSL
  4893. int tls_norestore = 0;
  4894. #endif /* CK_SSL */
  4895. #endif /* NOLOCAL */
  4896.  
  4897. int
  4898. netclos() {
  4899.     static int close_in_progress = 0;
  4900.     int x = 0;
  4901.     debug(F101,"netclos","",ttyfd);
  4902.  
  4903. #ifdef NETLEBUF
  4904.     if (!tt_push_inited)
  4905.       le_init();
  4906. #endif /* NETLEBUF */
  4907.  
  4908.     if (ttyfd == -1)                    /* Was open? */
  4909.       return(0);                        /* Wasn't. */
  4910.  
  4911.     if (close_in_progress)
  4912.       return(0);
  4913.     close_in_progress = 1;              /* Remember */
  4914.  
  4915. #ifndef NOLOCAL
  4916.     /* This function call should not be here since this is a direct call */
  4917.     /* from an I/O routine to a user interface level function.  However, */
  4918.     /* the reality is that we do not have pure interfaces.  If we ever   */
  4919.     /* decide to clean this up the UI level should assign this function  */
  4920.     /* via a pointer assignment.  - Jeff 9/10/1999                       */
  4921. #ifdef CK_SSL
  4922.     if (!tls_norestore)
  4923. #endif /* CK_SSL */
  4924.       slrestor();
  4925. #endif /* NOLOCAL */
  4926. #ifndef OS2
  4927.     if (ttyfd > -1)                     /* Was. */
  4928. #endif /* OS2 */
  4929.       {
  4930. #ifdef TNCODE
  4931.           if (ttnproto == NP_TELNET) {
  4932.             tn_push();                    /* Place any waiting data into input*/
  4933.             tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  4934.             TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  4935.           }
  4936. #endif /* TNCODE */
  4937. #ifdef CK_SSL
  4938.           if (ssl_active_flag) {
  4939.               if (ssl_debug_flag)
  4940.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4941.               SSL_shutdown(ssl_con);
  4942.               ssl_active_flag = 0;
  4943.           }
  4944.           if (tls_active_flag) {
  4945.               if (ssl_debug_flag)
  4946.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  4947.               SSL_shutdown(tls_con);
  4948.               tls_active_flag = 0;
  4949.           }
  4950. #endif /* CK_SSL */
  4951. #ifdef VMS
  4952.           ck_cancio();                  /* Cancel any outstanding reads. */
  4953. #endif /* VMS */
  4954. #ifdef TCPIPLIB
  4955.           x = socket_close(ttyfd);      /* Close it. */
  4956. #else
  4957. #ifndef OS2
  4958. #ifdef IBMX25
  4959.         if (ttnet == NET_IX25) {
  4960.             /* riehm: should send a disc_req - but only if link is still OK */
  4961.             x = x25clear();
  4962.             close(ttyfd);
  4963.             if (x25serverfd) {
  4964.                   /* we were the passive client of a server, now we
  4965.                    * go back to being the normal client.
  4966.                    * I hope that kermit can cope with the logic that
  4967.                    * there can still be a connection after netclos
  4968.                    * has been called.
  4969.                    */
  4970.                   ttyfd = x25serverfd;
  4971.                   x25serverfd = 0;
  4972.                   /*
  4973.                    * need to close the server connection too - because
  4974.                    * all file descriptors connected to the NPI have the
  4975.                    * same status.
  4976.                    *
  4977.                    * The problem is that any waiting connections get
  4978.                    * lost, the client doesn't realise, and hangs.
  4979.                    */
  4980.                   netclos();
  4981.               }
  4982.             x25_state = X25_CLOSED;     /* riehm: dead code? */
  4983.         } else
  4984. #endif /* IBMX25 */
  4985.           x = close(ttyfd);
  4986. #endif /* OS2 */
  4987. #endif /* TCPIPLIB */
  4988.       }
  4989.     ttyfd = -1;                         /* Mark it as closed. */
  4990.     wasclosed = 1;
  4991. #ifdef TNCODE
  4992. #ifdef CK_FORWARD_X
  4993.     fwdx_close_all();                   /* Shut down any Forward X sockets */
  4994. #endif /* CK_FORWARD_X */
  4995.     tn_reset();                   /* The Reset Telnet Option table.  */
  4996.     debug(F100,"netclose setting tn_init = 0","",0);
  4997.     tn_init = 0;                        /* Remember about telnet protocol... */
  4998.     sstelnet = 0;                       /* Client-side Telnet */
  4999. #endif /* TNCODE */
  5000.     *ipaddr = '\0';                     /* Zero the IP address string */
  5001.     tcp_incoming = 0;                   /* No longer incoming */
  5002.     /* Don't reset ttnproto so that we can remember which protocol is in use */
  5003.  
  5004. #ifdef TCPIPLIB
  5005. /*
  5006.   Empty the internal buffers so they won't be used as invalid input on
  5007.   the next connect attempt (rlogin).
  5008. */
  5009.     ttibp = 0;
  5010.     ttibn = 0;
  5011. #endif /* TCPIPLIB */
  5012. #ifdef CK_KERBEROS
  5013.     /* If we are automatically destroying Kerberos credentials on Close */
  5014.     /* do it now. */
  5015. #ifdef KRB4
  5016.     if (krb4_autodel == KRB_DEL_CL) {
  5017.         extern struct krb_op_data krb_op;
  5018.         krb_op.version = 4;
  5019.         krb_op.cache = NULL;
  5020.         ck_krb4_destroy(&krb_op);
  5021.     }
  5022. #endif /* KRB4 */
  5023. #ifdef KRB5
  5024.     if (krb5_autodel == KRB_DEL_CL) {
  5025.         extern struct krb_op_data krb_op;
  5026.         extern char * krb5_d_cc;
  5027.         krb_op.version = 5;
  5028.         krb_op.cache = krb5_d_cc;
  5029.         ck_krb5_destroy(&krb_op);
  5030.     }
  5031. #endif /* KRB5 */
  5032. #endif /* CK_KERBEROS */
  5033.     close_in_progress = 0;              /* Remember we are done. */
  5034.     return(x);
  5035. }
  5036.  
  5037. #ifdef OS2
  5038. int
  5039. os2socketerror( int s_errno ) {
  5040. #ifdef OS2ONLY
  5041.     if (s_errno > 0 && s_errno <= SOCBASEERR) {
  5042.         /* in OS/2, there is a problem with threading in that
  5043.          * the value of errno is not thread safe.  It can be
  5044.          * set to a value from a previous library call and if
  5045.          * it was not cleared it will appear here.  Only treat
  5046.          * valid socket error codes as errors in this function.
  5047.          */
  5048.         debug(F100,"os2socketerror errno.h","",0);
  5049.         socket_errno = 0;
  5050.         return(0);
  5051.     }
  5052. #endif /* OS2ONLY */
  5053.  
  5054.     switch (s_errno) {
  5055.       case 0:                           /* NO ERROR */
  5056.         debug(F100,"os2socketerror NOERROR","",0);
  5057.         return(0);
  5058. #ifdef NT
  5059.       case WSAECONNRESET:
  5060. #else /* NT */
  5061.       case SOCECONNRESET:
  5062.       case SOCECONNRESET - SOCBASEERR:
  5063. #endif /* NT */
  5064.         debug(F100,"os2socketerror ECONRESET","",0);
  5065.         tn_debug("ECONRESET");
  5066.         netclos();              /* *** *** */
  5067.         return(-1);             /* Connection is broken. */
  5068. #ifdef NT
  5069.       case WSAECONNABORTED:
  5070. #else /* NT */
  5071.       case SOCECONNABORTED:
  5072.       case SOCECONNABORTED - SOCBASEERR:
  5073. #endif /* NT */
  5074.         debug(F100,"os2socketerror ECONNABORTED","",0);
  5075.         tn_debug("ECONNABORTED");
  5076.         netclos();              /* *** *** */
  5077.         return(-1);             /* Connection is broken. */
  5078. #ifdef NT
  5079.       case WSAENETRESET:
  5080. #else /* NT */
  5081.       case SOCENETRESET:
  5082.       case SOCENETRESET - SOCBASEERR:
  5083. #endif /* NT */
  5084.         debug(F100,"os2socketerror ENETRESET","",0);
  5085.         tn_debug("ENETRESET");
  5086.         netclos();              /* *** *** */
  5087.         return(-1);             /* Connection is broken. */
  5088. #ifdef NT
  5089.       case WSAENOTCONN:
  5090. #else /* NT */
  5091.       case SOCENOTCONN:
  5092.       case SOCENOTCONN - SOCBASEERR:
  5093. #endif /* NT */
  5094.         debug(F100,"os2socketerror ENOTCONN","",0);
  5095.         tn_debug("ENOTCONN");
  5096.         netclos();                      /* *** *** */
  5097.         return(-1);                     /* Connection is broken. */
  5098. #ifdef NT
  5099.       case WSAESHUTDOWN:
  5100.         debug(F100,"os2socketerror ESHUTDOWN","",0);
  5101.         tn_debug("ESHUTDOWN");
  5102.         netclos();                      /* *** *** */
  5103.         return(-1);                     /* Connection is broken. */
  5104. #endif /* NT */
  5105. #ifdef NT
  5106.       case WSAEWOULDBLOCK:
  5107. #else
  5108.       case SOCEWOULDBLOCK:
  5109.       case SOCEWOULDBLOCK - SOCBASEERR:
  5110. #endif /* NT */
  5111.         debug(F100,"os2socketerror EWOULDBLOCK","",0);
  5112.         return(0);
  5113. #ifdef NT
  5114.       case ERROR_IO_INCOMPLETE:
  5115.       case ERROR_IO_PENDING:
  5116.       case ERROR_OPERATION_ABORTED:
  5117.         return(0);
  5118. #endif /* NT */
  5119.       default:
  5120.         return(-2);
  5121.     }
  5122.     return(0);
  5123. }
  5124. #endif /* OS2 */
  5125.  
  5126. /*  N E T T C H K  --  Check if network up, and how many bytes can be read */
  5127. /*
  5128.   Returns number of bytes waiting, or -1 if connection has been dropped.
  5129. */
  5130. int                                     /* Check how many bytes are ready */
  5131. nettchk() {                             /* for reading from network */
  5132. #ifdef TCPIPLIB
  5133.     long count = 0;
  5134.     int x = 0;
  5135.     long y;
  5136.     char c;
  5137.     int rc;
  5138. #ifdef NT
  5139.     extern int ionoblock;               /* For Overlapped I/O */
  5140. #endif /* NT */
  5141.  
  5142.     debug(F101,"nettchk entry ttibn","",ttibn);
  5143.     debug(F101,"nettchk entry ttibp","",ttibp);
  5144.  
  5145. #ifdef NETLEBUF
  5146.     {
  5147.         int n = 0;
  5148.         if (ttpush >= 0)
  5149.           n++;
  5150.         n += le_inbuf();
  5151.         if (n > 0)
  5152.           return(n);
  5153.     }
  5154. #endif /* NETLEBUF */
  5155.  
  5156. #ifndef OS2
  5157. #ifndef BEBOX
  5158.     socket_errno = 0; /* This is a function call in NT, and BeOS */
  5159. #endif /* BEBOX */
  5160. #endif /* OS2 */
  5161.  
  5162.     if (ttyfd == -1) {
  5163.         debug(F100,"nettchk socket is closed","",0);
  5164.         return(-1);
  5165.     }
  5166. /*
  5167.   Note: this socket_ioctl() call does NOT return an error if the
  5168.   connection has been broken.  (At least not in MultiNet.)
  5169. */
  5170. #ifdef COMMENT
  5171. /*  Another trick that can be tried here is something like this: */
  5172.  
  5173.     if (ttnet == NET_TCPB) {
  5174.         char dummy;
  5175.         x = read(ttyfd,&dummy,0);       /* Try to read nothing */
  5176.         if (x < 0) {                    /* "Connection reset by peer" */
  5177.             perror("TCP/IP");           /* or somesuch... */
  5178.             ttclos(0);                  /* Close our end too. */
  5179.             return(-1);
  5180.         }
  5181.     }
  5182. #endif /* COMMENT */
  5183.  
  5184.  
  5185. #ifdef CK_SSL
  5186.     if (ssl_active_flag) {
  5187. #ifndef IKSDONLY
  5188.         if ( IsConnectMode() ) {
  5189.             debug(F101,"nettchk (ssl_active_flag) returns","",count);
  5190.             return(0);
  5191.         }
  5192. #endif /* IKSDONLY */
  5193.         count = SSL_pending(ssl_con);
  5194.         if (count < 0) {
  5195.             debug(F111,"nettchk","SSL_pending error",count);
  5196.             netclos();
  5197.             return(-1);
  5198.         }
  5199.         if ( count > 0 )
  5200.             return(count);                  /* Don't perform a read */
  5201.     } else if (tls_active_flag) {
  5202. #ifndef IKSDONLY
  5203.         if ( IsConnectMode() ) {
  5204.             debug(F101,"nettchk (tls_active_flag) returns","",count);
  5205.             return(0);
  5206.         }
  5207. #endif /* IKSDONLY */
  5208.         count = SSL_pending(tls_con);
  5209.         if (count < 0) {
  5210.             debug(F111,"nettchk","TLS_pending error",count);
  5211.             netclos();
  5212.             return(-1);
  5213.         }
  5214.         if ( count > 0 )
  5215.             return(count);                  /* Don't perform a read */
  5216.     } else
  5217. #endif /* CK_SSL */
  5218.  
  5219.     if (socket_ioctl(ttyfd,FIONREAD,
  5220. #ifdef COMMENT
  5221.     /* Now we've changed the ioctl(..,..,x) prototype for DECC to (void *) */
  5222. #ifdef __DECC
  5223.     /* NOTE: "&count" might need to be "(char *)&count" in some settings. */
  5224.                      /* Cast needed for DECC 4.1 & later? */
  5225.                      /* Maybe, but __DECC_VER only exists in 5.0 and later */
  5226.                      (char *)
  5227. #endif /* __DECC */
  5228. #endif /* COMMENT */
  5229.                      &count
  5230.                      ) < 0) {
  5231.         debug(F101,"nettchk socket_ioctl error","",socket_errno);
  5232.         /* If the connection is gone, the connection is gone. */
  5233.         netclos();
  5234. #ifdef NT_TCP_OVERLAPPED
  5235.         /* Is there anything in the overlapped I/O buffers? */
  5236.         count += OverlappedDataWaiting();
  5237. #endif /* NT_TCP_OVERLAPPED */
  5238.         count += ttibn;
  5239.         return(count>0?count:-1);
  5240.     }
  5241.     debug(F101,"nettchk count","",count);
  5242. #ifdef NT_TCP_OVERLAPPED
  5243.     /* Is there anything in the overlapped I/O buffers? */
  5244.     count += OverlappedDataWaiting();
  5245.     debug(F101,"nettchk count w/overlapped","",count);
  5246. #endif /* NT_TCP_OVERLAPPED */
  5247.  
  5248. /* For the sake of efficiency, if there is still data in the ttibuf */
  5249. /* do not go to the bother of checking to see of the connection is  */
  5250. /* still valid.  The handle is still good, so just return the count */
  5251. /* of the bytes that we already have left to process.               */
  5252. #ifdef OS2
  5253.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5254.     if ( count > 0 || ttibn > 0 ) {
  5255.         count+=ttibn;
  5256.         ReleaseTCPIPMutex();
  5257.         debug(F101,"nettchk (count+ttibn > 0) returns","",count);
  5258.         return(count);
  5259.     } else {
  5260.         if ( ttibn == 0 )
  5261.             ttibp = 0;      /* reset for next read */
  5262.  
  5263. #ifndef IKSDONLY
  5264.         if ( IsConnectMode() ) {
  5265.             ReleaseTCPIPMutex();
  5266.             debug(F101,"nettchk (count+ttibn == 0) returns","",count);
  5267.             return(0);
  5268.         }
  5269. #endif /* IKSDONLY */
  5270.     }
  5271. #else /* OS2 */
  5272.     if ( count > 0 || ttibn > 0 ) {
  5273.         debug(F101,"nettchk returns","",count+ttibn);
  5274.         return(count+ttibn);
  5275.     }
  5276. #endif /* OS2 */
  5277.  
  5278. /*
  5279.   The following code works well in most settings, but messes things up in
  5280.   others, including CMU/Tek TCP/IP and UCX 2.0, where it somehow manages to
  5281.   make it impossible to ever make a new connection to the same host again with
  5282.   CONNECT, once it has been logged out from the first time.  Not even if you
  5283.   HANGUP first, or SET HOST<CR>, or SET LINE<CR>.  Reportedly, however, it
  5284.   does work OK in later releases of UCX.  But there is no way we can
  5285.   accommodate both old and new -- we might have static linking or dynamic
  5286.   linking, etc etc.  If we have static, I only have access to 2.0, where this
  5287.   doesn't work, etc etc blah blah.
  5288.  
  5289.   In the following lines, we define a symbol NOCOUNT for builds where we want
  5290.   to omit this code.  By default, it is omitted for CMU/Tek.  You can force
  5291.   omission of it for other combinations by defining NOCOUNT in CFLAGS.  You
  5292.   can force inclusion of this code, even for CMU/Tek, by including NONOCOUNT
  5293.   in CFLAGS.
  5294. */
  5295. #ifdef NONOCOUNT
  5296. #ifdef NOCOUNT
  5297. #undef NOCOUNT
  5298. #endif /* NOCOUNT */
  5299. #else
  5300. #ifndef NOCOUNT
  5301. #ifdef CMU_TCPIP
  5302. #define NOCOUNT
  5303. #endif /* CMU_TCPIP */
  5304. #endif /* NOCOUNT */
  5305. #endif /* NONOCOUNT */
  5306.  
  5307.  
  5308.     /* From this point forward we have a possible race condition in K95
  5309.      * due to its use of multiple threads.  Therefore, we must ensure
  5310.      * that only one thread attempt to read/write from the socket at a
  5311.      * time.  Otherwise, it is possible for a buffer to be overwritten.
  5312.      */
  5313.     /* we know now that count >= 0 and that ttibn == 0 */
  5314.  
  5315.     if (count == 0
  5316. #ifdef RLOGCODE
  5317. #ifdef CK_KERBEROS
  5318.         && ttnproto != NP_EK4LOGIN && ttnproto != NP_EK5LOGIN
  5319. #endif /* CK_KERBEROS */
  5320. #endif /* RLOGCODE */
  5321.         ) {
  5322.         int s_errno = 0;
  5323. #ifndef NOCOUNT
  5324. /*
  5325.   Here we need to tell the difference between a 0 count on an active
  5326.   connection, and a 0 count because the remote end of the socket broke the
  5327.   connection.  There is no mechanism in TGV MultiNet (or WIN/TCP?) to query
  5328.   the status of the connection, so we have to do a read.  -1 means there was
  5329.   no data available (socket_errno == EWOULDBLOCK), 0 means the connection is
  5330.   down.  But if, by chance, we actually get a character, we have to put it
  5331.   where it won't be lost.
  5332. */
  5333. #ifndef NON_BLOCK_IO
  5334. #ifdef OS2
  5335. #ifdef CK_SSL
  5336.         RequestSSLMutex(SEM_INDEFINITE_WAIT);
  5337. #endif /* CK_SSL */
  5338. #endif /* OS2 */
  5339.         y = 1;                          /* Turn on nonblocking reads */
  5340.         x = socket_ioctl(ttyfd,FIONBIO,&y);
  5341.         debug(F101,"nettchk FIONBIO","",x);
  5342. #ifdef OS2
  5343. #ifdef CK_SSL
  5344.         ReleaseSSLMutex();
  5345. #endif /* CK_SSL */
  5346. #endif /* OS2 */
  5347. #endif /* NON_BLOCK_IO */
  5348. #ifdef NT_TCP_OVERLAPPED
  5349.         ionoblock = 1;                  /* For Overlapped I/O */
  5350. #endif /* NT_TCP_OVERLAPPED */
  5351. #ifdef CK_SSL
  5352.         if ( ssl_active_flag || tls_active_flag ) {
  5353.             x = SSL_read( ssl_active_flag?ssl_con:tls_con,
  5354.                           &ttibuf[ttibp+ttibn],
  5355.                           TTIBUFL-ttibp-ttibn );
  5356.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  5357.             case SSL_ERROR_NONE:
  5358.                 debug(F111,"nettchk SSL_ERROR_NONE","count",count);
  5359.                 break;
  5360.             case SSL_ERROR_WANT_WRITE:
  5361.                 debug(F100,"nettchk SSL_ERROR_WANT_WRITE","",0);
  5362.                 x = -1;
  5363.                 break;
  5364.             case SSL_ERROR_WANT_READ:
  5365.                 debug(F100,"nettchk SSL_ERROR_WANT_READ","",0);
  5366.                 x = -1;
  5367.                 break;
  5368.             case SSL_ERROR_SYSCALL:
  5369.                 if ( x == 0 ) { /* EOF */
  5370.                     netclos();
  5371.                     rc = -1;
  5372.                     goto nettchk_return;
  5373.               } else {
  5374. #ifdef NT
  5375.                   int gle = GetLastError();
  5376.                   debug(F111,"nettchk SSL_ERROR_SYSCALL",
  5377.                          "GetLastError()",gle);
  5378.                   rc = os2socketerror(gle);
  5379.                   if (rc == -1)
  5380.                       rc = -2;
  5381.                   else if ( rc == -2 )
  5382.                       return -1;
  5383. #endif /* NT */
  5384.                   break;
  5385.               }
  5386.           case SSL_ERROR_WANT_X509_LOOKUP:
  5387.                 debug(F100,"nettchk SSL_ERROR_WANT_X509_LOOKUP","",0);
  5388.                 break;
  5389.           case SSL_ERROR_SSL:
  5390.                 debug(F100,"nettchk SSL_ERROR_SSL","",0);
  5391.                 netclos();
  5392.                 rc = -1;
  5393.                 goto nettchk_return;
  5394.           case SSL_ERROR_ZERO_RETURN:
  5395.                 debug(F100,"nettchk SSL_ERROR_ZERO_RETURN","",0);
  5396.                 netclos();
  5397.                 rc = -1;
  5398.                 goto nettchk_return;
  5399.             default:
  5400.                 debug(F100,"nettchk SSL_ERROR_?????","",0);
  5401.                 netclos();
  5402.                 rc = -1;
  5403.                 goto nettchk_return;
  5404.             }
  5405.         } else
  5406. #endif /* CK_SSL */
  5407.         {
  5408. #ifdef OS2
  5409.         x = socket_read(ttyfd,&ttibuf[ttibp+ttibn],
  5410.                          TTIBUFL-ttibp-ttibn);  /* Returns -1 if no data */
  5411. #else /* OS2 */
  5412.         x = socket_read(ttyfd,&c,1);    /* Returns -1 if no data */
  5413. #endif /* OS2 */
  5414.         }
  5415.         s_errno = socket_errno;         /* socket_errno may be a function */
  5416.         debug(F101,"nettchk socket_read","",x);
  5417.  
  5418. #ifndef NON_BLOCK_IO
  5419.         y = 0;                          /* Turn them back off */
  5420.         socket_ioctl(ttyfd,FIONBIO,&y);
  5421. #endif /* NON_BLOCK_IO */
  5422. #ifdef NT_TCP_OVERLAPPED
  5423.         ionoblock = 0;                  /* For Overlapped I/O */
  5424. #endif /* NT_TCP_OVERLAPPED */
  5425.  
  5426.         if (x == -1) {
  5427.             debug(F101,"nettchk socket_read errno","",s_errno);
  5428. #ifdef OS2
  5429.             if (os2socketerror(s_errno) < 0) {
  5430.                 rc = -1;
  5431.                 goto nettchk_return;
  5432.             }
  5433. #endif /* OS2 */
  5434.         } else if (x == 0) {
  5435.             debug(F100,"nettchk connection closed","",0);
  5436.             netclos();                  /* *** *** */
  5437.             rc = -1;
  5438.             goto nettchk_return;
  5439.         }
  5440.         if (x >= 1) {                   /* Oops, actually got a byte? */
  5441. #ifdef OS2
  5442.             /* In OS/2 we read directly into ttibuf[] */
  5443.             hexdump("nettchk got real data",&ttibuf[ttibp+ttibn],x);
  5444.             ttibn += x;
  5445. #else /* OS2 */
  5446.             debug(F101,"nettchk socket_read char","",c);
  5447.             debug(F101,"nettchk ttibp","",ttibp);
  5448.             debug(F101,"nettchk ttibn","",ttibn);
  5449. /*
  5450.   In the case of Overlapped I/O the character would have come from
  5451.   the beginning of the buffer, so put it back.
  5452. */
  5453.             if (ttibp > 0) {
  5454.                 ttibp--;
  5455.                 ttibuf[ttibp] = c;
  5456.                 ttibn++;
  5457.             } else {
  5458.                 ttibuf[ttibp+ttibn] = c;
  5459.                 ttibn++;
  5460.             }
  5461. #endif /* OS2 */
  5462.         }
  5463. #else /* NOCOUNT */
  5464.         if (ttnet == NET_TCPB) {
  5465.             char dummy;
  5466.             x = read(ttyfd,&dummy,0);   /* Try to read nothing */
  5467.             if (x < 0) {                /* "Connection reset by peer" */
  5468.                 perror("TCP/IP");       /* or somesuch... */
  5469.                 ttclos(0);              /* Close our end too. */
  5470.                 rc = -1;
  5471.                 goto nettchk_return;
  5472.             }
  5473.         }
  5474. #endif /* NOCOUNT */
  5475.     }
  5476. #ifdef CK_KERBEROS
  5477. #ifdef KRB4
  5478. #ifdef RLOGCODE
  5479.     if (ttnproto == NP_EK4LOGIN)
  5480.       count += krb4_des_avail(ttyfd);
  5481. #endif /* RLOGCODE */
  5482. #endif /* KRB4 */
  5483. #ifdef KRB5
  5484. #ifdef RLOGCODE
  5485.     if (ttnproto == NP_EK5LOGIN)
  5486.       count += krb5_des_avail(ttyfd);
  5487. #endif /* RLOGCODE */
  5488. #ifdef KRB5_U2U
  5489.     if (ttnproto == NP_K5U2U)
  5490.       count += krb5_u2u_avail(ttyfd);
  5491. #endif /* KRB5_U2U */
  5492. #endif /* KRB5 */
  5493. #endif /* CK_KERBEROS */
  5494.  
  5495.     debug(F101,"nettchk returns","",count+ttibn);
  5496.     rc = count + ttibn;
  5497.  
  5498.   nettchk_return:
  5499. #ifdef OS2
  5500.     ReleaseTCPIPMutex();
  5501. #endif /* OS2 */
  5502.     return(rc);
  5503.  
  5504. #else /* Not TCPIPLIB */
  5505. /*
  5506.   UNIX just uses ttchk(), in which the ioctl() calls on the file descriptor
  5507.   seem to work OK.
  5508. */
  5509.     return(0);
  5510. #endif /* TCPIPLIB */
  5511. /*
  5512.   But what about X.25?
  5513. */
  5514. }
  5515.  
  5516. #ifndef OS2
  5517. VOID
  5518. nettout(i) int i; {                     /* Catch the alarm interrupts */
  5519.     debug(F100,"nettout caught timeout","",0);
  5520.     ttimoff();
  5521.     cklongjmp(njbuf, -1);
  5522. }
  5523. #endif /* !OS2 */
  5524.  
  5525. #ifdef TCPIPLIB
  5526.  
  5527. VOID
  5528. #ifdef CK_ANSIC
  5529. donetinc(void * threadinfo)
  5530. #else /* CK_ANSIC */
  5531. donetinc(threadinfo) VOID * threadinfo;
  5532. #endif /* CK_ANSIC */
  5533. /* donetinc */ {
  5534. #ifdef NTSIG
  5535.     extern int TlsIndex;
  5536.     setint();
  5537.     if (threadinfo) {                   /* Thread local storage... */
  5538.         TlsSetValue(TlsIndex,threadinfo);
  5539.     }
  5540. #endif /* NTSIG */
  5541. #ifdef CK_LOGIN
  5542. #ifdef NT
  5543. #ifdef IKSD
  5544.     if (inserver)
  5545.       setntcreds();
  5546. #endif /* IKSD */
  5547. #endif /* NT */
  5548. #endif /* CK_LOGIN */
  5549.     while (1) {
  5550.         if (ttbufr() < 0)               /* Keep trying to refill it. */
  5551.           break;                        /* Till we get an error. */
  5552.         if (ttibn > 0)                  /* Or we get a character. */
  5553.           break;
  5554.     }
  5555. }
  5556. #endif /* TCPIPLIB */
  5557.  
  5558. VOID
  5559. #ifdef CK_ANSIC
  5560. failnetinc(void * threadinfo)
  5561. #else /* CK_ANSIC */
  5562. failnetinc(threadinfo) VOID * threadinfo;
  5563. #endif /* CK_ANSIC */
  5564. /* failnetinc */ {
  5565.     ; /* Nothing to do on an error */
  5566. }
  5567.  
  5568. /* N E T X I N -- Input block of characters from network */
  5569.  
  5570. int
  5571. netxin(n,buf) int n; CHAR * buf; {
  5572.     int len, i, j;
  5573. #ifdef TCPIPLIB
  5574.     int rc;
  5575. #endif /* TCPIPLIB */
  5576.  
  5577.     if (ttyfd == -1) {
  5578.         debug(F100,"netinc socket is closed","",0);
  5579.         return(-2);
  5580.     }
  5581. #ifdef CK_KERBEROS
  5582. #ifdef KRB4
  5583. #ifdef RLOGCODE
  5584.     if (ttnproto == NP_EK4LOGIN) {
  5585.         if ((len = krb4_des_read(ttyfd,buf,n)) < 0)
  5586.           return(-1);
  5587.         else
  5588.           return(len);
  5589.     }
  5590. #endif /* RLOGCODE */
  5591. #endif /* KRB4 */
  5592. #ifdef KRB5
  5593. #ifdef RLOGCODE
  5594.     if (ttnproto == NP_EK5LOGIN) {
  5595.         if ((len = krb5_des_read(ttyfd,buf,n)) < 0)
  5596.           return(-1);
  5597.         else
  5598.           return(len);
  5599.     }
  5600. #endif /* RLOGCODE */
  5601. #ifdef KRB5_U2U
  5602.     if (ttnproto == NP_K5U2U) {
  5603.         if ((len = krb5_u2u_read(ttyfd,buf,n)) < 0)
  5604.           return(-1);
  5605.         else
  5606.           return(len);
  5607.     }
  5608. #endif /* KRB5_U2U */
  5609. #endif /* KRB5 */
  5610. #endif /* CK_KERBEROS */
  5611.  
  5612. #ifdef TCPIPLIB
  5613. #ifdef OS2
  5614.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5615. #endif /* OS2 */
  5616.     if (ttibn == 0)
  5617.       if ((rc = ttbufr()) <= 0) {
  5618. #ifdef OS2
  5619.         ReleaseTCPIPMutex();
  5620. #endif /* OS2 */
  5621.         return(rc);
  5622.       }
  5623.  
  5624.     if (ttibn <= n) {
  5625.         len = ttibn;
  5626.         memcpy(buf,&ttibuf[ttibp],len);         /* safe */
  5627.         ttibp += len;
  5628.         ttibn = 0;
  5629.     } else {
  5630.         memcpy(buf,&ttibuf[ttibp],n);           /* safe */
  5631.         ttibp += n;
  5632.         ttibn -= n;
  5633.         len = n;
  5634.     }
  5635. #ifdef OS2
  5636.     ReleaseTCPIPMutex();
  5637. #endif /* OS2 */
  5638. #else /* TCPIPLIB */
  5639.     for (i = 0; i < n; i++) {
  5640.         if ((j = netinc(0)) < 0) {
  5641.             if (j < -1)
  5642.               return(j);
  5643.             else
  5644.               break;
  5645.         }
  5646.         buf[i] = j;
  5647.     }
  5648.     len = i;
  5649. #endif /* TCPIPLIB */
  5650.  
  5651. #ifdef COMMENT
  5652. #ifdef CK_ENCRYPTION
  5653.     /* This would be great if it worked.  But what if the buffer we read  */
  5654.     /* contains a telnet negotiation that changes the state of the        */
  5655.     /* encryption.  If so, we would be either decrypting unencrypted text */
  5656.     /* or not decrypting encrypted text.  So we must move this call to    */
  5657.     /* all functions that call ttxin().  In OS2 that means os2_netxin()   */
  5658.     /* where the Telnet Negotiations are handled.                         */
  5659.     if (u_encrypt)
  5660.       ck_tn_decrypt(buf,len);
  5661. #endif /* CK_ENCRYPTION */
  5662. #endif /* COMMENT */
  5663.  
  5664.     return(len);
  5665. }
  5666.  
  5667. /*  N E T I N C --  Input character from network */
  5668.  
  5669. #ifdef NETLEBUF
  5670. #define LEBUF
  5671. #endif /* NETLEBUF */
  5672. #ifdef TTLEBUF
  5673. #define LEBUF
  5674. #endif /* TTLEBUF */
  5675. #ifndef LEBUF
  5676. #ifdef OS2
  5677. #define LEBUF
  5678. #endif /* OS2 */
  5679. #endif /* LEBUF */
  5680.  
  5681. int
  5682. netinc(timo) int timo; {
  5683. #ifdef TCPIPLIB
  5684.     int x; unsigned char c;             /* The locals. */
  5685.  
  5686. #ifdef NETLEBUF
  5687.     if (ttpush >= 0) {
  5688.         debug(F111,"netinc","ttpush",ttpush);
  5689.         c = ttpush;
  5690.         ttpush = -1;
  5691.         return(c);
  5692.     }
  5693.     if (le_data) {
  5694.         if (le_getchar((CHAR *)&c) > 0) {
  5695.             debug(F111,"netinc le_getchar","c",c);
  5696.             return(c);
  5697.         }
  5698.     }
  5699. #endif /* NETLEBUF */
  5700.  
  5701.     if (ttyfd == -1) {
  5702.         debug(F100,"netinc socket is closed","",0);
  5703.         return(-2);
  5704.     }
  5705.  
  5706. #ifdef CK_KERBEROS
  5707. #ifdef KRB4
  5708. #ifdef RLOGCODE
  5709.     if (ttnproto == NP_EK4LOGIN) {
  5710.         if ((x = krb4_des_read(ttyfd,&c,1)) == 0)
  5711.           return(-1);
  5712.         else if (x < 0)
  5713.           return(-2);
  5714.         else
  5715.           return(c);
  5716.     }
  5717. #endif /* RLOGCODE */
  5718. #endif /* KRB4 */
  5719. #ifdef KRB5
  5720. #ifdef RLOGCODE
  5721.     if (ttnproto == NP_EK5LOGIN) {
  5722.         if ((x = krb5_des_read(ttyfd,&c,1)) == 0)
  5723.           return(-1);
  5724.         else if (x < 0)
  5725.           return(-2);
  5726.         else
  5727.           return(c);
  5728.     }
  5729. #endif /* RLOGCODE */
  5730. #ifdef KRB5_U2U
  5731.     if (ttnproto == NP_K5U2U) {
  5732.         if ((x = krb5_u2u_read(ttyfd,&c,1)) == 0)
  5733.           return(-1);
  5734.         else if (x < 0)
  5735.           return(-2);
  5736.         else
  5737.           return(c);
  5738.     }
  5739. #endif /* KRB5_U2U */
  5740. #endif /* KRB5 */
  5741. #endif /* CK_KERBEROS */
  5742.  
  5743. #ifdef OS2
  5744.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  5745. #endif /* OS2 */
  5746.     if (ttibn > 0) {                    /* Something in internal buffer? */
  5747. #ifdef COMMENT
  5748.         debug(F100,"netinc char in buf","",0); /* Yes. */
  5749. #endif /* COMMENT */
  5750.         x = 0;                          /* Success. */
  5751.     } else {                            /* Else must read from network. */
  5752.         x = -1;                         /* Assume failure. */
  5753. #ifdef DEBUG
  5754.         debug(F101,"netinc goes to net, timo","",timo);
  5755. #endif /* DEBUG */
  5756. #ifdef CK_SSL
  5757.         /*
  5758.          * In the case of OpenSSL, it is possible that there is still
  5759.          * data waiting in the SSL session buffers that has not yet
  5760.          * been read by Kermit.  If this is the case we must process
  5761.          * it without calling select() because select() will not return
  5762.          * with an indication that there is data to be read from the
  5763.          * socket.  If there is no data pending in the SSL session
  5764.          * buffers then fall through to the select() code and wait for
  5765.          * some data to arrive.
  5766.          */
  5767.         if (ssl_active_flag) {
  5768.             x = SSL_pending(ssl_con);
  5769.             if (x < 0) {
  5770.                 debug(F111,"netinc","SSL_pending error",x);
  5771.                 netclos();
  5772. #ifdef OS2
  5773.                 ReleaseTCPIPMutex();
  5774. #endif /* OS2 */
  5775.                 return(-1);
  5776.             } else if ( x > 0 ) {
  5777.                 if ( ttbufr() >= 0 ) {
  5778.                     x = netinc(timo);
  5779. #ifdef OS2
  5780.                     ReleaseTCPIPMutex();
  5781. #endif /* OS2 */
  5782.                     return(x);
  5783.                 }
  5784.             }
  5785.             x = -1;
  5786.         } else if (tls_active_flag) {
  5787.             x = SSL_pending(tls_con);
  5788.             if (x < 0) {
  5789.                 debug(F111,"netinc","TLS_pending error",x);
  5790.                 netclos();
  5791. #ifdef OS2
  5792.                 ReleaseTCPIPMutex();
  5793. #endif /* OS2 */
  5794.                 return(-1);
  5795.             } else if ( x > 0 ) {
  5796.                 if ( ttbufr() >= 0 ) {
  5797.                     x = netinc(timo);
  5798. #ifdef OS2
  5799.                     ReleaseTCPIPMutex();
  5800. #endif /* OS2 */
  5801.                     return(x);
  5802.                 }
  5803.             }
  5804.             x = -1;
  5805.         }
  5806. #endif /* CK_SSL */
  5807. #ifndef LEBUF
  5808.         if (timo == 0) {                /* Untimed case. */
  5809.             while (1) {                 /* Wait forever if necessary. */
  5810.                 if (ttbufr() < 0)       /* Refill buffer. */
  5811.                   break;                /* Error, fail. */
  5812.                 if (ttibn > 0) {        /* Success. */
  5813.                     x = 0;
  5814.                     break;
  5815.                 }
  5816.             }
  5817.         } else                          /* Timed case... */
  5818. #endif /* LEBUF */
  5819.           {
  5820. #ifdef NT_TCP_OVERLAPPED
  5821.             /* This code is for use on NT when we are using */
  5822.             /* Overlapped I/O to handle reads.  In the case */
  5823.             /* of outstanding reads select() doesn't work   */
  5824.  
  5825.             if (WaitForOverlappedReadData(timo)) {
  5826.                 while (1) {
  5827.                     if (ttbufr() < 0)   /* Keep trying to refill it. */
  5828.                         break;          /* Till we get an error. */
  5829.                     if (ttibn > 0) {    /* Or we get a character. */
  5830.                         x = 0;
  5831.                         break;
  5832.                     }
  5833.                 }
  5834.             }
  5835. #else /* NT_TCP_OVERLAPPED */
  5836. #ifdef BSDSELECT
  5837.             fd_set rfds;
  5838.             struct timeval tv;
  5839.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5840.             debug(F101,"netinc BSDSELECT","",timo);
  5841.  
  5842.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5843.                 int rc;
  5844.                 debug(F111,"netinc","timeout",timeout);
  5845.                 /* Don't move select() initialization out of the loop. */
  5846.                 FD_ZERO(&rfds);
  5847.                 FD_SET(ttyfd, &rfds);
  5848.                 tv.tv_sec  = tv.tv_usec = 0L;
  5849.                 if (timo)
  5850.                   tv.tv_usec = (long) 100000L;
  5851.                 else
  5852.                   tv.tv_sec = 30;
  5853. #ifdef NT
  5854.                 WSASafeToCancel = 1;
  5855. #endif /* NT */
  5856.                 rc = select(FD_SETSIZE,
  5857. #ifndef __DECC
  5858.                             (fd_set *)
  5859. #endif /* __DECC */
  5860.                             &rfds, NULL, NULL, &tv);
  5861.                 if (rc < 0) {
  5862.                     int s_errno = socket_errno;
  5863.                     debug(F111,"netinc","select",rc);
  5864.                     debug(F111,"netinc","socket_errno",s_errno);
  5865.                     if (s_errno) {
  5866. #ifdef OS2
  5867.                         ReleaseTCPIPMutex();
  5868. #endif /* OS2 */
  5869.                         return(-1);
  5870.                     }
  5871.                 }
  5872.                 debug(F111,"netinc","select",rc);
  5873. #ifdef NT
  5874.                 WSASafeToCancel = 0;
  5875. #endif /* NT */
  5876.                 if (!FD_ISSET(ttyfd, &rfds)) {
  5877. #ifdef LEBUF
  5878.                     if (le_inbuf() > 0) {
  5879.                         timeout = -1;
  5880.                         break;
  5881.                     }
  5882. #endif /* LEBUF */
  5883.                     /* If waiting forever we have no way of knowing if the */
  5884.                     /* socket closed so try writing a 0-length TCP packet  */
  5885.                     /* which should force an error if the socket is closed */
  5886.                     if (!timo) {
  5887.                         if ((rc = socket_write(ttyfd,"",0)) < 0) {
  5888.                             int s_errno = socket_errno;
  5889.                             debug(F101,"netinc socket_write error","",s_errno);
  5890. #ifdef OS2
  5891.                             if (os2socketerror(s_errno) < 0) {
  5892.                               ReleaseTCPIPMutex();
  5893.                               return(-2);
  5894.                             }
  5895.                             ReleaseTCPIPMutex();
  5896. #endif /* OS2 */
  5897.                             return(-1); /* Call it an i/o error */
  5898.                         }
  5899.                     }
  5900.                     continue;
  5901.                 }
  5902.                 while (1) {
  5903.                     if (ttbufr() < 0) { /* Keep trying to refill it. */
  5904.                         timeout = -1;
  5905.                         break;          /* Till we get an error. */
  5906.                     }
  5907.                     if (ttibn > 0) {    /* Or we get a character. */
  5908.                         x = 0;
  5909.                         timeout = -1;
  5910.                         break;
  5911.                     }
  5912.                 }
  5913.             }
  5914. #ifdef NT
  5915.             WSASafeToCancel = 0;
  5916. #endif /* NT */
  5917. #else /* !BSDSELECT */
  5918. #ifdef IBMSELECT
  5919. /*
  5920.   Was used by OS/2, currently not used, but might come in handy some day...
  5921.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  5922.   and timeval stuff since this is the only place where it is used.
  5923. */
  5924.             int socket = ttyfd;
  5925.             int timeout = timo < 0 ? -timo : 1000 * timo;
  5926.  
  5927.             debug(F101,"netinc IBMSELECT","",timo);
  5928.             for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  5929.                 if (select(&socket, 1, 0, 0, 100L) == 1) {
  5930.                     while (1) {
  5931.                         if (ttbufr() < 0) { /* Keep trying to refill it. */
  5932.                             timeout = -1;
  5933.                             break;      /* Till we get an error. */
  5934.                         }
  5935.                         if (ttibn > 0) { /* Or we get a character. */
  5936.                             x = 0;
  5937.                             timeout = -1;
  5938.                             break;
  5939.                         }
  5940.                     }
  5941.                 }
  5942. #ifdef LEBUF
  5943.                 else if (le_inbuf() > 0)  {
  5944.                     timeout = -1;
  5945.                     break;
  5946.                 }
  5947. #endif /* LEBUF */
  5948.             }
  5949. #else /* !IBMSELECT */
  5950. #ifdef WINSOCK
  5951.        /* Actually, under WinSock we have a better mechanism than select() */
  5952.        /* for setting timeouts (SO_RCVTIMEO, SO_SNDTIMEO) */
  5953.             SOCKET socket = ttyfd;
  5954.             debug(F101,"netinc NTSELECT","",timo);
  5955.             if (setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timo,
  5956.                             sizeof(timo))  == NO_ERROR)
  5957.               while (1) {
  5958.                   if (ttbufr() < 0)     /* Keep trying to refill it. */
  5959.                     break;              /* Till we get an error. */
  5960.                   if (ttibn > 0) {      /* Or we get a character. */
  5961.                       x = 0;
  5962.                       break;
  5963.                   }
  5964.               }
  5965. #else /* WINSOCK */
  5966. /*
  5967.   If we can't use select(), then we use the regular alarm()/signal()
  5968.   timeout mechanism.
  5969. */
  5970.             debug(F101,"netinc alarm","",timo);
  5971.             x = alrm_execute(ckjaddr(njbuf),timo,nettout,donetinc,failnetinc);
  5972.             ttimoff();                  /* Timer off. */
  5973. #endif /* WINSOCK */
  5974. #endif /* IBMSELECT */
  5975. #endif /* BSDSELECT */
  5976. #endif /* NT_TCP_OVERLAPPED */
  5977.         }
  5978.     }
  5979.  
  5980. #ifdef LEBUF
  5981.     if (le_inbuf() > 0) {               /* If data was inserted into the */
  5982.         if (le_getchar((CHAR *)&c) > 0) {/* Local Echo buffer while the   */
  5983. #ifdef OS2                               /* was taking place do not mix   */
  5984.           ReleaseTCPIPMutex();           /* the le data with the net data */
  5985. #endif /* OS2 */
  5986.           return(c);
  5987.         }
  5988.     }
  5989. #endif /* LEBUF */
  5990.     if (x < 0) {                        /* Return -1 if we failed. */
  5991.         debug(F100,"netinc timed out","",0);
  5992. #ifdef OS2
  5993.         ReleaseTCPIPMutex();
  5994. #endif /* OS2 */
  5995.         return(-1);
  5996.     } else {                            /* Otherwise */
  5997.         c = ttibuf[ttibp];              /* Return the first char in ttibuf[] */
  5998.         if (deblog) {
  5999. #ifndef COMMENT
  6000.             debug(F101,"netinc returning","",c);
  6001. #endif /* COMMENT */
  6002.             if (c == 0) {
  6003.                 debug(F101,"netinc 0 ttibn","",ttibn);
  6004.                 debug(F101,"netinc 0 ttibp","",ttibp);
  6005. #ifdef BETADEBUG
  6006.                 {
  6007. #ifdef OS2
  6008.                     extern int tt_type_mode;
  6009.                     if ( !ISVTNT(tt_type_mode) )
  6010. #endif /* OS2 */
  6011.                     hexdump("netinc &ttbuf[ttibp]",&ttibuf[ttibp],ttibn);
  6012.                 }
  6013. #endif /* BETADEBUG */
  6014.             }
  6015.         }
  6016.         ttibp++;
  6017.         ttibn--;
  6018. #ifdef OS2
  6019.         ReleaseTCPIPMutex();
  6020. #endif /* OS2 */
  6021. #ifdef CK_ENCRYPTION
  6022.         if (TELOPT_U(TELOPT_ENCRYPTION))
  6023.           ck_tn_decrypt(&c,1);
  6024. #endif /* CK_ENCRYPTION */
  6025.         return(c);
  6026.     }
  6027. #else /* Not using TCPIPLIB */
  6028.     return(-1);
  6029. #endif /* TCPIPLIB */
  6030. }
  6031.  
  6032. /*  N E T T O L  --  Output a string of bytes to the network  */
  6033. /*
  6034.   Call with s = pointer to string, n = length.
  6035.   Returns number of bytes actually written on success, or
  6036.   -1 on i/o error, -2 if called improperly.
  6037. */
  6038.  
  6039. int
  6040. nettol(s,n) CHAR *s; int n; {
  6041. #ifdef TCPIPLIB
  6042.     int count = 0;
  6043.     int len = n;
  6044.     int try = 0;
  6045.  
  6046.     if (ttyfd == -1) {
  6047.         debug(F100,"nettol socket is closed","",0);
  6048.         return -1;
  6049.     }
  6050.     debug(F101,"nettol TCPIPLIB ttnet","",ttnet);
  6051. #ifdef COMMENT
  6052.     hexdump("nettol",s,n);
  6053. #endif /* COMMENT */
  6054.  
  6055. #ifdef CK_KERBEROS
  6056. #ifdef KRB4
  6057. #ifdef RLOGCODE
  6058.     if (ttnproto == NP_EK4LOGIN) {
  6059.         return(krb4_des_write(ttyfd,s,n));
  6060.     }
  6061. #endif /* RLOGCODE */
  6062. #endif /* KRB4 */
  6063. #ifdef KRB5
  6064. #ifdef RLOGCODE
  6065.     if (ttnproto == NP_EK5LOGIN) {
  6066.         return(krb5_des_write(ttyfd,s,n));
  6067.     }
  6068. #endif /* RLOGCODE */
  6069. #ifdef KRB5_U2U
  6070.     if (ttnproto == NP_K5U2U) {
  6071.         return(krb5_u2u_write(ttyfd,s,n));
  6072.     }
  6073. #endif /* KRB5_U2U */
  6074. #endif /* KRB5 */
  6075. #endif /* CK_KERBEROS */
  6076.  
  6077. #ifdef CK_ENCRYPTION
  6078.     if (TELOPT_ME(TELOPT_ENCRYPTION))
  6079.       ck_tn_encrypt(s,n);
  6080. #endif /* CK_ENCRYPTION */
  6081.  
  6082. #ifdef CK_SSL
  6083.     if (ssl_active_flag || tls_active_flag) {
  6084.         int error, r;
  6085.         /* Write using SSL */
  6086.       ssl_retry:
  6087.         if (ssl_active_flag)
  6088.           r = SSL_write(ssl_con, s, len /* >1024?1024:len */);
  6089.         else
  6090.           r = SSL_write(tls_con, s, len /* >1024?1024:len */);
  6091.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,r)) {
  6092.           case SSL_ERROR_NONE:
  6093.             debug(F111,"nettol","SSL_write",r);
  6094.             if ( r == len )
  6095.                 return(n);
  6096.              s += r;
  6097.              len -= r;
  6098.              goto ssl_retry;
  6099.           case SSL_ERROR_WANT_WRITE:
  6100.             debug(F100,"nettol SSL_ERROR_WANT_WRITE","",0);
  6101.             return(-1);
  6102.           case SSL_ERROR_WANT_READ:
  6103.             debug(F100,"nettol SSL_ERROR_WANT_READ","",0);
  6104.             return(-1);
  6105.           case SSL_ERROR_SYSCALL:
  6106.               if ( r == 0 ) { /* EOF */
  6107.                   netclos();
  6108.                   return(-2);
  6109.               } else {
  6110.                   int rc = -1;
  6111. #ifdef NT
  6112.                   int gle = GetLastError();
  6113.                   debug(F111,"nettol SSL_ERROR_SYSCALL",
  6114.                          "GetLastError()",gle);
  6115.                   rc = os2socketerror(gle);
  6116.                   if (rc == -1)
  6117.                       rc = -2;
  6118.                   else if ( rc == -2 )
  6119.                       return -1;
  6120. #endif /* NT */
  6121.                   return(rc);
  6122.               }
  6123.           case SSL_ERROR_WANT_X509_LOOKUP:
  6124.             debug(F100,"nettol SSL_ERROR_WANT_X509_LOOKUP","",0);
  6125.             netclos();
  6126.             return(-2);
  6127.           case SSL_ERROR_SSL:
  6128.             debug(F100,"nettol SSL_ERROR_SSL","",0);
  6129.             netclos();
  6130.             return(-2);
  6131.           case SSL_ERROR_ZERO_RETURN:
  6132.             debug(F100,"nettol SSL_ERROR_ZERO_RETURN","",0);
  6133.             netclos();
  6134.             return(-2);
  6135.           default:
  6136.             debug(F100,"nettol SSL_ERROR_?????","",0);
  6137.             netclos();
  6138.             return(-2);
  6139.         }
  6140.     }
  6141. #endif /* CK_SSL */
  6142.  
  6143.   nettol_retry:
  6144.     try++;                              /* Increase the try counter */
  6145.  
  6146.     if (ttnet == NET_TCPB) {
  6147. #ifdef BSDSELECT
  6148.         fd_set wfds;
  6149.         struct timeval tv;
  6150.  
  6151.         debug(F101,"nettol BSDSELECT","",0);
  6152.         tv.tv_usec = 0L;
  6153.         tv.tv_sec=30;
  6154. #ifdef NT
  6155.         WSASafeToCancel = 1;
  6156. #endif /* NT */
  6157. #ifdef STREAMING
  6158.       do_select:
  6159. #endif /* STREAMING */
  6160.         FD_ZERO(&wfds);
  6161.         FD_SET(ttyfd, &wfds);
  6162.         if (select(FD_SETSIZE, NULL,
  6163. #ifdef __DECC
  6164. #ifndef __DECC_VER
  6165.                     (int *)
  6166. #endif /* __DECC_VER */
  6167. #endif /* __DECC */
  6168.                    &wfds, NULL, &tv) < 0) {
  6169.             int s_errno = socket_errno;
  6170.             debug(F101,"nettol select failed","",s_errno);
  6171. #ifdef BETADEBUG
  6172.             printf("nettol select failed: %d\n", s_errno);
  6173. #endif /* BETADEBUG */
  6174. #ifdef NT
  6175.             WSASafeToCancel = 0;
  6176.             if (!win95selectbug)
  6177. #endif /* NT */
  6178.               return(-1);
  6179.         }
  6180.         if (!FD_ISSET(ttyfd, &wfds)) {
  6181. #ifdef STREAMING
  6182.             if (streaming)
  6183.               goto do_select;
  6184. #endif /* STREAMING */
  6185.             debug(F111,"nettol","!FD_ISSET",ttyfd);
  6186. #ifdef NT
  6187.             WSASafeToCancel = 0;
  6188.             if (!win95selectbug)
  6189. #endif /* NT */
  6190.               return(-1);
  6191.         }
  6192. #ifdef NT
  6193.         WSASafeToCancel = 0;
  6194. #endif /* NT */
  6195. #else /* BSDSELECT */
  6196. #ifdef IBMSELECT
  6197.         {
  6198.             int tries = 0;
  6199.             debug(F101,"nettol IBMSELECT","",0);
  6200.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6201.                 int count;
  6202.                 if (tries++ >= 60) {
  6203.                     /* if after 60 seconds we can't get permission to write */
  6204.                     debug(F101,"nettol select failed","",socket_errno);
  6205.                     return(-1);
  6206.                 }
  6207.                 if ((count = nettchk()) < 0) {
  6208.                     debug(F111,"nettol","nettchk()",count);
  6209.                     return(count);
  6210.                 }
  6211.             }
  6212.         }
  6213. #endif /* IBMSELECT */
  6214. #endif /* BSDSELECT */
  6215.         if ((count = socket_write(ttyfd,s,n)) < 0) {
  6216.             int s_errno = socket_errno; /* maybe a function */
  6217.             debug(F101,"nettol socket_write error","",s_errno);
  6218. #ifdef OS2
  6219.             if (os2socketerror(s_errno) < 0)
  6220.               return(-2);
  6221. #endif /* OS2 */
  6222.             return(-1);                 /* Call it an i/o error */
  6223.         }
  6224.         if (count < n) {
  6225.             debug(F111,"nettol socket_write",s,count);
  6226.             if (try > 25) {
  6227.                 /* don't try more than 25 times */
  6228.                 debug(F100,"nettol tried more than 25 times","",0);
  6229.                 return(-1);
  6230.             }
  6231.             if (count > 0) {
  6232.                 s += count;
  6233.                 n -= count;
  6234.             }
  6235.             debug(F111,"nettol retry",s,n);
  6236.             goto nettol_retry;
  6237.         } else {
  6238.             debug(F111,"nettol socket_write",s,count);
  6239.             return(len); /* success - return total length */
  6240.         }
  6241.     } else
  6242.       return(-2);
  6243. #else
  6244.     debug(F100,"nettol TCPIPLIB not defined","",0);
  6245.     return(-2);
  6246. #endif /* TCPIPLIB */
  6247. }
  6248.  
  6249. /*  N E T T O C  --   Output character to network */
  6250. /*
  6251.   Call with character to be transmitted.
  6252.   Returns 0 if transmission was successful, or
  6253.   -1 upon i/o error, or -2 if called improperly.
  6254. */
  6255. int
  6256. #ifdef CK_ANSIC
  6257. nettoc(CHAR c)
  6258. #else
  6259. nettoc(c) CHAR c;
  6260. #endif /* CK_ANSIC */
  6261. /* nettoc */ {
  6262. #ifdef UNIX
  6263.     return(ttoc(c));
  6264. #else
  6265. #ifdef TCPIPLIB
  6266.     unsigned char cc;
  6267.     if (ttyfd == -1) {
  6268.         debug(F100,"nettoc socket is closed","",0);
  6269.         return -1;
  6270.     }
  6271.     cc = c;
  6272.     debug(F101,"nettoc cc","",cc);
  6273.  
  6274. #ifdef CK_KERBEROS
  6275. #ifdef KRB4
  6276. #ifdef RLOGCODE
  6277.     if (ttnproto == NP_EK4LOGIN) {
  6278.         return(krb4_des_write(ttyfd,&cc,1)==1?0:-1);
  6279.     }
  6280. #endif /* RLOGCODE */
  6281. #endif /* KRB4 */
  6282. #ifdef KRB5
  6283. #ifdef RLOGCODE
  6284.     if (ttnproto == NP_EK5LOGIN) {
  6285.         return(krb5_des_write(ttyfd,&cc,1)==1?0:-1);
  6286.     }
  6287. #endif /* RLOGCODE */
  6288. #ifdef KRB5_U2U
  6289.     if (ttnproto == NP_K5U2U) {
  6290.         return(krb5_u2u_write(ttyfd,&cc,1)==1?0:-1);
  6291.     }
  6292. #endif /* KRB5_U2U */
  6293. #endif /* KRB5 */
  6294. #endif /* CK_KERBEROS */
  6295.  
  6296. #ifdef CK_ENCRYPTION
  6297.         if ( TELOPT_ME(TELOPT_ENCRYPTION) )
  6298.             ck_tn_encrypt(&cc,1);
  6299. #endif /* CK_ENCRYPTION */
  6300. #ifdef CK_SSL
  6301.     if (ssl_active_flag || tls_active_flag) {
  6302.         int len, error;
  6303.         /* Write using SSL */
  6304.         if (ssl_active_flag)
  6305.           len = SSL_write(ssl_con, &cc, 1);
  6306.         else
  6307.           len = SSL_write(tls_con, &cc, 1);
  6308.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,len)) {
  6309.           case SSL_ERROR_NONE:
  6310.             debug(F111,"nettoc","SSL_write",len);
  6311.             return(len == 1 ? 0 : -1);
  6312.           case SSL_ERROR_WANT_WRITE:
  6313.           case SSL_ERROR_WANT_READ:
  6314.             return(-1);
  6315.           case SSL_ERROR_SYSCALL:
  6316.               if ( len == 0 ) { /* EOF */
  6317.                   netclos();
  6318.                   return(-2);
  6319.               } else {
  6320.                   int rc = -1;
  6321. #ifdef NT
  6322.                   int gle = GetLastError();
  6323.                   debug(F111,"nettoc SSL_ERROR_SYSCALL",
  6324.                          "GetLastError()",gle);
  6325.                   rc = os2socketerror(gle);
  6326.                   if (rc == -1)
  6327.                       rc = -2;
  6328.                   else if ( rc == -2 )
  6329.                       return -1;
  6330. #endif /* NT */
  6331.                   return(rc);
  6332.               }
  6333.           case SSL_ERROR_WANT_X509_LOOKUP:
  6334.           case SSL_ERROR_SSL:
  6335.           case SSL_ERROR_ZERO_RETURN:
  6336.           default:
  6337.             netclos();
  6338.             return(-2);
  6339.         }
  6340.     }
  6341. #endif /* CK_SSL */
  6342.     if (ttnet == NET_TCPB) {
  6343. #ifdef BSDSELECT
  6344.         fd_set wfds;
  6345.         struct timeval tv;
  6346.  
  6347.         debug(F101,"nettoc BSDSELECT","",0);
  6348.         tv.tv_usec = 0L;
  6349.         tv.tv_sec = 30;
  6350.  
  6351. #ifdef STREAMING
  6352.       do_select:
  6353. #endif /* STREAMING */
  6354.  
  6355.         FD_ZERO(&wfds);
  6356.         FD_SET(ttyfd, &wfds);
  6357.         if (select(FD_SETSIZE, NULL,
  6358. #ifdef __DECC
  6359. #ifndef __DECC_VER
  6360.                    (int *)
  6361. #endif /* __DECC_VER */
  6362. #endif /* __DECC */
  6363.                    &wfds, NULL, &tv) < 0) {
  6364.             int s_errno = socket_errno;
  6365.             debug(F101,"nettoc select failed","",s_errno);
  6366. #ifdef BETADEBUG
  6367.             printf("nettoc select failed: %d\n", s_errno);
  6368. #endif /* BETADEBUG */
  6369. #ifdef NT
  6370.             WSASafeToCancel = 0;
  6371.             if (!win95selectbug)
  6372. #endif /* NT */
  6373.               return(-1);
  6374.         }
  6375.         if (!FD_ISSET(ttyfd, &wfds)) {
  6376. #ifdef STREAMING
  6377.             if (streaming)
  6378.               goto do_select;
  6379. #endif /* STREAMING */
  6380.             debug(F111,"nettoc","!FD_ISSET",ttyfd);
  6381. #ifdef NT
  6382.             WSASafeToCancel = 0;
  6383.             if (!win95selectbug)
  6384. #endif /* NT */
  6385.               return(-1);
  6386.         }
  6387. #ifdef NT
  6388.         WSASafeToCancel = 0;
  6389. #endif /* NT */
  6390. #else /* BSDSELECT */
  6391. #ifdef IBMSELECT
  6392.         {
  6393.             int tries = 0;
  6394.             while (select(&ttyfd, 0, 1, 0, 1000) != 1) {
  6395.                 int count;
  6396.                 if (tries++ >= 60) {
  6397.                     /* if after 60 seconds we can't get permission to write */
  6398.                     debug(F101,"nettoc select failed","",socket_errno);
  6399.                     return(-1);
  6400.                 }
  6401.                 if ((count = nettchk()) < 0) {
  6402.                     debug(F111,"nettoc","nettchk()",count);
  6403.                     return(count);
  6404.                 }
  6405.             }
  6406.         }
  6407. #endif /* IBMSELECT */
  6408. #endif /* BSDSELECT */
  6409.         if (socket_write(ttyfd,&cc,1) < 1) {
  6410.             int s_errno = socket_errno;         /* maybe a function */
  6411.             debug(F101,"nettoc socket_write error","",s_errno);
  6412. #ifdef OS2
  6413.             if (os2socketerror(s_errno) < 0)
  6414.               return(-2);
  6415. #endif /* OS2 */
  6416.             return(-1);
  6417.         }
  6418.         debug(F101,"nettoc socket_write","", cc);
  6419.         return(0);
  6420.     } else return(-2);
  6421. #else
  6422.     return(-2);
  6423. #endif /* TCPIPLIB */
  6424. #endif /* UNIX */
  6425. }
  6426.  
  6427. /*  N E T F L U I  --  Flush network input buffer  */
  6428.  
  6429. #ifdef TNCODE
  6430. static int
  6431. #ifdef CK_ANSIC
  6432. netgetc(int timo)                       /* Input function to point to... */
  6433. #else  /* CK_ANSIC */
  6434. netgetc(timo) int timo;
  6435. #endif /* CK_ANSIC */
  6436. {                                       /* ...in the tn_doop() call */
  6437. #ifdef TCPIPLIB
  6438.     return netinc(timo);
  6439. #else /* TCPIPLIB */
  6440.     return ttinc(timo);
  6441. #endif /* TCPIPLIB */
  6442. }
  6443. #endif /* TNCODE */
  6444.  
  6445. int
  6446. netflui() {
  6447.     int n;
  6448.     int ch;
  6449. #ifdef NETLEBUF
  6450.     ttpush = -1;                        /* Clear the peek-ahead char */
  6451.     while (le_data && (le_inbuf() > 0)) {
  6452.         CHAR ch = '\0';
  6453.         if (le_getchar(&ch) > 0) {
  6454.             debug(F101,"ttflui le_inbuf ch","",ch);
  6455.         }
  6456.     }
  6457. #endif /* NETLEBUF */
  6458.  
  6459. #ifdef TCPIPLIB
  6460. #ifdef OS2
  6461.     RequestTCPIPMutex(SEM_INDEFINITE_WAIT);
  6462. #endif /* OS2 */
  6463. #ifdef TNCODE
  6464.     if (ttnproto == NP_TELNET) {
  6465.         /* Netflui must process Telnet negotiations or get out of sync */
  6466.         if ((n = nettchk()) <= 0)
  6467.           goto exit_flui;
  6468.         while (n-- > 0) {
  6469.             ch = netinc(1);
  6470.             if (ch == IAC) {
  6471.                 extern int duplex;  /* this really shouldn't be here but ... */
  6472.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6473.                 if (tx == 1) duplex = 1;
  6474.                 else if (tx == 2) duplex = 0;
  6475.                 n = nettchk();
  6476.             }
  6477.         }
  6478.     } else
  6479. #endif /* TNCODE */
  6480.     {
  6481.         ttibuf[ttibp+ttibn] = '\0';
  6482.         debug(F111,"netflui 1",ttibuf,ttibn);
  6483. #ifdef CK_ENCRYPTION
  6484.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6485.             ck_tn_decrypt(&ttibuf[ttibp],ttibn);
  6486.         }
  6487. #endif /* CK_ENCRYPTION */
  6488.         ttibn = ttibp = 0;              /* Flush internal buffer *FIRST* */
  6489.         if (ttyfd < 1)
  6490.           goto exit_flui;
  6491.         if ((n = nettchk()) > 0) {      /* Now see what's waiting on the net */
  6492.             if (n > TTIBUFL) n = TTIBUFL;       /* and sponge it up */
  6493.             debug(F101,"netflui 2","",n);       /* ... */
  6494.             n = socket_read(ttyfd,ttibuf,n); /* into our buffer */
  6495.             if (n >= 0) ttibuf[n] = '\0';
  6496.             debug(F111,"netflui 3",ttibuf,n);
  6497. #ifdef CK_ENCRYPTION
  6498.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  6499.                 ck_tn_decrypt(&ttibuf[ttibp],n);
  6500.             }
  6501. #endif /* CK_ENCRYPTION */
  6502.             ttibuf[0] = '\0';
  6503.         }
  6504.     }
  6505. #else  /* !TCPIPLIB */
  6506.     if (ttyfd < 1)
  6507.       goto exit_flui;
  6508. #ifdef TNCODE
  6509.     if (ttnproto == NP_TELNET) {
  6510.         if ((n = ttchk()) <= 0)
  6511.           goto exit_flui;
  6512.         while (n-- >= 0) {
  6513.             /* Netflui must process Telnet negotiations or get out of sync */
  6514.             ch = ttinc(1);
  6515.             if (ch == IAC) {
  6516.                 extern int duplex;  /* this really shouldn't be here but ... */
  6517.                 int tx = tn_doop((CHAR)(ch & 0xff),duplex,netgetc);
  6518.                 if (tx == 1) duplex = 1;
  6519.                 else if (tx == 2) duplex = 0;
  6520.                 n = ttchk();
  6521.             }
  6522.         };
  6523.     } else
  6524. #endif /* TNCODE */
  6525.     if ((n = ttchk()) > 0) {
  6526.         debug(F101,"netflui non-TCPIPLIB","",n);
  6527.         while ((n--) && ttinc(1) > -1)  /* Don't worry, ttinc() is buffered */
  6528.           ;                             /* and it handles the decryption... */
  6529.     }
  6530. #endif /* TCPIPLIB */
  6531.   exit_flui:
  6532. #ifdef OS2
  6533.     ReleaseTCPIPMutex();
  6534. #endif /* OS2 */
  6535.     return(0);
  6536. }
  6537.  
  6538. #ifdef CK_KERBEROS
  6539. /* The following two functions are required for encrypted rlogin */
  6540. /* They are called with nettoc() or nettol() are transmitting    */
  6541. /* encrypted data.  They call a function to encrypt the data     */
  6542. /* and that function needs to be able to write to/read from the  */
  6543. /* network in an unimpeded manner.  Hence, these two simple fns. */
  6544. int
  6545. net_write(fd, buf, len)
  6546.     int fd;
  6547.     register const char *buf;
  6548.     int len;
  6549. {
  6550.     int cc;
  6551.     register int wrlen = len;
  6552.     do {
  6553. #ifdef TCPIPLIB
  6554.         cc = socket_write(fd, buf, wrlen);
  6555. #else
  6556.         cc = write(fd,buf,wrlen);
  6557. #endif /* TCPIPLIB */
  6558.         if (cc < 0) {
  6559.             int s_errno = socket_errno;
  6560.             debug(F101,"net_write error","",s_errno);
  6561. #ifdef OS2
  6562.             if (os2socketerror(s_errno) < 0)
  6563.                 return(-1);
  6564.             else
  6565.                 continue;
  6566. #else /* OS2 */
  6567.             if (errno == EINTR)
  6568.                 continue;
  6569.             return(-1);
  6570. #endif /* OS2 */
  6571.         }
  6572.         else {
  6573.             buf += cc;
  6574.             wrlen -= cc;
  6575.         }
  6576.     } while (wrlen > 0);
  6577.     return(len);
  6578. }
  6579. int
  6580. net_read(fd, buf, len)
  6581.     int fd;
  6582.     register char *buf;
  6583.     register int len;
  6584. {
  6585.     int cc, len2 = 0;
  6586.  
  6587.     do {
  6588. #ifdef TCPIPLIB
  6589.         cc = socket_read(fd, buf, len);
  6590. #else
  6591.         cc = read(fd,buf,len);
  6592. #endif
  6593.         if (cc < 0) {
  6594.             int s_errno = socket_errno;
  6595.             debug(F101,"net_read error","",s_errno);
  6596. #ifdef OS2
  6597.             if (os2socketerror(s_errno) < 0)
  6598.                 return(-1);
  6599. #endif /* OS2 */
  6600.             return(cc);          /* errno is already set */
  6601.         }
  6602.         else if (cc == 0) {
  6603.             netclos();
  6604.             return(len2);
  6605.         } else {
  6606.             buf += cc;
  6607.             len2 += cc;
  6608.             len -= cc;
  6609.         }
  6610.     } while (len > 0);
  6611.     return(len2);
  6612. }
  6613. #endif /* CK_KERBEROS */
  6614. #endif /* NONET */
  6615.  
  6616. /* getlocalipaddr() attempts to resolve an IP Address for the local machine.
  6617.  *   If the host is multi-homed it returns only one address.
  6618.  *
  6619.  * Two techniques are used.
  6620.  * (1) get the local host name and perform a DNS lookup, then take
  6621.  *     the first entry;
  6622.  * (2) open a UDP socket, use it to connect to a fictitious host (it's OK,
  6623.  *    no data is sent), then retrieve the local address from the socket.
  6624.  * Note: the second technique won't work on Microsoft systems.  See
  6625.  * Article ID: Q129065 PRB: Getsockname() Returns IP Address 0.0.0.0 for UDP
  6626.  */
  6627.  
  6628. /* Technique number one cannot work reliably if the machine is a laptop
  6629.  * and the hostname is associated with a physical adapter which is not
  6630.  * installed and a PPP connection is being used instead.  This is because
  6631.  * the hostname DNS lookup will succeed for the physical adapter even though
  6632.  * it would be impossible to use it.  In NT4 SP4, the gethostbyname()
  6633.  * when given the result of gethostname() returns not the real DNS entries
  6634.  * for that name+domain.  Instead it returns all of the static and dynamic
  6635.  * IP addresses assigned to any physical or virtual adapter defined in the
  6636.  * system regardless of whether or not it is installed.  The order of the
  6637.  * addresses is fixed according to the binding order in the NT registry.
  6638.  */
  6639.  
  6640. /*
  6641.  * It appears that calling gethostbyname(NULL) is more reliable than
  6642.  * calling gethostbyname(gethostname()) on Windows.  So on Windows we will
  6643.  * only call gethostbyname(NULL).
  6644.  */
  6645.  
  6646. int
  6647. getlocalipaddr() {
  6648. #ifndef datageneral
  6649.     struct sockaddr_in l_sa;
  6650.     struct sockaddr_in r_sa;
  6651.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6652.     int sock;
  6653.     int rc;
  6654.     struct in_addr laddr;
  6655.  
  6656.     /* if still not resolved, then try second strategy */
  6657.     /* This second strategy does not work on Windows */
  6658.  
  6659.     memset(&l_sa,0,slen);
  6660.     memset(&r_sa,0,slen);
  6661.  
  6662.     /* get a UDP socket */
  6663.     sock = socket(AF_INET, SOCK_DGRAM, 0);
  6664.     if (sock != -1) {
  6665.         /* connect to arbirary port and address (NOT loopback) */
  6666.         r_sa.sin_family = AF_INET;
  6667.         r_sa.sin_port = htons(IPPORT_ECHO);
  6668.  
  6669.         /* The following is an "illegal conversion" in AOS/VS */
  6670.         /* (and who knows where else) */
  6671.  
  6672. #ifdef INADDRX
  6673.         inaddrx = inet_addr("128.127.50.1");
  6674.         r_sa.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  6675. #else
  6676.         r_sa.sin_addr.s_addr = inet_addr("128.127.50.1");
  6677. #endif /* INADDRX */
  6678.         rc = connect(sock, (struct sockaddr *) &r_sa, sizeof(struct sockaddr));
  6679.         if (!rc) {                      /* get local address */
  6680.             getsockname(sock,(struct sockaddr *)&l_sa,&slen);
  6681. #ifdef TCPIPLIB
  6682.             socket_close(sock);         /* We're done with the socket */
  6683. #else
  6684.             close(sock);
  6685. #endif /* TCPIPLIB */
  6686.             if (l_sa.sin_addr.s_addr != INADDR_ANY) {
  6687.                 myxipaddr = ntohl(l_sa.sin_addr.s_addr);
  6688.                 ckstrncpy(myipaddr,(char *)inet_ntoa(l_sa.sin_addr),20);
  6689.                 debug(F110,"getlocalipaddr setting buf to",myipaddr,0);
  6690.                 return(0);
  6691.             }
  6692.         }
  6693.     }
  6694.     return getlocalipaddrs(myipaddr,sizeof(myipaddr),0);
  6695. #else /* datageneral */
  6696.     return(-1);
  6697. #endif /* datageneral */
  6698. }
  6699.  
  6700. int
  6701. getlocalipaddrs(buf,bufsz,index)
  6702.     char * buf;
  6703.     int    bufsz;
  6704.     int    index;
  6705. /* getlocalipaddrs */ {
  6706. #ifndef datageneral
  6707.     char localhost[256];
  6708.     struct hostent * host=NULL;
  6709.     struct sockaddr_in l_sa;
  6710.     struct sockaddr_in r_sa;
  6711.     GSOCKNAME_T slen = sizeof(struct sockaddr_in);
  6712.     int rc;
  6713. #ifdef COMMENT
  6714.     int sock;
  6715.     char messageBuf[60];
  6716.     struct in_addr laddr;
  6717. #endif /* COMMENT */
  6718.  
  6719.     memset(&l_sa,0,slen);
  6720.     memset(&r_sa,0,slen);
  6721.  
  6722.     /* init local address (to zero) */
  6723.     l_sa.sin_addr.s_addr = INADDR_ANY;
  6724.  
  6725. #ifdef CKGHNLHOST
  6726.     rc = gethostname(localhost, 256);
  6727.     debug(F110,"getlocalipaddrs localhost",localhost,0);
  6728. #else
  6729.     /* This doesn't work on some platforms, e.g. Solaris */
  6730.     rc = 0;
  6731.     localhost[0] = '\0';
  6732. #ifdef NT
  6733.     if ( winsock_version < 20 ) {
  6734.         rc = gethostname(localhost, 256);
  6735.         debug(F110,"getlocalipaddrs localhost",localhost,0);
  6736.     }
  6737. #endif /* NT */
  6738. #endif /* CKGHNLHOST */
  6739.     if (!rc) {
  6740.         /* resolve host name for local address */
  6741.         debug(F110,"getlocalipaddrs","calling gethostbyname()",0);
  6742.         host = gethostbyname(localhost);
  6743.         debug(F111,"getlocalipaddrs","gethostbyname() returned",host);
  6744.         if (host) {
  6745. #ifdef HADDRLIST
  6746.             host = ck_copyhostent(host);
  6747.             if ( index < 0 || index > 63 || !host->h_addr_list[index] ) {
  6748.                 buf[0] = '\0';
  6749.                 return(-1);
  6750.             }
  6751.             l_sa.sin_addr.s_addr =
  6752.               *((unsigned long *) (host->h_addr_list[index]));
  6753.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),20);
  6754.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6755.  
  6756. #ifdef COMMENT
  6757.             /* This is for reporting multiple IP Address */
  6758.             while (host->h_addr_list && host->h_addr_list[0]) {
  6759.                 l_sa.sin_addr.s_addr =
  6760.                   *((unsigned long *) (host->h_addr_list[0]));
  6761.                 ckstrncpy(messageBuf,
  6762.                         (char *)inet_ntoa(l_sa.sin_addr),60);
  6763.                 if (tcp_address) {
  6764.                     if (!strcmp(messageBuf,tcp_address))
  6765.                       ckstrncpy(myipaddr,tcp_address,20);
  6766.                 }
  6767.                 debug(F110,"getlocalipaddrs ip address list", messageBuf, 0);
  6768.                 host->h_addr_list++;
  6769.             }
  6770. #endif /* COMMENT */
  6771. #else   /* HADDRLIST */
  6772.             if (index != 0) {
  6773.                 buf[0] = '\0';
  6774.                 return(-1);
  6775.             }
  6776.             l_sa.sin_addr.s_addr = *((unsigned long *) (host->h_addr));
  6777.             ckstrncpy(buf,(char *)inet_ntoa(l_sa.sin_addr),bufsz);
  6778.             debug(F110,"getlocalipaddrs setting buf to",buf,0);
  6779. #endif  /* HADDRLIST */
  6780.             return(0);
  6781.         } else debug(F110,
  6782.                      "getlocalipaddrs: gethostbyname() failed",
  6783.                      localhost,
  6784.                      0
  6785.                      );
  6786.     }
  6787. #endif /* datageneral */
  6788.     return(-1);
  6789. }
  6790.  
  6791. #ifdef RLOGCODE                 /* TCP/IP RLOGIN protocol support code */
  6792. int
  6793. rlog_naws() {
  6794.     struct rlog_naws {
  6795.         unsigned char id[4];
  6796.         unsigned short rows, cols, ypix, xpix;
  6797.     } nawsbuf;
  6798.  
  6799.     if (ttnet != NET_TCPB)
  6800.       return 0;
  6801.     if (ttnproto != NP_RLOGIN
  6802. #ifdef CK_KERBEROS
  6803.         && ttnproto != NP_K4LOGIN
  6804.         && ttnproto != NP_EK4LOGIN
  6805.         && ttnproto != NP_K5LOGIN
  6806.         && ttnproto != NP_EK5LOGIN
  6807. #endif /* CK_KERBEROS */
  6808.          )
  6809.       return 0;
  6810.     if (!TELOPT_ME(TELOPT_NAWS))
  6811.       return 0;
  6812.  
  6813.     debug(F100,"rlogin Window Size sent","",0);
  6814.  
  6815.     nawsbuf.id[0] = nawsbuf.id[1] = 0377;
  6816.     nawsbuf.id[2] = nawsbuf.id[3] = 's';
  6817. #ifdef OS2
  6818.     nawsbuf.rows = htons((unsigned short) (VscrnGetHeight(VTERM)
  6819.                           -(tt_status[VTERM]?1:0)));
  6820.     nawsbuf.cols = htons((unsigned short) VscrnGetWidth(VTERM));
  6821. #else /* OS2 */
  6822.     nawsbuf.rows = htons((unsigned short) tt_rows);
  6823.     nawsbuf.cols = htons((unsigned short) tt_cols);
  6824. #endif /* OS2 */
  6825.     nawsbuf.ypix = htons(0);            /* y pixels */
  6826.  
  6827.     nawsbuf.xpix = htons(0);            /* x pixels */
  6828.     if (ttol((CHAR *)(&nawsbuf), sizeof(nawsbuf)) < 0)
  6829.       return(-1);
  6830.     return(0);
  6831. }
  6832.  
  6833. #ifdef OS2ORUNIX
  6834. #define RLOGOUTBUF
  6835. #endif /* OS2 */
  6836. static int
  6837. #ifdef CK_ANSIC
  6838. rlog_ini(CHAR * hostname, int port,
  6839.          struct sockaddr_in * l_addr, struct sockaddr_in * r_addr)
  6840. #else /* CK_ANSIC */
  6841. rlog_ini(hostname, port, l_addr, r_addr)
  6842.     CHAR * hostname;
  6843.     int port;
  6844.     struct sockaddr_in * l_addr;
  6845.     struct sockaddr_in * r_addr;
  6846. #endif /* CK_ANSIC */
  6847. /* rlog_ini */ {
  6848.  
  6849. #ifdef RLOGOUTBUF
  6850.     char outbuf[512];
  6851.     int  outbytes=0;
  6852. #endif /* RLOGOUTBUF */
  6853.     int flag = 0;
  6854. #define TERMLEN 16
  6855. #define CONSPDLEN 16
  6856.     CHAR localuser[UIDBUFLEN+1];
  6857.     CHAR remoteuser[UIDBUFLEN+1];
  6858.     int userlen = 0;
  6859.     CHAR term_speed[TERMLEN+CONSPDLEN+1];
  6860. #ifdef CONGSPD
  6861.     long conspd = -1L;
  6862. #endif /* CONGSPD */
  6863. #ifdef OS2
  6864.     extern int tt_type, max_tt;
  6865.     extern struct tt_info_rec tt_info[];
  6866. #endif /* OS2 */
  6867.     int i, n;
  6868.  
  6869.     int rc = 0;
  6870.     tn_reset();                 /* This call will reset all of the Telnet */
  6871.                                 /* options and then quit.  We need to do  */
  6872.                                 /* this since we use the Telnet options   */
  6873.                                 /* to hold various state information      */
  6874.     duplex = 0;                 /* Rlogin is always remote echo */
  6875.  
  6876. #ifdef CK_TTGWSIZ
  6877. /*
  6878.   But compute the values anyway before the first read since the out-
  6879.   of-band NAWS request would arrive before the first data byte (NULL).
  6880. */
  6881. #ifdef OS2
  6882.     /* Console terminal screen rows and columns */
  6883.     debug(F101,"rlog_ini tt_rows 1","",VscrnGetHeight(VTERM)
  6884.            -(tt_status[VTERM]?1:0));
  6885.     debug(F101,"rlog_ini tt_cols 1","",VscrnGetWidth(VTERM));
  6886.     /* Not known yet */
  6887.     if (VscrnGetWidth(VTERM) < 0 ||
  6888.         VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0) < 0) {
  6889.         ttgwsiz();                      /* Try to get screen dimensions */
  6890.     }
  6891.     debug(F101,
  6892.           "rlog_ini tt_rows 2",
  6893.           "",
  6894.           VscrnGetHeight(VTERM)-(tt_status[VTERM]?1:0)
  6895.           );
  6896.     debug(F101,"rlog_ini tt_cols 2","",VscrnGetWidth(VTERM));
  6897. #else /* OS2 */
  6898.     debug(F101,"rlog_ini tt_rows 1","",tt_rows);
  6899.     debug(F101,"rlog_ini tt_cols 1","",tt_cols);
  6900.     if (tt_rows < 0 || tt_cols < 0) {   /* Not known yet */
  6901.         ttgwsiz();                      /* Try to find out */
  6902.     }
  6903.     debug(F101,"rlog_ini tt_rows 2","",tt_rows);
  6904.     debug(F101,"rlog_ini tt_cols 2","",tt_cols);
  6905. #endif /* OS2 */
  6906. #endif /* CK_TTGWSIZ */
  6907.  
  6908.     ttflui();                           /* Start by flushing the buffers */
  6909.  
  6910.     rlog_mode = RL_COOKED;
  6911.  
  6912.     /* Determine the user's local username ... */
  6913.  
  6914.     localuser[0] = '\0';
  6915. #ifdef NT
  6916.     {
  6917.         char localuid[UIDBUFLEN+1];
  6918.         ckstrncpy((char *)localuser,(char *)GetLocalUser(),UIDBUFLEN);
  6919.     }
  6920.  
  6921.     if ( !localuser[0] )
  6922. #endif /* NT */
  6923.     {
  6924.         char * user = getenv("USER");
  6925.         if (!user)
  6926.           user = "";
  6927.         userlen = strlen(user);
  6928.         debug(F111,"rlogin getenv(USER)",user,userlen);
  6929.         ckstrncpy((char *)localuser,user,UIDBUFLEN);
  6930.         debug(F110,"rlog_ini localuser 1",localuser,0);
  6931.     }
  6932.     if ( !localuser[0] )
  6933.         strcpy((char *)localuser,"unknown");
  6934.     else if (ck_lcname) {
  6935.         cklower((char *)localuser);
  6936.         debug(F110,"rlog_ini localuser 2",localuser,0);
  6937.     }
  6938.  
  6939.     /* And the username to login with */
  6940.     if (uidbuf[0]) {
  6941.         ckstrncpy((char *)remoteuser,uidbuf,UIDBUFLEN);
  6942.         debug(F110,"rlog_ini remoteuser 1",remoteuser,0);
  6943.     } else if (localuser[0]) {
  6944.         ckstrncpy((char *)remoteuser,(char *)localuser,UIDBUFLEN);
  6945.         debug(F110,"rlog_ini remoteuser 2",remoteuser,0);
  6946.     } else {
  6947.         remoteuser[0] = '\0';
  6948.         debug(F110,"rlog_ini remoteuser 3",remoteuser,0);
  6949.     }
  6950.     if (ck_lcname)
  6951.       cklower((char *)remoteuser);
  6952.     debug(F110,"rlog_ini remoteuser 4",remoteuser,0);
  6953.  
  6954.     /* The command to issue is the terminal type and speed */
  6955.     term_speed[0] = '\0';
  6956.     if (tn_term) {                      /* SET TELNET TERMINAL-TYPE value */
  6957.         if (*tn_term) {                 /* (if any) takes precedence. */
  6958.             ckstrncpy((char *)term_speed, tn_term, TERMLEN);
  6959.             flag = 1;
  6960.         }
  6961.     } else {                            /* Otherwise the local terminal type */
  6962. #ifdef OS2
  6963.         /* In terminal-emulating versions, it's the SET TERM TYPE value */
  6964.         ckstrncpy(term_speed, (tt_type >= 0 && tt_type <= max_tt) ?
  6965.                 tt_info[tt_type].x_name : "network", TERMLEN);
  6966. #else
  6967.         /* In the others, we just look at the TERM environment variable */
  6968.         {
  6969.             char *p = getenv("TERM");
  6970.             if (p)
  6971.               ckstrncpy((char *)term_speed,p,TERMLEN);
  6972.             else
  6973.               term_speed[0] = '\0';
  6974. #ifdef VMS
  6975.             for (p = (char *) term_speed; *p; p++) {
  6976.                 if (*p == '-' && (!strcmp(p,"-80") || !strcmp(p,"-132")))
  6977.                   break;
  6978.                 else if (isupper(*p))
  6979.                   *p = tolower(*p);
  6980.             }
  6981.             *p = '\0';
  6982. #endif /* VMS */
  6983.         }
  6984. #endif /* OS2 */
  6985.     }
  6986.     n = strlen((char *)term_speed);
  6987.     if (n > 0) {                        /* We have a terminal type */
  6988.         if (!flag) {                    /* If not user-specified */
  6989.             for (i = 0; i < n; i++)     /* then lowercase it.    */
  6990.               if (isupper(term_speed[i]))
  6991.                 term_speed[i] = tolower(term_speed[i]);
  6992.         }
  6993.         debug(F110,"rlog_ini term_speed 1",term_speed,0);
  6994.  
  6995. #ifdef CONGSPD
  6996.         /* conspd() is not yet defined in all ck*tio.c modules */
  6997.         conspd = congspd();
  6998.         if (conspd > 0L) {
  6999.             ckstrncat((char *)term_speed,"/",sizeof(term_speed));
  7000.             ckstrncat((char *)term_speed,ckltoa(conspd),sizeof(term_speed));
  7001.         } else
  7002. #endif /* CONGSPD */
  7003.           ckstrncat((char *)term_speed,"/19200",sizeof(term_speed));
  7004.         debug(F110,"rlog_ini term_speed 2",term_speed,0);
  7005.     } else {
  7006.         term_speed[0] = '\0';
  7007.         debug(F110,"rlog_ini term_speed 3",term_speed,0);
  7008.     }
  7009.  
  7010. #ifdef CK_KERBEROS
  7011.     if (ttnproto == NP_K4LOGIN || ttnproto == NP_EK4LOGIN ||
  7012.         ttnproto == NP_K5LOGIN || ttnproto == NP_EK5LOGIN) {
  7013.         int kver, encrypt, rc;
  7014.         switch (ttnproto) {
  7015.           case NP_K4LOGIN:
  7016.             kver = 4;
  7017.             encrypt = 0;
  7018.             break;
  7019.           case NP_EK4LOGIN:
  7020.             kver = 4;
  7021.             encrypt = 1;
  7022.             break;
  7023.           case NP_K5LOGIN:
  7024.             kver = 5;
  7025.             encrypt = 0;
  7026.             break;
  7027.           case NP_EK5LOGIN:
  7028.             kver = 5;
  7029.             encrypt = 1;
  7030.             break;
  7031.         default:
  7032.             kver = 0;
  7033.             encrypt = 0;
  7034.         }
  7035.         rc = ck_krb_rlogin(hostname, port,
  7036.                            localuser, remoteuser, term_speed,
  7037.                            l_addr, r_addr, kver, encrypt);
  7038.         if (!rc) {                      /* success */
  7039.             TELOPT_ME(TELOPT_NAWS) = 1;
  7040.             rc = rlog_naws();
  7041.         }
  7042.         return(rc);
  7043.     } else
  7044. #endif /* CK_KERBEROS */
  7045.     if (ttnproto == NP_RLOGIN) {
  7046. #ifdef RLOGOUTBUF
  7047.         /*
  7048.          *  The rcmds start the connection with a series of init data:
  7049.          *
  7050.          *    a port number upon which client is listening for stderr data
  7051.          *    the user's name on the client machine
  7052.          *    the user's name on the server machine
  7053.          *    the terminal_type/speed or command to execute
  7054.          */
  7055.         outbuf[outbytes++] = 0;
  7056.         strcpy((char *)outbuf+outbytes,(char *)localuser);
  7057.         outbytes += strlen((char *)localuser) + 1;
  7058.         strcpy((char *)outbuf+outbytes,(char *)remoteuser);
  7059.         outbytes += strlen((char *)remoteuser) + 1;
  7060.         strcpy((char *)outbuf+outbytes,(char *)term_speed);
  7061.         outbytes += strlen((char *)term_speed) + 1;
  7062.         rc = ttol((CHAR *)outbuf,outbytes);
  7063. #else /* RLOGOUTBUF */
  7064.         ttoc(0);                        /* Send an initial NUL as wake-up */
  7065.         /* Send each variable with the trailing NUL */
  7066.         rc = ttol(localuser,strlen((char *)localuser)+1);
  7067.         if (rc > 0)
  7068.           rc = ttol(remoteuser,strlen((char *)remoteuser)+1);
  7069.         if (rc > 0)
  7070.           rc = ttol(term_speed,strlen((char *)term_speed)+1);
  7071. #endif /* RLOGOUTBUF */
  7072.  
  7073.         /* Now we are supposed to get back a single NUL as confirmation */
  7074.         errno = 0;
  7075.         rc = ttinc(60);
  7076.         debug(F101,"rlogin first ttinc","",rc);
  7077.         if (rc > 0) {
  7078.             debug(F101,"rlogin ttinc 1","",rc);
  7079.             printf(
  7080.                "Rlogin protocol error - 0x%x received instead of 0x00\n", rc);
  7081.             return(-1);
  7082.         } else if (rc < 0) {
  7083.             debug(F101,"rlogin ttinc errno","",errno);
  7084.             /* printf("Network error: %d\n", errno); */
  7085.             return(-1);
  7086.         }
  7087.     }
  7088.     return(0);
  7089. }
  7090.  
  7091. #ifdef TCPIPLIB
  7092. static VOID
  7093. rlog_oob(oobdata, count) CHAR * oobdata; int count; {
  7094.     int i;
  7095.  
  7096.     debug(F111,"rlogin out_of_band","count",count);
  7097.  
  7098.     for (i = 0; i<count; i++)   {
  7099.         debug(F101,"rlogin out_of_band","",oobdata[i]);
  7100.                 if (oobdata[i] & 0x01)
  7101.                         continue;
  7102.  
  7103.         if (oobdata[i] & 0x02) { /* Flush Buffered Data not yet displayed */
  7104.             debug(F101,"rlogin Flush Buffered Data command","",oobdata[i]);
  7105.  
  7106.             /* Only flush the data if in fact we are in a mode that won't */
  7107.             /* get out of sync.  Ie, not when we are in protocol mode.    */
  7108.             switch ( what ) {
  7109.             case W_NOTHING:
  7110.             case W_CONNECT:
  7111.             case W_COMMAND:
  7112.                 ttflui();
  7113.                 break;
  7114.             }
  7115.         }
  7116.         if (oobdata[i] & 0x10) {        /* Switch to RAW mode */
  7117.             debug(F101,"rlogin Raw Mode command","",oobdata[i]);
  7118.             rlog_mode = RL_RAW;
  7119.         }
  7120.  
  7121.         if (oobdata[i] & 0x20) {        /* Switch to COOKED mode */
  7122.             debug(F101,"rlogin Cooked Mode command","",oobdata[i]);
  7123.             rlog_mode = RL_COOKED;
  7124.         }
  7125.         if (oobdata[i] & 0x80)
  7126.         {        /* Send Window Size Info */
  7127.             debug(F101,"rlogin Window Size command","",oobdata[i]);
  7128.             /* Remember to send WS Info when Window Size changes */
  7129.             if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7130.                 TELOPT_ME(TELOPT_NAWS) = 1;
  7131.                 rlog_naws();
  7132.             }
  7133.         }
  7134.     }
  7135. }
  7136. #else /* TCPIPLIB */
  7137. static SIGTYP
  7138. rlogoobh(sig) int sig; {
  7139. #ifdef SOLARIS
  7140.     char                                /* Or should it be char for all? */
  7141. #else
  7142.     CHAR
  7143. #endif /* SOLARIS */
  7144.       oobdata;
  7145.  
  7146.     /* int  count = 0; */ /* (not used) */
  7147.  
  7148.     while (recv(ttyfd, &oobdata, 1, MSG_OOB) < 0) {
  7149.       /*
  7150.        * We need to do some special processing here.
  7151.        * Just in case the socket is blocked for input
  7152.        *
  7153.        */
  7154.         switch (errno) {
  7155.           case EWOULDBLOCK:
  7156.             break;
  7157.           default:
  7158.             return;
  7159.         }
  7160.     }
  7161.     debug(F101,"rlogin out_of_band","",oobdata);
  7162.     if (oobdata == 0x02) {      /* Flush Buffered Data not yet displayed */
  7163.         debug(F101,"rlogin Flush Buffered Data command","",oobdata);
  7164.         netflui();
  7165.     }
  7166.     if (oobdata & 0x10) {               /* Switch to raw mode */
  7167.         debug(F101,"rlogin Raw Mode command","",oobdata);
  7168.         rlog_mode = RL_RAW;
  7169.     }
  7170.     if (oobdata & 0x20) {               /* Switch to cooked mode */
  7171.         debug(F101,"rlogin Cooked Mode command","",oobdata);
  7172.         rlog_mode = RL_COOKED;
  7173.     }
  7174.     if (oobdata & 0x80) {                 /* Send Window Size Info */
  7175.         debug(F101,"rlogin Window Size command","",oobdata);
  7176.         /* Remember to send WS Info when Window Size changes */
  7177.         if ( !TELOPT_ME(TELOPT_NAWS) ) {
  7178.             TELOPT_ME(TELOPT_NAWS) = 1;
  7179.             rlog_naws();
  7180.         }
  7181.     }
  7182. }
  7183. #endif /* TCPIPLIB */
  7184. #endif /* RLOGCODE */
  7185.  
  7186. /* Send network BREAK */
  7187. /*
  7188.   Returns -1 on error, 0 if nothing happens, 1 if BREAK sent successfully.
  7189. */
  7190. int
  7191. netbreak() {
  7192.     CHAR buf[3];
  7193.     if (ttnet == NET_TCPB) {
  7194.         if (ttnproto == NP_TELNET) {
  7195. #ifdef TNCODE
  7196.             buf[0] = (CHAR) IAC; buf[1] = (CHAR) BREAK; buf[2] = (CHAR) 0;
  7197.             if (
  7198. #ifdef OS2
  7199.                 nettol((char *) buf, 2)
  7200. #else
  7201.                 ttol(buf, 2)
  7202. #endif /* OS2 */
  7203.                 < 2)
  7204.               return(-1);
  7205.             if (tn_deb || debses || deblog) {
  7206.                 extern char tn_msg[];
  7207.                 ckmakmsg(tn_msg,TN_MSG_LEN,"TELNET SENT ",TELCMD(BREAK),
  7208.                           NULL,NULL);
  7209.                 debug(F101,tn_msg,"",BREAK);
  7210.                 if (debses || tn_deb) tn_debug(tn_msg);
  7211.             }
  7212.             return(1);
  7213. #else
  7214.             debug(F100,"netbreak no TNCODE","",0);
  7215.             return(0);
  7216. #endif /* TNCODE */
  7217.         }
  7218.         /* Insert other TCP/IP protocols here */
  7219.     }
  7220.     /* Insert other networks here */
  7221.     return(0);
  7222. }
  7223. #endif /* NETCONN */
  7224.  
  7225.  
  7226. #ifdef NETCONN
  7227. #ifdef SUNX25
  7228. /*
  7229.   SunLink X.25 support by Marcello Frutig, Catholic University,
  7230.   Rio de Janeiro, Brazil, 1990.
  7231. */
  7232.  
  7233. /* PAD X.3, X.28 and X.29 support */
  7234.  
  7235. static CHAR x29err[MAXPADPARMS+3] = { X29_ERROR, INVALID_PAD_PARM, '\0' };
  7236.  
  7237. /* Initialize PAD */
  7238.  
  7239. extern CHAR padparms[];
  7240.  
  7241. VOID
  7242. initpad() {
  7243.   padparms[PAD_BREAK_CHARACTER]        = 0;  /* Break character */
  7244.   padparms[PAD_ESCAPE]                 = 1;  /* Escape permitted */
  7245.   padparms[PAD_ECHO]                   = 1;  /* Kermit PAD does echo */
  7246.   padparms[PAD_DATA_FORWARD_CHAR]      = 2;  /* forward character CR */
  7247.   padparms[PAD_DATA_FORWARD_TIMEOUT]   = 0;  /* no timeout forward condition */
  7248.   padparms[PAD_FLOW_CONTROL_BY_PAD]    = 0;  /* not used */
  7249.   padparms[PAD_SUPPRESSION_OF_SIGNALS] = 1;  /* allow PAD service signals */
  7250.   padparms[PAD_BREAK_ACTION]           = 21; /* brk action: INT pk + brk ind*/
  7251.   padparms[PAD_SUPPRESSION_OF_DATA]    = 0;  /* no supression of user data */
  7252.   padparms[PAD_PADDING_AFTER_CR]       = 0;  /* no padding after CR */
  7253.   padparms[PAD_LINE_FOLDING]           = 0;  /* no line fold */
  7254.   padparms[PAD_LINE_SPEED]             = 0;  /* line speed - don't care */
  7255.   padparms[PAD_FLOW_CONTROL_BY_USER]   = 0;  /* flow cont of PAD - not used */
  7256.   padparms[PAD_LF_AFTER_CR]            = 0;  /* no LF insertion after CR */
  7257.   padparms[PAD_PADDING_AFTER_LF]       = 0;  /* no padding after LF */
  7258.   padparms[PAD_EDITING]                = 1;  /* can edit */
  7259.   padparms[PAD_CHAR_DELETE_CHAR]       = 8;  /* character delete character */
  7260.   padparms[PAD_BUFFER_DELETE_CHAR]     = 21; /* buffer delete character */
  7261.   padparms[PAD_BUFFER_DISPLAY_CHAR]    = 18; /* buffer display character */
  7262. }
  7263.  
  7264. /* Set PAD parameters */
  7265.  
  7266. VOID
  7267. setpad(s,n) CHAR *s; int n; {
  7268.     int i;
  7269.     CHAR *ps = s;
  7270.  
  7271.     if (n < 1) {
  7272.         initpad();
  7273.     } else {
  7274.         for (i = 0; i < n; i++) {
  7275.             if (*ps > MAXPADPARMS)
  7276.               x29err[i+2] = *ps;
  7277.             else
  7278.               padparms[*ps] = *(ps+1);
  7279.             ps += 2;
  7280.         }
  7281.     }
  7282. }
  7283.  
  7284. /* Read PAD parameters */
  7285.  
  7286. VOID
  7287. readpad(s,n,r) CHAR *s; int n; CHAR *r; {
  7288.     int i;
  7289.     CHAR *ps = s;
  7290.     CHAR *pr = r;
  7291.  
  7292.     *pr++ = X29_PARAMETER_INDICATION;
  7293.     if (n > 0) {
  7294.         for (i = 0; i < n; i++, ps++) {
  7295.             if (*ps > MAXPADPARMS) {
  7296.                 x29err[i+2] = *ps++;
  7297.             } else {
  7298.                 *pr++ = *ps;
  7299.                 *pr++ = padparms[*ps++];
  7300.             }
  7301.         }
  7302.     } else {
  7303.         for (i = 1; i < MAXPADPARMS; i++) {
  7304.             *pr++ = i;
  7305.             *pr++ = padparms[i];
  7306.         }
  7307.     }
  7308. }
  7309.  
  7310. int
  7311. qbitpkt(s,n) CHAR *s; int n; {
  7312.     CHAR *ps = s;
  7313.     int x29cmd = *ps;
  7314.     CHAR *psa = s+1;
  7315.     CHAR x29resp[(MAXPADPARMS*2)+1];
  7316.  
  7317.     switch (x29cmd) {
  7318.  
  7319.         case X29_SET_PARMS:
  7320.             setpad (ps+1,n/2);
  7321.             if ((int)strlen((char *)x29err) > 2) {
  7322.                 ttol(x29err,(int)strlen((char *)x29err));
  7323.                 x29err[2] = '\0';
  7324.             }
  7325.             return (-2);
  7326.         case X29_READ_PARMS:
  7327.             readpad (ps+1,n/2,x29resp);
  7328.             setqbit ();
  7329.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7330.             if ((int)strlen((char *)x29err) > 2) {
  7331.                 ttol(x29err,(int)strlen((char *)x29err));
  7332.                 x29err[2] = '\0';
  7333.             }
  7334.             resetqbit();
  7335.             break;
  7336.         case X29_SET_AND_READ_PARMS:
  7337.             setpad (ps+1,n/2);
  7338.             readpad (ps+1,n/2,x29resp);
  7339.             setqbit();
  7340.             ttol(x29resp,(n>1)?(n+1):(2*MAXPADPARMS+1));
  7341.             if ((int)strlen((char *)x29err) > 2) {
  7342.                 ttol (x29err,(int)strlen((char *)x29err));
  7343.                 x29err [2] = '\0';
  7344.             }
  7345.             resetqbit();
  7346.             return (-2);
  7347.         case X29_INVITATION_TO_CLEAR:
  7348.             (VOID) x25clear();
  7349.             return (-1);
  7350.         case X29_INDICATION_OF_BREAK:
  7351.             break;
  7352.     }
  7353.     return (0);
  7354. }
  7355.  
  7356. /* PAD break action processor */
  7357.  
  7358. VOID
  7359. breakact() {
  7360.     extern char x25obuf[MAXOX25];
  7361.     extern int obufl;
  7362.     extern int active;
  7363.     extern unsigned char tosend;
  7364.     static CHAR indbrk[3] = {
  7365.         X29_INDICATION_OF_BREAK,
  7366.         PAD_SUPPRESSION_OF_DATA,
  7367.         1
  7368.     };
  7369.     CHAR intudat, cause, diag;
  7370.  
  7371.     if (x25stat() < 0) return;  /* Ignore if no virtual call established */
  7372.  
  7373.     if (padparms[PAD_BREAK_ACTION] != 0) /* Forward condition */
  7374.         if (ttol((CHAR *)x25obuf,obufl) < 0) {
  7375.             perror ("\r\nCan't send characters");
  7376.             active = 0;
  7377.         } else {
  7378.             bzero (x25obuf,sizeof(x25obuf));
  7379.             obufl = 0;
  7380.             tosend = 0;
  7381.         };
  7382.  
  7383.     switch (padparms[PAD_BREAK_ACTION]) {
  7384.  
  7385.        case 0 : break;                  /* do nothing */
  7386.        case 1 : /* send interrupt packet with interrupt user data field = 1 */
  7387.                 intudat = 1;
  7388.                 x25intr (intudat);
  7389.                 break;
  7390.        case 2 : /* send reset packet with cause and diag = 0 */
  7391.                 cause = diag = 0;
  7392.                 x25reset (cause,diag);
  7393.                 break;
  7394.        case 5 : /* send interrupt packet with interrupt user data field = 0 */
  7395.                 intudat = 0;
  7396.                 x25intr (intudat);
  7397.                 setqbit ();
  7398.                 /* send indication of break without a parameter field */
  7399.                 ttoc(X29_INDICATION_OF_BREAK);
  7400.                 resetqbit ();
  7401.                 break;
  7402.        case 8 : active = 0;             /* leave data transfer */
  7403.                 conol ("\r\n");
  7404.                 break;
  7405.        case 21: /* send interrupt packet with interrupt user data field = 0 */
  7406.                 intudat = 0;
  7407.                 x25intr (intudat);
  7408.                 setpad (indbrk+1,2);    /* set pad to discard input */
  7409.                 setqbit ();
  7410.                 /* send indication of break with parameter field */
  7411.                 ttol (indbrk,sizeof(indbrk));
  7412.                 resetqbit ();
  7413.                 break;
  7414.      }
  7415. }
  7416.  
  7417. /* X.25 support functions */
  7418.  
  7419. X25_CAUSE_DIAG diag;
  7420.  
  7421. /*
  7422.   Convert a null-terminated string representing an X.121 address
  7423.   to a packed BCD form.
  7424. */
  7425. int
  7426. pkx121(str,bcd) char *str; CHAR *bcd; {
  7427.     int i, j;
  7428.     u_char c;
  7429.  
  7430.     i = j = 0;
  7431.     while (str[i]) {
  7432.         if (i >= 15 || str [i] < '0' || str [i] > '9')
  7433.           return (-1);
  7434.         c = str [i] - '0';
  7435.         if (i & 1)
  7436.           bcd [j++] |= c;
  7437.         else
  7438.           bcd [j] = c << 4;
  7439.         i++;
  7440.     }
  7441.     return (i);
  7442. }
  7443.  
  7444. /* Reads and prints X.25 diagnostic */
  7445.  
  7446. int
  7447. x25diag () {
  7448.     int i;
  7449.  
  7450.     bzero ((char *)&diag,sizeof(diag));
  7451.     if (ioctl(ttyfd,X25_RD_CAUSE_DIAG,&diag)) {
  7452.         perror ("Reading X.25 diagnostic");
  7453.         return(-1);
  7454.     }
  7455.     if (diag.datalen > 0) {
  7456.         printf ("X.25 Diagnostic :");
  7457.         for (i = 0; i < (int)diag.datalen; i++)
  7458.           printf(" %02h",diag.data[i])+
  7459.         printf ("\r\n");
  7460.     }
  7461.     return(0);
  7462. }
  7463.  
  7464. /* X.25 Out-of-Band Signal Handler */
  7465.  
  7466. SIGTYP
  7467. x25oobh(foo) int foo; {
  7468.     int oobtype;
  7469.     u_char oobdata;
  7470.     int t;
  7471.  
  7472.     (VOID) signal(SIGURG,x25oobh);
  7473.     do {
  7474.         if (ioctl(ttyfd,X25_OOB_TYPE,&oobtype)) {
  7475.             perror ("Getting signal type");
  7476.             return;
  7477.         }
  7478.         switch (oobtype) {
  7479.           case INT_DATA:
  7480.             if (recv(ttyfd,(char *)&oobdata,1,MSG_OOB) < 0) {
  7481.                 perror ("Receiving X.25 interrupt data");
  7482.                 return;
  7483.             }
  7484.             t = oobdata;
  7485.             printf ("\r\nInterrupt received, data = %d\r\n", t);
  7486.             break;
  7487.           case VC_RESET:
  7488.             printf ("\r\nVirtual circuit reset\r\n");
  7489.             x25diag ();
  7490.             break;
  7491.           case N_RESETS:
  7492.             printf ("\r\nReset timeout\r\n");
  7493.             break;
  7494.           case N_CLEARS:
  7495.             printf ("\r\nClear timeout\r\n");
  7496.             break;
  7497.           case MSG_TOO_LONG:
  7498.             printf ("\r\nMessage discarded, too long\r\n");
  7499.             break;
  7500.           default:
  7501.             if (oobtype) printf("\r\nUnknown oob type %d\r\n",oobtype);
  7502.             break;
  7503.         }
  7504.     } while (oobtype);
  7505. }
  7506.  
  7507. /* Send a X.25 interrupt packet */
  7508.  
  7509. int
  7510. #ifdef CK_ANSIC
  7511. x25intr(char intr)
  7512. #else
  7513. x25intr(intr) char intr;
  7514. #endif /* CK_ANSIC */
  7515. /* x25intr */ {
  7516.     if (send(ttyfd,&intr,1,MSG_OOB) < 0) return(-1);
  7517.     debug(F100,"X.25 intr","",0);
  7518.     return(0);
  7519. }
  7520.  
  7521. /* Reset X.25 virtual circuit */
  7522. int
  7523. #ifdef CK_ANSIC
  7524. x25reset(char cause, char diagn)
  7525. #else
  7526. x25reset(cause, diagn) char cause; char diagn;
  7527. #endif /* CK_ANSIC */
  7528. /* x25reset */ {
  7529.     bzero ((char *)&diag,sizeof(diag));
  7530.     diag.flags   = 0;
  7531.     diag.datalen = 2;
  7532.     diag.data[0] = cause;
  7533.     diag.data[1] = diagn;
  7534.     if (ioctl(ttyfd,X25_WR_CAUSE_DIAG,&diag) < 0)
  7535.       return(-1);
  7536.     debug(F100,"X.25 reset","",0);
  7537.     return(0);
  7538. }
  7539.  
  7540. /* Clear X.25 virtual circuit */
  7541. int
  7542. x25clear() {
  7543.     int i;
  7544.     debug(F100,"X.25 clear","",0);
  7545.     bzero ((char *)&diag,sizeof(diag));
  7546.     diag.flags = (1 << DIAG_TYPE);
  7547.     diag.datalen = 2;
  7548.     diag.data[0] = 0;
  7549.     diag.data[1] = 0;
  7550.     ioctl (ttyfd,X25_WR_CAUSE_DIAG,&diag); /* Send Clear Request */
  7551.     return(ttclos(0));                  /* Close socket */
  7552. }
  7553.  
  7554. /* X.25 status */
  7555. int
  7556. x25stat() {
  7557.     if (ttyfd == -1) return (-1);
  7558.     return(0);
  7559. }
  7560.  
  7561. /* Set Q_BIT on */
  7562. VOID
  7563. setqbit() {
  7564.     static int qbiton = 1 << Q_BIT;
  7565.     ioctl (ttyfd,X25_SEND_TYPE,&qbiton);
  7566. }
  7567.  
  7568. /* Set Q_BIT off */
  7569. VOID
  7570. resetqbit() {
  7571.     static int qbitoff = 0;
  7572.     ioctl (ttyfd,X25_SEND_TYPE,&qbitoff);
  7573. }
  7574.  
  7575. /* Read n characters from X.25 circuit into buf */
  7576.  
  7577. int
  7578. x25xin(n,buf) int n; CHAR *buf; {
  7579.     register int x, c;
  7580.     int qpkt;
  7581.  
  7582.     do {
  7583.         x = read(ttyfd,buf,n);
  7584.         if (buf[0] & (1 << Q_BIT)) { /* If Q_BIT packet, process it */
  7585.             /* If return -1 : invitation to clear; -2 : PAD changes */
  7586.             if ((c=qbitpkt(buf+1,x-2)) < 0) return(c);
  7587.             qpkt = 1;
  7588.         } else qpkt = 0;
  7589.     } while (qpkt);
  7590.  
  7591. #ifdef COMMENT                  /* Disabled by Stephen Riehm 19.12.97 */
  7592.     /* BUG!
  7593.      * if buf[] is full, then this null lands in nirvana!
  7594.      * I was unable to find any code which needs a trailing null in buf[]
  7595.      */
  7596.     if (x > 0) buf[x] = '\0';
  7597. #endif /* COMMENT */
  7598.     if (x < 1) x = -1;
  7599.     debug(F101,"x25xin x","",x);
  7600.  
  7601.     return(x);
  7602. }
  7603.  
  7604. #ifdef COMMENT /* NO LONGER NEEDED! */
  7605. /* X.25 read a line */
  7606.  
  7607. int
  7608. #ifdef PARSENSE
  7609. #ifdef CK_ANSIC
  7610. x25inl(CHAR *dest, int max,int timo, CHAR eol, CHAR start)
  7611. #else
  7612. x25inl(dest,max,timo,eol,start) int max,timo; CHAR *dest, eol, start;
  7613. #endif /* CK_ANSIC */
  7614. #else /* not PARSENSE */
  7615. #ifdef CK_ANSIC
  7616. x25inl(CHAR *dest, int max,int timo, CHAR eol)
  7617. #else
  7618. x25inl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  7619. #endif /* __SDTC__ */
  7620. #endif /*PARSENSE */
  7621.  /* x25inl */ {
  7622.     CHAR *pdest;
  7623.     int pktype, goteol, rest, n;
  7624.     int i, flag = 0;
  7625.     extern int ttprty, ttpflg;
  7626.     int ttpmsk;
  7627.  
  7628.     ttpmsk = (ttprty) ? 0177 : 0377;    /* Set parity stripping mask */
  7629.  
  7630.     debug(F101,"x25inl max","",max);
  7631.     debug(F101,"x25inl eol","",eol);
  7632.     pdest  = dest;
  7633.     rest   = max;
  7634.     goteol = 0;
  7635.     do {
  7636.         n = read(ttyfd,pdest,rest);
  7637.         n--;
  7638.         pktype = *pdest & 0x7f;
  7639.         switch (pktype) {
  7640.           case 1 << Q_BIT:
  7641.             if (qbitpkt(pdest+1,--n) < 0) return(-2);
  7642.             break;
  7643.           default:
  7644.             if (flag == 0) { /* if not in packet, search start */
  7645.                 for (i = 1; (i < n) &&
  7646.                      !(flag = ((dest[i] & 0x7f) == start));
  7647.                      i++);
  7648.                 if (flag == 0) { /* not found, discard junk */
  7649.                     debug(F101,"x25inl skipping","",n);
  7650.                     continue;
  7651.                 } else {                /* found, discard junk before start */
  7652.                     int k;
  7653.                     n = n - i + 1;
  7654.                     for (k = 1; k <= n; k++, i++) dest[k] = dest[i];
  7655.                 }
  7656.             }
  7657.             for (i = 0; (i < n) && /* search for eol */
  7658.                  !(goteol=(((*pdest = *(pdest+1)&ttpmsk)&0x7f)== eol));
  7659.                  i++,pdest++);
  7660.             *pdest = '\0';
  7661.             rest -= n;
  7662.         }
  7663.     } while ((rest > 0) && (!goteol));
  7664.  
  7665.     if (goteol) {
  7666.         n = max - rest;
  7667.         debug (F111,"x25inl X.25 got",(char *) dest,n);
  7668.         if (timo) ttimoff();
  7669.         if (ttpflg++ == 0 && ttprty == 0) {
  7670.             if ((ttprty = parchk(dest,start,n)) > 0) {
  7671.                 int j;
  7672.                 debug(F101,"x25inl senses parity","",ttprty);
  7673.                 debug(F110,"x25inl packet before",(char *)dest,0);
  7674.                 ttpmsk = 0x7f;
  7675.                 for (j = 0; j < n; j++)
  7676.                   dest[j] &= 0x7f; /* Strip parity from packet */
  7677.                 debug(F110,"x25inl packet after ",dest,0);
  7678.             } else {
  7679.                 debug(F101,"parchk","",ttprty);
  7680.                 if (ttprty < 0) { ttprty = 0; n = -1; }
  7681.             }
  7682.         }
  7683.         ttimoff();
  7684.         return(n);
  7685.     }
  7686.     ttimoff();
  7687.     return(-1);
  7688. }
  7689. #endif /* COMMENT */
  7690. #endif /* SUNX25 */
  7691.  
  7692. #ifdef IBMX25
  7693. /*
  7694.  * IBM X25 support - using the NPI streams interface
  7695.  * written by Stephen Riehm, pc-plus, Munich Germany
  7696.  */
  7697.  
  7698. /* riehm: missing functions / TODO list */
  7699.  
  7700. /*
  7701.   x25intr() - Send an interrupt packet
  7702. */
  7703.  
  7704. /* return an error message depending on packet type */
  7705. char *
  7706. x25err(n) int n; {
  7707.     static char buf[30];
  7708.     switch (n) {
  7709.       case NBADADDR:     return "invalid address";
  7710.       case NBADOPT:      return "invalid options";
  7711.       case NACCESS:      return "no permission";
  7712.       case NNOADDR:      return "unable to allocate address";
  7713.       case NOUTSTATE:    return "invalid state";
  7714.       case NBADSEQ:      return "invalid sequence number";
  7715.       case NSYSERR:      return "system error";
  7716.       case NBADDATA:     return "invalid data size";
  7717.       case NBADFLAG:     return "invalid flag";
  7718.       case NNOTSUPPORT:  return "unsupported primitive";
  7719.       case NBOUND:       return "address in use";
  7720.       case NBADQOSPARAM: return "bad QOS parameters";
  7721.       case NBADQOSTYPE:  return "bad QOS type";
  7722.       case NBADTOKEN:    return "bad token value";
  7723.       case NNOPROTOID:   return "protocol id could not be allocated";
  7724.       case NODDCUD:      return "odd length call user data";
  7725.       default:
  7726.         ckmakmsg(buf,sizeof(buf),"Unknown NPI error ",ckitoa(n),NULL,NULL);
  7727.         return buf;
  7728.     }
  7729. }
  7730.  
  7731. /* turn a meaningless primitive number into a meaningful primitive name */
  7732. char *
  7733. x25prim(n) int n; {
  7734.     static char buf[30];
  7735.     switch(n) {
  7736.       case N_BIND_ACK:     return "N_BIND_ACK";
  7737.       case N_BIND_REQ:     return "N_BIND_REQ";
  7738.       case N_CONN_CON:     return "N_CONN_CON";
  7739.       case N_CONN_IND:     return "N_CONN_IND";
  7740.       case N_CONN_REQ:     return "N_CONN_REQ";
  7741.       case N_CONN_RES:     return "N_CONN_RES";
  7742.       case N_DATACK_IND:   return "N_DATAACK_IND";
  7743.       case N_DATACK_REQ:   return "N_DATAACK_REQ";
  7744.       case N_DATA_IND:     return "N_DATA_IND";
  7745.       case N_DATA_REQ:     return "N_DATA_REQ";
  7746.       case N_DISCON_IND:   return "N_DISCON_IND";
  7747.       case N_DISCON_REQ:   return "N_DISCON_REQ";
  7748.       case N_ERROR_ACK:    return "N_ERROR_ACK";
  7749.       case N_EXDATA_IND:   return "N_EXDATA_IND";
  7750.       case N_EXDATA_REQ:   return "N_EXDATA_REQ";
  7751.       case N_INFO_ACK:     return "N_INFO_ACK";
  7752.       case N_INFO_REQ:     return "N_INFO_REQ";
  7753.       case N_OK_ACK:       return "N_OK_ACK";
  7754.       case N_OPTMGMT_REQ:  return "N_OPTMGMT_REQ";
  7755.       case N_RESET_CON:    return "N_RESET_CON";
  7756.       case N_RESET_IND:    return "N_RESET_IND";
  7757.       case N_RESET_REQ:    return "N_RESET_REQ";
  7758.       case N_RESET_RES:    return "N_RESET_RES";
  7759.       case N_UDERROR_IND:  return "N_UDERROR_IND";
  7760.       case N_UNBIND_REQ:   return "N_UNBIND_REQ";
  7761.       case N_UNITDATA_REQ: return "N_UNITDATA_REQ";
  7762.       case N_UNITDATA_IND: return "N_UNITDATA_IND";
  7763.       default:
  7764.         ckmakmsg(buf,sizeof(buf),"UNKNOWN (",ckitoa(n),")",NULL);
  7765.         return buf;
  7766.     }
  7767. }
  7768.  
  7769. /*****************************************************************************
  7770.  * Function: x25getmsg()
  7771.  * Description: get a STREAMS message, and check it for errors
  7772.  *
  7773.  * Parameters:
  7774.  * fd           - file descriptor to x25 device (opened)
  7775.  * control      - control buffer (pre-allocated)
  7776.  * ctl_size     - size of control buffer
  7777.  * data         - data buffer (pre-allocated)
  7778.  * data_size    - size of data buffer
  7779.  * flags        - flags for getmsg()
  7780.  * expected     - expected Primitive type
  7781.  *
  7782.  * Return Value:
  7783.  *      >= 0    OK (size of data returned)
  7784.  *      -1      error
  7785.  *
  7786.  */
  7787. int
  7788. x25getmsg( fd, control, ctl_size, data, data_size, get_flags, expected )
  7789.     int                 fd;             /* X25 device (opened) */
  7790.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  7791.     int                 ctl_size;       /* size of control buffer */
  7792.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  7793.     int                 data_size;      /* size of data buffer */
  7794.     int                 *get_flags;     /* getmsg() flags */
  7795.     int                 expected;       /* expected primitive type */
  7796. /* x25getmsg */ {
  7797.     int                 rc = 0;         /* return code */
  7798.     struct strbuf       *get_ctl=NULL;  /* getmsg control */
  7799.     struct strbuf       *get_data=NULL; /* getmsg data */
  7800.     int                 more = 0;       /* flag for more data etc */
  7801.     int                 file_status = -1; /* file async status */
  7802.     N_npi_ctl_t         * result;       /* pointer to simplify switch() */
  7803.     int                 packet_type = -1; /* unknown packet thus far */
  7804.  
  7805. #ifdef TRACE
  7806.     printf( "TRACE: entering x25getmsg\n" );
  7807. #endif /* TRACE */
  7808.  
  7809.     debug( F110, "x25getmsg waiting for packet ", x25prim( expected ), 0);
  7810.     /* prepare the control structures for getmsg */
  7811.     if (control) {
  7812.         if ((get_ctl = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7813.           {
  7814.               perror("kermit x25getmsg(): get_ctl malloc failed\n");
  7815.               debug( F100, "x25getmsg malloc failed for get_ctl\n", "", 0);
  7816.               return(-1);
  7817.           }
  7818.         /* allow getmsg to return an unexpected packet type (which may be
  7819.          * larger than the expected one)
  7820.          */
  7821.         get_ctl->maxlen = NPI_MAX_CTL;
  7822.         get_ctl->len = 0;
  7823.         get_ctl->buf = (char *)control;
  7824.     } else {
  7825.         printf(
  7826.  "kermit x25getmsg(): internal error. control buffer MUST be pre-allocated!\n"
  7827.                );
  7828.         debug(F100,"x25getmsg internal error. no buffer pre-allocated","",0);
  7829.         return( -1 );
  7830.     }
  7831.     if (data) {
  7832.         if ((get_data = (struct strbuf*)malloc(sizeof(struct strbuf))) == NULL)
  7833.           {
  7834.             perror("kermit x25getmsg(): get_data malloc failed\n");
  7835.             debug( F100, "x25getmsg malloc failed for get_data\n", "", 0);
  7836.             return(-1);
  7837.         }
  7838.         get_data->maxlen = (NPI_MAX_DATA < data_size ) ?
  7839.           NPI_MAX_DATA :
  7840.             data_size;
  7841.         get_data->len = 0;
  7842.         get_data->buf = (char *)data;
  7843.     }
  7844.  
  7845.     /* get an X.25 packet -
  7846.      * it may be any kind of packet, so check for special cases
  7847.      * it may be split into multiple parts - so loop if necessary
  7848.      */
  7849.     do {
  7850. #ifdef DEBUG
  7851.         printf( "kermit: x25getmsg(): getting a message\n" );
  7852. #endif /* DEBUG */
  7853.         errno = 0;
  7854.         if ((more = getmsg(fd, get_ctl, get_data, get_flags)) < 0) {
  7855. #ifdef DEBUG
  7856.             printf( "kermit: x25getmsg(): getmsg returned an error\n" );
  7857.             perror( "getmsg error was" );
  7858. #endif /* DEBUG */
  7859.             debug(F101, "x25getmsg getmsg returned an error\n", "", errno);
  7860.             if ((errno == EAGAIN) && (get_data && (get_data->len > 0)) ) {
  7861.                 /* was in non-blocking mode, nothing to get, but we're
  7862.                  * already waiting for the rest of the packet -
  7863.                  * switch to blocking mode for the next read.
  7864.                  * file_status used to reset file status before returning
  7865.                  */
  7866.                 if ((file_status = fcntl(fd, F_GETFL, 0)) < 0
  7867.                     || fcntl(fd, F_SETFL, file_status & ~O_NDELAY) < 0)
  7868.                   {
  7869.                       perror("x25getmsg(): couldn't change x25 blocking mode");
  7870.                       debug(F101,
  7871.                             "x25getmsg fcntl returned an error\n", "", errno);
  7872.                       /* netclos(); */
  7873.                       rc = -1;
  7874.                       break;
  7875.                   } else {
  7876.                       /* loop again into a blocking getmsg() */
  7877.                       continue;
  7878.                   }
  7879.             } else {
  7880.                 /* no data to get in non-blocking mode - return empty handed */
  7881.                 perror( "x25getmsg(): getmsg failed" );
  7882.                 debug(F101,"x25getmsg getmsg returned an error\n", "", errno);
  7883.                 rc = -1;
  7884.                 break;
  7885.             }
  7886.         } else if (more & MORECTL) {
  7887.             /* panic - the control information was larger than the
  7888.              * maximum control buffer size!
  7889.              */
  7890.             /* riehm: close connection? */
  7891. #ifdef DEBUG
  7892.             printf("x25getmsg(): received partial control packet - panic\n");
  7893. #endif /* DEBUG */
  7894.             debug( F101, "x25getmsg getmsg bad control block\n", "", errno);
  7895.             rc = -1;
  7896.             break;
  7897.         }
  7898.  
  7899.         if (result = (N_npi_ctl_t *)control) {
  7900.             packet_type = result->bind_ack.PRIM_type;
  7901.             if (packet_type != N_OK_ACK) {
  7902.                 x25lastmsg = packet_type;
  7903.             }
  7904.         }
  7905. #ifdef DEBUG
  7906.         /* printf( "kermit: x25getmsg(): getting " ); */
  7907.         if (get_ctl->len > 0) {
  7908.             x25dump_prim(result);
  7909.         }
  7910.         debug(F110,
  7911.               "x25getmsg got packet ",
  7912.               x25prim( result->bind_ack.PRIM_type ),
  7913.               0
  7914.               );
  7915. #endif /* DEBUG */
  7916.  
  7917.         if (get_ctl->len >= (int)sizeof(result->bind_ack.PRIM_type)) {
  7918.             /* not as pretty as a switch(), but switch can't handle
  7919.              * runtime variable values :-(
  7920.              */
  7921.             if (packet_type == expected ) {
  7922.                 /* got what we wanted, special case for DATA_IND
  7923.                  * packets though */
  7924.                 /* riehm: check Q-bit ? */
  7925. #ifdef DEBUG
  7926.                 printf("x25getmsg(): got expected packet\nrc is %d\n", rc);
  7927. #endif /* DEBUG */
  7928.                 if (packet_type == N_DATA_IND ) {
  7929.                     /* data received. May be incomplete, even though
  7930.                      * getmsg returned OK
  7931.                      */
  7932.                     if (result->data_ind.DATA_xfer_flags & N_MORE_DATA_FLAG)
  7933.                         more |= MOREDATA;
  7934.                     if (result->data_ind.DATA_xfer_flags & N_RC_FLAG)
  7935.                         printf( "x25getmsg(): data packet wants ack\n" );
  7936.                 }
  7937.             } else if( packet_type == N_DISCON_IND) {
  7938.                 printf( "X25 diconnected\n" );
  7939.                 /* riehm: need to acknowledge a disconnection? */
  7940.                 x25clear();
  7941.                 /* x25unbind( ttyfd ); */
  7942.                 rc = -1;
  7943.             } else if( packet_type == N_ERROR_ACK) {
  7944.                 errno = result->error_ack.UNIX_error;
  7945.                 perror( "X25 error received" );
  7946.                 rc = -1;
  7947.             } else {
  7948.                 printf("x25getmsg(): failed %s\n", x25err(packet_type));
  7949.                 rc = -1;
  7950.             }
  7951.         }
  7952. #ifdef COMMENT
  7953.         else {
  7954.             /* Panic - no control data */
  7955.             printf( "kermit: x25getmsg(): no control data with packet\n" );
  7956.             rc = -1;
  7957.         }
  7958. #endif /* COMMENT */
  7959.  
  7960.         if (get_data && (get_data->len >= 0)) {
  7961.             get_data->buf += get_data->len;
  7962.             get_data->maxlen -= get_data->len;
  7963.         }
  7964.     } while ((rc == 0)
  7965.              && (get_data && (get_data->maxlen > 0))
  7966.              && (more & MOREDATA)
  7967.              );
  7968.  
  7969.     /* return the file status to its original value, unless its still
  7970.      * set to -1, or one of the fcntl's failed */
  7971.     if ((file_status >= 0) && fcntl(fd, F_SETFL, file_status) < 0)
  7972.         rc = -1;
  7973.  
  7974.     /*
  7975.      * Verify that we received an expected primitive
  7976.      * there is apparantly an error case where the primitive is set
  7977.      * correctly, but there is not enough data in the control structure
  7978.      */
  7979.     if ((packet_type != expected) && (get_ctl->len >= ctl_size) ) {
  7980.         fprintf(stderr,
  7981.                 "x25getmsg(): %s NOT received. Primitive received was %s\n",
  7982.                 x25prim( expected ), x25prim( packet_type ));
  7983.         debug(F110, "x25getmsg got an unexpected packet ",
  7984.               x25prim(packet_type),
  7985.               0
  7986.               );
  7987.         rc = -1;
  7988.     }
  7989.  
  7990.     if (rc == 0) {
  7991.         if (get_data && ( get_data->len >= 0)) {
  7992.             rc = get_data->len;
  7993.         }
  7994.     }
  7995.  
  7996.     if (get_ctl)  { free(get_ctl); get_ctl = NULL; }
  7997.     if (get_data) { free(get_data); get_data = NULL; }
  7998.  
  7999. #ifdef COMMENT
  8000. #ifdef DEBUG
  8001.     printf( "kermit x25getmsg(): returning %d\n", rc );
  8002. #endif /* DEBUG */
  8003. #endif /* COMMENT */
  8004.     debug(F110, "x25getmsg returning packet ", x25prim( packet_type ), 0);
  8005.  
  8006. #ifdef TRACE
  8007.     printf( "TRACE: leaving x25getmsg\n" );
  8008. #endif /* TRACE */
  8009.     return(rc);
  8010. }
  8011.  
  8012. /*****************************************************************************
  8013.  * Function: x25putmsg()
  8014.  *
  8015.  * Description:
  8016.  *      send a message to a X25 STREAM
  8017.  *
  8018.  * Parameters:
  8019.  *      fd              - file descriptor to x25 device (opened)
  8020.  *      control         - control buffer (pre-allocated)
  8021.  *      data            - data buffer (pre-allocated)
  8022.  *      data_len        - length of data to be transmitted
  8023.  *      put_flags       - flags for putmsg()
  8024.  *
  8025.  * Return Value:
  8026.  *      >= 0    number of bytes transmitted
  8027.  *      -1      error
  8028.  */
  8029. int
  8030. x25putmsg(fd, control, data, data_len, put_flags)
  8031.     int                 fd;             /* X25 device (opened) */
  8032.     N_npi_ctl_t         *control;       /* control buffer (pre-allocated) */
  8033.     N_npi_data_t        *data;          /* data buffer (pre-allocated) */
  8034.     int                 data_len;       /* length of data (not the size of
  8035.                                            the buffer) */
  8036.     int                 *put_flags;     /* putmsg() flags */
  8037. /* x25putmsg */ {
  8038.     int                 rc = 0;         /* return code */
  8039.     ulong               type;           /* primitive type */
  8040.     struct strbuf       *put_ctl = NULL; /* putmsg control */
  8041.     struct strbuf       *put_data = NULL; /* putmsg data */
  8042.  
  8043. #ifdef TRACE
  8044.     printf( "TRACE: entering x25putmsg\n" );
  8045. #endif /* TRACE */
  8046.  
  8047. #ifdef DEBUG
  8048.     printf( "kermit: x25putmsg(): putting " );
  8049.     x25dump_prim( control );
  8050.     printf( "\tdata:\t\t" );
  8051.     x25dump_data( data, 0, data_len );
  8052.     debug(F110,"x25putmsg: putting packet ",x25prim(control->PRIM_type),0);
  8053. #endif /* DEBUG */
  8054.  
  8055.     if (control) {
  8056.         put_ctl = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  8057.         if (put_ctl == NULL) {
  8058.             perror("kermit x25putmsg(): put_ctl malloc failed\n");
  8059.             return(-1);
  8060.         }
  8061.         put_ctl->maxlen = 0;                    /* unused by putmsg */
  8062.         put_ctl->len = NPI_MAX_CTL;
  8063.         put_ctl->buf = (char *)control;
  8064.     }
  8065.     if (data && ( data_len > 0)) {
  8066.         put_data = (struct strbuf *)malloc( sizeof( struct strbuf ) );
  8067.         if( put_data == NULL) {
  8068.             perror("kermit x25putmsg(): put_data malloc failed\n");
  8069.             return(-1);
  8070.         }
  8071.         put_data->maxlen = 0;                   /* unused by putmsg */
  8072.         put_data->len = data_len;
  8073.         put_data->buf = (char *)data;
  8074.     }
  8075.  
  8076.     errno = 0;
  8077.     rc = putmsg (fd, put_ctl, put_data, 0);
  8078.     if (rc < 0) {
  8079.         printf("x25putmsg(): couldn't put %s\n",x25prim(control->PRIM_type));
  8080.         perror("kermit: x25putmsg(): putmsg failed");
  8081.         return(-1);
  8082.     }
  8083.  
  8084.     /* riehm: this should perhaps be discounted! */
  8085.     x25lastmsg = control->PRIM_type;
  8086.  
  8087. #ifdef COMMENT
  8088. #ifdef DEBUG
  8089.     printf( "kermit debug: x25putmsg() returning %d\n", data_len );
  8090. #endif /* DEBUG */
  8091. #endif /* COMMENT */
  8092.     debug( F101, "x25putmsg block size put ", "", data_len);
  8093.  
  8094. #ifdef TRACE
  8095.     printf( "TRACE: leaving x25putmsg\n" );
  8096. #endif /* TRACE */
  8097.  
  8098.     return( data_len );
  8099. }
  8100.  
  8101. /*****************************************************************************
  8102. * Function: x25bind
  8103. * Description:  The bind submitted to NPI provides the information required
  8104. *               by the packet layer for it to listen for suitable incoming
  8105. *               calls.
  8106. *
  8107. * WARNING:
  8108. *
  8109. * This routine needs to be called in a completely different manner for
  8110. * the client and server side. When starting a client, the
  8111. * num_waiting_calls and CUD information should all be set to 0! The
  8112. * client's CUD must be inserted in the CONN_REQ data block.
  8113. * When starting a server, the CUD must be set to a CUD pattern, and
  8114. * the number of waiting calls should be set to a number other than 0.
  8115. * (num waiting calls is the number of incomming calls which are to be
  8116. * put on hold while the server is servicing another client.)
  8117. *
  8118. * Who invented this crap?
  8119. *
  8120. * Parameters:
  8121. *       fd              - X25 device (opened)
  8122. *       addr            - local address
  8123. *       cud             - User Data (null terminated)
  8124. *       cud_len         - User Data length
  8125. *       num_waiting_calls - number of outstanding calls allowed on this stream
  8126. *       line            - logical port number (1)
  8127. *       flags           - 0, DEFAULT_LISTENER or TOKEN_REQUEST
  8128. *
  8129. * Return Value:
  8130. *       if binding is successful, 0 is returned for a client, and a token is
  8131. *       returned for a server
  8132. *
  8133. * Return code: 0 if successful
  8134. *              -1 if unsuccessful
  8135. *****************************************************************************/
  8136.  
  8137. ulong
  8138. x25bind(fd, addr, cud, cud_len, num_waiting_calls, line, bind_flags)
  8139.     int fd;                             /* X25 device (opened) */
  8140.     char * addr;                        /* local address */
  8141.     char * cud;                         /* Call User Data (null terminated) */
  8142.     int cud_len;                        /* User Data length */
  8143.     int num_waiting_calls;              /* Outstanding calls allowed */
  8144.     int line;                           /* logical port number */
  8145.     ulong bind_flags;           /* 0, DEFAULT_LISTENER or TOKEN_REQUEST */
  8146. /* x25bind */ {
  8147.     ulong rc;                           /* return code */
  8148.     int get_flags;                      /* priority flag passed to getmsg */
  8149.     int put_flags = 0;                  /* output flags for putmsg, always 0 */
  8150.     ulong type;                         /* primitive type */
  8151.     N_bind_req_t *bind_req;             /* pointer to N_BIND_REQ primitive */
  8152.     N_bind_ack_t *bind_ack;             /* pointer to N_BIND_ACK primitive */
  8153.     char *addtl_info;                   /* pointer to info in addition to
  8154.                                          * the N_BIND_REQ primitive that is
  8155.                                          * passed in the control structure
  8156.                                          * to putmsg */
  8157.     int addr_len = 0;                   /* length of address string */
  8158.     ulong bind_req_t_size;              /* for debugging only */
  8159.  
  8160. #ifdef TRACE
  8161.     printf("TRACE: entering x25bind\n" );
  8162. #endif /* TRACE */
  8163.  
  8164. #ifdef DEBUG
  8165.     printf("TRACE: x25bind( %d, %s, %s, %d, %d )\n",
  8166.            fd, addr, cud, line, bind_flags
  8167.            );
  8168. #endif /* DEBUG */
  8169.  
  8170.     /*
  8171.      * Allocate  and zero out space to hold the control portion of the
  8172.      * message passed to putmsg. This will contain the N_BIND_REQ
  8173.      * primitive and any additional info required for that.
  8174.      *
  8175.      * Note: allocated space is the size of the union typedef
  8176.      * N_npi_ctl_t to allow the use fo the generic x25putmsg routine.
  8177.      */
  8178.     bind_req = (N_bind_req_t *) malloc(sizeof( N_npi_ctl_t));
  8179.     if (bind_req == NULL) {
  8180.         perror("kermit: x25bind(): bind_req malloc failed");
  8181.         debug(F100, "x25bind bind_req malloc failed", "", 0);
  8182.         return(-1);
  8183.     }
  8184.     bzero((char *)bind_req, sizeof(N_npi_ctl_t));
  8185.  
  8186.     /* Build the Bind Request Primitive */
  8187.     bind_req->PRIM_type = (ulong) N_BIND_REQ;
  8188.  
  8189.     /* Note that the address length is n+2 and NOT n. Two bytes MUST preceed
  8190.      * the actual address in an N_BIND_REQ. The first byte contains the
  8191.      * line number being used with this address, and the second byte is the
  8192.      * X.121 address prefix, which must be zero.
  8193.      */
  8194.     addr_len = strlen(addr);
  8195.     bind_req->ADDR_length = (ulong) (addr_len + 2);
  8196.     bind_req->ADDR_offset = (ulong)(sizeof(N_bind_req_t));
  8197.     bind_req->CONIND_number = (ulong)num_waiting_calls; /* server only */
  8198.     bind_req->BIND_flags = (ulong) bind_flags; /* 0 in client */
  8199.     bind_req->PROTOID_length = (ulong) cud_len; /* 0 in client */
  8200.     if (cud_len == 0) {
  8201.         bind_req->PROTOID_offset = (ulong) 0;
  8202.     } else {
  8203.         /* need to remember the trailing NULL in the address - not
  8204.          * counted in the address length
  8205.          */
  8206.         bind_req->PROTOID_offset
  8207.           = (ulong) (sizeof(N_bind_req_t) + bind_req->ADDR_length);
  8208.     }
  8209.  
  8210.     /*
  8211.      * Now fill in the additional information required with this primitive
  8212.      * (address and protocol information (Call User Data))
  8213.      */
  8214.     addtl_info = (char *) ((void *)bind_req + bind_req->ADDR_offset);
  8215.     /*
  8216.      * The bitwise "&" ensures that the line number is only one byte long
  8217.      */
  8218.     *addtl_info++ = (char) line & 0xff;
  8219.     *addtl_info++ = (char) 0; /* X.121 format */
  8220.     bcopy( addr, addtl_info, addr_len ); /* include trailing null */
  8221.     addtl_info += addr_len;
  8222.     if (cud_len > 0)
  8223.       bcopy( cud, addtl_info, cud_len );
  8224.     /*
  8225.      * Call putmsg() to put the bind request message on the stream
  8226.      */
  8227.     if (x25putmsg(fd,
  8228.                   (N_npi_ctl_t*)bind_req,
  8229.                   (N_npi_data_t *)NULL,
  8230.                   0,
  8231.                   &put_flags
  8232.                   ) < 0) {
  8233.         printf( "kermit: x25bind(): x25putmsg failed\n" );
  8234.         return(-1);
  8235.     }
  8236.  
  8237.     /*
  8238.      * Allocate and zero out space for the N_BIND_ACK primitive
  8239.      */
  8240.     bind_ack = (N_bind_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8241.     if (bind_ack == NULL){
  8242.         perror("kermit: x25bind(): bind_ack malloc failed");
  8243.         return(-1);
  8244.     }
  8245.     bzero(bind_ack, sizeof(N_npi_ctl_t));
  8246.     /*
  8247.      * Initialize the control structure and flag variable sent to getmsg
  8248.      */
  8249.     get_flags=0;
  8250.  
  8251.     /* get the ACK for the bind */
  8252. #ifdef DEBUG
  8253.     printf( "kermit: x25bind() trying to get a BIND_ACK\n" );
  8254. #endif /* DEBUG */
  8255.     rc = (ulong)x25getmsg( fd, (N_npi_ctl_t*)bind_ack,
  8256.             (int)sizeof( N_bind_ack_t ), (N_npi_data_t*)NULL, 0, &get_flags,
  8257.             N_BIND_ACK );
  8258.  
  8259.     /* turn quantitive return code into a qualitative one */
  8260.     if (rc > 0) rc = 0;
  8261.  
  8262.     /* if all went well, get the token from the acknowledgement packet */
  8263.     if ((bind_flags & TOKEN_REQUEST ) && ( rc >= 0)) {
  8264.         rc = bind_ack->TOKEN_value;
  8265.     }
  8266.  
  8267.     /* free up the memory we allocated earlier */
  8268.     free(bind_req);
  8269.     free(bind_ack);
  8270.  
  8271. #ifdef TRACE
  8272.     printf( "TRACE: leaving x25bind\n" );
  8273. #endif /* TRACE */
  8274.  
  8275.     return( rc );
  8276. }
  8277.  
  8278. /*****************************************************************************
  8279. * Function: x25call
  8280. * Description:  This routine builds and sends an N_CONN_REQ primitive, then
  8281. *               checks for an N_CONN_CON primitive in return.
  8282. *
  8283. * Parameters:
  8284. * fd    - file descriptor of stream
  8285. * caddr - called address (remote address)
  8286. *
  8287. * Functions Referenced:
  8288. * malloc()
  8289. * bzero()
  8290. * getmsg()
  8291. * putmsg()
  8292. *
  8293. * Return code:
  8294. * 0 - if successful
  8295. * -1 if not successful
  8296. *****************************************************************************/
  8297. int
  8298. x25call(fd, remote_nua, cud)
  8299.     int fd;                             /* X25 device (opened) */
  8300.     char * remote_nua;                  /* remote address to call */
  8301.     char * cud;                         /* call user data */
  8302. /* x25call */ {
  8303.     int rc;                             /* return code */
  8304.     int flags;                          /* Connection flags */
  8305.     int get_flags;                      /* priority flags for getmsg */
  8306.     ulong type;                         /* primitive type */
  8307.     N_conn_req_t *connreq_ctl;          /* pointer to N_CONN_REQ primitive */
  8308.     N_npi_data_t *connreq_data;         /* pointer to N_CONN_REQ data (CUD) */
  8309.     int connreq_data_len;               /* length of filled data buffer */
  8310.     N_conn_con_t *conncon_ctl;          /* pointer to N_CONN_CON primitive */
  8311.     N_npi_data_t *conncon_data;         /* pointer to any data associated with
  8312.                                          * the N_CONN_CON primitive */
  8313.     char *addtl_info;                   /* pointer to additional info needed
  8314.                                          * for N_CONN_REQ primitive */
  8315.     int addr_len;                       /* length of address */
  8316.  
  8317. #ifdef TRACE
  8318.     printf( "TRACE: entering x25call\n" );
  8319. #endif /* TRACE */
  8320.  
  8321. #ifdef DEBUG
  8322.     printf( "x25call( %d, %s )\n", fd, remote_nua );
  8323.     printf( "connecting to %s on fd %d\n", remote_nua, fd );
  8324. #endif /* DEBUG */
  8325.  
  8326.     /*
  8327.      * Allocate and zero out space for the N_CONN_REQ primitive
  8328.      * use the size of the generic NPI primitive control buffer
  8329.      */
  8330.     connreq_ctl  = (N_conn_req_t *) malloc(sizeof(N_npi_ctl_t));
  8331.     if (connreq_ctl == NULL){
  8332.         perror("kermit: x25call(): connreq_ctl malloc failed");
  8333.         return(-1);
  8334.     }
  8335.     bzero(connreq_ctl,sizeof(N_npi_ctl_t));
  8336.     /*
  8337.      * Build the Connection Request Primitive
  8338.      */
  8339.     flags = 0;
  8340.     connreq_ctl->PRIM_type = (ulong) N_CONN_REQ;
  8341.  
  8342.     /* Note that the address length is nchai+1 and not n+2. The line number
  8343.      * is only passed with the address for the bind. The first byte of
  8344.      * the address for the N_CONN primitives contains the X.121
  8345.      * address prefix, which must be zero. The remaining bytes are the
  8346.      * address itself.
  8347.      */
  8348.     addr_len = strlen( remote_nua );
  8349.     connreq_ctl->DEST_length = (ulong) (addr_len + 1);
  8350.     connreq_ctl->DEST_offset = (ulong) sizeof(N_conn_req_t);
  8351.     /* connreq_ctl->CONN_flags = (ulong)EX_DATA_OPT | REC_CONF_OPT; */
  8352.     connreq_ctl->CONN_flags = (ulong) 0;
  8353.     connreq_ctl->QOS_length = (ulong) 0;        /* unsupported in AIX 4.1 */
  8354.     connreq_ctl->QOS_offset = (ulong) 0;        /* unsupported in AIX 4.1 */
  8355.  
  8356.     addtl_info = (char *) ((void*)connreq_ctl + connreq_ctl->DEST_offset);
  8357.     *addtl_info++ = (char) 0; /* X.121 format */
  8358.     bcopy( remote_nua, addtl_info, addr_len );
  8359.  
  8360.     /*
  8361.      * setup the data buffer for the connection request
  8362.      */
  8363.     connreq_data  = (N_npi_data_t *) malloc(sizeof(N_npi_data_t));
  8364.     if (connreq_data == NULL){
  8365.         perror("kermit: x25call(): connreq_data malloc failed");
  8366.         return(-1);
  8367.     }
  8368.     bzero(connreq_data,sizeof(N_npi_data_t));
  8369.  
  8370.     /* facility selection needs to be put in the front of connreq_data */
  8371.     connreq_data_len = 0;
  8372.     connreq_data_len += x25facilities( (char *)connreq_data );
  8373.     if (cud && *cud) {
  8374.         bcopy(cud,
  8375.               (char *)((char *)connreq_data + connreq_data_len),
  8376.               strlen(cud)
  8377.               );
  8378.         connreq_data_len += strlen( cud );
  8379.         }
  8380.  
  8381.     /*
  8382.      * Call putmsg() to put the connection request message on the stream
  8383.      */
  8384.     rc = x25putmsg( fd, (N_npi_ctl_t*)connreq_ctl, connreq_data,
  8385.             connreq_data_len, &flags );
  8386.     if (rc < 0) {
  8387.         return(-1);
  8388.     }
  8389.  
  8390.     /*
  8391.      * Allocate and zero out space for the N_CONN_CON primitive
  8392.      */
  8393.     if ((conncon_ctl = (N_conn_con_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8394.         perror("kermit: x25call(): conncon_ctl malloc failed");
  8395.         return(-1);
  8396.     }
  8397.     bzero(conncon_ctl, sizeof(N_npi_ctl_t));
  8398.  
  8399.     /*
  8400.      * Allocate and zero out space for any data associated with N_CONN_CON
  8401.      */
  8402.     if ( (conncon_data = (N_npi_data_t *) malloc(NPI_MAX_DATA)) == NULL) {
  8403.         perror("kermit: x25call(): conncon_data malloc failed");
  8404.         return(-1);
  8405.     }
  8406.     bzero(conncon_data, NPI_MAX_DATA);
  8407.  
  8408.     /* Initialize and build the structures for getmsg */
  8409.     get_flags=0;
  8410.  
  8411.     rc = x25getmsg( fd, (N_npi_ctl_t*)conncon_ctl, (int)sizeof( N_conn_con_t ),
  8412.             conncon_data, NPI_MAX_DATA, &get_flags, N_CONN_CON );
  8413.  
  8414.     /* turn quantitive return code into a qualitative one */
  8415.     if (rc > 0) rc = 0;
  8416.  
  8417.     /* Free the space that we no longer need */
  8418.     if (connreq_ctl) { free(connreq_ctl); connreq_ctl = NULL; }
  8419.     if (conncon_ctl) { free(conncon_ctl); conncon_ctl = NULL; }
  8420.     if (conncon_data) { free(conncon_data); conncon_data = NULL; }
  8421.  
  8422. #ifdef TRACE
  8423.     printf( "TRACE: leaving x25call\n" );
  8424. #endif /* TRACE */
  8425.  
  8426.     return(rc);
  8427. }
  8428.  
  8429. /*****************************************************************************
  8430.  * Function: x25getcall
  8431.  *
  8432.  * Description: This routine checks for an incomming call, verified
  8433.  * that it is a CONNIND (connection indication) message, and then
  8434.  * accepts the call and returns the file descriptor of the new stream
  8435.  *
  8436.  * Parameters:
  8437.  * fd   - file descriptor of listening stream
  8438.  *
  8439.  * Return Codes:
  8440.  * callfd       - file descriptor of connected incomming call.
  8441.  *              - set to -1 if an error occured
  8442.  *
  8443.  *****************************************************************************/
  8444. int
  8445. x25getcall(fd) int fd; {
  8446.     int x25callfd;                      /* fd of incomming call */
  8447.     N_conn_ind_t *connind_ctl;          /* connind controll buffer */
  8448.     N_npi_data_t *connind_data;         /* connind data buffer */
  8449.     int get_flags;                      /* flags for getmsg */
  8450.     ulong flags;                        /* connection flags */
  8451.     int rc;                             /* return code */
  8452.  
  8453.     extern x25addr_t remote_nua;        /* remote X.25 addr global var */
  8454.  
  8455. #ifdef TRACE
  8456.     printf( "TRACE: entering x25getcall\n" );
  8457. #endif /* TRACE */
  8458.  
  8459.     /* allocate space for connection indication buffers */
  8460.     if ((connind_ctl = (N_conn_ind_t *)malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8461.         perror("kermit: x25getcall(): connind_ctl malloc failed");
  8462.         return (-1);
  8463.     }
  8464.     bzero(connind_ctl, sizeof(N_npi_ctl_t));
  8465.  
  8466.     if ((connind_data = (N_npi_data_t *)malloc(NPI_MAX_DATA)) == NULL) {
  8467.         perror("kermit: x25getcall(): connind_data malloc failed");
  8468.         return (-1);
  8469.     }
  8470.     bzero(connind_data, NPI_MAX_DATA);
  8471.  
  8472.     /* initialise control structures */
  8473.     get_flags = 0;
  8474.  
  8475.     /* call getmsg to check for a connection indication */
  8476.     if (x25getmsg(fd,
  8477.                   (N_npi_ctl_t*)connind_ctl,
  8478.                   (int)sizeof(N_conn_ind_t),
  8479.                   connind_data,
  8480.                   NPI_MAX_DATA,
  8481.                   &get_flags,
  8482.                   N_CONN_IND
  8483.                   ) < 0) {
  8484. #ifdef DEBUG
  8485.         printf( "x25getcall(): errno is: %d\n", errno );
  8486. #endif /* DEBUG */
  8487.         perror ("x25getcall(): getmsg failed");
  8488.         return(-1);
  8489.     }
  8490.  
  8491.     /* a connection indication was received
  8492.      * - pull it to bits and answer the call
  8493.      */
  8494.     x25seqno = connind_ctl->SEQ_number;
  8495.     flags = connind_ctl->CONN_flags;
  8496. #ifdef DEBUG
  8497.     printf( "setting remote_nua to a new value due to incomming call\n" );
  8498. #endif /* DEBUG */
  8499.     /*
  8500.      * no guarantee that the address is null terminated, ensure that
  8501.      * after copying that it is (assumption: remote_nua is longer than
  8502.      * the address + 1)
  8503.      */
  8504.     bzero(remote_nua, sizeof(remote_nua));
  8505.     /* note: connind_ctl contains a x121 address, which has a null as
  8506.      * the FIRST character - strip it off!
  8507.      */
  8508.     ckstrncpy(remote_nua,
  8509.             (char*)((char*)connind_ctl + connind_ctl->SRC_offset + 1),
  8510.             connind_ctl->SRC_length - 1
  8511.             );
  8512. #ifdef DEBUG
  8513.     printf( "remote_nua set to new value of %s\n", remote_nua );
  8514. #endif /* DEBUG */
  8515.  
  8516.     /* errors handled by callee */
  8517.     x25callfd = x25accept(x25seqno, flags);
  8518.  
  8519.     /* free the malloc'd buffers */
  8520.     if (connind_ctl) { free(connind_ctl); connind_ctl = NULL; }
  8521.     if (connind_data) { free(connind_data); connind_data = NULL; }
  8522.  
  8523. #ifdef TRACE
  8524.     printf( "TRACE: leaving x25getcall\n" );
  8525. #endif /* TRACE */
  8526.  
  8527.     /* return the file descriptor (or error if < 0) */
  8528.     return( x25callfd );
  8529. }
  8530.  
  8531. /*****************************************************************************
  8532.  * Function: x25accept
  8533.  *
  8534.  * Description: accept an incomming call
  8535.  *              This essentially means opening a new STREAM and sending
  8536.  *              an acknowledge back to the caller.
  8537.  *
  8538.  * Parameters:
  8539.  *      seqno   - sequence number for acknowledgement
  8540.  *      flags   - flags passed to us by the caller
  8541.  *
  8542.  * Return Codes:
  8543.  *      fd      - file descriptor of new STREAM
  8544.  *                set to -1 if an error occured
  8545.  *
  8546.  *****************************************************************************/
  8547. int
  8548. x25accept(seqno,flags)
  8549.     ulong seqno;                        /* connection sequence number */
  8550.     ulong flags;                        /* connection flags */
  8551. /* x25accept */ {
  8552.     int x25callfd;                      /* fd for incomming call */
  8553.     int get_flags;                      /* priority flags for getmsg */
  8554.     int put_flags = 0;                  /* flags for putmsg, always 0 */
  8555.     int addr_len;                       /* length of local address */
  8556.     ulong token;                        /* connection token */
  8557.     N_conn_res_t *conn_res;             /* N_CONN_RES primitive */
  8558.     N_ok_ack_t *ok_ack;                 /* N_OK_ACK primitive */
  8559.     char *addtl_info;                   /* temp pointer */
  8560.     int rc;                             /* temporary return code */
  8561.  
  8562. /* global variables from ckcmai.c */
  8563.     extern int revcall, closgr, cudata;
  8564.     extern char udata[];
  8565.     extern x25addr_t local_nua;         /* local X.25 address */
  8566.     extern char x25name[];              /* x25 device name (sx25a0) */
  8567.     extern char x25dev[];               /* x25 device file /dev/x25pkt */
  8568.     extern int x25port;                 /* logical port to use */
  8569.     ulong bind_flags = 0;               /* flags for binding the X25 stream */
  8570.  
  8571. #ifdef TRACE
  8572.     printf( "TRACE: entering x25accept\n" );
  8573. #endif /* TRACE */
  8574.  
  8575.     /* open a new packet level stream */
  8576.     if ((x25callfd = open(x25dev, O_RDWR)) < 0) {
  8577.         perror ("kermit: x25accept(): X.25 device open error");
  8578.         debug(F101,"x25accept() device open error","",errno);
  8579.         return(-1);
  8580.     }
  8581.  
  8582.     /* push the NPI onto the STREAM */
  8583.     if (ioctl(x25callfd,I_PUSH,"npi") < 0) {
  8584.         perror( "kermit: x25accept(): couldn't push npi on the X25 stream" );
  8585.         debug(F101,"x25accept can't push npi on the X25 stream","",errno);
  8586.         return (-1);
  8587.     }
  8588.  
  8589.     /* bind kermit server to the local X25 address */
  8590.     /* taken from /usr/samples/sx25/npi/npiserver.c (AIX 4) */
  8591.     bind_flags |= TOKEN_REQUEST;
  8592.     token = x25bind(x25callfd,local_nua,(char *)NULL,0,0,x25port,bind_flags);
  8593.     if (token < 0) {
  8594.         printf( "kermit: x25accept(): couldn't bind to local X25 address\n" );
  8595.         netclos();
  8596.         return(-1);
  8597.     }
  8598.  
  8599.     /* allocate connection response primitive */
  8600.     if ((conn_res = (N_conn_res_t *)malloc( NPI_MAX_CTL )) == NULL) {
  8601.         perror("kermit: x25accept(): conn_res malloc failed");
  8602.         return (-1);
  8603.     }
  8604.     bzero((char *)conn_res, NPI_MAX_CTL);
  8605.  
  8606.     /* setup connection response primitive */
  8607.     addr_len = strlen( local_nua );
  8608.     conn_res->PRIM_type = (ulong)N_CONN_RES;
  8609.     conn_res->TOKEN_value = token;
  8610.     /* note address length is n+1 to accomodate the X.121 address prefix */
  8611.     conn_res->RES_length = (ulong)(addr_len + 1);
  8612.     conn_res->RES_offset = (ulong)sizeof( N_conn_res_t );
  8613.     conn_res->SEQ_number = seqno;
  8614.     conn_res->CONN_flags = 0;
  8615.     conn_res->QOS_length = 0;           /* unsupported - must be 0 (!?) */
  8616.     conn_res->QOS_offset = 0;
  8617.  
  8618.     addtl_info = (char *)((char *)conn_res + conn_res->RES_offset);
  8619.     *addtl_info++ = (char)0;    /* X.121 address prefix */
  8620.     bcopy( local_nua, addtl_info, addr_len );
  8621.  
  8622.     /*
  8623.      * send off the connect response
  8624.      */
  8625.     if (x25putmsg(x25callfd,
  8626.                   (N_npi_ctl_t*)conn_res,
  8627.                   (N_npi_data_t *)NULL,
  8628.                   0,
  8629.                   &put_flags
  8630.                   ) < 0 ) {
  8631.         perror("kermit: x25accept(): putmsg connect response failed");
  8632.         return(-1);
  8633.     }
  8634.  
  8635.     /*
  8636.      * Allocate and zero out space for the OK_ACK primitive
  8637.      */
  8638.     if ((ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t))) == NULL) {
  8639.         perror("kermit: x25call(): ok_ack malloc failed");
  8640.         return(-1);
  8641.     }
  8642.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8643.  
  8644.     /* Initialize and build the structures for getmsg */
  8645.     get_flags=0;
  8646.  
  8647.     rc = (int)x25getmsg(x25callfd,
  8648.                         (N_npi_ctl_t*)ok_ack,
  8649.                         (int)sizeof(N_ok_ack_t),
  8650.                         (N_npi_data_t*)NULL,
  8651.                         0,
  8652.                         &get_flags,
  8653.                         N_OK_ACK
  8654.                         );
  8655.     if (rc == 0) {
  8656.         /* sequence number is only for disconnecting when not connected !? */
  8657.         x25seqno = 0;
  8658.     }
  8659.  
  8660.     /* free up malloc'ed buffer space */
  8661.     if (conn_res) { free(conn_res); conn_res = NULL; }
  8662.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8663.  
  8664. #ifdef TRACE
  8665.     printf( "TRACE: leaving x25accept\n" );
  8666. #endif /* TRACE */
  8667.  
  8668.     return( ( rc >= 0 ) ? x25callfd : -1 );
  8669. }
  8670.  
  8671. /*****************************************************************************
  8672.  * Function: x25unbind
  8673.  *
  8674.  * Description:  This subroutine builds and sends an unbind request and gets
  8675.  * the acknowledgement for it.
  8676.  *
  8677.  * Parameters:
  8678.  * fd - File descriptor of the stream
  8679.  *
  8680.  * Functions Referenced:
  8681.  * getmsg()
  8682.  * putmsg()
  8683.  * malloc()
  8684.  * bzero()
  8685.  *
  8686.  * Return code:
  8687.  * 0 - if successful
  8688.  * -1 - if not successful
  8689.  *****************************************************************************/
  8690. int
  8691. x25unbind(fd) int fd; {                 /* X25 device (opened) */
  8692.     int rc;                             /* return code */
  8693.     int flags;                          /* bind flags */
  8694.     int get_flags;                      /* priority flag for getmsg */
  8695.     ulong type;                         /* primitive type */
  8696.     N_unbind_req_t *unbind_req;         /* pointer to N_UNBIND_REQ */
  8697.     N_ok_ack_t *ok_ack;                 /* pointer to N_OK_ACK */
  8698.  
  8699. #ifdef TRACE
  8700.     printf( "TRACE: entering x25unbind\n" );
  8701. #endif /* TRACE */
  8702.  
  8703. #ifdef DEBUG
  8704.     /* printf( "x25unbind( %d )\n", fd ); */
  8705. #endif /* DEBUG */
  8706.     debug(F101,"x25unbind closing x25 connection #","",fd);
  8707.  
  8708.     /* Allocate and zero out space to hold the N_UNBIND_REQ primitive */
  8709.     unbind_req = (N_unbind_req_t *) malloc(sizeof(N_npi_ctl_t));
  8710.     if (unbind_req == NULL) {
  8711.         perror("kermit: x25unbind(): unbind_req malloc failed");
  8712.         return(-1);
  8713.     }
  8714.     bzero(unbind_req, sizeof(N_npi_ctl_t));
  8715.  
  8716.     /*
  8717.      * Build the Unbind Request Primitive
  8718.      */
  8719.     flags = 0;
  8720.     unbind_req->PRIM_type = (ulong) N_UNBIND_REQ;
  8721.  
  8722.     /*
  8723.      * Call putmsg() to put the bind request message on the stream
  8724.      */
  8725.     if (x25putmsg(fd,
  8726.                   (N_npi_ctl_t*)unbind_req,
  8727.                   (N_npi_data_t *)NULL,
  8728.                   0,
  8729.                   &flags
  8730.                   ) < 0) {
  8731.         perror ("kermit: x25unbind(): putmsg failed");
  8732.         return(-1);
  8733.     }
  8734.  
  8735.     /* Allocate and Zero out space for the N_OK_ACK primitive */
  8736.     ok_ack = (N_ok_ack_t *) malloc(sizeof(N_npi_ctl_t));
  8737.     if (ok_ack == NULL) {
  8738.         perror("kermit x25unbind(): ok_ack malloc failed\n");
  8739.         return(-1);
  8740.     }
  8741.     bzero(ok_ack, sizeof(N_npi_ctl_t));
  8742.  
  8743.     /* Initialize and build the control structure for getmsg */
  8744.     get_flags=0;
  8745.  
  8746.     /* Call getmsg() to check for an acknowledgement */
  8747.     rc = x25getmsg(fd,
  8748.                    (N_npi_ctl_t*)ok_ack,
  8749.                    (int)sizeof(N_ok_ack_t),
  8750.                    (N_npi_data_t*)NULL,
  8751.                    0,
  8752.                    &get_flags,
  8753.                    N_OK_ACK
  8754.                    );
  8755.     if (rc < 0) {
  8756.         perror ("kermit: x25unbind: getmsg failed");
  8757.         return(-1);
  8758.     }
  8759.  
  8760.     /* Free up the space that we no longer need */
  8761.     if (unbind_req) { free(unbind_req); unbind_req = NULL; }
  8762.     if (ok_ack) { free(ok_ack); ok_ack = NULL; }
  8763.  
  8764. #ifdef TRACE
  8765.     printf( "TRACE: leaving x25unbind\n" );
  8766. #endif /* TRACE */
  8767.  
  8768.     return(0);
  8769. }
  8770.  
  8771. /*****************************************************************************
  8772.  * Function: x25xin
  8773.  *
  8774.  * Description:
  8775.  *      Read n characters from X.25 circuit into buf (AIX only)
  8776.  *
  8777.  * Parameters:
  8778.  *      data_buf_len    maximum size of data buffer
  8779.  *      data_buf        pointer to pre-allocated buffer space
  8780.  *
  8781.  * Return Value:
  8782.  *      the number of characters actually read
  8783.  */
  8784. int
  8785. x25xin(data_buf_len,data_buf) int data_buf_len; CHAR *data_buf; {
  8786.     struct strbuf getmsg_ctl;           /* streams control structure */
  8787.     struct strbuf getmsg_data;          /* streams data structure */
  8788.     int rc = 0;                         /* return code */
  8789.     int getmsg_flags;                   /* packet priority flags */
  8790.     char * ctl_buf;                     /* npi control buffer */
  8791.     N_npi_ctl_t * result;               /* pointer to simplify switch() */
  8792.  
  8793. #ifdef TRACE
  8794.     printf( "TRACE: entering x25xin\n" );
  8795. #endif /* TRACE */
  8796.  
  8797.     /* ensure that no maximum's are overridden */
  8798.     data_buf_len = (NPI_MAX_DATA < data_buf_len) ? NPI_MAX_DATA : data_buf_len;
  8799.  
  8800.     /* allocate space for packet control info */
  8801.     if ((ctl_buf = (char *)malloc(NPI_MAX_CTL)) == NULL) {
  8802.         perror( "kermit: x25xin(): ctl_buf malloc" );
  8803.         return(-1);
  8804.     }
  8805. #ifdef COMMENT
  8806.     /* riehm: need zeroed buffer for getmsg? */
  8807.     bzero( ctl_buf, NPI_MAX_CTL );
  8808.     /* clear data buffer */
  8809.     bzero( data_buf, data_buf_len );
  8810. #endif /* COMMENT */
  8811.  
  8812.     getmsg_flags = 0;                   /* get the first packet available */
  8813.  
  8814.     rc = x25getmsg(ttyfd,
  8815.                    ctl_buf,
  8816.                    NPI_MAX_CTL,
  8817.                    data_buf,
  8818.                    data_buf_len,
  8819.                    &getmsg_flags,
  8820.                    N_DATA_IND
  8821.                    );
  8822. #ifdef COMMENT
  8823. #ifdef DEBUG
  8824.     if (rc >= 0) {
  8825.         printf( "kermit: x25xin(): got " );
  8826.         x25dump_data( data_buf, 0, rc );
  8827.     } else {
  8828.         printf( "x25xin(): attempt to get data resulted in an error\n" );
  8829.     }
  8830. #endif /* DEBUG */
  8831. #endif /* COMMENT */
  8832.  
  8833.     /* free buffers */
  8834.     if (ctl_buf) { free(ctl_buf); ctl_buf = NULL; }
  8835.  
  8836. #ifdef TRACE
  8837.     printf( "TRACE: leaving x25xi\n" );
  8838. #endif /* TRACE */
  8839.  
  8840.     return(rc);
  8841. }
  8842.  
  8843. /*****************************************************************************
  8844.  * Function: x25write
  8845.  *
  8846.  * Description:
  8847.  *      write a block of characters to the X25 STREAM (AIX)
  8848.  *
  8849.  * Parameters:
  8850.  *      fd              file descriptor to write to
  8851.  *      databuf         buffer containing data to write
  8852.  *      databufsize             size of the buffer to write
  8853.  *
  8854.  * Return Value:
  8855.  *      size            the number of bytes actually transmitted
  8856.  */
  8857. int
  8858. x25write(fd, databuf, databufsize)
  8859.     int         fd;                  /* X25 STREAMS file descriptor (ttyfd) */
  8860.     char        *databuf;               /* buffer to write */
  8861.     int         databufsize;            /* buffer size */
  8862. /* x25write */ {
  8863.     N_data_req_t *data_req_ctl;
  8864.     int rc;                             /* return code (size transmitted) */
  8865.     int write_flags = 0;                /* always 0 !? */
  8866.  
  8867. #ifdef TRACE
  8868.     printf( "TRACE: entering x25write\n" );
  8869. #endif /* TRACE */
  8870.  
  8871.     if ((data_req_ctl = (N_data_req_t *)malloc(NPI_MAX_CTL) ) == NULL) {
  8872.         perror( "kermit: x25write(): data_req_ctl malloc" );
  8873.         return(-1);
  8874.     }
  8875.     data_req_ctl->PRIM_type = N_DATA_REQ;
  8876.     data_req_ctl->DATA_xfer_flags = 0;
  8877.  
  8878.     /* riehm: possible extension
  8879.      * possibly need to think about splitting up the data buffer
  8880.      * into multiple parts if databufsize > NPI_MAX_DATA
  8881.      */
  8882.  
  8883. #ifdef COMMENT
  8884. #ifdef DEBUG
  8885.     printf( "kermit: x25write(): writing data to x25 stream\n" );
  8886.     printf( "\tdata:\t" );
  8887.     x25dump_data(databuf, 0, databufsize);
  8888. #endif /* DEBUG */
  8889. #endif /* COMMENT */
  8890.     rc = x25putmsg(fd,
  8891.                    (N_npi_ctl_t*)data_req_ctl,
  8892.                    (N_npi_data_t*)databuf,
  8893.                    databufsize,
  8894.                    &write_flags
  8895.                    );
  8896.     if (data_req) { free(data_req_ctl);  data_req = NULL; }
  8897.  
  8898. #ifdef TRACE
  8899.     printf( "TRACE: leaving x25write\n" );
  8900. #endif /* TRACE */
  8901.  
  8902.     return(rc);
  8903. }
  8904.  
  8905. /*****************************************************************************
  8906.  * Function: x25local_nua
  8907.  *
  8908.  * Description:
  8909.  *      This routine is only interesting for IBM computers. In order
  8910.  *      to set up a connection (see x25bind()) you need to know the
  8911.  *      local NUA (x25 address). Unfortunately, you need all this code
  8912.  *      to find that out, I just hope this works for everyone else!
  8913.  *
  8914.  * Parameters:
  8915.  *      a pre-allocated character buffer, long enough to hold an X.25 address
  8916.  *      and the tailing null.
  8917.  *
  8918.  * Return Value:
  8919.  *      the length of the address string.
  8920.  *      0 = error
  8921.  */
  8922. int
  8923. x25local_nua(char *buf) {
  8924.     struct CuAt *response;      /* structure to fill with info from ODM */
  8925.     CLASS_SYMBOL retClass;      /* ODM class */
  8926.     char query[64];             /* odm database query */
  8927.     int rc = 0;                 /* return value (length of local NUA) */
  8928.     extern char x25name[];      /* x25 device name (sx25a0) */
  8929.  
  8930. #ifdef TRACE
  8931.     printf( "TRACE: entering x25local_nua\n" );
  8932. #endif /* TRACE */
  8933.  
  8934.     /* set up query string */
  8935.     if (x25name[0] == '\0') {
  8936. #ifdef DEBUG
  8937.         printf( "kermit: x25local_nua(): No x25 device set, trying sx25a0\n" );
  8938. #endif /* DEBUG */
  8939.         strcpy( x25name, "sx25a0" );
  8940.     }
  8941.     ckmakmsg(query, sizeof(query), "name like ",x25name,
  8942.              " and attribute like local_nua");
  8943.  
  8944.     /* initialise ODM database */
  8945.     odmerrno = 0;
  8946.     if (odm_initialize() == -1) {
  8947.         printf( "x25local_nua(): can't initialize ODM database");
  8948.         switch (odmerrno) {
  8949.           case ODMI_INVALID_PATH:
  8950.             printf( "invalid path\n" );
  8951.             break;
  8952.           case ODMI_MALLOC_ERR:
  8953.             printf( "malloc failed\n" );
  8954.             break;
  8955.           default:
  8956.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8957.         }
  8958.         return(rc);
  8959.     }
  8960.  
  8961.     /* open the CuAt class */
  8962.     retClass = odm_open_class(CuAt_CLASS);
  8963.     if (((int)retClass) == -1) {
  8964.         printf( "kermit: x25local_nua(): can't open CuAt class in odm. " );
  8965.         switch (odmerrno) {
  8966.           case ODMI_CLASS_DNE:
  8967.             printf( "CuAt class doesn't exist\n" );
  8968.             break;
  8969.           case ODMI_CLASS_PERMS:
  8970.             printf( "permission to CuAt class file denied\n" );
  8971.             break;
  8972.           case ODMI_MAGICNO_ERR:
  8973.             printf( "CuAt is an invalid ODM object class\n" );
  8974.             break;
  8975.           case ODMI_OPEN_ERR:
  8976.             printf( "cannot open CuAt class - and don't know why!\n" );
  8977.             break;
  8978.           case ODMI_INVALID_PATH:
  8979.             printf( "invalid path\n" );
  8980.             break;
  8981.           case ODMI_TOOMANYCLASSES:
  8982.             printf( "too many object classes have been opened\n" );
  8983.             break;
  8984.           default:
  8985.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  8986.         }
  8987.         return(rc);
  8988.     }
  8989.  
  8990. #ifdef DEBUG
  8991.     printf("retClass= %d\n", retClass);
  8992. #endif /* DEBUG */
  8993.  
  8994.     response = (struct CuAt *)odm_get_first( retClass, query, NULL );
  8995.     if (((int)response) == -1) {
  8996.         printf( "kermit: x25local_nua(): odm query failed " );
  8997.         switch (odmerrno) {
  8998.           case ODMI_BAD_CRIT:           /* Programming error */
  8999.             printf( "bad search criteria\n" );
  9000.             break;
  9001.           case ODMI_CLASS_DNE:
  9002.             printf( "CuAt class doesn't exist\n" );
  9003.             break;
  9004.           case ODMI_CLASS_PERMS:
  9005.             printf( "permission to CuAt class file denied\n" );
  9006.             break;
  9007.           case ODMI_INTERNAL_ERR:
  9008.             printf("odm internal error\nPlease contact your administrator\n" );
  9009.             break;
  9010.           case ODMI_INVALID_CLXN:
  9011.             printf("CuAt is invalid or inconsistent odm class collection\n");
  9012.             break;
  9013.           case ODMI_INVALID_PATH:
  9014.             printf( "invalid path\n" );
  9015.             break;
  9016.           case ODMI_MAGICNO_ERR:
  9017.             printf( "CuAt is an invalid ODM object class\n" );
  9018.             break;
  9019.           case ODMI_MALLOC_ERR:
  9020.             printf( "malloc failed\n" );
  9021.             break;
  9022.           case ODMI_OPEN_ERR:
  9023.             printf( "cannot open CuAt class - and don't know why!\n" );
  9024.             break;
  9025.           case ODMI_TOOMANYCLASSES:
  9026.             printf( "too many object classes have been opened\n" );
  9027.             break;
  9028.           default:
  9029.             printf( "unknown error %d\nPlease call IBM\n", odmerrno );
  9030.         }
  9031.         return(rc);
  9032.     }
  9033.  
  9034.     /* check for a meaningfull response */
  9035.     if (response != NULL) {
  9036.         if (response->value != NULL) {
  9037.             strcpy(buf, response->value);
  9038.             rc = strlen( buf );
  9039. #ifdef DEBUG
  9040. /*
  9041.             printf( "attribute name is: %s\n", (char *)response->attribute );
  9042.             printf( "I think my address is %s\n", (char*)response->value );
  9043. */
  9044. #endif /* DEBUG */
  9045.         } else {
  9046.             printf( "kermit: x25local_nua(): couldn't find the local NUA\n" );
  9047.         }
  9048.     } else {
  9049.         switch (odmerrno) {
  9050.           case ODMI_BAD_CRIT:
  9051.             printf( "Error: ODMI_BAD_CRIT - bad criteria\n" );
  9052.             break;
  9053.           case ODMI_CLASS_DNE:
  9054.             printf( "Error: ODMI_CLASS_DNE - class doesn't exist\n" );
  9055.             break;
  9056.           case ODMI_CLASS_PERMS:
  9057.             printf( "Error: ODMI_CLASS_PERMS - class permissions\n" );
  9058.             break;
  9059.           case ODMI_INTERNAL_ERR:
  9060.             printf( "Error: ODMI_INTERNAL_ERR - panic\n" );
  9061.             break;
  9062.           case ODMI_INVALID_CLXN:
  9063.             printf( "Error: ODMI_INVALID_CLXN - invalid collection\n" );
  9064.             break;
  9065.           case ODMI_INVALID_PATH:
  9066.             printf( "Error: ODMI_INVALID_PATH - invalid path - what path?\n" );
  9067.             break;
  9068.           case ODMI_MAGICNO_ERR:
  9069.             printf( "Error: ODMI_MAGICNO_ERR - invalid object magic\n" );
  9070.             break;
  9071.           case ODMI_MALLOC_ERR:
  9072.             printf( "Error: ODMI_MALLOC_ERR - malloc failed\n" );
  9073.             break;
  9074.           case ODMI_OPEN_ERR:
  9075.             printf( "Error: ODMI_OPEN_ERR - cannot open class\n" );
  9076.             break;
  9077.           case ODMI_TOOMANYCLASSES:
  9078.             printf( "Error: ODMI_TOOMANYCLASSES - too many classes\n" );
  9079.             break;
  9080.           default:
  9081.             printf( "Unknown error!\n" );
  9082.         }
  9083.         return(rc);
  9084.     }
  9085.  
  9086.     /* close the database again */
  9087.     odm_close_class( retClass );
  9088.  
  9089.     /* forget about ODM all together */
  9090.     odm_terminate();
  9091.  
  9092. #ifdef TRACE
  9093.     printf( "TRACE: leaving x25local_nua\n" );
  9094. #endif /* TRACE */
  9095.  
  9096.     debug(F110, "x25local_nua local address is ", buf, 0);
  9097.     return(rc);
  9098. }
  9099.  
  9100. /*****************************************************************************
  9101.  * Function: x25facilities
  9102.  *
  9103.  * Description:
  9104.  *      build up the facilities data packet for a connection request
  9105.  *
  9106.  * Parameters:
  9107.  *      a pre-allocated char buffer, normally NPI_MAX_DATA big.
  9108.  *
  9109.  * Return Value:
  9110.  *      the number of characters inserted into the buffer
  9111.  */
  9112. int
  9113. x25facilities(buffer) char *buffer; {
  9114.     extern int revcall;
  9115.     extern int closgr;
  9116.     char *p;                            /* temp pointer */
  9117.     char *start;                        /* temp pointer */
  9118.  
  9119. #ifdef TRACE
  9120.     printf( "TRACE: entering x25facilities\n" );
  9121. #endif /* TRACE */
  9122.  
  9123.     p = buffer + 1;
  9124.     start = p;
  9125.  
  9126. #ifdef DEBUG
  9127.     printf( "kermit: x25facilities(): getting X25 facilities\n" );
  9128. #endif /* DEBUG */
  9129.  
  9130.     if (revcall != 0) {
  9131. #ifdef DEBUG
  9132.         printf("reverse charge: %d\n", revcall );
  9133. #endif /* DEBUG */
  9134.         *++p = 0x01;
  9135.         *++p = revcall;
  9136.     }
  9137.     if (closgr > 0) {
  9138. #ifdef DEBUG
  9139.         printf("closed user group: %d\n", closgr );
  9140. #endif /* DEBUG */
  9141.         *++p = 0x03;
  9142.         *++p = closgr;
  9143.     }
  9144.  
  9145. #ifdef DEBUG
  9146.     if (p == start) {
  9147.         printf( "no facilities\n" );
  9148.     }
  9149. #endif /* DEBUG */
  9150.  
  9151.     /* set the size of the facilities buffer */
  9152.     *buffer = (char)( p - start ) & 0xff;
  9153.  
  9154. #ifdef DEBUG
  9155.     printf( "kermit: x25facilities(): returning %d\n", (int)(p - buffer)  );
  9156. #endif /* DEBUG */
  9157.  
  9158. #ifdef TRACE
  9159.     printf( "TRACE: leaving x25facilities\n" );
  9160. #endif /* TRACE */
  9161.  
  9162.     /* return the size of the facilities with size byte */
  9163.     /* 1 == no facilities, 0 byte returned as facilities size */
  9164.     return( (int)(p - buffer) );
  9165. }
  9166.  
  9167. /*
  9168.  * reset the connection
  9169.  */
  9170. int
  9171. x25reset(cause, diagn) char cause; char diagn; {
  9172.     /* not implemented */
  9173.  
  9174. #ifdef TRACE
  9175.     printf( "TRACE: entering x25reset\n" );
  9176. #endif /* TRACE */
  9177.  
  9178. #ifdef TRACE
  9179.     printf( "TRACE: leaving x25reset\n" );
  9180. #endif /* TRACE */
  9181.  
  9182.     return(0);
  9183. }
  9184.  
  9185. /*
  9186.  * clear the x25 connection - ie: hang up
  9187.  */
  9188. int
  9189. x25clear() {
  9190.     int get_flags = 0;                  /* priority flag for getmsg */
  9191.     int put_flags = 0;                  /* send flags, always 0 */
  9192.     ulong type;                         /* primitive type */
  9193.     N_discon_req_t *discon_req;         /* pointer to N_DISCON_REQ */
  9194.     N_discon_ind_t *discon_ind;         /* pointer to N_DISCON_IND */
  9195.     N_npi_data_t *discon_data;          /* pointer to N_DISCON_IND data */
  9196.     int rc = 0;                         /* return code */
  9197.  
  9198. #ifdef TRACE
  9199.     printf( "TRACE: entering x25clear\n" );
  9200. #endif /* TRACE */
  9201.  
  9202. #ifdef DEBUG
  9203.     /* printf( "x25clear(): checking last msg: %s\n", x25prim(x25lastmsg)); */
  9204. #endif /* DEBUG */
  9205.  
  9206.     /*
  9207.     * The following checks are used to ensure that we don't disconnect
  9208.     * or unbind twice - this seems to throw the NPI interface right out of
  9209.     * kilter.
  9210.     */
  9211.     switch(x25lastmsg) {
  9212.       case N_BIND_ACK:
  9213.       case N_CONN_CON:
  9214.       case N_CONN_REQ:
  9215.       case N_DATA_REQ:
  9216.       case N_DATA_IND:
  9217.         {
  9218. #ifdef DEBUG
  9219.             /* printf("x25clear(): actively disconnecting\n"); */
  9220. #endif /* DEBUG */
  9221.  
  9222.                 discon_req = (N_discon_req_t *)malloc(NPI_MAX_CTL);
  9223.                 if (discon_req == NULL) {
  9224.                     perror("kermit x25clear(): discon_req malloc failed\n");
  9225.                     /* fallthrough, try to unbind the NPI anyway */
  9226.                 } else {
  9227.                     discon_req->PRIM_type = N_DISCON_REQ;
  9228.                     discon_req->DISCON_reason = 0;      /* not used by AIX */
  9229.                     discon_req->RES_length = 0;
  9230.                     discon_req->RES_offset = (ulong)(sizeof(N_discon_req_t));
  9231.                     discon_req->SEQ_number = x25seqno;  /* global */
  9232.  
  9233.                     if (x25putmsg(ttyfd,
  9234.                                   (N_npi_ctl_t*)discon_req,
  9235.                                   (N_npi_data_t*)NULL,
  9236.                                   0,
  9237.                                   &put_flags
  9238.                                   ) < 0) {
  9239.                         perror("x25putmsg failed in x25clear()");
  9240.                     }
  9241.                     discon_ind = (N_discon_ind_t *)malloc(NPI_MAX_CTL);
  9242.                     discon_data = (N_npi_data_t *)malloc(NPI_MAX_DATA);
  9243.                     if((discon_ind == NULL) || (discon_data == NULL)) {
  9244.                         perror("x25clear(): discon_ind malloc failed\n");
  9245.                         /* fallthrough, try to unbind the NPI anyway */
  9246.                     } else {
  9247.                         if(x25getmsg(ttyfd,
  9248.                                      (N_npi_ctl_t*)discon_ind,
  9249.                                      NPI_MAX_CTL,
  9250.                                      (N_npi_data_t*)discon_data,
  9251.                                      NPI_MAX_DATA,
  9252.                                      &get_flags,
  9253.                                      N_OK_ACK
  9254.                                      ) < 0 ) {
  9255.                             perror("x25getmsg failed in x25clear()");
  9256.                             /* fallthrough, try to unbind the NPI anyway */
  9257.                         }
  9258.                     }
  9259.                 }
  9260.                 break;
  9261.             }
  9262.     }
  9263.  
  9264.     if (x25lastmsg != N_UNBIND_REQ) {
  9265.         rc = x25unbind(ttyfd);
  9266.     }
  9267.  
  9268. #ifdef TRACE
  9269.     printf( "TRACE: leaving x25clear\n" );
  9270. #endif /* TRACE */
  9271.  
  9272.     return(rc);
  9273. }
  9274.  
  9275. #ifdef DEBUG
  9276. /*
  9277.  * only for debugging
  9278.  *
  9279.  * turn the internal representation of a datablock into something
  9280.  * half-way readable. Because the length is known, we can print
  9281.  * the string including null's etc (important, because the first(!)
  9282.  * byte of an X121 address is a null! (X121 addr == 0 + X25 addr)
  9283.  */
  9284. x25dump_data(char *addr, ulong offset, ulong length) {
  9285.     char *ptr = addr + offset;
  9286.     ulong i = length;
  9287.     /* allocate enough memory for all unprintable chars */
  9288.     char *buf = (char *)malloc( length * 4 );
  9289.     char *bptr = buf;   /* pointer to current place in the print buffer */
  9290.  
  9291.     while (i > 0) {
  9292.         if (isprint(*ptr)) {
  9293.             *bptr++ = *ptr;
  9294.         } else {
  9295.             *bptr++ = '[';
  9296.             strcpy(bptr,ckctox(*ptr,1)); bptr += 2;
  9297.             *bptr++ = ']';
  9298.         }
  9299.         ptr++;
  9300.         i--;
  9301.     }
  9302.     if (length > 0) {
  9303.         *bptr = '\0';
  9304.         printf( "%s", buf );
  9305.     }
  9306.     printf( " (%d+%d)\n", offset, length );
  9307.  
  9308.     if (buf) { free(buf); buf = NULL; }
  9309.     return;
  9310. }
  9311.  
  9312. /*
  9313.  * only for debugging
  9314.  * print as much useful information about a packet as possible
  9315.  */
  9316. x25dump_prim(primitive)    N_npi_ctl_t *primitive; {
  9317.     printf("Primitive");
  9318.     switch (primitive->PRIM_type) {
  9319.       case N_BIND_ACK:
  9320.         printf( "\tN_BIND_ACK\n\taddress:\t" );
  9321.         x25dump_data( (char *)primitive,
  9322.                      primitive->bind_ack.ADDR_offset,
  9323.                      primitive->bind_ack.ADDR_length );
  9324.         printf( "\tproto id:\t" );
  9325.         x25dump_data( (char *)primitive,
  9326.                      primitive->bind_ack.PROTOID_offset,
  9327.                      primitive->bind_ack.PROTOID_length );
  9328.         printf( "\tconnind:\t%d\n\ttoken:\t\t%d\n",
  9329.                primitive->bind_ack.CONIND_number,
  9330.                primitive->bind_ack.TOKEN_value );
  9331.         break;
  9332.  
  9333.       case N_BIND_REQ:
  9334.         printf( "\tN_BIND_REQ\n\taddress:\t" );
  9335.         x25dump_data( (char *)primitive,
  9336.                      primitive->bind_req.ADDR_offset,
  9337.                      primitive->bind_req.ADDR_length );
  9338.         printf( "\tproto id:\t" );
  9339.         x25dump_data( (char *)primitive,
  9340.                      primitive->bind_req.PROTOID_offset,
  9341.                      primitive->bind_req.PROTOID_length );
  9342.         printf( "\tconnind:\t%d\n\tflags:\t\t%d\n",
  9343.                primitive->bind_req.CONIND_number,
  9344.                primitive->bind_req.BIND_flags );
  9345.         break;
  9346.  
  9347.       case N_CONN_CON:
  9348.         printf( "\tN_CONN_CON\n" );
  9349.         printf( "\tRES\t\t" );
  9350.         x25dump_data( (char *)primitive,
  9351.                      primitive->conn_con.RES_offset,
  9352.                      primitive->conn_con.RES_length );
  9353.         printf( "\tflags:\t%d\n", primitive->conn_con.CONN_flags );
  9354.         break;
  9355.  
  9356.       case N_CONN_IND:
  9357.         printf( "\tN_CONN_IND\n" );
  9358.         printf( "\tsource:\t\t" );
  9359.         x25dump_data( (char *)primitive,
  9360.                      primitive->conn_ind.SRC_offset,
  9361.                      primitive->conn_ind.SRC_length );
  9362.         printf( "\tdestination:\t" );
  9363.         x25dump_data( (char *)primitive,
  9364.                      primitive->conn_ind.DEST_offset,
  9365.                      primitive->conn_ind.DEST_length );
  9366.         printf( "\tSEQ_number:\t%d\n", primitive->conn_ind.SEQ_number );
  9367.         printf( "\tflags:\t%d\n", primitive->conn_ind.CONN_flags );
  9368.         break;
  9369.  
  9370.       case N_CONN_REQ:
  9371.         printf( "\tN_CONN_REQ\n\tdestination:\t" );
  9372.         x25dump_data( (char *)primitive,
  9373.                      primitive->conn_req.DEST_offset,
  9374.                      primitive->conn_req.DEST_length );
  9375.         printf( "\tflags:\t%d\n", primitive->conn_req.CONN_flags );
  9376.         break;
  9377.  
  9378.       case N_CONN_RES:
  9379.         printf( "\tN_CONN_RES\n" );
  9380.         printf( "\tTOKEN_value\t%d\n", primitive->conn_res.TOKEN_value );
  9381.         printf( "\tSEQ_number\t%d\n", primitive->conn_res.SEQ_number );
  9382.         printf( "\tCONN_flags\t%d\n", primitive->conn_res.CONN_flags );
  9383.         printf( "\tRES\t\t" );
  9384.         x25dump_data( (char *)primitive,
  9385.                      primitive->conn_res.RES_offset,
  9386.                      primitive->conn_res.RES_length );
  9387.         break;
  9388.  
  9389.       case N_DATACK_IND:
  9390.         printf( "\tN_DATACK_IND\n" );
  9391.         break;
  9392.  
  9393.       case N_DATACK_REQ:
  9394.         printf( "\tN_DATACK_REQ\n" );
  9395.         printf( "\tflags:\t%d\n", primitive->data_req.DATA_xfer_flags );
  9396.         break;
  9397.  
  9398.       case N_DATA_IND:
  9399.         printf( "\tN_DATA_IND\n" );
  9400.         printf( "\tflags:\t%d\n", primitive->data_ind.DATA_xfer_flags );
  9401.         break;
  9402.  
  9403.       case N_DATA_REQ:
  9404.         printf( "\tN_DATA_REQ\n" );
  9405.         break;
  9406.  
  9407.       case N_DISCON_IND:
  9408.         printf( "\tN_DISCON_IND\n" );
  9409.         printf( "\torigin:\t%d\n", primitive->discon_ind.DISCON_orig );
  9410.         printf( "\treason:\t\t%d\n", primitive->discon_ind.DISCON_reason );
  9411.         printf( "\tseq no:\t\t%d\n", primitive->discon_ind.SEQ_number );
  9412.         printf( "\tRES:\t" );
  9413.         x25dump_data( (char *)primitive,
  9414.                      primitive->discon_ind.RES_offset,
  9415.                      primitive->discon_ind.RES_length );
  9416.         break;
  9417.  
  9418.       case N_DISCON_REQ:
  9419.         printf( "\tN_DISCON_REQ\n" );
  9420.         printf( "\tDISCON_reason:\t%d\n",
  9421.                primitive->discon_req.DISCON_reason );
  9422.         printf( "\tRES:\t" );
  9423.         x25dump_data( (char *)primitive,
  9424.                      primitive->discon_req.RES_offset,
  9425.                      primitive->discon_req.RES_length );
  9426.         printf( "\tSEQ_number:\t%d\n", primitive->discon_req.SEQ_number );
  9427.         break;
  9428.  
  9429.       case N_ERROR_ACK:
  9430.         printf( "\tN_ERROR_ACK\n" );
  9431.         printf( "\tCaused by:\t%s\n",
  9432.                x25prim( primitive->error_ack.ERROR_prim ) );
  9433.         printf( "\tNPI error:\t%s\n",
  9434.                x25err( primitive->error_ack.NPI_error ));
  9435.         errno = primitive->error_ack.UNIX_error;
  9436.         perror( "\t" );
  9437.         break;
  9438.  
  9439.       case N_EXDATA_IND:
  9440.         printf( "\tN_EXDATA_ACK\n" );
  9441.         break;
  9442.  
  9443.       case N_EXDATA_REQ:
  9444.         printf( "\tN_EXDATA_REQ\n" );
  9445.         break;
  9446.  
  9447.       case N_INFO_ACK:
  9448.         printf( "\tN_INFO_ACK\n" );
  9449.         printf( "\tNSDU size:\t%d\n", primitive->info_ack.NSDU_size );
  9450.         printf( "\tENSDU size:\t%d\n", primitive->info_ack.ENSDU_size );
  9451.         printf( "\tCDATA size:\t%d\n", primitive->info_ack.CDATA_size );
  9452.         printf( "\tDDATA size:\t%d\n", primitive->info_ack.DDATA_size );
  9453.         printf( "\tADDR size:\t%d\n", primitive->info_ack.ADDR_size );
  9454.         printf( "\tNIDU size:\t%d\n", primitive->info_ack.NIDU_size );
  9455.         break;
  9456.  
  9457.       case N_INFO_REQ:
  9458.         printf( "\tN_INFO_REQ\n" );
  9459.         break;
  9460.  
  9461.       case N_OK_ACK:
  9462.         printf( "\tN_OK_ACK\n" );
  9463.         break;
  9464.  
  9465.       case N_OPTMGMT_REQ:
  9466.         printf( "\tN_OPTMGMT_REQ\n" );
  9467.         break;
  9468.  
  9469.       case N_RESET_CON:
  9470.         printf( "\tN_RESET_CON\n" );
  9471.         break;
  9472.  
  9473.       case N_RESET_IND:
  9474.         printf( "\tN_RESET_IND\n" );
  9475.         printf( "\treason:\t\t%d\n", primitive->reset_ind.RESET_reason );
  9476.         printf( "\torigin:\t\t%d\n", primitive->reset_ind.RESET_orig );
  9477.         break;
  9478.  
  9479.       case N_RESET_REQ:
  9480.         printf( "\tN_RESET_REQ\n" );
  9481.         printf( "\treason:\t\t%d\n", primitive->reset_req.RESET_reason );
  9482.         break;
  9483.  
  9484.       case N_RESET_RES:
  9485.         printf( "\tN_RESET_RES\n" );
  9486.         break;
  9487.  
  9488.       case N_UDERROR_IND:
  9489.         printf( "\tN_UDERROR_IND\n" );
  9490.         break;
  9491.  
  9492.       case N_UNBIND_REQ:
  9493.         printf( "\tN_UNBIND_REQ\n" );
  9494.         break;
  9495.  
  9496.       case N_UNITDATA_REQ:
  9497.         printf( "\tN_UNITDATA_REQ\n" );
  9498.         break;
  9499.  
  9500.       case N_UNITDATA_IND:
  9501.         printf( "\tN_UNITDATA_IND\n" );
  9502.         break;
  9503.  
  9504.       default:
  9505.         (void) printf( "Unknown NPI error %d", primitive->PRIM_type );
  9506.         return 0;
  9507.     }
  9508. }
  9509. #endif /* DEBUG */
  9510.  
  9511. /* it looks like signal handling is not needed with streams! */
  9512. /* x25oobh()    - handle SIGURG signals - take from isode ? */
  9513.  
  9514. #endif /* IBMX25 */
  9515.  
  9516. #ifndef NOHTTP
  9517. /*
  9518.   Which time.h files to include... See ckcdeb.h for defaults.
  9519.   Note that 0, 1, 2, or all 3 of these can be included according to
  9520.   the symbol definitions.
  9521. */
  9522. #ifndef NOTIMEH
  9523. #ifdef TIMEH
  9524. #include <time.h>
  9525. #endif /* TIMEH */
  9526. #endif /* NOTIMEH */
  9527.  
  9528. #ifndef NOSYSTIMEH
  9529. #ifdef SYSTIMEH
  9530. #include <sys/time.h>
  9531. #endif /* SYSTIMEH */
  9532. #endif /* NOSYSTIMEH */
  9533.  
  9534. #ifndef NOSYSTIMEBH
  9535. #ifdef SYSTIMEBH
  9536. #include <sys/timeb.h>
  9537. #endif /* SYSTIMEBH */
  9538. #endif /* NOSYSTIMEBH */
  9539.  
  9540. #ifndef TIMEH
  9541. #ifndef SYSTIMEH
  9542. #ifndef SYSTIMEBH
  9543. #ifdef Plan9
  9544. #include <sys/time.h>
  9545. #else
  9546. #ifdef AIX41
  9547. #include <time.h>
  9548. #else
  9549. #ifdef SUNOS4
  9550. #include <sys/time.h>
  9551. #else
  9552. #ifdef SYSTIMEH
  9553. #include <sys/time.h>
  9554. #else
  9555. #ifdef POSIX
  9556. #include <posix/time.h>
  9557. #else
  9558. #ifdef CLIX
  9559. #include <sys/time.h>
  9560. #else
  9561. #ifdef OS2
  9562. #include <time.h>
  9563. #else
  9564. #include <time.h>
  9565. /* #include <utime.h> */
  9566. #endif /* OS2 */
  9567. #endif /* CLIX */
  9568. #endif /* POSIX */
  9569. #endif /* SYSTIMEH */
  9570. #endif /* SUNOS4 */
  9571. #endif /* AIX41 */
  9572. #endif /* Plan9 */
  9573. #endif
  9574. #endif
  9575. #endif
  9576.  
  9577. #ifdef OS2
  9578. #include <sys/utime.h>
  9579. #ifdef NT
  9580. #define utimbuf _utimbuf
  9581. #endif /* NT */
  9582. #define utime   _utime
  9583. #else
  9584. #ifdef SYSUTIMEH                        /* <sys/utime.h> if requested,  */
  9585. #include <sys/utime.h>                  /* for extra fields required by */
  9586. #else                                   /* 88Open spec. */
  9587. #ifdef UTIMEH                           /* or <utime.h> if requested */
  9588. #include <utime.h>                      /* (SVR4, POSIX) */
  9589. #define SYSUTIMEH                       /* Use this for both cases. */
  9590. #endif /* UTIMEH */
  9591. #endif /* SYSUTIMEH */
  9592. #endif /* OS2 */
  9593.  
  9594. #ifndef HTTP_VERSION
  9595. #define HTTP_VERSION "HTTP/1.1"
  9596. #endif /* HTTP_VERSION */
  9597.  
  9598. #ifdef CMDATE2TM
  9599. time_t
  9600. #ifdef CK_ANSIC
  9601. http_date(char * date)
  9602. #else
  9603. http_date(date) char * date;
  9604. #endif /* CK_ANSIC */
  9605. /* http_date */ {
  9606.     /* HTTP dates are of the form:  "Sun, 06 Oct 1997 20:11:47 GMT" */
  9607.     /* There are two older formats which we are required to parse
  9608.      * that we currently do not:
  9609.      *
  9610.      * RFC 850:   "Sunday, 06-Oct-97 20:11:47 GMT"
  9611.      * asctime(): "Sun Nov  6 20:11:47 1997"
  9612.      *
  9613.      * However, it is required that all dates be sent in the form we
  9614.      * do accept.  The other two formats are for compatibility with
  9615.      * really old servers.
  9616.      */
  9617.     extern char cmdatebuf[18];
  9618.     struct tm t_tm;
  9619.     time_t t;
  9620.     char ldate[32];
  9621.     int j;
  9622.  
  9623.     j = ckindex(",",date,0,0,0);
  9624.     ckstrncpy(ldate,&date[j+1],25);
  9625.  
  9626.     {   /*
  9627.            cmcvtate() date changed to return a string pointer.
  9628.            fdc, 12 Aug 2001.
  9629.         */
  9630.         char * dp;
  9631.         dp = (char *)cmcvtdate(ldate,0); /* Convert to normal form */
  9632.         if (!dp)
  9633.           return(0);
  9634.         t_tm = *cmdate2tm(dp,1);
  9635.     }
  9636. /*
  9637.   From Lucas Hart, 5 Dec 2001:
  9638.   "On the systems to which I have access (SunOS 4.1.1, Solaris 8, and Tru64),
  9639.   setting tm_isdst to -1 maintains the correct timezone offsets, i.e., writes
  9640.   the specified (GMT) time if the buffer size is 21, or the contemporaneous
  9641.   localtime if the buffer size is 25.  Perhaps tm_isdst should be set in
  9642.   cmdate2tm(), rather than only in http_date."
  9643. */
  9644. #ifndef NOTM_ISDST                      /* For platforms where */
  9645.     t_tm.tm_isdst = -1;                 /* tm_isdst doesn't exist. */
  9646. #endif /* NOTM_ISDST */
  9647.  
  9648.     t = mktime(&t_tm);                  /* NOT PORTABLE */
  9649.  
  9650. #ifdef XX_TIMEZONE
  9651.     t -= _timezone;
  9652. #endif /* XX_TIMEZONE */
  9653.  
  9654.     return(t);
  9655. }
  9656. #endif /* CMDATE2TM */
  9657.  
  9658. char *
  9659. http_now() {
  9660.     static char nowstr[32];
  9661. #ifdef CMDATE2TM
  9662.     struct tm  *gmt;
  9663.     time_t ltime;                       /* NOT PORTABLE */
  9664.  
  9665.     time(<ime);
  9666.  
  9667.     gmt = gmtime(<ime);               /* PROBABLY NOT PORTABLE */
  9668.     strftime(nowstr,32,"%a, %d %b %Y %H:%M:%S GMT",gmt); /* NOT PORTABLE */
  9669.     /* not only is it not portable but it's locale-dependent */
  9670. #else
  9671. /*
  9672.   This is hopeless.  First of all, it seems that HTTP wants Day and Month
  9673.   NAMES?  In English?  Whose idea was that?  Even worse, the date/time must be
  9674.   expressed in Zulu (UTC (GMT)), and converting from local time to GMT is a
  9675.   nightmare.  Every platform does it differently, if at all -- even if we
  9676.   restrict ourselves to UNIX.  For example (quoting from recent C-Kermit edit
  9677.   history), "Fixed a longstanding bug in the BSDI version, in which incoming
  9678.   file dates were set in GMT rather than local time.  It seems in 4.4BSD,
  9679.   localtime() does not return the local time, but rather Zero Meridian (Zulu)
  9680.   time (GMT), and must be adjusted by the tm_gmtoff value."  Swell.  For
  9681.   greater appreciation of the scope of the problem, just take a look at the
  9682.   time-related #ifdefs in ckutio.c.  The only right way to do this is to add
  9683.   our own portable API for converting between local time and GMT/UTC/Zulu
  9684.   that shields us not only from UNIXisms like time_t and struct tm, but also
  9685.   the unbelievable amount of differences in time-related APIs -- e.g. is
  9686.   "timezone" an external variable or a function; which header file(s) do we
  9687.   include, etc etc etc.  It's a major project.
  9688. */
  9689.     int x;
  9690.     x = cmcvtdate("",1);
  9691.  
  9692. Evidently this code is not used -- if it is, it must be fixed to use
  9693. new (aug 2001) cmcvtdate() calling conventions.
  9694.  
  9695.     if (x < 0)
  9696.       return("");
  9697. /*  yyyymmdd hh:mm:ss */
  9698. /*  01234567890123456 */
  9699.     nowstr[0]  = 'X';                   /* 1st letter of day */
  9700.     nowstr[1]  = 'x';                   /* 2nd letter of day */
  9701.     nowstr[2]  = 'x';                   /* 3rd letter of day */
  9702.     nowstr[3]  = ',';
  9703.     nowstr[4]  = ' ';
  9704.     nowstr[5]  = cmdate[6];
  9705.     nowstr[6]  = cmdate[7];
  9706.     nowstr[7]  = ' ';
  9707.     nowstr[8]  = ' ';                   /* first letter of month */
  9708.     nowstr[9]  = ' ';                   /* second letter of month */
  9709.     nowstr[10] = ' ';                   /* third letter of month */
  9710.     nowstr[11] = ' ';
  9711.     nowstr[12] = cmdate[0];
  9712.     nowstr[13] = cmdate[1];
  9713.     nowstr[14] = cmdate[2];
  9714.     nowstr[15] = cmdate[3];
  9715.     nowstr[16] = ' ';
  9716.     nowstr[17] = cmdate[9];
  9717.     nowstr[18] = cmdate[10];
  9718.     nowstr[19] = cmdate[11];
  9719.     nowstr[20] = cmdate[12];
  9720.     nowstr[21] = cmdate[13];
  9721.     nowstr[22] = cmdate[14];
  9722.     nowstr[23] = cmdate[15];
  9723.     nowstr[24] = cmdate[16];
  9724.     nowstr[25] = ' ';
  9725.     nowstr[26] = 'G';
  9726.     nowstr[27] = 'M';
  9727.     nowstr[28] = 'T';
  9728.     nowstr[29] = '\0';
  9729. #endif /* CMDATE2TM */
  9730.     return(nowstr);
  9731. }
  9732.  
  9733. #ifndef OS2
  9734. #ifndef CK_AUTHENTICATION
  9735. /* from ckuusr.h, which this module normally doesn't include */
  9736. _PROTOTYP( int dclarray, (char, int) );
  9737. #endif /* CK_AUTHENTICATION */
  9738. #endif /* OS2 */
  9739. /*
  9740.   Assign http response pairs to given array.
  9741.   For best results, response pairs should contain no spaces.
  9742.  
  9743.   Call with:
  9744.     resp  =  pointer to response list.
  9745.     n     =  size of response list.
  9746.     array =  array letter.
  9747.   Returns:
  9748.     0 on failure.
  9749.     >= 1, size of array, on success.
  9750. */
  9751. static int
  9752. #ifdef CK_ANSIC
  9753. http_mkarray(char ** resp, int n, char array)
  9754. #else
  9755. http_mkarray(resp, n, array) char ** resp; int n; char array;
  9756. #endif /* CK_ANSIC */
  9757. {
  9758. #ifndef NOSPL
  9759.     int i, x;
  9760.     char ** ap;
  9761.     extern char ** a_ptr[];
  9762.     extern int a_dim[];
  9763.  
  9764.     if (!array || n <= 0)
  9765.       return(0);
  9766.     if ((x = dclarray(array,n)) < 0) {
  9767.         printf("?Array declaration failure\n");
  9768.         return(-9);
  9769.     }
  9770.     /* Note: argument array is 0-based but Kermit array is 1-based */
  9771.     ap = a_ptr[x];
  9772.     ap[0] = NULL;                       /* 0th element is empty */
  9773.     for (i = 1; i <= n; i++) {
  9774.         ap[i] = resp[i-1];              /* If resp elements were malloc'd */
  9775.         resp[i-1] = NULL;
  9776.     }
  9777.     a_dim[x] = n;
  9778.     return(n);
  9779. #else
  9780.     return(0);
  9781. #endif /* NOSPL */
  9782. }
  9783.  
  9784. #define HTTPHEADCNT 64
  9785. int
  9786. http_get_chunk_len()
  9787. {
  9788.     int len = 0;
  9789.     int i = 0, j = -1;
  9790.     char buf[24];
  9791.     int ch;
  9792.  
  9793.     while ((ch = http_inc(0)) >= 0 && i < 24) {
  9794.         buf[i] = ch;
  9795.         if ( buf[i] == ';' )            /* Find chunk-extension (if any) */
  9796.             j = i;
  9797.         if ( buf[i] == 10 ) {           /* found end of line */
  9798.             if (i > 0 && buf[i-1] == 13)
  9799.                 i--;
  9800.             buf[i] = '\0';
  9801.             break;
  9802.         }
  9803.         i++;
  9804.     }
  9805.     if ( i < 24 ) {                     /* buf now contains len in Hex */
  9806.         len = hextoulong(buf, j == -1 ? i : j-1);
  9807.     }
  9808.  
  9809.     return(len);
  9810. }
  9811.  
  9812. int
  9813. http_isconnected()
  9814. {
  9815.     return(httpfd != -1);
  9816. }
  9817.  
  9818. char *
  9819. http_host()
  9820. {
  9821.     return(httpfd != -1 ? http_host_port : "");
  9822. }
  9823.  
  9824. char *
  9825. http_security()
  9826. {
  9827.     if ( httpfd == -1 )
  9828.         return("NULL");
  9829. #ifdef CK_SSL
  9830.     if (tls_http_active_flag) {
  9831.         SSL_CIPHER * cipher;
  9832.         const char *cipher_list;
  9833.         static char buf[128];
  9834.         buf[0] = NUL;
  9835.         cipher = SSL_get_current_cipher(tls_http_con);
  9836.         cipher_list = SSL_CIPHER_get_name(cipher);
  9837.         SSL_CIPHER_description(cipher,buf,sizeof(buf));
  9838.         return(buf);
  9839.     }
  9840. #endif /* CK_SSL */
  9841.     return("NULL");
  9842. }
  9843.  
  9844. int
  9845. http_reopen()
  9846. {
  9847.     int rc = 0;
  9848.     char * s = NULL;                    /* strdup is not portable */
  9849.     makestr(&s,(char *)http_ip);
  9850.     rc = http_open(s,ckuitoa(http_port),http_ssl,NULL,0);
  9851.     free(s);
  9852.     return(rc);
  9853. }
  9854.  
  9855.  
  9856. int
  9857. #ifdef CK_ANSIC
  9858. http_open(char * hostname, char * svcname, int use_ssl, char * rdns_name,
  9859.           int rdns_len)
  9860. #else /* CK_ANSIC */
  9861. http_open(hostname, svcname, use_ssl, rdns_name, rdns_len)
  9862.     char * hostname;
  9863.     char * svcname;
  9864.     int    use_ssl;
  9865.     char * rdns_name;
  9866.     int    rdns_len;
  9867. #endif /* CK_ANSIC */
  9868. {
  9869.     char *p;
  9870.     int i, x, dns = 0;
  9871. #ifdef TCPSOCKET
  9872.     int isconnect = 0;
  9873. #ifdef SO_OOBINLINE
  9874.     int on = 1;
  9875. #endif /* SO_OOBINLINE */
  9876.     struct servent *service=NULL;
  9877.     struct hostent *host=NULL;
  9878.     struct sockaddr_in r_addr;
  9879.     struct sockaddr_in sin;
  9880.     struct sockaddr_in l_addr;
  9881.     GSOCKNAME_T l_slen;
  9882. #ifdef EXCELAN
  9883.     struct sockaddr_in send_socket;
  9884. #endif /* EXCELAN */
  9885.  
  9886. #ifdef INADDRX
  9887. /* inet_addr() is of type struct in_addr */
  9888. #ifdef datageneral
  9889.     extern struct in_addr inet_addr();
  9890. #else
  9891. #ifdef HPUX5WINTCP
  9892.     extern struct in_addr inet_addr();
  9893. #endif /* HPUX5WINTCP */
  9894. #endif /* datageneral */
  9895.     struct in_addr iax;
  9896. #else
  9897. #ifdef INADDR_NONE
  9898.     struct in_addr iax;
  9899. #else /* INADDR_NONE */
  9900.     long iax;
  9901. #endif /* INADDR_NONE */
  9902. #endif /* INADDRX */
  9903.  
  9904.     if ( rdns_name == NULL || rdns_len < 0 )
  9905.         rdns_len = 0;
  9906.  
  9907.     *http_ip = '\0';                     /* Initialize IP address string */
  9908.  
  9909. #ifdef DEBUG
  9910.     if (deblog) {
  9911.         debug(F110,"http_open hostname",hostname,0);
  9912.         debug(F110,"http_open svcname",svcname,0);
  9913.     }
  9914. #endif /* DEBUG */
  9915.     if (!hostname) hostname = "";
  9916.     if (!svcname) svcname = "";
  9917.     if (!*hostname || !*svcname) return(-1);
  9918.  
  9919.     service = ckgetservice(hostname,svcname,http_ip,20);
  9920.  
  9921.     if (service == NULL) {
  9922.         if ( !quiet )
  9923.             printf("?Invalid service: %s\r\n",svcname);
  9924.         return(-1);
  9925.     }
  9926.  
  9927.     /* For HTTP connections we must preserve the original hostname and */
  9928.     /* service requested so we can include them in the Host header.    */
  9929.     ckmakmsg(http_host_port,sizeof(http_host_port),hostname,":",
  9930.               ckuitoa(ntohs(service->s_port)),NULL);
  9931.     http_port = ntohs(service->s_port);
  9932.     http_ssl = use_ssl;
  9933.     debug(F111,"http_open",http_host_port,http_port);
  9934.  
  9935.     /* 'http_ip' contains the IP address to which we want to connect        */
  9936.     /* 'svcnam'   contains the service name                                 */
  9937.     /* 'service->s_port' contains the port number in network byte order     */
  9938.  
  9939.     /* If we are using an http proxy, we need to create a buffer containing */
  9940.     /*   hostname:port-number                                               */
  9941.     /* to pass to the http_connect() function.  Then we need to replace     */
  9942.     /* 'namecopy' with the name of the proxy server and the service->s_port */
  9943.     /* with the port number of the proxy (default port 80).                 */
  9944.  
  9945.     if ( tcp_http_proxy ) {
  9946.         char namecopy[NAMECPYL];
  9947.  
  9948.         ckmakmsg(proxycopy,sizeof(proxycopy),hostname,":",
  9949.                  ckuitoa(ntohs(service->s_port)),NULL);
  9950.         ckstrncpy(namecopy,tcp_http_proxy,NAMECPYL);
  9951.  
  9952.         p = namecopy;                       /* Was a service requested? */
  9953.         while (*p != '\0' && *p != ':') p++; /* Look for colon */
  9954.         if (*p == ':') {                    /* Have a colon */
  9955.             debug(F110,"netopen name has colon",namecopy,0);
  9956.             *p++ = '\0';                    /* Get service name or number */
  9957.         } else {
  9958.             strcpy(++p,"http");
  9959.         }
  9960.  
  9961.         service = ckgetservice(namecopy,p,http_ip,20);
  9962.         if (!service) {
  9963.             fprintf(stderr, "Can't find port for service %s\n", p);
  9964. #ifdef TGVORWIN
  9965.             debug(F101,"netopen can't get service for proxy","",socket_errno);
  9966. #else
  9967.             debug(F101,"netopen can't get service for proxy","",errno);
  9968. #endif /* TGVORWIN */
  9969.             errno = 0;                  /* (rather than mislead) */
  9970.             return(-1);
  9971.         }
  9972.     }
  9973.  
  9974.     /* Set up socket structure and get host address */
  9975.     bzero((char *)&r_addr, sizeof(r_addr));
  9976.     debug(F100,"http_open bzero ok","",0);
  9977.  
  9978. #ifdef INADDR_NONE
  9979.     debug(F101,"http_open INADDR_NONE defined","",INADDR_NONE);
  9980. #else /* INADDR_NONE */
  9981.     debug(F100,"http_open INADDR_NONE not defined","",0);
  9982. #endif /* INADDR_NONE */
  9983. #ifdef INADDRX
  9984.     debug(F100,"http_open INADDRX defined","",0);
  9985. #else /* INADDRX */
  9986.     debug(F100,"http_open INADDRX not defined","",0);
  9987. #endif /* INADDRX */
  9988.  
  9989. #ifndef NOMHHOST
  9990. #ifdef INADDRX
  9991.     iax = inet_addr(http_ip[0]?http_ip:hostname);
  9992.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  9993. #else /* INADDRX */
  9994. #ifdef INADDR_NONE
  9995.     iax.s_addr = inet_addr(http_ip[0]?http_ip:hostname);
  9996.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax.s_addr);
  9997. #else /* INADDR_NONE */
  9998. #ifndef datageneral
  9999.     iax = (unsigned int) inet_addr(http_ip[0]?http_ip:hostname);
  10000. #else
  10001.     iax = -1L;
  10002. #endif /* datageneral */
  10003.     debug(F111,"http_open inet_addr",http_ip[0]?http_ip:hostname,iax);
  10004. #endif /* INADDR_NONE */
  10005. #endif /* INADDRX */
  10006.  
  10007.     dns = 0;
  10008.     if (
  10009. #ifdef INADDR_NONE
  10010.         iax.s_addr == INADDR_NONE || iax.s_addr == (unsigned long) -1L
  10011. #else /* INADDR_NONE */
  10012.         iax < 0
  10013. #endif /* INADDR_NONE */
  10014.         ) {
  10015.         if (!quiet) {
  10016.             printf(" DNS Lookup... ");
  10017.             fflush(stdout);
  10018.         }
  10019.         if ((host = gethostbyname(http_ip[0] ? http_ip : hostname)) != NULL) {
  10020.             debug(F100,"http_open gethostbyname != NULL","",0);
  10021.             host = ck_copyhostent(host);
  10022.             dns = 1;                    /* Remember we performed dns lookup */
  10023.             r_addr.sin_family = host->h_addrtype;
  10024.             if (host->h_name && host->h_name[0] && (rdns_len > 0)
  10025.                  && (tcp_http_proxy == NULL)
  10026.                  )
  10027.                 ckmakmsg(rdns_name,rdns_len,host->h_name,":",svcname,NULL);
  10028.  
  10029. #ifdef HADDRLIST
  10030. #ifdef h_addr
  10031.             /* This is for trying multiple IP addresses - see <netdb.h> */
  10032.             if (!(host->h_addr_list))
  10033.               return(-1);
  10034.             bcopy(host->h_addr_list[0],
  10035.                   (caddr_t)&r_addr.sin_addr,
  10036.                   host->h_length
  10037.                   );
  10038. #else
  10039.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  10040. #endif /* h_addr */
  10041. #else  /* HADDRLIST */
  10042.             bcopy(host->h_addr, (caddr_t)&r_addr.sin_addr, host->h_length);
  10043. #endif /* HADDRLIST */
  10044. #ifndef EXCELAN
  10045.             debug(F111,"BCOPY","host->h_addr",host->h_addr);
  10046. #endif /* EXCELAN */
  10047.             debug(F111,"BCOPY"," (caddr_t)&r_addr.sin_addr",
  10048.                   (caddr_t)&r_addr.sin_addr);
  10049.             debug(F111,"BCOPY"," r_addr.sin_addr.s_addr",
  10050.                   r_addr.sin_addr.s_addr);
  10051.             debug(F111,"BCOPY","host->h_length",host->h_length);
  10052.         }
  10053.     }
  10054. #endif /* NOMHHOST */
  10055.  
  10056.     if (!dns) {
  10057. #ifdef INADDRX
  10058. /* inet_addr() is of type struct in_addr */
  10059.         struct in_addr ina;
  10060.         unsigned long uu;
  10061.         debug(F100,"http_open gethostbyname == NULL: INADDRX","",0);
  10062.         ina = inet_addr(http_ip[0]?http_ip:hostname);
  10063.         uu = *(unsigned int *)&ina;
  10064. #else /* Not INADDRX */
  10065. /* inet_addr() is unsigned long */
  10066.         unsigned long uu;
  10067.         debug(F100,"http_open gethostbyname == NULL: Not INADDRX","",0);
  10068.         uu = inet_addr(http_ip[0]?http_ip:hostname);
  10069. #endif /* INADDRX */
  10070.         debug(F101,"http_open uu","",uu);
  10071.         if (
  10072. #ifdef INADDR_NONE
  10073.             !(uu == INADDR_NONE || uu == (unsigned int) -1L)
  10074. #else   /* INADDR_NONE */
  10075.             uu != ((unsigned long)-1)
  10076. #endif /* INADDR_NONE */
  10077.             ) {
  10078.             r_addr.sin_addr.s_addr = uu;
  10079.             r_addr.sin_family = AF_INET;
  10080.         } else {
  10081. #ifdef VMS
  10082.             fprintf(stdout, "\r\n");    /* complete any previous message */
  10083. #endif /* VMS */
  10084.             fprintf(stderr, "Can't get address for %s\n",
  10085.                      http_ip[0]?http_ip:hostname);
  10086. #ifdef TGVORWIN
  10087.             debug(F101,"http_open can't get address","",socket_errno);
  10088. #else
  10089.             debug(F101,"http_open can't get address","",errno);
  10090. #endif /* TGVORWIN */
  10091.             errno = 0;                  /* Rather than mislead */
  10092.             return(-1);
  10093.         }
  10094.     }
  10095.  
  10096.     /* Get a file descriptor for the connection. */
  10097.  
  10098.     r_addr.sin_port = service->s_port;
  10099.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10100.     debug(F110,"http_open trying",http_ip,0);
  10101.     if (!quiet && *http_ip) {
  10102.         printf(" Trying %s... ", http_ip);
  10103.         fflush(stdout);
  10104.     }
  10105.  
  10106.     /* Loop to try additional IP addresses, if any. */
  10107.  
  10108.     do {
  10109. #ifdef EXCELAN
  10110.         send_socket.sin_family = AF_INET;
  10111.         send_socket.sin_addr.s_addr = 0;
  10112.         send_socket.sin_port = 0;
  10113.         if ((httpfd = socket(SOCK_STREAM, (struct sockproto *)0,
  10114.                             &send_socket, SO_REUSEADDR)) < 0)
  10115. #else  /* EXCELAN */
  10116.         if ((httpfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  10117. #endif /* EXCELAN */
  10118.             {
  10119. #ifdef EXCELAN
  10120.                 experror("TCP socket error");
  10121. #else
  10122. #ifdef TGVORWIN
  10123. #ifdef OLD_TWG
  10124.                 errno = socket_errno;
  10125. #endif /* OLD_TWG */
  10126.                 socket_perror("TCP socket error");
  10127.                 debug(F101,"http_open socket error","",socket_errno);
  10128. #else
  10129.                 perror("TCP socket error");
  10130.                 debug(F101,"http_open socket error","",errno);
  10131. #endif /* TGVORWIN */
  10132. #endif /* EXCELAN */
  10133.                 return (-1);
  10134.             }
  10135.         errno = 0;
  10136.  
  10137.        /* If a specific TCP address on the local host is desired we */
  10138.        /* must bind it to the socket.                               */
  10139. #ifndef datageneral
  10140.          if (tcp_address) {
  10141.              int s_errno;
  10142.  
  10143.              debug(F110,"http_open binding socket to",tcp_address,0);
  10144.              bzero((char *)&sin,sizeof(sin));
  10145.              sin.sin_family = AF_INET;
  10146. #ifdef INADDRX
  10147.              inaddrx = inet_addr(tcp_address);
  10148.              sin.sin_addr.s_addr = *(unsigned long *)&inaddrx;
  10149. #else
  10150.              sin.sin_addr.s_addr = inet_addr(tcp_address);
  10151. #endif /* INADDRX */
  10152.              sin.sin_port = 0;
  10153.              if (bind(httpfd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
  10154.                  s_errno = socket_errno; /* Save error code */
  10155. #ifdef TCPIPLIB
  10156.                  socket_close(httpfd);
  10157. #else /* TCPIPLIB */
  10158.                  close(httpfd);
  10159. #endif /* TCPIPLIB */
  10160.                  httpfd = -1;
  10161.                  errno = s_errno;       /* and report this error */
  10162.                  debug(F101,"http_open bind errno","",errno);
  10163.                  return(-1);
  10164.              }
  10165.          }
  10166. #endif /* datageneral */
  10167.  
  10168. /* Now connect to the socket on the other end. */
  10169.  
  10170. #ifdef EXCELAN
  10171.         if (connect(httpfd, &r_addr) < 0)
  10172. #else
  10173. #ifdef NT
  10174.           WSASafeToCancel = 1;
  10175. #endif /* NT */
  10176.         if (connect(httpfd, (struct sockaddr *)&r_addr, sizeof(r_addr)) < 0)
  10177. #endif /* EXCELAN */
  10178.           {
  10179. #ifdef NT
  10180.               WSASafeToCancel = 0;
  10181. #endif /* NT */
  10182. #ifdef OS2
  10183.               i = socket_errno;
  10184. #else /* OS2 */
  10185. #ifdef TGVORWIN
  10186.               i = socket_errno;
  10187. #else
  10188.               i = errno;                /* Save error code */
  10189. #endif /* TGVORWIN */
  10190. #endif /* OS2 */
  10191. #ifdef HADDRLIST
  10192. #ifdef h_addr
  10193.               if (host && host->h_addr_list && host->h_addr_list[1]) {
  10194.                   perror("");
  10195.                   host->h_addr_list++;
  10196.                   bcopy(host->h_addr_list[0],
  10197.                         (caddr_t)&r_addr.sin_addr,
  10198.                         host->h_length);
  10199.  
  10200.                   ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10201.                   debug(F110,"http_open h_addr_list",http_ip,0);
  10202.                   if (!quiet && *http_ip) {
  10203.                       printf(" Trying %s... ", http_ip);
  10204.                       fflush(stdout);
  10205.                   }
  10206. #ifdef TCPIPLIB
  10207.                   socket_close(httpfd); /* Close it. */
  10208. #else
  10209.                   close(httpfd);
  10210. #endif /* TCPIPLIB */
  10211.                   continue;
  10212.               }
  10213. #endif /* h_addr */
  10214. #endif  /* HADDRLIST */
  10215.               http_close();
  10216.               httpfd = -1;
  10217.               errno = i;                /* And report this error */
  10218. #ifdef EXCELAN
  10219.               if (errno) experror("http_open connect");
  10220. #else
  10221. #ifdef TGVORWIN
  10222.               debug(F101,"http_open connect error","",socket_errno);
  10223.               /* if (errno) socket_perror("http_open connect"); */
  10224. #ifdef OLD_TWG
  10225.               errno = socket_errno;
  10226. #endif /* OLD_TWG */
  10227.               if (!quiet)
  10228.                 socket_perror("http_open connect");
  10229. #else /* TGVORWIN */
  10230.               debug(F101,"http_open connect errno","",errno);
  10231. #ifdef VMS
  10232.               if (!quiet)
  10233.                 perror("\r\nFailed");
  10234. #else
  10235.               if (!quiet)
  10236.                 perror("Failed");
  10237. #endif /* VMS */
  10238. #ifdef DEC_TCPIP
  10239.               if (!quiet)
  10240.                 perror("http_open connect");
  10241. #endif /* DEC_TCPIP */
  10242. #ifdef CMU_TCPIP
  10243.               if (!quiet)
  10244.                 perror("http_open connect");
  10245. #endif /* CMU_TCPIP */
  10246. #endif /* TGVORWIN */
  10247. #endif /* EXCELAN */
  10248.               return(-1);
  10249.           }
  10250. #ifdef NT
  10251.         WSASafeToCancel = 0;
  10252. #endif /* NT */
  10253.         isconnect = 1;
  10254.     } while (!isconnect);
  10255.  
  10256. #ifdef NON_BLOCK_IO
  10257.     on = 1;
  10258.     x = socket_ioctl(httpfd,FIONBIO,&on);
  10259.     debug(F101,"http_open FIONBIO","",x);
  10260. #endif /* NON_BLOCK_IO */
  10261.  
  10262.     /* We have succeeded in connecting to the HTTP PROXY.  So now we   */
  10263.     /* need to attempt to connect through the proxy to the actual host */
  10264.     /* If that is successful, we have to pretend that we made a direct */
  10265.     /* connection to the actual host.                                  */
  10266.  
  10267.     if ( tcp_http_proxy ) {
  10268. #ifdef OS2
  10269.         char * agent = "Kermit 95";             /* Default user agent */
  10270. #else
  10271.         char * agent = "C-Kermit";
  10272. #endif /* OS2 */
  10273.  
  10274.         if (http_connect(httpfd,agent,NULL,
  10275.                          tcp_http_proxy_user,
  10276.                          tcp_http_proxy_pwd,
  10277.                          0,
  10278.                          proxycopy
  10279.                          ) < 0) {
  10280.             http_close();
  10281.             return(-1);
  10282.         }
  10283.     }
  10284.  
  10285. #ifdef SO_OOBINLINE
  10286.     /* See note on SO_OOBINLINE in netopen() */
  10287. #ifdef datageneral
  10288.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10289. #else
  10290. #ifdef BSD43
  10291.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10292. #else
  10293. #ifdef OSF1
  10294.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10295. #else
  10296. #ifdef POSIX
  10297.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10298. #else
  10299. #ifdef MOTSV88R4
  10300.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10301. #else
  10302. #ifdef SOLARIS
  10303. /*
  10304.   Maybe this applies to all SVR4 versions, but the other (else) way has been
  10305.   compiling and working fine on all the others, so best not to change it.
  10306. */
  10307.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10308. #else
  10309. #ifdef OSK
  10310.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10311. #else
  10312. #ifdef OS2
  10313.     {
  10314.         int rc;
  10315.         rc = setsockopt(httpfd,
  10316.                         SOL_SOCKET,
  10317.                         SO_OOBINLINE,
  10318.                         (char *) &on,
  10319.                         sizeof on
  10320.                         );
  10321.         debug(F111,"setsockopt SO_OOBINLINE",on ? "on" : "off" ,rc);
  10322.     }
  10323. #else
  10324. #ifdef VMS /* or, at least, VMS with gcc */
  10325.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10326. #else
  10327. #ifdef CLIX
  10328.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE,(char *) &on, sizeof on);
  10329. #else
  10330.     setsockopt(httpfd, SOL_SOCKET, SO_OOBINLINE, &on, sizeof on);
  10331. #endif /* CLIX */
  10332. #endif /* VMS */
  10333. #endif /* OS2 */
  10334. #endif /* OSK */
  10335. #endif /* SOLARIS */
  10336. #endif /* MOTSV88R4 */
  10337. #endif /* POSIX */
  10338. #endif /* BSD43 */
  10339. #endif /* OSF1 */
  10340. #endif /* datageneral */
  10341. #endif /* SO_OOBINLINE */
  10342.  
  10343. #ifndef NOTCPOPTS
  10344. #ifndef datageneral
  10345. #ifdef SOL_SOCKET
  10346. #ifdef TCP_NODELAY
  10347.     no_delay(ttyfd,tcp_nodelay);
  10348. #endif /* TCP_NODELAY */
  10349. #ifdef SO_KEEPALIVE
  10350.     keepalive(ttyfd,tcp_keepalive);
  10351. #endif /* SO_KEEPALIVE */
  10352. #ifdef SO_LINGER
  10353.     ck_linger(ttyfd,tcp_linger, tcp_linger_tmo);
  10354. #endif /* SO_LINGER */
  10355. #ifdef SO_SNDBUF
  10356.     sendbuf(ttyfd,tcp_sendbuf);
  10357. #endif /* SO_SNDBUF */
  10358. #ifdef SO_RCVBUF
  10359.     recvbuf(ttyfd,tcp_recvbuf);
  10360. #endif /* SO_RCVBUF */
  10361. #endif /* SOL_SOCKET */
  10362. #endif /* datageneral */
  10363. #endif /* NOTCPOPTS */
  10364.  
  10365. #ifndef datageneral
  10366.     /* Find out our own IP address. */
  10367.     /* We need the l_addr structure for [E]KLOGIN. */
  10368.     l_slen = sizeof(l_addr);
  10369.     bzero((char *)&l_addr, l_slen);
  10370. #ifndef EXCELAN
  10371.     if (!getsockname(httpfd, (struct sockaddr *)&l_addr, &l_slen)) {
  10372.         char * s = (char *)inet_ntoa(l_addr.sin_addr);
  10373.         ckstrncpy(myipaddr, s, 20);
  10374.         debug(F110,"getsockname",myipaddr,0);
  10375.     }
  10376. #endif /* EXCELAN */
  10377. #endif /* datageneral */
  10378.  
  10379. /* See note in netopen() on Reverse DNS lookups */
  10380.      if (tcp_rdns == SET_ON) {
  10381. #ifdef NT
  10382.         if (isWin95())
  10383.           sleep(1);
  10384. #endif /* NT */
  10385.         if (!quiet) {
  10386.             printf(" Reverse DNS Lookup... ");
  10387.             fflush(stdout);
  10388.         }
  10389.         if (host = gethostbyaddr((char *)&r_addr.sin_addr,4,PF_INET)) {
  10390.             char * s;
  10391.             host = ck_copyhostent(host);
  10392.             debug(F100,"http_open gethostbyname != NULL","",0);
  10393.             if (!quiet) {
  10394.                 printf("(OK)\n");
  10395.                 fflush(stdout);
  10396.             }
  10397.             s = host->h_name;
  10398.             if (!s) {                   /* This can happen... */
  10399.                 debug(F100,"http_open host->h_name is NULL","",0);
  10400.                 s = "";
  10401.             }
  10402.             /* Something is wrong with inet_ntoa() on HPUX 10.xx */
  10403.             /* The compiler says "Integral value implicitly converted to */
  10404.             /* pointer in assignment."  The prototype is right there */
  10405.             /* in <arpa/inet.h> so what's the problem? */
  10406.             /* Ditto in HP-UX 5.x, but not 8.x or 9.x... */
  10407.             if (!*s) {                  /* No name so substitute the address */
  10408.                 debug(F100,"http_open host->h_name is empty","",0);
  10409.                 s = inet_ntoa(r_addr.sin_addr); /* Convert address to string */
  10410.                 if (!s)                 /* Trust No 1 */
  10411.                   s = "";
  10412.                 if (*s) {               /* If it worked, use this string */
  10413.                     ckstrncpy(http_ip,s,20);
  10414.                 }
  10415.                 s = http_ip;             /* Otherwise stick with the IP */
  10416.                 if (!*s)                 /* or failing that */
  10417.                   s = http_host_port;    /* the name we were called with. */
  10418.             }
  10419.             if (*s)                     /* return the rdns name */
  10420.                 ckmakmsg(rdns_name,rdns_len,s,":",svcname,NULL);
  10421.  
  10422.             if (!quiet && *s
  10423. #ifndef NOICP
  10424.                 && !doconx
  10425. #endif /* NOICP */
  10426.                 ) {
  10427.                 printf(" %s connected on port %s\n",s,
  10428.                        ckuitoa(ntohs(service->s_port)));
  10429. #ifdef BETADEBUG
  10430.                 /* This is simply for testing the DNS entries */
  10431.                 if (host->h_aliases) {
  10432.                     char ** a = host->h_aliases;
  10433.                     while (*a) {
  10434.                         printf(" alias => %s\n",*a);
  10435.                         a++;
  10436.                     }
  10437.                 }
  10438. #endif /* BETADEBUG */
  10439.             }
  10440.         } else {
  10441.             if (!quiet) printf("Failed.\n");
  10442.         }
  10443.     } else if (!quiet) printf("(OK)\n");
  10444.     if (!quiet) fflush(stdout);
  10445.  
  10446.     /* This should already have been done but just in case */
  10447.     ckstrncpy(http_ip,(char *)inet_ntoa(r_addr.sin_addr),20);
  10448.  
  10449. #ifdef CK_SSL
  10450.     if (use_ssl && ck_ssleay_is_installed()) {
  10451.         if (!ssl_http_init(hostname)) {
  10452.             if (bio_err!=NULL) {
  10453.                 BIO_printf(bio_err,"ssl_tn_init() failed\n");
  10454.                 ERR_print_errors(bio_err);
  10455.             } else {
  10456.                 fflush(stderr);
  10457.                 fprintf(stderr,"ssl_tn_init() failed\n");
  10458.                 ERR_print_errors_fp(stderr);
  10459.             }
  10460.             http_close();
  10461.             return(-1);
  10462.         } else if ( ck_ssl_http_client(httpfd,hostname) < 0 ) {
  10463.             http_close();
  10464.             return(-1);
  10465.         }
  10466.     }
  10467. #endif /* CK_SSL */
  10468. #endif /* TCPSOCKET */
  10469.     return(0);                          /* Done. */
  10470. }
  10471.  
  10472. int
  10473. #ifdef CK_ANSIC
  10474. http_close(VOID)
  10475. #else /* CK_ANSIC */
  10476. http_close()
  10477. #endif /* CK_ANSIC */
  10478. {
  10479.     int x = 0;
  10480.     debug(F101,"http_close","",httpfd);
  10481.  
  10482.     if (httpfd == -1)                    /* Was open? */
  10483.       return(0);                        /* Wasn't. */
  10484.  
  10485. #ifndef OS2
  10486.     if (httpfd > -1)                     /* Was. */
  10487. #endif /* OS2 */
  10488.       {
  10489. #ifdef CK_SSL
  10490.           if (tls_http_active_flag) {
  10491.               if (ssl_debug_flag)
  10492.                 BIO_printf(bio_err,"calling SSL_shutdown\n");
  10493.               SSL_shutdown(tls_http_con);
  10494.               tls_http_active_flag = 0;
  10495.           }
  10496. #endif /* CK_SSL */
  10497. #ifdef TCPIPLIB
  10498.           x = socket_close(httpfd);      /* Close it. */
  10499. #else
  10500. #ifndef OS2
  10501.           x = close(httpfd);
  10502. #endif /* OS2 */
  10503. #endif /* TCPIPLIB */
  10504.       }
  10505.     httpfd = -1;                          /* Mark it as closed. */
  10506.     /* do not erase http_host_port, http_ip, http_port so they */
  10507.     /* can be used by http_reopen() */
  10508.     return(x);
  10509. }
  10510.  
  10511.  
  10512. /* http_tol()
  10513.  * Call with s = pointer to string, n = length.
  10514.  * Returns number of bytes actually written on success, or
  10515.  * -1 on i/o error, -2 if called improperly.
  10516.  */
  10517.  
  10518. int
  10519. http_tol(s,n) CHAR *s; int n; {
  10520.     int count = 0;
  10521.     int len = n;
  10522.     int try = 0;
  10523.  
  10524.     if (httpfd == -1) {
  10525.         debug(F100,"http_tol socket is closed","",0);
  10526.         return -1;
  10527.     }
  10528.     debug(F101,"http_tol TCPIPLIB ttnet","",ttnet);
  10529. #ifdef COMMENT
  10530.     hexdump("http_tol",s,n);
  10531. #endif /* COMMENT */
  10532.  
  10533. #ifdef CK_SSL
  10534.     if (tls_http_active_flag) {
  10535.         int error, r;
  10536.         /* Write using SSL */
  10537.       ssl_retry:
  10538.           r = SSL_write(tls_http_con, s, len /* >1024?1024:len */);
  10539.         switch (SSL_get_error(tls_http_con,r)) {
  10540.           case SSL_ERROR_NONE:
  10541.             debug(F111,"http_tol","SSL_write",r);
  10542.             if ( r == len )
  10543.                 return(n);
  10544.              s += r;
  10545.              len -= r;
  10546.              goto ssl_retry;
  10547.           case SSL_ERROR_WANT_WRITE:
  10548.             debug(F100,"http_tol SSL_ERROR_WANT_WRITE","",0);
  10549.             return(-1);
  10550.           case SSL_ERROR_WANT_READ:
  10551.             debug(F100,"http_tol SSL_ERROR_WANT_READ","",0);
  10552.             return(-1);
  10553.           case SSL_ERROR_SYSCALL:
  10554.               if ( r == 0 ) { /* EOF */
  10555.                   http_close();
  10556.                   return(-2);
  10557.               } else {
  10558.                   int rc = -1;
  10559. #ifdef NT
  10560.                   int gle = GetLastError();
  10561.                   debug(F111,"http_tol SSL_ERROR_SYSCALL",
  10562.                          "GetLastError()",gle);
  10563.                   rc = os2socketerror(gle);
  10564.                   if (rc == -1)
  10565.                       rc = -2;
  10566.                   else if ( rc == -2 )
  10567.                       return -1;
  10568. #endif /* NT */
  10569.                   return(rc);
  10570.               }
  10571.           case SSL_ERROR_WANT_X509_LOOKUP:
  10572.             debug(F100,"http_tol SSL_ERROR_WANT_X509_LOOKUP","",0);
  10573.             http_close();
  10574.             return(-2);
  10575.           case SSL_ERROR_SSL:
  10576.             debug(F100,"http_tol SSL_ERROR_SSL","",0);
  10577.             http_close();
  10578.             return(-2);
  10579.           case SSL_ERROR_ZERO_RETURN:
  10580.             debug(F100,"http_tol SSL_ERROR_ZERO_RETURN","",0);
  10581.             http_close();
  10582.             return(-2);
  10583.           default:
  10584.             debug(F100,"http_tol SSL_ERROR_?????","",0);
  10585.             http_close();
  10586.             return(-2);
  10587.         }
  10588.     }
  10589. #endif /* CK_SSL */
  10590.  
  10591.   http_tol_retry:
  10592.     try++;                              /* Increase the try counter */
  10593.  
  10594.     {
  10595. #ifdef BSDSELECT
  10596.         fd_set wfds;
  10597.         struct timeval tv;
  10598.  
  10599.         debug(F101,"http_tol BSDSELECT","",0);
  10600.         tv.tv_usec = 0L;
  10601.         tv.tv_sec=30;
  10602. #ifdef NT
  10603.         WSASafeToCancel = 1;
  10604. #endif /* NT */
  10605. #ifdef STREAMING
  10606.       do_select:
  10607. #endif /* STREAMING */
  10608.         FD_ZERO(&wfds);
  10609.         FD_SET(httpfd, &wfds);
  10610.         if (select(FD_SETSIZE, NULL,
  10611. #ifdef __DECC
  10612. #ifndef __DECC_VER
  10613.                     (int *)
  10614. #endif /* __DECC_VER */
  10615. #endif /* __DECC */
  10616.                    &wfds, NULL, &tv) < 0) {
  10617.             int s_errno = socket_errno;
  10618.             debug(F101,"http_tol select failed","",s_errno);
  10619. #ifdef BETADEBUG
  10620.             printf("http_tol select failed: %d\n", s_errno);
  10621. #endif /* BETADEBUG */
  10622. #ifdef NT
  10623.             WSASafeToCancel = 0;
  10624.             if (!win95selectbug)
  10625. #endif /* NT */
  10626.               return(-1);
  10627.         }
  10628.         if (!FD_ISSET(httpfd, &wfds)) {
  10629. #ifdef STREAMING
  10630.             if (streaming)
  10631.               goto do_select;
  10632. #endif /* STREAMING */
  10633.             debug(F111,"http_tol","!FD_ISSET",ttyfd);
  10634. #ifdef NT
  10635.             WSASafeToCancel = 0;
  10636.             if (!win95selectbug)
  10637. #endif /* NT */
  10638.               return(-1);
  10639.         }
  10640. #ifdef NT
  10641.         WSASafeToCancel = 0;
  10642. #endif /* NT */
  10643. #else /* BSDSELECT */
  10644. #ifdef IBMSELECT
  10645.         {
  10646.             int tries = 0;
  10647.             debug(F101,"http_tol IBMSELECT","",0);
  10648.             while (select(&httpfd, 0, 1, 0, 1000) != 1) {
  10649.                 int count;
  10650.                 if (tries++ >= 60) {
  10651.                     /* if after 60 seconds we can't get permission to write */
  10652.                     debug(F101,"http_tol select failed","",socket_errno);
  10653.                     return(-1);
  10654.                 }
  10655. #ifdef COMMENT
  10656.                 if ((count = http_tchk()) < 0) {
  10657.                     debug(F111,"http_tol","http_tchk()",count);
  10658.                     return(count);
  10659.                 }
  10660. #endif /* COMMENT */
  10661.             }
  10662.         }
  10663. #endif /* IBMSELECT */
  10664. #endif /* BSDSELECT */
  10665. #ifdef TCPIPLIB
  10666.         if ((count = socket_write(httpfd,s,n)) < 0) {
  10667.             int s_errno = socket_errno; /* maybe a function */
  10668.             debug(F101,"http_tol socket_write error","",s_errno);
  10669. #ifdef OS2
  10670.             if (os2socketerror(s_errno) < 0)
  10671.               return(-2);
  10672. #endif /* OS2 */
  10673.             return(-1);                 /* Call it an i/o error */
  10674.         }
  10675. #else /* TCPIPLIB */
  10676.         if ((count = write(httpfd,s,n)) < 0) {
  10677.             debug(F101,"http_tol socket_write error","",errno);
  10678.             return(-1);                 /* Call it an i/o error */
  10679.         }
  10680. #endif /* TCPIPLIB */
  10681.         if (count < n) {
  10682.             debug(F111,"http_tol socket_write",s,count);
  10683.             if (try > 25) {
  10684.                 /* don't try more than 25 times */
  10685.                 debug(F100,"http_tol tried more than 25 times","",0);
  10686.                 return(-1);
  10687.             }
  10688.             if (count > 0) {
  10689.                 s += count;
  10690.                 n -= count;
  10691.             }
  10692.             debug(F111,"http_tol retry",s,n);
  10693.             goto http_tol_retry;
  10694.         } else {
  10695.             debug(F111,"http_tol socket_write",s,count);
  10696.             return(len); /* success - return total length */
  10697.         }
  10698.     }
  10699. }
  10700.  
  10701.  
  10702. int
  10703. http_inc(timo) int timo; {
  10704.     int x=-1; unsigned char c;             /* The locals. */
  10705.  
  10706.     if (httpfd == -1) {
  10707.         debug(F100,"http_inc socket is closed","",0);
  10708.         return(-2);
  10709.     }
  10710.  
  10711. #ifdef CK_SSL
  10712.     /*
  10713.      * In the case of OpenSSL, it is possible that there is still
  10714.      * data waiting in the SSL session buffers that has not yet
  10715.      * been read by Kermit.  If this is the case we must process
  10716.      * it without calling select() because select() will not return
  10717.      * with an indication that there is data to be read from the
  10718.      * socket.  If there is no data pending in the SSL session
  10719.      * buffers then fall through to the select() code and wait for
  10720.      * some data to arrive.
  10721.      */
  10722.     if (tls_http_active_flag) {
  10723.         int error;
  10724.  
  10725.         x = SSL_pending(tls_http_con);
  10726.         if (x < 0) {
  10727.             debug(F111,"http_inc","SSL_pending error",x);
  10728.             http_close();
  10729.             return(-1);
  10730.         } else if ( x > 0 ) {
  10731.             x = SSL_read(tls_http_con, &c, 1);
  10732.             error = SSL_get_error(tls_http_con,x);
  10733.             switch (error) {
  10734.             case SSL_ERROR_NONE:
  10735.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  10736.                 if (x > 0) {
  10737. #ifdef OS2
  10738.                     ReleaseTCPIPMutex();
  10739. #endif /* OS2 */
  10740.                     return(c);          /* Return character. */
  10741.                 } else if (x < 0) {
  10742. #ifdef OS2
  10743.                     ReleaseTCPIPMutex();
  10744. #endif /* OS2 */
  10745.                     return(-1);
  10746.                 } else {
  10747.                     http_close();
  10748. #ifdef OS2
  10749.                     ReleaseTCPIPMutex();
  10750. #endif /* OS2 */
  10751.                     return(-2);
  10752.                 }
  10753.             case SSL_ERROR_WANT_WRITE:
  10754.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  10755. #ifdef OS2
  10756.                 ReleaseTCPIPMutex();
  10757. #endif /* OS2 */
  10758.                 return(-1);
  10759.             case SSL_ERROR_WANT_READ:
  10760.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  10761. #ifdef OS2
  10762.                 ReleaseTCPIPMutex();
  10763. #endif /* OS2 */
  10764.                 return(-1);
  10765.             case SSL_ERROR_SYSCALL:
  10766.                 if ( x == 0 ) { /* EOF */
  10767.                     http_close();
  10768. #ifdef OS2
  10769.                     ReleaseTCPIPMutex();
  10770. #endif /* OS2 */
  10771.                     return(-2);
  10772.                 } else {
  10773.                     int rc = -1;
  10774. #ifdef NT
  10775.                     int gle = GetLastError();
  10776.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  10777.                            "GetLastError()",gle);
  10778.                     rc = os2socketerror(gle);
  10779.                     if (rc == -1)
  10780.                         rc = -2;
  10781.                     else if ( rc == -2 )
  10782.                         return -1;
  10783. #endif /* NT */
  10784. #ifdef OS2
  10785.                     ReleaseTCPIPMutex();
  10786. #endif /* OS2 */
  10787.                     return(rc);
  10788.                 }
  10789.             case SSL_ERROR_WANT_X509_LOOKUP:
  10790.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  10791.                 http_close();
  10792. #ifdef OS2
  10793.                 ReleaseTCPIPMutex();
  10794. #endif /* OS2 */
  10795.                 return(-2);
  10796.             case SSL_ERROR_SSL:
  10797.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  10798. #ifdef COMMENT
  10799.                 http_close();
  10800. #endif /* COMMENT */
  10801. #ifdef OS2
  10802.                 ReleaseTCPIPMutex();
  10803. #endif /* OS2 */
  10804.                 return(-2);
  10805.             case SSL_ERROR_ZERO_RETURN:
  10806.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  10807.                 http_close();
  10808. #ifdef OS2
  10809.                 ReleaseTCPIPMutex();
  10810. #endif /* OS2 */
  10811.                 return(-2);
  10812.             default:
  10813.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  10814.                 http_close();
  10815. #ifdef OS2
  10816.                 ReleaseTCPIPMutex();
  10817. #endif /* OS2 */
  10818.                 return(-2);
  10819.             }
  10820.         }
  10821.     }
  10822. #endif /* CK_SSL */
  10823.     {
  10824. #ifdef BSDSELECT
  10825.         fd_set rfds;
  10826.         struct timeval tv;
  10827.         int timeout = timo < 0 ? -timo : 1000 * timo;
  10828.         debug(F101,"http_inc BSDSELECT","",timo);
  10829.  
  10830.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  10831.             int rc;
  10832.             debug(F111,"http_inc","timeout",timeout);
  10833.             /* Don't move select() initialization out of the loop. */
  10834.             FD_ZERO(&rfds);
  10835.             FD_SET(httpfd, &rfds);
  10836.             tv.tv_sec  = tv.tv_usec = 0L;
  10837.             if (timo)
  10838.                 tv.tv_usec = (long) 100000L;
  10839.             else
  10840.                 tv.tv_sec = 30;
  10841. #ifdef NT
  10842.             WSASafeToCancel = 1;
  10843. #endif /* NT */
  10844.             rc = select(FD_SETSIZE,
  10845. #ifndef __DECC
  10846.                          (fd_set *)
  10847. #endif /* __DECC */
  10848.                          &rfds, NULL, NULL, &tv);
  10849.             if (rc < 0) {
  10850.                 int s_errno = socket_errno;
  10851.                 debug(F111,"http_inc","select",rc);
  10852.                 debug(F111,"http_inc","socket_errno",s_errno);
  10853.                 if (s_errno)
  10854.                     return(-1);
  10855.             }
  10856.             debug(F111,"http_inc","select",rc);
  10857. #ifdef NT
  10858.             WSASafeToCancel = 0;
  10859. #endif /* NT */
  10860.             if (FD_ISSET(httpfd, &rfds)) {
  10861.                 x = 0;
  10862.                 break;
  10863.             } else {
  10864.                 /* If waiting forever we have no way of knowing if the */
  10865.                 /* socket closed so try writing a 0-length TCP packet  */
  10866.                 /* which should force an error if the socket is closed */
  10867.                 if (!timo) {
  10868. #ifdef TCPIPLIB
  10869.                     if ((rc = socket_write(httpfd,"",0)) < 0) {
  10870.                         int s_errno = socket_errno;
  10871.                         debug(F101,"http_inc socket_write error","",s_errno);
  10872. #ifdef OS2
  10873.                         if (os2socketerror(s_errno) < 0)
  10874.                             return(-2);
  10875. #endif /* OS2 */
  10876.                         return(-1); /* Call it an i/o error */
  10877.                     }
  10878. #else /* TCPIPLIB */
  10879.                     if ((rc = write(httpfd,"",0)) < 0) {
  10880.                         debug(F101,"http_inc socket_write error","",errno);
  10881.                         return(-1); /* Call it an i/o error */
  10882.                     }
  10883. #endif /* TCPIPLIB */
  10884.                 }
  10885.                 continue;
  10886.             }
  10887.         }
  10888. #ifdef NT
  10889.         WSASafeToCancel = 0;
  10890. #endif /* NT */
  10891. #else /* !BSDSELECT */
  10892. #ifdef IBMSELECT
  10893.  /*
  10894.   Was used by OS/2, currently not used, but might come in handy some day...
  10895.   ... and it came in handy!  For our TCP/IP layer, it avoids all the fd_set
  10896.   and timeval stuff since this is the only place where it is used.
  10897.  */
  10898.         int socket = httpfd;
  10899.         int timeout = timo < 0 ? -timo : 1000 * timo;
  10900.  
  10901.         debug(F101,"http_inc IBMSELECT","",timo);
  10902.         for ( ; timeout >= 0; timeout -= (timo ? 100 : 0)) {
  10903.             if (select(&socket, 1, 0, 0, 100L) == 1) {
  10904.                 x = 0;
  10905.                 break;
  10906.             }
  10907.         }
  10908. #else /* !IBMSELECT */
  10909.         SELECT is required for this code
  10910. #endif /* IBMSELECT */
  10911. #endif /* BSDSELECT */
  10912.     }
  10913.  
  10914.     if (timo && x < 0) {        /* select() timed out */
  10915.         debug(F100,"http_inc select() timed out","",0);
  10916.         return(-1); /* Call it an i/o error */
  10917.     }
  10918.  
  10919. #ifdef CK_SSL
  10920.         if ( tls_http_active_flag ) {
  10921.             int error;
  10922.  
  10923.             x = SSL_read(tls_http_con, &c, 1);
  10924.             error = SSL_get_error(tls_http_con,x);
  10925.             switch (error) {
  10926.             case SSL_ERROR_NONE:
  10927.                 debug(F111,"http_inc SSL_ERROR_NONE","x",x);
  10928.                 if (x > 0) {
  10929. #ifdef OS2
  10930.                     ReleaseTCPIPMutex();
  10931. #endif /* OS2 */
  10932.                     return(c);          /* Return character. */
  10933.                 } else if (x < 0) {
  10934. #ifdef OS2
  10935.                     ReleaseTCPIPMutex();
  10936. #endif /* OS2 */
  10937.                     return(-1);
  10938.                 } else {
  10939.                     http_close();
  10940. #ifdef OS2
  10941.                     ReleaseTCPIPMutex();
  10942. #endif /* OS2 */
  10943.                     return(-2);
  10944.                 }
  10945.             case SSL_ERROR_WANT_WRITE:
  10946.                 debug(F100,"http_inc SSL_ERROR_WANT_WRITE","",0);
  10947. #ifdef OS2
  10948.                 ReleaseTCPIPMutex();
  10949. #endif /* OS2 */
  10950.                 return(-1);
  10951.             case SSL_ERROR_WANT_READ:
  10952.                 debug(F100,"http_inc SSL_ERROR_WANT_READ","",0);
  10953. #ifdef OS2
  10954.                 ReleaseTCPIPMutex();
  10955. #endif /* OS2 */
  10956.                 return(-1);
  10957.             case SSL_ERROR_SYSCALL:
  10958.                 if ( x == 0 ) { /* EOF */
  10959.                     http_close();
  10960. #ifdef OS2
  10961.                     ReleaseTCPIPMutex();
  10962. #endif /* OS2 */
  10963.                     return(-2);
  10964.                 } else {
  10965.                     int rc = -1;
  10966. #ifdef NT
  10967.                     int gle = GetLastError();
  10968.                     debug(F111,"http_inc SSL_ERROR_SYSCALL",
  10969.                            "GetLastError()",gle);
  10970.                     rc = os2socketerror(gle);
  10971.                     if (rc == -1)
  10972.                         rc = -2;
  10973.                     else if ( rc == -2 )
  10974.                         return -1;
  10975. #endif /* NT */
  10976. #ifdef OS2
  10977.                     ReleaseTCPIPMutex();
  10978. #endif /* OS2 */
  10979.                     return(rc);
  10980.                 }
  10981.             case SSL_ERROR_WANT_X509_LOOKUP:
  10982.                 debug(F100,"http_inc SSL_ERROR_WANT_X509_LOOKUP","",0);
  10983.                 http_close();
  10984. #ifdef OS2
  10985.                 ReleaseTCPIPMutex();
  10986. #endif /* OS2 */
  10987.                 return(-2);
  10988.             case SSL_ERROR_SSL:
  10989.                 debug(F100,"http_inc SSL_ERROR_SSL","",0);
  10990. #ifdef COMMENT
  10991.                 http_close();
  10992. #endif /* COMMENT */
  10993. #ifdef OS2
  10994.                 ReleaseTCPIPMutex();
  10995. #endif /* OS2 */
  10996.                 return(-2);
  10997.             case SSL_ERROR_ZERO_RETURN:
  10998.                 debug(F100,"http_inc SSL_ERROR_ZERO_RETURN","",0);
  10999.                 http_close();
  11000. #ifdef OS2
  11001.                 ReleaseTCPIPMutex();
  11002. #endif /* OS2 */
  11003.                 return(-2);
  11004.             default:
  11005.                 debug(F100,"http_inc SSL_ERROR_?????","",0);
  11006.                 http_close();
  11007. #ifdef OS2
  11008.                 ReleaseTCPIPMutex();
  11009. #endif /* OS2 */
  11010.                 return(-2);
  11011.             }
  11012.         }
  11013. #endif /* CK_SSL */
  11014. #ifdef TCPIPLIB
  11015.         x = socket_read(httpfd,&c,1);
  11016. #else
  11017.         x = read(httpfd,&c,1);
  11018. #endif
  11019.  
  11020.         if (x <= 0) {
  11021.             int s_errno = socket_errno;
  11022.             debug(F101,"ttbufr socket_read","",x);
  11023.             debug(F101,"ttbufr socket_errno","",s_errno);
  11024. #ifdef OS2
  11025.             if (x == 0 || os2socketerror(s_errno) < 0) {
  11026.                 http_close();
  11027.                 ReleaseTCPIPMutex();
  11028.                 return(-2);
  11029.             }
  11030.             ReleaseTCPIPMutex();
  11031.             return(-1);
  11032. #else /* OS2 */
  11033.             http_close();                      /* *** *** */
  11034.             return(-2);
  11035. #endif /* OS2 */
  11036.         }
  11037.         return(c);
  11038. }
  11039.  
  11040. void
  11041. #ifdef CK_ANSIC
  11042. http_set_code_reply(char * msg)
  11043. #else
  11044. http_set_code_reply(msg)
  11045.     char * msg;
  11046. #endif /* CK_ANSIC */
  11047. {
  11048.     char * p = msg;
  11049.     char buf[16];
  11050.     int i=0;
  11051.  
  11052.     while ( *p != SP && *p != NUL ) {
  11053.         buf[i] = *p;
  11054.         p++;
  11055.         i++;
  11056.     }
  11057.  
  11058.     http_code = atoi(buf);
  11059.  
  11060.     while ( *p == SP )
  11061.         p++;
  11062.  
  11063.     ckstrncpy(http_reply_str,p,HTTPBUFLEN);
  11064. }
  11065.  
  11066. int
  11067. #ifdef CK_ANSIC
  11068. http_get(char * agent, char ** hdrlist, char * user,
  11069.          char * pwd, char array, char * local, char * remote,
  11070.          int stdio)
  11071. #else
  11072. http_get(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11073.     char * agent; char ** hdrlist; char * user;
  11074.     char * pwd; char array; char * local; char * remote;
  11075.     int stdio;
  11076. #endif /* CK_ANSIC */
  11077. {
  11078.     char * request = NULL;
  11079.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11080.     int    ch;
  11081.     int    http_fnd = 0;
  11082.     char   buf[HTTPBUFLEN], *p;
  11083.     int    nullline;
  11084. #ifdef OS2
  11085.     struct utimbuf u_t;
  11086. #else /* OS2 */
  11087. #ifdef SYSUTIMEH
  11088.     struct utimbuf u_t;
  11089. #else
  11090.     struct utimbuf {
  11091.         time_t atime;
  11092.         time_t mtime;
  11093.     } u_t;
  11094. #endif /* SYSUTIMH */
  11095. #endif /* OS2 */
  11096.     time_t mod_t = 0;
  11097.     time_t srv_t = 0;
  11098.     time_t local_t = 0;
  11099.     char passwd[64];
  11100.     char b64in[128];
  11101.     char b64out[256];
  11102.     char * headers[HTTPHEADCNT];
  11103.     int closecon = 0;
  11104.     int chunked = 0;
  11105.     int zfile = 0;
  11106.     int first = 1;
  11107.  
  11108. #ifdef DEBUG
  11109.     if (deblog) {
  11110.         debug(F101,"http_get httpfd","",httpfd);
  11111.         debug(F110,"http_agent",agent,0);
  11112.         debug(F110,"http_user",user,0);
  11113.         debug(F110,"http_local",local,0);
  11114.         debug(F110,"http_remote",remote,0);
  11115.     }
  11116. #endif /* DEBUG */
  11117.     if (!remote) remote = "";
  11118.  
  11119.     if (httpfd == -1)
  11120.       return(-1);
  11121.  
  11122.     if (array) {
  11123.         for (i = 0; i < HTTPHEADCNT; i++)
  11124.           headers[i] = NULL;
  11125.     }
  11126.     len = 8;                            /* GET */
  11127.     len += strlen(HTTP_VERSION);
  11128.     len += strlen(remote);
  11129.     len += 16;
  11130.  
  11131.     if (hdrlist) {
  11132.         for (i = 0; hdrlist[i]; i++)
  11133.             len += strlen(hdrlist[i]) + 2;
  11134.     }
  11135.     len += (int) strlen(http_host_port) + 8;
  11136.  
  11137.     if (agent)
  11138.       len += 13 + strlen(agent);
  11139.     if (user) {
  11140.         if (!pwd) {
  11141.             readpass("Password: ",passwd,64);
  11142.             pwd = passwd;
  11143.         }
  11144.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11145.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11146.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11147.         if (j < 0)
  11148.           return(-1);
  11149.         b64out[j] = '\0';
  11150.         len += j + 24;
  11151.     }
  11152. #ifdef HTTP_CLOSE
  11153.     len += 19;                          /* Connection: close */
  11154. #endif
  11155.     len += 3;                           /* blank line + null */
  11156.  
  11157.     request = malloc(len);
  11158.     if (!request)
  11159.       return(-1);
  11160.  
  11161.     sprintf(request,"GET %s %s\r\n",remote,HTTP_VERSION);       /* safe */
  11162.     ckstrncat(request,"Host: ", len);
  11163.     ckstrncat(request,http_host_port, len);
  11164.     ckstrncat(request,"\r\n",len);
  11165.     if (agent) {
  11166.         ckstrncat(request,"User-agent: ",len);
  11167.         ckstrncat(request,agent,len);
  11168.         ckstrncat(request,"\r\n",len);
  11169.     }
  11170.     if (user) {
  11171.         ckstrncat(request,"Authorization: Basic ",len);
  11172.         ckstrncat(request,b64out,len);
  11173.         ckstrncat(request,"\r\n",len);
  11174.     }
  11175.     if ( hdrlist ) {
  11176.         for (i = 0; hdrlist[i]; i++) {
  11177.             ckstrncat(request,hdrlist[i],len);
  11178.             ckstrncat(request,"\r\n",len);
  11179.         }
  11180.     }
  11181. #ifdef HTTP_CLOSE
  11182.     ckstrncat(request,"Connection: close\r\n",len);
  11183. #endif
  11184.     ckstrncat(request,"\r\n",len);
  11185.  
  11186.   getreq:
  11187.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11188.     {
  11189.         http_close();
  11190.         if ( first ) {
  11191.             first--;
  11192.             http_reopen();
  11193.             goto getreq;
  11194.         }
  11195.         rc = -1;
  11196.         goto getexit;
  11197.     }
  11198.  
  11199.     /* Process the headers */
  11200.     local_t = time(NULL);
  11201.     nullline = 0;
  11202.     i = 0;
  11203.     len = -1;
  11204.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11205.         buf[i] = ch;
  11206.         if ( buf[i] == 10 ) { /* found end of line */
  11207.             if (i > 0 && buf[i-1] == 13)
  11208.               i--;
  11209.             if (i < 1)
  11210.               nullline = 1;
  11211.             buf[i] = '\0';
  11212.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11213.               makestr(&headers[hdcnt++],buf);
  11214.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11215.                 http_fnd = 1;
  11216.                 j = ckindex(" ",buf,0,0,0);
  11217.                 p = &buf[j];
  11218.                 while ( isspace(*p) )
  11219.                   p++;
  11220.                 switch ( p[0] ) {
  11221.                   case '1':             /* Informational message */
  11222.                     break;
  11223.                   case '2':             /* Success */
  11224.                     break;
  11225.                   case '3':             /* Redirection */
  11226.                   case '4':             /* Client failure */
  11227.                   case '5':             /* Server failure */
  11228.                   default:              /* Unknown */
  11229.                     if (!quiet)
  11230.                       printf("Failure: Server reports %s\n",p);
  11231.                     rc = -1;
  11232.                     local = NULL;
  11233.                 }
  11234.                 http_set_code_reply(p);
  11235. #ifdef CMDATE2TM
  11236.             } else if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11237.                 mod_t = http_date(&buf[15]);
  11238.             } else if (!ckstrcmp(buf,"Date",4,0)) {
  11239.                 srv_t = http_date(&buf[4]);
  11240. #endif /* CMDATE2TM */
  11241.             } else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11242.                 if ( ckindex("close",buf,11,0,0) != 0 )
  11243.                     closecon = 1;
  11244.             } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11245.                 len = atoi(&buf[16]);
  11246.             } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11247.                 if ( ckindex("chunked",buf,18,0,0) != 0 )
  11248.                     chunked = 1;
  11249.             }
  11250.             i = 0;
  11251.         } else {
  11252.             i++;
  11253.         }
  11254.     }
  11255.     if (ch < 0 && first) {
  11256.         first--;
  11257.         http_close();
  11258.         http_reopen();
  11259.         goto getreq;
  11260.     }
  11261.     if (http_fnd == 0) {
  11262.         rc = -1;
  11263.         closecon = 1;
  11264.         goto getexit;
  11265.     }
  11266.  
  11267.     /* Now we have the contents of the file */
  11268.     if ( local && local[0] ) {
  11269.         if (zopeno(ZOFILE,local,NULL,NULL))
  11270.             zfile = 1;
  11271.         else
  11272.             rc = -1;
  11273.     }
  11274.  
  11275.     if ( chunked ) {
  11276.         while ((len = http_get_chunk_len()) > 0) {
  11277.             while (len && (ch = http_inc(0)) >= 0) {
  11278.                 len--;
  11279.                 if ( zfile )
  11280.                     zchout(ZOFILE,(CHAR)ch);
  11281.                 if ( stdio )
  11282.                     conoc((CHAR)ch);
  11283.             }
  11284.             if ((ch = http_inc(0)) != CR)
  11285.                 break;
  11286.             if ((ch = http_inc(0)) != LF)
  11287.                 break;
  11288.         }
  11289.     } else {
  11290.         while (len && (ch = http_inc(0)) >= 0) {
  11291.             len--;
  11292.             if ( zfile )
  11293.                 zchout(ZOFILE,(CHAR)ch);
  11294.             if ( stdio )
  11295.                 conoc((CHAR)ch);
  11296.         }
  11297.     }
  11298.  
  11299.     if ( zfile )
  11300.         zclose(ZOFILE);
  11301.  
  11302.     if ( chunked ) {            /* Parse Trailing Headers */
  11303.         nullline = 0;
  11304.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11305.             buf[i] = ch;
  11306.             if ( buf[i] == 10 ) { /* found end of line */
  11307.                 if (i > 0 && buf[i-1] == 13)
  11308.                   i--;
  11309.                 if (i < 1)
  11310.                   nullline = 1;
  11311.                 buf[i] = '\0';
  11312.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11313.                     makestr(&headers[hdcnt++],buf);
  11314. #ifdef CMDATE2TM
  11315.                 if (!ckstrcmp(buf,"Last-Modified",13,0)) {
  11316.                     mod_t = http_date(&buf[15]);
  11317.                 } else if (!ckstrcmp(buf,"Date",4,0)) {
  11318.                     srv_t = http_date(&buf[4]);
  11319.                 }
  11320. #endif /* CMDATE2TM */
  11321.                 else if (!ckstrcmp(buf,"Connection:",11,0)) {
  11322.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11323.                         closecon = 1;
  11324.                 }
  11325.                 i = 0;
  11326.             } else {
  11327.                 i++;
  11328.             }
  11329.         }
  11330.     }
  11331.  
  11332.     if ( zfile ) {              /* Set timestamp */
  11333. #ifdef CMDATE2TM
  11334. #ifdef OS2
  11335.         u_t.actime = srv_t ? srv_t : local_t;
  11336.         u_t.modtime = mod_t ? mod_t : local_t;
  11337. #else /* OS2 */
  11338. #ifdef SYSUTIMEH
  11339.         u_t.actime = srv_t ? srv_t : local_t;
  11340.         u_t.modtime = mod_t ? mod_t : local_t;
  11341. #else
  11342. #ifdef BSD44
  11343.         u_t[0].tv_sec = srv_t ? srv_t : local_t;
  11344.         u_t[1].tv_sec = mod_t ? mod_t : local_t;
  11345. #else
  11346.         u_t.mtime = srv_t ? srv_t : local_t;
  11347.         u_t.atime = mod_t ? mod_t : local_t;
  11348. #endif /* BSD44 */
  11349. #endif /* SYSUTIMEH */
  11350. #endif /* OS2 */
  11351.             utime(local,&u_t);
  11352. #endif /* CMDATE2TM */
  11353.     }
  11354.  
  11355.   getexit:
  11356.     if (array)
  11357.       http_mkarray(headers,hdcnt,array);
  11358.  
  11359.     if ( closecon )
  11360.         http_close();
  11361.     free(request);
  11362.     for (i = 0; i < hdcnt; i++) {
  11363.         if (headers[i])
  11364.           free(headers[i]);
  11365.     }
  11366.     return(rc);
  11367. }
  11368.  
  11369. int
  11370. #ifdef CK_ANSIC
  11371. http_head(char * agent, char ** hdrlist, char * user,
  11372.           char * pwd, char array, char * local, char * remote,
  11373.           int stdio)
  11374. #else
  11375. http_head(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11376.     char * agent; char ** hdrlist; char * user;
  11377.     char * pwd; char array; char * local; char * remote;
  11378.     int stdio;
  11379. #endif /* CK_ANSIC */
  11380. {
  11381.     char * request = NULL;
  11382.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11383.     int    ch;
  11384.     int    http_fnd = 0;
  11385.     char   buf[HTTPBUFLEN], *p;
  11386.     int    nullline;
  11387.     time_t mod_t;
  11388.     time_t srv_t;
  11389.     time_t local_t;
  11390.     char passwd[64];
  11391.     char b64in[128];
  11392.     char b64out[256];
  11393.     char * headers[HTTPHEADCNT];
  11394.     int  closecon = 0;
  11395.     int  first = 1;
  11396.  
  11397.     if (httpfd == -1)
  11398.       return(-1);
  11399.  
  11400.     if (array) {
  11401.         for (i = 0; i < HTTPHEADCNT; i++)
  11402.           headers[i] = NULL;
  11403.     }
  11404.     len = 9;                            /* HEAD */
  11405.     len += strlen(HTTP_VERSION);
  11406.     len += strlen(remote);
  11407.     len += 16;
  11408.  
  11409.     if ( hdrlist ) {
  11410.         for (i = 0; hdrlist[i]; i++)
  11411.             len += strlen(hdrlist[i]) + 2;
  11412.     }
  11413.     len += strlen(http_host_port) + 8;
  11414.  
  11415.     if (agent)
  11416.       len += 13 + strlen(agent);
  11417.     if (user) {
  11418.         if (!pwd) {
  11419.             readpass("Password: ",passwd,64);
  11420.             pwd = passwd;
  11421.         }
  11422.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11423.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11424.         memset(pwd,0,strlen(pwd));      /* NOT PORTABLE */
  11425.         if (j < 0)
  11426.           return(-1);
  11427.         b64out[j] = '\0';
  11428.         len += j + 24;
  11429.     }
  11430. #ifdef HTTP_CLOSE
  11431.     len += 19;                          /* Connection: close */
  11432. #endif
  11433.     len += 3;                           /* blank line + null */
  11434.  
  11435.     request = (char *)malloc(len);
  11436.     if (!request)
  11437.       return(-1);
  11438.  
  11439.     sprintf(request,"HEAD %s %s\r\n",remote,HTTP_VERSION);
  11440.     ckstrncat(request,"Host: ", len);
  11441.     ckstrncat(request,http_host_port, len);
  11442.     ckstrncat(request,"\r\n",len);
  11443.     if (agent) {
  11444.         ckstrncat(request,"User-agent: ",len);
  11445.         ckstrncat(request,agent,len);
  11446.         ckstrncat(request,"\r\n",len);
  11447.     }
  11448.     if (user) {
  11449.         ckstrncat(request,"Authorization: Basic ",len);
  11450.         ckstrncat(request,b64out,len);
  11451.         ckstrncat(request,"\r\n",len);
  11452.     }
  11453.     if ( hdrlist ) {
  11454.         for (i = 0; hdrlist[i]; i++) {
  11455.             ckstrncat(request,hdrlist[i],len);
  11456.             ckstrncat(request,"\r\n",len);
  11457.         }
  11458.     }
  11459. #ifdef HTTP_CLOSE
  11460.     ckstrncat(request,"Connection: close\r\n",len);
  11461. #endif
  11462.     ckstrncat(request,"\r\n",len);
  11463.  
  11464.     if ( local && local[0] ) {
  11465.         if (!zopeno(ZOFILE,local,NULL,NULL)) {
  11466.             free(request);
  11467.             return(-1);
  11468.         }
  11469.     }
  11470.  
  11471.   headreq:
  11472.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11473.     {
  11474.         http_close();
  11475.         if ( first ) {
  11476.             first--;
  11477.             http_reopen();
  11478.             goto headreq;
  11479.         }
  11480.         rc = -1;
  11481.         goto headexit;
  11482.     }
  11483.  
  11484.     /* Process the headers */
  11485.  
  11486.     local_t = time(NULL);
  11487.     nullline = 0;
  11488.     i = 0;
  11489.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11490.         buf[i] = ch;
  11491.         if (buf[i] == 10) {             /* found end of line */
  11492.             if (i > 0 && buf[i-1] == 13)
  11493.               i--;
  11494.             if (i < 1)
  11495.               nullline = 1;
  11496.             buf[i] = '\0';
  11497.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11498.               makestr(&headers[hdcnt++],buf);
  11499.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11500.                 http_fnd = 1;
  11501.                 j = ckindex(" ",buf,0,0,0);
  11502.                 p = &buf[j];
  11503.                 while (isspace(*p))
  11504.                   p++;
  11505.                 switch (p[0]) {
  11506.                   case '1':             /* Informational message */
  11507.                     break;
  11508.                   case '2':             /* Success */
  11509.                     break;
  11510.                   case '3':             /* Redirection */
  11511.                   case '4':             /* Client failure */
  11512.                   case '5':             /* Server failure */
  11513.                   default:              /* Unknown */
  11514.                     if (!quiet)
  11515.                       printf("Failure: Server reports %s\n",p);
  11516.                     rc = -1;
  11517.                 }
  11518.                 http_set_code_reply(p);
  11519.             } else {
  11520.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11521.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11522.                         closecon = 1;
  11523.                 }
  11524.                 if ( local && local[0] ) {
  11525.                     zsout(ZOFILE,buf);
  11526.                     zsout(ZOFILE,"\r\n");
  11527.                 }
  11528.                 if (stdio)
  11529.                     printf("%s\r\n",buf);
  11530.             }
  11531.             i = 0;
  11532.         } else {
  11533.             i++;
  11534.         }
  11535.     }
  11536.     if (ch < 0 && first) {
  11537.         first--;
  11538.         http_close();
  11539.         http_reopen();
  11540.         goto headreq;
  11541.     }
  11542.     if ( http_fnd == 0 )
  11543.         rc = -1;
  11544.  
  11545.     if (array)
  11546.       http_mkarray(headers,hdcnt,array);
  11547.  
  11548.   headexit:
  11549.     if ( local && local[0] )
  11550.         zclose(ZOFILE);
  11551.     if (closecon)
  11552.         http_close();
  11553.     free(request);
  11554.     for (i = 0; i < hdcnt; i++) {
  11555.         if (headers[i])
  11556.           free(headers[i]);
  11557.     }
  11558.     return(rc);
  11559. }
  11560.  
  11561. int
  11562. #ifdef CK_ANSIC
  11563. http_index(char * agent, char ** hdrlist, char * user, char * pwd,
  11564.              char array, char * local, char * remote, int stdio)
  11565. #else
  11566. http_index(agent, hdrlist, user, pwd, array, local, remote, stdio)
  11567.     char * agent; char ** hdrlist; char * user; char * pwd;
  11568.     char array; char * local; char * remote; int stdio;
  11569. #endif /* CK_ANSIC */
  11570. {
  11571.     char * request = NULL;
  11572.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11573.     int    ch;
  11574.     int    http_fnd = 0;
  11575.     char   buf[HTTPBUFLEN], *p;
  11576.     int    nullline;
  11577.     time_t mod_t;
  11578.     time_t srv_t;
  11579.     time_t local_t;
  11580.     char passwd[64];
  11581.     char b64in[128];
  11582.     char b64out[256];
  11583.     char * headers[HTTPHEADCNT];
  11584.     int  closecon = 0;
  11585.     int  chunked = 0;
  11586.     int  zfile = 0;
  11587.     int  first = 1;
  11588.  
  11589.     if (httpfd == -1)
  11590.       return(-1);
  11591.  
  11592.     if (array) {
  11593.         for (i = 0; i < HTTPHEADCNT; i++)
  11594.           headers[i] = NULL;
  11595.     }
  11596.     len = 10;                            /* INDEX */
  11597.     len += strlen(HTTP_VERSION);
  11598.     len += strlen(remote);
  11599.     len += 16;
  11600.  
  11601.     if ( hdrlist ) {
  11602.         for (i = 0; hdrlist[i]; i++)
  11603.             len += strlen(hdrlist[i]) + 2;
  11604.     }
  11605.     len += strlen(http_host_port) + 8;
  11606.  
  11607.     if (agent)
  11608.         len += 13 + strlen(agent);
  11609.     if (user) {
  11610.         if (!pwd) {
  11611.             readpass("Password: ",passwd,64);
  11612.             pwd = passwd;
  11613.         }
  11614.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11615.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11616.         memset(pwd,0,strlen(pwd));
  11617.         if (j < 0)
  11618.           return(-1);
  11619.         b64out[j] = '\0';
  11620.         len += j + 24;
  11621.     }
  11622. #ifdef HTTP_CLOSE
  11623.     len += 19;                          /* Connection: close */
  11624. #endif
  11625.     len += 3;                           /* blank line + null */
  11626.  
  11627.     request = malloc(len);
  11628.     if (!request)
  11629.       return(-1);
  11630.  
  11631.     sprintf(request,"INDEX %s\r\n",HTTP_VERSION);
  11632.     ckstrncat(request,"Host: ", len);
  11633.     ckstrncat(request,http_host_port, len);
  11634.     ckstrncat(request,"\r\n",len);
  11635.     if (agent) {
  11636.         ckstrncat(request,"User-agent: ",len);
  11637.         ckstrncat(request,agent,len);
  11638.         ckstrncat(request,"\r\n",len);
  11639.     }
  11640.     if (user) {
  11641.         ckstrncat(request,"Authorization: Basic ",len);
  11642.         ckstrncat(request,b64out,len);
  11643.         ckstrncat(request,"\r\n",len);
  11644.     }
  11645.     if ( hdrlist ) {
  11646.         for (i = 0; hdrlist[i]; i++) {
  11647.             ckstrncat(request,hdrlist[i],len);
  11648.             ckstrncat(request,"\r\n",len);
  11649.         }
  11650.     }
  11651. #ifdef HTTP_CLOSE
  11652.     ckstrncat(request,"Connection: close\r\n",len);
  11653. #endif
  11654.     ckstrncat(request,"\r\n",len);
  11655.   indexreq:
  11656.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  11657.     {
  11658.         http_close();
  11659.         if ( first ) {
  11660.             first--;
  11661.             http_reopen();
  11662.             goto indexreq;
  11663.         }
  11664.         rc = -1;
  11665.         goto indexexit;
  11666.     }
  11667.  
  11668.     /* Process the headers */
  11669.     local_t = time(NULL);
  11670.     nullline = 0;
  11671.     i = 0;
  11672.     len = -1;
  11673.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11674.         buf[i] = ch;
  11675.         if (buf[i] == 10) {             /* found end of line */
  11676.             if (i > 0 && buf[i-1] == 13)
  11677.               i--;
  11678.             if (i < 1)
  11679.               nullline = 1;
  11680.             buf[i] = '\0';
  11681.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  11682.               makestr(&headers[hdcnt++],buf);
  11683.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  11684.                 http_fnd = 1;
  11685.                 j = ckindex(" ",buf,0,0,0);
  11686.                 p = &buf[j];
  11687.                 while (isspace(*p))
  11688.                   p++;
  11689.                 switch ( p[0] ) {
  11690.                   case '1':             /* Informational message */
  11691.                     break;
  11692.                   case '2':             /* Success */
  11693.                     break;
  11694.                   case '3':             /* Redirection */
  11695.                   case '4':             /* Client failure */
  11696.                   case '5':             /* Server failure */
  11697.                   default:              /* Unknown */
  11698.                     if (!quiet)
  11699.                       printf("Failure: Server reports %s\n",p);
  11700.                     rc = -1;
  11701.                 }
  11702.                 http_set_code_reply(p);
  11703.             } else if ( !nullline ) {
  11704.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11705.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11706.                         closecon = 1;
  11707.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  11708.                     len = atoi(&buf[16]);
  11709.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  11710.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  11711.                         chunked = 1;
  11712.                 }
  11713.                 printf("%s\n",buf);
  11714.             }
  11715.             i = 0;
  11716.         } else {
  11717.             i++;
  11718.         }
  11719.     }
  11720.  
  11721.     if (ch < 0 && first) {
  11722.         first--;
  11723.         http_close();
  11724.         http_reopen();
  11725.         goto indexreq;
  11726.     }
  11727.     if ( http_fnd == 0 ) {
  11728.         rc = -1;
  11729.         closecon = 1;
  11730.         goto indexexit;
  11731.     }
  11732.  
  11733.     /* Now we have the contents of the file */
  11734.     if ( local && local[0] ) {
  11735.         if (zopeno(ZOFILE,local,NULL,NULL))
  11736.             zfile = 1;
  11737.         else
  11738.             rc = -1;
  11739.     }
  11740.  
  11741.     if ( chunked ) {
  11742.         while ((len = http_get_chunk_len()) > 0) {
  11743.             while (len && (ch = http_inc(0)) >= 0) {
  11744.                 len--;
  11745.                 if ( zfile )
  11746.                     zchout(ZOFILE,(CHAR)ch);
  11747.                 if ( stdio )
  11748.                     conoc((CHAR)ch);
  11749.             }
  11750.             if ((ch = http_inc(0)) != CR)
  11751.                 break;
  11752.             if ((ch = http_inc(0)) != LF)
  11753.                 break;
  11754.         }
  11755.     } else {
  11756.         while (len && (ch = http_inc(0)) >= 0) {
  11757.             len--;
  11758.             if ( zfile )
  11759.                 zchout(ZOFILE,(CHAR)ch);
  11760.             if ( stdio )
  11761.                 conoc((CHAR)ch);
  11762.         }
  11763.     }
  11764.  
  11765.     if ( zfile )
  11766.         zclose(ZOFILE);
  11767.  
  11768.     if ( chunked ) {            /* Parse Trailing Headers */
  11769.         nullline = 0;
  11770.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11771.             buf[i] = ch;
  11772.             if ( buf[i] == 10 ) { /* found end of line */
  11773.                 if (i > 0 && buf[i-1] == 13)
  11774.                   i--;
  11775.                 if (i < 1)
  11776.                   nullline = 1;
  11777.                 buf[i] = '\0';
  11778.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11779.                     makestr(&headers[hdcnt++],buf);
  11780.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  11781.                     if ( ckindex("close",buf,11,0,0) != 0 )
  11782.                         closecon = 1;
  11783.                 }
  11784.                 i = 0;
  11785.             } else {
  11786.                 i++;
  11787.             }
  11788.         }
  11789.     }
  11790.     rc = 0;
  11791.  
  11792.   indexexit:
  11793.     if (array)
  11794.       http_mkarray(headers,hdcnt,array);
  11795.  
  11796.     if (closecon)
  11797.         http_close();
  11798.     free(request);
  11799.     for (i = 0; i < hdcnt; i++) {
  11800.         if (headers[i])
  11801.           free(headers[i]);
  11802.     }
  11803.     return(rc);
  11804. }
  11805.  
  11806. int
  11807. #ifdef CK_ANSIC
  11808. http_put(char * agent, char ** hdrlist, char * mime, char * user,
  11809.          char * pwd, char array, char * local, char * remote,
  11810.          char * dest, int stdio)
  11811. #else
  11812. http_put(agent, hdrlist, mime, user, pwd, array, local, remote, dest, stdio)
  11813.     char * agent; char ** hdrlist; char * mime; char * user;
  11814.     char * pwd; char array; char * local; char * remote; char * dest;
  11815.     int stdio;
  11816. #endif /* CK_ANSIC */
  11817. {
  11818.     char * request=NULL;
  11819.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  11820.     int    ch;
  11821.     int    http_fnd = 0;
  11822.     char   buf[HTTPBUFLEN], *p;
  11823.     int    nullline;
  11824.     time_t mod_t;
  11825.     time_t srv_t;
  11826.     time_t local_t;
  11827.     char passwd[64];
  11828.     char b64in[128];
  11829.     char b64out[256];
  11830.     int  filelen;
  11831.     char * headers[HTTPHEADCNT];
  11832.     int  closecon = 0;
  11833.     int  chunked = 0;
  11834.     int  first = 1;
  11835.     int  zfile = 0;
  11836.  
  11837.     if (httpfd == -1)
  11838.       return(-1);
  11839.     if (!mime) mime = "";
  11840.     if (!remote) remote = "";
  11841.     if (!local) local = "";
  11842.     if (!*local) return(-1);
  11843.  
  11844.     if (array) {
  11845.         for (i = 0; i < HTTPHEADCNT; i++)
  11846.           headers[i] = NULL;
  11847.     }
  11848.     filelen = zchki(local);
  11849.     if (filelen < 0)
  11850.       return(-1);
  11851.  
  11852.     /* Compute length of request header */
  11853.     len = 8;                            /* PUT */
  11854.     len += strlen(HTTP_VERSION);
  11855.     len += strlen(remote);
  11856.     len += 16;
  11857.  
  11858.     if ( hdrlist ) {
  11859.         for (i = 0; hdrlist[i]; i++)
  11860.             len += strlen(hdrlist[i]) + 2;
  11861.     }
  11862.     len += strlen(http_host_port) + 8;
  11863.  
  11864.     if (agent)
  11865.       len += 13 + strlen(agent);
  11866.     if (user) {
  11867.         if (!pwd) {
  11868.             readpass("Password: ",passwd,64);
  11869.             pwd = passwd;
  11870.         }
  11871.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  11872.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  11873.         memset(pwd,0,strlen(pwd));
  11874.         if (j < 0)
  11875.           return(-1);
  11876.         b64out[j] = '\0';
  11877.         len += j + 24;
  11878.     }
  11879.     len += 16 + strlen(mime);           /* Content-type: */
  11880.     len += 32;                          /* Content-length: */
  11881.     len += 32;                          /* Date: */
  11882. #ifdef HTTP_CLOSE
  11883.     len += 19;                          /* Connection: close */
  11884. #endif
  11885.     len += 3;                           /* blank line + null */
  11886.  
  11887.     request = malloc(len);
  11888.     if (!request)
  11889.       return(-1);
  11890.  
  11891.     sprintf(request,"PUT %s %s\r\n",remote,HTTP_VERSION);
  11892.     ckstrncat(request,"Date: ",len);
  11893. #ifdef CMDATE2TM
  11894.     ckstrncat(request,http_now(),len);
  11895. #else
  11896.     strcat(request,...);
  11897. #endif /* CMDATE2TM */
  11898.     ckstrncat(request,"\r\n",len);
  11899.     ckstrncat(request,"Host: ", len);
  11900.     ckstrncat(request,http_host_port, len);
  11901.     ckstrncat(request,"\r\n",len);
  11902.     if (agent) {
  11903.         ckstrncat(request,"User-agent: ",len);
  11904.         ckstrncat(request,agent,len);
  11905.         ckstrncat(request,"\r\n",len);
  11906.     }
  11907.     if (user) {
  11908.         ckstrncat(request,"Authorization: Basic ",len);
  11909.         ckstrncat(request,b64out,len);
  11910.         ckstrncat(request,"\r\n",len);
  11911.     }
  11912.     if ( hdrlist ) {
  11913.         for (i = 0; hdrlist[i]; i++) {
  11914.             ckstrncat(request,hdrlist[i],len);
  11915.             ckstrncat(request,"\r\n",len);
  11916.         }
  11917.     }
  11918.     ckstrncat(request,"Content-type: ",len);
  11919.     ckstrncat(request,mime,len);
  11920.     ckstrncat(request,"\r\n",len);
  11921.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  11922.     ckstrncat(request,buf,len);
  11923. #ifdef HTTP_CLOSE
  11924.     ckstrncat(request,"Connection: close\r\n",len);
  11925. #endif
  11926.     ckstrncat(request,"\r\n",len);
  11927.  
  11928.     /* Now we have the contents of the file */
  11929.     if (zopeni(ZIFILE,local)) {
  11930.  
  11931.       putreq:
  11932.         if (http_tol((CHAR *)request,strlen(request)) <= 0) { /* Send request */
  11933.             http_close();
  11934.             if ( first ) {
  11935.                 first--;
  11936.                 http_reopen();
  11937.                 goto putreq;
  11938.             }
  11939.             zclose(ZIFILE);
  11940.             rc = -1;
  11941.             goto putexit;
  11942.         }
  11943.         /* Request headers have been sent */
  11944.  
  11945.         i = 0;
  11946.         while (zchin(ZIFILE,&ch) == 0) {
  11947.             buf[i++] = ch;
  11948.             if (i == HTTPBUFLEN) {
  11949.                 if (http_tol((CHAR *)buf,HTTPBUFLEN) <= 0) {
  11950.                     http_close();
  11951.                     if ( first ) {
  11952.                         first--;
  11953.                         http_reopen();
  11954.                         goto putreq;
  11955.                     }
  11956.                 }
  11957.                 i = 0;
  11958.             }
  11959.         }
  11960.         if (i > 0) {
  11961.             if (http_tol((CHAR *)buf,i) < 0) {
  11962.                 http_close();
  11963.                 if ( first ) {
  11964.                     first--;
  11965.                     http_reopen();
  11966.                     goto putreq;
  11967.                 }
  11968.             }
  11969.         }
  11970.         zclose(ZIFILE);
  11971.  
  11972.         /* Process the response headers */
  11973.         local_t = time(NULL);
  11974.         nullline = 0;
  11975.         i = 0;
  11976.         len = -1;
  11977.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  11978.             buf[i] = ch;
  11979.             if (buf[i] == 10) {         /* found end of line */
  11980.                 if (i > 0 && buf[i-1] == 13)
  11981.                   i--;
  11982.                 if (i < 1)
  11983.                   nullline = 1;
  11984.                 buf[i] = '\0';
  11985.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  11986.                   makestr(&headers[hdcnt++],buf);
  11987.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  11988.                     http_fnd = 1;
  11989.                     j = ckindex(" ",buf,0,0,0);
  11990.                     p = &buf[j];
  11991.                     while (isspace(*p))
  11992.                       p++;
  11993.                     switch (p[0]) {
  11994.                       case '1':         /* Informational message */
  11995.                         break;
  11996.                       case '2':         /* Success */
  11997.                         break;
  11998.                       case '3':         /* Redirection */
  11999.                       case '4':         /* Client failure */
  12000.                       case '5':         /* Server failure */
  12001.                       default:          /* Unknown */
  12002.                         if (!quiet)
  12003.                           printf("Failure: Server reports %s\n",p);
  12004.                         rc = -1;
  12005.                     }
  12006.                     http_set_code_reply(p);
  12007.                 } else {
  12008.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12009.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12010.                             closecon = 1;
  12011.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12012.                         len = atoi(&buf[16]);
  12013.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12014.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  12015.                             chunked = 1;
  12016.                     }
  12017.                     if ( stdio )
  12018.                         printf("%s\n",buf);
  12019.                 }
  12020.                 i = 0;
  12021.             } else {
  12022.                 i++;
  12023.             }
  12024.         }
  12025.         if (ch < 0 && first) {
  12026.             first--;
  12027.             http_close();
  12028.             http_reopen();
  12029.             goto putreq;
  12030.         }
  12031.         if ( http_fnd == 0 ) {
  12032.             closecon = 1;
  12033.             rc = -1;
  12034.             goto putexit;
  12035.         }
  12036.  
  12037.         /* Any response data? */
  12038.         if ( dest && dest[0] ) {
  12039.             if (zopeno(ZOFILE,dest,NULL,NULL))
  12040.                 zfile = 1;
  12041.             else
  12042.                 rc = -1;
  12043.         }
  12044.  
  12045.         if ( chunked ) {
  12046.             while ((len = http_get_chunk_len()) > 0) {
  12047.                 while (len && (ch = http_inc(0)) >= 0) {
  12048.                     len--;
  12049.                     if ( zfile )
  12050.                         zchout(ZOFILE,(CHAR)ch);
  12051.                     if ( stdio )
  12052.                         conoc((CHAR)ch);
  12053.                 }
  12054.                 if ((ch = http_inc(0)) != CR)
  12055.                     break;
  12056.                 if ((ch = http_inc(0)) != LF)
  12057.                     break;
  12058.             }
  12059.         } else {
  12060.             while (len && (ch = http_inc(0)) >= 0) {
  12061.                 len--;
  12062.                 if ( zfile )
  12063.                     zchout(ZOFILE,(CHAR)ch);
  12064.                 if ( stdio )
  12065.                     conoc((CHAR)ch);
  12066.             }
  12067.         }
  12068.  
  12069.         if ( zfile )
  12070.             zclose(ZOFILE);
  12071.  
  12072.         if ( chunked ) {            /* Parse Trailing Headers */
  12073.             nullline = 0;
  12074.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12075.                 buf[i] = ch;
  12076.                 if ( buf[i] == 10 ) { /* found end of line */
  12077.                     if (i > 0 && buf[i-1] == 13)
  12078.                       i--;
  12079.                     if (i < 1)
  12080.                       nullline = 1;
  12081.                     buf[i] = '\0';
  12082.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  12083.                         makestr(&headers[hdcnt++],buf);
  12084.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12085.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12086.                             closecon = 1;
  12087.                     }
  12088.                     i = 0;
  12089.                 } else {
  12090.                     i++;
  12091.                 }
  12092.             }
  12093.         }
  12094.     } else {
  12095.         rc = -1;
  12096.     }
  12097.  
  12098.   putexit:
  12099.     if ( array )
  12100.         http_mkarray(headers,hdcnt,array);
  12101.  
  12102.     if (closecon)
  12103.         http_close();
  12104.     free(request);
  12105.     for (i = 0; i < hdcnt; i++) {
  12106.         if (headers[i])
  12107.           free(headers[i]);
  12108.     }
  12109.     return(rc);
  12110. }
  12111.  
  12112. int
  12113. #ifdef CK_ANSIC
  12114. http_delete(char * agent, char ** hdrlist, char * user,
  12115.           char * pwd, char array, char * remote)
  12116. #else
  12117. http_delete(agent, hdrlist, user, pwd, array, remote)
  12118.     char * agent; char ** hdrlist; char * user;
  12119.     char * pwd; char array; char * remote;
  12120. #endif /* CK_ANSIC */
  12121. {
  12122.     char * request=NULL;
  12123.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12124.     int    ch;
  12125.     int    http_fnd = 0;
  12126.     char   buf[HTTPBUFLEN], *p;
  12127.     int    nullline;
  12128.     time_t mod_t;
  12129.     time_t srv_t;
  12130.     time_t local_t;
  12131.     char passwd[64];
  12132.     char b64in[128];
  12133.     char b64out[256];
  12134.     char * headers[HTTPHEADCNT];
  12135.     int  closecon = 0;
  12136.     int  chunked = 0;
  12137.     int  first = 1;
  12138.  
  12139.     if (httpfd == -1)
  12140.       return(-1);
  12141.  
  12142.     if (array) {
  12143.         for (i = 0; i < HTTPHEADCNT; i++)
  12144.           headers[i] = NULL;
  12145.     }
  12146.  
  12147.     /* Compute length of request header */
  12148.     len = 11;                            /* DELETE */
  12149.     len += strlen(HTTP_VERSION);
  12150.     len += strlen(remote);
  12151.     len += 16;
  12152.  
  12153.     if ( hdrlist ) {
  12154.         for (i = 0; hdrlist[i]; i++)
  12155.             len += strlen(hdrlist[i]) + 2;
  12156.     }
  12157.     len += strlen(http_host_port) + 8;
  12158.  
  12159.     if (agent)
  12160.       len += 13 + strlen(agent);
  12161.     if (user) {
  12162.         if (!pwd) {
  12163.             readpass("Password: ",passwd,64);
  12164.             pwd = passwd;
  12165.         }
  12166.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12167.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12168.         memset(pwd,0,strlen(pwd));
  12169.         if (j < 0)
  12170.           return(-1);
  12171.         b64out[j] = '\0';
  12172.         len += j + 24;
  12173.     }
  12174.     len += 32;                          /* Date: */
  12175. #ifdef HTTP_CLOSE
  12176.     len += 19;                          /* Connection: close */
  12177. #endif
  12178.     len += 3;                           /* blank line + null */
  12179.  
  12180.     request = malloc(len);
  12181.     if (!request)
  12182.       return(-1);
  12183.  
  12184.     sprintf(request,"DELETE %s %s\r\n",remote,HTTP_VERSION);
  12185.     ckstrncat(request,"Date: ",len);
  12186. #ifdef CMDATE2TM
  12187.     ckstrncat(request,http_now(),len);
  12188. #else
  12189.     strcat(request,...);
  12190. #endif /* CMDATE2TM */
  12191.     ckstrncat(request,"\r\n",len);
  12192.     ckstrncat(request,"Host: ", len);
  12193.     ckstrncat(request,http_host_port, len);
  12194.     ckstrncat(request,"\r\n",len);
  12195.     if (agent) {
  12196.         ckstrncat(request,"User-agent: ",len);
  12197.         ckstrncat(request,agent,len);
  12198.         ckstrncat(request,"\r\n",len);
  12199.     }
  12200.     if (user) {
  12201.         ckstrncat(request,"Authorization: Basic ",len);
  12202.         ckstrncat(request,b64out,len);
  12203.         ckstrncat(request,"\r\n",len);
  12204.     }
  12205.     if ( hdrlist ) {
  12206.         for (i = 0; hdrlist[i]; i++) {
  12207.             ckstrncat(request,hdrlist[i],len);
  12208.             ckstrncat(request,"\r\n",len);
  12209.         }
  12210.     }
  12211. #ifdef HTTP_CLOSE
  12212.     ckstrncat(request,"Connection: close\r\n",len);
  12213. #endif
  12214.     ckstrncat(request,"\r\n",len);
  12215.   delreq:
  12216.     if (http_tol((CHAR *)request,strlen(request)) < 0)
  12217.     {
  12218.         http_close();
  12219.         if ( first ) {
  12220.             first--;
  12221.             http_reopen();
  12222.             goto delreq;
  12223.         }
  12224.         rc = -1;
  12225.         goto delexit;
  12226.     }
  12227.  
  12228.     /* Process the response headers */
  12229.     local_t = time(NULL);
  12230.     nullline = 0;
  12231.     i = 0;
  12232.     len = -1;
  12233.     while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12234.         buf[i] = ch;
  12235.         if (buf[i] == 10) {         /* found end of line */
  12236.             if (i > 0 && buf[i-1] == 13)
  12237.               i--;
  12238.             if (i < 1)
  12239.               nullline = 1;
  12240.             buf[i] = '\0';
  12241.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12242.                 makestr(&headers[hdcnt++],buf);
  12243.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12244.                 http_fnd = 1;
  12245.                 j = ckindex(" ",buf,0,0,0);
  12246.                 p = &buf[j];
  12247.                 while (isspace(*p))
  12248.                   p++;
  12249.                 switch (p[0]) {
  12250.                   case '1':             /* Informational message */
  12251.                     break;
  12252.                   case '2':             /* Success */
  12253.                     break;
  12254.                   case '3':             /* Redirection */
  12255.                   case '4':             /* Client failure */
  12256.                   case '5':             /* Server failure */
  12257.                   default:              /* Unknown */
  12258.                     if (!quiet)
  12259.                       printf("Failure: Server reports %s\n",p);
  12260.                     rc = -1;
  12261.                 }
  12262.                 http_set_code_reply(p);
  12263.             } else {
  12264.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12265.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12266.                         closecon = 1;
  12267.                 } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12268.                     len = atoi(&buf[16]);
  12269.                 } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12270.                     if ( ckindex("chunked",buf,18,0,0) != 0 )
  12271.                         chunked = 1;
  12272.                 }
  12273.                 printf("%s\n",buf);
  12274.             }
  12275.             i = 0;
  12276.         } else {
  12277.             i++;
  12278.         }
  12279.     }
  12280.     if (ch < 0 && first) {
  12281.         first--;
  12282.         http_close();
  12283.         http_reopen();
  12284.         goto delreq;
  12285.     }
  12286.     if ( http_fnd == 0 ) {
  12287.         rc = -1;
  12288.         closecon = 1;
  12289.         goto delexit;
  12290.     }
  12291.  
  12292.     /* Any response data? */
  12293.     if ( chunked ) {
  12294.         while ((len = http_get_chunk_len()) > 0) {
  12295.             while (len && (ch = http_inc(0)) >= 0) {
  12296.                 len--;
  12297.                 conoc((CHAR)ch);
  12298.             }
  12299.             if ((ch = http_inc(0)) != CR)
  12300.                 break;
  12301.             if ((ch = http_inc(0)) != LF)
  12302.                 break;
  12303.         }
  12304.     } else {
  12305.         while (len && (ch = http_inc(0)) >= 0) {
  12306.             len--;
  12307.             conoc((CHAR)ch);
  12308.         }
  12309.     }
  12310.  
  12311.     if ( chunked ) {            /* Parse Trailing Headers */
  12312.         nullline = 0;
  12313.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12314.             buf[i] = ch;
  12315.             if ( buf[i] == 10 ) { /* found end of line */
  12316.                 if (i > 0 && buf[i-1] == 13)
  12317.                   i--;
  12318.                 if (i < 1)
  12319.                   nullline = 1;
  12320.                 buf[i] = '\0';
  12321.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12322.                     makestr(&headers[hdcnt++],buf);
  12323.                 if (!ckstrcmp(buf,"Connection:",11,0)) {
  12324.                     if ( ckindex("close",buf,11,0,0) != 0 )
  12325.                         closecon = 1;
  12326.                 }
  12327.                 i = 0;
  12328.             } else {
  12329.                 i++;
  12330.             }
  12331.         }
  12332.     }
  12333.  
  12334.   delexit:
  12335.     if (array)
  12336.         http_mkarray(headers,hdcnt,array);
  12337.  
  12338.     if (closecon)
  12339.         http_close();
  12340.     free(request);
  12341.     for (i = 0; i < hdcnt; i++) {
  12342.         if (headers[i])
  12343.           free(headers[i]);
  12344.     }
  12345.     return(rc);
  12346. }
  12347.  
  12348. int
  12349. #ifdef CK_ANSIC
  12350. http_post(char * agent, char ** hdrlist, char * mime, char * user,
  12351.           char * pwd, char array, char * local, char * remote,
  12352.           char * dest, int stdio)
  12353. #else
  12354. http_post(agent, hdrlist, mime, user, pwd, array, local, remote, dest,
  12355.           stdio)
  12356.     char * agent; char ** hdrlist; char * mime; char * user;
  12357.     char * pwd; char array; char * local; char * remote; char * dest;
  12358.     int stdio;
  12359. #endif /* CK_ANSIC */
  12360. {
  12361.     char * request=NULL;
  12362.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12363.     int    ch;
  12364.     int    http_fnd = 0;
  12365.     char   buf[HTTPBUFLEN], *p;
  12366.     int    nullline;
  12367.     time_t mod_t;
  12368.     time_t srv_t;
  12369.     time_t local_t;
  12370.     char passwd[64];
  12371.     char b64in[128];
  12372.     char b64out[256];
  12373.     int  filelen;
  12374.     char * headers[HTTPHEADCNT];
  12375.     int  closecon = 0;
  12376.     int  chunked = 0;
  12377.     int  zfile = 0;
  12378.     int  first = 1;
  12379.  
  12380.     if (httpfd == -1)
  12381.       return(-1);
  12382.  
  12383.     if (array) {
  12384.         for (i = 0; i < HTTPHEADCNT; i++)
  12385.           headers[i] = NULL;
  12386.     }
  12387.     filelen = zchki(local);
  12388.     if (filelen < 0)
  12389.       return(-1);
  12390.  
  12391.     /* Compute length of request header */
  12392.     len = 9;                            /* POST */
  12393.     len += strlen(HTTP_VERSION);
  12394.     len += strlen(remote);
  12395.     len += 16;
  12396.  
  12397.     if ( hdrlist ) {
  12398.         for (i = 0; hdrlist[i]; i++)
  12399.             len += strlen(hdrlist[i]) + 2;
  12400.     }
  12401.     len += strlen(http_host_port) + 8;
  12402.  
  12403.     if (agent)
  12404.       len += 13 + strlen(agent);
  12405.     if (user) {
  12406.         if (!pwd) {
  12407.             readpass("Password: ",passwd,64);
  12408.             pwd = passwd;
  12409.         }
  12410.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12411.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12412.         memset(pwd,0,strlen(pwd));
  12413.         if (j < 0)
  12414.           return(-1);
  12415.         b64out[j] = '\0';
  12416.         len += j + 24;
  12417.     }
  12418.     len += 16 + strlen(mime);           /* Content-type: */
  12419.     len += 32;                          /* Content-length: */
  12420.     len += 32;                          /* Date: */
  12421. #ifdef HTTP_CLOSE
  12422.     len += 19;                          /* Connection: close */
  12423. #endif
  12424.     len += 3;                           /* blank line + null */
  12425.  
  12426.     request = malloc(len);
  12427.     if (!request)
  12428.       return(-1);
  12429.  
  12430.     sprintf(request,"POST %s %s\r\n",remote,HTTP_VERSION);
  12431.     ckstrncat(request,"Date: ",len);
  12432.     ckstrncat(request,http_now(),len);
  12433.     ckstrncat(request,"\r\n",len);
  12434.     ckstrncat(request,"Host: ", len);
  12435.     ckstrncat(request,http_host_port, len);
  12436.     ckstrncat(request,"\r\n",len);
  12437.     if (agent) {
  12438.         ckstrncat(request,"User-agent: ",len);
  12439.         ckstrncat(request,agent,len);
  12440.         ckstrncat(request,"\r\n",len);
  12441.     }
  12442.     if (user) {
  12443.         ckstrncat(request,"Authorization: Basic ",len);
  12444.         ckstrncat(request,b64out,len);
  12445.         ckstrncat(request,"\r\n",len);
  12446.     }
  12447.     if ( hdrlist ) {
  12448.         for (i = 0; hdrlist[i]; i++) {
  12449.             ckstrncat(request,hdrlist[i],len);
  12450.             ckstrncat(request,"\r\n",len);
  12451.         }
  12452.     }
  12453.     ckstrncat(request,"Content-type: ",len);
  12454.     ckstrncat(request,mime,len);
  12455.     ckstrncat(request,"\r\n",len);
  12456. #ifdef HTTP_CLOSE
  12457.     ckstrncat(request,"Connection: close\r\n",len);
  12458. #endif
  12459.     sprintf(buf,"Content-length: %d\r\n",filelen,len);
  12460.     ckstrncat(request,buf,len);
  12461.     ckstrncat(request,"\r\n",len);
  12462.     ckstrncat(request,"\r\n",len);
  12463.  
  12464.     /* Now we have the contents of the file */
  12465.   postopen:
  12466.     if (zopeni(ZIFILE,local)) {
  12467.       postreq:
  12468.         if (http_tol((CHAR *)request,strlen(request)) < 0)
  12469.         {
  12470.             http_close();
  12471.             if ( first ) {
  12472.                 first--;
  12473.                 http_reopen();
  12474.                 goto postreq;
  12475.             }
  12476.             rc = -1;
  12477.             zclose(ZIFILE);
  12478.             goto postexit;
  12479.         }
  12480.  
  12481.         i = 0;
  12482.         while (zchin(ZIFILE,&ch) == 0) {
  12483.             buf[i++] = ch;
  12484.             if (i == HTTPBUFLEN) {
  12485.                 http_tol((CHAR *)buf,HTTPBUFLEN);
  12486.                 i = 0;
  12487.             }
  12488.         }
  12489.         if (i > 0)
  12490.           http_tol((CHAR *)buf,HTTPBUFLEN);
  12491.         zclose(ZIFILE);
  12492.  
  12493.         /* Process the response headers */
  12494.         local_t = time(NULL);
  12495.         nullline = 0;
  12496.         i = 0;
  12497.         len = -1;
  12498.         while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12499.             buf[i] = ch;
  12500.             if (buf[i] == 10) {         /* found end of line */
  12501.                 if (i > 0 && buf[i-1] == 13)
  12502.                   i--;
  12503.                 if (i < 1)
  12504.                   nullline = 1;
  12505.                 buf[i] = '\0';
  12506.                 if (array && !nullline && hdcnt < HTTPHEADCNT)
  12507.                   makestr(&headers[hdcnt++],buf);
  12508.                 if (!ckstrcmp(buf,"HTTP",4,0)) {
  12509.                     http_fnd = 1;
  12510.                     j = ckindex(" ",buf,0,0,0);
  12511.                     p = &buf[j];
  12512.                     while (isspace(*p))
  12513.                       p++;
  12514.                     switch (p[0]) {
  12515.                       case '1':         /* Informational message */
  12516.                         break;
  12517.                       case '2':         /* Success */
  12518.                         break;
  12519.                       case '3':         /* Redirection */
  12520.                       case '4':         /* Client failure */
  12521.                       case '5':         /* Server failure */
  12522.                       default:          /* Unknown */
  12523.                         if (!quiet)
  12524.                           printf("Failure: Server reports %s\n",p);
  12525.                         rc = -1;
  12526.                     }
  12527.                     http_set_code_reply(p);
  12528.                 } else {
  12529.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12530.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12531.                             closecon = 1;
  12532.                     } else if (!ckstrcmp(buf,"Content-Length:",15,0)) {
  12533.                         len = atoi(&buf[16]);
  12534.                     } else if (!ckstrcmp(buf,"Transfer-Encoding:",18,0)) {
  12535.                         if ( ckindex("chunked",buf,18,0,0) != 0 )
  12536.                             chunked = 1;
  12537.                     }
  12538.                     if (stdio)
  12539.                         printf("%s\n",buf);
  12540.                 }
  12541.                 i = 0;
  12542.             } else {
  12543.                 i++;
  12544.             }
  12545.         }
  12546.         if (ch < 0 && first) {
  12547.             first--;
  12548.             http_close();
  12549.             http_reopen();
  12550.             goto postopen;
  12551.         }
  12552.         if (http_fnd == 0) {
  12553.             rc = -1;
  12554.             closecon = 1;
  12555.             goto postexit;
  12556.         }
  12557.  
  12558.         /* Any response data? */
  12559.         if ( dest && dest[0] ) {
  12560.             if (zopeno(ZOFILE,dest,NULL,NULL))
  12561.                 zfile = 1;
  12562.             else
  12563.                 rc = -1;
  12564.         }
  12565.  
  12566.         if ( chunked ) {
  12567.             while ((len = http_get_chunk_len()) > 0) {
  12568.                 while (len && (ch = http_inc(0)) >= 0) {
  12569.                     len--;
  12570.                     if ( zfile )
  12571.                         zchout(ZOFILE,(CHAR)ch);
  12572.                     if ( stdio )
  12573.                         conoc((CHAR)ch);
  12574.                 }
  12575.                 if ((ch = http_inc(0)) != CR)
  12576.                     break;
  12577.                 if ((ch = http_inc(0)) != LF)
  12578.                     break;
  12579.             }
  12580.         } else {
  12581.             while (len && (ch = http_inc(0)) >= 0) {
  12582.                 len--;
  12583.                 if ( zfile )
  12584.                     zchout(ZOFILE,(CHAR)ch);
  12585.                 if ( stdio )
  12586.                     conoc((CHAR)ch);
  12587.             }
  12588.         }
  12589.  
  12590.         if ( zfile )
  12591.             zclose(ZOFILE);
  12592.  
  12593.         if ( chunked ) {            /* Parse Trailing Headers */
  12594.             nullline = 0;
  12595.             while (!nullline && (ch = http_inc(0)) >= 0 && i < HTTPBUFLEN) {
  12596.                 buf[i] = ch;
  12597.                 if ( buf[i] == 10 ) { /* found end of line */
  12598.                     if (i > 0 && buf[i-1] == 13)
  12599.                       i--;
  12600.                     if (i < 1)
  12601.                       nullline = 1;
  12602.                     buf[i] = '\0';
  12603.                     if (array && !nullline && hdcnt < HTTPHEADCNT)
  12604.                         makestr(&headers[hdcnt++],buf);
  12605.                     if (!ckstrcmp(buf,"Connection:",11,0)) {
  12606.                         if ( ckindex("close",buf,11,0,0) != 0 )
  12607.                             closecon = 1;
  12608.                     }
  12609.                     i = 0;
  12610.                 } else {
  12611.                     i++;
  12612.                 }
  12613.             }
  12614.         }
  12615.     } else {
  12616.         rc = -1;
  12617.     }
  12618.  
  12619.   postexit:
  12620.     if (array)
  12621.         http_mkarray(headers,hdcnt,array);
  12622.     if (closecon)
  12623.         http_close();
  12624.     free(request);
  12625.     for (i = 0; i < hdcnt; i++) {
  12626.         if (headers[i])
  12627.           free(headers[i]);
  12628.     }
  12629.     return(rc);
  12630. }
  12631.  
  12632. int
  12633. #ifdef CK_ANSIC
  12634. http_connect(int socket, char * agent, char ** hdrlist, char * user,
  12635.              char * pwd, char array, char * host_port)
  12636. #else
  12637. http_connect(socket, agent, hdrlist, user, pwd, array, host_port)
  12638.     int socket;
  12639.     char * agent; char ** hdrlist; char * user;
  12640.     char * pwd; char array; char * host_port;
  12641. #endif /* CK_ANSIC */
  12642. {
  12643.     char * request=NULL;
  12644.     int    i, j, len = 0, hdcnt = 0, rc = 0;
  12645.     int    http_fnd = 0;
  12646.     char   buf[HTTPBUFLEN], *p, ch;
  12647.     int    nullline;
  12648.     time_t mod_t;
  12649.     time_t srv_t;
  12650.     time_t local_t;
  12651.     char passwd[64];
  12652.     char b64in[128];
  12653.     char b64out[256];
  12654.     char * headers[HTTPHEADCNT];
  12655.     int    connected = 0;
  12656.     int    chunked = 0;
  12657.  
  12658.     tcp_http_proxy_errno = 0;
  12659.  
  12660.     if (socket == -1)
  12661.       return(-1);
  12662.  
  12663.     if (array) {
  12664.         for (i = 0; i < HTTPHEADCNT; i++)
  12665.           headers[i] = NULL;
  12666.     }
  12667.  
  12668.     /* Compute length of request header */
  12669.     len = 12;                            /* CONNECT */
  12670.     len += strlen(HTTP_VERSION);
  12671.     len += strlen(host_port);
  12672.     len += 16;
  12673.     len += strlen("Proxy-Connection: Keep-Alive\r\n");
  12674.     if ( hdrlist ) {
  12675.         for (i = 0; hdrlist[i]; i++)
  12676.             len += strlen(hdrlist[i]) + 2;
  12677.     }
  12678.     if (agent)
  12679.       len += 13 + strlen(agent);
  12680.     if (user) {
  12681.         if (!pwd) {
  12682.             readpass("Password: ",passwd,64);
  12683.             pwd = passwd;
  12684.         }
  12685.         ckmakmsg(b64in,sizeof(b64in),user,":",pwd,NULL);
  12686.         j = b8tob64(b64in,strlen(b64in),b64out,256);
  12687.         memset(pwd,0,strlen(pwd));
  12688.         if (j < 0)
  12689.           return(-1);
  12690.         b64out[j] = '\0';
  12691.         len += j + 72;
  12692.     }
  12693.     len += 32;                          /* Date: */
  12694.     len += 3;                           /* blank line + null */
  12695.  
  12696.     request = malloc(len);
  12697.     if (!request)
  12698.       return(-1);
  12699.  
  12700.     sprintf(request,"CONNECT %s %s\r\n",host_port,HTTP_VERSION);
  12701.     ckstrncat(request,"Date: ",len);
  12702. #ifdef CMDATE2TM
  12703.     ckstrncat(request,http_now(),len);
  12704. #else
  12705.     strcat(request,...);
  12706. #endif /* CMDATE2TM */
  12707.     ckstrncat(request,"\r\n",len);
  12708.     if (agent) {
  12709.         ckstrncat(request,"User-agent: ",len);
  12710.         ckstrncat(request,agent,len);
  12711.         ckstrncat(request,"\r\n",len);
  12712.     }
  12713.     if (user) {
  12714.         ckstrncat(request,"Proxy-authorization: Basic ",len);
  12715.         ckstrncat(request,b64out,len);
  12716.         ckstrncat(request,"\r\n",len);
  12717.         ckstrncat(request,"Extension: Security/Remote-Passphrase\r\n",len);
  12718.     }
  12719.     ckstrncat(request,"Proxy-Connection: Keep-Alive\r\n",len);
  12720.     if ( hdrlist ) {
  12721.         for (i = 0; hdrlist[i]; i++) {
  12722.             ckstrncat(request,hdrlist[i],len);
  12723.             ckstrncat(request,"\r\n",len);
  12724.         }
  12725.     }
  12726.     ckstrncat(request,"\r\n",len);
  12727.     len = strlen(request);
  12728.  
  12729. #ifdef TCPIPLIB
  12730.     /* Send request */
  12731.     if (socket_write(socket,(CHAR *)request,strlen(request)) < 0) {
  12732.       rc = -1;
  12733.       goto connexit;
  12734.     }
  12735. #else
  12736.     if (write(socket,(CHAR *)request,strlen(request)) < 0) { /* Send request */
  12737.         rc = -1;
  12738.         goto connexit;
  12739.     }
  12740. #endif /* TCPIPLIB */
  12741.  
  12742.     /* Process the response headers */
  12743.     local_t = time(NULL);
  12744.     nullline = 0;
  12745.     i = 0;
  12746.     while (!nullline &&
  12747. #ifdef TCPIPLIB
  12748.            (socket_read(socket,&ch,1) == 1) &&
  12749. #else
  12750.            (read(socket,&ch,1) == 1) &&
  12751. #endif /* TCPIPLIB */
  12752.            i < HTTPBUFLEN) {
  12753.         buf[i] = ch;
  12754.         if (buf[i] == 10) {         /* found end of line */
  12755.             if (i > 0 && buf[i-1] == 13)
  12756.               i--;
  12757.             if (i < 1)
  12758.               nullline = 1;
  12759.             buf[i] = '\0';
  12760.  
  12761.             if (array && !nullline && hdcnt < HTTPHEADCNT)
  12762.                 makestr(&headers[hdcnt++],buf);
  12763.             if (!ckstrcmp(buf,"HTTP",4,0)) {
  12764.                 http_fnd = 1;
  12765.                 j = ckindex(" ",buf,0,0,0);
  12766.                 p = &buf[j];
  12767.                 while (isspace(*p))
  12768.                   p++;
  12769.                 tcp_http_proxy_errno = atoi(p);
  12770.                 switch (p[0]) {
  12771.                   case '1':             /* Informational message */
  12772.                     break;
  12773.                   case '2':             /* Success */
  12774.                     connected = 1;
  12775.                     break;
  12776.                   case '3':             /* Redirection */
  12777.                   case '4':             /* Client failure */
  12778.                   case '5':             /* Server failure */
  12779.                   default:              /* Unknown */
  12780.                     if (!quiet)
  12781.                       printf("Failure: Server reports %s\n",p);
  12782.                     rc = -1;
  12783.                 }
  12784.                 http_set_code_reply(p);
  12785.             } else {
  12786.                 printf("%s\n",buf);
  12787.             }
  12788.             i = 0;
  12789.         } else {
  12790.             i++;
  12791.         }
  12792.     }
  12793.     if ( http_fnd == 0 )
  12794.         rc = -1;
  12795.  
  12796.     if (array)
  12797.         http_mkarray(headers,hdcnt,array);
  12798.  
  12799.   connexit:
  12800.     if ( !connected ) {
  12801.         if ( socket == ttyfd ) {
  12802.             ttclos(0);
  12803.         }
  12804.         else if ( socket == httpfd ) {
  12805.             http_close();
  12806.         }
  12807.     }
  12808.  
  12809.     free(request);
  12810.     for (i = 0; i < hdcnt; i++) {
  12811.         if (headers[i])
  12812.           free(headers[i]);
  12813.     }
  12814.     return(rc);
  12815. }
  12816. #endif /* NOHTTP */
  12817.  
  12818. #ifdef CK_DNS_SRV
  12819.  
  12820. #define INCR_CHECK(x,y) x += y; if (x > size + answer.bytes) goto dnsout
  12821. #define CHECK(x,y) if (x + y > size + answer.bytes) goto dnsout
  12822. #define NTOHSP(x,y) x[0] << 8 | x[1]; x += y
  12823.  
  12824. #ifndef CKQUERYTYPE
  12825. #ifdef UNIXWARE
  12826. #ifndef UW7
  12827. #define CKQUERYTYPE CHAR
  12828. #endif /* UW7 */
  12829. #endif /* UNIXWARE */
  12830. #endif /* CKQUERYTYPE */
  12831.  
  12832. #ifndef CKQUERYTYPE
  12833. #define CKQUERYTYPE char
  12834. #endif /* CKQUERYTYPE */
  12835.  
  12836. /* 1 is success, 0 is failure */
  12837. int
  12838. locate_srv_dns(host, service, protocol, addr_pp, naddrs)
  12839.     char *host;
  12840.     char *service;
  12841.     char *protocol;
  12842.     struct sockaddr **addr_pp;
  12843.     int *naddrs;
  12844. {
  12845.     int nout, j, count;
  12846.     union {
  12847.         unsigned char bytes[2048];
  12848.         HEADER hdr;
  12849.     } answer;
  12850.     unsigned char *p=NULL;
  12851.     CKQUERYTYPE query[MAX_DNS_NAMELEN];
  12852. #ifdef CK_ANSIC
  12853.     const char * h;
  12854. #else
  12855.     char * h;
  12856. #endif /* CK_ANSIC */
  12857.     struct sockaddr *addr = NULL;
  12858.     struct sockaddr_in *sin = NULL;
  12859.     struct hostent *hp = NULL;
  12860.     int type, class;
  12861.     int priority, weight, size, len, numanswers, numqueries, rdlen;
  12862.     unsigned short port;
  12863. #ifdef CK_ANSIC
  12864.     const
  12865. #endif /* CK_ANSIC */
  12866.       int hdrsize = sizeof(HEADER);
  12867.     struct srv_dns_entry {
  12868.         struct srv_dns_entry *next;
  12869.         int priority;
  12870.         int weight;
  12871.         unsigned short port;
  12872.         char *host;
  12873.     };
  12874.     struct srv_dns_entry *head = NULL;
  12875.     struct srv_dns_entry *srv = NULL, *entry = NULL;
  12876.     char * s = NULL;
  12877.  
  12878.     nout = 0;
  12879.     addr = (struct sockaddr *) malloc(sizeof(struct sockaddr));
  12880.     if (addr == NULL)
  12881.       return 0;
  12882.  
  12883.     count = 1;
  12884.  
  12885.     /*
  12886.      * First build a query of the form:
  12887.      *
  12888.      *   service.protocol.host
  12889.      *
  12890.      * which will most likely be something like:
  12891.      *
  12892.      *   _telnet._tcp.host
  12893.      *
  12894.      */
  12895.     if (((int)strlen(service) + strlen(protocol) + strlen(host) + 5)
  12896.         > MAX_DNS_NAMELEN
  12897.         )
  12898.       goto dnsout;
  12899.  
  12900.     /* Realm names don't (normally) end with ".", but if the query
  12901.        doesn't end with "." and doesn't get an answer as is, the
  12902.        resolv code will try appending the local domain.  Since the
  12903.        realm names are absolutes, let's stop that.
  12904.  
  12905.        But only if a name has been specified.  If we are performing
  12906.        a search on the prefix alone then the intention is to allow
  12907.        the local domain or domain search lists to be expanded.
  12908.     */
  12909.     h = host + strlen (host);
  12910.     ckmakxmsg(query, sizeof(query), "_",service,"._",protocol,".", host,
  12911.               ((h > host) && (h[-1] != '.')?".":NULL),
  12912.                NULL,NULL,NULL,NULL,NULL);
  12913.  
  12914.     size = res_search(query, C_IN, T_SRV, answer.bytes, sizeof(answer.bytes));
  12915.  
  12916.     if (size < hdrsize)
  12917.       goto dnsout;
  12918.  
  12919.     /* We got a reply - See how many answers it contains. */
  12920.  
  12921.     p = answer.bytes;
  12922.  
  12923.     numqueries = ntohs(answer.hdr.qdcount);
  12924.     numanswers = ntohs(answer.hdr.ancount);
  12925.  
  12926.     p += sizeof(HEADER);
  12927.  
  12928.     /*
  12929.      * We need to skip over all of the questions, so we have to iterate
  12930.      * over every query record.  dn_expand() is able to tell us the size
  12931.      * of compressed DNS names, so we use it.
  12932.      */
  12933.     while (numqueries--) {
  12934.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  12935.         if (len < 0)
  12936.           goto dnsout;
  12937.         INCR_CHECK(p, len + 4);
  12938.     }
  12939.  
  12940.     /*
  12941.      * We're now pointing at the answer records.  Only process them if
  12942.      * they're actually T_SRV records (they might be CNAME records,
  12943.      * for instance).
  12944.      *
  12945.      * But in a DNS reply, if you get a CNAME you always get the associated
  12946.      * "real" RR for that CNAME.  RFC 1034, 3.6.2:
  12947.      *
  12948.      * CNAME RRs cause special action in DNS software.  When a name server
  12949.      * fails to find a desired RR in the resource set associated with the
  12950.      * domain name, it checks to see if the resource set consists of a CNAME
  12951.      * record with a matching class.  If so, the name server includes the CNAME
  12952.      * record in the response and restarts the query at the domain name
  12953.      * specified in the data field of the CNAME record.  The one exception to
  12954.      * this rule is that queries which match the CNAME type are not restarted.
  12955.      *
  12956.      * In other words, CNAMEs do not need to be expanded by the client.
  12957.      */
  12958.     while (numanswers--) {
  12959.  
  12960.         /* First is the name; use dn_expand() to get the compressed size. */
  12961.         len = dn_expand(answer.bytes,answer.bytes+size,p,query,sizeof(query));
  12962.         if (len < 0)
  12963.           goto dnsout;
  12964.         INCR_CHECK(p, len);
  12965.  
  12966.         CHECK(p,2);                     /* Query type */
  12967.         type = NTOHSP(p,2);
  12968.  
  12969.         CHECK(p, 6);                    /* Query class */
  12970.         class = NTOHSP(p,6);            /* Also skip over 4-byte TTL */
  12971.  
  12972.         CHECK(p,2);                     /* Record data length */
  12973.         rdlen = NTOHSP(p,2);
  12974.         /*
  12975.          * If this is an SRV record, process it.  Record format is:
  12976.          *
  12977.          * Priority
  12978.          * Weight
  12979.          * Port
  12980.          * Server name
  12981.          */
  12982.         if (class == C_IN && type == T_SRV) {
  12983.             CHECK(p,2);
  12984.             priority = NTOHSP(p,2);
  12985.             CHECK(p, 2);
  12986.             weight = NTOHSP(p,2);
  12987.             CHECK(p, 2);
  12988.             port = NTOHSP(p,2);
  12989.             len = dn_expand(answer.
  12990.                             bytes,
  12991.                             answer.bytes + size,
  12992.                             p,
  12993.                             query,
  12994.                             sizeof(query)
  12995.                             );
  12996.             if (len < 0)
  12997.               goto dnsout;
  12998.             INCR_CHECK(p, len);
  12999.             /*
  13000.              * We got everything.  Insert it into our list, but make sure
  13001.              * it's in the right order.  Right now we don't do anything
  13002.              * with the weight field
  13003.              */
  13004.             srv = (struct srv_dns_entry *)malloc(sizeof(struct srv_dns_entry));
  13005.             if (srv == NULL)
  13006.               goto dnsout;
  13007.  
  13008.             srv->priority = priority;
  13009.             srv->weight = weight;
  13010.             srv->port = port;
  13011.             makestr(&s,(char *)query);  /* strdup() is not portable */
  13012.             srv->host = s;
  13013.  
  13014.             if (head == NULL || head->priority > srv->priority) {
  13015.                 srv->next = head;
  13016.                 head = srv;
  13017.             } else
  13018.                 /*
  13019.                  * Confusing.  Insert an entry into this spot only if:
  13020.                  *  . The next person has a higher priority (lower
  13021.                  *    priorities are preferred), or:
  13022.                  *  . There is no next entry (we're at the end)
  13023.                  */
  13024.               for (entry = head; entry != NULL; entry = entry->next)
  13025.                 if ((entry->next &&
  13026.                      entry->next->priority > srv->priority) ||
  13027.                     entry->next == NULL) {
  13028.                     srv->next = entry->next;
  13029.                     entry->next = srv;
  13030.                     break;
  13031.                 }
  13032.         } else
  13033.           INCR_CHECK(p, rdlen);
  13034.     }
  13035.  
  13036.     /*
  13037.      * Now we've got a linked list of entries sorted by priority.
  13038.      * Start looking up A records and returning addresses.
  13039.      */
  13040.     if (head == NULL)
  13041.       goto dnsout;
  13042.  
  13043.     for (entry = head; entry != NULL; entry = entry->next) {
  13044.         hp = gethostbyname(entry->host);
  13045.         if (hp != 0) {
  13046.  
  13047.             /* Watch out - memset() and memcpy() are not portable... */
  13048.  
  13049.             switch (hp->h_addrtype) {
  13050.               case AF_INET:
  13051.                 for (j = 0; hp->h_addr_list[j]; j++) {
  13052.                     sin = (struct sockaddr_in *) &addr[nout++];
  13053.                     memset ((char *) sin, 0, sizeof (struct sockaddr));
  13054.                     sin->sin_family = hp->h_addrtype;
  13055.                     sin->sin_port = htons(entry->port);
  13056.                     memcpy((char *) &sin->sin_addr,
  13057.                            (char *) hp->h_addr_list[j],
  13058.                            sizeof(struct in_addr));             /* safe */
  13059.                     if (nout + 1 >= count) {
  13060.                         count += 5;
  13061.                         addr = (struct sockaddr *)
  13062.                           realloc((char *) addr,
  13063.                                   sizeof(struct sockaddr) * count);
  13064.                         if (!addr)
  13065.                           goto dnsout;
  13066.                     }
  13067.                 }
  13068.                 break;
  13069.               default:
  13070.                 break;
  13071.             }
  13072.         }
  13073.     }
  13074.     for (entry = head; entry != NULL;) {
  13075.         free(entry->host);
  13076.         entry->host = NULL;
  13077.         srv = entry;
  13078.         entry = entry->next;
  13079.         free(srv);
  13080.         srv = NULL;
  13081.     }
  13082.  
  13083.   dnsout:
  13084.     if (srv)
  13085.       free(srv);
  13086.  
  13087.     if (nout == 0) {                    /* No good servers */
  13088.         if (addr)
  13089.           free(addr);
  13090.         return 0;
  13091.     }
  13092.     *addr_pp = addr;
  13093.     *naddrs = nout;
  13094.     return 1;
  13095. }
  13096. #undef INCR_CHECK
  13097. #undef CHECK
  13098. #undef NTOHSP
  13099.  
  13100. #define INCR_CHECK(x, y) x += y; if (x > size + answer.bytes) \
  13101.                          return 0
  13102. #define CHECK(x, y) if (x + y > size + answer.bytes) \
  13103.                          return 0
  13104. #define NTOHSP(x, y) x[0] << 8 | x[1]; x += y
  13105.  
  13106. int
  13107. locate_txt_rr(prefix, name, retstr)
  13108.     char *prefix, *name;
  13109.     char **retstr;
  13110. {
  13111.     union {
  13112.         unsigned char bytes[2048];
  13113.         HEADER hdr;
  13114.     } answer;
  13115.     unsigned char *p;
  13116.     char host[MAX_DNS_NAMELEN], *h;
  13117.     int size;
  13118.     int type, class, numanswers, numqueries, rdlen, len;
  13119.  
  13120.     /*
  13121.      * Form our query, and send it via DNS
  13122.      */
  13123.  
  13124.     if (name == NULL || name[0] == '\0') {
  13125.         strcpy(host,prefix);
  13126.     } else {
  13127.         if ( strlen(prefix) + strlen(name) + 3 > MAX_DNS_NAMELEN )
  13128.             return 0;
  13129.  
  13130.         /* Realm names don't (normally) end with ".", but if the query
  13131.            doesn't end with "." and doesn't get an answer as is, the
  13132.            resolv code will try appending the local domain.  Since the
  13133.            realm names are absolutes, let's stop that.
  13134.  
  13135.            But only if a name has been specified.  If we are performing
  13136.            a search on the prefix alone then the intention is to allow
  13137.            the local domain or domain search lists to be expanded.
  13138.         */
  13139.         h = host + strlen (host);
  13140.         ckmakmsg(host,sizeof(host),prefix, ".", name,
  13141.                  ((h > host) && (h[-1] != '.'))?".":NULL);
  13142.  
  13143.     }
  13144.     size = res_search(host, C_IN, T_TXT, answer.bytes, sizeof(answer.bytes));
  13145.  
  13146.     if (size < 0)
  13147.         return 0;
  13148.  
  13149.     p = answer.bytes;
  13150.  
  13151.     numqueries = ntohs(answer.hdr.qdcount);
  13152.     numanswers = ntohs(answer.hdr.ancount);
  13153.  
  13154.     p += sizeof(HEADER);
  13155.  
  13156.     /*
  13157.      * We need to skip over the questions before we can get to the answers,
  13158.      * which means we have to iterate over every query record.  We use
  13159.      * dn_expand to tell us how long each compressed name is.
  13160.      */
  13161.  
  13162.     while (numqueries--) {
  13163.         len = dn_expand(answer.bytes, answer.bytes + size, p, host,
  13164.                          sizeof(host));
  13165.         if (len < 0)
  13166.             return 0;
  13167.         INCR_CHECK(p, len + 4);         /* Name plus type plus class */
  13168.     }
  13169.  
  13170.     /*
  13171.      * We're now pointing at the answer records.  Process the first
  13172.      * TXT record we find.
  13173.      */
  13174.  
  13175.     while (numanswers--) {
  13176.  
  13177.         /* First the name; use dn_expand to get the compressed size */
  13178.         len = dn_expand(answer.bytes, answer.bytes + size, p,
  13179.                         host, sizeof(host));
  13180.         if (len < 0)
  13181.             return 0;
  13182.         INCR_CHECK(p, len);
  13183.  
  13184.         /* Next is the query type */
  13185.         CHECK(p, 2);
  13186.         type = NTOHSP(p,2);
  13187.  
  13188.         /* Next is the query class; also skip over 4 byte TTL */
  13189.         CHECK(p,6);
  13190.         class = NTOHSP(p,6);
  13191.  
  13192.         /* Record data length - make sure we aren't truncated */
  13193.  
  13194.         CHECK(p,2);
  13195.         rdlen = NTOHSP(p,2);
  13196.  
  13197.         if (p + rdlen > answer.bytes + size)
  13198.             return 0;
  13199.  
  13200.         /*
  13201.          * If this is a TXT record, return the string.  Note that the
  13202.          * string has a 1-byte length in the front
  13203.          */
  13204.         /* XXX What about flagging multiple TXT records as an error?  */
  13205.  
  13206.         if (class == C_IN && type == T_TXT) {
  13207.             len = *p++;
  13208.             if (p + len > answer.bytes + size)
  13209.                 return 0;
  13210.             *retstr = malloc(len + 1);
  13211.             if (*retstr == NULL)
  13212.                 return ENOMEM;
  13213.             strncpy(*retstr, (char *) p, len);
  13214.             (*retstr)[len] = '\0';
  13215.             /* Avoid a common error. */
  13216.             if ( (*retstr)[len-1] == '.' )
  13217.                 (*retstr)[len-1] = '\0';
  13218.             return 1;
  13219.         }
  13220.     }
  13221.  
  13222.     return 0;
  13223. }
  13224. #undef INCR_CHECK
  13225. #undef CHECK
  13226. #undef NTOHSP
  13227. #endif /* CK_DNS_SRV */
  13228.  
  13229. #ifdef TNCODE
  13230. #ifdef CK_FORWARD_X
  13231. #ifdef UNIX
  13232. #include <sys/un.h>
  13233. #define FWDX_UNIX_SOCK
  13234. #ifndef AF_LOCAL
  13235. #define AF_LOCAL AF_UNIX
  13236. #endif
  13237. #ifndef PF_LOCAL
  13238. #define PF_LOCAL PF_UNIX
  13239. #endif
  13240. #ifndef SUN_LEN
  13241. /* Evaluate to actual length of the `sockaddr_un' structure.  */
  13242. #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path)         \
  13243.                       + strlen ((ptr)->sun_path))
  13244. #endif
  13245. #endif /* UNIX */
  13246. int
  13247. fwdx_create_listen_socket(screen) int screen; {
  13248. #ifdef NOPUTENV
  13249.     return(-1);
  13250. #else /* NOPUTENV */
  13251.     struct sockaddr_in saddr;
  13252.     int display, port, sock=-1, i;
  13253.     static char env[512];
  13254.  
  13255.     /*
  13256.      * X Windows Servers support multiple displays by listening on
  13257.      * one socket per display.  Display 0 is port 6000; Display 1 is
  13258.      * port 6001; etc.
  13259.      *
  13260.      * We start by trying to open port 6001 so that display 0 is
  13261.      * reserved for the local X Windows Server.
  13262.      */
  13263.  
  13264.     for ( display=1; display < 1000 ; display++  ) {
  13265.  
  13266.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13267.             debug(F111,"fwdx_create_listen_socket()","socket() < 0",sock);
  13268.             return(-1);
  13269.         }
  13270.  
  13271.         port = 6000 + display;
  13272.         bzero((char *)&saddr, sizeof(saddr));
  13273.         saddr.sin_family = AF_INET;
  13274.         saddr.sin_addr.s_addr = inet_addr(myipaddr);
  13275.         saddr.sin_port = htons(port);
  13276.  
  13277.         if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13278.             i = errno;                  /* Save error code */
  13279. #ifdef TCPIPLIB
  13280.             socket_close(sock);
  13281. #else /* TCPIPLIB */
  13282.             close(sock);
  13283. #endif /* TCPIPLIB */
  13284.             sock = -1;
  13285.             debug(F110,"fwdx_create_listen_socket()","bind() < 0",0);
  13286.             continue;
  13287.         }
  13288.  
  13289.         debug(F100,"fdwx_create_listen_socket() bind OK","",0);
  13290.         break;
  13291.     }
  13292.  
  13293.     if ( display > 1000 ) {
  13294.         debug(F100,"fwdx_create_listen_socket() Out of Displays","",0);
  13295.         return(-1);
  13296.     }
  13297.  
  13298.     if (listen(sock, 5) < 0) {
  13299.         i = errno;                  /* Save error code */
  13300. #ifdef TCPIPLIB
  13301.         socket_close(sock);
  13302. #else /* TCPIPLIB */
  13303.         close(sock);
  13304. #endif /* TCPIPLIB */
  13305.         debug(F101,"fdwx_create_listen_socket() listen() errno","",errno);
  13306.         return(-1);
  13307.     }
  13308.     debug(F100,"fwdx_create_listen_socket() listen OK","",0);
  13309.  
  13310.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = sock;
  13311.     if (!myipaddr[0])
  13312.         getlocalipaddr();
  13313.     if ( myipaddr[0] )
  13314.         ckmakxmsg(env,sizeof(env),"DISPLAY=",myipaddr,":",
  13315.                   ckuitoa(display),":",ckuitoa(screen),
  13316.                   NULL,NULL,NULL,NULL,NULL,NULL);
  13317.     else
  13318.         ckmakmsg(env,sizeof(env),"DISPLAY=",ckuitoa(display),":",
  13319.                  ckuitoa(screen));
  13320.     putenv(env);
  13321.     return(0);
  13322. #endif /* NOPUTENV */
  13323. }
  13324.  
  13325.  
  13326. int
  13327. fwdx_open_client_channel(channel) int channel; {
  13328.     char * env;
  13329.     struct sockaddr_in saddr;
  13330. #ifdef FWDX_UNIX_SOCK
  13331.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13332. #endif /* FWDX_UNIX_SOCK */
  13333.     int colon, dot, display, port, sock, i, screen;
  13334.     int family;
  13335.     char buf[256], * host=NULL, * rest=NULL;
  13336. #ifdef TCP_NODELAY
  13337.     int on=1;
  13338. #endif /* TCP_NODELAY */
  13339.  
  13340.     debug(F111,"fwdx_create_client_channel()","channel",channel);
  13341.  
  13342.     for ( i=0; i<MAXFWDX ; i++ ) {
  13343.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel) {
  13344.             /* Already open */
  13345.             debug(F110,"fwdx_create_client_channel()","already open",0);
  13346.             return(0);
  13347.         }
  13348.     }
  13349.  
  13350.     env = getenv("DISPLAY");
  13351.     if ( !env )
  13352.         env = tn_get_display();
  13353.     if ( env )
  13354.         ckstrncpy(buf,env,256);
  13355.     else
  13356.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13357.  
  13358.     bzero((char *)&saddr,sizeof(saddr));
  13359.     saddr.sin_family = AF_INET;
  13360.  
  13361.     if (!fwdx_parse_displayname(buf,
  13362.                                 &family,
  13363.                                 &host,
  13364.                                 &display,
  13365.                                 &screen,
  13366.                                 &rest
  13367.                                 )
  13368.         ) {
  13369.         if ( host ) free(host);
  13370.         if ( rest ) free(rest);
  13371.         return(0);
  13372.     }
  13373.     if (rest) free(rest);
  13374.  
  13375. #ifndef FWDX_UNIX_SOCK
  13376.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13377.    * we change things to use inet sockets on the ip loopback interface instead,
  13378.    * and hope that it works.
  13379.    */
  13380.     if (family == FamilyLocal) {
  13381.         debug(F100,"fwdx_create_client_channel() FamilyLocal","",0);
  13382.         family = FamilyInternet;
  13383.         if (host) free(host);
  13384.         if (host = malloc(strlen("localhost") + 1))
  13385.             strcpy(host, "localhost");
  13386.         else {
  13387.             return(-1);
  13388.         }
  13389.     }
  13390. #else /* FWDX_UNIX_SOCK */
  13391.     if (family == FamilyLocal) {
  13392.         if (host) free(host);
  13393.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13394.         if (sock < 0)
  13395.             return(-1);
  13396.  
  13397.         ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13398.         strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13399.         if (connect(sock,(struct sockaddr *)&saddr_un, SUN_LEN(&saddr_un)) < 0)
  13400.           return(-1);
  13401.     } else
  13402. #endif  /* FWDX_UNIX_SOCK */
  13403.     {
  13404.         /* Otherwise, we are assuming FamilyInternet */
  13405.         if (host) {
  13406.             ckstrncpy(buf,host,sizeof(buf));
  13407.             free(host);
  13408.         } else
  13409.             ckstrncpy(buf,myipaddr,sizeof(buf));
  13410.  
  13411.         debug(F111,"fwdx_create_client_channel()","display",display);
  13412.  
  13413.         port = 6000 + display;
  13414.         saddr.sin_port = htons(port);
  13415.  
  13416.         debug(F110,"fwdx_create_client_channel() ip-address",buf,0);
  13417.         saddr.sin_addr.s_addr = inet_addr(buf);
  13418.         if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13419. #ifdef INADDR_NONE
  13420.              || saddr.sin_addr.s_addr == INADDR_NONE
  13421. #endif /* INADDR_NONE */
  13422.              )
  13423.         {
  13424.             struct hostent *host;
  13425.             host = gethostbyname(buf);
  13426.             if ( host == NULL )
  13427.                 return(-1);
  13428.             host = ck_copyhostent(host);
  13429. #ifdef HADDRLIST
  13430. #ifdef h_addr
  13431.             /* This is for trying multiple IP addresses - see <netdb.h> */
  13432.             if (!(host->h_addr_list))
  13433.                 return(-1);
  13434.             bcopy(host->h_addr_list[0],
  13435.                    (caddr_t)&saddr.sin_addr,
  13436.                    host->h_length
  13437.                    );
  13438. #else
  13439.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13440. #endif /* h_addr */
  13441. #else  /* HADDRLIST */
  13442.             bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13443. #endif /* HADDRLIST */
  13444.         }
  13445.  
  13446.         if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13447.             debug(F111,"fwdx_create_client_channel()","socket() < 0",sock);
  13448.             return(-1);
  13449.         }
  13450.  
  13451.         if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13452.             debug(F110,"fwdx_create_client_channel()","connect() failed",0);
  13453. #ifdef TCPIPLIB
  13454.             socket_close(sock);
  13455. #else /* TCPIPLIB */
  13456.             close(sock);
  13457. #endif /* TCPIPLIB */
  13458.             return(-1);
  13459.         }
  13460.  
  13461. #ifdef TCP_NODELAY
  13462.         setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13463. #endif /* TCP_NODELAY */
  13464.     }
  13465.  
  13466.     for (i = 0; i < MAXFWDX; i++) {
  13467.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == -1) {
  13468.          TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = sock;
  13469.          TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = channel;
  13470.        TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 1;
  13471.          debug(F111,"fwdx_create_client_channel()","socket",sock);
  13472.          return(0);
  13473.      }
  13474.     }
  13475.     return(-1);
  13476. }
  13477.  
  13478. int
  13479. fwdx_server_avail() {
  13480.     char * env;
  13481.     struct sockaddr_in saddr;
  13482. #ifdef FWDX_UNIX_SOCK
  13483.     struct sockaddr_un saddr_un = { AF_LOCAL };
  13484. #endif  /* FWDX_UNIX_SOCK */
  13485.     int colon, dot, display, port, sock, i, screen;
  13486.     char buf[256], *host=NULL, *rest=NULL;
  13487. #ifdef TCP_NODELAY
  13488.     int on=1;
  13489. #endif /* TCP_NODELAY */
  13490.     int family;
  13491.  
  13492.     env = getenv("DISPLAY");
  13493.     if ( !env )
  13494.         env = tn_get_display();
  13495.     if ( env )
  13496.         ckstrncpy(buf,env,256);
  13497.     else
  13498.         ckstrncpy(buf,"127.0.0.1:0.0",256);
  13499.  
  13500.     bzero((char *)&saddr,sizeof(saddr));
  13501.     saddr.sin_family = AF_INET;
  13502.  
  13503.     if (!fwdx_parse_displayname(buf,&family,&host,&display,&screen,&rest)) {
  13504.         if ( host ) free(host);
  13505.         if ( rest ) free(rest);
  13506.         return(0);
  13507.     }
  13508.     if (rest) free(rest);
  13509.  
  13510. #ifndef FWDX_UNIX_SOCK
  13511.   /* if $DISPLAY indicates use of unix domain sockets, but we don't support it,
  13512.    * we change things to use inet sockets on the ip loopback interface instead,
  13513.    * and hope that it works.
  13514.    */
  13515.     if (family == FamilyLocal) {
  13516.         family = FamilyInternet;
  13517.         if (host) free(host);
  13518.         if (host = malloc(strlen("localhost") + 1))
  13519.             strcpy(host, "localhost");
  13520.         else {
  13521.             return(-1);
  13522.         }
  13523.     }
  13524. #else /* FWDX_UNIX_SOCK */
  13525.     if (family == FamilyLocal) {
  13526.         debug(F100,"fwdx_server_avail() FamilyLocal","",0);
  13527.         if (host) free(host);
  13528.         sock = socket(PF_LOCAL, SOCK_STREAM, 0);
  13529.         if (sock < 0)
  13530.             return(0);
  13531.  
  13532.         ckmakmsg(buf,sizeof(buf),"/tmp/.X11-unix/X",ckitoa(display),NULL,NULL);
  13533.         strncpy(saddr_un.sun_path, buf, sizeof(saddr_un.sun_path));
  13534.         if (connect(sock,(struct sockaddr *)&saddr_un,SUN_LEN(&saddr_un)) < 0)
  13535.             return(0);
  13536.         close(sock);
  13537.         return(1);
  13538.     }
  13539. #endif  /* FWDX_UNIX_SOCK */
  13540.  
  13541.     /* Otherwise, we are assuming FamilyInternet */
  13542.     if (host) {
  13543.         ckstrncpy(buf,host,sizeof(buf));
  13544.         free(host);
  13545.     } else
  13546.         ckstrncpy(buf,myipaddr,sizeof(buf));
  13547.  
  13548.     debug(F111,"fwdx_server_avail()","display",display);
  13549.  
  13550.     port = 6000 + display;
  13551.     saddr.sin_port = htons(port);
  13552.  
  13553.     debug(F110,"fwdx_server_avail() ip-address",buf,0);
  13554.     saddr.sin_addr.s_addr = inet_addr(buf);
  13555.     if ( saddr.sin_addr.s_addr == (unsigned long) -1
  13556. #ifdef INADDR_NONE
  13557.          || saddr.sin_addr.s_addr == INADDR_NONE
  13558. #endif /* INADDR_NONE */
  13559.          )
  13560.     {
  13561.         struct hostent *host;
  13562.         host = gethostbyname(buf);
  13563.         if ( host == NULL ) {
  13564.             debug(F110,"fwdx_server_avail() gethostbyname() failed",
  13565.                    myipaddr,0);
  13566.             return(-1);
  13567.         }
  13568.         host = ck_copyhostent(host);
  13569. #ifdef HADDRLIST
  13570. #ifdef h_addr
  13571.         /* This is for trying multiple IP addresses - see <netdb.h> */
  13572.         if (!(host->h_addr_list))
  13573.             return(-1);
  13574.         bcopy(host->h_addr_list[0],
  13575.                (caddr_t)&saddr.sin_addr,
  13576.                host->h_length
  13577.                );
  13578. #else
  13579.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13580. #endif /* h_addr */
  13581. #else  /* HADDRLIST */
  13582.         bcopy(host->h_addr, (caddr_t)&saddr.sin_addr, host->h_length);
  13583. #endif /* HADDRLIST */
  13584.     }
  13585.  
  13586.     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  13587.         debug(F111,"fwdx_server_avail()","socket() < 0",sock);
  13588.         return(0);
  13589.     }
  13590.  
  13591.     if ( connect(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) {
  13592.         debug(F110,"fwdx_server_avail()","connect() failed",0);
  13593. #ifdef TCPIPLIB
  13594.         socket_close(sock);
  13595. #else /* TCPIPLIB */
  13596.         close(sock);
  13597. #endif /* TCPIPLIB */
  13598.         return(0);
  13599.     }
  13600.  
  13601. #ifdef TCPIPLIB
  13602.     socket_close(sock);
  13603. #else /* TCPIPLIB */
  13604.     close(sock);
  13605. #endif /* TCPIPLIB */
  13606.     return(1);
  13607. }
  13608.  
  13609. int
  13610. fwdx_open_server_channel() {
  13611.     int sock, ready_to_accept, sock2,channel,i;
  13612. #ifdef TCP_NODELAY
  13613.     int on=1;
  13614. #endif /* TCP_NODELAY */
  13615. #ifdef UCX50
  13616.     static u_int saddrlen;
  13617. #else
  13618.     static SOCKOPT_T saddrlen;
  13619. #endif /* UCX50 */
  13620.     struct sockaddr_in saddr;
  13621.     char sb[8];
  13622.     extern char tn_msg[];
  13623. #ifdef BSDSELECT
  13624.     fd_set rfds;
  13625.     struct timeval tv;
  13626. #else
  13627. #ifdef BELLSELCT
  13628.     fd_set rfds;
  13629. #else
  13630.     fd_set rfds;
  13631.     struct timeval {
  13632.         long tv_sec;
  13633.         long tv_usec;
  13634.     } tv;
  13635. #endif /* BELLSELECT */
  13636. #endif /* BSDSELECT */
  13637.     unsigned short nchannel;
  13638.     unsigned char * p;
  13639.  
  13640.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket;
  13641.  
  13642.   try_again:
  13643.  
  13644. #ifdef BSDSELECT
  13645.     tv.tv_sec  = tv.tv_usec = 0L;
  13646.     tv.tv_usec = 50;
  13647.     FD_ZERO(&rfds);
  13648.     FD_SET(sock, &rfds);
  13649.     ready_to_accept =
  13650.         ((select(FD_SETSIZE,
  13651. #ifdef HPUX
  13652. #ifdef HPUX1010
  13653.                   (fd_set *)
  13654. #else
  13655.  
  13656.                   (int *)
  13657. #endif /* HPUX1010 */
  13658. #else
  13659. #ifdef __DECC
  13660.                   (fd_set *)
  13661. #endif /* __DECC */
  13662. #endif /* HPUX */
  13663.                   &rfds, NULL, NULL, &tv) > 0) &&
  13664.           FD_ISSET(sock, &rfds));
  13665. #else /* BSDSELECT */
  13666. #ifdef IBMSELECT
  13667.     ready_to_accept = (select(&sock, 1, 0, 0, 50) == 1);
  13668. #else
  13669. #ifdef BELLSELECT
  13670.     FD_ZERO(rfds);
  13671.     FD_SET(sock, rfds);
  13672.     ready_to_accept =
  13673.         ((select(128, rfds, NULL, NULL, 50) > 0) &&
  13674.           FD_ISSET(sock, rfds));
  13675. #else
  13676. /* Try this - what's the worst that can happen... */
  13677.  
  13678.     tv.tv_sec  = tv.tv_usec = 0L;
  13679.     tv.tv_usec = 50;
  13680.     FD_ZERO(&rfds);
  13681.     FD_SET(sock, &rfds);
  13682.     ready_to_accept =
  13683.         ((select(FD_SETSIZE,
  13684.                   (fd_set *) &rfds, NULL, NULL, &tv) > 0) &&
  13685.           FD_ISSET(sock, &rfds));
  13686. #endif /* BELLSELECT */
  13687. #endif /* IBMSELECT */
  13688. #endif /* BSDSELECT */
  13689.  
  13690.     if ( !ready_to_accept )
  13691.         return(0);
  13692.  
  13693.     if ((sock2 = accept(sock,(struct sockaddr *)&saddr,&saddrlen)) < 0) {
  13694.         int i = errno;                  /* save error code */
  13695.         debug(F101,"tcpsrv_open accept errno","",i);
  13696.         return(-1);
  13697.     }
  13698.  
  13699.     /*
  13700.      * Now we have the open socket.  We must now find a channel to store
  13701.      * it in, and then notify the client.
  13702.      */
  13703.  
  13704.     for ( channel=0;channel<MAXFWDX;channel++ ) {
  13705.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd == -1 )
  13706.             break;
  13707.     }
  13708.  
  13709.     if ( channel == MAXFWDX ) {
  13710. #ifdef TCPIPLIB
  13711.         socket_close(sock2);
  13712. #else /* TCPIPLIB */
  13713.         close(sock2);
  13714. #endif /* TCPIPLIB */
  13715.         return(-1);
  13716.     }
  13717.  
  13718.     if ( fwdx_send_open(channel) < 0 ) {
  13719. #ifdef TCPIPLIB
  13720.         socket_close(sock2);
  13721. #else /* TCPIPLIB */
  13722.         close(sock2);
  13723. #endif /* TCPIPLIB */
  13724.     }
  13725.  
  13726. #ifdef TCP_NODELAY
  13727.     setsockopt(sock2,IPPROTO_TCP,TCP_NODELAY,(char *)&on,sizeof(on));
  13728. #endif /* TCP_NODELAY */
  13729.  
  13730.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].fd = sock2;
  13731.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[channel].id = channel;
  13732.     goto try_again;
  13733.  
  13734.     return(0);  /* never reached */
  13735. }
  13736.  
  13737. int
  13738. fwdx_close_channel(channel) int channel; {
  13739.     int i,fd;
  13740.  
  13741.     for ( i=0; i<MAXFWDX ; i++ ) {
  13742.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13743.             break;
  13744.     }
  13745.     if ( i == MAXFWDX )
  13746.         return(-1);
  13747.  
  13748.     fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13749.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd = -1;
  13750.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id = -1;
  13751.     TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].need_to_send_xauth = 0;
  13752.  
  13753. #ifdef TCPIPLIB
  13754.     socket_close(fd);
  13755. #else /* TCPIPLIB */
  13756.     close(fd);
  13757. #endif /* TCPIPLIB */
  13758.     return(0);
  13759. }
  13760.  
  13761. int
  13762. fwdx_close_all() {
  13763.     int x,fd;
  13764.  
  13765.     debug(F111,"fwdx_close_all()",
  13766.           "TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket",
  13767.           TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13768.  
  13769.     if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1 ) {
  13770. #ifdef TCPIPLIB
  13771.         socket_close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13772. #else /* TCPIPLIB */
  13773.         close(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket);
  13774. #endif /* TCPIPLIB */
  13775.         TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket = -1;
  13776.     }
  13777.  
  13778.     for (x = 0; x < MAXFWDX; x++) {
  13779.      if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  13780.       fd = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13781.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd = -1;
  13782.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id = -1;
  13783.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].need_to_send_xauth = 0;
  13784.       TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend = 0;
  13785. #ifdef TCPIPLIB
  13786.       socket_close(fd);
  13787. #else /* TCPIPLIB */
  13788.       close(fd);
  13789. #endif /* TCPIPLIB */
  13790.      }
  13791.     }
  13792.     return(0);
  13793. }
  13794.  
  13795. /* The following definitions are for Unix */
  13796. #ifndef socket_write
  13797. #define socket_write(f,s,n)    write(f,s,n)
  13798. #endif /* socket_write */
  13799. #ifndef socket_read
  13800. #define socket_read(f,s,n)     read(f,s,n)
  13801. #endif /* socket_read */
  13802.  
  13803. int
  13804. fwdx_write_data_to_channel(channel, data, len)
  13805.     int channel; char * data; int len;
  13806. {
  13807.     int sock, count, try=0, length = len, i;
  13808.  
  13809.     if ( len <= 0 )
  13810.         return(0);
  13811.  
  13812.     for ( i=0; i<MAXFWDX ; i++ ) {
  13813.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].id == channel)
  13814.             break;
  13815.     }
  13816.     if ( i == MAXFWDX ) {
  13817.         debug(F110,"fwdx_write_data_to_channel",
  13818.                "attempting to write to closed channel",0);
  13819.         return(-1);
  13820.     }
  13821.  
  13822.     sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[i].fd;
  13823.     debug(F111,"fwdx_write_data_to_channel","socket",sock);
  13824.     hexdump("fwdx_write_data_to_channel",data,len);
  13825.  
  13826.   fwdx_write_data_to_channel_retry:
  13827.  
  13828.     if ((count = socket_write(sock,data,len)) < 0) {
  13829.         int s_errno = socket_errno; /* maybe a function */
  13830.         debug(F101,"fwdx_write_data_to_channel socket_write error","",s_errno);
  13831. #ifdef BETATEST
  13832.         printf("fwdx_write_data_to_channel error\r\n");
  13833. #endif /* BETATEST */
  13834. #ifdef OS2
  13835.         if (os2socketerror(s_errno) < 0)
  13836.             return(-2);
  13837. #endif /* OS2 */
  13838.         return(-1);                 /* Call it an i/o error */
  13839.     }
  13840.     if (count < len) {
  13841.         debug(F111,"fwdx_write_data_to_channel socket_write",data,count);
  13842.         if (count > 0) {
  13843.             data += count;
  13844.             len -= count;
  13845.         }
  13846.         debug(F111,"fwdx_write_data_to_channel retry",data,len);
  13847.         if ( len > 0 )
  13848.             goto fwdx_write_data_to_channel_retry;
  13849.     }
  13850.  
  13851.     debug(F111,"fwdx_write_data_to_channel complete",data,length);
  13852.     return(length); /* success - return total length */
  13853. }
  13854.  
  13855. VOID
  13856. fwdx_check_sockets(fd_set *ibits)
  13857. {
  13858.     int x, sock, channel, bytes;
  13859.     static char buffer[32000];
  13860.  
  13861.     debug(F100,"fwdx_check_sockets()","",0);
  13862.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  13863.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  13864.         debug(F110,"fwdx_check_sockets()","TELOPT_FORWARD_X not negotiated",0);
  13865.         return;
  13866.     }
  13867.  
  13868.     for (x = 0; x < MAXFWDX; x++) {
  13869.         if ( TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd == -1 ||
  13870.              TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend )
  13871.             continue;
  13872.  
  13873.         sock = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd;
  13874.         if (FD_ISSET(sock, ibits))
  13875.         {
  13876.             channel = TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].id;
  13877.             debug(F111,"fwdx_check_sockets()","channel set",channel);
  13878.  
  13879.             bytes = socket_read(sock, buffer, sizeof(buffer));
  13880.             if (bytes > 0)
  13881.                 fwdx_send_data_from_channel(channel, buffer, bytes);
  13882.             else if (bytes == 0) {
  13883.                 fwdx_close_channel(channel);
  13884.                 fwdx_send_close(channel);
  13885.             }
  13886.         }
  13887.     }
  13888. }
  13889.  
  13890. int
  13891. fwdx_init_fd_set(fd_set *ibits)
  13892. {
  13893.     int x,set=0,cnt=0;
  13894.  
  13895.     if ( sstelnet && !TELOPT_ME(TELOPT_FORWARD_X) ||
  13896.          !sstelnet && !TELOPT_U(TELOPT_FORWARD_X)) {
  13897.         debug(F110,"fwdx_init_fd_set()","TELOPT_FORWARD_X not negotiated",0);
  13898.         return(0);
  13899.     }
  13900.  
  13901.     if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket != -1) {
  13902.         set++;
  13903.         FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.listen_socket, ibits);
  13904.     }
  13905.     for (x = 0; x < MAXFWDX; x++) {
  13906.         if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd != -1) {
  13907.             cnt++;
  13908.             if (TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].suspend)
  13909.                 continue;
  13910.             set++;
  13911.             FD_SET(TELOPT_SB(TELOPT_FORWARD_X).forward_x.channel[x].fd, ibits);
  13912.         }
  13913.     }
  13914.     if (set + cnt == 0) {
  13915.         return(-1);
  13916.     } else {
  13917.         return(set);
  13918.     }
  13919. }
  13920.  
  13921. #ifdef NT
  13922. VOID
  13923. fwdx_thread( VOID * dummy )
  13924. {
  13925.     fd_set ifds;
  13926.     struct timeval tv;
  13927.     extern int priority;
  13928.     int n;
  13929.  
  13930.     setint();
  13931.     SetThreadPrty(priority,isWin95() ? 3 : 11);
  13932.  
  13933.     while ( !sstelnet && TELOPT_U(TELOPT_FORWARD_X) ||
  13934.             sstelnet && TELOPT_ME(TELOPT_FORWARD_X))
  13935.     {
  13936.         FD_ZERO(&ifds);
  13937.         n = fwdx_init_fd_set(&ifds);
  13938.         if (n > 0) {
  13939.             tv.tv_sec = 0;
  13940.             tv.tv_usec = 2500;
  13941.             if ( select(FD_SETSIZE, &ifds, NULL, NULL, &tv) > 0 )
  13942.                 fwdx_check_sockets(&ifds);
  13943.  
  13944.         } else if (n < 0) {
  13945.             TELOPT_SB(TELOPT_FORWARD_X).forward_x.thread_started = 0;
  13946.             ckThreadEnd(NULL);
  13947.         } else {
  13948.             sleep(1);
  13949.         }
  13950.     }
  13951. }
  13952. #endif /* NT */
  13953. #endif /* CK_FORWARD_X */
  13954. #endif /* TNCODE */
  13955. #endif /* NETCONN */
  13956.