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