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