Fix several compile warnings
[yaz-moved-to-github.git] / src / unix.c
1 /*
2  * Copyright (c) 1995-2003, Index Data
3  * See the file LICENSE for details.
4  *
5  * $Id: unix.c,v 1.3 2003-12-30 00:29:53 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 #define CERTF "ztest.pem"
347 #define KEYF "ztest.pem"
348
349 static int unix_bind(COMSTACK h, void *address, int mode)
350 {
351     unix_state *sp = (unix_state *)h->cprivate;
352     struct sockaddr *addr = (struct sockaddr *)address;
353     const char * path = ((struct sockaddr_un *)addr)->sun_path;
354     struct stat stat_buf;
355
356     TRC (fprintf (stderr, "unix_bind\n"));
357
358     if(stat(path, &stat_buf) != -1) {
359         struct sockaddr_un socket_unix;
360         int socket_out = -1;
361         if(! S_ISSOCK(stat_buf.st_mode)) {
362             h->cerrno = CSYSERR;
363             yaz_set_errno(EEXIST); /* Not a socket (File exists) */
364             return -1;
365         }
366         if((socket_out = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
367             h->cerrno = CSYSERR;
368             return -1;
369         }
370         socket_unix.sun_family = AF_UNIX;
371         strncpy(socket_unix.sun_path, path, sizeof(socket_unix.sun_path));
372         if(connect(socket_out, (struct sockaddr *) &socket_unix, SUN_LEN(&socket_unix)) < 0) {
373             if(yaz_errno() == ECONNREFUSED) {
374                 TRC (fprintf (stderr, "Socket exists but nobody is listening\n"));
375             } else {
376                 h->cerrno = CSYSERR;
377                 return -1;
378             }
379         } else {
380             close(socket_out);
381             h->cerrno = CSYSERR;
382             yaz_set_errno(EADDRINUSE);
383             return -1;
384         }
385         unlink(path);
386     }
387
388     if (bind(h->iofile, (struct sockaddr *) addr, SUN_LEN((struct sockaddr_un *)addr)))
389     {
390         h->cerrno = CSYSERR;
391         return -1;
392     }
393     chown(path, sp->uid, sp->gid);
394     chmod(path, sp->umask != -1 ? sp->umask : 0666);
395     if (mode == CS_SERVER && listen(h->iofile, 3) < 0)
396     {
397         h->cerrno = CSYSERR;
398         return -1;
399     }
400     h->state = CS_ST_IDLE;
401     h->event = CS_LISTEN;
402     return 0;
403 }
404
405 static int unix_listen(COMSTACK h, char *raddr, int *addrlen,
406                     int (*check_ip)(void *cd, const char *a, int len, int t),
407                     void *cd)
408 {
409     struct sockaddr_un addr;
410     YAZ_SOCKLEN_T len = sizeof(addr);
411
412     TRC(fprintf(stderr, "unix_listen pid=%d\n", getpid()));
413     if (h->state != CS_ST_IDLE)
414     {
415         h->cerrno = CSOUTSTATE;
416         return -1;
417     }
418     h->newfd = accept(h->iofile, (struct sockaddr*)&addr, &len);
419     if (h->newfd < 0)
420     {
421         if (
422             yaz_errno() == EWOULDBLOCK
423 #ifdef EAGAIN
424 #if EAGAIN != EWOULDBLOCK
425             || yaz_errno() == EAGAIN
426 #endif
427 #endif
428             )
429             h->cerrno = CSNODATA;
430         else
431             h->cerrno = CSYSERR;
432         return -1;
433     }
434     if (addrlen && (size_t) (*addrlen) >= sizeof(struct sockaddr_un))
435         memcpy(raddr, &addr, *addrlen = sizeof(struct sockaddr_un));
436     else if (addrlen)
437         *addrlen = 0;
438     h->state = CS_ST_INCON;
439     return 0;
440 }
441
442 static COMSTACK unix_accept(COMSTACK h)
443 {
444     COMSTACK cnew;
445     unix_state *state, *st = (unix_state *)h->cprivate;
446
447     TRC(fprintf(stderr, "unix_accept\n"));
448     if (h->state == CS_ST_INCON)
449     {
450         if (!(cnew = (COMSTACK)xmalloc(sizeof(*cnew))))
451         {
452             h->cerrno = CSYSERR;
453             close(h->newfd);
454             h->newfd = -1;
455             return 0;
456         }
457         memcpy(cnew, h, sizeof(*h));
458         cnew->iofile = h->newfd;
459         cnew->io_pending = 0;
460         if (!(state = (unix_state *)
461               (cnew->cprivate = xmalloc(sizeof(unix_state)))))
462         {
463             h->cerrno = CSYSERR;
464             if (h->newfd != -1)
465             {
466                 close(h->newfd);
467                 h->newfd = -1;
468             }
469             return 0;
470         }
471         if (!(cnew->blocking&1) && 
472             (fcntl(cnew->iofile, F_SETFL, O_NONBLOCK) < 0)
473             )
474         {
475             h->cerrno = CSYSERR;
476             if (h->newfd != -1)
477             {
478                 close(h->newfd);
479                 h->newfd = -1;
480             }
481             xfree (cnew);
482             xfree (state);
483             return 0;
484         }
485         h->newfd = -1;
486         state->altbuf = 0;
487         state->altsize = state->altlen = 0;
488         state->towrite = state->written = -1;
489         state->complete = st->complete;
490         memcpy(&state->addr, &st->addr, sizeof(state->addr));
491         cnew->state = CS_ST_ACCEPT;
492         cnew->event = CS_NONE;
493         h->state = CS_ST_IDLE;
494
495         h = cnew;
496     }
497     if (h->state == CS_ST_ACCEPT)
498     {
499     }
500     else
501     {
502         h->cerrno = CSOUTSTATE;
503         return 0;
504     }
505     h->io_pending = 0;
506     h->state = CS_ST_DATAXFER;
507     h->event = CS_DATA;
508     return h;
509 }
510
511 #define CS_UNIX_BUFCHUNK 4096
512
513 /*
514  * Return: -1 error, >1 good, len of buffer, ==1 incomplete buffer,
515  * 0=connection closed.
516  */
517 static int unix_get(COMSTACK h, char **buf, int *bufsize)
518 {
519     unix_state *sp = (unix_state *)h->cprivate;
520     char *tmpc;
521     int tmpi, berlen, rest, req, tomove;
522     int hasread = 0, res;
523
524     TRC(fprintf(stderr, "unix_get: bufsize=%d\n", *bufsize));
525     if (sp->altlen) /* switch buffers */
526     {
527         TRC(fprintf(stderr, "  %d bytes in altbuf (0x%x)\n", sp->altlen,
528                     (unsigned) sp->altbuf));
529         tmpc = *buf;
530         tmpi = *bufsize;
531         *buf = sp->altbuf;
532         *bufsize = sp->altsize;
533         hasread = sp->altlen;
534         sp->altlen = 0;
535         sp->altbuf = tmpc;
536         sp->altsize = tmpi;
537     }
538     h->io_pending = 0;
539     while (!(berlen = (*sp->complete)((unsigned char *)*buf, hasread)))
540     {
541         if (!*bufsize)
542         {
543             if (!(*buf = (char *)xmalloc(*bufsize = CS_UNIX_BUFCHUNK)))
544                 return -1;
545         }
546         else if (*bufsize - hasread < CS_UNIX_BUFCHUNK)
547             if (!(*buf =(char *)xrealloc(*buf, *bufsize *= 2)))
548                 return -1;
549         res = recv(h->iofile, *buf + hasread, CS_UNIX_BUFCHUNK, 0);
550         TRC(fprintf(stderr, "  recv res=%d, hasread=%d\n", res, hasread));
551         if (res < 0)
552         {
553             if (yaz_errno() == EWOULDBLOCK
554 #ifdef EAGAIN
555 #if EAGAIN != EWOULDBLOCK
556                 || yaz_errno() == EAGAIN
557 #endif
558 #endif
559                 || yaz_errno() == EINPROGRESS
560                 )
561             {
562                 h->io_pending = CS_WANT_READ;
563                 break;
564             }
565             else if (yaz_errno() == 0)
566                 continue;
567             else
568                 return -1;
569         }
570         else if (!res)
571             return 0;
572         hasread += res;
573     }
574     TRC (fprintf (stderr, "  Out of read loop with hasread=%d, berlen=%d\n",
575                   hasread, berlen));
576     /* move surplus buffer (or everything if we didn't get a BER rec.) */
577     if (hasread > berlen)
578     {
579         tomove = req = hasread - berlen;
580         rest = tomove % CS_UNIX_BUFCHUNK;
581         if (rest)
582             req += CS_UNIX_BUFCHUNK - rest;
583         if (!sp->altbuf)
584         {
585             if (!(sp->altbuf = (char *)xmalloc(sp->altsize = req)))
586                 return -1;
587         } else if (sp->altsize < req)
588             if (!(sp->altbuf =(char *)xrealloc(sp->altbuf, sp->altsize = req)))
589                 return -1;
590         TRC(fprintf(stderr, "  Moving %d bytes to altbuf(0x%x)\n", tomove,
591                     (unsigned) sp->altbuf));
592         memcpy(sp->altbuf, *buf + berlen, sp->altlen = tomove);
593     }
594     if (berlen < CS_UNIX_BUFCHUNK - 1)
595         *(*buf + berlen) = '\0';
596     return berlen ? berlen : 1;
597 }
598
599
600
601 /*
602  * Returns 1, 0 or -1
603  * In nonblocking mode, you must call again with same buffer while
604  * return value is 1.
605  */
606 static int unix_put(COMSTACK h, char *buf, int size)
607 {
608     int res;
609     struct unix_state *state = (struct unix_state *)h->cprivate;
610
611     TRC(fprintf(stderr, "unix_put: size=%d\n", size));
612     h->io_pending = 0;
613     h->event = CS_DATA;
614     if (state->towrite < 0)
615     {
616         state->towrite = size;
617         state->written = 0;
618     }
619     else if (state->towrite != size)
620     {
621         h->cerrno = CSWRONGBUF;
622         return -1;
623     }
624     while (state->towrite > state->written)
625     {
626         if ((res =
627              send(h->iofile, buf + state->written, size -
628                   state->written,
629 #ifdef MSG_NOSIGNAL
630                   MSG_NOSIGNAL
631 #else
632                   0
633 #endif
634                  )) < 0)
635         {
636             if (
637                 yaz_errno() == EWOULDBLOCK
638 #ifdef EAGAIN
639 #if EAGAIN != EWOULDBLOCK
640                 || yaz_errno() == EAGAIN
641 #endif
642 #endif
643                 )
644             {
645                 TRC(fprintf(stderr, "  Flow control stop\n"));
646                 h->io_pending = CS_WANT_WRITE;
647                 return 1;
648             }
649             h->cerrno = CSYSERR;
650             return -1;
651         }
652         state->written += res;
653         TRC(fprintf(stderr, "  Wrote %d, written=%d, nbytes=%d\n",
654                     res, state->written, size));
655     }
656     state->towrite = state->written = -1;
657     TRC(fprintf(stderr, "  Ok\n"));
658     return 0;
659 }
660
661 static int unix_close(COMSTACK h)
662 {
663     unix_state *sp = (struct unix_state *)h->cprivate;
664
665     TRC(fprintf(stderr, "unix_close\n"));
666     if (h->iofile != -1)
667     {
668         close(h->iofile);
669     }
670     if (sp->altbuf)
671         xfree(sp->altbuf);
672     xfree(sp);
673     xfree(h);
674     return 0;
675 }
676
677 static char *unix_addrstr(COMSTACK h)
678 {
679     unix_state *sp = (struct unix_state *)h->cprivate;
680     char *buf = sp->buf;
681     sprintf(buf, "unix:%s", sp->addr.sun_path);
682     return buf;
683 }
684
685 static int unix_set_blocking(COMSTACK p, int blocking)
686 {
687     unsigned long flag;
688
689     if (p->blocking == blocking)
690         return 1;
691     flag = fcntl(p->iofile, F_GETFL, 0);
692     if(!blocking)
693         flag = flag & ~O_NONBLOCK;
694     else
695         flag = flag | O_NONBLOCK;
696     if (fcntl(p->iofile, F_SETFL, flag) < 0)
697         return 0;
698     p->blocking = blocking;
699     return 1;
700 }
701 #endif