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