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