1 /**
2  * @file
3  * User Datagram Protocol module
4  *
5  */
6 
7 /*
8  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without modification,
12  * are permitted provided that the following conditions are met:
13  *
14  * 1. Redistributions of source code must retain the above copyright notice,
15  *    this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright notice,
17  *    this list of conditions and the following disclaimer in the documentation
18  *    and/or other materials provided with the distribution.
19  * 3. The name of the author may not be used to endorse or promote products
20  *    derived from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
23  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
24  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
25  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
27  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
31  * OF SUCH DAMAGE.
32  *
33  * This file is part of the lwIP TCP/IP stack.
34  *
35  * Author: Adam Dunkels <adam@sics.se>
36  *
37  */
38 
39 
40 /* udp.c
41  *
42  * The code for the User Datagram Protocol UDP & UDPLite (RFC 3828).
43  *
44  */
45 
46 /* @todo Check the use of '(struct udp_pcb).chksum_len_rx'!
47  */
48 
49 #include "lwip/opt.h"
50 
51 #if LWIP_UDP /* don't build if not configured for use in lwipopts.h */
52 
53 #include "lwip/udp.h"
54 #include "lwip/def.h"
55 #include "lwip/memp.h"
56 #include "lwip/inet_chksum.h"
57 #include "lwip/ip_addr.h"
58 #include "lwip/netif.h"
59 #include "lwip/icmp.h"
60 #include "lwip/stats.h"
61 #include "lwip/snmp.h"
62 #include "arch/perf.h"
63 #include "lwip/dhcp.h"
64 
65 #include <string.h>
66 
67 #ifndef UDP_LOCAL_PORT_RANGE_START
68 /* From http://www.iana.org/assignments/port-numbers:
69    "The Dynamic and/or Private Ports are those from 49152 through 65535" */
70 #define UDP_LOCAL_PORT_RANGE_START  0xc000
71 #define UDP_LOCAL_PORT_RANGE_END    0xffff
72 #define UDP_ENSURE_LOCAL_PORT_RANGE(port) (((port) & ~UDP_LOCAL_PORT_RANGE_START) + UDP_LOCAL_PORT_RANGE_START)
73 #endif
74 
75 /* last local UDP port */
76 static u16_t udp_port = UDP_LOCAL_PORT_RANGE_START;
77 
78 /* The list of UDP PCBs */
79 /* exported in udp.h (was static) */
80 struct udp_pcb *udp_pcbs;
81 
82 /**
83  * Initialize this module.
84  */
85 void
udp_init(void)86 udp_init(void)
87 {
88 #if LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND)
89   udp_port = UDP_ENSURE_LOCAL_PORT_RANGE(LWIP_RAND());
90 #endif /* LWIP_RANDOMIZE_INITIAL_LOCAL_PORTS && defined(LWIP_RAND) */
91 }
92 
93 /**
94  * Allocate a new local UDP port.
95  *
96  * @return a new (free) local UDP port number
97  */
98 static u16_t
udp_new_port(void)99 udp_new_port(void)
100 {
101   u16_t n = 0;
102   struct udp_pcb *pcb;
103 
104 again:
105   if (udp_port++ == UDP_LOCAL_PORT_RANGE_END) {
106     udp_port = UDP_LOCAL_PORT_RANGE_START;
107   }
108   /* Check all PCBs. */
109   for(pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
110     if (pcb->local_port == udp_port) {
111       if (++n > (UDP_LOCAL_PORT_RANGE_END - UDP_LOCAL_PORT_RANGE_START)) {
112         return 0;
113       }
114       goto again;
115     }
116   }
117   return udp_port;
118 #if 0
119   struct udp_pcb *ipcb = udp_pcbs;
120   while ((ipcb != NULL) && (udp_port != UDP_LOCAL_PORT_RANGE_END)) {
121     if (ipcb->local_port == udp_port) {
122       /* port is already used by another udp_pcb */
123       udp_port++;
124       /* restart scanning all udp pcbs */
125       ipcb = udp_pcbs;
126     } else {
127       /* go on with next udp pcb */
128       ipcb = ipcb->next;
129     }
130   }
131   if (ipcb != NULL) {
132     return 0;
133   }
134   return udp_port;
135 #endif
136 }
137 
138 /**
139  * Process an incoming UDP datagram.
140  *
141  * Given an incoming UDP datagram (as a chain of pbufs) this function
142  * finds a corresponding UDP PCB and hands over the pbuf to the pcbs
143  * recv function. If no pcb is found or the datagram is incorrect, the
144  * pbuf is freed.
145  *
146  * @param p pbuf to be demultiplexed to a UDP PCB.
147  * @param inp network interface on which the datagram was received.
148  *
149  */
150 void
udp_input(struct pbuf * p,struct netif * inp)151 udp_input(struct pbuf *p, struct netif *inp)
152 {
153   struct udp_hdr *udphdr;
154   struct udp_pcb *pcb, *prev;
155   struct udp_pcb *uncon_pcb;
156   struct ip_hdr *iphdr;
157   u16_t src, dest;
158   u8_t local_match;
159   u8_t broadcast;
160 
161   PERF_START;
162 
163   UDP_STATS_INC(udp.recv);
164 
165   iphdr = (struct ip_hdr *)p->payload;
166 
167   /* Check minimum length (IP header + UDP header)
168    * and move payload pointer to UDP header */
169   if (p->tot_len < (IPH_HL(iphdr) * 4 + UDP_HLEN) || pbuf_header(p, -(s16_t)(IPH_HL(iphdr) * 4))) {
170     /* drop short packets */
171     LWIP_DEBUGF(UDP_DEBUG,
172                 ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len));
173     UDP_STATS_INC(udp.lenerr);
174     UDP_STATS_INC(udp.drop);
175     snmp_inc_udpinerrors();
176     pbuf_free(p);
177     goto end;
178   }
179 
180   udphdr = (struct udp_hdr *)p->payload;
181 
182   /* is broadcast packet ? */
183   broadcast = ip_addr_isbroadcast(&current_iphdr_dest, inp);
184 
185   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
186 
187   /* convert src and dest ports to host byte order */
188   src = ntohs(udphdr->src);
189   dest = ntohs(udphdr->dest);
190 
191   udp_debug_print(udphdr);
192 
193   /* print the UDP source and destination */
194   LWIP_DEBUGF(UDP_DEBUG,
195               ("udp (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") <-- "
196                "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
197                ip4_addr1_16(&iphdr->dest), ip4_addr2_16(&iphdr->dest),
198                ip4_addr3_16(&iphdr->dest), ip4_addr4_16(&iphdr->dest), ntohs(udphdr->dest),
199                ip4_addr1_16(&iphdr->src), ip4_addr2_16(&iphdr->src),
200                ip4_addr3_16(&iphdr->src), ip4_addr4_16(&iphdr->src), ntohs(udphdr->src)));
201 
202 #if LWIP_DHCP
203   pcb = NULL;
204   /* when LWIP_DHCP is active, packets to DHCP_CLIENT_PORT may only be processed by
205      the dhcp module, no other UDP pcb may use the local UDP port DHCP_CLIENT_PORT */
206   if (dest == DHCP_CLIENT_PORT) {
207     /* all packets for DHCP_CLIENT_PORT not coming from DHCP_SERVER_PORT are dropped! */
208     if (src == DHCP_SERVER_PORT) {
209       if ((inp->dhcp != NULL) && (inp->dhcp->pcb != NULL)) {
210         /* accept the packe if
211            (- broadcast or directed to us) -> DHCP is link-layer-addressed, local ip is always ANY!
212            - inp->dhcp->pcb->remote == ANY or iphdr->src */
213         if ((ip_addr_isany(&inp->dhcp->pcb->remote_ip) ||
214            ip_addr_cmp(&(inp->dhcp->pcb->remote_ip), &current_iphdr_src))) {
215           pcb = inp->dhcp->pcb;
216         }
217       }
218     }
219   } else
220 #endif /* LWIP_DHCP */
221   {
222     prev = NULL;
223     local_match = 0;
224     uncon_pcb = NULL;
225     /* Iterate through the UDP pcb list for a matching pcb.
226      * 'Perfect match' pcbs (connected to the remote port & ip address) are
227      * preferred. If no perfect match is found, the first unconnected pcb that
228      * matches the local port and ip address gets the datagram. */
229     for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
230       local_match = 0;
231       /* print the PCB local and remote address */
232       LWIP_DEBUGF(UDP_DEBUG,
233                   ("pcb (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") --- "
234                    "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
235                    ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip),
236                    ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip), pcb->local_port,
237                    ip4_addr1_16(&pcb->remote_ip), ip4_addr2_16(&pcb->remote_ip),
238                    ip4_addr3_16(&pcb->remote_ip), ip4_addr4_16(&pcb->remote_ip), pcb->remote_port));
239 
240       /* compare PCB local addr+port to UDP destination addr+port */
241       if (pcb->local_port == dest) {
242         if (
243            (!broadcast && ip_addr_isany(&pcb->local_ip)) ||
244            ip_addr_cmp(&(pcb->local_ip), &current_iphdr_dest) ||
245 #if LWIP_IGMP
246            ip_addr_ismulticast(&current_iphdr_dest) ||
247 #endif /* LWIP_IGMP */
248 #if IP_SOF_BROADCAST_RECV
249             (broadcast && ip_get_option(pcb, SOF_BROADCAST) &&
250              (ip_addr_isany(&pcb->local_ip) ||
251               ip_addr_netcmp(&pcb->local_ip, ip_current_dest_addr(), &inp->netmask)))) {
252 #else /* IP_SOF_BROADCAST_RECV */
253             (broadcast &&
254              (ip_addr_isany(&pcb->local_ip) ||
255               ip_addr_netcmp(&pcb->local_ip, ip_current_dest_addr(), &inp->netmask)))) {
256 #endif /* IP_SOF_BROADCAST_RECV */
257           local_match = 1;
258           if ((uncon_pcb == NULL) &&
259               ((pcb->flags & UDP_FLAGS_CONNECTED) == 0)) {
260             /* the first unconnected matching PCB */
261             uncon_pcb = pcb;
262           }
263         }
264       }
265       /* compare PCB remote addr+port to UDP source addr+port */
266       if ((local_match != 0) &&
267           (pcb->remote_port == src) &&
268           (ip_addr_isany(&pcb->remote_ip) ||
269            ip_addr_cmp(&(pcb->remote_ip), &current_iphdr_src))) {
270         /* the first fully matching PCB */
271         if (prev != NULL) {
272           /* move the pcb to the front of udp_pcbs so that is
273              found faster next time */
274           prev->next = pcb->next;
275           pcb->next = udp_pcbs;
276           udp_pcbs = pcb;
277         } else {
278           UDP_STATS_INC(udp.cachehit);
279         }
280         break;
281       }
282       prev = pcb;
283     }
284     /* no fully matching pcb found? then look for an unconnected pcb */
285     if (pcb == NULL) {
286       pcb = uncon_pcb;
287     }
288   }
289 
290   /* Check checksum if this is a match or if it was directed at us. */
291   if (pcb != NULL || ip_addr_cmp(&inp->ip_addr, &current_iphdr_dest)) {
292     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n"));
293 #if LWIP_UDPLITE
294     if (IPH_PROTO(iphdr) == IP_PROTO_UDPLITE) {
295       /* Do the UDP Lite checksum */
296 #if CHECKSUM_CHECK_UDP
297       u16_t chklen = ntohs(udphdr->len);
298       if (chklen < sizeof(struct udp_hdr)) {
299         if (chklen == 0) {
300           /* For UDP-Lite, checksum length of 0 means checksum
301              over the complete packet (See RFC 3828 chap. 3.1) */
302           chklen = p->tot_len;
303         } else {
304           /* At least the UDP-Lite header must be covered by the
305              checksum! (Again, see RFC 3828 chap. 3.1) */
306           UDP_STATS_INC(udp.chkerr);
307           UDP_STATS_INC(udp.drop);
308           snmp_inc_udpinerrors();
309           pbuf_free(p);
310           goto end;
311         }
312       }
313       if (inet_chksum_pseudo_partial(p, &current_iphdr_src, &current_iphdr_dest,
314                              IP_PROTO_UDPLITE, p->tot_len, chklen) != 0) {
315        LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
316                    ("udp_input: UDP Lite datagram discarded due to failing checksum\n"));
317         UDP_STATS_INC(udp.chkerr);
318         UDP_STATS_INC(udp.drop);
319         snmp_inc_udpinerrors();
320         pbuf_free(p);
321         goto end;
322       }
323 #endif /* CHECKSUM_CHECK_UDP */
324     } else
325 #endif /* LWIP_UDPLITE */
326     {
327 #if CHECKSUM_CHECK_UDP
328       if (udphdr->chksum != 0) {
329         if (inet_chksum_pseudo(p, ip_current_src_addr(), ip_current_dest_addr(),
330                                IP_PROTO_UDP, p->tot_len) != 0) {
331           LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
332                       ("udp_input: UDP datagram discarded due to failing checksum\n"));
333           UDP_STATS_INC(udp.chkerr);
334           UDP_STATS_INC(udp.drop);
335           snmp_inc_udpinerrors();
336           pbuf_free(p);
337           goto end;
338         }
339       }
340 #endif /* CHECKSUM_CHECK_UDP */
341     }
342     if(pbuf_header(p, -UDP_HLEN)) {
343       /* Can we cope with this failing? Just assert for now */
344       LWIP_ASSERT("pbuf_header failed\n", 0);
345       UDP_STATS_INC(udp.drop);
346       snmp_inc_udpinerrors();
347       pbuf_free(p);
348       goto end;
349     }
350     if (pcb != NULL) {
351       snmp_inc_udpindatagrams();
352 #if SO_REUSE && SO_REUSE_RXTOALL
353       if ((broadcast || ip_addr_ismulticast(&current_iphdr_dest)) &&
354           ip_get_option(pcb, SOF_REUSEADDR)) {
355         /* pass broadcast- or multicast packets to all multicast pcbs
356            if SOF_REUSEADDR is set on the first match */
357         struct udp_pcb *mpcb;
358         u8_t p_header_changed = 0;
359         for (mpcb = udp_pcbs; mpcb != NULL; mpcb = mpcb->next) {
360           if (mpcb != pcb) {
361             /* compare PCB local addr+port to UDP destination addr+port */
362             if ((mpcb->local_port == dest) &&
363                 ((!broadcast && ip_addr_isany(&mpcb->local_ip)) ||
364                  ip_addr_cmp(&(mpcb->local_ip), &current_iphdr_dest) ||
365 #if LWIP_IGMP
366                  ip_addr_ismulticast(&current_iphdr_dest) ||
367 #endif /* LWIP_IGMP */
368 #if IP_SOF_BROADCAST_RECV
369                  (broadcast && ip_get_option(mpcb, SOF_BROADCAST)))) {
370 #else  /* IP_SOF_BROADCAST_RECV */
371                  (broadcast))) {
372 #endif /* IP_SOF_BROADCAST_RECV */
373               /* pass a copy of the packet to all local matches */
374               if (mpcb->recv != NULL) {
375                 struct pbuf *q;
376                 /* for that, move payload to IP header again */
377                 if (p_header_changed == 0) {
378                   pbuf_header(p, (s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN));
379                   p_header_changed = 1;
380                 }
381                 q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
382                 if (q != NULL) {
383                   err_t err = pbuf_copy(q, p);
384                   if (err == ERR_OK) {
385                     /* move payload to UDP data */
386                     pbuf_header(q, -(s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN));
387                     mpcb->recv(mpcb->recv_arg, mpcb, q, ip_current_src_addr(), src);
388                   }
389                 }
390               }
391             }
392           }
393         }
394         if (p_header_changed) {
395           /* and move payload to UDP data again */
396           pbuf_header(p, -(s16_t)((IPH_HL(iphdr) * 4) + UDP_HLEN));
397         }
398       }
399 #endif /* SO_REUSE && SO_REUSE_RXTOALL */
400       /* callback */
401       if (pcb->recv != NULL) {
402         /* now the recv function is responsible for freeing p */
403         pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr(), src);
404       } else {
405         /* no recv function registered? then we have to free the pbuf! */
406         pbuf_free(p);
407         goto end;
408       }
409     } else {
410       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n"));
411 
412 #if LWIP_ICMP
413       /* No match was found, send ICMP destination port unreachable unless
414          destination address was broadcast/multicast. */
415       if (!broadcast &&
416           !ip_addr_ismulticast(&current_iphdr_dest)) {
417         /* move payload pointer back to ip header */
418         pbuf_header(p, (IPH_HL(iphdr) * 4) + UDP_HLEN);
419         LWIP_ASSERT("p->payload == iphdr", (p->payload == iphdr));
420         icmp_dest_unreach(p, ICMP_DUR_PORT);
421       }
422 #endif /* LWIP_ICMP */
423       UDP_STATS_INC(udp.proterr);
424       UDP_STATS_INC(udp.drop);
425       snmp_inc_udpnoports();
426       pbuf_free(p);
427     }
428   } else {
429     pbuf_free(p);
430   }
431 end:
432   PERF_STOP("udp_input");
433 }
434 
435 /**
436  * Send data using UDP.
437  *
438  * @param pcb UDP PCB used to send the data.
439  * @param p chain of pbuf's to be sent.
440  *
441  * The datagram will be sent to the current remote_ip & remote_port
442  * stored in pcb. If the pcb is not bound to a port, it will
443  * automatically be bound to a random port.
444  *
445  * @return lwIP error code.
446  * - ERR_OK. Successful. No error occured.
447  * - ERR_MEM. Out of memory.
448  * - ERR_RTE. Could not find route to destination address.
449  * - More errors could be returned by lower protocol layers.
450  *
451  * @see udp_disconnect() udp_sendto()
452  */
453 err_t
454 udp_send(struct udp_pcb *pcb, struct pbuf *p)
455 {
456   /* send to the packet using remote ip and port stored in the pcb */
457   return udp_sendto(pcb, p, &pcb->remote_ip, pcb->remote_port);
458 }
459 
460 #if LWIP_CHECKSUM_ON_COPY
461 /** Same as udp_send() but with checksum
462  */
463 err_t
464 udp_send_chksum(struct udp_pcb *pcb, struct pbuf *p,
465                 u8_t have_chksum, u16_t chksum)
466 {
467   /* send to the packet using remote ip and port stored in the pcb */
468   return udp_sendto_chksum(pcb, p, &pcb->remote_ip, pcb->remote_port,
469     have_chksum, chksum);
470 }
471 #endif /* LWIP_CHECKSUM_ON_COPY */
472 
473 /**
474  * Send data to a specified address using UDP.
475  *
476  * @param pcb UDP PCB used to send the data.
477  * @param p chain of pbuf's to be sent.
478  * @param dst_ip Destination IP address.
479  * @param dst_port Destination UDP port.
480  *
481  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
482  *
483  * If the PCB already has a remote address association, it will
484  * be restored after the data is sent.
485  *
486  * @return lwIP error code (@see udp_send for possible error codes)
487  *
488  * @see udp_disconnect() udp_send()
489  */
490 err_t
491 udp_sendto(struct udp_pcb *pcb, struct pbuf *p,
492   ip_addr_t *dst_ip, u16_t dst_port)
493 {
494 #if LWIP_CHECKSUM_ON_COPY
495   return udp_sendto_chksum(pcb, p, dst_ip, dst_port, 0, 0);
496 }
497 
498 /** Same as udp_sendto(), but with checksum */
499 err_t
500 udp_sendto_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip,
501                   u16_t dst_port, u8_t have_chksum, u16_t chksum)
502 {
503 #endif /* LWIP_CHECKSUM_ON_COPY */
504   struct netif *netif;
505 
506   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send\n"));
507 
508   /* find the outgoing network interface for this packet */
509 #if LWIP_IGMP
510   netif = ip_route((ip_addr_ismulticast(dst_ip))?(&(pcb->multicast_ip)):(dst_ip));
511 #else
512   netif = ip_route(dst_ip);
513 #endif /* LWIP_IGMP */
514 
515   /* no outgoing network interface could be found? */
516   if (netif == NULL) {
517     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: No route to %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
518       ip4_addr1_16(dst_ip), ip4_addr2_16(dst_ip), ip4_addr3_16(dst_ip), ip4_addr4_16(dst_ip)));
519     UDP_STATS_INC(udp.rterr);
520     return ERR_RTE;
521   }
522 #if LWIP_CHECKSUM_ON_COPY
523   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, have_chksum, chksum);
524 #else /* LWIP_CHECKSUM_ON_COPY */
525   return udp_sendto_if(pcb, p, dst_ip, dst_port, netif);
526 #endif /* LWIP_CHECKSUM_ON_COPY */
527 }
528 
529 /**
530  * Send data to a specified address using UDP.
531  * The netif used for sending can be specified.
532  *
533  * This function exists mainly for DHCP, to be able to send UDP packets
534  * on a netif that is still down.
535  *
536  * @param pcb UDP PCB used to send the data.
537  * @param p chain of pbuf's to be sent.
538  * @param dst_ip Destination IP address.
539  * @param dst_port Destination UDP port.
540  * @param netif the netif used for sending.
541  *
542  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
543  *
544  * @return lwIP error code (@see udp_send for possible error codes)
545  *
546  * @see udp_disconnect() udp_send()
547  */
548 err_t
549 udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p,
550   ip_addr_t *dst_ip, u16_t dst_port, struct netif *netif)
551 {
552 #if LWIP_CHECKSUM_ON_COPY
553   return udp_sendto_if_chksum(pcb, p, dst_ip, dst_port, netif, 0, 0);
554 }
555 
556 /** Same as udp_sendto_if(), but with checksum */
557 err_t
558 udp_sendto_if_chksum(struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *dst_ip,
559                      u16_t dst_port, struct netif *netif, u8_t have_chksum,
560                      u16_t chksum)
561 {
562 #endif /* LWIP_CHECKSUM_ON_COPY */
563   struct udp_hdr *udphdr;
564   ip_addr_t *src_ip;
565   err_t err;
566   struct pbuf *q; /* q will be sent down the stack */
567 
568 #if IP_SOF_BROADCAST
569   /* broadcast filter? */
570   if (!ip_get_option(pcb, SOF_BROADCAST) && ip_addr_isbroadcast(dst_ip, netif)) {
571     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_LEVEL_SERIOUS,
572       ("udp_sendto_if: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb));
573     return ERR_VAL;
574   }
575 #endif /* IP_SOF_BROADCAST */
576 
577   /* if the PCB is not yet bound to a port, bind it here */
578   if (pcb->local_port == 0) {
579     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_send: not yet bound to a port, binding now\n"));
580     err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
581     if (err != ERR_OK) {
582       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: forced port bind failed\n"));
583       return err;
584     }
585   }
586 
587   /* not enough space to add an UDP header to first pbuf in given p chain? */
588   if (pbuf_header(p, UDP_HLEN)) {
589     /* allocate header in a separate new pbuf */
590     q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM);
591     /* new header pbuf could not be allocated? */
592     if (q == NULL) {
593       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("udp_send: could not allocate header\n"));
594       return ERR_MEM;
595     }
596     if (p->tot_len != 0) {
597       /* chain header q in front of given pbuf p (only if p contains data) */
598       pbuf_chain(q, p);
599     }
600     /* first pbuf q points to header pbuf */
601     LWIP_DEBUGF(UDP_DEBUG,
602                 ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
603   } else {
604     /* adding space for header within p succeeded */
605     /* first pbuf q equals given pbuf */
606     q = p;
607     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p));
608   }
609   LWIP_ASSERT("check that first pbuf can hold struct udp_hdr",
610               (q->len >= sizeof(struct udp_hdr)));
611   /* q now represents the packet to be sent */
612   udphdr = (struct udp_hdr *)q->payload;
613   udphdr->src = htons(pcb->local_port);
614   udphdr->dest = htons(dst_port);
615   /* in UDP, 0 checksum means 'no checksum' */
616   udphdr->chksum = 0x0000;
617 
618   /* Multicast Loop? */
619 #if LWIP_IGMP
620   if (ip_addr_ismulticast(dst_ip) && ((pcb->flags & UDP_FLAGS_MULTICAST_LOOP) != 0)) {
621     q->flags |= PBUF_FLAG_MCASTLOOP;
622   }
623 #endif /* LWIP_IGMP */
624 
625 
626   /* PCB local address is IP_ANY_ADDR? */
627   if (ip_addr_isany(&pcb->local_ip)) {
628     /* use outgoing network interface IP address as source address */
629     src_ip = &(netif->ip_addr);
630   } else {
631     /* check if UDP PCB local IP address is correct
632      * this could be an old address if netif->ip_addr has changed */
633     if (!ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr))) {
634       /* local_ip doesn't match, drop the packet */
635       if (q != p) {
636         /* free the header pbuf */
637         pbuf_free(q);
638         q = NULL;
639         /* p is still referenced by the caller, and will live on */
640       }
641       return ERR_VAL;
642     }
643     /* use UDP PCB local IP address as source address */
644     src_ip = &(pcb->local_ip);
645   }
646 
647   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len));
648 
649 #if LWIP_UDPLITE
650   /* UDP Lite protocol? */
651   if (pcb->flags & UDP_FLAGS_UDPLITE) {
652     u16_t chklen, chklen_hdr;
653     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len));
654     /* set UDP message length in UDP header */
655     chklen_hdr = chklen = pcb->chksum_len_tx;
656     if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) {
657       if (chklen != 0) {
658         LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen));
659       }
660       /* For UDP-Lite, checksum length of 0 means checksum
661          over the complete packet. (See RFC 3828 chap. 3.1)
662          At least the UDP-Lite header must be covered by the
663          checksum, therefore, if chksum_len has an illegal
664          value, we generate the checksum over the complete
665          packet to be safe. */
666       chklen_hdr = 0;
667       chklen = q->tot_len;
668     }
669     udphdr->len = htons(chklen_hdr);
670     /* calculate checksum */
671 #if CHECKSUM_GEN_UDP
672     udphdr->chksum = inet_chksum_pseudo_partial(q, src_ip, dst_ip,
673       IP_PROTO_UDPLITE, q->tot_len,
674 #if !LWIP_CHECKSUM_ON_COPY
675       chklen);
676 #else /* !LWIP_CHECKSUM_ON_COPY */
677       (have_chksum ? UDP_HLEN : chklen));
678     if (have_chksum) {
679       u32_t acc;
680       acc = udphdr->chksum + (u16_t)~(chksum);
681       udphdr->chksum = FOLD_U32T(acc);
682     }
683 #endif /* !LWIP_CHECKSUM_ON_COPY */
684 
685     /* chksum zero must become 0xffff, as zero means 'no checksum' */
686     if (udphdr->chksum == 0x0000) {
687       udphdr->chksum = 0xffff;
688     }
689 #endif /* CHECKSUM_GEN_UDP */
690     /* output to IP */
691     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDPLITE,)\n"));
692     NETIF_SET_HWADDRHINT(netif, &pcb->addr_hint);
693     err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDPLITE, netif);
694     NETIF_SET_HWADDRHINT(netif, NULL);
695   } else
696 #endif /* LWIP_UDPLITE */
697   {      /* UDP */
698     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
699     udphdr->len = htons(q->tot_len);
700     /* calculate checksum */
701 #if CHECKSUM_GEN_UDP
702     if ((pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) {
703       u16_t udpchksum;
704 #if LWIP_CHECKSUM_ON_COPY
705       if (have_chksum) {
706         u32_t acc;
707         udpchksum = inet_chksum_pseudo_partial(q, src_ip, dst_ip, IP_PROTO_UDP,
708           q->tot_len, UDP_HLEN);
709         acc = udpchksum + (u16_t)~(chksum);
710         udpchksum = FOLD_U32T(acc);
711       } else
712 #endif /* LWIP_CHECKSUM_ON_COPY */
713       {
714         udpchksum = inet_chksum_pseudo(q, src_ip, dst_ip, IP_PROTO_UDP, q->tot_len);
715       }
716 
717       /* chksum zero must become 0xffff, as zero means 'no checksum' */
718       if (udpchksum == 0x0000) {
719         udpchksum = 0xffff;
720       }
721       udphdr->chksum = udpchksum;
722     }
723 #endif /* CHECKSUM_GEN_UDP */
724     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum));
725     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDP,)\n"));
726     /* output to IP */
727     NETIF_SET_HWADDRHINT(netif, &pcb->addr_hint);
728     err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDP, netif);
729     NETIF_SET_HWADDRHINT(netif, NULL);
730   }
731   /* TODO: must this be increased even if error occured? */
732   snmp_inc_udpoutdatagrams();
733 
734   /* did we chain a separate header pbuf earlier? */
735   if (q != p) {
736     /* free the header pbuf */
737     pbuf_free(q);
738     q = NULL;
739     /* p is still referenced by the caller, and will live on */
740   }
741 
742   UDP_STATS_INC(udp.xmit);
743   return err;
744 }
745 
746 /**
747  * Bind an UDP PCB.
748  *
749  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
750  * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to
751  * bind to all local interfaces.
752  * @param port local UDP port to bind with. Use 0 to automatically bind
753  * to a random port between UDP_LOCAL_PORT_RANGE_START and
754  * UDP_LOCAL_PORT_RANGE_END.
755  *
756  * ipaddr & port are expected to be in the same byte order as in the pcb.
757  *
758  * @return lwIP error code.
759  * - ERR_OK. Successful. No error occured.
760  * - ERR_USE. The specified ipaddr and port are already bound to by
761  * another UDP PCB.
762  *
763  * @see udp_disconnect()
764  */
765 err_t
766 udp_bind(struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port)
767 {
768   struct udp_pcb *ipcb;
769   u8_t rebind;
770 
771   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_bind(ipaddr = "));
772   ip_addr_debug_print(UDP_DEBUG, ipaddr);
773   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, (", port = %"U16_F")\n", port));
774 
775   rebind = 0;
776   /* Check for double bind and rebind of the same pcb */
777   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
778     /* is this UDP PCB already on active list? */
779     if (pcb == ipcb) {
780       /* pcb may occur at most once in active list */
781       LWIP_ASSERT("rebind == 0", rebind == 0);
782       /* pcb already in list, just rebind */
783       rebind = 1;
784     }
785 
786     /* By default, we don't allow to bind to a port that any other udp
787        PCB is alread bound to, unless *all* PCBs with that port have tha
788        REUSEADDR flag set. */
789 #if SO_REUSE
790     else if (!ip_get_option(pcb, SOF_REUSEADDR) &&
791              !ip_get_option(ipcb, SOF_REUSEADDR)) {
792 #else /* SO_REUSE */
793     /* port matches that of PCB in list and REUSEADDR not set -> reject */
794     else {
795 #endif /* SO_REUSE */
796       if ((ipcb->local_port == port) &&
797           /* IP address matches, or one is IP_ADDR_ANY? */
798           (ip_addr_isany(&(ipcb->local_ip)) ||
799            ip_addr_isany(ipaddr) ||
800            ip_addr_cmp(&(ipcb->local_ip), ipaddr))) {
801         /* other PCB already binds to this local IP and port */
802         LWIP_DEBUGF(UDP_DEBUG,
803                     ("udp_bind: local port %"U16_F" already bound by another pcb\n", port));
804         return ERR_USE;
805       }
806     }
807   }
808 
809   ip_addr_set(&pcb->local_ip, ipaddr);
810 
811   /* no port specified? */
812   if (port == 0) {
813     port = udp_new_port();
814     if (port == 0) {
815       /* no more ports available in local range */
816       LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n"));
817       return ERR_USE;
818     }
819   }
820   pcb->local_port = port;
821   snmp_insert_udpidx_tree(pcb);
822   /* pcb not active yet? */
823   if (rebind == 0) {
824     /* place the PCB on the active list if not already there */
825     pcb->next = udp_pcbs;
826     udp_pcbs = pcb;
827   }
828   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
829               ("udp_bind: bound to %"U16_F".%"U16_F".%"U16_F".%"U16_F", port %"U16_F"\n",
830                ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip),
831                ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip),
832                pcb->local_port));
833   return ERR_OK;
834 }
835 /**
836  * Connect an UDP PCB.
837  *
838  * This will associate the UDP PCB with the remote address.
839  *
840  * @param pcb UDP PCB to be connected with remote address ipaddr and port.
841  * @param ipaddr remote IP address to connect with.
842  * @param port remote UDP port to connect with.
843  *
844  * @return lwIP error code
845  *
846  * ipaddr & port are expected to be in the same byte order as in the pcb.
847  *
848  * The udp pcb is bound to a random local port if not already bound.
849  *
850  * @see udp_disconnect()
851  */
852 err_t
853 udp_connect(struct udp_pcb *pcb, ip_addr_t *ipaddr, u16_t port)
854 {
855   struct udp_pcb *ipcb;
856 
857   if (pcb->local_port == 0) {
858     err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
859     if (err != ERR_OK) {
860       return err;
861     }
862   }
863 
864   ip_addr_set(&pcb->remote_ip, ipaddr);
865   pcb->remote_port = port;
866   pcb->flags |= UDP_FLAGS_CONNECTED;
867 /** TODO: this functionality belongs in upper layers */
868 #ifdef LWIP_UDP_TODO
869   /* Nail down local IP for netconn_addr()/getsockname() */
870   if (ip_addr_isany(&pcb->local_ip) && !ip_addr_isany(&pcb->remote_ip)) {
871     struct netif *netif;
872 
873     if ((netif = ip_route(&(pcb->remote_ip))) == NULL) {
874       LWIP_DEBUGF(UDP_DEBUG, ("udp_connect: No route to 0x%lx\n", pcb->remote_ip.addr));
875       UDP_STATS_INC(udp.rterr);
876       return ERR_RTE;
877     }
878     /** TODO: this will bind the udp pcb locally, to the interface which
879         is used to route output packets to the remote address. However, we
880         might want to accept incoming packets on any interface! */
881     pcb->local_ip = netif->ip_addr;
882   } else if (ip_addr_isany(&pcb->remote_ip)) {
883     pcb->local_ip.addr = 0;
884   }
885 #endif
886   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
887               ("udp_connect: connected to %"U16_F".%"U16_F".%"U16_F".%"U16_F",port %"U16_F"\n",
888                ip4_addr1_16(&pcb->local_ip), ip4_addr2_16(&pcb->local_ip),
889                ip4_addr3_16(&pcb->local_ip), ip4_addr4_16(&pcb->local_ip),
890                pcb->local_port));
891 
892   /* Insert UDP PCB into the list of active UDP PCBs. */
893   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
894     if (pcb == ipcb) {
895       /* already on the list, just return */
896       return ERR_OK;
897     }
898   }
899   /* PCB not yet on the list, add PCB now */
900   pcb->next = udp_pcbs;
901   udp_pcbs = pcb;
902   return ERR_OK;
903 }
904 
905 /**
906  * Disconnect a UDP PCB
907  *
908  * @param pcb the udp pcb to disconnect.
909  */
910 void
911 udp_disconnect(struct udp_pcb *pcb)
912 {
913   /* reset remote address association */
914   ip_addr_set_any(&pcb->remote_ip);
915   pcb->remote_port = 0;
916   /* mark PCB as unconnected */
917   pcb->flags &= ~UDP_FLAGS_CONNECTED;
918 }
919 
920 /**
921  * Set a receive callback for a UDP PCB
922  *
923  * This callback will be called when receiving a datagram for the pcb.
924  *
925  * @param pcb the pcb for wich to set the recv callback
926  * @param recv function pointer of the callback function
927  * @param recv_arg additional argument to pass to the callback function
928  */
929 void
930 udp_recv(struct udp_pcb *pcb, udp_recv_fn recv, void *recv_arg)
931 {
932   /* remember recv() callback and user data */
933   pcb->recv = recv;
934   pcb->recv_arg = recv_arg;
935 }
936 
937 /**
938  * Remove an UDP PCB.
939  *
940  * @param pcb UDP PCB to be removed. The PCB is removed from the list of
941  * UDP PCB's and the data structure is freed from memory.
942  *
943  * @see udp_new()
944  */
945 void
946 udp_remove(struct udp_pcb *pcb)
947 {
948   struct udp_pcb *pcb2;
949 
950   snmp_delete_udpidx_tree(pcb);
951   /* pcb to be removed is first in list? */
952   if (udp_pcbs == pcb) {
953     /* make list start at 2nd pcb */
954     udp_pcbs = udp_pcbs->next;
955     /* pcb not 1st in list */
956   } else {
957     for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
958       /* find pcb in udp_pcbs list */
959       if (pcb2->next != NULL && pcb2->next == pcb) {
960         /* remove pcb from list */
961         pcb2->next = pcb->next;
962       }
963     }
964   }
965   memp_free(MEMP_UDP_PCB, pcb);
966 }
967 
968 /**
969  * Create a UDP PCB.
970  *
971  * @return The UDP PCB which was created. NULL if the PCB data structure
972  * could not be allocated.
973  *
974  * @see udp_remove()
975  */
976 struct udp_pcb *
977 udp_new(void)
978 {
979   struct udp_pcb *pcb;
980   pcb = (struct udp_pcb *)memp_malloc(MEMP_UDP_PCB);
981   /* could allocate UDP PCB? */
982   if (pcb != NULL) {
983     /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0
984      * which means checksum is generated over the whole datagram per default
985      * (recommended as default by RFC 3828). */
986     /* initialize PCB to all zeroes */
987     memset(pcb, 0, sizeof(struct udp_pcb));
988     pcb->ttl = UDP_TTL;
989   }
990   return pcb;
991 }
992 
993 #if UDP_DEBUG
994 /**
995  * Print UDP header information for debug purposes.
996  *
997  * @param udphdr pointer to the udp header in memory.
998  */
999 void
1000 udp_debug_print(struct udp_hdr *udphdr)
1001 {
1002   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
1003   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1004   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
1005                           ntohs(udphdr->src), ntohs(udphdr->dest)));
1006   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1007   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
1008                           ntohs(udphdr->len), ntohs(udphdr->chksum)));
1009   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
1010 }
1011 #endif /* UDP_DEBUG */
1012 
1013 #endif /* LWIP_UDP */
1014