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