0163f3c1c56bfb18951640791827e4c7215951c3
[yaz-moved-to-github.git] / comstack / tcpip.c
1 /*
2  * Copyright (c) 1995-1997, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: tcpip.c,v $
7  * Revision 1.18  1997-09-29 07:15:25  adam
8  * Changed use of setsockopt to avoid warnings on MSVC.
9  *
10  * Revision 1.17  1997/09/17 12:10:30  adam
11  * YAZ version 1.4.
12  *
13  * Revision 1.16  1997/09/01 08:49:14  adam
14  * New windows NT/95 port using MSV5.0. Minor changes only.
15  *
16  * Revision 1.15  1997/05/14 06:53:33  adam
17  * C++ support.
18  *
19  * Revision 1.14  1997/05/01 15:06:32  adam
20  * Moved WINSOCK init. code to tcpip_init routine.
21  *
22  * Revision 1.13  1996/11/01 08:45:18  adam
23  * Bug fix: used close on MS-Windows. Fixed to closesocket.
24  *
25  * Revision 1.12  1996/07/06 19:58:30  quinn
26  * System headerfiles gathered in yconfig
27  *
28  * Revision 1.11  1996/02/23  10:00:39  quinn
29  * WAIS Work
30  *
31  * Revision 1.10  1996/02/20  12:52:11  quinn
32  * WAIS protocol support.
33  *
34  * Revision 1.9  1996/02/10  12:23:11  quinn
35  * Enablie inetd operations fro TCP/IP stack
36  *
37  * Revision 1.8  1995/11/01  13:54:27  quinn
38  * Minor adjustments
39  *
40  * Revision 1.7  1995/10/30  12:41:16  quinn
41  * Added hostname lookup for server.
42  *
43  * Revision 1.6  1995/09/29  17:12:00  quinn
44  * Smallish
45  *
46  * Revision 1.5  1995/09/29  17:01:48  quinn
47  * More Windows work
48  *
49  * Revision 1.4  1995/09/28  10:12:26  quinn
50  * Windows-support changes
51  *
52  * Revision 1.3  1995/09/27  15:02:45  quinn
53  * Modified function heads & prototypes.
54  *
55  * Revision 1.2  1995/06/15  12:30:06  quinn
56  * Added @ as hostname alias for INADDR ANY.
57  *
58  * Revision 1.1  1995/06/14  09:58:20  quinn
59  * Renamed yazlib to comstack.
60  *
61  * Revision 1.20  1995/05/16  08:51:16  quinn
62  * License, documentation, and memory fixes
63  *
64  * Revision 1.19  1995/04/10  10:24:08  quinn
65  * Some bug-fixes.
66  *
67  * Revision 1.18  1995/03/30  13:29:27  quinn
68  * Added REUSEADDR in tcpip_bind
69  *
70  * Revision 1.17  1995/03/27  08:36:10  quinn
71  * Some work on nonblocking operation in xmosi.c and rfct.c.
72  * Added protocol parameter to cs_create()
73  *
74  * Revision 1.16  1995/03/21  15:53:41  quinn
75  * Added rcvconnect
76  *
77  * Revision 1.15  1995/03/21  12:31:27  quinn
78  * Added check for EINPROGRESS on connect.
79  *
80  * Revision 1.14  1995/03/20  09:47:21  quinn
81  * Added server-side support to xmosi.c
82  * Fixed possible problems in rfct
83  * Other little mods
84  *
85  * Revision 1.13  1995/03/15  16:15:13  adam
86  * Removed p_write.
87  *
88  * Revision 1.12  1995/03/15  15:36:27  quinn
89  * Mods to support nonblocking I/O
90  *
91  * Revision 1.11  1995/03/15  08:37:57  quinn
92  * Now we're pretty much set for nonblocking I/O.
93  *
94  * Revision 1.10  1995/03/14  17:00:07  quinn
95  * Bug-fixes - added tracing info to tcpip.c
96  *
97  * Revision 1.9  1995/03/14  10:28:42  quinn
98  * Adding server-side support to tcpip.c and fixing bugs in nonblocking I/O
99  *
100  * Revision 1.8  1995/03/10  14:22:50  quinn
101  * Removed debug output.
102  *
103  * Revision 1.7  1995/03/10  11:44:59  quinn
104  * Fixes and debugging
105  *
106  * Revision 1.6  1995/03/07  10:26:55  quinn
107  * Initialized type field in the comstacks.
108  *
109  * Revision 1.5  1995/02/14  20:40:07  quinn
110  * Various stuff.
111  *
112  * Revision 1.4  1995/02/14  11:54:49  quinn
113  * Beginning to add full CCL.
114  *
115  * Revision 1.3  1995/02/10  18:58:10  quinn
116  * Fixed tcpip_get (formerly tcpip_read).
117  * Turned tst (cli) into a proper, event-driven thingy.
118  *
119  * Revision 1.2  1995/02/10  15:55:47  quinn
120  * Small things.
121  *
122  * Revision 1.1  1995/02/09  15:51:52  quinn
123  * Works better now.
124  *
125  */
126
127 #include <stdio.h>
128 #include <string.h>
129 #include <stdlib.h>
130 #ifndef WINDOWS
131 #include <unistd.h>
132 #endif
133 #include <errno.h>
134 #include <fcntl.h>
135
136 #include <comstack.h>
137 #include <tcpip.h>
138
139 int tcpip_close(COMSTACK h);
140 int tcpip_put(COMSTACK h, char *buf, int size);
141 int tcpip_get(COMSTACK h, char **buf, int *bufsize);
142 int tcpip_connect(COMSTACK h, void *address);
143 int tcpip_more(COMSTACK h);
144 int tcpip_rcvconnect(COMSTACK h);
145 int tcpip_bind(COMSTACK h, void *address, int mode);
146 int tcpip_listen(COMSTACK h, char *addrp, int *addrlen);
147 COMSTACK tcpip_accept(COMSTACK h);
148 char *tcpip_addrstr(COMSTACK h);
149 void *tcpip_straddr(COMSTACK h, const char *str);
150
151 /*
152  * Determine length/completeness of incoming packages
153  */
154 int completeBER(unsigned char *buf, int len); /* from the ODR module */
155 int completeWAIS(unsigned char *buf, int len); /* from waislen.c */
156
157 #ifdef TRACE_TCPIP
158 #define TRC(x) x
159 #else
160 #define TRC(X)
161 #endif
162
163 typedef struct tcpip_state
164 {
165     char *altbuf; /* alternate buffer for surplus data */
166     int altsize;  /* size as xmalloced */
167     int altlen;   /* length of data or 0 if none */
168
169     int written;  /* -1 if we aren't writing */
170     int towrite;  /* to verify against user input */
171     int (*complete)(unsigned char *buf, int len); /* length/completeness */
172     struct sockaddr_in addr;  /* returned by cs_straddr */
173     char buf[128]; /* returned by cs_addrstr */
174 } tcpip_state;
175
176 #ifdef WINDOWS
177 static int tcpip_init (void)
178 {
179     static int initialized = 0;
180     if (!initialized)
181     {
182         WORD requested;
183         WSADATA wd;
184
185         requested = MAKEWORD(1, 1);
186         if (WSAStartup(requested, &wd))
187             return 0;
188         initialized = 1;
189     }
190     return 1;
191 }
192 #else
193 static int tcpip_init (void)
194 {
195     return 1;
196 }
197 #endif
198 /*
199  * This function is always called through the cs_create() macro.
200  * s >= 0: socket has already been established for us.
201  */
202 COMSTACK tcpip_type(int s, int blocking, int protocol)
203 {
204     COMSTACK p;
205     tcpip_state *state;
206     int new_socket;
207 #ifdef WINDOWS
208     unsigned long tru = 1;
209 #else
210     struct protoent *proto;
211 #endif
212
213     if (!tcpip_init ())
214         return 0;
215     if (s < 0)
216     {
217 #ifndef WINDOWS
218         if (!(proto = getprotobyname("tcp")))
219             return 0;
220         if ((s = socket(AF_INET, SOCK_STREAM, proto->p_proto)) < 0)
221 #else
222         if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
223 #endif
224             return 0;
225         new_socket = 1;
226     }
227     else
228         new_socket = 0;
229     if (!(p = xmalloc(sizeof(struct comstack))))
230         return 0;
231     if (!(state = p->cprivate = xmalloc(sizeof(tcpip_state))))
232         return 0;
233
234 #ifdef WINDOWS
235     if (!(p->blocking = blocking) && ioctlsocket(s, FIONBIO, &tru) < 0)
236 #else
237     if (!(p->blocking = blocking) && fcntl(s, F_SETFL, O_NONBLOCK) < 0)
238 #endif
239         return 0;
240
241     p->iofile = s;
242     p->type = tcpip_type;
243     p->protocol = protocol;
244
245     p->f_connect = tcpip_connect;
246     p->f_rcvconnect = tcpip_rcvconnect;
247     p->f_get = tcpip_get;
248     p->f_put = tcpip_put;
249     p->f_close = tcpip_close;
250     p->f_more = tcpip_more;
251     p->f_bind = tcpip_bind;
252     p->f_listen = tcpip_listen;
253     p->f_accept = tcpip_accept;
254     p->f_addrstr = tcpip_addrstr;
255     p->f_straddr = tcpip_straddr;
256
257     p->state = new_socket ? CS_UNBND : CS_IDLE; /* state of line */
258     p->event = CS_NONE;
259     p->cerrno = 0;
260     p->stackerr = 0;
261
262     state->altbuf = 0;
263     state->altsize = state->altlen = 0;
264     state->towrite = state->written = -1;
265     if (protocol == PROTO_WAIS)
266         state->complete = completeWAIS;
267     else
268         state->complete = completeBER;
269
270     p->timeout = COMSTACK_DEFAULT_TIMEOUT;
271     TRC(fprintf(stderr, "Created new TCPIP comstack\n"));
272
273     return p;
274 }
275
276 static int tcpip_strtoaddr_ex(const char *str, struct sockaddr_in *add)
277 {
278     struct hostent *hp;
279     char *p, buf[512];
280     short int port = 210;
281     unsigned tmpadd;
282
283     if (!tcpip_init ())
284         return 0;
285     TRC(fprintf(stderr, "tcpip_strtoaddress: %s\n", str ? str : "NULL"));
286     add->sin_family = AF_INET;
287     strcpy(buf, str);
288     if ((p = strchr(buf, ':')))
289     {
290         *p = 0;
291         port = atoi(p + 1);
292     }
293     add->sin_port = htons(port);
294     if (!strcmp("@", buf))
295         add->sin_addr.s_addr = INADDR_ANY;
296     else if ((hp = gethostbyname(buf)))
297         memcpy(&add->sin_addr.s_addr, *hp->h_addr_list,
298                sizeof(struct in_addr));
299     else if ((tmpadd = (unsigned) inet_addr(buf)) != 0)
300         memcpy(&add->sin_addr.s_addr, &tmpadd, sizeof(struct in_addr));
301     else
302         return 0;
303     return 1;
304 }
305
306 void *tcpip_straddr(COMSTACK h, const char *str)
307 {
308     tcpip_state *sp = h->cprivate;
309
310     if (!tcpip_strtoaddr_ex (str, &sp->addr))
311         return 0;
312     return &sp->addr;
313 }
314
315 struct sockaddr_in *tcpip_strtoaddr(const char *str)
316 {
317     static struct sockaddr_in add;
318     
319     if (!tcpip_strtoaddr_ex (str, &add))
320         return 0;
321     return &add;
322 }
323
324 int tcpip_more(COMSTACK h)
325 {
326     tcpip_state *sp = h->cprivate;
327     
328     return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
329         sp->altlen);
330 }
331
332 /*
333  * connect(2) will block (sometimes) - nothing we can do short of doing
334  * weird things like spawning subprocesses or threading or some weird junk
335  * like that.
336  */
337 int tcpip_connect(COMSTACK h, void *address)
338 {
339     struct sockaddr_in *add = address;
340
341     TRC(fprintf(stderr, "tcpip_connect\n"));
342     if (connect(h->iofile, (struct sockaddr *) add, sizeof(*add)) < 0)
343     {
344 #ifdef WINDOWS
345         if (WSAGetLastError() == WSAEWOULDBLOCK)
346 #else
347         if (errno == EINPROGRESS)
348 #endif
349             return 1;
350         return -1;
351     }
352     h->state = CS_DATAXFER;
353     return 0;
354 }
355
356 /*
357  * nop
358  */
359 int tcpip_rcvconnect(COMSTACK h)
360 {
361     TRC(fprintf(stderr, "tcpip_rcvconnect\n"));
362     return 0;
363 }
364
365 int tcpip_bind(COMSTACK h, void *address, int mode)
366 {
367     struct sockaddr *addr = address;
368 #ifdef WINDOWS
369     BOOL one = 1;
370 #else
371     unsigned long one = 1;
372 #endif
373
374     TRC(fprintf(stderr, "tcpip_bind\n"));
375     if (setsockopt(h->iofile, SOL_SOCKET, SO_REUSEADDR, (void*) 
376         &one, sizeof(one)) < 0)
377     {
378         h->cerrno = CSYSERR;
379         return -1;
380     }
381     if (bind(h->iofile, addr, sizeof(struct sockaddr_in)) < 0)
382     {
383         h->cerrno = CSYSERR;
384         return -1;
385     }
386     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
387     {
388         h->cerrno = CSYSERR;
389         return -1;
390     }
391     h->state = CS_IDLE;
392     return 0;
393 }
394
395 int tcpip_listen(COMSTACK h, char *raddr, int *addrlen)
396 {
397     struct sockaddr_in addr;
398     int len = sizeof(addr);
399
400     TRC(fprintf(stderr, "tcpip_listen\n"));
401     if (h->state != CS_IDLE)
402     {
403         h->cerrno = CSOUTSTATE;
404         return -1;
405     }
406     if ((h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len)) < 0)
407     {
408 #ifdef WINDOWS
409         if (WSAGetLastError() == WSAEWOULDBLOCK)
410 #else
411         if (errno == EWOULDBLOCK)
412 #endif
413
414             h->cerrno = CSNODATA;
415         else
416             h->cerrno = CSYSERR;
417         return -1;
418     }
419     if (addrlen && *addrlen > sizeof(struct sockaddr_in))
420         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_in));
421     else if (addrlen)
422         *addrlen = 0;
423     h->state = CS_INCON;
424     return 0;
425 }
426
427 COMSTACK tcpip_accept(COMSTACK h)
428 {
429     COMSTACK cnew;
430     tcpip_state *state, *st = h->cprivate;
431 #ifdef WINDOWS
432     unsigned long tru = 1;
433 #endif
434
435     TRC(fprintf(stderr, "tcpip_accept\n"));
436     if (h->state != CS_INCON)
437     {
438         h->cerrno = CSOUTSTATE;
439         return 0;
440     }
441     if (!(cnew = xmalloc(sizeof(*cnew))))
442     {
443         h->cerrno = CSYSERR;
444         return 0;
445     }
446     memcpy(cnew, h, sizeof(*h));
447     cnew->iofile = h->newfd;
448     if (!(state = cnew->cprivate = xmalloc(sizeof(tcpip_state))))
449     {
450         h->cerrno = CSYSERR;
451         return 0;
452     }
453 #ifdef WINDOWS
454     if (!cnew->blocking && ioctlsocket(cnew->iofile, FIONBIO, &tru) < 0)
455 #else
456     if (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
457 #endif
458         return 0;
459     state->altbuf = 0;
460     state->altsize = state->altlen = 0;
461     state->towrite = state->written = -1;
462     state->complete = st->complete;
463     cnew->state = CS_DATAXFER;
464     h->state = CS_IDLE;
465     return cnew;
466 }
467
468 #define CS_TCPIP_BUFCHUNK 4096
469
470 /*
471  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
472  * 0=connection closed.
473  */
474 int tcpip_get(COMSTACK h, char **buf, int *bufsize)
475 {
476     tcpip_state *sp = h->cprivate;
477     char *tmpc;
478     int tmpi, berlen, rest, req, tomove;
479     int hasread = 0, res;
480
481     TRC(fprintf(stderr, "tcpip_get: bufsize=%d\n", *bufsize));
482     if (sp->altlen) /* switch buffers */
483     {
484         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
485             (unsigned) sp->altbuf));
486         tmpc = *buf;
487         tmpi = *bufsize;
488         *buf = sp->altbuf;
489         *bufsize = sp->altsize;
490         hasread = sp->altlen;
491         sp->altlen = 0;
492         sp->altbuf = tmpc;
493         sp->altsize = tmpi;
494     }
495     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
496     {
497         if (!*bufsize)
498         {
499             if (!(*buf = xmalloc(*bufsize = CS_TCPIP_BUFCHUNK)))
500                 return -1;
501         }
502         else if (*bufsize - hasread < CS_TCPIP_BUFCHUNK)
503             if (!(*buf =xrealloc(*buf, *bufsize *= 2)))
504                 return -1;
505         if ((res = recv(h->iofile, *buf + hasread, CS_TCPIP_BUFCHUNK, 0)) < 0)
506 #ifdef WINDOWS
507             if (WSAGetLastError() == WSAEWOULDBLOCK)
508 #else
509             if (errno == EWOULDBLOCK)
510 #endif
511                 break;
512             else
513                 return -1;
514         if (!res)
515             return 0;
516         hasread += res;
517         TRC(fprintf(stderr, "  res=%d, hasread=%d\n", res, hasread));
518     }
519     TRC(fprintf(stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
520         hasread, berlen));
521     /* move surplus buffer (or everything if we didn't get a BER rec.) */
522     if (hasread > berlen)
523     {
524         tomove = req = hasread - berlen;
525         rest = tomove % CS_TCPIP_BUFCHUNK;
526         if (rest)
527             req += CS_TCPIP_BUFCHUNK - rest;
528         if (!sp->altbuf)
529         {
530             if (!(sp->altbuf = xmalloc(sp->altsize = req)))
531                 return -1;
532         } else if (sp->altsize < req)
533             if (!(sp->altbuf =xrealloc(sp->altbuf, sp->altsize = req)))
534                 return -1;
535         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
536             (unsigned) sp->altbuf));
537         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
538     }
539     if (berlen < CS_TCPIP_BUFCHUNK - 1)
540         *(*buf + berlen) = '\0';
541     return berlen ? berlen : 1;
542 }
543
544 /*
545  * Returns 1, 0 or -1
546  * In nonblocking mode, you must call again with same buffer while
547  * return value is 1.
548  */
549 int tcpip_put(COMSTACK h, char *buf, int size)
550 {
551     int res;
552     struct tcpip_state *state = h->cprivate;
553
554     TRC(fprintf(stderr, "tcpip_put: size=%d\n", size));
555     if (state->towrite < 0)
556     {
557         state->towrite = size;
558         state->written = 0;
559     }
560     else if (state->towrite != size)
561     {
562         h->cerrno = CSWRONGBUF;
563         return -1;
564     }
565     while (state->towrite > state->written)
566     {
567         if ((res = send(h->iofile, buf + state->written, size -
568             state->written, 0)) < 0)
569         {
570 #ifdef WINDOWS
571             if (WSAGetLastError() == WSAEWOULDBLOCK)
572 #else
573             if (errno == EAGAIN)
574 #endif
575             {
576                 TRC(fprintf(stderr, "  Flow control stop\n"));
577                 return 1;
578             }
579             h->cerrno = CSYSERR;
580             return -1;
581         }
582         state->written += res;
583         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
584             res, state->written, size));
585     }
586     state->towrite = state->written = -1;
587     TRC(fprintf(stderr, "  Ok\n"));
588     return 0;
589 }
590
591 int tcpip_close(COMSTACK h)
592 {
593     tcpip_state *sp = h->cprivate;
594
595     TRC(fprintf(stderr, "tcpip_close\n"));
596     if (h->iofile != -1)
597 #ifdef WINDOWS
598         closesocket(h->iofile);
599 #else
600         close(h->iofile);
601 #endif
602     if (sp->altbuf)
603         xfree(sp->altbuf);
604     xfree(sp);
605     xfree(h);
606     return 0;
607 }
608
609 char *tcpip_addrstr(COMSTACK h)
610 {
611     struct sockaddr_in addr;
612     tcpip_state *sp = h->cprivate;
613     char *r, *buf = sp->buf;
614     int len;
615     struct hostent *host;
616     
617     len = sizeof(addr);
618     if (getpeername(h->iofile, (struct sockaddr*) &addr, &len) < 0)
619     {
620         h->cerrno = CSYSERR;
621         return 0;
622     }
623     if ((host = gethostbyaddr((char*)&addr.sin_addr, sizeof(addr.sin_addr),
624                               AF_INET)))
625         r = (char*) host->h_name;
626     else
627         r = inet_ntoa(addr.sin_addr);
628     sprintf(buf, "tcp:%s", r);
629     return buf;
630 }