tsocket/bsd: fix bug #7115 FreeBSD includes the UDP header in FIONREAD
[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         /*
887          * some systems too much bytes in tsocket_bsd_pending()
888          * the return value includes some IP/UDP header bytes
889          */
890         state->len = ret;
891         talloc_realloc(state, state->buf, uint8_t, ret);
892
893         tevent_req_done(req);
894 }
895
896 static ssize_t tdgram_bsd_recvfrom_recv(struct tevent_req *req,
897                                         int *perrno,
898                                         TALLOC_CTX *mem_ctx,
899                                         uint8_t **buf,
900                                         struct tsocket_address **src)
901 {
902         struct tdgram_bsd_recvfrom_state *state = tevent_req_data(req,
903                                         struct tdgram_bsd_recvfrom_state);
904         ssize_t ret;
905
906         ret = tsocket_simple_int_recv(req, perrno);
907         if (ret == 0) {
908                 *buf = talloc_move(mem_ctx, &state->buf);
909                 ret = state->len;
910                 if (src) {
911                         *src = talloc_move(mem_ctx, &state->src);
912                 }
913         }
914
915         tevent_req_received(req);
916         return ret;
917 }
918
919 struct tdgram_bsd_sendto_state {
920         struct tdgram_context *dgram;
921
922         const uint8_t *buf;
923         size_t len;
924         const struct tsocket_address *dst;
925
926         ssize_t ret;
927 };
928
929 static int tdgram_bsd_sendto_destructor(struct tdgram_bsd_sendto_state *state)
930 {
931         struct tdgram_bsd *bsds = tdgram_context_data(state->dgram,
932                                   struct tdgram_bsd);
933
934         tdgram_bsd_set_writeable_handler(bsds, NULL, NULL, NULL);
935
936         return 0;
937 }
938
939 static void tdgram_bsd_sendto_handler(void *private_data);
940
941 static struct tevent_req *tdgram_bsd_sendto_send(TALLOC_CTX *mem_ctx,
942                                                  struct tevent_context *ev,
943                                                  struct tdgram_context *dgram,
944                                                  const uint8_t *buf,
945                                                  size_t len,
946                                                  const struct tsocket_address *dst)
947 {
948         struct tevent_req *req;
949         struct tdgram_bsd_sendto_state *state;
950         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
951         int ret;
952
953         req = tevent_req_create(mem_ctx, &state,
954                                 struct tdgram_bsd_sendto_state);
955         if (!req) {
956                 return NULL;
957         }
958
959         state->dgram    = dgram;
960         state->buf      = buf;
961         state->len      = len;
962         state->dst      = dst;
963         state->ret      = -1;
964
965         talloc_set_destructor(state, tdgram_bsd_sendto_destructor);
966
967         if (bsds->fd == -1) {
968                 tevent_req_error(req, ENOTCONN);
969                 goto post;
970         }
971
972         /*
973          * this is a fast path, not waiting for the
974          * socket to become explicit writeable gains
975          * about 10%-20% performance in benchmark tests.
976          */
977         tdgram_bsd_sendto_handler(req);
978         if (!tevent_req_is_in_progress(req)) {
979                 goto post;
980         }
981
982         ret = tdgram_bsd_set_writeable_handler(bsds, ev,
983                                                tdgram_bsd_sendto_handler,
984                                                req);
985         if (ret == -1) {
986                 tevent_req_error(req, errno);
987                 goto post;
988         }
989
990         return req;
991
992  post:
993         tevent_req_post(req, ev);
994         return req;
995 }
996
997 static void tdgram_bsd_sendto_handler(void *private_data)
998 {
999         struct tevent_req *req = talloc_get_type_abort(private_data,
1000                                  struct tevent_req);
1001         struct tdgram_bsd_sendto_state *state = tevent_req_data(req,
1002                                         struct tdgram_bsd_sendto_state);
1003         struct tdgram_context *dgram = state->dgram;
1004         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
1005         struct sockaddr *sa = NULL;
1006         socklen_t sa_socklen = 0;
1007         ssize_t ret;
1008         int err;
1009         bool retry;
1010
1011         if (state->dst) {
1012                 struct tsocket_address_bsd *bsda =
1013                         talloc_get_type(state->dst->private_data,
1014                         struct tsocket_address_bsd);
1015
1016                 sa = &bsda->u.sa;
1017                 sa_socklen = sizeof(bsda->u.ss);
1018                 /*
1019                  * for unix sockets we can't use the size of sockaddr_storage
1020                  * we would get EINVAL
1021                  */
1022                 if (bsda->u.sa.sa_family == AF_UNIX) {
1023                         sa_socklen = sizeof(bsda->u.un);
1024                 }
1025         }
1026
1027         ret = sendto(bsds->fd, state->buf, state->len, 0, sa, sa_socklen);
1028         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1029         if (retry) {
1030                 /* retry later */
1031                 return;
1032         }
1033         if (tevent_req_error(req, err)) {
1034                 return;
1035         }
1036
1037         state->ret = ret;
1038
1039         tevent_req_done(req);
1040 }
1041
1042 static ssize_t tdgram_bsd_sendto_recv(struct tevent_req *req, int *perrno)
1043 {
1044         struct tdgram_bsd_sendto_state *state = tevent_req_data(req,
1045                                         struct tdgram_bsd_sendto_state);
1046         ssize_t ret;
1047
1048         ret = tsocket_simple_int_recv(req, perrno);
1049         if (ret == 0) {
1050                 ret = state->ret;
1051         }
1052
1053         tevent_req_received(req);
1054         return ret;
1055 }
1056
1057 struct tdgram_bsd_disconnect_state {
1058         uint8_t __dummy;
1059 };
1060
1061 static struct tevent_req *tdgram_bsd_disconnect_send(TALLOC_CTX *mem_ctx,
1062                                                      struct tevent_context *ev,
1063                                                      struct tdgram_context *dgram)
1064 {
1065         struct tdgram_bsd *bsds = tdgram_context_data(dgram, struct tdgram_bsd);
1066         struct tevent_req *req;
1067         struct tdgram_bsd_disconnect_state *state;
1068         int ret;
1069         int err;
1070         bool dummy;
1071
1072         req = tevent_req_create(mem_ctx, &state,
1073                                 struct tdgram_bsd_disconnect_state);
1074         if (req == NULL) {
1075                 return NULL;
1076         }
1077
1078         if (bsds->fd == -1) {
1079                 tevent_req_error(req, ENOTCONN);
1080                 goto post;
1081         }
1082
1083         ret = close(bsds->fd);
1084         bsds->fd = -1;
1085         err = tsocket_bsd_error_from_errno(ret, errno, &dummy);
1086         if (tevent_req_error(req, err)) {
1087                 goto post;
1088         }
1089
1090         tevent_req_done(req);
1091 post:
1092         tevent_req_post(req, ev);
1093         return req;
1094 }
1095
1096 static int tdgram_bsd_disconnect_recv(struct tevent_req *req,
1097                                       int *perrno)
1098 {
1099         int ret;
1100
1101         ret = tsocket_simple_int_recv(req, perrno);
1102
1103         tevent_req_received(req);
1104         return ret;
1105 }
1106
1107 static const struct tdgram_context_ops tdgram_bsd_ops = {
1108         .name                   = "bsd",
1109
1110         .recvfrom_send          = tdgram_bsd_recvfrom_send,
1111         .recvfrom_recv          = tdgram_bsd_recvfrom_recv,
1112
1113         .sendto_send            = tdgram_bsd_sendto_send,
1114         .sendto_recv            = tdgram_bsd_sendto_recv,
1115
1116         .disconnect_send        = tdgram_bsd_disconnect_send,
1117         .disconnect_recv        = tdgram_bsd_disconnect_recv,
1118 };
1119
1120 static int tdgram_bsd_destructor(struct tdgram_bsd *bsds)
1121 {
1122         TALLOC_FREE(bsds->fde);
1123         if (bsds->fd != -1) {
1124                 close(bsds->fd);
1125                 bsds->fd = -1;
1126         }
1127         return 0;
1128 }
1129
1130 static int tdgram_bsd_dgram_socket(const struct tsocket_address *local,
1131                                    const struct tsocket_address *remote,
1132                                    bool broadcast,
1133                                    TALLOC_CTX *mem_ctx,
1134                                    struct tdgram_context **_dgram,
1135                                    const char *location)
1136 {
1137         struct tsocket_address_bsd *lbsda =
1138                 talloc_get_type_abort(local->private_data,
1139                 struct tsocket_address_bsd);
1140         struct tsocket_address_bsd *rbsda = NULL;
1141         struct tdgram_context *dgram;
1142         struct tdgram_bsd *bsds;
1143         int fd;
1144         int ret;
1145         bool do_bind = false;
1146         bool do_reuseaddr = false;
1147         bool do_ipv6only = false;
1148         bool is_inet = false;
1149         int sa_fam = lbsda->u.sa.sa_family;
1150         socklen_t sa_socklen = sizeof(lbsda->u.ss);
1151
1152         if (remote) {
1153                 rbsda = talloc_get_type_abort(remote->private_data,
1154                         struct tsocket_address_bsd);
1155         }
1156
1157         switch (lbsda->u.sa.sa_family) {
1158         case AF_UNIX:
1159                 if (broadcast) {
1160                         errno = EINVAL;
1161                         return -1;
1162                 }
1163                 if (lbsda->u.un.sun_path[0] != 0) {
1164                         do_reuseaddr = true;
1165                         do_bind = true;
1166                 }
1167                 /*
1168                  * for unix sockets we can't use the size of sockaddr_storage
1169                  * we would get EINVAL
1170                  */
1171                 sa_socklen = sizeof(lbsda->u.un);
1172                 break;
1173         case AF_INET:
1174                 if (lbsda->u.in.sin_port != 0) {
1175                         do_reuseaddr = true;
1176                         do_bind = true;
1177                 }
1178                 if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) {
1179                         do_bind = true;
1180                 }
1181                 is_inet = true;
1182                 sa_socklen = sizeof(rbsda->u.in);
1183                 break;
1184 #ifdef HAVE_IPV6
1185         case AF_INET6:
1186                 if (lbsda->u.in6.sin6_port != 0) {
1187                         do_reuseaddr = true;
1188                         do_bind = true;
1189                 }
1190                 if (memcmp(&in6addr_any,
1191                            &lbsda->u.in6.sin6_addr,
1192                            sizeof(in6addr_any)) != 0) {
1193                         do_bind = true;
1194                 }
1195                 is_inet = true;
1196                 sa_socklen = sizeof(rbsda->u.in6);
1197                 do_ipv6only = true;
1198                 break;
1199 #endif
1200         default:
1201                 errno = EINVAL;
1202                 return -1;
1203         }
1204
1205         if (!do_bind && is_inet && rbsda) {
1206                 sa_fam = rbsda->u.sa.sa_family;
1207                 switch (sa_fam) {
1208                 case AF_INET:
1209                         sa_socklen = sizeof(rbsda->u.in);
1210                         do_ipv6only = false;
1211                         break;
1212 #ifdef HAVE_IPV6
1213                 case AF_INET6:
1214                         sa_socklen = sizeof(rbsda->u.in6);
1215                         do_ipv6only = true;
1216                         break;
1217 #endif
1218                 }
1219         }
1220
1221         fd = socket(sa_fam, SOCK_DGRAM, 0);
1222         if (fd < 0) {
1223                 return fd;
1224         }
1225
1226         fd = tsocket_bsd_common_prepare_fd(fd, true);
1227         if (fd < 0) {
1228                 return fd;
1229         }
1230
1231         dgram = tdgram_context_create(mem_ctx,
1232                                       &tdgram_bsd_ops,
1233                                       &bsds,
1234                                       struct tdgram_bsd,
1235                                       location);
1236         if (!dgram) {
1237                 int saved_errno = errno;
1238                 close(fd);
1239                 errno = saved_errno;
1240                 return -1;
1241         }
1242         ZERO_STRUCTP(bsds);
1243         bsds->fd = fd;
1244         talloc_set_destructor(bsds, tdgram_bsd_destructor);
1245
1246 #ifdef HAVE_IPV6
1247         if (do_ipv6only) {
1248                 int val = 1;
1249
1250                 ret = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
1251                                  (const void *)&val, sizeof(val));
1252                 if (ret == -1) {
1253                         int saved_errno = errno;
1254                         talloc_free(dgram);
1255                         errno = saved_errno;
1256                         return ret;
1257                 }
1258         }
1259 #endif
1260
1261         if (broadcast) {
1262                 int val = 1;
1263
1264                 ret = setsockopt(fd, SOL_SOCKET, SO_BROADCAST,
1265                                  (const void *)&val, sizeof(val));
1266                 if (ret == -1) {
1267                         int saved_errno = errno;
1268                         talloc_free(dgram);
1269                         errno = saved_errno;
1270                         return ret;
1271                 }
1272         }
1273
1274         if (do_reuseaddr) {
1275                 int val = 1;
1276
1277                 ret = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
1278                                  (const void *)&val, sizeof(val));
1279                 if (ret == -1) {
1280                         int saved_errno = errno;
1281                         talloc_free(dgram);
1282                         errno = saved_errno;
1283                         return ret;
1284                 }
1285         }
1286
1287         if (do_bind) {
1288                 ret = bind(fd, &lbsda->u.sa, sa_socklen);
1289                 if (ret == -1) {
1290                         int saved_errno = errno;
1291                         talloc_free(dgram);
1292                         errno = saved_errno;
1293                         return ret;
1294                 }
1295         }
1296
1297         if (rbsda) {
1298                 if (rbsda->u.sa.sa_family != sa_fam) {
1299                         talloc_free(dgram);
1300                         errno = EINVAL;
1301                         return -1;
1302                 }
1303
1304                 ret = connect(fd, &rbsda->u.sa, sa_socklen);
1305                 if (ret == -1) {
1306                         int saved_errno = errno;
1307                         talloc_free(dgram);
1308                         errno = saved_errno;
1309                         return ret;
1310                 }
1311         }
1312
1313         *_dgram = dgram;
1314         return 0;
1315 }
1316
1317 int _tdgram_inet_udp_socket(const struct tsocket_address *local,
1318                             const struct tsocket_address *remote,
1319                             TALLOC_CTX *mem_ctx,
1320                             struct tdgram_context **dgram,
1321                             const char *location)
1322 {
1323         struct tsocket_address_bsd *lbsda =
1324                 talloc_get_type_abort(local->private_data,
1325                 struct tsocket_address_bsd);
1326         int ret;
1327
1328         switch (lbsda->u.sa.sa_family) {
1329         case AF_INET:
1330                 break;
1331 #ifdef HAVE_IPV6
1332         case AF_INET6:
1333                 break;
1334 #endif
1335         default:
1336                 errno = EINVAL;
1337                 return -1;
1338         }
1339
1340         ret = tdgram_bsd_dgram_socket(local, remote, false,
1341                                       mem_ctx, dgram, location);
1342
1343         return ret;
1344 }
1345
1346 int _tdgram_unix_socket(const struct tsocket_address *local,
1347                         const struct tsocket_address *remote,
1348                         TALLOC_CTX *mem_ctx,
1349                         struct tdgram_context **dgram,
1350                         const char *location)
1351 {
1352         struct tsocket_address_bsd *lbsda =
1353                 talloc_get_type_abort(local->private_data,
1354                 struct tsocket_address_bsd);
1355         int ret;
1356
1357         switch (lbsda->u.sa.sa_family) {
1358         case AF_UNIX:
1359                 break;
1360         default:
1361                 errno = EINVAL;
1362                 return -1;
1363         }
1364
1365         ret = tdgram_bsd_dgram_socket(local, remote, false,
1366                                       mem_ctx, dgram, location);
1367
1368         return ret;
1369 }
1370
1371 struct tstream_bsd {
1372         int fd;
1373
1374         void *event_ptr;
1375         struct tevent_fd *fde;
1376
1377         void *readable_private;
1378         void (*readable_handler)(void *private_data);
1379         void *writeable_private;
1380         void (*writeable_handler)(void *private_data);
1381 };
1382
1383 static void tstream_bsd_fde_handler(struct tevent_context *ev,
1384                                     struct tevent_fd *fde,
1385                                     uint16_t flags,
1386                                     void *private_data)
1387 {
1388         struct tstream_bsd *bsds = talloc_get_type_abort(private_data,
1389                                    struct tstream_bsd);
1390
1391         if (flags & TEVENT_FD_WRITE) {
1392                 bsds->writeable_handler(bsds->writeable_private);
1393                 return;
1394         }
1395         if (flags & TEVENT_FD_READ) {
1396                 if (!bsds->readable_handler) {
1397                         if (bsds->writeable_handler) {
1398                                 bsds->writeable_handler(bsds->writeable_private);
1399                                 return;
1400                         }
1401                         TEVENT_FD_NOT_READABLE(bsds->fde);
1402                         return;
1403                 }
1404                 bsds->readable_handler(bsds->readable_private);
1405                 return;
1406         }
1407 }
1408
1409 static int tstream_bsd_set_readable_handler(struct tstream_bsd *bsds,
1410                                             struct tevent_context *ev,
1411                                             void (*handler)(void *private_data),
1412                                             void *private_data)
1413 {
1414         if (ev == NULL) {
1415                 if (handler) {
1416                         errno = EINVAL;
1417                         return -1;
1418                 }
1419                 if (!bsds->readable_handler) {
1420                         return 0;
1421                 }
1422                 bsds->readable_handler = NULL;
1423                 bsds->readable_private = NULL;
1424
1425                 return 0;
1426         }
1427
1428         /* read and write must use the same tevent_context */
1429         if (bsds->event_ptr != ev) {
1430                 if (bsds->readable_handler || bsds->writeable_handler) {
1431                         errno = EINVAL;
1432                         return -1;
1433                 }
1434                 bsds->event_ptr = NULL;
1435                 TALLOC_FREE(bsds->fde);
1436         }
1437
1438         if (tevent_fd_get_flags(bsds->fde) == 0) {
1439                 TALLOC_FREE(bsds->fde);
1440
1441                 bsds->fde = tevent_add_fd(ev, bsds,
1442                                           bsds->fd, TEVENT_FD_READ,
1443                                           tstream_bsd_fde_handler,
1444                                           bsds);
1445                 if (!bsds->fde) {
1446                         errno = ENOMEM;
1447                         return -1;
1448                 }
1449
1450                 /* cache the event context we're running on */
1451                 bsds->event_ptr = ev;
1452         } else if (!bsds->readable_handler) {
1453                 TEVENT_FD_READABLE(bsds->fde);
1454         }
1455
1456         bsds->readable_handler = handler;
1457         bsds->readable_private = private_data;
1458
1459         return 0;
1460 }
1461
1462 static int tstream_bsd_set_writeable_handler(struct tstream_bsd *bsds,
1463                                              struct tevent_context *ev,
1464                                              void (*handler)(void *private_data),
1465                                              void *private_data)
1466 {
1467         if (ev == NULL) {
1468                 if (handler) {
1469                         errno = EINVAL;
1470                         return -1;
1471                 }
1472                 if (!bsds->writeable_handler) {
1473                         return 0;
1474                 }
1475                 bsds->writeable_handler = NULL;
1476                 bsds->writeable_private = NULL;
1477                 TEVENT_FD_NOT_WRITEABLE(bsds->fde);
1478
1479                 return 0;
1480         }
1481
1482         /* read and write must use the same tevent_context */
1483         if (bsds->event_ptr != ev) {
1484                 if (bsds->readable_handler || bsds->writeable_handler) {
1485                         errno = EINVAL;
1486                         return -1;
1487                 }
1488                 bsds->event_ptr = NULL;
1489                 TALLOC_FREE(bsds->fde);
1490         }
1491
1492         if (tevent_fd_get_flags(bsds->fde) == 0) {
1493                 TALLOC_FREE(bsds->fde);
1494
1495                 bsds->fde = tevent_add_fd(ev, bsds,
1496                                           bsds->fd,
1497                                           TEVENT_FD_READ | TEVENT_FD_WRITE,
1498                                           tstream_bsd_fde_handler,
1499                                           bsds);
1500                 if (!bsds->fde) {
1501                         errno = ENOMEM;
1502                         return -1;
1503                 }
1504
1505                 /* cache the event context we're running on */
1506                 bsds->event_ptr = ev;
1507         } else if (!bsds->writeable_handler) {
1508                 uint16_t flags = tevent_fd_get_flags(bsds->fde);
1509                 flags |= TEVENT_FD_READ | TEVENT_FD_WRITE;
1510                 tevent_fd_set_flags(bsds->fde, flags);
1511         }
1512
1513         bsds->writeable_handler = handler;
1514         bsds->writeable_private = private_data;
1515
1516         return 0;
1517 }
1518
1519 static ssize_t tstream_bsd_pending_bytes(struct tstream_context *stream)
1520 {
1521         struct tstream_bsd *bsds = tstream_context_data(stream,
1522                                    struct tstream_bsd);
1523         ssize_t ret;
1524
1525         if (bsds->fd == -1) {
1526                 errno = ENOTCONN;
1527                 return -1;
1528         }
1529
1530         ret = tsocket_bsd_pending(bsds->fd);
1531
1532         return ret;
1533 }
1534
1535 struct tstream_bsd_readv_state {
1536         struct tstream_context *stream;
1537
1538         struct iovec *vector;
1539         size_t count;
1540
1541         int ret;
1542 };
1543
1544 static int tstream_bsd_readv_destructor(struct tstream_bsd_readv_state *state)
1545 {
1546         struct tstream_bsd *bsds = tstream_context_data(state->stream,
1547                                    struct tstream_bsd);
1548
1549         tstream_bsd_set_readable_handler(bsds, NULL, NULL, NULL);
1550
1551         return 0;
1552 }
1553
1554 static void tstream_bsd_readv_handler(void *private_data);
1555
1556 static struct tevent_req *tstream_bsd_readv_send(TALLOC_CTX *mem_ctx,
1557                                         struct tevent_context *ev,
1558                                         struct tstream_context *stream,
1559                                         struct iovec *vector,
1560                                         size_t count)
1561 {
1562         struct tevent_req *req;
1563         struct tstream_bsd_readv_state *state;
1564         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1565         int ret;
1566
1567         req = tevent_req_create(mem_ctx, &state,
1568                                 struct tstream_bsd_readv_state);
1569         if (!req) {
1570                 return NULL;
1571         }
1572
1573         state->stream   = stream;
1574         /* we make a copy of the vector so that we can modify it */
1575         state->vector   = talloc_array(state, struct iovec, count);
1576         if (tevent_req_nomem(state->vector, req)) {
1577                 goto post;
1578         }
1579         memcpy(state->vector, vector, sizeof(struct iovec)*count);
1580         state->count    = count;
1581         state->ret      = 0;
1582
1583         talloc_set_destructor(state, tstream_bsd_readv_destructor);
1584
1585         if (bsds->fd == -1) {
1586                 tevent_req_error(req, ENOTCONN);
1587                 goto post;
1588         }
1589
1590         /*
1591          * this is a fast path, not waiting for the
1592          * socket to become explicit readable gains
1593          * about 10%-20% performance in benchmark tests.
1594          */
1595         tstream_bsd_readv_handler(req);
1596         if (!tevent_req_is_in_progress(req)) {
1597                 goto post;
1598         }
1599
1600         ret = tstream_bsd_set_readable_handler(bsds, ev,
1601                                               tstream_bsd_readv_handler,
1602                                               req);
1603         if (ret == -1) {
1604                 tevent_req_error(req, errno);
1605                 goto post;
1606         }
1607
1608         return req;
1609
1610  post:
1611         tevent_req_post(req, ev);
1612         return req;
1613 }
1614
1615 static void tstream_bsd_readv_handler(void *private_data)
1616 {
1617         struct tevent_req *req = talloc_get_type_abort(private_data,
1618                                  struct tevent_req);
1619         struct tstream_bsd_readv_state *state = tevent_req_data(req,
1620                                         struct tstream_bsd_readv_state);
1621         struct tstream_context *stream = state->stream;
1622         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1623         int ret;
1624         int err;
1625         bool retry;
1626
1627         ret = readv(bsds->fd, state->vector, state->count);
1628         if (ret == 0) {
1629                 /* propagate end of file */
1630                 tevent_req_error(req, EPIPE);
1631                 return;
1632         }
1633         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1634         if (retry) {
1635                 /* retry later */
1636                 return;
1637         }
1638         if (tevent_req_error(req, err)) {
1639                 return;
1640         }
1641
1642         state->ret += ret;
1643
1644         while (ret > 0) {
1645                 if (ret < state->vector[0].iov_len) {
1646                         uint8_t *base;
1647                         base = (uint8_t *)state->vector[0].iov_base;
1648                         base += ret;
1649                         state->vector[0].iov_base = base;
1650                         state->vector[0].iov_len -= ret;
1651                         break;
1652                 }
1653                 ret -= state->vector[0].iov_len;
1654                 state->vector += 1;
1655                 state->count -= 1;
1656         }
1657
1658         /*
1659          * there're maybe some empty vectors at the end
1660          * which we need to skip, otherwise we would get
1661          * ret == 0 from the readv() call and return EPIPE
1662          */
1663         while (state->count > 0) {
1664                 if (state->vector[0].iov_len > 0) {
1665                         break;
1666                 }
1667                 state->vector += 1;
1668                 state->count -= 1;
1669         }
1670
1671         if (state->count > 0) {
1672                 /* we have more to read */
1673                 return;
1674         }
1675
1676         tevent_req_done(req);
1677 }
1678
1679 static int tstream_bsd_readv_recv(struct tevent_req *req,
1680                                   int *perrno)
1681 {
1682         struct tstream_bsd_readv_state *state = tevent_req_data(req,
1683                                         struct tstream_bsd_readv_state);
1684         int ret;
1685
1686         ret = tsocket_simple_int_recv(req, perrno);
1687         if (ret == 0) {
1688                 ret = state->ret;
1689         }
1690
1691         tevent_req_received(req);
1692         return ret;
1693 }
1694
1695 struct tstream_bsd_writev_state {
1696         struct tstream_context *stream;
1697
1698         struct iovec *vector;
1699         size_t count;
1700
1701         int ret;
1702 };
1703
1704 static int tstream_bsd_writev_destructor(struct tstream_bsd_writev_state *state)
1705 {
1706         struct tstream_bsd *bsds = tstream_context_data(state->stream,
1707                                   struct tstream_bsd);
1708
1709         tstream_bsd_set_writeable_handler(bsds, NULL, NULL, NULL);
1710
1711         return 0;
1712 }
1713
1714 static void tstream_bsd_writev_handler(void *private_data);
1715
1716 static struct tevent_req *tstream_bsd_writev_send(TALLOC_CTX *mem_ctx,
1717                                                  struct tevent_context *ev,
1718                                                  struct tstream_context *stream,
1719                                                  const struct iovec *vector,
1720                                                  size_t count)
1721 {
1722         struct tevent_req *req;
1723         struct tstream_bsd_writev_state *state;
1724         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1725         int ret;
1726
1727         req = tevent_req_create(mem_ctx, &state,
1728                                 struct tstream_bsd_writev_state);
1729         if (!req) {
1730                 return NULL;
1731         }
1732
1733         state->stream   = stream;
1734         /* we make a copy of the vector so that we can modify it */
1735         state->vector   = talloc_array(state, struct iovec, count);
1736         if (tevent_req_nomem(state->vector, req)) {
1737                 goto post;
1738         }
1739         memcpy(state->vector, vector, sizeof(struct iovec)*count);
1740         state->count    = count;
1741         state->ret      = 0;
1742
1743         talloc_set_destructor(state, tstream_bsd_writev_destructor);
1744
1745         if (bsds->fd == -1) {
1746                 tevent_req_error(req, ENOTCONN);
1747                 goto post;
1748         }
1749
1750         /*
1751          * this is a fast path, not waiting for the
1752          * socket to become explicit writeable gains
1753          * about 10%-20% performance in benchmark tests.
1754          */
1755         tstream_bsd_writev_handler(req);
1756         if (!tevent_req_is_in_progress(req)) {
1757                 goto post;
1758         }
1759
1760         ret = tstream_bsd_set_writeable_handler(bsds, ev,
1761                                                tstream_bsd_writev_handler,
1762                                                req);
1763         if (ret == -1) {
1764                 tevent_req_error(req, errno);
1765                 goto post;
1766         }
1767
1768         return req;
1769
1770  post:
1771         tevent_req_post(req, ev);
1772         return req;
1773 }
1774
1775 static void tstream_bsd_writev_handler(void *private_data)
1776 {
1777         struct tevent_req *req = talloc_get_type_abort(private_data,
1778                                  struct tevent_req);
1779         struct tstream_bsd_writev_state *state = tevent_req_data(req,
1780                                         struct tstream_bsd_writev_state);
1781         struct tstream_context *stream = state->stream;
1782         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1783         ssize_t ret;
1784         int err;
1785         bool retry;
1786
1787         ret = writev(bsds->fd, state->vector, state->count);
1788         if (ret == 0) {
1789                 /* propagate end of file */
1790                 tevent_req_error(req, EPIPE);
1791                 return;
1792         }
1793         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
1794         if (retry) {
1795                 /* retry later */
1796                 return;
1797         }
1798         if (tevent_req_error(req, err)) {
1799                 return;
1800         }
1801
1802         state->ret += ret;
1803
1804         while (ret > 0) {
1805                 if (ret < state->vector[0].iov_len) {
1806                         uint8_t *base;
1807                         base = (uint8_t *)state->vector[0].iov_base;
1808                         base += ret;
1809                         state->vector[0].iov_base = base;
1810                         state->vector[0].iov_len -= ret;
1811                         break;
1812                 }
1813                 ret -= state->vector[0].iov_len;
1814                 state->vector += 1;
1815                 state->count -= 1;
1816         }
1817
1818         /*
1819          * there're maybe some empty vectors at the end
1820          * which we need to skip, otherwise we would get
1821          * ret == 0 from the writev() call and return EPIPE
1822          */
1823         while (state->count > 0) {
1824                 if (state->vector[0].iov_len > 0) {
1825                         break;
1826                 }
1827                 state->vector += 1;
1828                 state->count -= 1;
1829         }
1830
1831         if (state->count > 0) {
1832                 /* we have more to read */
1833                 return;
1834         }
1835
1836         tevent_req_done(req);
1837 }
1838
1839 static int tstream_bsd_writev_recv(struct tevent_req *req, int *perrno)
1840 {
1841         struct tstream_bsd_writev_state *state = tevent_req_data(req,
1842                                         struct tstream_bsd_writev_state);
1843         int ret;
1844
1845         ret = tsocket_simple_int_recv(req, perrno);
1846         if (ret == 0) {
1847                 ret = state->ret;
1848         }
1849
1850         tevent_req_received(req);
1851         return ret;
1852 }
1853
1854 struct tstream_bsd_disconnect_state {
1855         void *__dummy;
1856 };
1857
1858 static struct tevent_req *tstream_bsd_disconnect_send(TALLOC_CTX *mem_ctx,
1859                                                      struct tevent_context *ev,
1860                                                      struct tstream_context *stream)
1861 {
1862         struct tstream_bsd *bsds = tstream_context_data(stream, struct tstream_bsd);
1863         struct tevent_req *req;
1864         struct tstream_bsd_disconnect_state *state;
1865         int ret;
1866         int err;
1867         bool dummy;
1868
1869         req = tevent_req_create(mem_ctx, &state,
1870                                 struct tstream_bsd_disconnect_state);
1871         if (req == NULL) {
1872                 return NULL;
1873         }
1874
1875         if (bsds->fd == -1) {
1876                 tevent_req_error(req, ENOTCONN);
1877                 goto post;
1878         }
1879
1880         ret = close(bsds->fd);
1881         bsds->fd = -1;
1882         err = tsocket_bsd_error_from_errno(ret, errno, &dummy);
1883         if (tevent_req_error(req, err)) {
1884                 goto post;
1885         }
1886
1887         tevent_req_done(req);
1888 post:
1889         tevent_req_post(req, ev);
1890         return req;
1891 }
1892
1893 static int tstream_bsd_disconnect_recv(struct tevent_req *req,
1894                                       int *perrno)
1895 {
1896         int ret;
1897
1898         ret = tsocket_simple_int_recv(req, perrno);
1899
1900         tevent_req_received(req);
1901         return ret;
1902 }
1903
1904 static const struct tstream_context_ops tstream_bsd_ops = {
1905         .name                   = "bsd",
1906
1907         .pending_bytes          = tstream_bsd_pending_bytes,
1908
1909         .readv_send             = tstream_bsd_readv_send,
1910         .readv_recv             = tstream_bsd_readv_recv,
1911
1912         .writev_send            = tstream_bsd_writev_send,
1913         .writev_recv            = tstream_bsd_writev_recv,
1914
1915         .disconnect_send        = tstream_bsd_disconnect_send,
1916         .disconnect_recv        = tstream_bsd_disconnect_recv,
1917 };
1918
1919 static int tstream_bsd_destructor(struct tstream_bsd *bsds)
1920 {
1921         TALLOC_FREE(bsds->fde);
1922         if (bsds->fd != -1) {
1923                 close(bsds->fd);
1924                 bsds->fd = -1;
1925         }
1926         return 0;
1927 }
1928
1929 int _tstream_bsd_existing_socket(TALLOC_CTX *mem_ctx,
1930                                  int fd,
1931                                  struct tstream_context **_stream,
1932                                  const char *location)
1933 {
1934         struct tstream_context *stream;
1935         struct tstream_bsd *bsds;
1936
1937         stream = tstream_context_create(mem_ctx,
1938                                         &tstream_bsd_ops,
1939                                         &bsds,
1940                                         struct tstream_bsd,
1941                                         location);
1942         if (!stream) {
1943                 return -1;
1944         }
1945         ZERO_STRUCTP(bsds);
1946         bsds->fd = fd;
1947         talloc_set_destructor(bsds, tstream_bsd_destructor);
1948
1949         *_stream = stream;
1950         return 0;
1951 }
1952
1953 struct tstream_bsd_connect_state {
1954         int fd;
1955         struct tevent_fd *fde;
1956         struct tstream_conext *stream;
1957 };
1958
1959 static int tstream_bsd_connect_destructor(struct tstream_bsd_connect_state *state)
1960 {
1961         TALLOC_FREE(state->fde);
1962         if (state->fd != -1) {
1963                 close(state->fd);
1964                 state->fd = -1;
1965         }
1966
1967         return 0;
1968 }
1969
1970 static void tstream_bsd_connect_fde_handler(struct tevent_context *ev,
1971                                             struct tevent_fd *fde,
1972                                             uint16_t flags,
1973                                             void *private_data);
1974
1975 static struct tevent_req * tstream_bsd_connect_send(TALLOC_CTX *mem_ctx,
1976                                         struct tevent_context *ev,
1977                                         int sys_errno,
1978                                         const struct tsocket_address *local,
1979                                         const struct tsocket_address *remote)
1980 {
1981         struct tevent_req *req;
1982         struct tstream_bsd_connect_state *state;
1983         struct tsocket_address_bsd *lbsda =
1984                 talloc_get_type_abort(local->private_data,
1985                 struct tsocket_address_bsd);
1986         struct tsocket_address_bsd *rbsda =
1987                 talloc_get_type_abort(remote->private_data,
1988                 struct tsocket_address_bsd);
1989         int ret;
1990         int err;
1991         bool retry;
1992         bool do_bind = false;
1993         bool do_reuseaddr = false;
1994         bool do_ipv6only = false;
1995         bool is_inet = false;
1996         int sa_fam = lbsda->u.sa.sa_family;
1997         socklen_t sa_socklen = sizeof(rbsda->u.ss);
1998
1999         req = tevent_req_create(mem_ctx, &state,
2000                                 struct tstream_bsd_connect_state);
2001         if (!req) {
2002                 return NULL;
2003         }
2004         state->fd = -1;
2005         state->fde = NULL;
2006
2007         talloc_set_destructor(state, tstream_bsd_connect_destructor);
2008
2009         /* give the wrappers a chance to report an error */
2010         if (sys_errno != 0) {
2011                 tevent_req_error(req, sys_errno);
2012                 goto post;
2013         }
2014
2015         switch (lbsda->u.sa.sa_family) {
2016         case AF_UNIX:
2017                 if (lbsda->u.un.sun_path[0] != 0) {
2018                         do_reuseaddr = true;
2019                         do_bind = true;
2020                 }
2021                 /*
2022                  * for unix sockets we can't use the size of sockaddr_storage
2023                  * we would get EINVAL
2024                  */
2025                 sa_socklen = sizeof(rbsda->u.un);
2026                 break;
2027         case AF_INET:
2028                 if (lbsda->u.in.sin_port != 0) {
2029                         do_reuseaddr = true;
2030                         do_bind = true;
2031                 }
2032                 if (lbsda->u.in.sin_addr.s_addr != INADDR_ANY) {
2033                         do_bind = true;
2034                 }
2035                 is_inet = true;
2036                 sa_socklen = sizeof(rbsda->u.in);
2037                 break;
2038 #ifdef HAVE_IPV6
2039         case AF_INET6:
2040                 if (lbsda->u.in6.sin6_port != 0) {
2041                         do_reuseaddr = true;
2042                         do_bind = true;
2043                 }
2044                 if (memcmp(&in6addr_any,
2045                            &lbsda->u.in6.sin6_addr,
2046                            sizeof(in6addr_any)) != 0) {
2047                         do_bind = true;
2048                 }
2049                 is_inet = true;
2050                 sa_socklen = sizeof(rbsda->u.in6);
2051                 do_ipv6only = true;
2052                 break;
2053 #endif
2054         default:
2055                 tevent_req_error(req, EINVAL);
2056                 goto post;
2057         }
2058
2059         if (!do_bind && is_inet) {
2060                 sa_fam = rbsda->u.sa.sa_family;
2061                 switch (sa_fam) {
2062                 case AF_INET:
2063                         sa_socklen = sizeof(rbsda->u.in);
2064                         do_ipv6only = false;
2065                         break;
2066 #ifdef HAVE_IPV6
2067                 case AF_INET6:
2068                         sa_socklen = sizeof(rbsda->u.in6);
2069                         do_ipv6only = true;
2070                         break;
2071 #endif
2072                 }
2073         }
2074
2075         state->fd = socket(sa_fam, SOCK_STREAM, 0);
2076         if (state->fd == -1) {
2077                 tevent_req_error(req, errno);
2078                 goto post;
2079         }
2080
2081         state->fd = tsocket_bsd_common_prepare_fd(state->fd, true);
2082         if (state->fd == -1) {
2083                 tevent_req_error(req, errno);
2084                 goto post;
2085         }
2086
2087 #ifdef HAVE_IPV6
2088         if (do_ipv6only) {
2089                 int val = 1;
2090
2091                 ret = setsockopt(state->fd, IPPROTO_IPV6, IPV6_V6ONLY,
2092                                  (const void *)&val, sizeof(val));
2093                 if (ret == -1) {
2094                         tevent_req_error(req, errno);
2095                         goto post;
2096                 }
2097         }
2098 #endif
2099
2100         if (do_reuseaddr) {
2101                 int val = 1;
2102
2103                 ret = setsockopt(state->fd, SOL_SOCKET, SO_REUSEADDR,
2104                                  (const void *)&val, sizeof(val));
2105                 if (ret == -1) {
2106                         tevent_req_error(req, errno);
2107                         goto post;
2108                 }
2109         }
2110
2111         if (do_bind) {
2112                 ret = bind(state->fd, &lbsda->u.sa, sa_socklen);
2113                 if (ret == -1) {
2114                         tevent_req_error(req, errno);
2115                         goto post;
2116                 }
2117         }
2118
2119         if (rbsda->u.sa.sa_family != sa_fam) {
2120                 tevent_req_error(req, EINVAL);
2121                 goto post;
2122         }
2123
2124         ret = connect(state->fd, &rbsda->u.sa, sa_socklen);
2125         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
2126         if (retry) {
2127                 /* retry later */
2128                 goto async;
2129         }
2130         if (tevent_req_error(req, err)) {
2131                 goto post;
2132         }
2133
2134         tevent_req_done(req);
2135         goto post;
2136
2137  async:
2138         state->fde = tevent_add_fd(ev, state,
2139                                    state->fd,
2140                                    TEVENT_FD_READ | TEVENT_FD_WRITE,
2141                                    tstream_bsd_connect_fde_handler,
2142                                    req);
2143         if (tevent_req_nomem(state->fde, req)) {
2144                 goto post;
2145         }
2146
2147         return req;
2148
2149  post:
2150         tevent_req_post(req, ev);
2151         return req;
2152 }
2153
2154 static void tstream_bsd_connect_fde_handler(struct tevent_context *ev,
2155                                             struct tevent_fd *fde,
2156                                             uint16_t flags,
2157                                             void *private_data)
2158 {
2159         struct tevent_req *req = talloc_get_type_abort(private_data,
2160                                  struct tevent_req);
2161         struct tstream_bsd_connect_state *state = tevent_req_data(req,
2162                                         struct tstream_bsd_connect_state);
2163         int ret;
2164         int error=0;
2165         socklen_t len = sizeof(error);
2166         int err;
2167         bool retry;
2168
2169         ret = getsockopt(state->fd, SOL_SOCKET, SO_ERROR, &error, &len);
2170         if (ret == 0) {
2171                 if (error != 0) {
2172                         errno = error;
2173                         ret = -1;
2174                 }
2175         }
2176         err = tsocket_bsd_error_from_errno(ret, errno, &retry);
2177         if (retry) {
2178                 /* retry later */
2179                 return;
2180         }
2181         if (tevent_req_error(req, err)) {
2182                 return;
2183         }
2184
2185         tevent_req_done(req);
2186 }
2187
2188 static int tstream_bsd_connect_recv(struct tevent_req *req,
2189                                     int *perrno,
2190                                     TALLOC_CTX *mem_ctx,
2191                                     struct tstream_context **stream,
2192                                     const char *location)
2193 {
2194         struct tstream_bsd_connect_state *state = tevent_req_data(req,
2195                                         struct tstream_bsd_connect_state);
2196         int ret;
2197
2198         ret = tsocket_simple_int_recv(req, perrno);
2199         if (ret == 0) {
2200                 ret = _tstream_bsd_existing_socket(mem_ctx,
2201                                                    state->fd,
2202                                                    stream,
2203                                                    location);
2204                 if (ret == -1) {
2205                         *perrno = errno;
2206                         goto done;
2207                 }
2208                 TALLOC_FREE(state->fde);
2209                 state->fd = -1;
2210         }
2211
2212 done:
2213         tevent_req_received(req);
2214         return ret;
2215 }
2216
2217 struct tevent_req * tstream_inet_tcp_connect_send(TALLOC_CTX *mem_ctx,
2218                                         struct tevent_context *ev,
2219                                         const struct tsocket_address *local,
2220                                         const struct tsocket_address *remote)
2221 {
2222         struct tsocket_address_bsd *lbsda =
2223                 talloc_get_type_abort(local->private_data,
2224                 struct tsocket_address_bsd);
2225         struct tevent_req *req;
2226         int sys_errno = 0;
2227
2228         switch (lbsda->u.sa.sa_family) {
2229         case AF_INET:
2230                 break;
2231 #ifdef HAVE_IPV6
2232         case AF_INET6:
2233                 break;
2234 #endif
2235         default:
2236                 sys_errno = EINVAL;
2237                 break;
2238         }
2239
2240         req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote);
2241
2242         return req;
2243 }
2244
2245 int _tstream_inet_tcp_connect_recv(struct tevent_req *req,
2246                                    int *perrno,
2247                                    TALLOC_CTX *mem_ctx,
2248                                    struct tstream_context **stream,
2249                                    const char *location)
2250 {
2251         return tstream_bsd_connect_recv(req, perrno, mem_ctx, stream, location);
2252 }
2253
2254 struct tevent_req * tstream_unix_connect_send(TALLOC_CTX *mem_ctx,
2255                                         struct tevent_context *ev,
2256                                         const struct tsocket_address *local,
2257                                         const struct tsocket_address *remote)
2258 {
2259         struct tsocket_address_bsd *lbsda =
2260                 talloc_get_type_abort(local->private_data,
2261                 struct tsocket_address_bsd);
2262         struct tevent_req *req;
2263         int sys_errno = 0;
2264
2265         switch (lbsda->u.sa.sa_family) {
2266         case AF_UNIX:
2267                 break;
2268         default:
2269                 sys_errno = EINVAL;
2270                 break;
2271         }
2272
2273         req = tstream_bsd_connect_send(mem_ctx, ev, sys_errno, local, remote);
2274
2275         return req;
2276 }
2277
2278 int _tstream_unix_connect_recv(struct tevent_req *req,
2279                                       int *perrno,
2280                                       TALLOC_CTX *mem_ctx,
2281                                       struct tstream_context **stream,
2282                                       const char *location)
2283 {
2284         return tstream_bsd_connect_recv(req, perrno, mem_ctx, stream, location);
2285 }
2286
2287 int _tstream_unix_socketpair(TALLOC_CTX *mem_ctx1,
2288                              struct tstream_context **_stream1,
2289                              TALLOC_CTX *mem_ctx2,
2290                              struct tstream_context **_stream2,
2291                              const char *location)
2292 {
2293         int ret;
2294         int fds[2];
2295         int fd1;
2296         int fd2;
2297         struct tstream_context *stream1 = NULL;
2298         struct tstream_context *stream2 = NULL;
2299
2300         ret = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
2301         if (ret == -1) {
2302                 return -1;
2303         }
2304         fd1 = fds[0];
2305         fd2 = fds[1];
2306
2307         fd1 = tsocket_bsd_common_prepare_fd(fd1, true);
2308         if (fd1 == -1) {
2309                 int sys_errno = errno;
2310                 close(fd2);
2311                 errno = sys_errno;
2312                 return -1;
2313         }
2314
2315         fd2 = tsocket_bsd_common_prepare_fd(fd2, true);
2316         if (fd2 == -1) {
2317                 int sys_errno = errno;
2318                 close(fd1);
2319                 errno = sys_errno;
2320                 return -1;
2321         }
2322
2323         ret = _tstream_bsd_existing_socket(mem_ctx1,
2324                                            fd1,
2325                                            &stream1,
2326                                            location);
2327         if (ret == -1) {
2328                 int sys_errno = errno;
2329                 close(fd1);
2330                 close(fd2);
2331                 errno = sys_errno;
2332                 return -1;
2333         }
2334
2335         ret = _tstream_bsd_existing_socket(mem_ctx2,
2336                                            fd2,
2337                                            &stream2,
2338                                            location);
2339         if (ret == -1) {
2340                 int sys_errno = errno;
2341                 talloc_free(stream1);
2342                 close(fd2);
2343                 errno = sys_errno;
2344                 return -1;
2345         }
2346
2347         *_stream1 = stream1;
2348         *_stream2 = stream2;
2349         return 0;
2350 }
2351