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