13680ec0c54793d71cc8bbb0d777f3f84155a9db
[ira/wip.git] / lib / tsocket / tsocket_bsd.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher 2009
5
6      ** NOTE! The following LGPL license applies to the tsocket
7      ** library. This does NOT imply that all of Samba is released
8      ** under the LGPL
9
10    This library is free software; you can redistribute it and/or
11    modify it under the terms of the GNU Lesser General Public
12    License as published by the Free Software Foundation; either
13    version 3 of the License, or (at your option) any later version.
14
15    This library is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18    Lesser General Public License for more details.
19
20    You should have received a copy of the GNU Lesser General Public
21    License along with this library; if not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "replace.h"
25 #include "system/filesys.h"
26 #include "system/network.h"
27 #include "tsocket.h"
28 #include "tsocket_internal.h"
29
30 static int tsocket_bsd_error_from_errno(int ret,
31                                         int sys_errno,
32                                         bool *retry)
33 {
34         *retry = false;
35
36         if (ret >= 0) {
37                 return 0;
38         }
39
40         if (ret != -1) {
41                 return EIO;
42         }
43
44         if (sys_errno == 0) {
45                 return EIO;
46         }
47
48         if (sys_errno == EINTR) {
49                 *retry = true;
50                 return sys_errno;
51         }
52
53         if (sys_errno == EINPROGRESS) {
54                 *retry = true;
55                 return sys_errno;
56         }
57
58         if (sys_errno == EAGAIN) {
59                 *retry = true;
60                 return sys_errno;
61         }
62
63 #ifdef EWOULDBLOCK
64         if (sys_errno == EWOULDBLOCK) {
65                 *retry = true;
66                 return sys_errno;
67         }
68 #endif
69
70         return sys_errno;
71 }
72
73 static int tsocket_bsd_common_prepare_fd(int fd, bool high_fd)
74 {
75         int i;
76         int sys_errno = 0;
77         int fds[3];
78         int num_fds = 0;
79
80         int result, flags;
81
82         if (fd == -1) {
83                 return -1;
84         }
85
86         /* first make a fd >= 3 */
87         if (high_fd) {
88                 while (fd < 3) {
89                         fds[num_fds++] = fd;
90                         fd = dup(fd);
91                         if (fd == -1) {
92                                 sys_errno = errno;
93                                 break;
94                         }
95                 }
96                 for (i=0; i<num_fds; i++) {
97                         close(fds[i]);
98                 }
99                 if (fd == -1) {
100                         errno = sys_errno;
101                         return fd;
102                 }
103         }
104
105         /* fd should be nonblocking. */
106
107 #ifdef O_NONBLOCK
108 #define FLAG_TO_SET O_NONBLOCK
109 #else
110 #ifdef SYSV
111 #define FLAG_TO_SET O_NDELAY
112 #else /* BSD */
113 #define FLAG_TO_SET FNDELAY
114 #endif
115 #endif
116
117         if ((flags = fcntl(fd, F_GETFL)) == -1) {
118                 goto fail;
119         }
120
121         flags |= FLAG_TO_SET;
122         if (fcntl(fd, F_SETFL, flags) == -1) {
123                 goto fail;
124         }
125
126 #undef FLAG_TO_SET
127
128         /* fd should be closed on exec() */
129 #ifdef FD_CLOEXEC
130         result = flags = fcntl(fd, F_GETFD, 0);
131         if (flags >= 0) {
132                 flags |= FD_CLOEXEC;
133                 result = fcntl(fd, F_SETFD, flags);
134         }
135         if (result < 0) {
136                 goto fail;
137         }
138 #endif
139         return fd;
140
141  fail:
142         if (fd != -1) {
143                 sys_errno = errno;
144                 close(fd);
145                 errno = sys_errno;
146         }
147         return -1;
148 }
149
150 static ssize_t tsocket_bsd_pending(int fd)
151 {
152         int ret, error;
153         int value = 0;
154         socklen_t len;
155
156         ret = ioctl(fd, FIONREAD, &value);
157         if (ret == -1) {
158                 return ret;
159         }
160
161         if (ret != 0) {
162                 /* this should not be reached */
163                 errno = EIO;
164                 return -1;
165         }
166
167         if (value != 0) {
168                 return value;
169         }
170
171         error = 0;
172         len = sizeof(error);
173
174         /*
175          * if no data is available check if the socket is in error state. For
176          * dgram sockets it's the way to return ICMP error messages of
177          * connected sockets to the caller.
178          */
179         ret = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len);
180         if (ret == -1) {
181                 return ret;
182         }
183         if (error != 0) {
184                 errno = error;
185                 return -1;
186         }
187         return 0;
188 }
189
190 static const struct tsocket_address_ops tsocket_address_bsd_ops;
191
192 struct tsocket_address_bsd {
193         union {
194                 struct sockaddr sa;
195                 struct sockaddr_in in;
196 #ifdef HAVE_IPV6
197                 struct sockaddr_in6 in6;
198 #endif
199                 struct sockaddr_un un;
200                 struct sockaddr_storage ss;
201         } u;
202 };
203
204 int _tsocket_address_bsd_from_sockaddr(TALLOC_CTX *mem_ctx,
205                                        struct sockaddr *sa,
206                                        size_t sa_socklen,
207                                        struct tsocket_address **_addr,
208                                        const char *location)
209 {
210         struct tsocket_address *addr;
211         struct tsocket_address_bsd *bsda;
212
213         if (sa_socklen < sizeof(sa->sa_family)) {
214                 errno = EINVAL;
215                 return -1;
216         }
217
218         switch (sa->sa_family) {
219         case AF_UNIX:
220                 if (sa_socklen > sizeof(struct sockaddr_un)) {
221                         sa_socklen = sizeof(struct sockaddr_un);
222                 }
223                 break;
224         case AF_INET:
225                 if (sa_socklen < sizeof(struct sockaddr_in)) {
226                         errno = EINVAL;
227                         return -1;
228                 }
229                 sa_socklen = sizeof(struct sockaddr_in);
230                 break;
231 #ifdef HAVE_IPV6
232         case AF_INET6:
233                 if (sa_socklen < sizeof(struct sockaddr_in6)) {
234                         errno = EINVAL;
235                         return -1;
236                 }
237                 sa_socklen = sizeof(struct sockaddr_in6);
238                 break;
239 #endif
240         default:
241                 errno = EAFNOSUPPORT;
242                 return -1;
243         }
244
245         if (sa_socklen > sizeof(struct sockaddr_storage)) {
246                 errno = EINVAL;
247                 return -1;
248         }
249
250         addr = tsocket_address_create(mem_ctx,
251                                       &tsocket_address_bsd_ops,
252                                       &bsda,
253                                       struct tsocket_address_bsd,
254                                       location);
255         if (!addr) {
256                 errno = ENOMEM;
257                 return -1;
258         }
259
260         ZERO_STRUCTP(bsda);
261
262         memcpy(&bsda->u.ss, sa, sa_socklen);
263
264         *_addr = addr;
265         return 0;
266 }
267
268 ssize_t tsocket_address_bsd_sockaddr(const struct tsocket_address *addr,
269                                      struct sockaddr *sa,
270                                      size_t sa_socklen)
271 {
272         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
273                                            struct tsocket_address_bsd);
274         ssize_t rlen = 0;
275
276         if (!bsda) {
277                 errno = EINVAL;
278                 return -1;
279         }
280
281         switch (bsda->u.sa.sa_family) {
282         case AF_UNIX:
283                 rlen = sizeof(struct sockaddr_un);
284                 break;
285         case AF_INET:
286                 rlen = sizeof(struct sockaddr_in);
287                 break;
288 #ifdef HAVE_IPV6
289         case AF_INET6:
290                 rlen = sizeof(struct sockaddr_in6);
291                 break;
292 #endif
293         default:
294                 errno = EAFNOSUPPORT;
295                 return -1;
296         }
297
298         if (sa_socklen < rlen) {
299                 errno = EINVAL;
300                 return -1;
301         }
302
303         if (sa_socklen > sizeof(struct sockaddr_storage)) {
304                 memset(sa, 0, sa_socklen);
305                 sa_socklen = sizeof(struct sockaddr_storage);
306         }
307
308         memcpy(sa, &bsda->u.ss, sa_socklen);
309         return rlen;
310 }
311
312 int _tsocket_address_inet_from_strings(TALLOC_CTX *mem_ctx,
313                                        const char *fam,
314                                        const char *addr,
315                                        uint16_t port,
316                                        struct tsocket_address **_addr,
317                                        const char *location)
318 {
319         struct addrinfo hints;
320         struct addrinfo *result = NULL;
321         char port_str[6];
322         int ret;
323
324         ZERO_STRUCT(hints);
325         /*
326          * we use SOCKET_STREAM here to get just one result
327          * back from getaddrinfo().
328          */
329         hints.ai_socktype = SOCK_STREAM;
330         hints.ai_flags = AI_NUMERICHOST | AI_NUMERICSERV;
331
332         if (strcasecmp(fam, "ip") == 0) {
333                 hints.ai_family = AF_UNSPEC;
334                 if (!addr) {
335 #ifdef HAVE_IPV6
336                         addr = "::";
337 #else
338                         addr = "0.0.0.0";
339 #endif
340                 }
341         } else if (strcasecmp(fam, "ipv4") == 0) {
342                 hints.ai_family = AF_INET;
343                 if (!addr) {
344                         addr = "0.0.0.0";
345                 }
346 #ifdef HAVE_IPV6
347         } else if (strcasecmp(fam, "ipv6") == 0) {
348                 hints.ai_family = AF_INET6;
349                 if (!addr) {
350                         addr = "::";
351                 }
352 #endif
353         } else {
354                 errno = EAFNOSUPPORT;
355                 return -1;
356         }
357
358         snprintf(port_str, sizeof(port_str) - 1, "%u", port);
359
360         ret = getaddrinfo(addr, port_str, &hints, &result);
361         if (ret != 0) {
362                 switch (ret) {
363                 case EAI_FAIL:
364                         errno = EINVAL;
365                         break;
366                 }
367                 ret = -1;
368                 goto done;
369         }
370
371         if (result->ai_socktype != SOCK_STREAM) {
372                 errno = EINVAL;
373                 ret = -1;
374                 goto done;
375         }
376
377         ret = _tsocket_address_bsd_from_sockaddr(mem_ctx,
378                                                   result->ai_addr,
379                                                   result->ai_addrlen,
380                                                   _addr,
381                                                   location);
382
383 done:
384         if (result) {
385                 freeaddrinfo(result);
386         }
387         return ret;
388 }
389
390 char *tsocket_address_inet_addr_string(const struct tsocket_address *addr,
391                                        TALLOC_CTX *mem_ctx)
392 {
393         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
394                                            struct tsocket_address_bsd);
395         char addr_str[INET6_ADDRSTRLEN+1];
396         const char *str;
397
398         if (!bsda) {
399                 errno = EINVAL;
400                 return NULL;
401         }
402
403         switch (bsda->u.sa.sa_family) {
404         case AF_INET:
405                 str = inet_ntop(bsda->u.in.sin_family,
406                                 &bsda->u.in.sin_addr,
407                                 addr_str, sizeof(addr_str));
408                 break;
409 #ifdef HAVE_IPV6
410         case AF_INET6:
411                 str = inet_ntop(bsda->u.in6.sin6_family,
412                                 &bsda->u.in6.sin6_addr,
413                                 addr_str, sizeof(addr_str));
414                 break;
415 #endif
416         default:
417                 errno = EINVAL;
418                 return NULL;
419         }
420
421         if (!str) {
422                 return NULL;
423         }
424
425         return talloc_strdup(mem_ctx, str);
426 }
427
428 uint16_t tsocket_address_inet_port(const struct tsocket_address *addr)
429 {
430         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
431                                            struct tsocket_address_bsd);
432         uint16_t port = 0;
433
434         if (!bsda) {
435                 errno = EINVAL;
436                 return 0;
437         }
438
439         switch (bsda->u.sa.sa_family) {
440         case AF_INET:
441                 port = ntohs(bsda->u.in.sin_port);
442                 break;
443 #ifdef HAVE_IPV6
444         case AF_INET6:
445                 port = ntohs(bsda->u.in6.sin6_port);
446                 break;
447 #endif
448         default:
449                 errno = EINVAL;
450                 return 0;
451         }
452
453         return port;
454 }
455
456 int tsocket_address_inet_set_port(struct tsocket_address *addr,
457                                   uint16_t port)
458 {
459         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
460                                            struct tsocket_address_bsd);
461
462         if (!bsda) {
463                 errno = EINVAL;
464                 return -1;
465         }
466
467         switch (bsda->u.sa.sa_family) {
468         case AF_INET:
469                 bsda->u.in.sin_port = htons(port);
470                 break;
471 #ifdef HAVE_IPV6
472         case AF_INET6:
473                 bsda->u.in6.sin6_port = htons(port);
474                 break;
475 #endif
476         default:
477                 errno = EINVAL;
478                 return -1;
479         }
480
481         return 0;
482 }
483
484 int _tsocket_address_unix_from_path(TALLOC_CTX *mem_ctx,
485                                     const char *path,
486                                     struct tsocket_address **_addr,
487                                     const char *location)
488 {
489         struct sockaddr_un un;
490         void *p = &un;
491         int ret;
492
493         if (!path) {
494                 path = "";
495         }
496
497         if (strlen(path) > sizeof(un.sun_path)-1) {
498                 errno = ENAMETOOLONG;
499                 return -1;
500         }
501
502         ZERO_STRUCT(un);
503         un.sun_family = AF_UNIX;
504         strncpy(un.sun_path, path, sizeof(un.sun_path)-1);
505
506         ret = _tsocket_address_bsd_from_sockaddr(mem_ctx,
507                                                  (struct sockaddr *)p,
508                                                  sizeof(un),
509                                                  _addr,
510                                                  location);
511
512         return ret;
513 }
514
515 char *tsocket_address_unix_path(const struct tsocket_address *addr,
516                                 TALLOC_CTX *mem_ctx)
517 {
518         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
519                                            struct tsocket_address_bsd);
520         const char *str;
521
522         if (!bsda) {
523                 errno = EINVAL;
524                 return NULL;
525         }
526
527         switch (bsda->u.sa.sa_family) {
528         case AF_UNIX:
529                 str = bsda->u.un.sun_path;
530                 break;
531         default:
532                 errno = EINVAL;
533                 return NULL;
534         }
535
536         return talloc_strdup(mem_ctx, str);
537 }
538
539 static char *tsocket_address_bsd_string(const struct tsocket_address *addr,
540                                         TALLOC_CTX *mem_ctx)
541 {
542         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
543                                            struct tsocket_address_bsd);
544         char *str;
545         char *addr_str;
546         const char *prefix = NULL;
547         uint16_t port;
548
549         switch (bsda->u.sa.sa_family) {
550         case AF_UNIX:
551                 return talloc_asprintf(mem_ctx, "unix:%s",
552                                        bsda->u.un.sun_path);
553         case AF_INET:
554                 prefix = "ipv4";
555                 break;
556 #ifdef HAVE_IPV6
557         case AF_INET6:
558                 prefix = "ipv6";
559                 break;
560 #endif
561         default:
562                 errno = EINVAL;
563                 return NULL;
564         }
565
566         addr_str = tsocket_address_inet_addr_string(addr, mem_ctx);
567         if (!addr_str) {
568                 return NULL;
569         }
570
571         port = tsocket_address_inet_port(addr);
572
573         str = talloc_asprintf(mem_ctx, "%s:%s:%u",
574                               prefix, addr_str, port);
575         talloc_free(addr_str);
576
577         return str;
578 }
579
580 static struct tsocket_address *tsocket_address_bsd_copy(const struct tsocket_address *addr,
581                                                          TALLOC_CTX *mem_ctx,
582                                                          const char *location)
583 {
584         struct tsocket_address_bsd *bsda = talloc_get_type(addr->private_data,
585                                            struct tsocket_address_bsd);
586         struct tsocket_address *copy;
587         int ret;
588
589         ret = _tsocket_address_bsd_from_sockaddr(mem_ctx,
590                                                  &bsda->u.sa,
591                                                  sizeof(bsda->u.ss),
592                                                  &copy,
593                                                  location);
594         if (ret != 0) {
595                 return NULL;
596         }
597
598         return copy;
599 }
600
601 static const struct tsocket_address_ops tsocket_address_bsd_ops = {
602         .name           = "bsd",
603         .string         = tsocket_address_bsd_string,
604         .copy           = tsocket_address_bsd_copy,
605 };
606
607 struct tdgram_bsd {
608         int fd;
609
610         void *event_ptr;
611         struct tevent_fd *fde;
612
613         void *readable_private;
614         void (*readable_handler)(void *private_data);
615         void *writeable_private;
616         void (*writeable_handler)(void *private_data);
617 };
618
619 static void tdgram_bsd_fde_handler(struct tevent_context *ev,
620                                    struct tevent_fd *fde,
621                                    uint16_t flags,
622                                    void *private_data)
623 {
624         struct tdgram_bsd *bsds = talloc_get_type_abort(private_data,
625                                   struct tdgram_bsd);
626
627         if (flags & TEVENT_FD_WRITE) {
628                 bsds->writeable_handler(bsds->writeable_private);
629                 return;
630         }
631         if (flags & TEVENT_FD_READ) {
632                 if (!bsds->readable_handler) {
633                         TEVENT_FD_NOT_READABLE(bsds->fde);
634                         return;
635                 }
636                 bsds->readable_handler(bsds->readable_private);
637                 return;
638         }
639 }
640
641 static int tdgram_bsd_set_readable_handler(struct tdgram_bsd *bsds,
642                                            struct tevent_context *ev,
643                                            void (*handler)(void *private_data),
644                                            void *private_data)
645 {
646         if (ev == NULL) {
647                 if (handler) {
648                         errno = EINVAL;
649                         return -1;
650                 }
651                 if (!bsds->readable_handler) {
652                         return 0;
653                 }
654                 bsds->readable_handler = NULL;
655                 bsds->readable_private = NULL;
656
657                 return 0;
658         }
659
660         /* read and write must use the same tevent_context */
661         if (bsds->event_ptr != ev) {
662                 if (bsds->readable_handler || bsds->writeable_handler) {
663                         errno = EINVAL;
664                         return -1;
665                 }
666                 bsds->event_ptr = NULL;
667                 TALLOC_FREE(bsds->fde);
668         }
669
670         if (tevent_fd_get_flags(bsds->fde) == 0) {
671                 TALLOC_FREE(bsds->fde);
672
673                 bsds->fde = tevent_add_fd(ev, bsds,
674                                           bsds->fd, TEVENT_FD_READ,
675                                           tdgram_bsd_fde_handler,
676                                           bsds);
677                 if (!bsds->fde) {
678                         errno = ENOMEM;
679                         return -1;
680                 }
681
682                 /* cache the event context we're running on */
683                 bsds->event_ptr = ev;
684         } else if (!bsds->readable_handler) {
685                 TEVENT_FD_READABLE(bsds->fde);
686         }
687
688         bsds->readable_handler = handler;
689         bsds->readable_private = private_data;
690
691         return 0;
692 }
693
694 static int tdgram_bsd_set_writeable_handler(struct tdgram_bsd *bsds,
695                                             struct tevent_context *ev,
696                                             void (*handler)(void *private_data),
697                                             void *private_data)
698 {
699         if (ev == NULL) {
700                 if (handler) {
701                         errno = EINVAL;
702                         return -1;
703                 }
704                 if (!bsds->writeable_handler) {
705                         return 0;
706                 }
707                 bsds->writeable_handler = NULL;
708                 bsds->writeable_private = NULL;
709                 TEVENT_FD_NOT_WRITEABLE(bsds->fde);
710
711                 return 0;
712         }
713
714         /* read and write must use the same tevent_context */
715         if (bsds->event_ptr != ev) {
716                 if (bsds->readable_handler || bsds->writeable_handler) {
717                         errno = EINVAL;
718                         return -1;
719                 }
720                 bsds->event_ptr = NULL;
721                 TALLOC_FREE(bsds->fde);
722         }
723
724         if (tevent_fd_get_flags(bsds->fde) == 0) {
725                 TALLOC_FREE(bsds->fde);
726
727                 bsds->fde = tevent_add_fd(ev, bsds,
728                                           bsds->fd, TEVENT_FD_WRITE,
729                                           tdgram_bsd_fde_handler,
730                                           bsds);
731                 if (!bsds->fde) {
732                         errno = ENOMEM;
733                         return -1;
734                 }
735
736                 /* cache the event context we're running on */
737                 bsds->event_ptr = ev;
738         } else if (!bsds->writeable_handler) {
739                 TEVENT_FD_WRITEABLE(bsds->fde);
740         }
741
742         bsds->writeable_handler = handler;
743         bsds->writeable_private = private_data;
744
745         return 0;
746 }
747
748 struct tdgram_bsd_recvfrom_state {
749         struct tdgram_context *dgram;
750
751         uint8_t *buf;
752         size_t len;
753         struct tsocket_address *src;
754 };
755
756 static int tdgram_bsd_recvfrom_destructor(struct tdgram_bsd_recvfrom_state *state)
757 {
758         struct tdgram_bsd *bsds = tdgram_context_data(state->dgram,
759                                   struct tdgram_bsd);
760
761         tdgram_bsd_set_readable_handler(bsds, NULL, NULL, NULL);
762
763         return 0;
764 }
765
766 static void tdgram_bsd_recvfrom_handler(void *private_data);
767
768 static struct tevent_req *tdgram_bsd_recvfrom_send(TALLOC_CTX *mem_ctx,
769                                         struct tevent_context *ev,
770                                         struct tdgram_context *dgram)
771 {
772         struct tevent_req *req;
773         struct tdgram_bsd_recvfrom_state *state;
774         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
775         int ret;
776
777         req = tevent_req_create(mem_ctx, &state,
778                                 struct tdgram_bsd_recvfrom_state);
779         if (!req) {
780                 return NULL;
781         }
782
783         state->dgram    = dgram;
784         state->buf      = NULL;
785         state->len      = 0;
786         state->src      = NULL;
787
788         talloc_set_destructor(state, tdgram_bsd_recvfrom_destructor);
789
790         if (bsds->fd == -1) {
791                 tevent_req_error(req, ENOTCONN);
792                 goto post;
793         }
794
795         /*
796          * this is a fast path, not waiting for the
797          * socket to become explicit readable gains
798          * about 10%-20% performance in benchmark tests.
799          */
800         tdgram_bsd_recvfrom_handler(req);
801         if (!tevent_req_is_in_progress(req)) {
802                 goto post;
803         }
804
805         ret = tdgram_bsd_set_readable_handler(bsds, ev,
806                                               tdgram_bsd_recvfrom_handler,
807                                               req);
808         if (ret == -1) {
809                 tevent_req_error(req, errno);
810                 goto post;
811         }
812
813         return req;
814
815  post:
816         tevent_req_post(req, ev);
817         return req;
818 }
819
820 static void tdgram_bsd_recvfrom_handler(void *private_data)
821 {
822         struct tevent_req *req = talloc_get_type_abort(private_data,
823                                  struct tevent_req);
824         struct tdgram_bsd_recvfrom_state *state = tevent_req_data(req,
825                                         struct tdgram_bsd_recvfrom_state);
826         struct tdgram_context *dgram = state->dgram;
827         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
828         struct tsocket_address_bsd *bsda;
829         ssize_t ret;
830         struct sockaddr *sa = NULL;
831         socklen_t sa_socklen = 0;
832         int err;
833         bool retry;
834
835         ret = tsocket_bsd_pending(bsds->fd);
836         if (ret == 0) {
837                 /* retry later */
838                 return;
839         }
840         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
841         if (retry) {
842                 /* retry later */
843                 return;
844         }
845         if (tevent_req_error(req, err)) {
846                 return;
847         }
848
849         state->buf = talloc_array(state, uint8_t, ret);
850         if (tevent_req_nomem(state->buf, req)) {
851                 return;
852         }
853         state->len = ret;
854
855         state->src = tsocket_address_create(state,
856                                             &tsocket_address_bsd_ops,
857                                             &bsda,
858                                             struct tsocket_address_bsd,
859                                             __location__ "bsd_recvfrom");
860         if (tevent_req_nomem(state->src, req)) {
861                 return;
862         }
863
864         ZERO_STRUCTP(bsda);
865
866         sa = &bsda->u.sa;
867         sa_socklen = sizeof(bsda->u.ss);
868         /*
869          * for unix sockets we can't use the size of sockaddr_storage
870          * we would get EINVAL
871          */
872         if (bsda->u.sa.sa_family == AF_UNIX) {
873                 sa_socklen = sizeof(bsda->u.un);
874         }
875
876         ret = recvfrom(bsds->fd, state->buf, state->len, 0, sa, &sa_socklen);
877         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
878         if (retry) {
879                 /* retry later */
880                 return;
881         }
882         if (tevent_req_error(req, err)) {
883                 return;
884         }
885
886         if (ret != state->len) {
887                 tevent_req_error(req, EIO);
888                 return;
889         }
890
891         tevent_req_done(req);
892 }
893
894 static ssize_t tdgram_bsd_recvfrom_recv(struct tevent_req *req,
895                                         int *perrno,
896                                         TALLOC_CTX *mem_ctx,
897                                         uint8_t **buf,
898                                         struct tsocket_address **src)
899 {
900         struct tdgram_bsd_recvfrom_state *state = tevent_req_data(req,
901                                         struct tdgram_bsd_recvfrom_state);
902         ssize_t ret;
903
904         ret = tsocket_simple_int_recv(req, perrno);
905         if (ret == 0) {
906                 *buf = talloc_move(mem_ctx, &state->buf);
907                 ret = state->len;
908                 if (src) {
909                         *src = talloc_move(mem_ctx, &state->src);
910                 }
911         }
912
913         tevent_req_received(req);
914         return ret;
915 }
916
917 struct tdgram_bsd_sendto_state {
918         struct tdgram_context *dgram;
919
920         const uint8_t *buf;
921         size_t len;
922         const struct tsocket_address *dst;
923
924         ssize_t ret;
925 };
926
927 static int tdgram_bsd_sendto_destructor(struct tdgram_bsd_sendto_state *state)
928 {
929         struct tdgram_bsd *bsds = tdgram_context_data(state->dgram,
930                                   struct tdgram_bsd);
931
932         tdgram_bsd_set_writeable_handler(bsds, NULL, NULL, NULL);
933
934         return 0;
935 }
936
937 static void tdgram_bsd_sendto_handler(void *private_data);
938
939 static struct tevent_req *tdgram_bsd_sendto_send(TALLOC_CTX *mem_ctx,
940                                                  struct tevent_context *ev,
941                                                  struct tdgram_context *dgram,
942                                                  const uint8_t *buf,
943                                                  size_t len,
944                                                  const struct tsocket_address *dst)
945 {
946         struct tevent_req *req;
947         struct tdgram_bsd_sendto_state *state;
948         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
949         int ret;
950
951         req = tevent_req_create(mem_ctx, &state,
952                                 struct tdgram_bsd_sendto_state);
953         if (!req) {
954                 return NULL;
955         }
956
957         state->dgram    = dgram;
958         state->buf      = buf;
959         state->len      = len;
960         state->dst      = dst;
961         state->ret      = -1;
962
963         talloc_set_destructor(state, tdgram_bsd_sendto_destructor);
964
965         if (bsds->fd == -1) {
966                 tevent_req_error(req, ENOTCONN);
967                 goto post;
968         }
969
970         /*
971          * this is a fast path, not waiting for the
972          * socket to become explicit writeable gains
973          * about 10%-20% performance in benchmark tests.
974          */
975         tdgram_bsd_sendto_handler(req);
976         if (!tevent_req_is_in_progress(req)) {
977                 goto post;
978         }
979
980         ret = tdgram_bsd_set_writeable_handler(bsds, ev,
981                                                tdgram_bsd_sendto_handler,
982                                                req);
983         if (ret == -1) {
984                 tevent_req_error(req, errno);
985                 goto post;
986         }
987
988         return req;
989
990  post:
991         tevent_req_post(req, ev);
992         return req;
993 }
994
995 static void tdgram_bsd_sendto_handler(void *private_data)
996 {
997         struct tevent_req *req = talloc_get_type_abort(private_data,
998                                  struct tevent_req);
999         struct tdgram_bsd_sendto_state *state = tevent_req_data(req,
1000                                         struct tdgram_bsd_sendto_state);
1001         struct tdgram_context *dgram = state->dgram;
1002         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
1003         struct sockaddr *sa = NULL;
1004         socklen_t sa_socklen = 0;
1005         ssize_t ret;
1006         int err;
1007         bool retry;
1008
1009         if (state->dst) {
1010                 struct tsocket_address_bsd *bsda =
1011                         talloc_get_type(state->dst->private_data,
1012                         struct tsocket_address_bsd);
1013
1014                 sa = &bsda->u.sa;
1015                 sa_socklen = sizeof(bsda->u.ss);
1016                 /*
1017                  * for unix sockets we can't use the size of sockaddr_storage
1018                  * we would get EINVAL
1019                  */
1020                 if (bsda->u.sa.sa_family == AF_UNIX) {
1021                         sa_socklen = sizeof(bsda->u.un);
1022                 }
1023         }
1024
1025         ret = sendto(bsds->fd, state->buf, state->len, 0, sa, sa_socklen);
1026         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1027         if (retry) {
1028                 /* retry later */
1029                 return;
1030         }
1031         if (tevent_req_error(req, err)) {
1032                 return;
1033         }
1034
1035         state->ret = ret;
1036
1037         tevent_req_done(req);
1038 }
1039
1040 static ssize_t tdgram_bsd_sendto_recv(struct tevent_req *req, int *perrno)
1041 {
1042         struct tdgram_bsd_sendto_state *state = tevent_req_data(req,
1043                                         struct tdgram_bsd_sendto_state);
1044         ssize_t ret;
1045
1046         ret = tsocket_simple_int_recv(req, perrno);
1047         if (ret == 0) {
1048                 ret = state->ret;
1049         }
1050
1051         tevent_req_received(req);
1052         return ret;
1053 }
1054
1055 struct tdgram_bsd_disconnect_state {
1056         uint8_t __dummy;
1057 };
1058
1059 static struct tevent_req *tdgram_bsd_disconnect_send(TALLOC_CTX *mem_ctx,
1060                                                      struct tevent_context *ev,
1061                                                      struct tdgram_context *dgram)
1062 {
1063         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
1064         struct tevent_req *req;
1065         struct tdgram_bsd_disconnect_state *state;
1066         int ret;
1067         int err;
1068         bool dummy;
1069
1070         req = tevent_req_create(mem_ctx, &state,
1071                                 struct tdgram_bsd_disconnect_state);
1072         if (req == NULL) {
1073                 return NULL;
1074         }
1075
1076         if (bsds->fd == -1) {
1077                 tevent_req_error(req, ENOTCONN);
1078                 goto post;
1079         }
1080
1081         ret = close(bsds->fd);
1082         bsds->fd = -1;
1083         err = tsocket_bsd_error_from_errno(ret, errno, &dummy);
1084         if (tevent_req_error(req, err)) {
1085                 goto post;
1086         }
1087
1088         tevent_req_done(req);
1089 post:
1090         tevent_req_post(req, ev);
1091         return req;
1092 }
1093
1094 static int tdgram_bsd_disconnect_recv(struct tevent_req *req,
1095                                       int *perrno)
1096 {
1097         int ret;
1098
1099         ret = tsocket_simple_int_recv(req, perrno);
1100
1101         tevent_req_received(req);
1102         return ret;
1103 }
1104
1105 static const struct tdgram_context_ops tdgram_bsd_ops = {
1106         .name                   = "bsd",
1107
1108         .recvfrom_send          = tdgram_bsd_recvfrom_send,
1109         .recvfrom_recv          = tdgram_bsd_recvfrom_recv,
1110
1111         .sendto_send            = tdgram_bsd_sendto_send,
1112         .sendto_recv            = tdgram_bsd_sendto_recv,
1113
1114         .disconnect_send        = tdgram_bsd_disconnect_send,
1115         .disconnect_recv        = tdgram_bsd_disconnect_recv,
1116 };
1117
1118 static int tdgram_bsd_destructor(struct tdgram_bsd *bsds)
1119 {
1120         TALLOC_FREE(bsds->fde);
1121         if (bsds->fd != -1) {
1122                 close(bsds->fd);
1123                 bsds->fd = -1;
1124         }
1125         return 0;
1126 }
1127
1128 static int tdgram_bsd_dgram_socket(const struct tsocket_address *local,
1129                                    const struct tsocket_address *remote,
1130                                    bool broadcast,
1131                                    TALLOC_CTX *mem_ctx,
1132                                    struct tdgram_context **_dgram,
1133                                    const char *location)
1134 {
1135         struct tsocket_address_bsd *lbsda =
1136                 talloc_get_type_abort(local->private_data,
1137                 struct tsocket_address_bsd);
1138         struct tsocket_address_bsd *rbsda = NULL;
1139         struct tdgram_context *dgram;
1140         struct tdgram_bsd *bsds;
1141         int fd;
1142         int ret;
1143         bool do_bind = false;
1144         bool do_reuseaddr = false;
1145         bool do_ipv6only = false;
1146         bool is_inet = false;
1147         int sa_fam = lbsda->u.sa.sa_family;
1148         socklen_t sa_socklen = sizeof(lbsda->u.ss);
1149
1150         if (remote) {
1151                 rbsda = talloc_get_type_abort(remote->private_data,
1152                         struct tsocket_address_bsd);
1153         }
1154
1155         switch (lbsda->u.sa.sa_family) {
1156         case AF_UNIX:
1157                 if (broadcast) {
1158                         errno = EINVAL;
1159                         return -1;
1160                 }
1161                 if (lbsda->u.un.sun_path[0] != 0) {
1162                         do_reuseaddr = true;
1163                         do_bind = true;
1164                 }
1165                 /*
1166                  * for unix sockets we can't use the size of sockaddr_storage
1167                  * we would get EINVAL
1168                  */
1169                 sa_socklen = sizeof(lbsda->u.un);
1170                 break;
1171         case AF_INET:
1172                 if (lbsda->u.in.sin_port != 0) {
1173                         do_reuseaddr = true;
1174                         do_bind = true;
1175                 }
1176                 if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) {
1177                         do_bind = true;
1178                 }
1179                 is_inet = true;
1180                 sa_socklen = sizeof(rbsda->u.in);
1181                 break;
1182 #ifdef HAVE_IPV6
1183         case AF_INET6:
1184                 if (lbsda->u.in6.sin6_port != 0) {
1185                         do_reuseaddr = true;
1186                         do_bind = true;
1187                 }
1188                 if (memcmp(&in6addr_any,
1189                            &lbsda->u.in6.sin6_addr,
1190                            sizeof(in6addr_any)) != 0) {
1191                         do_bind = true;
1192                 }
1193                 is_inet = true;
1194                 sa_socklen = sizeof(rbsda->u.in6);
1195                 do_ipv6only = true;
1196                 break;
1197 #endif
1198         default:
1199                 errno = EINVAL;
1200                 return -1;
1201         }
1202
1203         if (!do_bind && is_inet && rbsda) {
1204                 sa_fam = rbsda->u.sa.sa_family;
1205                 switch (sa_fam) {
1206                 case AF_INET:
1207                         sa_socklen = sizeof(rbsda->u.in);
1208                         do_ipv6only = false;
1209                         break;
1210 #ifdef HAVE_IPV6
1211                 case AF_INET6:
1212                         sa_socklen = sizeof(rbsda->u.in6);
1213                         do_ipv6only = true;
1214                         break;
1215 #endif
1216                 }
1217         }
1218
1219         fd = socket(sa_fam, SOCK_DGRAM, 0);
1220         if (fd < 0) {
1221                 return fd;
1222         }
1223
1224         fd = tsocket_bsd_common_prepare_fd(fd, true);
1225         if (fd < 0) {
1226                 return fd;
1227         }
1228
1229         dgram = tdgram_context_create(mem_ctx,
1230                                       &tdgram_bsd_ops,
1231                                       &bsds,
1232                                       struct tdgram_bsd,
1233                                       location);
1234         if (!dgram) {
1235                 int saved_errno = errno;
1236                 close(fd);
1237                 errno = saved_errno;
1238                 return -1;
1239         }
1240         ZERO_STRUCTP(bsds);
1241         bsds->fd = fd;
1242         talloc_set_destructor(bsds, tdgram_bsd_destructor);
1243
1244 #ifdef HAVE_IPV6
1245         if (do_ipv6only) {
1246                 int val = 1;
1247
1248                 ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
1249                                  (const void *)&val, sizeof(val));
1250                 if (ret == -1) {
1251                         int saved_errno = errno;
1252                         talloc_free(dgram);
1253                         errno = saved_errno;
1254                         return ret;
1255                 }
1256         }
1257 #endif
1258
1259         if (broadcast) {
1260                 int val = 1;
1261
1262                 ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
1263                                  (const void *)&val, sizeof(val));
1264                 if (ret == -1) {
1265                         int saved_errno = errno;
1266                         talloc_free(dgram);
1267                         errno = saved_errno;
1268                         return ret;
1269                 }
1270         }
1271
1272         if (do_reuseaddr) {
1273                 int val = 1;
1274
1275                 ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1276                                  (const void *)&val, sizeof(val));
1277                 if (ret == -1) {
1278                         int saved_errno = errno;
1279                         talloc_free(dgram);
1280                         errno = saved_errno;
1281                         return ret;
1282                 }
1283         }
1284
1285         if (do_bind) {
1286                 ret = bind(fd, &lbsda->u.sa, sa_socklen);
1287                 if (ret == -1) {
1288                         int saved_errno = errno;
1289                         talloc_free(dgram);
1290                         errno = saved_errno;
1291                         return ret;
1292                 }
1293         }
1294
1295         if (rbsda) {
1296                 if (rbsda->u.sa.sa_family != sa_fam) {
1297                         talloc_free(dgram);
1298                         errno = EINVAL;
1299                         return -1;
1300                 }
1301
1302                 ret = connect(fd, &rbsda->u.sa, sa_socklen);
1303                 if (ret == -1) {
1304                         int saved_errno = errno;
1305                         talloc_free(dgram);
1306                         errno = saved_errno;
1307                         return ret;
1308                 }
1309         }
1310
1311         *_dgram = dgram;
1312         return 0;
1313 }
1314
1315 int _tdgram_inet_udp_socket(const struct tsocket_address *local,
1316                             const struct tsocket_address *remote,
1317                             TALLOC_CTX *mem_ctx,
1318                             struct tdgram_context **dgram,
1319                             const char *location)
1320 {
1321         struct tsocket_address_bsd *lbsda =
1322                 talloc_get_type_abort(local->private_data,
1323                 struct tsocket_address_bsd);
1324         int ret;
1325
1326         switch (lbsda->u.sa.sa_family) {
1327         case AF_INET:
1328                 break;
1329 #ifdef HAVE_IPV6
1330         case AF_INET6:
1331                 break;
1332 #endif
1333         default:
1334                 errno = EINVAL;
1335                 return -1;
1336         }
1337
1338         ret = tdgram_bsd_dgram_socket(local, remote, false,
1339                                       mem_ctx, dgram, location);
1340
1341         return ret;
1342 }
1343
1344 int _tdgram_unix_socket(const struct tsocket_address *local,
1345                         const struct tsocket_address *remote,
1346                         TALLOC_CTX *mem_ctx,
1347                         struct tdgram_context **dgram,
1348                         const char *location)
1349 {
1350         struct tsocket_address_bsd *lbsda =
1351                 talloc_get_type_abort(local->private_data,
1352                 struct tsocket_address_bsd);
1353         int ret;
1354
1355         switch (lbsda->u.sa.sa_family) {
1356         case AF_UNIX:
1357                 break;
1358         default:
1359                 errno = EINVAL;
1360                 return -1;
1361         }
1362
1363         ret = tdgram_bsd_dgram_socket(local, remote, false,
1364                                       mem_ctx, dgram, location);
1365
1366         return ret;
1367 }
1368
1369 struct tstream_bsd {
1370         int fd;
1371
1372         void *event_ptr;
1373         struct tevent_fd *fde;
1374
1375         void *readable_private;
1376         void (*readable_handler)(void *private_data);
1377         void *writeable_private;
1378         void (*writeable_handler)(void *private_data);
1379 };
1380
1381 static void tstream_bsd_fde_handler(struct tevent_context *ev,
1382                                     struct tevent_fd *fde,
1383                                     uint16_t flags,
1384                                     void *private_data)
1385 {
1386         struct tstream_bsd *bsds = talloc_get_type_abort(private_data,
1387                                    struct tstream_bsd);
1388
1389         if (flags & TEVENT_FD_WRITE) {
1390                 bsds->writeable_handler(bsds->writeable_private);
1391                 return;
1392         }
1393         if (flags & TEVENT_FD_READ) {
1394                 if (!bsds->readable_handler) {
1395                         if (bsds->writeable_handler) {
1396                                 bsds->writeable_handler(bsds->writeable_private);
1397                                 return;
1398                         }
1399                         TEVENT_FD_NOT_READABLE(bsds->fde);
1400                         return;
1401                 }
1402                 bsds->readable_handler(bsds->readable_private);
1403                 return;
1404         }
1405 }
1406
1407 static int tstream_bsd_set_readable_handler(struct tstream_bsd *bsds,
1408                                             struct tevent_context *ev,
1409                                             void (*handler)(void *private_data),
1410                                             void *private_data)
1411 {
1412         if (ev == NULL) {
1413                 if (handler) {
1414                         errno = EINVAL;
1415                         return -1;
1416                 }
1417                 if (!bsds->readable_handler) {
1418                         return 0;
1419                 }
1420                 bsds->readable_handler = NULL;
1421                 bsds->readable_private = NULL;
1422
1423                 return 0;
1424         }
1425
1426         /* read and write must use the same tevent_context */
1427         if (bsds->event_ptr != ev) {
1428                 if (bsds->readable_handler || bsds->writeable_handler) {
1429                         errno = EINVAL;
1430                         return -1;
1431                 }
1432                 bsds->event_ptr = NULL;
1433                 TALLOC_FREE(bsds->fde);
1434         }
1435
1436         if (tevent_fd_get_flags(bsds->fde) == 0) {
1437                 TALLOC_FREE(bsds->fde);
1438
1439                 bsds->fde = tevent_add_fd(ev, bsds,
1440                                           bsds->fd, TEVENT_FD_READ,
1441                                           tstream_bsd_fde_handler,
1442                                           bsds);
1443                 if (!bsds->fde) {
1444                         errno = ENOMEM;
1445                         return -1;
1446                 }
1447
1448                 /* cache the event context we're running on */
1449                 bsds->event_ptr = ev;
1450         } else if (!bsds->readable_handler) {
1451                 TEVENT_FD_READABLE(bsds->fde);
1452         }
1453
1454         bsds->readable_handler = handler;
1455         bsds->readable_private = private_data;
1456
1457         return 0;
1458 }
1459
1460 static int tstream_bsd_set_writeable_handler(struct tstream_bsd *bsds,
1461                                              struct tevent_context *ev,
1462                                              void (*handler)(void *private_data),
1463                                              void *private_data)
1464 {
1465         if (ev == NULL) {
1466                 if (handler) {
1467                         errno = EINVAL;
1468                         return -1;
1469                 }
1470                 if (!bsds->writeable_handler) {
1471                         return 0;
1472                 }
1473                 bsds->writeable_handler = NULL;
1474                 bsds->writeable_private = NULL;
1475                 TEVENT_FD_NOT_WRITEABLE(bsds->fde);
1476
1477                 return 0;
1478         }
1479
1480         /* read and write must use the same tevent_context */
1481         if (bsds->event_ptr != ev) {
1482                 if (bsds->readable_handler || bsds->writeable_handler) {
1483                         errno = EINVAL;
1484                         return -1;
1485                 }
1486                 bsds->event_ptr = NULL;
1487                 TALLOC_FREE(bsds->fde);
1488         }
1489
1490         if (tevent_fd_get_flags(bsds->fde) == 0) {
1491                 TALLOC_FREE(bsds->fde);
1492
1493                 bsds->fde = tevent_add_fd(ev, bsds,
1494                                           bsds->fd,
1495                                           TEVENT_FD_READ | TEVENT_FD_WRITE,
1496                                           tstream_bsd_fde_handler,
1497                                           bsds);
1498                 if (!bsds->fde) {
1499                         errno = ENOMEM;
1500                         return -1;
1501                 }
1502
1503                 /* cache the event context we're running on */
1504                 bsds->event_ptr = ev;
1505         } else if (!bsds->writeable_handler) {
1506                 uint16_t flags = tevent_fd_get_flags(bsds->fde);
1507                 flags |= TEVENT_FD_READ | TEVENT_FD_WRITE;
1508                 tevent_fd_set_flags(bsds->fde, flags);
1509         }
1510
1511         bsds->writeable_handler = handler;
1512         bsds->writeable_private = private_data;
1513
1514         return 0;
1515 }
1516
1517 static ssize_t tstream_bsd_pending_bytes(struct tstream_context *stream)
1518 {
1519         struct tstream_bsd *bsds = tstream_context_data(stream,
1520                                    struct tstream_bsd);
1521         ssize_t ret;
1522
1523         if (bsds->fd == -1) {
1524                 errno = ENOTCONN;
1525                 return -1;
1526         }
1527
1528         ret = tsocket_bsd_pending(bsds->fd);
1529
1530         return ret;
1531 }
1532
1533 struct tstream_bsd_readv_state {
1534         struct tstream_context *stream;
1535
1536         struct iovec *vector;
1537         size_t count;
1538
1539         int ret;
1540 };
1541
1542 static int tstream_bsd_readv_destructor(struct tstream_bsd_readv_state *state)
1543 {
1544         struct tstream_bsd *bsds = tstream_context_data(state->stream,
1545                                    struct tstream_bsd);
1546
1547         tstream_bsd_set_readable_handler(bsds, NULL, NULL, NULL);
1548
1549         return 0;
1550 }
1551
1552 static void tstream_bsd_readv_handler(void *private_data);
1553
1554 static struct tevent_req *tstream_bsd_readv_send(TALLOC_CTX *mem_ctx,
1555                                         struct tevent_context *ev,
1556                                         struct tstream_context *stream,
1557                                         struct iovec *vector,
1558                                         size_t count)
1559 {
1560         struct tevent_req *req;
1561         struct tstream_bsd_readv_state *state;
1562         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1563         int ret;
1564
1565         req = tevent_req_create(mem_ctx, &state,
1566                                 struct tstream_bsd_readv_state);
1567         if (!req) {
1568                 return NULL;
1569         }
1570
1571         state->stream   = stream;
1572         /* we make a copy of the vector so that we can modify it */
1573         state->vector   = talloc_array(state, struct iovec, count);
1574         if (tevent_req_nomem(state->vector, req)) {
1575                 goto post;
1576         }
1577         memcpy(state->vector, vector, sizeof(struct iovec)*count);
1578         state->count    = count;
1579         state->ret      = 0;
1580
1581         talloc_set_destructor(state, tstream_bsd_readv_destructor);
1582
1583         if (bsds->fd == -1) {
1584                 tevent_req_error(req, ENOTCONN);
1585                 goto post;
1586         }
1587
1588         /*
1589          * this is a fast path, not waiting for the
1590          * socket to become explicit readable gains
1591          * about 10%-20% performance in benchmark tests.
1592          */
1593         tstream_bsd_readv_handler(req);
1594         if (!tevent_req_is_in_progress(req)) {
1595                 goto post;
1596         }
1597
1598         ret = tstream_bsd_set_readable_handler(bsds, ev,
1599                                               tstream_bsd_readv_handler,
1600                                               req);
1601         if (ret == -1) {
1602                 tevent_req_error(req, errno);
1603                 goto post;
1604         }
1605
1606         return req;
1607
1608  post:
1609         tevent_req_post(req, ev);
1610         return req;
1611 }
1612
1613 static void tstream_bsd_readv_handler(void *private_data)
1614 {
1615         struct tevent_req *req = talloc_get_type_abort(private_data,
1616                                  struct tevent_req);
1617         struct tstream_bsd_readv_state *state = tevent_req_data(req,
1618                                         struct tstream_bsd_readv_state);
1619         struct tstream_context *stream = state->stream;
1620         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1621         int ret;
1622         int err;
1623         bool retry;
1624
1625         ret = readv(bsds->fd, state->vector, state->count);
1626         if (ret == 0) {
1627                 /* propagate end of file */
1628                 tevent_req_error(req, EPIPE);
1629                 return;
1630         }
1631         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1632         if (retry) {
1633                 /* retry later */
1634                 return;
1635         }
1636         if (tevent_req_error(req, err)) {
1637                 return;
1638         }
1639
1640         state->ret += ret;
1641
1642         while (ret > 0) {
1643                 if (ret < state->vector[0].iov_len) {
1644                         uint8_t *base;
1645                         base = (uint8_t *)state->vector[0].iov_base;
1646                         base += ret;
1647                         state->vector[0].iov_base = base;
1648                         state->vector[0].iov_len -= ret;
1649                         break;
1650                 }
1651                 ret -= state->vector[0].iov_len;
1652                 state->vector += 1;
1653                 state->count -= 1;
1654         }
1655
1656         /*
1657          * there're maybe some empty vectors at the end
1658          * which we need to skip, otherwise we would get
1659          * ret == 0 from the readv() call and return EPIPE
1660          */
1661         while (state->count > 0) {
1662                 if (state->vector[0].iov_len > 0) {
1663                         break;
1664                 }
1665                 state->vector += 1;
1666                 state->count -= 1;
1667         }
1668
1669         if (state->count > 0) {
1670                 /* we have more to read */
1671                 return;
1672         }
1673
1674         tevent_req_done(req);
1675 }
1676
1677 static int tstream_bsd_readv_recv(struct tevent_req *req,
1678                                   int *perrno)
1679 {
1680         struct tstream_bsd_readv_state *state = tevent_req_data(req,
1681                                         struct tstream_bsd_readv_state);
1682         int ret;
1683
1684         ret = tsocket_simple_int_recv(req, perrno);
1685         if (ret == 0) {
1686                 ret = state->ret;
1687         }
1688
1689         tevent_req_received(req);
1690         return ret;
1691 }
1692
1693 struct tstream_bsd_writev_state {
1694         struct tstream_context *stream;
1695
1696         struct iovec *vector;
1697         size_t count;
1698
1699         int ret;
1700 };
1701
1702 static int tstream_bsd_writev_destructor(struct tstream_bsd_writev_state *state)
1703 {
1704         struct tstream_bsd *bsds = tstream_context_data(state->stream,
1705                                   struct tstream_bsd);
1706
1707         tstream_bsd_set_writeable_handler(bsds, NULL, NULL, NULL);
1708
1709         return 0;
1710 }
1711
1712 static void tstream_bsd_writev_handler(void *private_data);
1713
1714 static struct tevent_req *tstream_bsd_writev_send(TALLOC_CTX *mem_ctx,
1715                                                  struct tevent_context *ev,
1716                                                  struct tstream_context *stream,
1717                                                  const struct iovec *vector,
1718                                                  size_t count)
1719 {
1720         struct tevent_req *req;
1721         struct tstream_bsd_writev_state *state;
1722         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1723         int ret;
1724
1725         req = tevent_req_create(mem_ctx, &state,
1726                                 struct tstream_bsd_writev_state);
1727         if (!req) {
1728                 return NULL;
1729         }
1730
1731         state->stream   = stream;
1732         /* we make a copy of the vector so that we can modify it */
1733         state->vector   = talloc_array(state, struct iovec, count);
1734         if (tevent_req_nomem(state->vector, req)) {
1735                 goto post;
1736         }
1737         memcpy(state->vector, vector, sizeof(struct iovec)*count);
1738         state->count    = count;
1739         state->ret      = 0;
1740
1741         talloc_set_destructor(state, tstream_bsd_writev_destructor);
1742
1743         if (bsds->fd == -1) {
1744                 tevent_req_error(req, ENOTCONN);
1745                 goto post;
1746         }
1747
1748         /*
1749          * this is a fast path, not waiting for the
1750          * socket to become explicit writeable gains
1751          * about 10%-20% performance in benchmark tests.
1752          */
1753         tstream_bsd_writev_handler(req);
1754         if (!tevent_req_is_in_progress(req)) {
1755                 goto post;
1756         }
1757
1758         ret = tstream_bsd_set_writeable_handler(bsds, ev,
1759                                                tstream_bsd_writev_handler,
1760                                                req);
1761         if (ret == -1) {
1762                 tevent_req_error(req, errno);
1763                 goto post;
1764         }
1765
1766         return req;
1767
1768  post:
1769         tevent_req_post(req, ev);
1770         return req;
1771 }
1772
1773 static void tstream_bsd_writev_handler(void *private_data)
1774 {
1775         struct tevent_req *req = talloc_get_type_abort(private_data,
1776                                  struct tevent_req);
1777         struct tstream_bsd_writev_state *state = tevent_req_data(req,
1778                                         struct tstream_bsd_writev_state);
1779         struct tstream_context *stream = state->stream;
1780         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1781         ssize_t ret;
1782         int err;
1783         bool retry;
1784
1785         ret = writev(bsds->fd, state->vector, state->count);
1786         if (ret == 0) {
1787                 /* propagate end of file */
1788                 tevent_req_error(req, EPIPE);
1789                 return;
1790         }
1791         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1792         if (retry) {
1793                 /* retry later */
1794                 return;
1795         }
1796         if (tevent_req_error(req, err)) {
1797                 return;
1798         }
1799
1800         state->ret += ret;
1801
1802         while (ret > 0) {
1803                 if (ret < state->vector[0].iov_len) {
1804                         uint8_t *base;
1805                         base = (uint8_t *)state->vector[0].iov_base;
1806                         base += ret;
1807                         state->vector[0].iov_base = base;
1808                         state->vector[0].iov_len -= ret;
1809                         break;
1810                 }
1811                 ret -= state->vector[0].iov_len;
1812                 state->vector += 1;
1813                 state->count -= 1;
1814         }
1815
1816         /*
1817          * there're maybe some empty vectors at the end
1818          * which we need to skip, otherwise we would get
1819          * ret == 0 from the writev() call and return EPIPE
1820          */
1821         while (state->count > 0) {
1822                 if (state->vector[0].iov_len > 0) {
1823                         break;
1824                 }
1825                 state->vector += 1;
1826                 state->count -= 1;
1827         }
1828
1829         if (state->count > 0) {
1830                 /* we have more to read */
1831                 return;
1832         }
1833
1834         tevent_req_done(req);
1835 }
1836
1837 static int tstream_bsd_writev_recv(struct tevent_req *req, int *perrno)
1838 {
1839         struct tstream_bsd_writev_state *state = tevent_req_data(req,
1840                                         struct tstream_bsd_writev_state);
1841         int ret;
1842
1843         ret = tsocket_simple_int_recv(req, perrno);
1844         if (ret == 0) {
1845                 ret = state->ret;
1846         }
1847
1848         tevent_req_received(req);
1849         return ret;
1850 }
1851
1852 struct tstream_bsd_disconnect_state {
1853         void *__dummy;
1854 };
1855
1856 static struct tevent_req *tstream_bsd_disconnect_send(TALLOC_CTX *mem_ctx,
1857                                                      struct tevent_context *ev,
1858                                                      struct tstream_context *stream)
1859 {
1860         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1861         struct tevent_req *req;
1862         struct tstream_bsd_disconnect_state *state;
1863         int ret;
1864         int err;
1865         bool dummy;
1866
1867         req = tevent_req_create(mem_ctx, &state,
1868                                 struct tstream_bsd_disconnect_state);
1869         if (req == NULL) {
1870                 return NULL;
1871         }
1872
1873         if (bsds->fd == -1) {
1874                 tevent_req_error(req, ENOTCONN);
1875                 goto post;
1876         }
1877
1878         ret = close(bsds->fd);
1879         bsds->fd = -1;
1880         err = tsocket_bsd_error_from_errno(ret, errno, &dummy);
1881         if (tevent_req_error(req, err)) {
1882                 goto post;
1883         }
1884
1885         tevent_req_done(req);
1886 post:
1887         tevent_req_post(req, ev);
1888         return req;
1889 }
1890
1891 static int tstream_bsd_disconnect_recv(struct tevent_req *req,
1892                                       int *perrno)
1893 {
1894         int ret;
1895
1896         ret = tsocket_simple_int_recv(req, perrno);
1897
1898         tevent_req_received(req);
1899         return ret;
1900 }
1901
1902 static const struct tstream_context_ops tstream_bsd_ops = {
1903         .name                   = "bsd",
1904
1905         .pending_bytes          = tstream_bsd_pending_bytes,
1906
1907         .readv_send             = tstream_bsd_readv_send,
1908         .readv_recv             = tstream_bsd_readv_recv,
1909
1910         .writev_send            = tstream_bsd_writev_send,
1911         .writev_recv            = tstream_bsd_writev_recv,
1912
1913         .disconnect_send        = tstream_bsd_disconnect_send,
1914         .disconnect_recv        = tstream_bsd_disconnect_recv,
1915 };
1916
1917 static int tstream_bsd_destructor(struct tstream_bsd *bsds)
1918 {
1919         TALLOC_FREE(bsds->fde);
1920         if (bsds->fd != -1) {
1921                 close(bsds->fd);
1922                 bsds->fd = -1;
1923         }
1924         return 0;
1925 }
1926
1927 int _tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx,
1928                                  int fd,
1929                                  struct tstream_context **_stream,
1930                                  const char *location)
1931 {
1932         struct tstream_context *stream;
1933         struct tstream_bsd *bsds;
1934
1935         stream = tstream_context_create(mem_ctx,
1936                                         &tstream_bsd_ops,
1937                                         &bsds,
1938                                         struct tstream_bsd,
1939                                         location);
1940         if (!stream) {
1941                 return -1;
1942         }
1943         ZERO_STRUCTP(bsds);
1944         bsds->fd = fd;
1945         talloc_set_destructor(bsds, tstream_bsd_destructor);
1946
1947         *_stream = stream;
1948         return 0;
1949 }
1950
1951 struct tstream_bsd_connect_state {
1952         int fd;
1953         struct tevent_fd *fde;
1954         struct tstream_conext *stream;
1955 };
1956
1957 static int tstream_bsd_connect_destructor(struct tstream_bsd_connect_state *state)
1958 {
1959         TALLOC_FREE(state->fde);
1960         if (state->fd != -1) {
1961                 close(state->fd);
1962                 state->fd = -1;
1963         }
1964
1965         return 0;
1966 }
1967
1968 static void tstream_bsd_connect_fde_handler(struct tevent_context *ev,
1969                                             struct tevent_fd *fde,
1970                                             uint16_t flags,
1971                                             void *private_data);
1972
1973 static struct tevent_req * tstream_bsd_connect_send(TALLOC_CTX *mem_ctx,
1974                                         struct tevent_context *ev,
1975                                         int sys_errno,
1976                                         const struct tsocket_address *local,
1977                                         const struct tsocket_address *remote)
1978 {
1979         struct tevent_req *req;
1980         struct tstream_bsd_connect_state *state;
1981         struct tsocket_address_bsd *lbsda =
1982                 talloc_get_type_abort(local->private_data,
1983                 struct tsocket_address_bsd);
1984         struct tsocket_address_bsd *rbsda =
1985                 talloc_get_type_abort(remote->private_data,
1986                 struct tsocket_address_bsd);
1987         int ret;
1988         int err;
1989         bool retry;
1990         bool do_bind = false;
1991         bool do_reuseaddr = false;
1992         bool do_ipv6only = false;
1993         bool is_inet = false;
1994         int sa_fam = lbsda->u.sa.sa_family;
1995         socklen_t sa_socklen = sizeof(rbsda->u.ss);
1996
1997         req = tevent_req_create(mem_ctx, &state,
1998                                 struct tstream_bsd_connect_state);
1999         if (!req) {
2000                 return NULL;
2001         }
2002         state->fd = -1;
2003         state->fde = NULL;
2004
2005         talloc_set_destructor(state, tstream_bsd_connect_destructor);
2006
2007         /* give the wrappers a chance to report an error */
2008         if (sys_errno != 0) {
2009                 tevent_req_error(req, sys_errno);
2010                 goto post;
2011         }
2012
2013         switch (lbsda->u.sa.sa_family) {
2014         case AF_UNIX:
2015                 if (lbsda->u.un.sun_path[0] != 0) {
2016                         do_reuseaddr = true;
2017                         do_bind = true;
2018                 }
2019                 /*
2020                  * for unix sockets we can't use the size of sockaddr_storage
2021                  * we would get EINVAL
2022                  */
2023                 sa_socklen = sizeof(rbsda->u.un);
2024                 break;
2025         case AF_INET:
2026                 if (lbsda->u.in.sin_port != 0) {
2027                         do_reuseaddr = true;
2028                         do_bind = true;
2029                 }
2030                 if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) {
2031                         do_bind = true;
2032                 }
2033                 is_inet = true;
2034                 sa_socklen = sizeof(rbsda->u.in);
2035                 break;
2036 #ifdef HAVE_IPV6
2037         case AF_INET6:
2038                 if (lbsda->u.in6.sin6_port != 0) {
2039                         do_reuseaddr = true;
2040                         do_bind = true;
2041                 }
2042                 if (memcmp(&in6addr_any,
2043                            &lbsda->u.in6.sin6_addr,
2044                            sizeof(in6addr_any)) != 0) {
2045                         do_bind = true;
2046                 }
2047                 is_inet = true;
2048                 sa_socklen = sizeof(rbsda->u.in6);
2049                 do_ipv6only = true;
2050                 break;
2051 #endif
2052         default:
2053                 tevent_req_error(req, EINVAL);
2054                 goto post;
2055         }
2056
2057         if (!do_bind && is_inet) {
2058                 sa_fam = rbsda->u.sa.sa_family;
2059                 switch (sa_fam) {
2060                 case AF_INET:
2061                         sa_socklen = sizeof(rbsda->u.in);
2062                         do_ipv6only = false;
2063                         break;
2064 #ifdef HAVE_IPV6
2065                 case AF_INET6:
2066                         sa_socklen = sizeof(rbsda->u.in6);
2067                         do_ipv6only = true;
2068                         break;
2069 #endif
2070                 }
2071         }
2072
2073         state->fd = socket(sa_fam, SOCK_STREAM, 0);
2074         if (state->fd == -1) {
2075                 tevent_req_error(req, errno);
2076                 goto post;
2077         }
2078
2079         state->fd = tsocket_bsd_common_prepare_fd(state->fd, true);
2080         if (state->fd == -1) {
2081                 tevent_req_error(req, errno);
2082                 goto post;
2083         }
2084
2085 #ifdef HAVE_IPV6
2086         if (do_ipv6only) {
2087                 int val = 1;
2088
2089                 ret = setsockopt(state->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2090                                  (const void *)&val, sizeof(val));
2091                 if (ret == -1) {
2092                         tevent_req_error(req, errno);
2093                         goto post;
2094                 }
2095         }
2096 #endif
2097
2098         if (do_reuseaddr) {
2099                 int val = 1;
2100
2101                 ret = setsockopt(state->fd, SOL_SOCKET, SO_REUSEADDR,
2102                                  (const void *)&val, sizeof(val));
2103                 if (ret == -1) {
2104                         tevent_req_error(req, errno);
2105                         goto post;
2106                 }
2107         }
2108
2109         if (do_bind) {
2110                 ret = bind(state->fd, &lbsda->u.sa, sa_socklen);
2111                 if (ret == -1) {
2112                         tevent_req_error(req, errno);
2113                         goto post;
2114                 }
2115         }
2116
2117         if (rbsda->u.sa.sa_family != sa_fam) {
2118                 tevent_req_error(req, EINVAL);
2119                 goto post;
2120         }
2121
2122         ret = connect(state->fd, &rbsda->u.sa, sa_socklen);
2123         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
2124         if (retry) {
2125                 /* retry later */
2126                 goto async;
2127         }
2128         if (tevent_req_error(req, err)) {
2129                 goto post;
2130         }
2131
2132         tevent_req_done(req);
2133         goto post;
2134
2135  async:
2136         state->fde = tevent_add_fd(ev, state,
2137                                    state->fd,
2138                                    TEVENT_FD_READ | TEVENT_FD_WRITE,
2139                                    tstream_bsd_connect_fde_handler,
2140                                    req);
2141         if (tevent_req_nomem(state->fde, req)) {
2142                 goto post;
2143         }
2144
2145         return req;
2146
2147  post:
2148         tevent_req_post(req, ev);
2149         return req;
2150 }
2151
2152 static void tstream_bsd_connect_fde_handler(struct tevent_context *ev,
2153                                             struct tevent_fd *fde,
2154                                             uint16_t flags,
2155                                             void *private_data)
2156 {
2157         struct tevent_req *req = talloc_get_type_abort(private_data,
2158                                  struct tevent_req);
2159         struct tstream_bsd_connect_state *state = tevent_req_data(req,
2160                                         struct tstream_bsd_connect_state);
2161         int ret;
2162         int error=0;
2163         socklen_t len = sizeof(error);
2164         int err;
2165         bool retry;
2166
2167         ret = getsockopt(state->fd, SOL_SOCKET, SO_ERROR, &error, &len);
2168         if (ret == 0) {
2169                 if (error != 0) {
2170                         errno = error;
2171                         ret = -1;
2172                 }
2173         }
2174         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
2175         if (retry) {
2176                 /* retry later */
2177                 return;
2178         }
2179         if (tevent_req_error(req, err)) {
2180                 return;
2181         }
2182
2183         tevent_req_done(req);
2184 }
2185
2186 static int tstream_bsd_connect_recv(struct tevent_req *req,
2187                                     int *perrno,
2188                                     TALLOC_CTX *mem_ctx,
2189                                     struct tstream_context **stream,
2190                                     const char *location)
2191 {
2192         struct tstream_bsd_connect_state *state = tevent_req_data(req,
2193                                         struct tstream_bsd_connect_state);
2194         int ret;
2195
2196         ret = tsocket_simple_int_recv(req, perrno);
2197         if (ret == 0) {
2198                 ret = _tstream_bsd_existing_socket(mem_ctx,
2199                                                    state->fd,
2200                                                    stream,
2201                                                    location);
2202                 if (ret == -1) {
2203                         *perrno = errno;
2204                         goto done;
2205                 }
2206                 TALLOC_FREE(state->fde);
2207                 state->fd = -1;
2208         }
2209
2210 done:
2211         tevent_req_received(req);
2212         return ret;
2213 }
2214
2215 struct tevent_req * tstream_inet_tcp_connect_send(TALLOC_CTX *mem_ctx,
2216                                         struct tevent_context *ev,
2217                                         const struct tsocket_address *local,
2218                                         const struct tsocket_address *remote)
2219 {
2220         struct tsocket_address_bsd *lbsda =
2221                 talloc_get_type_abort(local->private_data,
2222                 struct tsocket_address_bsd);
2223         struct tevent_req *req;
2224         int sys_errno = 0;
2225
2226         switch (lbsda->u.sa.sa_family) {
2227         case AF_INET:
2228                 break;
2229 #ifdef HAVE_IPV6
2230         case AF_INET6:
2231                 break;
2232 #endif
2233         default:
2234                 sys_errno = EINVAL;
2235                 break;
2236         }
2237
2238         req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote);
2239
2240         return req;
2241 }
2242
2243 int _tstream_inet_tcp_connect_recv(struct tevent_req *req,
2244                                    int *perrno,
2245                                    TALLOC_CTX *mem_ctx,
2246                                    struct tstream_context **stream,
2247                                    const char *location)
2248 {
2249         return tstream_bsd_connect_recv(req, perrno, mem_ctx, stream, location);
2250 }
2251
2252 struct tevent_req * tstream_unix_connect_send(TALLOC_CTX *mem_ctx,
2253                                         struct tevent_context *ev,
2254                                         const struct tsocket_address *local,
2255                                         const struct tsocket_address *remote)
2256 {
2257         struct tsocket_address_bsd *lbsda =
2258                 talloc_get_type_abort(local->private_data,
2259                 struct tsocket_address_bsd);
2260         struct tevent_req *req;
2261         int sys_errno = 0;
2262
2263         switch (lbsda->u.sa.sa_family) {
2264         case AF_UNIX:
2265                 break;
2266         default:
2267                 sys_errno = EINVAL;
2268                 break;
2269         }
2270
2271         req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote);
2272
2273         return req;
2274 }
2275
2276 int _tstream_unix_connect_recv(struct tevent_req *req,
2277                                       int *perrno,
2278                                       TALLOC_CTX *mem_ctx,
2279                                       struct tstream_context **stream,
2280                                       const char *location)
2281 {
2282         return tstream_bsd_connect_recv(req, perrno, mem_ctx, stream, location);
2283 }
2284
2285 int _tstream_unix_socketpair(TALLOC_CTX *mem_ctx1,
2286                              struct tstream_context **_stream1,
2287                              TALLOC_CTX *mem_ctx2,
2288                              struct tstream_context **_stream2,
2289                              const char *location)
2290 {
2291         int ret;
2292         int fds[2];
2293         int fd1;
2294         int fd2;
2295         struct tstream_context *stream1 = NULL;
2296         struct tstream_context *stream2 = NULL;
2297
2298         ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
2299         if (ret == -1) {
2300                 return -1;
2301         }
2302         fd1 = fds[0];
2303         fd2 = fds[1];
2304
2305         fd1 = tsocket_bsd_common_prepare_fd(fd1, true);
2306         if (fd1 == -1) {
2307                 int sys_errno = errno;
2308                 close(fd2);
2309                 errno = sys_errno;
2310                 return -1;
2311         }
2312
2313         fd2 = tsocket_bsd_common_prepare_fd(fd2, true);
2314         if (fd2 == -1) {
2315                 int sys_errno = errno;
2316                 close(fd1);
2317                 errno = sys_errno;
2318                 return -1;
2319         }
2320
2321         ret = _tstream_bsd_existing_socket(mem_ctx1,
2322                                            fd1,
2323                                            &stream1,
2324                                            location);
2325         if (ret == -1) {
2326                 int sys_errno = errno;
2327                 close(fd1);
2328                 close(fd2);
2329                 errno = sys_errno;
2330                 return -1;
2331         }
2332
2333         ret = _tstream_bsd_existing_socket(mem_ctx2,
2334                                            fd2,
2335                                            &stream2,
2336                                            location);
2337         if (ret == -1) {
2338                 int sys_errno = errno;
2339                 talloc_free(stream1);
2340                 close(fd2);
2341                 errno = sys_errno;
2342                 return -1;
2343         }
2344
2345         *_stream1 = stream1;
2346         *_stream2 = stream2;
2347         return 0;
2348 }
2349