xref: /minix3/minix/lib/liblwip/dist/src/core/udp.c (revision e4dbab1e5368dc2124168836ba46a7d3ff6414b0)
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 raw_api and @ref netconn
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) & ~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 /**
84  * Initialize this module.
85  */
86 void
87 udp_init(void)
88 {
89 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
90   udp_port = UDP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
91 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
92 }
93 
94 /**
95  * Allocate a new local UDP port.
96  *
97  * @return a new (free) local UDP port number
98  */
99 static u16_t
100 udp_new_port(void)
101 {
102   u16_t n = 0;
103   struct udp_pcb *pcb;
104 
105 again:
106   if (udp_port++ == UDP_LOCAL_PORT_RANGE_END) {
107     udp_port = UDP_LOCAL_PORT_RANGE_START;
108   }
109   /* Check all PCBs. */
110   for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
111     if (pcb->local_port == udp_port) {
112       if (++n > (UDP_LOCAL_PORT_RANGE_END - UDP_LOCAL_PORT_RANGE_START)) {
113         return 0;
114       }
115       goto again;
116     }
117   }
118   return udp_port;
119 }
120 
121 /** Common code to see if the current input packet matches the pcb
122  * (current input packet is accessed via ip(4/6)_current_* macros)
123  *
124  * @param pcb pcb to check
125  * @param inp network interface on which the datagram was received (only used for IPv4)
126  * @param broadcast 1 if his is an IPv4 broadcast (global or subnet-only), 0 otherwise (only used for IPv4)
127  * @return 1 on match, 0 otherwise
128  */
129 static u8_t
130 udp_input_local_match(struct udp_pcb *pcb, struct netif *inp, u8_t broadcast)
131 {
132   LWIP_UNUSED_ARG(inp);       /* in IPv6 only case */
133   LWIP_UNUSED_ARG(broadcast); /* in IPv6 only case */
134 
135   /* Dual-stack: PCBs listening to any IP type also listen to any IP address */
136   if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
137 #if LWIP_IPV4 && IP_SOF_BROADCAST_RECV
138     if ((broadcast != 0) && !ip_get_option(pcb, SOF_BROADCAST)) {
139       return 0;
140     }
141 #endif /* LWIP_IPV4 && IP_SOF_BROADCAST_RECV */
142     return 1;
143   }
144 
145   /* Only need to check PCB if incoming IP version matches PCB IP version */
146   if (IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ip_current_dest_addr())) {
147 #if LWIP_IPV4
148     /* Special case: IPv4 broadcast: all or broadcasts in my subnet
149      * Note: broadcast variable can only be 1 if it is an IPv4 broadcast */
150     if (broadcast != 0) {
151 #if IP_SOF_BROADCAST_RECV
152       if (ip_get_option(pcb, SOF_BROADCAST))
153 #endif /* IP_SOF_BROADCAST_RECV */
154       {
155         if (ip4_addr_isany(ip_2_ip4(&pcb->local_ip)) ||
156           ((ip4_current_dest_addr()->addr == IPADDR_BROADCAST)) ||
157            ip4_addr_netcmp(ip_2_ip4(&pcb->local_ip), ip4_current_dest_addr(), netif_ip4_netmask(inp))) {
158           return 1;
159         }
160       }
161     } else
162 #endif /* LWIP_IPV4 */
163     /* Handle IPv4 and IPv6: all or exact match */
164     if (ip_addr_isany(&pcb->local_ip) || ip_addr_cmp(&pcb->local_ip, ip_current_dest_addr())) {
165       return 1;
166     }
167   }
168 
169   return 0;
170 }
171 
172 /**
173  * Process an incoming UDP datagram.
174  *
175  * Given an incoming UDP datagram (as a chain of pbufs) this function
176  * finds a corresponding UDP PCB and hands over the pbuf to the pcbs
177  * recv function. If no pcb is found or the datagram is incorrect, the
178  * pbuf is freed.
179  *
180  * @param p pbuf to be demultiplexed to a UDP PCB (p->payload pointing to the UDP header)
181  * @param inp network interface on which the datagram was received.
182  *
183  */
184 void
185 udp_input(struct pbuf *p, struct netif *inp)
186 {
187   struct udp_hdr *udphdr;
188   struct udp_pcb *pcb, *prev;
189   struct udp_pcb *uncon_pcb;
190   u16_t src, dest;
191   u8_t broadcast;
192   u8_t for_us = 0;
193 
194   LWIP_UNUSED_ARG(inp);
195 
196   PERF_START;
197 
198   UDP_STATS_INC(udp.recv);
199 
200   /* Check minimum length (UDP header) */
201   if (p->len < UDP_HLEN) {
202     /* drop short packets */
203     LWIP_DEBUGF(UDP_DEBUG,
204                 ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len));
205     UDP_STATS_INC(udp.lenerr);
206     UDP_STATS_INC(udp.drop);
207     MIB2_STATS_INC(mib2.udpinerrors);
208     pbuf_free(p);
209     goto end;
210   }
211 
212   udphdr = (struct udp_hdr *)p->payload;
213 
214   /* is broadcast packet ? */
215   broadcast = ip_addr_isbroadcast(ip_current_dest_addr(), ip_current_netif());
216 
217   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
218 
219   /* convert src and dest ports to host byte order */
220   src = lwip_ntohs(udphdr->src);
221   dest = lwip_ntohs(udphdr->dest);
222 
223   udp_debug_print(udphdr);
224 
225   /* print the UDP source and destination */
226   LWIP_DEBUGF(UDP_DEBUG, ("udp ("));
227   ip_addr_debug_print(UDP_DEBUG, ip_current_dest_addr());
228   LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", lwip_ntohs(udphdr->dest)));
229   ip_addr_debug_print(UDP_DEBUG, ip_current_src_addr());
230   LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", lwip_ntohs(udphdr->src)));
231 
232   pcb = NULL;
233   prev = NULL;
234   uncon_pcb = NULL;
235   /* Iterate through the UDP pcb list for a matching pcb.
236    * 'Perfect match' pcbs (connected to the remote port & ip address) are
237    * preferred. If no perfect match is found, the first unconnected pcb that
238    * matches the local port and ip address gets the datagram. */
239   for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
240     /* print the PCB local and remote address */
241     LWIP_DEBUGF(UDP_DEBUG, ("pcb ("));
242     ip_addr_debug_print(UDP_DEBUG, &pcb->local_ip);
243     LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F") <-- (", pcb->local_port));
244     ip_addr_debug_print(UDP_DEBUG, &pcb->remote_ip);
245     LWIP_DEBUGF(UDP_DEBUG, (", %"U16_F")\n", pcb->remote_port));
246 
247     /* compare PCB local addr+port to UDP destination addr+port */
248     if ((pcb->local_port == dest) &&
249         (udp_input_local_match(pcb, inp, broadcast) != 0)) {
250       if (((pcb->flags & UDP_FLAGS_CONNECTED) == 0) &&
251           ((uncon_pcb == NULL)
252 #if SO_REUSE
253           /* prefer specific IPs over cath-all */
254           || !ip_addr_isany(&pcb->local_ip)
255 #endif /* SO_REUSE */
256           )) {
257         /* the first unconnected matching PCB */
258         uncon_pcb = pcb;
259       }
260 
261       /* compare PCB remote addr+port to UDP source addr+port */
262       if ((pcb->remote_port == src) &&
263           (ip_addr_isany_val(pcb->remote_ip) ||
264           ip_addr_cmp(&pcb->remote_ip, ip_current_src_addr()))) {
265         /* the first fully matching PCB */
266         if (prev != NULL) {
267           /* move the pcb to the front of udp_pcbs so that is
268              found faster next time */
269           prev->next = pcb->next;
270           pcb->next = udp_pcbs;
271           udp_pcbs = pcb;
272         } else {
273           UDP_STATS_INC(udp.cachehit);
274         }
275         break;
276       }
277     }
278 
279     prev = pcb;
280   }
281   /* no fully matching pcb found? then look for an unconnected pcb */
282   if (pcb == NULL) {
283     pcb = uncon_pcb;
284   }
285 
286   /* Check checksum if this is a match or if it was directed at us. */
287   if (pcb != NULL) {
288     for_us = 1;
289   } else {
290 #if LWIP_IPV6
291     if (ip_current_is_v6()) {
292       for_us = netif_get_ip6_addr_match(inp, ip6_current_dest_addr()) >= 0;
293     }
294 #endif /* LWIP_IPV6 */
295 #if LWIP_IPV4
296     if (!ip_current_is_v6()) {
297       for_us = ip4_addr_cmp(netif_ip4_addr(inp), ip4_current_dest_addr());
298     }
299 #endif /* LWIP_IPV4 */
300   }
301 
302   if (for_us) {
303     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n"));
304 #if CHECKSUM_CHECK_UDP
305     IF__NETIF_CHECKSUM_ENABLED(inp, CHECKSUM_CHECK_UDP) {
306 #if LWIP_UDPLITE
307       if (ip_current_header_proto() == IP_PROTO_UDPLITE) {
308         /* Do the UDP Lite checksum */
309         u16_t chklen = lwip_ntohs(udphdr->len);
310         if (chklen < sizeof(struct udp_hdr)) {
311           if (chklen == 0) {
312             /* For UDP-Lite, checksum length of 0 means checksum
313                over the complete packet (See RFC 3828 chap. 3.1) */
314             chklen = p->tot_len;
315           } else {
316             /* At least the UDP-Lite header must be covered by the
317                checksum! (Again, see RFC 3828 chap. 3.1) */
318             goto chkerr;
319           }
320         }
321         if (ip_chksum_pseudo_partial(p, IP_PROTO_UDPLITE,
322                      p->tot_len, chklen,
323                      ip_current_src_addr(), ip_current_dest_addr()) != 0) {
324           goto chkerr;
325         }
326       } else
327 #endif /* LWIP_UDPLITE */
328       {
329         if (udphdr->chksum != 0) {
330           if (ip_chksum_pseudo(p, IP_PROTO_UDP, p->tot_len,
331                                ip_current_src_addr(),
332                                ip_current_dest_addr()) != 0) {
333             goto chkerr;
334           }
335         }
336       }
337     }
338 #endif /* CHECKSUM_CHECK_UDP */
339     if (pbuf_header(p, -UDP_HLEN)) {
340       /* Can we cope with this failing? Just assert for now */
341       LWIP_ASSERT("pbuf_header failed\n", 0);
342       UDP_STATS_INC(udp.drop);
343       MIB2_STATS_INC(mib2.udpinerrors);
344       pbuf_free(p);
345       goto end;
346     }
347 
348     if (pcb != NULL) {
349       MIB2_STATS_INC(mib2.udpindatagrams);
350 #if SO_REUSE && SO_REUSE_RXTOALL
351       if (ip_get_option(pcb, SOF_REUSEADDR) &&
352           (broadcast || ip_addr_ismulticast(ip_current_dest_addr()))) {
353         /* pass broadcast- or multicast packets to all multicast pcbs
354            if SOF_REUSEADDR is set on the first match */
355         struct udp_pcb *mpcb;
356         u8_t p_header_changed = 0;
357         s16_t hdrs_len = (s16_t)(ip_current_header_tot_len() + UDP_HLEN);
358         for (mpcb = udp_pcbs; mpcb != NULL; mpcb = mpcb->next) {
359           if (mpcb != pcb) {
360             /* compare PCB local addr+port to UDP destination addr+port */
361             if ((mpcb->local_port == dest) &&
362                 (udp_input_local_match(mpcb, inp, broadcast) != 0)) {
363               /* pass a copy of the packet to all local matches */
364               if (mpcb->recv != NULL) {
365                 struct pbuf *q;
366                 /* for that, move payload to IP header again */
367                 if (p_header_changed == 0) {
368                   pbuf_header_force(p, hdrs_len);
369                   p_header_changed = 1;
370                 }
371 #if defined(__minix)
372                 q = pchain_alloc(PBUF_RAW, p->tot_len);
373 #else /* !defined(__minix) */
374                 q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
375 #endif /* !defined(__minix) */
376                 if (q != NULL) {
377                   err_t err = pbuf_copy(q, p);
378                   if (err == ERR_OK) {
379                     /* move payload to UDP data */
380                     pbuf_header(q, -hdrs_len);
381                     mpcb->recv(mpcb->recv_arg, mpcb, q, ip_current_src_addr(), src);
382                   }
383                 }
384               }
385             }
386           }
387         }
388         if (p_header_changed) {
389           /* and move payload to UDP data again */
390           pbuf_header(p, -hdrs_len);
391         }
392       }
393 #endif /* SO_REUSE && SO_REUSE_RXTOALL */
394       /* callback */
395       if (pcb->recv != NULL) {
396         /* now the recv function is responsible for freeing p */
397         pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr(), src);
398       } else {
399         /* no recv function registered? then we have to free the pbuf! */
400         pbuf_free(p);
401         goto end;
402       }
403     } else {
404       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n"));
405 
406 #if LWIP_ICMP || LWIP_ICMP6
407       /* No match was found, send ICMP destination port unreachable unless
408          destination address was broadcast/multicast. */
409       if (!broadcast && !ip_addr_ismulticast(ip_current_dest_addr())) {
410         /* move payload pointer back to ip header */
411         pbuf_header_force(p, (s16_t)(ip_current_header_tot_len() + UDP_HLEN));
412         icmp_port_unreach(ip_current_is_v6(), p);
413       }
414 #endif /* LWIP_ICMP || LWIP_ICMP6 */
415       UDP_STATS_INC(udp.proterr);
416       UDP_STATS_INC(udp.drop);
417       MIB2_STATS_INC(mib2.udpnoports);
418       pbuf_free(p);
419     }
420   } else {
421     pbuf_free(p);
422   }
423 end:
424   PERF_STOP("udp_input");
425   return;
426 #if CHECKSUM_CHECK_UDP
427 chkerr:
428   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
429               ("udp_input: UDP (or UDP Lite) datagram discarded due to failing checksum\n"));
430   UDP_STATS_INC(udp.chkerr);
431   UDP_STATS_INC(udp.drop);
432   MIB2_STATS_INC(mib2.udpinerrors);
433   pbuf_free(p);
434   PERF_STOP("udp_input");
435 #endif /* CHECKSUM_CHECK_UDP */
436 }
437 
438 /**
439  * @ingroup udp_raw
440  * Send data using UDP.
441  *
442  * @param pcb UDP PCB used to send the data.
443  * @param p chain of pbuf's to be sent.
444  *
445  * The datagram will be sent to the current remote_ip & remote_port
446  * stored in pcb. If the pcb is not bound to a port, it will
447  * automatically be bound to a random port.
448  *
449  * @return lwIP error code.
450  * - ERR_OK. Successful. No error occurred.
451  * - ERR_MEM. Out of memory.
452  * - ERR_RTE. Could not find route to destination address.
453  * - ERR_VAL. No PCB or PCB is dual-stack
454  * - More errors could be returned by lower protocol layers.
455  *
456  * @see udp_disconnect() udp_sendto()
457  */
458 err_t
459 udp_send(struct udp_pcb *pcb, struct pbuf *p)
460 {
461   if ((pcb == NULL) || IP_IS_ANY_TYPE_VAL(pcb->remote_ip)) {
462     return ERR_VAL;
463   }
464 
465   /* send to the packet using remote ip and port stored in the pcb */
466   return udp_sendto(pcb, p, &pcb->remote_ip, pcb->remote_port);
467 }
468 
469 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
470 /** @ingroup udp_raw
471  * Same as udp_send() but with checksum
472  */
473 err_t
474 udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p,
475                 u8_t have_chksum, u16_t chksum)
476 {
477   if ((pcb == NULL) || IP_IS_ANY_TYPE_VAL(pcb->remote_ip)) {
478     return ERR_VAL;
479   }
480 
481   /* send to the packet using remote ip and port stored in the pcb */
482   return udp_sendto_chksum(pcb, p, &pcb->remote_ip, pcb->remote_port,
483     have_chksum, chksum);
484 }
485 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
486 
487 /**
488  * @ingroup udp_raw
489  * Send data to a specified address using UDP.
490  *
491  * @param pcb UDP PCB used to send the data.
492  * @param p chain of pbuf's to be sent.
493  * @param dst_ip Destination IP address.
494  * @param dst_port Destination UDP port.
495  *
496  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
497  *
498  * If the PCB already has a remote address association, it will
499  * be restored after the data is sent.
500  *
501  * @return lwIP error code (@see udp_send for possible error codes)
502  *
503  * @see udp_disconnect() udp_send()
504  */
505 err_t
506 udp_sendto(struct udp_pcb *pcb, struct pbuf *p,
507   const ip_addr_t *dst_ip, u16_t dst_port)
508 {
509 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
510   return udp_sendto_chksum(pcb, p, dst_ip, dst_port, 0, 0);
511 }
512 
513 /** @ingroup udp_raw
514  * Same as udp_sendto(), but with checksum */
515 err_t
516 udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
517                   u16_t dst_port, u8_t have_chksum, u16_t chksum)
518 {
519 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
520   struct netif *netif;
521   const ip_addr_t *src_ip_route;
522 
523   if ((pcb == NULL) || (dst_ip == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
524     return ERR_VAL;
525   }
526 
527   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send\n"));
528 
529   if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
530     /* Don't call ip_route() with IP_ANY_TYPE */
531     src_ip_route = IP46_ADDR_ANY(IP_GET_TYPE(dst_ip));
532   } else {
533     src_ip_route = &pcb->local_ip;
534   }
535   LWIP_UNUSED_ARG(src_ip_route); /* IPv4 only and no source based routing */
536 
537 #if LWIP_MULTICAST_TX_OPTIONS
538   netif = NULL;
539   if (ip_addr_ismulticast(dst_ip)) {
540     /* For IPv6, the interface to use for packets with a multicast destination
541      * is specified using an interface index. The same approach may be used for
542      * IPv4 as well, in which case it overrides the IPv4 multicast override
543      * address below. Here we have to look up the netif by going through the
544      * list, but by doing so we skip a route lookup. If the interface index has
545      * gone stale, we fall through and do the regular route lookup after all. */
546     if (pcb->mcast_ifindex != NETIF_NO_INDEX) {
547       netif = netif_get_by_index(pcb->mcast_ifindex);
548     }
549 #if LWIP_IPV4
550     else
551 #if LWIP_IPV6
552     if (IP_IS_V4(dst_ip))
553 #endif /* LWIP_IPV6 */
554     {
555       /* IPv4 does not use source-based routing by default, so we use an
556          administratively selected interface for multicast by default.
557          However, this can be overridden by setting an interface address
558          in pcb->mcast_ip4 that is used for routing. If this routing lookup
559          fails, we try regular routing as though no override was set. */
560       if (!ip4_addr_isany_val(pcb->mcast_ip4) &&
561           !ip4_addr_cmp(&pcb->mcast_ip4, IP4_ADDR_BROADCAST)) {
562         netif = ip4_route_src(ip_2_ip4(src_ip_route), &pcb->mcast_ip4);
563       }
564     }
565 #endif /* LWIP_IPV4 */
566   }
567 
568   if (netif == NULL)
569 #endif /* LWIP_MULTICAST_TX_OPTIONS */
570   {
571     /* find the outgoing network interface for this packet */
572     netif = ip_route(src_ip_route, dst_ip);
573   }
574 
575   /* no outgoing network interface could be found? */
576   if (netif == NULL) {
577     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: No route to "));
578     ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, dst_ip);
579     LWIP_DEBUGF(UDP_DEBUG, ("\n"));
580     UDP_STATS_INC(udp.rterr);
581     return ERR_RTE;
582   }
583 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
584   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum);
585 #else /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
586   return udp_sendto_if(pcb, p, dst_ip, dst_port, netif);
587 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
588 }
589 
590 /**
591  * @ingroup udp_raw
592  * Send data to a specified address using UDP.
593  * The netif used for sending can be specified.
594  *
595  * This function exists mainly for DHCP, to be able to send UDP packets
596  * on a netif that is still down.
597  *
598  * @param pcb UDP PCB used to send the data.
599  * @param p chain of pbuf's to be sent.
600  * @param dst_ip Destination IP address.
601  * @param dst_port Destination UDP port.
602  * @param netif the netif used for sending.
603  *
604  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
605  *
606  * @return lwIP error code (@see udp_send for possible error codes)
607  *
608  * @see udp_disconnect() udp_send()
609  */
610 err_t
611 udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p,
612   const ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif)
613 {
614 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
615   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0);
616 }
617 
618 /** Same as udp_sendto_if(), but with checksum */
619 err_t
620 udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
621                      u16_t dst_port, struct netif *netif, u8_t have_chksum,
622                      u16_t chksum)
623 {
624 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
625   const ip_addr_t *src_ip;
626 
627   if ((pcb == NULL) || (dst_ip == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
628     return ERR_VAL;
629   }
630 
631   /* PCB local address is IP_ANY_ADDR or multicast? */
632 #if LWIP_IPV6
633   if (IP_IS_V6(dst_ip)) {
634     if (ip6_addr_isany(ip_2_ip6(&pcb->local_ip)) ||
635         ip6_addr_ismulticast(ip_2_ip6(&pcb->local_ip))) {
636       src_ip = ip6_select_source_address(netif, ip_2_ip6(dst_ip));
637       if (src_ip == NULL) {
638         /* No suitable source address was found. */
639         return ERR_RTE;
640       }
641     } else {
642       /* use UDP PCB local IPv6 address as source address, if still valid. */
643       if (netif_get_ip6_addr_match(netif, ip_2_ip6(&pcb->local_ip)) < 0) {
644         /* Address isn't valid anymore. */
645         return ERR_RTE;
646       }
647       src_ip = &pcb->local_ip;
648     }
649   }
650 #endif /* LWIP_IPV6 */
651 #if LWIP_IPV4 && LWIP_IPV6
652   else
653 #endif /* LWIP_IPV4 && LWIP_IPV6 */
654 #if LWIP_IPV4
655   if (ip4_addr_isany(ip_2_ip4(&pcb->local_ip)) ||
656       ip4_addr_ismulticast(ip_2_ip4(&pcb->local_ip))) {
657     /* if the local_ip is any or multicast
658      * use the outgoing network interface IP address as source address */
659     src_ip = netif_ip_addr4(netif);
660   } else {
661     /* check if UDP PCB local IP address is correct
662      * this could be an old address if netif->ip_addr has changed */
663     if (!ip4_addr_cmp(ip_2_ip4(&(pcb->local_ip)), netif_ip4_addr(netif))) {
664       /* local_ip doesn't match, drop the packet */
665       return ERR_RTE;
666     }
667     /* use UDP PCB local IP address as source address */
668     src_ip = &pcb->local_ip;
669   }
670 #endif /* LWIP_IPV4 */
671 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
672   return udp_sendto_if_src_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum, src_ip);
673 #else /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
674   return udp_sendto_if_src(pcb, p, dst_ip, dst_port, netif, src_ip);
675 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
676 }
677 
678 /** @ingroup udp_raw
679  * Same as @ref udp_sendto_if, but with source address */
680 err_t
681 udp_sendto_if_src(struct udp_pcb *pcb, struct pbuf *p,
682   const ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif, const ip_addr_t *src_ip)
683 {
684 #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP
685   return udp_sendto_if_src_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0, src_ip);
686 }
687 
688 /** Same as udp_sendto_if_src(), but with checksum */
689 err_t
690 udp_sendto_if_src_chksum(struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
691                      u16_t dst_port, struct netif *netif, u8_t have_chksum,
692                      u16_t chksum, const ip_addr_t *src_ip)
693 {
694 #endif /* LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP */
695   struct udp_hdr *udphdr;
696   err_t err;
697   struct pbuf *q; /* q will be sent down the stack */
698   u8_t ip_proto;
699   u8_t ttl;
700 
701   if ((pcb == NULL) || (dst_ip == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, src_ip) ||
702       !IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
703     return ERR_VAL;
704   }
705 
706 #if LWIP_IPV4 && IP_SOF_BROADCAST
707   /* broadcast filter? */
708   if (!ip_get_option(pcb, SOF_BROADCAST) &&
709 #if LWIP_IPV6
710       IP_IS_V4(dst_ip) &&
711 #endif /* LWIP_IPV6 */
712       ip_addr_isbroadcast(dst_ip, netif)) {
713     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
714       ("udp_sendto_if: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb));
715     return ERR_VAL;
716   }
717 #endif /* LWIP_IPV4 && IP_SOF_BROADCAST */
718 
719   /* if the PCB is not yet bound to a port, bind it here */
720   if (pcb->local_port == 0) {
721     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send: not yet bound to a port, binding now\n"));
722     err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
723     if (err != ERR_OK) {
724       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: forced port bind failed\n"));
725       return err;
726     }
727   }
728 
729   /* packet too large to add a UDP header without causing an overflow? */
730   if ((u16_t)(p->tot_len + UDP_HLEN) < p->tot_len) {
731     return ERR_MEM;
732   }
733   /* not enough space to add an UDP header to first pbuf in given p chain? */
734   if (pbuf_header(p, UDP_HLEN)) {
735     /* allocate header in a separate new pbuf */
736     q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM);
737     /* new header pbuf could not be allocated? */
738     if (q == NULL) {
739       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: could not allocate header\n"));
740       return ERR_MEM;
741     }
742     if (p->tot_len != 0) {
743       /* chain header q in front of given pbuf p (only if p contains data) */
744       pbuf_chain(q, p);
745     }
746     /* first pbuf q points to header pbuf */
747     LWIP_DEBUGF(UDP_DEBUG,
748                 ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
749   } else {
750     /* adding space for header within p succeeded */
751     /* first pbuf q equals given pbuf */
752     q = p;
753     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p));
754   }
755   LWIP_ASSERT("check that first pbuf can hold struct udp_hdr",
756               (q->len >= sizeof(struct udp_hdr)));
757   /* q now represents the packet to be sent */
758   udphdr = (struct udp_hdr *)q->payload;
759   udphdr->src = lwip_htons(pcb->local_port);
760   udphdr->dest = lwip_htons(dst_port);
761   /* in UDP, 0 checksum means 'no checksum' */
762   udphdr->chksum = 0x0000;
763 
764   /* Multicast Loop? */
765 #if LWIP_MULTICAST_TX_OPTIONS
766   if (((pcb->flags & UDP_FLAGS_MULTICAST_LOOP) != 0) && ip_addr_ismulticast(dst_ip)) {
767     q->flags |= PBUF_FLAG_MCASTLOOP;
768   }
769 #endif /* LWIP_MULTICAST_TX_OPTIONS */
770 
771   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len));
772 
773 #if LWIP_UDPLITE
774   /* UDP Lite protocol? */
775   if (pcb->flags & UDP_FLAGS_UDPLITE) {
776     u16_t chklen, chklen_hdr;
777     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len));
778     /* set UDP message length in UDP header */
779     chklen_hdr = chklen = pcb->chksum_len_tx;
780     if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) {
781       if (chklen != 0) {
782         LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen));
783       }
784       /* For UDP-Lite, checksum length of 0 means checksum
785          over the complete packet. (See RFC 3828 chap. 3.1)
786          At least the UDP-Lite header must be covered by the
787          checksum, therefore, if chksum_len has an illegal
788          value, we generate the checksum over the complete
789          packet to be safe. */
790       chklen_hdr = 0;
791       chklen = q->tot_len;
792     }
793     udphdr->len = lwip_htons(chklen_hdr);
794     /* calculate checksum */
795 #if CHECKSUM_GEN_UDP
796     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
797 #if LWIP_CHECKSUM_ON_COPY
798       if (have_chksum) {
799         chklen = UDP_HLEN;
800       }
801 #endif /* LWIP_CHECKSUM_ON_COPY */
802       udphdr->chksum = ip_chksum_pseudo_partial(q, IP_PROTO_UDPLITE,
803         q->tot_len, chklen, src_ip, dst_ip);
804 #if LWIP_CHECKSUM_ON_COPY
805       if (have_chksum) {
806         u32_t acc;
807         acc = udphdr->chksum + (u16_t)~(chksum);
808         udphdr->chksum = FOLD_U32T(acc);
809       }
810 #endif /* LWIP_CHECKSUM_ON_COPY */
811 
812       /* chksum zero must become 0xffff, as zero means 'no checksum' */
813       if (udphdr->chksum == 0x0000) {
814         udphdr->chksum = 0xffff;
815       }
816     }
817 #endif /* CHECKSUM_GEN_UDP */
818 
819     ip_proto = IP_PROTO_UDPLITE;
820   } else
821 #endif /* LWIP_UDPLITE */
822   {      /* UDP */
823     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
824     udphdr->len = lwip_htons(q->tot_len);
825     /* calculate checksum */
826 #if CHECKSUM_GEN_UDP
827     IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_UDP) {
828       /* Checksum is mandatory over IPv6. */
829       if (IP_IS_V6(dst_ip) || (pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) {
830         u16_t udpchksum;
831 #if LWIP_CHECKSUM_ON_COPY
832         if (have_chksum) {
833           u32_t acc;
834           udpchksum = ip_chksum_pseudo_partial(q, IP_PROTO_UDP,
835             q->tot_len, UDP_HLEN, src_ip, dst_ip);
836           acc = udpchksum + (u16_t)~(chksum);
837           udpchksum = FOLD_U32T(acc);
838         } else
839 #endif /* LWIP_CHECKSUM_ON_COPY */
840         {
841           udpchksum = ip_chksum_pseudo(q, IP_PROTO_UDP, q->tot_len,
842             src_ip, dst_ip);
843         }
844 
845         /* chksum zero must become 0xffff, as zero means 'no checksum' */
846         if (udpchksum == 0x0000) {
847           udpchksum = 0xffff;
848         }
849         udphdr->chksum = udpchksum;
850       }
851     }
852 #endif /* CHECKSUM_GEN_UDP */
853     ip_proto = IP_PROTO_UDP;
854   }
855 
856   /* Determine TTL to use */
857 #if LWIP_MULTICAST_TX_OPTIONS
858   ttl = (ip_addr_ismulticast(dst_ip) ? udp_get_multicast_ttl(pcb) : pcb->ttl);
859 #else /* LWIP_MULTICAST_TX_OPTIONS */
860   ttl = pcb->ttl;
861 #endif /* LWIP_MULTICAST_TX_OPTIONS */
862 
863   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum));
864   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,0x%02"X16_F",)\n", (u16_t)ip_proto));
865   /* output to IP */
866   NETIF_SET_HWADDRHINT(netif, &(pcb->addr_hint));
867   err = ip_output_if_src(q, src_ip, dst_ip, ttl, pcb->tos, ip_proto, netif);
868   NETIF_SET_HWADDRHINT(netif, NULL);
869 
870   /* @todo: must this be increased even if error occurred? */
871   MIB2_STATS_INC(mib2.udpoutdatagrams);
872 
873   /* did we chain a separate header pbuf earlier? */
874   if (q != p) {
875     /* free the header pbuf */
876     pbuf_free(q);
877     q = NULL;
878     /* p is still referenced by the caller, and will live on */
879   }
880 
881   UDP_STATS_INC(udp.xmit);
882   return err;
883 }
884 
885 /**
886  * @ingroup udp_raw
887  * Bind an UDP PCB.
888  *
889  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
890  * @param ipaddr local IP address to bind with. Use IP4_ADDR_ANY to
891  * bind to all local interfaces.
892  * @param port local UDP port to bind with. Use 0 to automatically bind
893  * to a random port between UDP_LOCAL_PORT_RANGE_START and
894  * UDP_LOCAL_PORT_RANGE_END.
895  *
896  * ipaddr & port are expected to be in the same byte order as in the pcb.
897  *
898  * @return lwIP error code.
899  * - ERR_OK. Successful. No error occurred.
900  * - ERR_USE. The specified ipaddr and port are already bound to by
901  * another UDP PCB.
902  *
903  * @see udp_disconnect()
904  */
905 err_t
906 udp_bind(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
907 {
908   struct udp_pcb *ipcb;
909   u8_t rebind;
910 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
911   ip_addr_t zoned_ipaddr;
912 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
913 
914 #if LWIP_IPV4
915   /* Don't propagate NULL pointer (IPv4 ANY) to subsequent functions */
916   if (ipaddr == NULL) {
917     ipaddr = IP4_ADDR_ANY;
918   }
919 #endif /* LWIP_IPV4 */
920 
921   /* still need to check for ipaddr == NULL in IPv6 only case */
922   if ((pcb == NULL) || (ipaddr == NULL)) {
923     return ERR_VAL;
924   }
925 
926   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_bind(ipaddr = "));
927   ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_TRACE, ipaddr);
928   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, (", port = %"U16_F")\n", port));
929 
930   rebind = 0;
931   /* Check for double bind and rebind of the same pcb */
932   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
933     /* is this UDP PCB already on active list? */
934     if (pcb == ipcb) {
935       rebind = 1;
936       break;
937     }
938   }
939 
940 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
941   /* If the given IP address should have a zone but doesn't, assign one now.
942    * This is legacy support: scope-aware callers should always provide properly
943    * zoned source addresses. Do the zone selection before the address-in-use
944    * check below; as such we have to make a temporary copy of the address. */
945   if (IP_IS_V6(ipaddr) && ip6_addr_lacks_zone(ip_2_ip6(ipaddr), IP6_UNKNOWN)) {
946     ip_addr_copy(zoned_ipaddr, *ipaddr);
947     ip6_addr_select_zone(ip_2_ip6(&zoned_ipaddr), ip_2_ip6(&zoned_ipaddr));
948     ipaddr = &zoned_ipaddr;
949   }
950 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
951 
952   /* no port specified? */
953   if (port == 0) {
954     port = udp_new_port();
955     if (port == 0) {
956       /* no more ports available in local range */
957       LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n"));
958       return ERR_USE;
959     }
960   } else {
961     for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
962       if (pcb != ipcb) {
963       /* By default, we don't allow to bind to a port that any other udp
964          PCB is already bound to, unless *all* PCBs with that port have tha
965          REUSEADDR flag set. */
966 #if SO_REUSE
967         if (!ip_get_option(pcb, SOF_REUSEADDR) ||
968             !ip_get_option(ipcb, SOF_REUSEADDR))
969 #endif /* SO_REUSE */
970         {
971           /* port matches that of PCB in list and REUSEADDR not set -> reject */
972           if ((ipcb->local_port == port) &&
973               /* IP address matches? */
974               ip_addr_cmp(&ipcb->local_ip, ipaddr)) {
975             /* other PCB already binds to this local IP and port */
976             LWIP_DEBUGF(UDP_DEBUG,
977                         ("udp_bind: local port %"U16_F" already bound by another pcb\n", port));
978             return ERR_USE;
979           }
980         }
981       }
982     }
983   }
984 
985   ip_addr_set_ipaddr(&pcb->local_ip, ipaddr);
986 
987   pcb->local_port = port;
988   mib2_udp_bind(pcb);
989   /* pcb not active yet? */
990   if (rebind == 0) {
991     /* place the PCB on the active list if not already there */
992     pcb->next = udp_pcbs;
993     udp_pcbs = pcb;
994   }
995   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("udp_bind: bound to "));
996   ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, &pcb->local_ip);
997   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, (", port %"U16_F")\n", pcb->local_port));
998   return ERR_OK;
999 }
1000 
1001 /**
1002  * @ingroup udp_raw
1003  * Connect an UDP PCB.
1004  *
1005  * This will associate the UDP PCB with the remote address.
1006  *
1007  * @param pcb UDP PCB to be connected with remote address ipaddr and port.
1008  * @param ipaddr remote IP address to connect with.
1009  * @param port remote UDP port to connect with.
1010  *
1011  * @return lwIP error code
1012  *
1013  * ipaddr & port are expected to be in the same byte order as in the pcb.
1014  *
1015  * The udp pcb is bound to a random local port if not already bound.
1016  *
1017  * @see udp_disconnect()
1018  */
1019 err_t
1020 udp_connect(struct udp_pcb *pcb, const ip_addr_t *ipaddr, u16_t port)
1021 {
1022   struct udp_pcb *ipcb;
1023 
1024   if ((pcb == NULL) || (ipaddr == NULL)) {
1025     return ERR_VAL;
1026   }
1027 
1028   if (pcb->local_port == 0) {
1029     err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
1030     if (err != ERR_OK) {
1031       return err;
1032     }
1033   }
1034 
1035   ip_addr_set_ipaddr(&pcb->remote_ip, ipaddr);
1036 #if LWIP_IPV6 && LWIP_IPV6_SCOPES
1037   /* If the given IP address should have a zone but doesn't, assign one now,
1038    * using the bound address to make a more informed decision when possible. */
1039   if (IP_IS_V6(&pcb->remote_ip) &&
1040       ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNKNOWN)) {
1041     ip6_addr_select_zone(ip_2_ip6(&pcb->remote_ip), ip_2_ip6(&pcb->local_ip));
1042   }
1043 #endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
1044 
1045   pcb->remote_port = port;
1046   pcb->flags |= UDP_FLAGS_CONNECTED;
1047 
1048   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("udp_connect: connected to "));
1049   ip_addr_debug_print(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
1050                       &pcb->remote_ip);
1051   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, (", port %"U16_F")\n", pcb->remote_port));
1052 
1053   /* Insert UDP PCB into the list of active UDP PCBs. */
1054   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
1055     if (pcb == ipcb) {
1056       /* already on the list, just return */
1057       return ERR_OK;
1058     }
1059   }
1060   /* PCB not yet on the list, add PCB now */
1061   pcb->next = udp_pcbs;
1062   udp_pcbs = pcb;
1063   return ERR_OK;
1064 }
1065 
1066 /**
1067  * @ingroup udp_raw
1068  * Disconnect a UDP PCB
1069  *
1070  * @param pcb the udp pcb to disconnect.
1071  */
1072 void
1073 udp_disconnect(struct udp_pcb *pcb)
1074 {
1075   /* reset remote address association */
1076 #if LWIP_IPV4 && LWIP_IPV6
1077   if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
1078     ip_addr_copy(pcb->remote_ip, *IP_ANY_TYPE);
1079   } else {
1080 #endif
1081     ip_addr_set_any(IP_IS_V6_VAL(pcb->remote_ip), &pcb->remote_ip);
1082 #if LWIP_IPV4 && LWIP_IPV6
1083   }
1084 #endif
1085   pcb->remote_port = 0;
1086   /* mark PCB as unconnected */
1087   pcb->flags &= ~UDP_FLAGS_CONNECTED;
1088 }
1089 
1090 /**
1091  * @ingroup udp_raw
1092  * Set a receive callback for a UDP PCB
1093  *
1094  * This callback will be called when receiving a datagram for the pcb.
1095  *
1096  * @param pcb the pcb for which to set the recv callback
1097  * @param recv function pointer of the callback function
1098  * @param recv_arg additional argument to pass to the callback function
1099  */
1100 void
1101 udp_recv(struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg)
1102 {
1103   /* remember recv() callback and user data */
1104   pcb->recv = recv;
1105   pcb->recv_arg = recv_arg;
1106 }
1107 
1108 /**
1109  * @ingroup udp_raw
1110  * Remove an UDP PCB.
1111  *
1112  * @param pcb UDP PCB to be removed. The PCB is removed from the list of
1113  * UDP PCB's and the data structure is freed from memory.
1114  *
1115  * @see udp_new()
1116  */
1117 void
1118 udp_remove(struct udp_pcb *pcb)
1119 {
1120   struct udp_pcb *pcb2;
1121 
1122   mib2_udp_unbind(pcb);
1123   /* pcb to be removed is first in list? */
1124   if (udp_pcbs == pcb) {
1125     /* make list start at 2nd pcb */
1126     udp_pcbs = udp_pcbs->next;
1127     /* pcb not 1st in list */
1128   } else {
1129     for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
1130       /* find pcb in udp_pcbs list */
1131       if (pcb2->next != NULL && pcb2->next == pcb) {
1132         /* remove pcb from list */
1133         pcb2->next = pcb->next;
1134         break;
1135       }
1136     }
1137   }
1138   memp_free(MEMP_UDP_PCB, pcb);
1139 }
1140 
1141 /**
1142  * @ingroup udp_raw
1143  * Create a UDP PCB.
1144  *
1145  * @return The UDP PCB which was created. NULL if the PCB data structure
1146  * could not be allocated.
1147  *
1148  * @see udp_remove()
1149  */
1150 struct udp_pcb *
1151 udp_new(void)
1152 {
1153   struct udp_pcb *pcb;
1154   pcb = (struct udp_pcb *)memp_malloc(MEMP_UDP_PCB);
1155   /* could allocate UDP PCB? */
1156   if (pcb != NULL) {
1157     /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0
1158      * which means checksum is generated over the whole datagram per default
1159      * (recommended as default by RFC 3828). */
1160     /* initialize PCB to all zeroes */
1161     memset(pcb, 0, sizeof(struct udp_pcb));
1162     pcb->ttl = UDP_TTL;
1163 #if LWIP_MULTICAST_TX_OPTIONS
1164     udp_set_multicast_ttl(pcb, UDP_TTL);
1165 #endif /* LWIP_MULTICAST_TX_OPTIONS */
1166   }
1167   return pcb;
1168 }
1169 
1170 /**
1171  * @ingroup udp_raw
1172  * Create a UDP PCB for specific IP type.
1173  *
1174  * @param type IP address type, see @ref lwip_ip_addr_type definitions.
1175  * If you want to listen to IPv4 and IPv6 (dual-stack) packets,
1176  * supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
1177  * @return The UDP PCB which was created. NULL if the PCB data structure
1178  * could not be allocated.
1179  *
1180  * @see udp_remove()
1181  */
1182 struct udp_pcb *
1183 udp_new_ip_type(u8_t type)
1184 {
1185   struct udp_pcb *pcb;
1186   pcb = udp_new();
1187 #if LWIP_IPV4 && LWIP_IPV6
1188   if (pcb != NULL) {
1189     IP_SET_TYPE_VAL(pcb->local_ip,  type);
1190     IP_SET_TYPE_VAL(pcb->remote_ip, type);
1191   }
1192 #else
1193   LWIP_UNUSED_ARG(type);
1194 #endif /* LWIP_IPV4 && LWIP_IPV6 */
1195   return pcb;
1196 }
1197 
1198 /** This function is called from netif.c when address is changed
1199  *
1200  * @param old_addr IP address of the netif before change
1201  * @param new_addr IP address of the netif after change
1202  */
1203 void udp_netif_ip_addr_changed(const ip_addr_t* old_addr, const ip_addr_t* new_addr)
1204 {
1205   struct udp_pcb* upcb;
1206 
1207   if (!ip_addr_isany(old_addr) && !ip_addr_isany(new_addr)) {
1208     for (upcb = udp_pcbs; upcb != NULL; upcb = upcb->next) {
1209       /* PCB bound to current local interface address? */
1210       if (ip_addr_cmp(&upcb->local_ip, old_addr)) {
1211         /* The PCB is bound to the old ipaddr and
1212          * is set to bound to the new one instead */
1213         ip_addr_copy(upcb->local_ip, *new_addr);
1214       }
1215     }
1216   }
1217 }
1218 
1219 #if UDP_DEBUG
1220 /**
1221  * Print UDP header information for debug purposes.
1222  *
1223  * @param udphdr pointer to the udp header in memory.
1224  */
1225 void
1226 udp_debug_print(struct udp_hdr *udphdr)
1227 {
1228   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
1229   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1230   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
1231                           lwip_ntohs(udphdr->src), lwip_ntohs(udphdr->dest)));
1232   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1233   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
1234                           lwip_ntohs(udphdr->len), lwip_ntohs(udphdr->chksum)));
1235   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1236 }
1237 #endif /* UDP_DEBUG */
1238 
1239 #endif /* LWIP_UDP */
1240