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