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