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