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