1 /*
2  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3  *               2008, 2009, 2010, 2011, 2012, 2013, 2014
4  *      Inferno Nettverk A/S, Norway.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. The above copyright notice, this list of conditions and the following
10  *    disclaimer must appear in all copies of the software, derivative works
11  *    or modified versions, and any portions thereof, aswell as in all
12  *    supporting documentation.
13  * 2. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by
16  *      Inferno Nettverk A/S, Norway.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  * Inferno Nettverk A/S requests users of this software to return to
32  *
33  *  Software Distribution Coordinator  or  sdc@inet.no
34  *  Inferno Nettverk A/S
35  *  Oslo Research Park
36  *  Gaustadall�en 21
37  *  NO-0349 Oslo
38  *  Norway
39  *
40  * any improvements or extensions that they make and grant Inferno Nettverk A/S
41  * the rights to redistribute these changes.
42  *
43  */
44 
45 #include "common.h"
46 #include "config_parse.h"
47 
48 static const char rcsid[] =
49 "$Id: sockd_udp.c,v 1.58.4.4 2014/08/15 18:16:44 karls Exp $";
50 
51 extern int       rawsocket;
52 extern iostate_t iostate;
53 
54 #if HAVE_SO_TIMESTAMP
55 struct iostats {
56    iostat_t ro;    /* read-only stats.    */
57    iostat_t rw;    /* read/write stats.   */
58 } iostats;
59 
60 
61 static iostat_t *
62 io_updatestat(iostat_t *iostat);
63 /*
64  * Updates (recalculates) the info in "iostat".
65  * Returns a pointer to the updated iostats, or NULL if information
66  * is not yet available.
67  */
68 
69 
70 static int
71 io_timercmp(const void *a, const void *b);
72 /*
73  * Comparison function compatible with qsort.
74  * "a" and "b" are pointers to struct timeval.
75  */
76 
77 #endif /* HAVE_SO_TIMESTAMP */
78 
79 iostatus_t
doio_udp(io,rset,badfd)80 doio_udp(io, rset, badfd)
81    sockd_io_t *io;
82    fd_set *rset;
83    int *badfd;
84 {
85    /*
86     * In the socks case the client-side of udp i/o is always fixed.
87     * In barefoot the client-side can/will vary for each packet,
88     * as one socket can receive packets from multiple clients.
89     *
90     * Also note that we are less strict about bandwidth in the udp
91     * case since we can't truncate packets.  Therefore we don't limit
92     * the amount of i/o we do in one go for the udp-case; it has to be
93     * whole packets.  Trying to buffer udp packets would probably be
94     * suboptimal latency-wise, even if we could attempt to do it by
95     * expanding the iobuf-mechanism to handle udp also.
96     *
97     * In both Barefoot and Dante we need to do both a rulespermit()
98     * per packet, but we also need to save the original rule that
99     * allowed the udp session (in Barefoot's case, we fake the session).
100     *
101     * In Dante, the "original" rule is the socks-rule that matched the
102     * clients's udpassociate request, or the first udp packet if the address
103     * in the request was not exact.  In Barefoot it is the client-rule that
104     * was used to generate the corresponding socks-rule.
105     *
106     * E.g., the following will work correctly since only one of the
107     * rules below can be assigned to any udp client in Barefoot and the
108     * assignment is fixed (until SIGHUP at least):
109     *
110     * client pass { from: 10.1/16 to: 10.1.1.1/32 port = echo
111     *               bounce to: 10.10.10.1 port = echo
112     *               maxsessions: 10 }
113     *
114     * client pass { from: 10.2/16 to: 10.1.1.1/32 port = echo
115     *               bounce to: 10.10.10.2 port = echo
116     *               maxsessions: 1 }
117     *
118     * Correspondingly, in Dante, the below will not work as the
119     * socks udp client can change it's destination at any time.
120     *
121     * pass { from: 10/8 to: 10.1.1.1/32 port = echo
122     *        maxsessions: 10 }
123     *
124     * pass { from: 10/8 to: 10.1.1.2/32 port = echo
125     *        maxsessions: 1 }
126     *
127     * E.g., assume that the client first sends packets matching rule
128     * #1, having a maxsessions value of 10.  It then sends a packet
129     * matching rule #2, and then a packet matching rule #1 again.
130     * Do we then allocate two sessions to this client, one from rule #1
131     * and one from rule #2?  Obviously not.
132     * Do we move the client from the session belonging to rule #1 when it
133     * sends a packet matching rule #2, and then move it back again from
134     * rule #2 to rule #1?  Also obviously not.
135     * Instead we do the simple thing and and lock the resources when the
136     * udp session is established, which will be in the request child.
137     */
138    const char *function   = "doio_udp()";
139    iostatus_t iostatus;
140    size_t sideschecked;
141    iologaddr_t src, dst;
142 
143 #if BAREFOOTD
144 
145    rule_t packetrule;
146 
147 #else /* SOCKS_SERVER */
148 
149    rule_t *packetrule;
150 
151 #endif /* SOCKS_SERVER */
152 
153 
154    SASSERTX(io->allocated);
155    SASSERTX(io->state.protocol == SOCKS_UDP);
156 
157 #if DIAGNOSTIC /* no buffering of udp should be done. */
158    SASSERTX(socks_bufferhasbytes(io->src.s, WRITE_BUF) == 0);
159    SASSERTX(socks_bufferhasbytes(io->src.s, READ_BUF)  == 0);
160    SASSERTX(socks_bufferhasbytes(io->dst.s, WRITE_BUF) == 0);
161    SASSERTX(socks_bufferhasbytes(io->dst.s, READ_BUF)  == 0);
162 #endif /* DIAGNOSTIC */
163 
164    init_iologaddr(&src,
165                   object_sockaddr,
166                   &io->src.laddr,
167                   object_sockaddr,
168                   &io->src.raddr,
169                   &io->src.auth,
170                   NULL,
171                   0);
172 
173    init_iologaddr(&dst,
174                   object_sockaddr,
175                   io->dst.s == -1 ? NULL : &io->dst.laddr,
176                   object_sockaddr,
177                   io->dst.s == -1 ? NULL : &io->dst.raddr,
178                   io->dst.s == -1 ? NULL : &io->dst.auth,
179                   NULL,
180                   0);
181 
182    slog(LOG_DEBUG, "%s: control-fd %d, src-fd %d, dst-fd %d",
183         function, io->control.s, io->src.s, io->dst.s);
184 
185    if (!timerisset(&io->state.time.firstio))
186       gettimeofday_monotonic(&io->state.time.firstio);
187 
188    errno  = 0; /* reset before each call. */
189    *badfd = -1;
190 
191    iostatus     = IO_EAGAIN;
192    sideschecked = 0;
193 
194    /*
195     * UDP to relay from client to destination?
196     */
197 
198    if (FD_ISSET(io->src.s, rset)) {
199       const int originaldst = io->dst.s;
200       iocount_t src_read    = io->src.read,
201                 src_written = io->src.written,
202                 dst_read    = io->dst.read,
203                 dst_written = io->dst.written;
204       iologaddr_t lsrc = src, ldst = dst;
205       size_t bwused = 0;
206 
207       ++sideschecked;
208 
209       /*
210        * Don't yet know what the target address/socket used will be.
211        * If any data is actually to be forwarded to a target, this will
212        * be updated based on the target.
213        */
214       io->dst.s = -1;
215 
216 #if BAREFOOTD
217       /*
218        * initalize to crule, and if we get far enough, rulespermit() will
219        * update it, possibly changing it to another crule based on the source
220        * address of the client who sent the packet we will read.
221        *
222        * Since we want to be sure to not change the original crule,
223        * don't use a pointer for packetrule.
224        */
225       packetrule = io->crule;
226 
227       slog(LOG_DEBUG, "%s: client2target i/o on fd %d -> fd %d",
228            function, io->src.s, io->dst.s);
229 
230       iostatus = io_udp_client2target(&io->src,
231                                       &io->dst,
232                                       &io->cauth,
233                                       &io->state,
234                                       &lsrc,
235                                       &ldst,
236                                       badfd,
237                                       &packetrule,
238                                       &bwused);
239 
240 #else /* SOCKS_SERVER */
241 
242       /*
243        * Default to packetrule being the rule matched for this udp session,
244        * unless we've progressed far enough to have a previously saved rule
245        * to use.
246        */
247       if (!io->src.state.use_saved_srule)
248          *io->cmd.udp.sfwdrule = io->srule; /* reset to initial match. */
249 
250       packetrule = io->cmd.udp.sfwdrule;
251 
252       slog(LOG_DEBUG, "%s: client2target i/o on fd %d -> {fd %d, fd %d}",
253            function, io->src.s, io->dst.dstv[0].s, io->dst.dstv[1].s);
254 
255       iostatus = io_udp_client2target(&io->control,
256                                       &io->src,
257                                       &io->dst,
258                                       &io->cauth,
259                                       &io->state,
260                                       &lsrc,
261                                       &ldst,
262                                       badfd,
263                                       packetrule,
264                                       &bwused);
265 #endif /* SOCKS_SERVER */
266 
267       if (IOSTATUS_FATALERROR(iostatus))
268          /* can not be sure the error did not affect dst, so return now. */
269          return iostatus;
270 
271       if (iostatus == IO_NOERROR) {
272          DO_IOCOUNT(&src_read,
273                     &src_written,
274                     &dst_read,
275                     &dst_written,
276                     io);
277 
278          io_update(&io->lastio,
279                    bwused,
280                    &src_read,
281                    NULL,
282                    NULL,
283                    &dst_written,
284 
285 #if BAREFOOTD
286                    &packetrule,
287                    &packetrule,
288 
289 #else /* SOCKS_SERVER */
290 
291                    &io->srule,
292                    packetrule,
293 
294 #endif /* SOCKS_SERVER */
295 
296                    sockscf.shmemfd);
297 
298           /*
299            * client2target will have changed dst to the object associated with
300            * the client it read the packet from, possibly a brand new dst.
301            */
302          io->dst.s = originaldst;
303       }
304       else
305          slog(LOG_DEBUG, "%s: some non-fatal error, iostatus = %d",
306               function, (int)iostatus);
307    }
308 
309    /*
310     * Datagram reply from target present?
311     */
312 
313    if (io->dst.s != -1 && FD_ISSET(io->dst.s, rset)) {
314       /*
315        * - io->src is dst of packet (our client).
316        * - io->dst is (presumably) one of client's target and can vary for
317        *   each packet.
318        */
319       iocount_t src_read    = io->src.read,
320                 src_written = io->src.written,
321                 dst_read    = io->dst.read,
322                 dst_written = io->dst.written;
323       iologaddr_t lsrc = src, ldst = dst;
324       connectionstate_t replystate;
325       size_t bwused = 0;
326 
327 #if BAREFOOTD
328       packetrule = io->crule;
329 
330 #else /* SOCKS_SERVER */
331       SASSERTX(io->cmd.udp.sfwdrule   != NULL);
332       SASSERTX(io->cmd.udp.sreplyrule != NULL);
333 
334       if (!io->dst.state.use_saved_srule)
335          *io->cmd.udp.sreplyrule = io->srule; /* reset to initial match. */
336 
337       packetrule = io->cmd.udp.sreplyrule;
338 #endif /* SOCKS_SERVER */
339 
340       replystate         = io->state;
341       replystate.command = SOCKS_UDPREPLY;
342 
343       ++sideschecked;
344 
345       slog(LOG_DEBUG,
346            "%s: target2client i/o on fd %d -> fd %d",
347            function, io->dst.s, io->src.s);
348 
349 #if BAREFOOTD
350       iostatus = io_udp_target2client(&io->src,
351                                       &io->dst,
352                                       &io->cauth,
353                                       &replystate,
354                                       &lsrc,
355                                       &ldst,
356                                       badfd,
357                                       &packetrule,
358                                       &bwused);
359 #else /* SOCKS_SERVER */
360       iostatus = io_udp_target2client(&io->control,
361                                       &io->src,
362                                       &io->dst,
363                                       &replystate,
364                                       &lsrc,
365                                       &ldst,
366                                       badfd,
367                                       packetrule,
368                                       &bwused);
369 #endif /* SOCKS_SERVER */
370 
371 
372       if (IOSTATUS_FATALERROR(iostatus))
373          return iostatus;
374 
375       if (iostatus == IO_NOERROR) {
376          DO_IOCOUNT(&src_read,
377                     &src_written,
378                     &dst_read,
379                     &dst_written,
380                     io);
381 
382          io_update(&io->lastio,
383                    bwused,
384                    NULL,
385                    &src_written,
386                    &dst_read,
387                    NULL,
388 
389 #if BAREFOOTD
390                    &packetrule,
391                    &packetrule,
392 
393 #else /* SOCKS_SERVER */
394 
395                    &io->srule,
396                    packetrule,
397 
398 #endif /* SOCKS_SERVER */
399 
400                    sockscf.shmemfd);
401       }
402    }
403 
404    SASSERTX(sideschecked > 0);
405 
406    gettimeofday_monotonic(&io->lastio);
407 
408    return iostatus;
409 }
410 
411 iostatus_t
io_packet_received(recvflags,bytesreceived,from,receivedon)412 io_packet_received(recvflags, bytesreceived, from, receivedon)
413    const recvfrom_info_t *recvflags;
414    const size_t bytesreceived;
415    const struct sockaddr_storage *from;
416    const struct sockaddr_storage *receivedon;
417 {
418    const char *function = "io_packet_received()";
419 #if HAVE_SO_TIMESTAMP
420    struct timeval tnow, latency;
421 #endif /* HAVE_SO_TIMESTAMP */
422 
423    if (recvflags->flags & MSG_TRUNC) {
424       log_truncatedudp(function, from, bytesreceived);
425       return IO_TMPERROR;
426    }
427 
428 #if HAVE_SO_TIMESTAMP
429    gettimeofday(&tnow, NULL);
430 
431    io_addts(io_calculatelatency(&recvflags->ts, &tnow, &latency), from, NULL);
432 #endif /* HAVE_SO_TIMESTAMP */
433 
434    return IO_NOERROR;
435 }
436 
437 iostatus_t
io_packet_sent(bytestosend,bytessent,tsreceived,from,to,emsg,emsglen)438 io_packet_sent(bytestosend, bytessent, tsreceived, from, to, emsg, emsglen)
439    const size_t bytestosend;
440    const size_t bytessent;
441    const struct timeval *tsreceived;
442    const struct sockaddr_storage *from;
443    const struct sockaddr_storage *to;
444    char *emsg;
445    size_t emsglen;
446 {
447    const char *function = "io_packet_sent()";
448 #if HAVE_SO_TIMESTAMP
449    struct timeval tnow, latency;
450 
451    gettimeofday(&tnow, NULL);
452 
453    io_addts(io_calculatelatency(tsreceived, &tnow, &latency), from, to);
454 #endif /* HAVE_SO_TIMESTAMP */
455 
456    if (bytestosend != bytessent) {
457       snprintf(emsg, emsglen, "%s", strerror(errno));
458 
459       slog(LOG_DEBUG, "%s: sendto() failed: %s", function, emsg);
460 
461       if (ERRNOISTMP(errno))
462          return IO_TMPERROR;
463       else
464          return IO_IOERROR;
465    }
466 
467    return IO_NOERROR;
468 }
469 
470 iostat_t *
io_get_io_stats(void)471 io_get_io_stats(void)
472 {
473 
474 #if HAVE_SO_TIMESTAMP
475    return io_updatestat(&iostats.rw);
476 #else /* !HAVE_SO_TIMESTAMP */
477    return NULL;
478 #endif /* !HAVE_SO_TIMESTAMP */
479 }
480 
481 iostat_t *
io_get_ro_stats(void)482 io_get_ro_stats(void)
483 {
484 
485 #if HAVE_SO_TIMESTAMP
486    return io_updatestat(&iostats.ro);
487 #else /* !HAVE_SO_TIMESTAMP */
488    return NULL;
489 #endif /* !HAVE_SO_TIMESTAMP */
490 }
491 
492 struct timeval *
io_calculatelatency(ts_recv,tnow,latency)493 io_calculatelatency(ts_recv, tnow, latency)
494    const struct timeval *ts_recv;
495    const struct timeval *tnow;
496    struct timeval *latency;
497 {
498    const char *function = "io_calculatelatency()";
499 
500    timersub(tnow, ts_recv, latency);
501 
502    return latency;
503 }
504 
505 #if HAVE_SO_TIMESTAMP
506 void
io_addts(ts,from,to)507 io_addts(ts, from, to)
508    const struct timeval *ts;
509    const struct sockaddr_storage *from;
510    const struct sockaddr_storage *to;
511 {
512    const char *function = "io_addts()";
513    iostat_t *iostat;
514    char fstr[MAXSOCKADDRSTRING], tstr[MAXSOCKADDRSTRING];
515 
516    slog(ts->tv_sec < 0 ? LOG_WARNING : LOG_DEBUG,
517         "%s: packetlatency for packet from %s to %s: %ld.%06lds%s",
518         function,
519         sockaddr2string(from, fstr, sizeof(fstr)),
520         to == NULL ? "<read by us>" : sockaddr2string(to, tstr, sizeof(tstr)),
521         (long)ts->tv_sec,
522         (long)ts->tv_usec,
523         ts->tv_sec < 0 ?
524             ".  Sub-zero latency.  Impossible.  Clock changed?" : "");
525 
526    if (ts->tv_sec < 0)
527       return;
528 
529    if (to == NULL)
530       iostat = &iostats.ro;
531    else
532       iostat = &iostats.rw;
533 
534    if (iostat->lastlatencyi + 1 >= ELEMENTS(iostat->latencyv))
535       iostat->lastlatencyi = 0; /* treat as a circular buffer. */
536    else {
537       if (iostat->latencyc > 0)
538          ++iostat->lastlatencyi;
539 
540       if (iostat->latencyc < ELEMENTS(iostat->latencyv))
541          ++iostat->latencyc;
542       /* else; keep at max - that's how many ts's we have. */
543    }
544 
545    iostat->latencyv[iostat->lastlatencyi] = *ts;
546 
547    SASSERTX(iostat->latencyc     <= ELEMENTS(iostat->latencyv));
548    SASSERTX(iostat->lastlatencyi <= ELEMENTS(iostat->latencyv));
549 }
550 
551 static iostat_t *
io_updatestat(iostat)552 io_updatestat(iostat)
553    iostat_t *iostat;
554 {
555    const char *function = "io_updatestat()";
556 
557    if (iostat->latencyc == 0)
558       return NULL;
559 
560    SASSERTX(iostat->latencyc <= ELEMENTS(iostat->latencyv));
561 
562    /* save last ts before we start sorting the info. */
563    SASSERTX(iostat->lastlatencyi < ELEMENTS(iostat->latencyv));
564    iostat->last_us = tv2us(&iostat->latencyv[iostat->lastlatencyi]);
565 
566    /*
567     * the rest of the calculations require a sorted array.
568     */
569    qsort(iostat->latencyv,
570          iostat->latencyc,
571          sizeof(*iostat->latencyv),
572          io_timercmp);
573 
574    iostat->min_us     = tv2us(&iostat->latencyv[0]);
575    iostat->max_us     = tv2us(&iostat->latencyv[iostat->latencyc - 1]);
576    iostat->median_us  = medtv(iostat->latencyv, iostat->latencyc);
577    iostat->average_us = avgtv(iostat->latencyv, iostat->latencyc);
578    iostat->stddev_us  = stddevtv(iostat->latencyv,
579                                  iostat->latencyc,
580                                  iostat->average_us);
581 
582 #if 0
583    for (i = 0; i < iostat->latencyc; ++i) {
584       slog(LOG_DEBUG, "%s: index #%lu, latency: %ld.%06ld",
585            function,
586            (unsigned long)i,
587            (long)iostat->latencyv[i].tv_sec,
588            (long)iostat->latencyv[i].tv_usec);
589    }
590 #endif
591 
592    return iostat;
593 }
594 
595 static int
io_timercmp(a,b)596 io_timercmp(a, b)
597    const void *a;
598    const void *b;
599 {
600 
601    if (timercmp((const struct timeval *)a, (const struct timeval *)b, <))
602       return -1;
603 
604    if (timercmp((const struct timeval *)a, (const struct timeval *)b, ==))
605       return 0;
606 
607    return 1;
608 }
609 #endif /* HAVE_SO_TIMESTAMP */
610 
611 udptarget_t *
initclient(control,client_l,client_r,tohost,toaddr,rule,emsg,emsglen,udpdst)612 initclient(control, client_l, client_r, tohost, toaddr, rule,
613             emsg, emsglen, udpdst)
614    const int control;
615    const struct sockaddr_storage *client_l;
616    const struct sockaddr_storage *client_r;
617    const sockshost_t *tohost;
618    const struct sockaddr_storage *toaddr;
619    const rule_t *rule;
620    char *emsg;
621    const size_t emsglen;
622    udptarget_t *udpdst;
623 {
624    const char *function = "initclient()";
625    char fromstr[MAXSOCKADDRSTRING], tohoststr[MAXSOCKSHOSTSTRING],
626         toaddrstr[MAXSOCKADDRSTRING];
627    int s, rc;
628 
629    slog(LOG_DEBUG, "%s: from %s to %s (%s)",
630         function,
631         sockaddr2string(client_r, fromstr,   sizeof(fromstr)),
632         sockshost2string(tohost,  tohoststr, sizeof(tohoststr)),
633         sockaddr2string(toaddr,   toaddrstr, sizeof(toaddrstr)));
634 
635    bzero(udpdst, sizeof(*udpdst));
636 
637    udpdst->raddrhost = *tohost;
638    udpdst->raddr     = *toaddr;
639 
640    /*
641     * Create a new socket and use that for sending out packets
642     * from this client only.  When reading replies on this socket,
643     * we will thus know who it's destined for (from).
644     * Since we place no bound on the number of udp clients we
645     * handle, we need to make sure we leave room for at least
646     * SOCKD_IOMAX tcp clients, so we don't fail on recvmsg(2)
647     * when mother sends us a new tcp client.
648     */
649 
650    errno = 0;
651    s     = -1;
652 
653    if (iostate.freefds  <= ((SOCKD_IOMAX - 1) * FDPASS_MAX)
654    || (s = socket(udpdst->raddr.ss_family, SOCK_DGRAM, 0)) == -1) {
655       snprintf(emsg, emsglen, "could not create %s udp socket: %s",
656                safamily2string(udpdst->raddr.ss_family),
657                errno == 0 ?
658                   "already running short of sockets" : strerror(errno));
659 
660       swarnx("%s: %s", function, emsg);
661 
662       if (s != -1)
663          close(s);
664 
665       return NULL;
666    }
667 
668    SASSERTX(s != -1);
669 
670    if (getoutaddr(&udpdst->laddr,
671                   client_l,
672                   client_r,
673                   SOCKS_UDPASSOCIATE,
674                   &udpdst->raddrhost,
675                   emsg,
676                   emsglen) == NULL) {
677       slog(LOG_DEBUG,
678            "%s: could not establish address to use for sending UDP to %s: %s",
679            function, sockshost2string(&udpdst->raddrhost, NULL, 0), emsg);
680 
681       close(s);
682       return NULL;
683    }
684 
685    setsockoptions(s, udpdst->raddr.ss_family, SOCK_DGRAM, 0);
686 
687    setconfsockoptions(s,
688                       control,
689                       SOCKS_UDP,
690                       0,
691                       rule->socketoptionc,
692                       rule->socketoptionv,
693                       SOCKETOPT_PRE | SOCKETOPT_ANYTIME,
694                       SOCKETOPT_PRE | SOCKETOPT_ANYTIME);
695 
696    if ((rc = socks_bind(s, &udpdst->laddr, 0)) != 0) {
697       if (GET_SOCKADDRPORT(&udpdst->laddr) != htons(0))
698          SET_SOCKADDRPORT(&udpdst->laddr, htons(0));
699 
700       rc = socks_bind(s, &udpdst->laddr, 0);
701    }
702 
703    if (rc != 0) {
704       log_bind_failed(function, SOCKS_UDP, &udpdst->laddr);
705 
706       snprintf(emsg, emsglen, "could not bind udp address %s: %s",
707                sockaddr2string(&udpdst->laddr, NULL, 0),
708                strerror(errno));
709 
710       close(s);
711       return NULL;
712    }
713 
714    log_boundexternaladdress(function, &udpdst->laddr);
715 
716 #if SOCKS_SERVER
717   /*
718    * Dante uses iobufs for some udp stuff too (just to save a getsockopt(2)
719    * call?), though we don't buffer udp packets.  Barefootd is not dimensioned
720    * for allocating iobufs for udp however.
721    */
722   socks_allocbuffer(s, SOCK_DGRAM);
723 #endif /* SOCKS_SERVER */
724 
725    /*
726     * All ok, save contents into udpdst and return success.
727     */
728 
729 
730 #if BAREFOOTD
731    sockaddrcpy(&udpdst->client, client_r, salen(client_r->ss_family));
732    sockaddr2sockshost(&udpdst->client, &udpdst->clienthost);
733 #endif /* BAREFOOTD */
734 
735    gettimeofday_monotonic(&udpdst->lastio);
736    udpdst->firstio = udpdst->lastio;
737    udpdst->s       = s;
738 
739    --iostate.freefds;
740 
741    slog(LOG_DEBUG,
742         "%s: allocated socket fd %d for packets from %s to, initially, %s",
743         function, udpdst->s, fromstr, tohoststr);
744 
745    return udpdst;
746 }
747 
748 udptarget_t *
addclient(clientladdr,client,clientc,maxclientc,clientv,state,rule)749 addclient(clientladdr, client, clientc, maxclientc, clientv, state, rule)
750    const struct sockaddr_storage *clientladdr;
751    const udptarget_t *client;
752    size_t *clientc;
753    size_t *maxclientc;
754    udptarget_t **clientv;
755    const connectionstate_t *state;
756    const struct rule_t *rule;
757 {
758    const char *function = "addclient()";
759 #if BAREFOOTD
760    iologaddr_t src, dst;
761 
762    char client_str[MAXSOCKADDRSTRING],
763         laddr_str[MAXSOCKADDRSTRING],
764         raddr_str[MAXSOCKSHOSTSTRING];
765 
766    slog(LOG_DEBUG,
767         "%s: adding client on fd %d: client %s, bound %s, dst %s (%s).  "
768         "New clientc will become %lu, new free fds will become %lu",
769         function,
770         client->s,
771         sockaddr2string(&client->client, client_str, sizeof(client_str)),
772         sockaddr2string(&client->laddr, laddr_str, sizeof(laddr_str)),
773         sockaddr2string(&client->raddr, raddr_str, sizeof(raddr_str)),
774         sockshost2string(&client->raddrhost, NULL, 0),
775         (unsigned long)(*clientc + 1),
776         (unsigned long)(iostate.freefds - 1));
777 
778    if (*clientc >= *maxclientc) {
779       udptarget_t *pv;
780 
781       SASSERTX(*clientc == *maxclientc);
782 
783       if ((pv = realloc(*clientv, ((*maxclientc) + 1) * sizeof(*pv))) == NULL) {
784          swarn("%s: failed to allocate memory for new udp client from %s",
785                function, sockaddr2string(&client->client, NULL, 0));
786 
787          return NULL;
788       }
789 
790       if (pv != *clientv)
791          *clientv = pv;
792 
793       *maxclientc += 1;
794 
795       slog(LOG_DEBUG,
796            "%s: reallocated memory for udp clients.  Have memory for a total "
797            "of %lu clients now, and %lu clients already",
798            function, (unsigned long)*maxclientc, (unsigned long)*clientc);
799    }
800 
801 #else  /* !BAREFOOTD */
802 
803       /*
804        * In Dante there can never be more than two; one for IPv4 and
805        * one for IPv6.
806        */
807       SASSERTX(*clientc < *maxclientc);
808 #endif /* !BAREFOOTD */
809 
810    (*clientv)[*clientc] = *client;
811 
812 #if BAREFOOTD
813    init_iologaddr(&src,
814                   object_sockaddr,
815                   clientladdr,
816                   object_sockshost,
817                   &client->clienthost,
818                   NULL,
819                   NULL,
820                   0);
821 
822    init_iologaddr(&dst,
823                   object_sockaddr,
824                   &client->laddr,
825                   object_sockshost,
826                   &client->raddrhost,
827                   NULL,
828                   NULL,
829                   0);
830 
831    iolog(rule,
832          state,
833          OPERATION_CONNECT,
834          &src,
835          &dst,
836          NULL,
837          NULL,
838          NULL,
839          0);
840 #endif /* !BAREFOOTD */
841 
842    return &(*clientv)[(*clientc)++];
843 }
844 
845 void
io_syncudp(io,udpclient)846 io_syncudp(io, udpclient)
847    sockd_io_t *io;
848    udptarget_t *udpclient;
849 {
850    io->state.time.established     = udpclient->firstio;
851 
852 #if BAREFOOTD
853    io->crule                      = udpclient->crule;
854 #endif /* BAREFOOTD */
855 
856    io_syncudpsrc(&io->src, udpclient);
857 
858    io_syncudpdst(&io->dst, udpclient);
859 }
860 
861 void
io_syncudpsrc(src,udpclient)862 io_syncudpsrc(src, udpclient)
863    sockd_io_direction_t *src;
864    const udptarget_t *udpclient;
865 {
866 
867    /* src.laddr is the same for all clients and never changes. */
868 
869 #if BAREFOOTD
870    /*
871     * In Dante this remain the same as Dante only has one client per
872     * udp i/o-session.  Each client can have up to two targets though,
873     * with independent byte counts for each.
874     */
875 
876    src->raddr                 = udpclient->client;
877    src->host                  = udpclient->clienthost;
878 #endif /* BAREFOOTD */
879 
880    src->read                  = udpclient->client_read;
881    src->written               = udpclient->client_written;
882 }
883 
884 
885 void
io_syncudpdst(dst,udptarget)886 io_syncudpdst(dst, udptarget)
887    sockd_io_direction_t *dst;
888    const udptarget_t *udptarget;
889 {
890    dst->s                     = udptarget->s;
891    dst->laddr                 = udptarget->laddr;
892    dst->raddr                 = udptarget->raddr;
893    dst->host                  = udptarget->raddrhost;
894 
895    dst->read                  = udptarget->target_read;
896    dst->written               = udptarget->target_written;
897 
898    dst->state.isconnected     = udptarget->isconnected;
899 }
900 
901 
902 
903 udptarget_t *
clientofsocket(s,udpclientc,udpclientv)904 clientofsocket(s, udpclientc, udpclientv)
905    const int s;
906    const size_t udpclientc;
907    udptarget_t *udpclientv;
908 {
909    static size_t i;
910 
911    if (i < udpclientc && udpclientv[i].s == s)
912       return &udpclientv[i];
913 
914    for (i = 0; i < udpclientc; ++i)
915       if (udpclientv[i].s == s)
916          return &udpclientv[i];
917 
918    return NULL;
919 }
920