• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * @file
3  * User Datagram Protocol module\n
4  * The code for the User Datagram Protocol UDP & UDPLite (RFC 3828).\n
5  * See also @ref udp_raw
6  *
7  * @defgroup udp_raw UDP
8  * @ingroup callbackstyle_api
9  * User Datagram Protocol module\n
10  * @see @ref api
11  */
12 
13 /*
14  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without modification,
18  * are permitted provided that the following conditions are met:
19  *
20  * 1. Redistributions of source code must retain the above copyright notice,
21  *    this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright notice,
23  *    this list of conditions and the following disclaimer in the documentation
24  *    and/or other materials provided with the distribution.
25  * 3. The name of the author may not be used to endorse or promote products
26  *    derived from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
29  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
30  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
31  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
33  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
37  * OF SUCH DAMAGE.
38  *
39  * This file is part of the lwIP TCP/IP stack.
40  *
41  * Author: Adam Dunkels <adam@sics.se>
42  *
43  */
44 
45 /* @todo Check the use of '(struct udp_pcb).chksum_len_rx'!
46  */
47 
48 #include "lwip/opt.h"
49 
50 #if LWIP_UDP /* don't build if not configured for use in lwipopts.h */
51 
52 #include "lwip/udp.h"
53 #include "lwip/def.h"
54 #include "lwip/memp.h"
55 #include "lwip/inet_chksum.h"
56 #include "lwip/ip_addr.h"
57 #include "lwip/ip6.h"
58 #include "lwip/ip6_addr.h"
59 #include "lwip/netif.h"
60 #include "lwip/icmp.h"
61 #include "lwip/icmp6.h"
62 #include "lwip/stats.h"
63 #include "lwip/snmp.h"
64 #include "lwip/dhcp.h"
65 
66 #include <string.h>
67 
68 #ifndef UDP_LOCAL_PORT_RANGE_START
69 /* From http://www.iana.org/assignments/port-numbers:
70    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
71 #define UDP_LOCAL_PORT_RANGE_START  0xc000
72 #define UDP_LOCAL_PORT_RANGE_END    0xffff
73 #define UDP_ENSURE_LOCAL_PORT_RANGE(port) ((u16_t)(((port) & (u16_t)~UDP_LOCAL_PORT_RANGE_START) + UDP_LOCAL_PORT_RANGE_START))
74 #endif
75 
76 /* last local UDP port */
77 static u16_t udp_port = UDP_LOCAL_PORT_RANGE_START;
78 
79 /* The list of UDP PCBs */
80 /* exported in udp.h (was static) */
81 struct udp_pcb *udp_pcbs;
82 
83 #ifdef LOSCFG_NET_CONTAINER
set_udp_pcb_net_group(struct udp_pcb * pcb,struct net_group * group)84 void set_udp_pcb_net_group(struct udp_pcb *pcb, struct net_group *group)
85 {
86   set_ippcb_net_group((struct ip_pcb *)pcb, group);
87 }
88 
get_net_group_from_udp_pcb(struct udp_pcb * pcb)89 struct net_group *get_net_group_from_udp_pcb(struct udp_pcb *pcb)
90 {
91   return get_net_group_from_ippcb((struct ip_pcb *)pcb);
92 }
93 #endif
94 /**
95  * Initialize this module.
96  */
97 void
udp_init(void)98 udp_init(void)
99 {
100 #ifdef LWIP_RAND
101   udp_port = UDP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
102 #endif /* LWIP_RAND */
103 }
104 
105 /**
106  * Allocate a new local UDP port.
107  *
108  * @return a new (free) local UDP port number
109  */
110 static u16_t
udp_new_port(void)111 udp_new_port(void)
112 {
113   u16_t n = 0;
114   struct udp_pcb *pcb;
115 
116 again:
117   if (udp_port++ == UDP_LOCAL_PORT_RANGE_END) {
118     udp_port = UDP_LOCAL_PORT_RANGE_START;
119   }
120   /* Check all PCBs. */
121   for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
122     if (pcb->local_port == udp_port) {
123       if (++n > (UDP_LOCAL_PORT_RANGE_END - UDP_LOCAL_PORT_RANGE_START)) {
124         return 0;
125       }
126       goto again;
127     }
128   }
129   return udp_port;
130 }
131 
132 /** Common code to see if the current input packet matches the pcb
133  * (current input packet is accessed via ip(4/6)_current_* macros)
134  *
135  * @param pcb pcb to check
136  * @param inp network interface on which the datagram was received (only used for IPv4)
137  * @param broadcast 1 if his is an IPv4 broadcast (global or subnet-only), 0 otherwise (only used for IPv4)
138  * @return 1 on match, 0 otherwise
139  */
140 static u8_t
udp_input_local_match(struct udp_pcb * pcb,struct netif * inp,u8_t broadcast)141 udp_input_local_match(struct udp_pcb *pcb, struct netif *inp, u8_t broadcast)
142 {
143   LWIP_UNUSED_ARG(inp);       /* in IPv6 only case */
144   LWIP_UNUSED_ARG(broadcast); /* in IPv6 only case */
145 
146   LWIP_ASSERT("udp_input_local_match: invalid pcb", pcb != NULL);
147   LWIP_ASSERT("udp_input_local_match: invalid netif", inp != NULL);
148 
149   /* check if PCB is bound to specific netif */
150   if ((pcb->netif_idx != NETIF_NO_INDEX) &&
151       (pcb->netif_idx != netif_get_index(ip_data.current_input_netif))) {
152     return 0;
153   }
154 
155   /* Dual-stack: PCBs listening to any IP type also listen to any IP address */
156   if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
157 #if LWIP_IPV4 && IP_SOF_BROADCAST_RECV
158     if ((broadcast != 0) && !ip_get_option(pcb, SOF_BROADCAST)) {
159       return 0;
160     }
161 #endif /* LWIP_IPV4 && IP_SOF_BROADCAST_RECV */
162     return 1;
163   }
164 
165   /* Only need to check PCB if incoming IP version matches PCB IP version */
166   if (IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ip_current_dest_addr())) {
167 #if LWIP_IPV4
168     /* Special case: IPv4 broadcast: all or broadcasts in my subnet
169      * Note: broadcast variable can only be 1 if it is an IPv4 broadcast */
170     if (broadcast != 0) {
171 #if IP_SOF_BROADCAST_RECV
172       if (ip_get_option(pcb, SOF_BROADCAST))
173 #endif /* IP_SOF_BROADCAST_RECV */
174       {
175         if (ip4_addr_isany(ip_2_ip4(&pcb->local_ip)) ||
176             ((ip4_current_dest_addr()->addr == IPADDR_BROADCAST)) ||
177             ip4_addr_netcmp(ip_2_ip4(&pcb->local_ip), ip4_current_dest_addr(), netif_ip4_netmask(inp))) {
178           return 1;
179         }
180       }
181     } else
182 #endif /* LWIP_IPV4 */
183       /* Handle IPv4 and IPv6: all or exact match */
184       if (ip_addr_isany(&pcb->local_ip) || ip_addr_cmp(&pcb->local_ip, ip_current_dest_addr())) {
185         return 1;
186       }
187   }
188 
189   return 0;
190 }
191 
192 /**
193  * Process an incoming UDP datagram.
194  *
195  * Given an incoming UDP datagram (as a chain of pbufs) this function
196  * finds a corresponding UDP PCB and hands over the pbuf to the pcbs
197  * recv function. If no pcb is found or the datagram is incorrect, the
198  * pbuf is freed.
199  *
200  * @param p pbuf to be demultiplexed to a UDP PCB (p->payload pointing to the UDP header)
201  * @param inp network interface on which the datagram was received.
202  *
203  */
204 void
udp_input(struct pbuf * p,struct netif * inp)205 udp_input(struct pbuf *p, struct netif *inp)
206 {
207   struct udp_hdr *udphdr;
208   struct udp_pcb *pcb, *prev;
209   struct udp_pcb *uncon_pcb;
210 #ifdef LOSCFG_NET_CONTAINER
211   struct net_group *inp_net_group = get_net_group_from_netif(inp);
212 #endif
213   u16_t src, dest;
214   u8_t broadcast;
215   u8_t for_us = 0;
216 
217   LWIP_UNUSED_ARG(inp);
218 
219   LWIP_ASSERT_CORE_LOCKED();
220 
221   LWIP_ASSERT("udp_input: invalid pbuf", p != NULL);
222   LWIP_ASSERT("udp_input: invalid netif", inp != NULL);
223 
224   PERF_START;
225 
226   UDP_STATS_INC(udp.recv);
227 
228   /* Check minimum length (UDP header) */
229   if (p->len < UDP_HLEN) {
230     /* drop short packets */
231     LWIP_DEBUGF(UDP_DEBUG,
232                 ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len));
233     UDP_STATS_INC(udp.lenerr);
234     UDP_STATS_INC(udp.drop);
235     MIB2_STATS_INC(mib2.udpinerrors);
236     pbuf_free(p);
237     goto end;
238   }
239 
240   udphdr = (struct udp_hdr *)p->payload;
241 
242   /* is broadcast packet ? */
243   broadcast = ip_addr_isbroadcast(ip_current_dest_addr(), ip_current_netif());
244 
245   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
246 
247   /* convert src and dest ports to host byte order */
248   src = lwip_ntohs(udphdr->src);
249   dest = lwip_ntohs(udphdr->dest);
250 
251   udp_debug_print(udphdr);
252 
253   /* print the UDP source and destination */
254   LWIP_DEBUGF(UDP_DEBUG, ("udp ("));
255   ip_addr_debug_print_val(UDP_DEBUG, *ip_current_dest_addr());
256   LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", lwip_ntohs(udphdr->dest)));
257   ip_addr_debug_print_val(UDP_DEBUG, *ip_current_src_addr());
258   LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", lwip_ntohs(udphdr->src)));
259 
260   pcb = NULL;
261   prev = NULL;
262   uncon_pcb = NULL;
263   /* Iterate through the UDP pcb list for a matching pcb.
264    * 'Perfect match' pcbs (connected to the remote port & ip address) are
265    * preferred. If no perfect match is found, the first unconnected pcb that
266    * matches the local port and ip address gets the datagram. */
267   for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
268     /* print the PCB local and remote address */
269     LWIP_DEBUGF(UDP_DEBUG, ("pcb ("));
270     ip_addr_debug_print_val(UDP_DEBUG, pcb->local_ip);
271     LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", pcb->local_port));
272     ip_addr_debug_print_val(UDP_DEBUG, pcb->remote_ip);
273     LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", pcb->remote_port));
274 
275     /* compare PCB local addr+port to UDP destination addr+port */
276 #ifdef LOSCFG_NET_CONTAINER
277     if (inp_net_group == get_net_group_from_udp_pcb(pcb) && (pcb->local_port == dest) &&
278 #else
279     if ((pcb->local_port == dest) &&
280 #endif
281         (udp_input_local_match(pcb, inp, broadcast) != 0)) {
282       if ((pcb->flags & UDP_FLAGS_CONNECTED) == 0) {
283         if (uncon_pcb == NULL) {
284           /* the first unconnected matching PCB */
285           uncon_pcb = pcb;
286 #if LWIP_IPV4
287         } else if (broadcast && ip4_current_dest_addr()->addr == IPADDR_BROADCAST) {
288           /* global broadcast address (only valid for IPv4; match was checked before) */
289           if (!IP_IS_V4_VAL(uncon_pcb->local_ip) || !ip4_addr_cmp(ip_2_ip4(&uncon_pcb->local_ip), netif_ip4_addr(inp))) {
290             /* uncon_pcb does not match the input netif, check this pcb */
291             if (IP_IS_V4_VAL(pcb->local_ip) && ip4_addr_cmp(ip_2_ip4(&pcb->local_ip), netif_ip4_addr(inp))) {
292               /* better match */
293               uncon_pcb = pcb;
294             }
295           }
296 #endif /* LWIP_IPV4 */
297         }
298 #if SO_REUSE
299         else if (!ip_addr_isany(&pcb->local_ip)) {
300           /* prefer specific IPs over catch-all */
301           uncon_pcb = pcb;
302         }
303 #endif /* SO_REUSE */
304       }
305 
306       /* compare PCB remote addr+port to UDP source addr+port */
307       if ((pcb->remote_port == src) &&
308           (ip_addr_isany_val(pcb->remote_ip) ||
309            ip_addr_cmp(&pcb->remote_ip, ip_current_src_addr()))) {
310         /* the first fully matching PCB */
311         if (prev != NULL) {
312           /* move the pcb to the front of udp_pcbs so that is
313              found faster next time */
314           prev->next = pcb->next;
315           pcb->next = udp_pcbs;
316           udp_pcbs = pcb;
317         } else {
318           UDP_STATS_INC(udp.cachehit);
319         }
320         break;
321       }
322     }
323 
324     prev = pcb;
325   }
326   /* no fully matching pcb found? then look for an unconnected pcb */
327   if (pcb == NULL) {
328     pcb = uncon_pcb;
329   }
330 
331   /* Check checksum if this is a match or if it was directed at us. */
332   if (pcb != NULL) {
333     for_us = 1;
334   } else {
335 #if LWIP_IPV6
336     if (ip_current_is_v6()) {
337       for_us = netif_get_ip6_addr_match(inp, ip6_current_dest_addr()) >= 0;
338     }
339 #endif /* LWIP_IPV6 */
340 #if LWIP_IPV4
341     if (!ip_current_is_v6()) {
342       for_us = ip4_addr_cmp(netif_ip4_addr(inp), ip4_current_dest_addr());
343     }
344 #endif /* LWIP_IPV4 */
345   }
346 
347   if (for_us) {
348     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n"));
349 #if CHECKSUM_CHECK_UDP
350     IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_CHECK_UDP) {
351 #if LWIP_UDPLITE
352       if (ip_current_header_proto() == IP_PROTO_UDPLITE) {
353         /* Do the UDP Lite checksum */
354         u16_t chklen = lwip_ntohs(udphdr->len);
355         if (chklen < sizeof(struct udp_hdr)) {
356           if (chklen == 0) {
357             /* For UDP-Lite, checksum length of 0 means checksum
358                over the complete packet (See RFC 3828 chap. 3.1) */
359             chklen = p->tot_len;
360           } else {
361             /* At least the UDP-Lite header must be covered by the
362                checksum! (Again, see RFC 3828 chap. 3.1) */
363             goto chkerr;
364           }
365         }
366         if (ip_chksum_pseudo_partial(p, IP_PROTO_UDPLITE,
367                                      p->tot_len, chklen,
368                                      ip_current_src_addr(), ip_current_dest_addr()) != 0) {
369           goto chkerr;
370         }
371       } else
372 #endif /* LWIP_UDPLITE */
373       {
374         if (udphdr->chksum != 0) {
375           if (ip_chksum_pseudo(p, IP_PROTO_UDP, p->tot_len,
376                                ip_current_src_addr(),
377                                ip_current_dest_addr()) != 0) {
378             goto chkerr;
379           }
380         }
381       }
382     }
383 #endif /* CHECKSUM_CHECK_UDP */
384     if (pbuf_remove_header(p, UDP_HLEN)) {
385       /* Can we cope with this failing? Just assert for now */
386       LWIP_ASSERT("pbuf_remove_header failed\n", 0);
387       UDP_STATS_INC(udp.drop);
388       MIB2_STATS_INC(mib2.udpinerrors);
389       pbuf_free(p);
390       goto end;
391     }
392 
393     if (pcb != NULL) {
394       MIB2_STATS_INC(mib2.udpindatagrams);
395 #if SO_REUSE && SO_REUSE_RXTOALL
396       if (ip_get_option(pcb, SOF_REUSEADDR) &&
397           (broadcast || ip_addr_ismulticast(ip_current_dest_addr()))) {
398         /* pass broadcast- or multicast packets to all multicast pcbs
399            if SOF_REUSEADDR is set on the first match */
400         struct udp_pcb *mpcb;
401         for (mpcb = udp_pcbs; mpcb != NULL; mpcb = mpcb->next) {
402 #ifdef LOSCFG_NET_CONTAINER
403           if (mpcb != pcb && inp_net_group == get_net_group_from_udp_pcb(mpcb)) {
404 #else
405           if (mpcb != pcb) {
406 #endif
407             /* compare PCB local addr+port to UDP destination addr+port */
408             if ((mpcb->local_port == dest) &&
409                 (udp_input_local_match(mpcb, inp, broadcast) != 0)) {
410               /* pass a copy of the packet to all local matches */
411               if (mpcb->recv != NULL) {
412                 struct pbuf *q;
413 #if USE_PBUF_RAM_UDP_INPUT
414                 q = pbuf_clone(PBUF_RAW, PBUF_RAM, p);
415 #else
416                 q = pbuf_clone(PBUF_RAW, PBUF_POOL, p);
417 #endif
418                 if (q != NULL) {
419                   mpcb->recv(mpcb->recv_arg, mpcb, q, ip_current_src_addr(), src);
420                 }
421               }
422             }
423           }
424         }
425       }
426 #endif /* SO_REUSE && SO_REUSE_RXTOALL */
427       /* callback */
428       if (pcb->recv != NULL) {
429         /* now the recv function is responsible for freeing p */
430         pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr(), src);
431       } else {
432         /* no recv function registered? then we have to free the pbuf! */
433         pbuf_free(p);
434         goto end;
435       }
436     } else {
437       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n"));
438 
439 #if LWIP_ICMP || LWIP_ICMP6
440       /* No match was found, send ICMP destination port unreachable unless
441          destination address was broadcast/multicast. */
442       if (!broadcast && !ip_addr_ismulticast(ip_current_dest_addr())) {
443         /* move payload pointer back to ip header */
444         pbuf_header_force(p, (s16_t)(ip_current_header_tot_len() + UDP_HLEN));
445         icmp_port_unreach(ip_current_is_v6(), p);
446       }
447 #endif /* LWIP_ICMP || LWIP_ICMP6 */
448       UDP_STATS_INC(udp.proterr);
449       UDP_STATS_INC(udp.drop);
450       MIB2_STATS_INC(mib2.udpnoports);
451       pbuf_free(p);
452     }
453   } else {
454     pbuf_free(p);
455   }
456 end:
457   PERF_STOP("udp_input");
458   return;
459 #if CHECKSUM_CHECK_UDP
460 chkerr:
461   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
462               ("udp_input: UDP (or UDP Lite) datagram discarded due to failing checksum\n"));
463   UDP_STATS_INC(udp.chkerr);
464   UDP_STATS_INC(udp.drop);
465   MIB2_STATS_INC(mib2.udpinerrors);
466   pbuf_free(p);
467   PERF_STOP("udp_input");
468 #endif /* CHECKSUM_CHECK_UDP */
469 }
470 
471 /**
472  * @ingroup udp_raw
473  * Sends the pbuf p using UDP. The pbuf is not deallocated.
474  *
475  *
476  * @param pcb UDP PCB used to send the data.
477  * @param p chain of pbuf's to be sent.
478  *
479  * The datagram will be sent to the current remote_ip & remote_port
480  * stored in pcb. If the pcb is not bound to a port, it will
481  * automatically be bound to a random port.
482  *
483  * @return lwIP error code.
484  * - ERR_OK. Successful. No error occurred.
485  * - ERR_MEM. Out of memory.
486  * - ERR_RTE. Could not find route to destination address.
487  * - ERR_VAL. No PCB or PCB is dual-stack
488  * - More errors could be returned by lower protocol layers.
489  *
490  * @see udp_disconnect() udp_sendto()
491  */
492 err_t
493 udp_send(struct udp_pcb *pcb, struct pbuf *p)
494 {
495   LWIP_ERROR("udp_send: invalid pcb", pcb != NULL, return ERR_ARG);
496   LWIP_ERROR("udp_send: invalid pbuf", p != NULL, return ERR_ARG);
497 
498   if (IP_IS_ANY_TYPE_VAL(pcb->remote_ip)) {
499     return ERR_VAL;
500   }
501 
502   /* send to the packet using remote ip and port stored in the pcb */
503   return udp_sendto(pcb, p, &pcb->remote_ip, pcb->remote_port);
504 }
505 
506 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
507 /** @ingroup udp_raw
508  * Same as udp_send() but with checksum
509  */
510 err_t
511 udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p,
512                 u8_t have_chksum, u16_t chksum)
513 {
514   LWIP_ERROR("udp_send_chksum: invalid pcb", pcb != NULL, return ERR_ARG);
515   LWIP_ERROR("udp_send_chksum: invalid pbuf", p != NULL, return ERR_ARG);
516 
517   if (IP_IS_ANY_TYPE_VAL(pcb->remote_ip)) {
518     return ERR_VAL;
519   }
520 
521   /* send to the packet using remote ip and port stored in the pcb */
522   return udp_sendto_chksum(pcb, p, &pcb->remote_ip, pcb->remote_port,
523                            have_chksum, chksum);
524 }
525 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
526 
527 /**
528  * @ingroup udp_raw
529  * Send data to a specified address using UDP.
530  *
531  * @param pcb UDP PCB used to send the data.
532  * @param p chain of pbuf's to be sent.
533  * @param dst_ip Destination IP address.
534  * @param dst_port Destination UDP port.
535  *
536  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
537  *
538  * If the PCB already has a remote address association, it will
539  * be restored after the data is sent.
540  *
541  * @return lwIP error code (@see udp_send for possible error codes)
542  *
543  * @see udp_disconnect() udp_send()
544  */
545 err_t
546 udp_sendto(struct udp_pcb *pcb, struct pbuf *p,
547            const ip_addr_t *dst_ip, u16_t dst_port)
548 {
549 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
550   return udp_sendto_chksum(pcb, p, dst_ip, dst_port, 0, 0);
551 }
552 
553 /** @ingroup udp_raw
554  * Same as udp_sendto(), but with checksum */
555 err_t
556 udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
557                   u16_t dst_port, u8_t have_chksum, u16_t chksum)
558 {
559 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
560   struct netif *netif;
561 
562   LWIP_ERROR("udp_sendto: invalid pcb", pcb != NULL, return ERR_ARG);
563   LWIP_ERROR("udp_sendto: invalid pbuf", p != NULL, return ERR_ARG);
564   LWIP_ERROR("udp_sendto: invalid dst_ip", dst_ip != NULL, return ERR_ARG);
565 
566   if (!IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
567     return ERR_VAL;
568   }
569 
570   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send\n"));
571 
572 #ifdef LOSCFG_NET_CONTAINER
573   struct net_group *group = get_net_group_from_udp_pcb(pcb);
574   LWIP_ERROR("udp_sendto: invalid net group", group != NULL, return ERR_VAL);
575 #endif
576   if (pcb->netif_idx != NETIF_NO_INDEX) {
577 #ifdef LOSCFG_NET_CONTAINER
578     netif = netif_get_by_index(pcb->netif_idx, group);
579 #else
580     netif = netif_get_by_index(pcb->netif_idx);
581 #endif
582   } else {
583 #if LWIP_MULTICAST_TX_OPTIONS
584     netif = NULL;
585     if (ip_addr_ismulticast(dst_ip)) {
586       /* For IPv6, the interface to use for packets with a multicast destination
587        * is specified using an interface index. The same approach may be used for
588        * IPv4 as well, in which case it overrides the IPv4 multicast override
589        * address below. Here we have to look up the netif by going through the
590        * list, but by doing so we skip a route lookup. If the interface index has
591        * gone stale, we fall through and do the regular route lookup after all. */
592       if (pcb->mcast_ifindex != NETIF_NO_INDEX) {
593 #ifdef LOSCFG_NET_CONTAINER
594         netif = netif_get_by_index(pcb->mcast_ifindex, group);
595 #else
596         netif = netif_get_by_index(pcb->mcast_ifindex);
597 #endif
598       }
599 #if LWIP_IPV4
600       else
601 #if LWIP_IPV6
602         if (IP_IS_V4(dst_ip))
603 #endif /* LWIP_IPV6 */
604         {
605           /* IPv4 does not use source-based routing by default, so we use an
606              administratively selected interface for multicast by default.
607              However, this can be overridden by setting an interface address
608              in pcb->mcast_ip4 that is used for routing. If this routing lookup
609              fails, we try regular routing as though no override was set. */
610           if (!ip4_addr_isany_val(pcb->mcast_ip4) &&
611               !ip4_addr_cmp(&pcb->mcast_ip4, IP4_ADDR_BROADCAST)) {
612 #ifdef LOSCFG_NET_CONTAINER
613             netif = ip4_route_src(ip_2_ip4(&pcb->local_ip), &pcb->mcast_ip4, group);
614 #else
615             netif = ip4_route_src(ip_2_ip4(&pcb->local_ip), &pcb->mcast_ip4);
616 #endif
617           }
618         }
619 #endif /* LWIP_IPV4 */
620     }
621 
622     if (netif == NULL)
623 #endif /* LWIP_MULTICAST_TX_OPTIONS */
624     {
625       /* find the outgoing network interface for this packet */
626 #ifdef LOSCFG_NET_CONTAINER
627       netif = ip_route(&pcb->local_ip, dst_ip, group);
628 #else
629       netif = ip_route(&pcb->local_ip, dst_ip);
630 #endif
631     }
632   }
633 
634   /* no outgoing network interface could be found? */
635   if (netif == NULL) {
636     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: No route to "));
637     ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, dst_ip);
638     LWIP_DEBUGF(UDP_DEBUG, ("\n"));
639     UDP_STATS_INC(udp.rterr);
640     return ERR_RTE;
641   }
642 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
643   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum);
644 #else /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
645   return udp_sendto_if(pcb, p, dst_ip, dst_port, netif);
646 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
647 }
648 
649 /**
650  * @ingroup udp_raw
651  * Send data to a specified address using UDP.
652  * The netif used for sending can be specified.
653  *
654  * This function exists mainly for DHCP, to be able to send UDP packets
655  * on a netif that is still down.
656  *
657  * @param pcb UDP PCB used to send the data.
658  * @param p chain of pbuf's to be sent.
659  * @param dst_ip Destination IP address.
660  * @param dst_port Destination UDP port.
661  * @param netif the netif used for sending.
662  *
663  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
664  *
665  * @return lwIP error code (@see udp_send for possible error codes)
666  *
667  * @see udp_disconnect() udp_send()
668  */
669 err_t
670 udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p,
671               const ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif)
672 {
673 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
674   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0);
675 }
676 
677 /** Same as udp_sendto_if(), but with checksum */
678 err_t
679 udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
680                      u16_t dst_port, struct netif *netif, u8_t have_chksum,
681                      u16_t chksum)
682 {
683 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
684   const ip_addr_t *src_ip;
685 
686   LWIP_ERROR("udp_sendto_if: invalid pcb", pcb != NULL, return ERR_ARG);
687   LWIP_ERROR("udp_sendto_if: invalid pbuf", p != NULL, return ERR_ARG);
688   LWIP_ERROR("udp_sendto_if: invalid dst_ip", dst_ip != NULL, return ERR_ARG);
689   LWIP_ERROR("udp_sendto_if: invalid netif", netif != NULL, return ERR_ARG);
690 
691   if (!IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
692     return ERR_VAL;
693   }
694 
695   /* PCB local address is IP_ANY_ADDR or multicast? */
696 #if LWIP_IPV6
697   if (IP_IS_V6(dst_ip)) {
698     if (ip6_addr_isany(ip_2_ip6(&pcb->local_ip)) ||
699         ip6_addr_ismulticast(ip_2_ip6(&pcb->local_ip))) {
700       src_ip = ip6_select_source_address(netif, ip_2_ip6(dst_ip));
701       if (src_ip == NULL) {
702         /* No suitable source address was found. */
703         return ERR_RTE;
704       }
705     } else {
706       /* use UDP PCB local IPv6 address as source address, if still valid. */
707       if (netif_get_ip6_addr_match(netif, ip_2_ip6(&pcb->local_ip)) < 0) {
708         /* Address isn't valid anymore. */
709         return ERR_RTE;
710       }
711       src_ip = &pcb->local_ip;
712     }
713   }
714 #endif /* LWIP_IPV6 */
715 #if LWIP_IPV4 && LWIP_IPV6
716   else
717 #endif /* LWIP_IPV4 && LWIP_IPV6 */
718 #if LWIP_IPV4
719     if (ip4_addr_isany(ip_2_ip4(&pcb->local_ip)) ||
720         ip4_addr_ismulticast(ip_2_ip4(&pcb->local_ip))) {
721       /* if the local_ip is any or multicast
722        * use the outgoing network interface IP address as source address */
723       src_ip = netif_ip_addr4(netif);
724     } else {
725       /* check if UDP PCB local IP address is correct
726        * this could be an old address if netif->ip_addr has changed */
727       if (!ip4_addr_cmp(ip_2_ip4(&(pcb->local_ip)), netif_ip4_addr(netif))) {
728         /* local_ip doesn't match, drop the packet */
729         return ERR_RTE;
730       }
731       /* use UDP PCB local IP address as source address */
732       src_ip = &pcb->local_ip;
733     }
734 #endif /* LWIP_IPV4 */
735 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
736   return udp_sendto_if_src_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum, src_ip);
737 #else /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
738   return udp_sendto_if_src(pcb, p, dst_ip, dst_port, netif, src_ip);
739 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
740 }
741 
742 /** @ingroup udp_raw
743  * Same as @ref udp_sendto_if, but with source address */
744 err_t
745 udp_sendto_if_src(struct udp_pcb *pcb, struct pbuf *p,
746                   const ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif, const ip_addr_t *src_ip)
747 {
748 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
749   return udp_sendto_if_src_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0, src_ip);
750 }
751 
752 /** Same as udp_sendto_if_src(), but with checksum */
753 err_t
754 udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
755                          u16_t dst_port, struct netif *netif, u8_t have_chksum,
756                          u16_t chksum, const ip_addr_t *src_ip)
757 {
758 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
759   struct udp_hdr *udphdr;
760   err_t err;
761   struct pbuf *q; /* q will be sent down the stack */
762   u8_t ip_proto;
763   u8_t ttl;
764 
765   LWIP_ASSERT_CORE_LOCKED();
766 
767   LWIP_ERROR("udp_sendto_if_src: invalid pcb", pcb != NULL, return ERR_ARG);
768   LWIP_ERROR("udp_sendto_if_src: invalid pbuf", p != NULL, return ERR_ARG);
769   LWIP_ERROR("udp_sendto_if_src: invalid dst_ip", dst_ip != NULL, return ERR_ARG);
770   LWIP_ERROR("udp_sendto_if_src: invalid src_ip", src_ip != NULL, return ERR_ARG);
771   LWIP_ERROR("udp_sendto_if_src: invalid netif", netif != NULL, return ERR_ARG);
772 
773   if (!IP_ADDR_PCB_VERSION_MATCH(pcb, src_ip) ||
774       !IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
775     return ERR_VAL;
776   }
777 
778 #if LWIP_IPV4 && IP_SOF_BROADCAST
779   /* broadcast filter? */
780   if (!ip_get_option(pcb, SOF_BROADCAST) &&
781 #if LWIP_IPV6
782       IP_IS_V4(dst_ip) &&
783 #endif /* LWIP_IPV6 */
784       ip_addr_isbroadcast(dst_ip, netif)) {
785     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
786                 ("udp_sendto_if: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb));
787     return ERR_VAL;
788   }
789 #endif /* LWIP_IPV4 && IP_SOF_BROADCAST */
790 
791   /* if the PCB is not yet bound to a port, bind it here */
792   if (pcb->local_port == 0) {
793     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send: not yet bound to a port, binding now\n"));
794     err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
795     if (err != ERR_OK) {
796       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: forced port bind failed\n"));
797       return err;
798     }
799   }
800 
801   /* packet too large to add a UDP header without causing an overflow? */
802   if ((u16_t)(p->tot_len + UDP_HLEN) < p->tot_len) {
803     return ERR_MEM;
804   }
805   /* not enough space to add an UDP header to first pbuf in given p chain? */
806   if (pbuf_add_header(p, UDP_HLEN)) {
807     /* allocate header in a separate new pbuf */
808     q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM);
809     /* new header pbuf could not be allocated? */
810     if (q == NULL) {
811       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: could not allocate header\n"));
812       return ERR_MEM;
813     }
814     if (p->tot_len != 0) {
815       /* chain header q in front of given pbuf p (only if p contains data) */
816       pbuf_chain(q, p);
817     }
818     /* first pbuf q points to header pbuf */
819     LWIP_DEBUGF(UDP_DEBUG,
820                 ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
821   } else {
822     /* adding space for header within p succeeded */
823     /* first pbuf q equals given pbuf */
824     q = p;
825     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p));
826   }
827   LWIP_ASSERT("check that first pbuf can hold struct udp_hdr",
828               (q->len >= sizeof(struct udp_hdr)));
829   /* q now represents the packet to be sent */
830   udphdr = (struct udp_hdr *)q->payload;
831   udphdr->src = lwip_htons(pcb->local_port);
832   udphdr->dest = lwip_htons(dst_port);
833   /* in UDP, 0 checksum means 'no checksum' */
834   udphdr->chksum = 0x0000;
835 
836   /* Multicast Loop? */
837 #if LWIP_MULTICAST_TX_OPTIONS
838   if (((pcb->flags & UDP_FLAGS_MULTICAST_LOOP) != 0) && ip_addr_ismulticast(dst_ip)) {
839     q->flags |= PBUF_FLAG_MCASTLOOP;
840   }
841 #endif /* LWIP_MULTICAST_TX_OPTIONS */
842 
843   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len));
844 
845 #if LWIP_UDPLITE
846   /* UDP Lite protocol? */
847   if (pcb->flags & UDP_FLAGS_UDPLITE) {
848     u16_t chklen, chklen_hdr;
849     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len));
850     /* set UDP message length in UDP header */
851     chklen_hdr = chklen = pcb->chksum_len_tx;
852     if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) {
853       if (chklen != 0) {
854         LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen));
855       }
856       /* For UDP-Lite, checksum length of 0 means checksum
857          over the complete packet. (See RFC 3828 chap. 3.1)
858          At least the UDP-Lite header must be covered by the
859          checksum, therefore, if chksum_len has an illegal
860          value, we generate the checksum over the complete
861          packet to be safe. */
862       chklen_hdr = 0;
863       chklen = q->tot_len;
864     }
865     udphdr->len = lwip_htons(chklen_hdr);
866     /* calculate checksum */
867 #if CHECKSUM_GEN_UDP
868     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
869 #if LWIP_CHECKSUM_ON_COPY
870       if (have_chksum) {
871         chklen = UDP_HLEN;
872       }
873 #endif /* LWIP_CHECKSUM_ON_COPY */
874       udphdr->chksum = ip_chksum_pseudo_partial(q, IP_PROTO_UDPLITE,
875                        q->tot_len, chklen, src_ip, dst_ip);
876 #if LWIP_CHECKSUM_ON_COPY
877       if (have_chksum) {
878         u32_t acc;
879         acc = udphdr->chksum + (u16_t)~(chksum);
880         udphdr->chksum = FOLD_U32T(acc);
881       }
882 #endif /* LWIP_CHECKSUM_ON_COPY */
883 
884       /* chksum zero must become 0xffff, as zero means 'no checksum' */
885       if (udphdr->chksum == 0x0000) {
886         udphdr->chksum = 0xffff;
887       }
888     }
889 #endif /* CHECKSUM_GEN_UDP */
890 
891     ip_proto = IP_PROTO_UDPLITE;
892   } else
893 #endif /* LWIP_UDPLITE */
894   {      /* UDP */
895     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
896     udphdr->len = lwip_htons(q->tot_len);
897     /* calculate checksum */
898 #if CHECKSUM_GEN_UDP
899     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
900       /* Checksum is mandatory over IPv6. */
901       if (IP_IS_V6(dst_ip) || (pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) {
902         u16_t udpchksum;
903 #if LWIP_CHECKSUM_ON_COPY
904         if (have_chksum) {
905           u32_t acc;
906           udpchksum = ip_chksum_pseudo_partial(q, IP_PROTO_UDP,
907                                                q->tot_len, UDP_HLEN, src_ip, dst_ip);
908           acc = udpchksum + (u16_t)~(chksum);
909           udpchksum = FOLD_U32T(acc);
910         } else
911 #endif /* LWIP_CHECKSUM_ON_COPY */
912         {
913           udpchksum = ip_chksum_pseudo(q, IP_PROTO_UDP, q->tot_len,
914                                        src_ip, dst_ip);
915         }
916 
917         /* chksum zero must become 0xffff, as zero means 'no checksum' */
918         if (udpchksum == 0x0000) {
919           udpchksum = 0xffff;
920         }
921         udphdr->chksum = udpchksum;
922       }
923     }
924 #endif /* CHECKSUM_GEN_UDP */
925     ip_proto = IP_PROTO_UDP;
926   }
927 
928   /* Determine TTL to use */
929 #if LWIP_MULTICAST_TX_OPTIONS
930   ttl = (ip_addr_ismulticast(dst_ip) ? udp_get_multicast_ttl(pcb) : pcb->ttl);
931 #else /* LWIP_MULTICAST_TX_OPTIONS */
932   ttl = pcb->ttl;
933 #endif /* LWIP_MULTICAST_TX_OPTIONS */
934 
935   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum));
936   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,0x%02"X16_F",)\n", (u16_t)ip_proto));
937   /* output to IP */
938   NETIF_SET_HINTS(netif, &(pcb->netif_hints));
939   err = ip_output_if_src(q, src_ip, dst_ip, ttl, pcb->tos, ip_proto, netif);
940   NETIF_RESET_HINTS(netif);
941 
942   /* @todo: must this be increased even if error occurred? */
943   MIB2_STATS_INC(mib2.udpoutdatagrams);
944 
945   /* did we chain a separate header pbuf earlier? */
946   if (q != p) {
947     /* free the header pbuf */
948     pbuf_free(q);
949     q = NULL;
950     /* p is still referenced by the caller, and will live on */
951   }
952 
953   UDP_STATS_INC(udp.xmit);
954   return err;
955 }
956 
957 /**
958  * @ingroup udp_raw
959  * Bind an UDP PCB.
960  *
961  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
962  * @param ipaddr local IP address to bind with. Use IP_ANY_TYPE to
963  * bind to all local interfaces.
964  * @param port local UDP port to bind with. Use 0 to automatically bind
965  * to a random port between UDP_LOCAL_PORT_RANGE_START and
966  * UDP_LOCAL_PORT_RANGE_END.
967  *
968  * ipaddr & port are expected to be in the same byte order as in the pcb.
969  *
970  * @return lwIP error code.
971  * - ERR_OK. Successful. No error occurred.
972  * - ERR_USE. The specified ipaddr and port are already bound to by
973  * another UDP PCB.
974  *
975  * @see udp_disconnect()
976  */
977 err_t
978 udp_bind(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
979 {
980   struct udp_pcb *ipcb;
981   u8_t rebind;
982 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
983   ip_addr_t zoned_ipaddr;
984 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
985 
986   LWIP_ASSERT_CORE_LOCKED();
987 
988 #if LWIP_IPV4
989   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
990   if (ipaddr == NULL) {
991     ipaddr = IP4_ADDR_ANY;
992   }
993 #else /* LWIP_IPV4 */
994   LWIP_ERROR("udp_bind: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
995 #endif /* LWIP_IPV4 */
996 
997   LWIP_ERROR("udp_bind: invalid pcb", pcb != NULL, return ERR_ARG);
998 
999   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_bind(ipaddr = "));
1000   ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_TRACE, ipaddr);
1001   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, (", port = %"U16_F")\n", port));
1002 
1003   rebind = 0;
1004   /* Check for double bind and rebind of the same pcb */
1005   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
1006     /* is this UDP PCB already on active list? */
1007     if (pcb == ipcb) {
1008       rebind = 1;
1009       break;
1010     }
1011   }
1012 
1013 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1014   /* If the given IP address should have a zone but doesn't, assign one now.
1015    * This is legacy support: scope-aware callers should always provide properly
1016    * zoned source addresses. Do the zone selection before the address-in-use
1017    * check below; as such we have to make a temporary copy of the address. */
1018   if (IP_IS_V6(ipaddr) && ip6_addr_lacks_zone(ip_2_ip6(ipaddr), IP6_UNKNOWN)) {
1019     ip_addr_copy(zoned_ipaddr, *ipaddr);
1020     ip6_addr_select_zone(ip_2_ip6(&zoned_ipaddr), ip_2_ip6(&zoned_ipaddr));
1021     ipaddr = &zoned_ipaddr;
1022   }
1023 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1024 
1025   /* no port specified? */
1026   if (port == 0) {
1027     port = udp_new_port();
1028     if (port == 0) {
1029       /* no more ports available in local range */
1030       LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n"));
1031       return ERR_USE;
1032     }
1033   } else {
1034     for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
1035 #ifdef LOSCFG_NET_CONTAINER
1036       if (pcb != ipcb && (get_net_group_from_udp_pcb(pcb) == get_net_group_from_udp_pcb(ipcb))) {
1037 #else
1038       if (pcb != ipcb) {
1039 #endif
1040         /* By default, we don't allow to bind to a port that any other udp
1041            PCB is already bound to, unless *all* PCBs with that port have tha
1042            REUSEADDR flag set. */
1043 #if SO_REUSE
1044         if (!ip_get_option(pcb, SOF_REUSEADDR) ||
1045             !ip_get_option(ipcb, SOF_REUSEADDR))
1046 #endif /* SO_REUSE */
1047         {
1048           /* port matches that of PCB in list and REUSEADDR not set -> reject */
1049           if ((ipcb->local_port == port) &&
1050               (((IP_GET_TYPE(&ipcb->local_ip) == IP_GET_TYPE(ipaddr)) &&
1051               /* IP address matches or any IP used? */
1052               (ip_addr_cmp(&ipcb->local_ip, ipaddr) ||
1053               ip_addr_isany(ipaddr) ||
1054               ip_addr_isany(&ipcb->local_ip))) ||
1055               (IP_GET_TYPE(&ipcb->local_ip) == IPADDR_TYPE_ANY) ||
1056               (IP_GET_TYPE(ipaddr) == IPADDR_TYPE_ANY))) {
1057             /* other PCB already binds to this local IP and port */
1058             LWIP_DEBUGF(UDP_DEBUG,
1059                         ("udp_bind: local port %"U16_F" already bound by another pcb\n", port));
1060             return ERR_USE;
1061           }
1062         }
1063       }
1064     }
1065   }
1066 
1067   ip_addr_set_ipaddr(&pcb->local_ip, ipaddr);
1068 
1069   pcb->local_port = port;
1070   mib2_udp_bind(pcb);
1071   /* pcb not active yet? */
1072   if (rebind == 0) {
1073     /* place the PCB on the active list if not already there */
1074     pcb->next = udp_pcbs;
1075     udp_pcbs = pcb;
1076   }
1077   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("udp_bind: bound to "));
1078   ip_addr_debug_print_val(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, pcb->local_ip);
1079   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, (", port %"U16_F")\n", pcb->local_port));
1080   return ERR_OK;
1081 }
1082 
1083 /**
1084  * @ingroup udp_raw
1085  * Bind an UDP PCB to a specific netif.
1086  * After calling this function, all packets received via this PCB
1087  * are guaranteed to have come in via the specified netif, and all
1088  * outgoing packets will go out via the specified netif.
1089  *
1090  * @param pcb UDP PCB to be bound.
1091  * @param netif netif to bind udp pcb to. Can be NULL.
1092  *
1093  * @see udp_disconnect()
1094  */
1095 void
1096 udp_bind_netif(struct udp_pcb *pcb, const struct netif *netif)
1097 {
1098   LWIP_ASSERT_CORE_LOCKED();
1099 
1100   if (netif != NULL) {
1101     pcb->netif_idx = netif_get_index(netif);
1102   } else {
1103     pcb->netif_idx = NETIF_NO_INDEX;
1104   }
1105 }
1106 
1107 /**
1108  * @ingroup udp_raw
1109  * Sets the remote end of the pcb. This function does not generate any
1110  * network traffic, but only sets the remote address of the pcb.
1111  *
1112  * @param pcb UDP PCB to be connected with remote address ipaddr and port.
1113  * @param ipaddr remote IP address to connect with.
1114  * @param port remote UDP port to connect with.
1115  *
1116  * @return lwIP error code
1117  *
1118  * ipaddr & port are expected to be in the same byte order as in the pcb.
1119  *
1120  * The udp pcb is bound to a random local port if not already bound.
1121  *
1122  * @see udp_disconnect()
1123  */
1124 err_t
1125 udp_connect(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
1126 {
1127   struct udp_pcb *ipcb;
1128 
1129   LWIP_ASSERT_CORE_LOCKED();
1130 
1131   LWIP_ERROR("udp_connect: invalid pcb", pcb != NULL, return ERR_ARG);
1132   LWIP_ERROR("udp_connect: invalid ipaddr", ipaddr != NULL, return ERR_ARG);
1133 
1134   if (pcb->local_port == 0) {
1135     err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
1136     if (err != ERR_OK) {
1137       return err;
1138     }
1139   }
1140 
1141   ip_addr_set_ipaddr(&pcb->remote_ip, ipaddr);
1142 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1143   /* If the given IP address should have a zone but doesn't, assign one now,
1144    * using the bound address to make a more informed decision when possible. */
1145   if (IP_IS_V6(&pcb->remote_ip) &&
1146       ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNKNOWN)) {
1147     ip6_addr_select_zone(ip_2_ip6(&pcb->remote_ip), ip_2_ip6(&pcb->local_ip));
1148   }
1149 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1150 
1151   pcb->remote_port = port;
1152   pcb->flags |= UDP_FLAGS_CONNECTED;
1153 
1154   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("udp_connect: connected to "));
1155   ip_addr_debug_print_val(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
1156                           pcb->remote_ip);
1157   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, (", port %"U16_F")\n", pcb->remote_port));
1158 
1159   /* Insert UDP PCB into the list of active UDP PCBs. */
1160   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
1161     if (pcb == ipcb) {
1162       /* already on the list, just return */
1163       return ERR_OK;
1164     }
1165   }
1166   /* PCB not yet on the list, add PCB now */
1167   pcb->next = udp_pcbs;
1168   udp_pcbs = pcb;
1169   return ERR_OK;
1170 }
1171 
1172 /**
1173  * @ingroup udp_raw
1174  * Remove the remote end of the pcb. This function does not generate
1175  * any network traffic, but only removes the remote address of the pcb.
1176  *
1177  * @param pcb the udp pcb to disconnect.
1178  */
1179 void
1180 udp_disconnect(struct udp_pcb *pcb)
1181 {
1182   LWIP_ASSERT_CORE_LOCKED();
1183 
1184   LWIP_ERROR("udp_disconnect: invalid pcb", pcb != NULL, return);
1185 
1186   /* reset remote address association */
1187 #if LWIP_IPV4 && LWIP_IPV6
1188   if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
1189     ip_addr_copy(pcb->remote_ip, *IP_ANY_TYPE);
1190   } else {
1191 #endif
1192     ip_addr_set_any(IP_IS_V6_VAL(pcb->remote_ip), &pcb->remote_ip);
1193 #if LWIP_IPV4 && LWIP_IPV6
1194   }
1195 #endif
1196   pcb->remote_port = 0;
1197   pcb->netif_idx = NETIF_NO_INDEX;
1198   /* mark PCB as unconnected */
1199   udp_clear_flags(pcb, UDP_FLAGS_CONNECTED);
1200 }
1201 
1202 /**
1203  * @ingroup udp_raw
1204  * Set a receive callback for a UDP PCB.
1205  * This callback will be called when receiving a datagram for the pcb.
1206  *
1207  * @param pcb the pcb for which to set the recv callback
1208  * @param recv function pointer of the callback function
1209  * @param recv_arg additional argument to pass to the callback function
1210  */
1211 void
1212 udp_recv(struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg)
1213 {
1214   LWIP_ASSERT_CORE_LOCKED();
1215 
1216   LWIP_ERROR("udp_recv: invalid pcb", pcb != NULL, return);
1217 
1218   /* remember recv() callback and user data */
1219   pcb->recv = recv;
1220   pcb->recv_arg = recv_arg;
1221 }
1222 
1223 /**
1224  * @ingroup udp_raw
1225  * Removes and deallocates the pcb.
1226  *
1227  * @param pcb UDP PCB to be removed. The PCB is removed from the list of
1228  * UDP PCB's and the data structure is freed from memory.
1229  *
1230  * @see udp_new()
1231  */
1232 void
1233 udp_remove(struct udp_pcb *pcb)
1234 {
1235   struct udp_pcb *pcb2;
1236 
1237   LWIP_ASSERT_CORE_LOCKED();
1238 
1239   LWIP_ERROR("udp_remove: invalid pcb", pcb != NULL, return);
1240 
1241   mib2_udp_unbind(pcb);
1242   /* pcb to be removed is first in list? */
1243   if (udp_pcbs == pcb) {
1244     /* make list start at 2nd pcb */
1245     udp_pcbs = udp_pcbs->next;
1246     /* pcb not 1st in list */
1247   } else {
1248     for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
1249       /* find pcb in udp_pcbs list */
1250       if (pcb2->next != NULL && pcb2->next == pcb) {
1251         /* remove pcb from list */
1252         pcb2->next = pcb->next;
1253         break;
1254       }
1255     }
1256   }
1257   memp_free(MEMP_UDP_PCB, pcb);
1258 }
1259 
1260 /**
1261  * @ingroup udp_raw
1262  * Creates a new UDP pcb which can be used for UDP communication. The
1263  * pcb is not active until it has either been bound to a local address
1264  * or connected to a remote address.
1265  * @see MEMP_NUM_UDP_PCB
1266  *
1267  * @return The UDP PCB which was created. NULL if the PCB data structure
1268  * could not be allocated.
1269  *
1270  * @see udp_remove()
1271  */
1272 struct udp_pcb *
1273 udp_new(void)
1274 {
1275   struct udp_pcb *pcb;
1276 
1277   LWIP_ASSERT_CORE_LOCKED();
1278 
1279   pcb = (struct udp_pcb *)memp_malloc(MEMP_UDP_PCB);
1280   /* could allocate UDP PCB? */
1281   if (pcb != NULL) {
1282     /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0
1283      * which means checksum is generated over the whole datagram per default
1284      * (recommended as default by RFC 3828). */
1285     /* initialize PCB to all zeroes */
1286     memset(pcb, 0, sizeof(struct udp_pcb));
1287     pcb->ttl = UDP_TTL;
1288 #if LWIP_MULTICAST_TX_OPTIONS
1289     udp_set_multicast_ttl(pcb, UDP_TTL);
1290 #endif /* LWIP_MULTICAST_TX_OPTIONS */
1291   }
1292   return pcb;
1293 }
1294 
1295 /**
1296  * @ingroup udp_raw
1297  * Create a UDP PCB for specific IP type.
1298  * The pcb is not active until it has either been bound to a local address
1299  * or connected to a remote address.
1300  * @see MEMP_NUM_UDP_PCB
1301  *
1302  * @param type IP address type, see @ref lwip_ip_addr_type definitions.
1303  * If you want to listen to IPv4 and IPv6 (dual-stack) packets,
1304  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
1305  * @return The UDP PCB which was created. NULL if the PCB data structure
1306  * could not be allocated.
1307  *
1308  * @see udp_remove()
1309  */
1310 struct udp_pcb *
1311 udp_new_ip_type(u8_t type)
1312 {
1313   struct udp_pcb *pcb;
1314 
1315   LWIP_ASSERT_CORE_LOCKED();
1316 
1317   pcb = udp_new();
1318 #if LWIP_IPV4 && LWIP_IPV6
1319   if (pcb != NULL) {
1320     IP_SET_TYPE_VAL(pcb->local_ip,  type);
1321     IP_SET_TYPE_VAL(pcb->remote_ip, type);
1322   }
1323 #else
1324   LWIP_UNUSED_ARG(type);
1325 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1326   return pcb;
1327 }
1328 
1329 /** This function is called from netif.c when address is changed
1330  *
1331  * @param old_addr IP address of the netif before change
1332  * @param new_addr IP address of the netif after change
1333  */
1334 void udp_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr)
1335 {
1336   struct udp_pcb *upcb;
1337 
1338   if (!ip_addr_isany(old_addr) && !ip_addr_isany(new_addr)) {
1339     for (upcb = udp_pcbs; upcb != NULL; upcb = upcb->next) {
1340       /* PCB bound to current local interface address? */
1341       if (ip_addr_cmp(&upcb->local_ip, old_addr)) {
1342         /* The PCB is bound to the old ipaddr and
1343          * is set to bound to the new one instead */
1344         ip_addr_copy(upcb->local_ip, *new_addr);
1345       }
1346     }
1347   }
1348 }
1349 
1350 #if UDP_DEBUG
1351 /**
1352  * Print UDP header information for debug purposes.
1353  *
1354  * @param udphdr pointer to the udp header in memory.
1355  */
1356 void
1357 udp_debug_print(struct udp_hdr *udphdr)
1358 {
1359   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
1360   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1361   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
1362                           lwip_ntohs(udphdr->src), lwip_ntohs(udphdr->dest)));
1363   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1364   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
1365                           lwip_ntohs(udphdr->len), lwip_ntohs(udphdr->chksum)));
1366   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1367 }
1368 #endif /* UDP_DEBUG */
1369 
1370 #endif /* LWIP_UDP */
1371