Check for socklen_t type for accept, getpeername
[yaz-moved-to-github.git] / comstack / tcpip.c
1 /*
2  * Copyright (c) 1995-2002, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: tcpip.c,v 1.48 2002-09-10 20:56:34 adam Exp $
6  */
7
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdlib.h>
11 #ifndef WIN32
12 #include <unistd.h>
13 #endif
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #if HAVE_OPENSSL_SSL_H
18 #include <openssl/ssl.h>
19 #include <openssl/err.h>
20 #endif
21
22 #include <yaz/comstack.h>
23 #include <yaz/tcpip.h>
24 #include <yaz/log.h>
25
26 /* Chas added the following, so we get the definition of completeBER */
27 #include <yaz/odr.h>
28
29 int tcpip_close(COMSTACK h);
30 int tcpip_put(COMSTACK h, char *buf, int size);
31 int tcpip_get(COMSTACK h, char **buf, int *bufsize);
32 int tcpip_connect(COMSTACK h, void *address);
33 int tcpip_more(COMSTACK h);
34 int tcpip_rcvconnect(COMSTACK h);
35 int tcpip_bind(COMSTACK h, void *address, int mode);
36 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
37                  int (*check_ip)(void *cd, const char *a, int len, int type),
38                  void *cd);
39 int static tcpip_set_blocking(COMSTACK p, int blocking);
40
41 #if HAVE_OPENSSL_SSL_H
42 int ssl_get(COMSTACK h, char **buf, int *bufsize);
43 int ssl_put(COMSTACK h, char *buf, int size);
44 #endif
45
46 COMSTACK tcpip_accept(COMSTACK h);
47 char *tcpip_addrstr(COMSTACK h);
48 void *tcpip_straddr(COMSTACK h, const char *str);
49
50 #if 0
51 #define TRC(x) x
52 #else
53 #define TRC(X)
54 #endif
55
56 #if HAVE_SOCKLEN_T
57 #define NET_LEN_T socklen_t
58 #else
59 #if GETPEERNAME_ACCEPTS_SIZE_T_FOR_THIRD_ARGUMENT
60 #define NET_LEN_T size_t
61 #else
62 #define NET_LEN_T int
63 #endif
64 #endif
65
66 /* this state is used for both SSL and straight TCP/IP */
67 typedef struct tcpip_state
68 {
69     char *altbuf; /* alternate buffer for surplus data */
70     int altsize;  /* size as xmalloced */
71     int altlen;   /* length of data or 0 if none */
72
73     int written;  /* -1 if we aren't writing */
74     int towrite;  /* to verify against user input */
75     int (*complete)(const unsigned char *buf, int len); /* length/comple. */
76     struct sockaddr_in addr;  /* returned by cs_straddr */
77     char buf[128]; /* returned by cs_addrstr */
78 #if HAVE_OPENSSL_SSL_H
79     SSL_CTX *ctx;
80     SSL_CTX *ctx_alloc;
81     SSL *ssl;
82 #endif
83 } tcpip_state;
84
85 #ifdef WIN32
86 static int tcpip_init (void)
87 {
88     static int initialized = 0;
89     if (!initialized)
90     {
91         WORD requested;
92         WSADATA wd;
93
94         requested = MAKEWORD(1, 1);
95         if (WSAStartup(requested, &wd))
96             return 0;
97         initialized = 1;
98     }
99     return 1;
100 }
101 #else
102 static int tcpip_init (void)
103 {
104     return 1;
105 }
106 #endif
107
108 /*
109  * This function is always called through the cs_create() macro.
110  * s >= 0: socket has already been established for us.
111  */
112 COMSTACK tcpip_type(int s, int blocking, int protocol, void *vp)
113 {
114     COMSTACK p;
115     tcpip_state *state;
116     int new_socket;
117 #ifdef WIN32
118     unsigned long tru = 1;
119 #endif
120
121     if (!tcpip_init ())
122         return 0;
123     if (s < 0)
124     {
125         if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
126             return 0;
127         new_socket = 1;
128     }
129     else
130         new_socket = 0;
131     if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
132         return 0;
133     if (!(state = (struct tcpip_state *)(p->cprivate =
134                                          xmalloc(sizeof(tcpip_state)))))
135         return 0;
136
137 #ifdef WIN32
138     if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
139         return 0;
140 #else
141     if (!(p->blocking = blocking))
142     {   
143         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
144             return 0;
145 #ifndef MSG_NOSIGNAL
146         signal (SIGPIPE, SIG_IGN);
147 #endif
148     }
149 #endif
150
151     p->io_pending = 0;
152     p->iofile = s;
153     p->type = tcpip_type;
154     p->protocol = (enum oid_proto) protocol;
155
156     p->f_connect = tcpip_connect;
157     p->f_rcvconnect = tcpip_rcvconnect;
158     p->f_get = tcpip_get;
159     p->f_put = tcpip_put;
160     p->f_close = tcpip_close;
161     p->f_more = tcpip_more;
162     p->f_bind = tcpip_bind;
163     p->f_listen = tcpip_listen;
164     p->f_accept = tcpip_accept;
165     p->f_addrstr = tcpip_addrstr;
166     p->f_straddr = tcpip_straddr;
167     p->f_set_blocking = tcpip_set_blocking;
168
169     p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
170     p->event = CS_NONE;
171     p->cerrno = 0;
172     p->stackerr = 0;
173
174 #if HAVE_OPENSSL_SSL_H
175     state->ctx = state->ctx_alloc = 0;
176     state->ssl = 0;
177 #endif
178
179     state->altbuf = 0;
180     state->altsize = state->altlen = 0;
181     state->towrite = state->written = -1;
182     if (protocol == PROTO_WAIS)
183         state->complete = completeWAIS;
184     else
185         state->complete = completeBER;
186
187     p->timeout = COMSTACK_DEFAULT_TIMEOUT;
188     TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
189
190     return p;
191 }
192
193 #if HAVE_OPENSSL_SSL_H
194
195 COMSTACK ssl_type(int s, int blocking, int protocol, void *vp)
196 {
197     tcpip_state *state;
198     COMSTACK p;
199     yaz_log(LOG_LOG, "ssl_type begin");
200
201     p = tcpip_type (s, blocking, protocol, 0);
202     if (!p)
203         return 0;
204     p->f_get = ssl_get;
205     p->f_put = ssl_put;
206     p->type = ssl_type;
207     state = (tcpip_state *) p->cprivate;
208     if (vp)
209         state->ctx = vp;
210     else
211     {
212         SSL_load_error_strings();
213         SSLeay_add_all_algorithms();
214
215         state->ctx = state->ctx_alloc = SSL_CTX_new (SSLv23_method());
216         if (!state->ctx)
217         {
218             tcpip_close(p);
219             return 0;
220         }
221     }
222     /* note: we don't handle already opened socket in SSL mode - yet */
223     yaz_log(LOG_LOG, "ssl_type end");
224     return p;
225 }
226 #endif
227
228 int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
229 {
230     struct hostent *hp;
231     char *p, buf[512];
232     short int port = 210;
233     unsigned tmpadd;
234
235     if (!tcpip_init ())
236         return 0;
237     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
238     add->sin_family = AF_INET;
239     strncpy(buf, str, 511);
240     buf[511] = 0;
241     if ((p = strchr(buf, '/')))
242         *p = 0;
243     if ((p = strchr(buf, ':')))
244     {
245         *p = 0;
246         port = atoi(p + 1);
247     }
248     add->sin_port = htons(port);
249     if (!strcmp("@", buf))
250         add->sin_addr.s_addr = INADDR_ANY;
251     else if ((hp = gethostbyname(buf)))
252         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
253                sizeof(struct in_addr));
254     else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
255         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
256     else
257         return 0;
258     return 1;
259 }
260
261 void *tcpip_straddr(COMSTACK h, const char *str)
262 {
263     tcpip_state *sp = (tcpip_state *)h->cprivate;
264
265     if (!tcpip_strtoaddr_ex (str, &sp->addr))
266         return 0;
267     return &sp->addr;
268 }
269
270 struct sockaddr_in *tcpip_strtoaddr(const char *str)
271 {
272     static struct sockaddr_in add;
273     
274     if (!tcpip_strtoaddr_ex (str, &add))
275         return 0;
276     return &add;
277 }
278
279 int tcpip_more(COMSTACK h)
280 {
281     tcpip_state *sp = (tcpip_state *)h->cprivate;
282     
283     return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
284         sp->altlen);
285 }
286
287 /*
288  * connect(2) will block (sometimes) - nothing we can do short of doing
289  * weird things like spawning subprocesses or threading or some weird junk
290  * like that.
291  */
292 int tcpip_connect(COMSTACK h, void *address)
293 {
294     struct sockaddr_in *add = (struct sockaddr_in *)address;
295 #if HAVE_OPENSSL_SSL_H
296     tcpip_state *sp = (tcpip_state *)h->cprivate;
297 #endif
298     int r;
299
300     TRC(fprintf(stderr, "tcpip_connect\n"));
301     h->io_pending = 0;
302     if (h->state != CS_ST_UNBND)
303     {
304         h->cerrno = CSOUTSTATE;
305         return -1;
306     }
307     r = connect(h->iofile, (struct sockaddr *) add, sizeof(*add));
308     if (r < 0)
309     {
310 #ifdef WIN32
311         if (WSAGetLastError() == WSAEWOULDBLOCK)
312         {
313             h->event = CS_CONNECT;
314             h->state = CS_ST_CONNECTING;
315             h->io_pending = CS_WANT_WRITE;
316             return 1;
317         }
318 #else
319         if (errno == EINPROGRESS)
320         {
321             h->event = CS_CONNECT;
322             h->state = CS_ST_CONNECTING;
323             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
324             return 1;
325         }
326 #endif
327         h->cerrno = CSYSERR;
328         return -1;
329     }
330     h->event = CS_CONNECT;
331     h->state = CS_ST_CONNECTING;
332
333     return tcpip_rcvconnect (h);
334 }
335
336 /*
337  * nop
338  */
339 int tcpip_rcvconnect(COMSTACK h)
340 {
341     tcpip_state *sp = (tcpip_state *)h->cprivate;
342     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
343
344     if (h->state == CS_ST_DATAXFER)
345         return 0;
346     if (h->state != CS_ST_CONNECTING)
347     {
348         h->cerrno = CSOUTSTATE;
349         return -1;
350     }
351 #if HAVE_OPENSSL_SSL_H
352     if (sp->ctx)
353     {
354         int res;
355
356         if (!sp->ssl)
357         {
358             sp->ssl = SSL_new (sp->ctx);
359             SSL_set_fd (sp->ssl, h->iofile);
360         }
361         res = SSL_connect (sp->ssl);
362         if (res <= 0)
363         {
364             int err = SSL_get_error(sp->ssl, res);
365             if (err == SSL_ERROR_WANT_READ)
366             {
367                 h->io_pending = CS_WANT_READ;
368                 return 1;
369             }
370             if (err == SSL_ERROR_WANT_WRITE)
371             {
372                 h->io_pending = CS_WANT_WRITE;
373                 return 1;
374             }
375             h->cerrno = CSERRORSSL;
376             return -1;
377         }
378     }
379 #endif
380     h->event = CS_DATA;
381     h->state = CS_ST_DATAXFER;
382     return 0;
383 }
384
385 #define CERTF "ztest.pem"
386 #define KEYF "ztest.pem"
387
388 int tcpip_bind(COMSTACK h, void *address, int mode)
389 {
390     struct sockaddr *addr = (struct sockaddr *)address;
391 #ifdef WIN32
392     BOOL one = 1;
393 #else
394     unsigned long one = 1;
395 #endif
396
397 #if HAVE_OPENSSL_SSL_H
398     tcpip_state *sp = (tcpip_state *)h->cprivate;
399     if (sp->ctx)
400     {
401         if (sp->ctx_alloc)
402         {
403             int res;
404             res = SSL_CTX_use_certificate_file (sp->ctx, CERTF,
405                                                 SSL_FILETYPE_PEM);
406             if (res <= 0)
407             {
408                 ERR_print_errors_fp(stderr);
409                 exit (2);
410             }
411             res = SSL_CTX_use_PrivateKey_file (sp->ctx, KEYF,
412                                                SSL_FILETYPE_PEM);
413             if (res <= 0)
414             {
415                 ERR_print_errors_fp(stderr);
416                 exit (3);
417             }
418             res = SSL_CTX_check_private_key (sp->ctx);
419             if (res <= 0)
420             {
421                 ERR_print_errors_fp(stderr);
422                 exit(5);
423             }
424         }
425         TRC (fprintf (stderr, "ssl_bind\n"));
426     }
427     else
428     {
429         TRC (fprintf (stderr, "tcpip_bind\n"));
430     }
431 #else
432     TRC (fprintf (stderr, "tcpip_bind\n"));
433 #endif
434 #ifndef WIN32
435     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (char*) 
436         &one, sizeof(one)) < 0)
437     {
438         h->cerrno = CSYSERR;
439         return -1;
440     }
441 #endif
442     if (bind(h->iofile, addr, sizeof(struct sockaddr_in)))
443     {
444         h->cerrno = CSYSERR;
445         return -1;
446     }
447     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
448     {
449         h->cerrno = CSYSERR;
450         return -1;
451     }
452     h->state = CS_ST_IDLE;
453     h->event = CS_LISTEN;
454     return 0;
455 }
456
457 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen,
458                  int (*check_ip)(void *cd, const char *a, int len, int t),
459                  void *cd)
460 {
461     struct sockaddr_in addr;
462     NET_LEN_T len = sizeof(addr);
463
464     TRC(fprintf(stderr, "tcpip_listen pid=%d\n", getpid()));
465     if (h->state != CS_ST_IDLE)
466     {
467         h->cerrno = CSOUTSTATE;
468         return -1;
469     }
470     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
471     if (h->newfd < 0)
472     {
473         if (
474 #ifdef WIN32
475             WSAGetLastError() == WSAEWOULDBLOCK
476 #else
477             errno == EWOULDBLOCK 
478 #ifdef EAGAIN
479 #if EAGAIN != EWOULDBLOCK
480             || errno == EAGAIN
481 #endif
482 #endif
483 #endif
484             )
485             h->cerrno = CSNODATA;
486         else
487             h->cerrno = CSYSERR;
488         return -1;
489     }
490     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_in))
491         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
492     else if (addrlen)
493         *addrlen = 0;
494     if (check_ip && (*check_ip)(cd, (const char *) &addr,
495         sizeof(addr), AF_INET))
496     {
497         h->cerrno = CSDENY;
498 #ifdef WIN32
499         closesocket(h->newfd);
500 #else
501         close(h->newfd);
502 #endif
503         h->newfd = -1;
504         return -1;
505     }
506     h->state = CS_ST_INCON;
507     return 0;
508 }
509
510 COMSTACK tcpip_accept(COMSTACK h)
511 {
512     COMSTACK cnew;
513     tcpip_state *state, *st = (tcpip_state *)h->cprivate;
514 #ifdef WIN32
515     unsigned long tru = 1;
516 #endif
517
518     TRC(fprintf(stderr, "tcpip_accept\n"));
519     if (h->state == CS_ST_INCON)
520     {
521         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
522         {
523             h->cerrno = CSYSERR;
524 #ifdef WIN32
525             closesocket(h->newfd);
526 #else
527             close(h->newfd);
528 #endif
529             h->newfd = -1;
530             return 0;
531         }
532         memcpy(cnew, h, sizeof(*h));
533         cnew->iofile = h->newfd;
534         cnew->io_pending = 0;
535         if (!(state = (tcpip_state *)
536               (cnew->cprivate = xmalloc(sizeof(tcpip_state)))))
537         {
538             h->cerrno = CSYSERR;
539             if (h->newfd != -1)
540             {
541 #ifdef WIN32
542                 closesocket(h->newfd);
543 #else
544                 close(h->newfd);
545 #endif
546                 h->newfd = -1;
547             }
548             return 0;
549         }
550         if (!cnew->blocking && 
551 #ifdef WIN32
552             (ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
553 #else
554             (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
555 #endif
556             )
557         {
558             h->cerrno = CSYSERR;
559             if (h->newfd != -1)
560             {
561 #ifdef WIN32
562                 closesocket(h->newfd);
563 #else
564                 close(h->newfd);
565 #endif
566                 h->newfd = -1;
567             }
568             xfree (cnew);
569             xfree (state);
570             return 0;
571         }
572         h->newfd = -1;
573         state->altbuf = 0;
574         state->altsize = state->altlen = 0;
575         state->towrite = state->written = -1;
576         state->complete = st->complete;
577         cnew->state = CS_ST_ACCEPT;
578         h->state = CS_ST_IDLE;
579         
580 #if HAVE_OPENSSL_SSL_H
581         state->ctx = st->ctx;
582         state->ctx_alloc = 0;
583         state->ssl = st->ssl;
584         if (state->ctx)
585         {
586             state->ssl = SSL_new (state->ctx);
587             SSL_set_fd (state->ssl, cnew->iofile);
588         }
589 #endif
590         h = cnew;
591     }
592     if (h->state == CS_ST_ACCEPT)
593     {
594 #if HAVE_OPENSSL_SSL_H
595         tcpip_state *state = (tcpip_state *)h->cprivate;
596         if (state->ctx)
597         {
598             int res = SSL_accept (state->ssl);
599             TRC(fprintf(stderr, "SSL_accept\n"));
600             if (res <= 0)
601             {
602                 int err = SSL_get_error(state->ssl, res);
603                 if (err == SSL_ERROR_WANT_READ)
604                 {
605                     h->io_pending = CS_WANT_READ;
606                     return h;
607                 }
608                 if (err == SSL_ERROR_WANT_WRITE)
609                 {
610                     h->io_pending = CS_WANT_WRITE;
611                     return h;
612                 }
613                 cs_close (h);
614                 return 0;
615             }
616         }
617 #endif
618     }
619     else
620     {
621         h->cerrno = CSOUTSTATE;
622         return 0;
623     }
624     h->io_pending = 0;
625     h->state = CS_ST_DATAXFER;
626     h->event = CS_DATA;
627     return h;
628 }
629
630 #define CS_TCPIP_BUFCHUNK 4096
631
632 /*
633  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
634  * 0=connection closed.
635  */
636 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
637 {
638     tcpip_state *sp = (tcpip_state *)h->cprivate;
639     char *tmpc;
640     int tmpi, berlen, rest, req, tomove;
641     int hasread = 0, res;
642
643     TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
644     if (sp->altlen) /* switch buffers */
645     {
646         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
647             (unsigned) sp->altbuf));
648         tmpc = *buf;
649         tmpi = *bufsize;
650         *buf = sp->altbuf;
651         *bufsize = sp->altsize;
652         hasread = sp->altlen;
653         sp->altlen = 0;
654         sp->altbuf = tmpc;
655         sp->altsize = tmpi;
656     }
657     h->io_pending = 0;
658     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
659     {
660         if (!*bufsize)
661         {
662             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
663                 return -1;
664         }
665         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
666             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
667                 return -1;
668         res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0);
669         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
670         if (res < 0)
671         {
672 #ifdef WIN32
673             if (WSAGetLastError() == WSAEWOULDBLOCK)
674             {
675                 h->io_pending = CS_WANT_READ;
676                 break;
677             }
678             else
679                 return -1;
680 #else
681             if (errno == EWOULDBLOCK 
682 #ifdef EAGAIN   
683 #if EAGAIN != EWOULDBLOCK
684                 || errno == EAGAIN
685 #endif
686 #endif
687                 || errno == EINPROGRESS
688 #ifdef __sun__
689                 || errno == ENOENT /* Sun's sometimes set errno to this */
690 #endif
691                 )
692             {
693                 h->io_pending = CS_WANT_READ;
694                 break;
695             }
696             else if (errno == 0)
697                 continue;
698             else
699                 return -1;
700 #endif
701         }
702         else if (!res)
703             return 0;
704         hasread += res;
705     }
706     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
707                   hasread, berlen));
708     /* move surplus buffer (or everything if we didn't get a BER rec.) */
709     if (hasread > berlen)
710     {
711         tomove = req = hasread - berlen;
712         rest = tomove % CS_TCPIP_BUFCHUNK;
713         if (rest)
714             req += CS_TCPIP_BUFCHUNK - rest;
715         if (!sp->altbuf)
716         {
717             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
718                 return -1;
719         } else if (sp->altsize < req)
720             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
721                 return -1;
722         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
723             (unsigned) sp->altbuf));
724         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
725     }
726     if (berlen < CS_TCPIP_BUFCHUNK - 1)
727         *(*buf + berlen) = '\0';
728     return berlen ? berlen : 1;
729 }
730
731
732 #if HAVE_OPENSSL_SSL_H
733 /*
734  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
735  * 0=connection closed.
736  */
737 int ssl_get(COMSTACK h, char **buf, int *bufsize)
738 {
739     tcpip_state *sp = (tcpip_state *)h->cprivate;
740     char *tmpc;
741     int tmpi, berlen, rest, req, tomove;
742     int hasread = 0, res;
743
744     TRC(fprintf(stderr, "ssl_get: bufsize=%d\n", *bufsize));
745     if (sp->altlen) /* switch buffers */
746     {
747         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
748             (unsigned) sp->altbuf));
749         tmpc = *buf;
750         tmpi = *bufsize;
751         *buf = sp->altbuf;
752         *bufsize = sp->altsize;
753         hasread = sp->altlen;
754         sp->altlen = 0;
755         sp->altbuf = tmpc;
756         sp->altsize = tmpi;
757     }
758     h->io_pending = 0;
759     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
760     {
761         if (!*bufsize)
762         {
763             if (!(*buf = (char *)xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
764                 return -1;
765         }
766         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
767             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
768                 return -1;
769         res = SSL_read (sp->ssl, *buf + hasread, CS_TCPIP_BUFCHUNK);
770         TRC(fprintf(stderr, "  SSL_read res=%d, hasread=%d\n", res, hasread));
771         if (res <= 0)
772         {
773             int ssl_err = SSL_get_error(sp->ssl, res);
774             if (ssl_err == SSL_ERROR_WANT_READ)
775             {
776                 h->io_pending = CS_WANT_READ;
777                 break;
778             }
779             if (ssl_err == SSL_ERROR_WANT_WRITE)
780             {
781                 h->io_pending = CS_WANT_WRITE;
782                 break;
783             }
784             if (res == 0)
785                 return 0;
786             h->cerrno = CSERRORSSL;
787             return -1;
788         }
789         hasread += res;
790     }
791     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
792         hasread, berlen));
793     /* move surplus buffer (or everything if we didn't get a BER rec.) */
794     if (hasread > berlen)
795     {
796         tomove = req = hasread - berlen;
797         rest = tomove % CS_TCPIP_BUFCHUNK;
798         if (rest)
799             req += CS_TCPIP_BUFCHUNK - rest;
800         if (!sp->altbuf)
801         {
802             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
803                 return -1;
804         } else if (sp->altsize < req)
805             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
806                 return -1;
807         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
808             (unsigned) sp->altbuf));
809         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
810     }
811     if (berlen < CS_TCPIP_BUFCHUNK - 1)
812         *(*buf + berlen) = '\0';
813     return berlen ? berlen : 1;
814 }
815 #endif
816
817 /*
818  * Returns 1, 0 or -1
819  * In nonblocking mode, you must call again with same buffer while
820  * return value is 1.
821  */
822 int tcpip_put(COMSTACK h, char *buf, int size)
823 {
824     int res;
825     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
826
827     TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
828     h->io_pending = 0;
829     h->event = CS_DATA;
830     if (state->towrite < 0)
831     {
832         state->towrite = size;
833         state->written = 0;
834     }
835     else if (state->towrite != size)
836     {
837         h->cerrno = CSWRONGBUF;
838         return -1;
839     }
840     while (state->towrite > state->written)
841     {
842         if ((res =
843              send(h->iofile, buf + state->written, size -
844                   state->written, 
845 #ifdef MSG_NOSIGNAL
846                   MSG_NOSIGNAL
847 #else
848                   0
849 #endif
850                  )) < 0)
851         {
852             if (
853 #ifdef WIN32
854                 WSAGetLastError() == WSAEWOULDBLOCK
855 #else
856                 errno == EWOULDBLOCK 
857 #ifdef EAGAIN
858 #if EAGAIN != EWOULDBLOCK
859              || errno == EAGAIN
860 #endif
861 #endif
862 #endif
863                 )
864             {
865                 TRC(fprintf(stderr, "  Flow control stop\n"));
866                 h->io_pending = CS_WANT_WRITE;
867                 return 1;
868             }
869             h->cerrno = CSYSERR;
870             return -1;
871         }
872         state->written += res;
873         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
874                     res, state->written, size));
875     }
876     state->towrite = state->written = -1;
877     TRC(fprintf(stderr, "  Ok\n"));
878     return 0;
879 }
880
881
882 #if HAVE_OPENSSL_SSL_H
883 /*
884  * Returns 1, 0 or -1
885  * In nonblocking mode, you must call again with same buffer while
886  * return value is 1.
887  */
888 int ssl_put(COMSTACK h, char *buf, int size)
889 {
890     int res;
891     struct tcpip_state *state = (struct tcpip_state *)h->cprivate;
892
893     TRC(fprintf(stderr, "ssl_put: size=%d\n", size));
894     h->io_pending = 0;
895     h->event = CS_DATA;
896     if (state->towrite < 0)
897     {
898         state->towrite = size;
899         state->written = 0;
900     }
901     else if (state->towrite != size)
902     {
903         h->cerrno = CSWRONGBUF;
904         return -1;
905     }
906     while (state->towrite > state->written)
907     {
908         res = SSL_write (state->ssl, buf + state->written,
909                          size - state->written);
910         if (res <= 0)
911         {
912             int ssl_err = SSL_get_error(state->ssl, res);
913             if (ssl_err == SSL_ERROR_WANT_READ)
914             {
915                 h->io_pending = CS_WANT_READ;
916                 return 1;
917             }
918             if (ssl_err == SSL_ERROR_WANT_WRITE)
919             {
920                 h->io_pending = CS_WANT_WRITE;
921                 return 1;
922             }
923             h->cerrno = CSERRORSSL;
924             return -1;
925         }
926         state->written += res;
927         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
928                     res, state->written, size));
929     }
930     state->towrite = state->written = -1;
931     TRC(fprintf(stderr, "  Ok\n"));
932     return 0;
933 }
934 #endif
935
936 int tcpip_close(COMSTACK h)
937 {
938     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
939
940     TRC(fprintf(stderr, "tcpip_close\n"));
941     if (h->iofile != -1)
942     {
943 #if HAVE_OPENSSL_SSL_H
944         if (sp->ssl)
945         {
946             SSL_shutdown (sp->ssl);
947         }
948 #endif
949 #ifdef WIN32
950         closesocket(h->iofile);
951 #else
952         close(h->iofile);
953 #endif
954     }
955     if (sp->altbuf)
956         xfree(sp->altbuf);
957 #if HAVE_OPENSSL_SSL_H
958     if (sp->ssl)
959     {
960         TRC (fprintf(stderr, "SSL_free\n"));
961         SSL_free (sp->ssl);
962     }
963     sp->ssl = 0;
964     if (sp->ctx_alloc)
965         SSL_CTX_free (sp->ctx_alloc);
966 #endif
967     xfree(sp);
968     xfree(h);
969     return 0;
970 }
971
972 char *tcpip_addrstr(COMSTACK h)
973 {
974     struct sockaddr_in addr;
975     tcpip_state *sp = (struct tcpip_state *)h->cprivate;
976     char *r, *buf = sp->buf;
977     NET_LEN_T len;
978     struct hostent *host;
979     
980     len = sizeof(addr);
981     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
982     {
983         h->cerrno = CSYSERR;
984         return 0;
985     }
986     if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
987                               AF_INET)))
988         r = (char*) host->h_name;
989     else
990         r = inet_ntoa(addr.sin_addr);
991     sprintf(buf, "tcp:%s", r);
992 #if HAVE_OPENSSL_SSL_H
993     if (sp->ctx)
994         sprintf(buf, "ssl:%s", r);
995 #endif
996     return buf;
997 }
998
999 int static tcpip_set_blocking(COMSTACK p, int blocking)
1000 {
1001     unsigned long flag;
1002     
1003     if (p->blocking == blocking)
1004         return 1;
1005 #ifdef WIN32
1006     flag = 1;
1007     if (ioctlsocket(p->iofile, FIONBIO, &flag) < 0)
1008         return 0;
1009 #else
1010     flag = fcntl(p->iofile, F_GETFL, 0);
1011     if(!blocking)
1012         flag = flag & ~O_NONBLOCK;
1013     else
1014         flag = flag | O_NONBLOCK;
1015     if (fcntl(p->iofile, F_SETFL, flag) < 0)
1016         return 0;
1017 #endif
1018     p->blocking = blocking;
1019     return 1;
1020 }