e5cd9e58d9cfea14b64fcaa8daef24347bcfe4a6
[yaz-moved-to-github.git] / comstack / unix.c
1 /*
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: unix.c,v 1.11 2003-03-03 19:57:35 adam Exp $
6  * UNIX socket COMSTACK. By Morten Bøgeskov.
7  */
8 #ifndef WIN32
9
10 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <signal.h>
17
18 #include <sys/socket.h>
19 #include <sys/stat.h>
20 #include <sys/un.h>
21
22 #include <yaz/comstack.h>
23 #include <yaz/unix.h>
24 #include <yaz/log.h>
25 #include <yaz/nmem.h>
26
27 #ifndef YAZ_SOCKLEN_T
28 #define YAZ_SOCKLEN_T int
29 #endif
30
31 static int unix_close(COMSTACK h);
32 static int unix_put(COMSTACK h, char *buf, int size);
33 static int unix_get(COMSTACK h, char **buf, int *bufsize);
34 static int unix_connect(COMSTACK h, void *address);
35 static int unix_more(COMSTACK h);
36 static int unix_rcvconnect(COMSTACK h);
37 static int unix_bind(COMSTACK h, void *address, int mode);
38 static int unix_listen(COMSTACK h, char *raddr, int *addrlen,
39                 int (*check_ip)(void *cd, const char *a, int len, int type),
40                 void *cd);
41 static int unix_set_blocking(COMSTACK p, int blocking);
42
43
44 static COMSTACK unix_accept(COMSTACK h);
45 static char *unix_addrstr(COMSTACK h);
46 static void *unix_straddr(COMSTACK h, const char *str);
47
48 #ifndef SUN_LEN
49 #define SUN_LEN(ptr) ((size_t) (((struct sockaddr_un *) 0)->sun_path) \
50                       + strlen ((ptr)->sun_path))
51 #endif
52 #if 0
53 #define TRC(x) x
54 #else
55 #define TRC(X)
56 #endif
57
58 /* this state is used for both SSL and straight TCP/IP */
59 typedef struct unix_state
60 {
61     char *altbuf; /* alternate buffer for surplus data */
62     int altsize;  /* size as xmalloced */
63     int altlen;   /* length of data or 0 if none */
64
65     int written;  /* -1 if we aren't writing */
66     int towrite;  /* to verify against user input */
67     int (*complete)(const unsigned char *buf, int len); /* length/comple. */
68     struct sockaddr_un addr;  /* returned by cs_straddr */
69     char buf[128]; /* returned by cs_addrstr */
70 } unix_state;
71
72 static int unix_init (void)
73 {
74     return 1;
75 }
76
77 /*
78  * This function is always called through the cs_create() macro.
79  * s >= 0: socket has already been established for us.
80  */
81 COMSTACK unix_type(int s, int blocking, int protocol, void *vp)
82 {
83     COMSTACK p;
84     unix_state *state;
85     int new_socket;
86
87     if (!unix_init ())
88         return 0;
89     if (s < 0)
90     {
91         if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
92             return 0;
93         new_socket = 1;
94     }
95     else
96         new_socket = 0;
97     if (!(p = (struct comstack *)xmalloc(sizeof(struct comstack))))
98         return 0;
99     if (!(state = (struct unix_state *)(p->cprivate =
100                                         xmalloc(sizeof(unix_state)))))
101         return 0;
102
103     if (!(p->blocking = blocking))
104     {
105         if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
106             return 0;
107 #ifndef MSG_NOSIGNAL
108         signal (SIGPIPE, SIG_IGN);
109 #endif
110     }
111
112     p->io_pending = 0;
113     p->iofile = s;
114     p->type = unix_type;
115     p->protocol = (enum oid_proto) protocol;
116
117     p->f_connect = unix_connect;
118     p->f_rcvconnect = unix_rcvconnect;
119     p->f_get = unix_get;
120     p->f_put = unix_put;
121     p->f_close = unix_close;
122     p->f_more = unix_more;
123     p->f_bind = unix_bind;
124     p->f_listen = unix_listen;
125     p->f_accept = unix_accept;
126     p->f_addrstr = unix_addrstr;
127     p->f_straddr = unix_straddr;
128     p->f_set_blocking = unix_set_blocking;
129
130     p->state = new_socket ? CS_ST_UNBND : CS_ST_IDLE; /* state of line */
131     p->event = CS_NONE;
132     p->cerrno = 0;
133     p->stackerr = 0;
134
135     state->altbuf = 0;
136     state->altsize = state->altlen = 0;
137     state->towrite = state->written = -1;
138     if (protocol == PROTO_WAIS)
139         state->complete = completeWAIS;
140     else
141         state->complete = cs_complete_auto;
142
143     p->timeout = COMSTACK_DEFAULT_TIMEOUT;
144     TRC(fprintf(stderr, "Created new UNIX comstack\n"));
145
146     return p;
147 }
148
149
150 static int unix_strtoaddr_ex(const char *str, struct sockaddr_un *add)
151 {
152     char *cp;
153     if (!unix_init ())
154         return 0;
155     TRC(fprintf(stderr, "unix_strtoaddress: %s\n", str ? str : "NULL"));
156     add->sun_family = AF_UNIX;
157     strncpy(add->sun_path, str, sizeof(add->sun_path));
158     cp = strchr (add->sun_path, ':');
159     if (cp)
160         *cp = '\0';
161     return 1;
162 }
163
164 static void *unix_straddr(COMSTACK h, const char *str)
165 {
166     unix_state *sp = (unix_state *)h->cprivate;
167
168     TRC(fprintf(stderr, "unix_straddr: %s\n", str ? str : "NULL"));
169
170     if (!unix_strtoaddr_ex (str, &sp->addr))
171         return 0;
172     return &sp->addr;
173 }
174
175 struct sockaddr_un *unix_strtoaddr(const char *str)
176 {
177     static struct sockaddr_un add;
178
179     TRC(fprintf(stderr, "unix_strtoaddr: %s\n", str ? str : "NULL"));
180
181     if (!unix_strtoaddr_ex (str, &add))
182         return 0;
183     return &add;
184 }
185
186 static int unix_more(COMSTACK h)
187 {
188     unix_state *sp = (unix_state *)h->cprivate;
189
190     return sp->altlen && (*sp->complete)((unsigned char *) sp->altbuf,
191                                          sp->altlen);
192 }
193
194 /*
195  * connect(2) will block (sometimes) - nothing we can do short of doing
196  * weird things like spawning subprocesses or threading or some weird junk
197  * like that.
198  */
199 static int unix_connect(COMSTACK h, void *address)
200 {
201     struct sockaddr_un *add = (struct sockaddr_un *)address;
202     int r;
203
204     TRC(fprintf(stderr, "unix_connect\n"));
205     h->io_pending = 0;
206     if (h->state != CS_ST_UNBND)
207     {
208         h->cerrno = CSOUTSTATE;
209         return -1;
210     }
211     r = connect(h->iofile, (struct sockaddr *) add, SUN_LEN(add));
212     if (r < 0)
213     {
214         if (yaz_errno() == EINPROGRESS)
215         {
216             h->event = CS_CONNECT;
217             h->state = CS_ST_CONNECTING;
218             h->io_pending = CS_WANT_WRITE|CS_WANT_READ;
219             return 1;
220         }
221         h->cerrno = CSYSERR;
222         return -1;
223     }
224     h->event = CS_CONNECT;
225     h->state = CS_ST_CONNECTING;
226
227     return unix_rcvconnect (h);
228 }
229
230 /*
231  * nop
232  */
233 static int unix_rcvconnect(COMSTACK h)
234 {
235     TRC(fprintf(stderr, "unix_rcvconnect\n"));
236
237     if (h->state == CS_ST_DATAXFER)
238         return 0;
239     if (h->state != CS_ST_CONNECTING)
240     {
241         h->cerrno = CSOUTSTATE;
242         return -1;
243     }
244     h->event = CS_DATA;
245     h->state = CS_ST_DATAXFER;
246     return 0;
247 }
248
249 #define CERTF "ztest.pem"
250 #define KEYF "ztest.pem"
251
252 static int unix_bind(COMSTACK h, void *address, int mode)
253 {
254     struct sockaddr *addr = (struct sockaddr *)address;
255     const char * path = ((struct sockaddr_un *)addr)->sun_path;
256     struct stat stat_buf;
257
258     TRC (fprintf (stderr, "unix_bind\n"));
259
260     if(stat(path, &stat_buf) != -1) {
261         struct sockaddr_un socket_unix;
262         int socket_out = -1;
263         if(! S_ISSOCK(stat_buf.st_mode)) {
264             h->cerrno = CSYSERR;
265             yaz_set_errno(EEXIST); /* Not a socket (File exists) */
266             return -1;
267         }
268         if((socket_out = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
269             h->cerrno = CSYSERR;
270             return -1;
271         }
272         socket_unix.sun_family = AF_UNIX;
273         strncpy(socket_unix.sun_path, path, sizeof(socket_unix.sun_path));
274         if(connect(socket_out, (struct sockaddr *) &socket_unix, SUN_LEN(&socket_unix)) < 0) {
275             if(yaz_errno() == ECONNREFUSED) {
276                 TRC (fprintf (stderr, "Socket exists but nobody is listening\n"));
277             } else {
278                 h->cerrno = CSYSERR;
279                 return -1;
280             }
281         } else {
282             close(socket_out);
283             h->cerrno = CSYSERR;
284             yaz_set_errno(EADDRINUSE);
285             return -1;
286         }
287         unlink(path);
288     }
289
290     if (bind(h->iofile, (struct sockaddr *) addr, SUN_LEN((struct sockaddr_un *)addr)))
291     {
292         h->cerrno = CSYSERR;
293         return -1;
294     }
295     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
296     {
297         h->cerrno = CSYSERR;
298         return -1;
299     }
300     h->state = CS_ST_IDLE;
301     h->event = CS_LISTEN;
302     return 0;
303 }
304
305 static int unix_listen(COMSTACK h, char *raddr, int *addrlen,
306                     int (*check_ip)(void *cd, const char *a, int len, int t),
307                     void *cd)
308 {
309     struct sockaddr_un addr;
310     YAZ_SOCKLEN_T len = SUN_LEN(&addr);
311
312     TRC(fprintf(stderr, "unix_listen pid=%d\n", getpid()));
313     if (h->state != CS_ST_IDLE)
314     {
315         h->cerrno = CSOUTSTATE;
316         return -1;
317     }
318     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
319     if (h->newfd < 0)
320     {
321         if (
322             yaz_errno() == EWOULDBLOCK
323 #ifdef EAGAIN
324 #if EAGAIN != EWOULDBLOCK
325             || yaz_errno() == EAGAIN
326 #endif
327 #endif
328             )
329             h->cerrno = CSNODATA;
330         else
331             h->cerrno = CSYSERR;
332         return -1;
333     }
334     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_un))
335         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_un));
336     else if (addrlen)
337         *addrlen = 0;
338     h->state = CS_ST_INCON;
339     return 0;
340 }
341
342 static COMSTACK unix_accept(COMSTACK h)
343 {
344     COMSTACK cnew;
345     unix_state *state, *st = (unix_state *)h->cprivate;
346
347     TRC(fprintf(stderr, "unix_accept\n"));
348     if (h->state == CS_ST_INCON)
349     {
350         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
351         {
352             h->cerrno = CSYSERR;
353             close(h->newfd);
354             h->newfd = -1;
355             return 0;
356         }
357         memcpy(cnew, h, sizeof(*h));
358         cnew->iofile = h->newfd;
359         cnew->io_pending = 0;
360         if (!(state = (unix_state *)
361               (cnew->cprivate = xmalloc(sizeof(unix_state)))))
362         {
363             h->cerrno = CSYSERR;
364             if (h->newfd != -1)
365             {
366                 close(h->newfd);
367                 h->newfd = -1;
368             }
369             return 0;
370         }
371         if (!cnew->blocking &&
372             (!cnew->blocking && fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
373             )
374         {
375             h->cerrno = CSYSERR;
376             if (h->newfd != -1)
377             {
378                 close(h->newfd);
379                 h->newfd = -1;
380             }
381             xfree (cnew);
382             xfree (state);
383             return 0;
384         }
385         h->newfd = -1;
386         state->altbuf = 0;
387         state->altsize = state->altlen = 0;
388         state->towrite = state->written = -1;
389         state->complete = st->complete;
390         cnew->state = CS_ST_ACCEPT;
391         cnew->event = CS_NONE;
392         h->state = CS_ST_IDLE;
393
394         h = cnew;
395     }
396     if (h->state == CS_ST_ACCEPT)
397     {
398     }
399     else
400     {
401         h->cerrno = CSOUTSTATE;
402         return 0;
403     }
404     h->io_pending = 0;
405     h->state = CS_ST_DATAXFER;
406     h->event = CS_DATA;
407     return h;
408 }
409
410 #define CS_UNIX_BUFCHUNK 4096
411
412 /*
413  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
414  * 0=connection closed.
415  */
416 static int unix_get(COMSTACK h, char **buf, int *bufsize)
417 {
418     unix_state *sp = (unix_state *)h->cprivate;
419     char *tmpc;
420     int tmpi, berlen, rest, req, tomove;
421     int hasread = 0, res;
422
423     TRC(fprintf(stderr, "unix_get: bufsize=%d\n", *bufsize));
424     if (sp->altlen) /* switch buffers */
425     {
426         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
427                     (unsigned) sp->altbuf));
428         tmpc = *buf;
429         tmpi = *bufsize;
430         *buf = sp->altbuf;
431         *bufsize = sp->altsize;
432         hasread = sp->altlen;
433         sp->altlen = 0;
434         sp->altbuf = tmpc;
435         sp->altsize = tmpi;
436     }
437     h->io_pending = 0;
438     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
439     {
440         if (!*bufsize)
441         {
442             if (!(*buf = (char *)xmalloc(*bufsize = CS_UNIX_BUFCHUNK)))
443                 return -1;
444         }
445         else if (*bufsize - hasread < CS_UNIX_BUFCHUNK)
446             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
447                 return -1;
448         res = recv(h->iofile, *buf + hasread, CS_UNIX_BUFCHUNK, 0);
449         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
450         if (res < 0)
451         {
452             if (yaz_errno() == EWOULDBLOCK
453 #ifdef EAGAIN
454 #if EAGAIN != EWOULDBLOCK
455                 || yaz_errno() == EAGAIN
456 #endif
457 #endif
458                 || yaz_errno() == EINPROGRESS
459                 )
460             {
461                 h->io_pending = CS_WANT_READ;
462                 break;
463             }
464             else if (yaz_errno() == 0)
465                 continue;
466             else
467                 return -1;
468         }
469         else if (!res)
470             return 0;
471         hasread += res;
472     }
473     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
474                   hasread, berlen));
475     /* move surplus buffer (or everything if we didn't get a BER rec.) */
476     if (hasread > berlen)
477     {
478         tomove = req = hasread - berlen;
479         rest = tomove % CS_UNIX_BUFCHUNK;
480         if (rest)
481             req += CS_UNIX_BUFCHUNK - rest;
482         if (!sp->altbuf)
483         {
484             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
485                 return -1;
486         } else if (sp->altsize < req)
487             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
488                 return -1;
489         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
490                     (unsigned) sp->altbuf));
491         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
492     }
493     if (berlen < CS_UNIX_BUFCHUNK - 1)
494         *(*buf + berlen) = '\0';
495     return berlen ? berlen : 1;
496 }
497
498
499
500 /*
501  * Returns 1, 0 or -1
502  * In nonblocking mode, you must call again with same buffer while
503  * return value is 1.
504  */
505 static int unix_put(COMSTACK h, char *buf, int size)
506 {
507     int res;
508     struct unix_state *state = (struct unix_state *)h->cprivate;
509
510     TRC(fprintf(stderr, "unix_put: size=%d\n", size));
511     h->io_pending = 0;
512     h->event = CS_DATA;
513     if (state->towrite < 0)
514     {
515         state->towrite = size;
516         state->written = 0;
517     }
518     else if (state->towrite != size)
519     {
520         h->cerrno = CSWRONGBUF;
521         return -1;
522     }
523     while (state->towrite > state->written)
524     {
525         if ((res =
526              send(h->iofile, buf + state->written, size -
527                   state->written,
528 #ifdef MSG_NOSIGNAL
529                   MSG_NOSIGNAL
530 #else
531                   0
532 #endif
533                  )) < 0)
534         {
535             if (
536                 yaz_errno() == EWOULDBLOCK
537 #ifdef EAGAIN
538 #if EAGAIN != EWOULDBLOCK
539                 || yaz_errno() == EAGAIN
540 #endif
541 #endif
542                 )
543             {
544                 TRC(fprintf(stderr, "  Flow control stop\n"));
545                 h->io_pending = CS_WANT_WRITE;
546                 return 1;
547             }
548             h->cerrno = CSYSERR;
549             return -1;
550         }
551         state->written += res;
552         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
553                     res, state->written, size));
554     }
555     state->towrite = state->written = -1;
556     TRC(fprintf(stderr, "  Ok\n"));
557     return 0;
558 }
559
560 static int unix_close(COMSTACK h)
561 {
562     unix_state *sp = (struct unix_state *)h->cprivate;
563
564     TRC(fprintf(stderr, "unix_close\n"));
565     if (h->iofile != -1)
566     {
567         close(h->iofile);
568     }
569     if (sp->altbuf)
570         xfree(sp->altbuf);
571     xfree(sp);
572     xfree(h);
573     return 0;
574 }
575
576 static char *unix_addrstr(COMSTACK h)
577 {
578     unix_state *sp = (struct unix_state *)h->cprivate;
579     char *buf = sp->buf;
580     sprintf(buf, "unix:%s", sp->addr.sun_path);
581     return buf;
582 }
583
584 static int unix_set_blocking(COMSTACK p, int blocking)
585 {
586     unsigned long flag;
587
588     if (p->blocking == blocking)
589         return 1;
590     flag = fcntl(p->iofile, F_GETFL, 0);
591     if(!blocking)
592         flag = flag & ~O_NONBLOCK;
593     else
594         flag = flag | O_NONBLOCK;
595     if (fcntl(p->iofile, F_SETFL, flag) < 0)
596         return 0;
597     p->blocking = blocking;
598     return 1;
599 }
600 #endif