]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lwip.git/blob - src/core/udp.c
Changed initialization: many init functions are not needed any more since we now...
[pes-rpp/rpp-lwip.git] / src / core / udp.c
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/def.h"
54 #include "lwip/memp.h"
55 #include "lwip/inet.h"
56 #include "lwip/ip_addr.h"
57 #include "lwip/netif.h"
58 #include "lwip/udp.h"
59 #include "lwip/icmp.h"
60 #include "lwip/stats.h"
61 #include "lwip/snmp.h"
62 #include "arch/perf.h"
63
64 #include <string.h>
65
66 /* The list of UDP PCBs */
67 /* exported in udp.h (was static) */
68 struct udp_pcb *udp_pcbs;
69
70 /**
71  * Process an incoming UDP datagram.
72  *
73  * Given an incoming UDP datagram (as a chain of pbufs) this function
74  * finds a corresponding UDP PCB and hands over the pbuf to the pcbs
75  * recv function. If no pcb is found or the datagram is incorrect, the
76  * pbuf is freed.
77  *
78  * @param p pbuf to be demultiplexed to a UDP PCB.
79  * @param inp network interface on which the datagram was received.
80  *
81  */
82 void
83 udp_input(struct pbuf *p, struct netif *inp)
84 {
85   struct udp_hdr *udphdr;
86   struct udp_pcb *pcb;
87   struct udp_pcb *uncon_pcb;
88   struct ip_hdr *iphdr;
89   u16_t src, dest;
90   u8_t local_match;
91
92   PERF_START;
93
94   UDP_STATS_INC(udp.recv);
95
96   iphdr = p->payload;
97
98   /* Check minimum length (IP header + UDP header)
99    * and move payload pointer to UDP header */
100   if (p->tot_len < (IPH_HL(iphdr) * 4 + UDP_HLEN) || pbuf_header(p, -(s16_t)(IPH_HL(iphdr) * 4))) {
101     /* drop short packets */
102     LWIP_DEBUGF(UDP_DEBUG,
103                 ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len));
104     UDP_STATS_INC(udp.lenerr);
105     UDP_STATS_INC(udp.drop);
106     snmp_inc_udpinerrors();
107     pbuf_free(p);
108     goto end;
109   }
110
111   udphdr = (struct udp_hdr *)p->payload;
112
113   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
114
115   /* convert src and dest ports to host byte order */
116   src = ntohs(udphdr->src);
117   dest = ntohs(udphdr->dest);
118
119   udp_debug_print(udphdr);
120
121   /* print the UDP source and destination */
122   LWIP_DEBUGF(UDP_DEBUG,
123               ("udp (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") <-- "
124                "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
125                ip4_addr1(&iphdr->dest), ip4_addr2(&iphdr->dest),
126                ip4_addr3(&iphdr->dest), ip4_addr4(&iphdr->dest), ntohs(udphdr->dest),
127                ip4_addr1(&iphdr->src), ip4_addr2(&iphdr->src),
128                ip4_addr3(&iphdr->src), ip4_addr4(&iphdr->src), ntohs(udphdr->src)));
129
130   local_match = 0;
131   uncon_pcb = NULL;
132   /* Iterate through the UDP pcb list for a matching pcb.
133    * 'Perfect match' pcbs (connected to the remote port & ip address) are
134    * preferred. If no perfect match is found, the first unconnected pcb that
135    * matches the local port and ip address gets the datagram. */
136   for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
137     local_match = 0;
138     /* print the PCB local and remote address */
139     LWIP_DEBUGF(UDP_DEBUG,
140                 ("pcb (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") --- "
141                  "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
142                  ip4_addr1(&pcb->local_ip), ip4_addr2(&pcb->local_ip),
143                  ip4_addr3(&pcb->local_ip), ip4_addr4(&pcb->local_ip), pcb->local_port,
144                  ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
145                  ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip), pcb->remote_port));
146
147     /* compare PCB local addr+port to UDP destination addr+port */
148     if ((pcb->local_port == dest) &&
149         (ip_addr_isany(&pcb->local_ip) ||
150          ip_addr_cmp(&(pcb->local_ip), &(iphdr->dest)) || 
151 #if LWIP_IGMP
152          ip_addr_ismulticast(&(iphdr->dest)) ||
153 #endif /* LWIP_IGMP */
154          ip_addr_isbroadcast(&(iphdr->dest), inp))) {
155       local_match = 1;
156       if ((uncon_pcb == NULL) && 
157           ((pcb->flags & UDP_FLAGS_CONNECTED) == 0)) {
158         /* the first unconnected matching PCB */     
159         uncon_pcb = pcb;
160       }
161     }
162     /* compare PCB remote addr+port to UDP source addr+port */
163     if ((local_match != 0) &&
164         (pcb->remote_port == src) &&
165         (ip_addr_isany(&pcb->remote_ip) ||
166          ip_addr_cmp(&(pcb->remote_ip), &(iphdr->src)))) {
167       /* the first fully matching PCB */
168       break;
169     }
170   }
171   /* no fully matching pcb found? then look for an unconnected pcb */
172   if (pcb == NULL) {
173     pcb = uncon_pcb;
174   }
175
176   /* Check checksum if this is a match or if it was directed at us. */
177   if (pcb != NULL || ip_addr_cmp(&inp->ip_addr, &iphdr->dest)) {
178     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n"));
179 #if LWIP_UDPLITE
180     if (IPH_PROTO(iphdr) == IP_PROTO_UDPLITE) {
181       /* Do the UDP Lite checksum */
182 #if CHECKSUM_CHECK_UDP
183       u16_t chklen = ntohs(udphdr->len);
184       if (chklen < sizeof(struct udp_hdr)) {
185         if (chklen == 0) {
186           /* For UDP-Lite, checksum length of 0 means checksum
187              over the complete packet (See RFC 3828 chap. 3.1) */
188           chklen = p->tot_len;
189         } else {
190           /* At least the UDP-Lite header must be covered by the
191              checksum! (Again, see RFC 3828 chap. 3.1) */
192           UDP_STATS_INC(udp.chkerr);
193           UDP_STATS_INC(udp.drop);
194           snmp_inc_udpinerrors();
195           pbuf_free(p);
196           goto end;
197         }
198       }
199       if (inet_chksum_pseudo_partial(p, (struct ip_addr *)&(iphdr->src),
200                              (struct ip_addr *)&(iphdr->dest),
201                              IP_PROTO_UDPLITE, p->tot_len, chklen) != 0) {
202         LWIP_DEBUGF(UDP_DEBUG | 2,
203                     ("udp_input: UDP Lite datagram discarded due to failing checksum\n"));
204         UDP_STATS_INC(udp.chkerr);
205         UDP_STATS_INC(udp.drop);
206         snmp_inc_udpinerrors();
207         pbuf_free(p);
208         goto end;
209       }
210 #endif /* CHECKSUM_CHECK_UDP */
211     } else
212 #endif /* LWIP_UDPLITE */
213     {
214 #if CHECKSUM_CHECK_UDP
215       if (udphdr->chksum != 0) {
216         if (inet_chksum_pseudo(p, (struct ip_addr *)&(iphdr->src),
217                                (struct ip_addr *)&(iphdr->dest),
218                                IP_PROTO_UDP, p->tot_len) != 0) {
219           LWIP_DEBUGF(UDP_DEBUG | 2,
220                       ("udp_input: UDP datagram discarded due to failing checksum\n"));
221           UDP_STATS_INC(udp.chkerr);
222           UDP_STATS_INC(udp.drop);
223           snmp_inc_udpinerrors();
224           pbuf_free(p);
225           goto end;
226         }
227       }
228 #endif /* CHECKSUM_CHECK_UDP */
229     }
230     if(pbuf_header(p, -UDP_HLEN)) {
231       /* Can we cope with this failing? Just assert for now */
232       LWIP_ASSERT("pbuf_header failed\n", 0);
233       UDP_STATS_INC(udp.drop);
234       snmp_inc_udpinerrors();
235       pbuf_free(p);
236       goto end;
237     }
238     if (pcb != NULL) {
239       snmp_inc_udpindatagrams();
240       /* callback */
241       if (pcb->recv != NULL) {
242         /* now the recv function is responsible for freeing p */
243         pcb->recv(pcb->recv_arg, pcb, p, &(iphdr->src), src);
244       } else {
245         /* no recv function registered? then we have to free the pbuf! */
246         pbuf_free(p);
247         goto end;
248       }
249     } else {
250       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n"));
251
252 #if LWIP_ICMP
253       /* No match was found, send ICMP destination port unreachable unless
254          destination address was broadcast/multicast. */
255       if (!ip_addr_isbroadcast(&iphdr->dest, inp) &&
256           !ip_addr_ismulticast(&iphdr->dest)) {
257         /* move payload pointer back to ip header */
258         pbuf_header(p, (IPH_HL(iphdr) * 4) + UDP_HLEN);
259         LWIP_ASSERT("p->payload == iphdr", (p->payload == iphdr));
260         icmp_dest_unreach(p, ICMP_DUR_PORT);
261       }
262 #endif /* LWIP_ICMP */
263       UDP_STATS_INC(udp.proterr);
264       UDP_STATS_INC(udp.drop);
265       snmp_inc_udpnoports();
266       pbuf_free(p);
267     }
268   } else {
269     pbuf_free(p);
270   }
271 end:
272   PERF_STOP("udp_input");
273 }
274
275 /**
276  * Send data to a specified address using UDP.
277  *
278  * @param pcb UDP PCB used to send the data.
279  * @param p chain of pbuf's to be sent.
280  * @param dst_ip Destination IP address.
281  * @param dst_port Destination UDP port.
282  *
283  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
284  *
285  * If the PCB already has a remote address association, it will
286  * be restored after the data is sent.
287  * 
288  * @return lwIP error code (@see udp_send for possible error codes)
289  *
290  * @see udp_disconnect() udp_send()
291  */
292 err_t
293 udp_sendto(struct udp_pcb *pcb, struct pbuf *p,
294   struct ip_addr *dst_ip, u16_t dst_port)
295 {
296   err_t err;
297   /* temporary space for current PCB remote address */
298   struct ip_addr pcb_remote_ip;
299   u16_t pcb_remote_port;
300   /* remember current remote peer address of PCB */
301   pcb_remote_ip.addr = pcb->remote_ip.addr;
302   pcb_remote_port = pcb->remote_port;
303   /* copy packet destination address to PCB remote peer address */
304   pcb->remote_ip.addr = dst_ip->addr;
305   pcb->remote_port = dst_port;
306   /* send to the packet destination address */
307   err = udp_send(pcb, p);
308   /* restore PCB remote peer address */
309   pcb->remote_ip.addr = pcb_remote_ip.addr;
310   pcb->remote_port = pcb_remote_port;
311   return err;
312 }
313
314 /**
315  * Send data using UDP.
316  *
317  * @param pcb UDP PCB used to send the data.
318  * @param p chain of pbuf's to be sent.
319  *
320  * The datagram will be sent to the current remote_ip & remote_port
321  * stored in pcb. If the pcb is not bound to a port, it will
322  * automatically be bound to a random port.
323  *
324  * @return lwIP error code.
325  * - ERR_OK. Successful. No error occured.
326  * - ERR_MEM. Out of memory.
327  * - ERR_RTE. Could not find route to destination address.
328  * - More errors could be returned by lower protocol layers.
329  *
330  * @see udp_disconnect() udp_sendto()
331  */
332 err_t
333 udp_send(struct udp_pcb *pcb, struct pbuf *p)
334 {
335   struct udp_hdr *udphdr;
336   struct netif *netif;
337   struct ip_addr *src_ip;
338   err_t err;
339   struct pbuf *q; /* q will be sent down the stack */
340
341   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, ("udp_send\n"));
342
343   /* if the PCB is not yet bound to a port, bind it here */
344   if (pcb->local_port == 0) {
345     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: not yet bound to a port, binding now\n"));
346     err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
347     if (err != ERR_OK) {
348       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: forced port bind failed\n"));
349       return err;
350     }
351   }
352
353   /* find the outgoing network interface for this packet */
354 #if LWIP_IGMP
355   netif = ip_route((ip_addr_ismulticast(&(pcb->remote_ip)))?(&(pcb->multicast_ip)):(&(pcb->remote_ip)));
356 #else
357   netif = ip_route(&(pcb->remote_ip));
358 #endif /* LWIP_IGMP */
359
360   /* no outgoing network interface could be found? */
361   if (netif == NULL) {
362     LWIP_DEBUGF(UDP_DEBUG | 1, ("udp_send: No route to 0x%"X32_F"\n", pcb->remote_ip.addr));
363     UDP_STATS_INC(udp.rterr);
364     return ERR_RTE;
365   }
366
367   /* not enough space to add an UDP header to first pbuf in given p chain? */
368   if (pbuf_header(p, UDP_HLEN)) {
369     /* allocate header in a seperate new pbuf */
370     q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM);
371     /* new header pbuf could not be allocated? */
372     if (q == NULL) {
373       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: could not allocate header\n"));
374       return ERR_MEM;
375     }
376     /* chain header q in front of given pbuf p */
377     pbuf_chain(q, p);
378     /* first pbuf q points to header pbuf */
379     LWIP_DEBUGF(UDP_DEBUG,
380                 ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
381   } else {
382     /* adding space for header within p succeeded */
383     /* first pbuf q equals given pbuf */
384     q = p;
385     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p));
386   }
387   LWIP_ASSERT("check that first pbuf can hold struct udp_hdr",
388               (q->len >= sizeof(struct udp_hdr)));
389   /* q now represents the packet to be sent */
390   udphdr = q->payload;
391   udphdr->src = htons(pcb->local_port);
392   udphdr->dest = htons(pcb->remote_port);
393   /* in UDP, 0 checksum means 'no checksum' */
394   udphdr->chksum = 0x0000; 
395
396   /* PCB local address is IP_ANY_ADDR? */
397   if (ip_addr_isany(&pcb->local_ip)) {
398     /* use outgoing network interface IP address as source address */
399     src_ip = &(netif->ip_addr);
400   } else {
401     /* check if UDP PCB local IP address is correct
402      * this could be an old address if netif->ip_addr has changed */
403     if (!ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr))) {
404       /* local_ip doesn't match, drop the packet */
405       if (q != p) {
406         /* free the header pbuf */
407         pbuf_free(q);
408         q = NULL;
409         /* p is still referenced by the caller, and will live on */
410       }
411       return ERR_VAL;
412     }
413     /* use UDP PCB local IP address as source address */
414     src_ip = &(pcb->local_ip);
415   }
416
417   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len));
418
419 #if LWIP_UDPLITE
420   /* UDP Lite protocol? */
421   if (pcb->flags & UDP_FLAGS_UDPLITE) {
422     u16_t chklen, chklen_hdr;
423     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len));
424     /* set UDP message length in UDP header */
425     chklen_hdr = chklen = pcb->chksum_len_tx;
426     if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) {
427       if (chklen != 0) {
428         LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen));
429       }
430       /* For UDP-Lite, checksum length of 0 means checksum
431          over the complete packet. (See RFC 3828 chap. 3.1)
432          At least the UDP-Lite header must be covered by the
433          checksum, therefore, if chksum_len has an illegal
434          value, we generate the checksum over the complete
435          packet to be safe. */
436       chklen_hdr = 0;
437       chklen = q->tot_len;
438     }
439     udphdr->len = htons(chklen_hdr);
440     /* calculate checksum */
441 #if CHECKSUM_GEN_UDP
442     udphdr->chksum = inet_chksum_pseudo_partial(q, src_ip, &(pcb->remote_ip),
443                                         IP_PROTO_UDPLITE, q->tot_len, chklen);
444     /* chksum zero must become 0xffff, as zero means 'no checksum' */
445     if (udphdr->chksum == 0x0000)
446       udphdr->chksum = 0xffff;
447 #endif /* CHECKSUM_CHECK_UDP */
448     /* output to IP */
449     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDPLITE,)\n"));
450 #if LWIP_NETIF_HWADDRHINT
451     netif->addr_hint = &(pcb->addr_hint);
452 #endif /* LWIP_NETIF_HWADDRHINT*/
453     err = ip_output_if(q, src_ip, &pcb->remote_ip, pcb->ttl, pcb->tos, IP_PROTO_UDPLITE, netif);    
454 #if LWIP_NETIF_HWADDRHINT
455     netif->addr_hint = NULL;
456 #endif /* LWIP_NETIF_HWADDRHINT*/
457   } else
458 #endif /* LWIP_UDPLITE */
459   {      /* UDP */
460     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
461     udphdr->len = htons(q->tot_len);
462     /* calculate checksum */
463 #if CHECKSUM_GEN_UDP
464     if ((pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) {
465       udphdr->chksum = inet_chksum_pseudo(q, src_ip, &pcb->remote_ip, IP_PROTO_UDP, q->tot_len);
466       /* chksum zero must become 0xffff, as zero means 'no checksum' */
467       if (udphdr->chksum == 0x0000) udphdr->chksum = 0xffff;
468     }
469 #endif /* CHECKSUM_CHECK_UDP */
470     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum));
471     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDP,)\n"));
472     /* output to IP */
473 #if LWIP_NETIF_HWADDRHINT
474     netif->addr_hint = &(pcb->addr_hint);
475 #endif /* LWIP_NETIF_HWADDRHINT*/
476     err = ip_output_if(q, src_ip, &pcb->remote_ip, pcb->ttl, pcb->tos, IP_PROTO_UDP, netif);    
477 #if LWIP_NETIF_HWADDRHINT
478     netif->addr_hint = NULL;
479 #endif /* LWIP_NETIF_HWADDRHINT*/
480   }
481   /* TODO: must this be increased even if error occured? */
482   snmp_inc_udpoutdatagrams();
483
484   /* did we chain a seperate header pbuf earlier? */
485   if (q != p) {
486     /* free the header pbuf */
487     pbuf_free(q);
488     q = NULL;
489     /* p is still referenced by the caller, and will live on */
490   }
491
492   UDP_STATS_INC(udp.xmit);
493   return err;
494 }
495
496 /**
497  * Bind an UDP PCB.
498  *
499  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
500  * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to
501  * bind to all local interfaces.
502  * @param port local UDP port to bind with. Use 0 to automatically bind
503  * to a random port between UDP_LOCAL_PORT_RANGE_START and
504  * UDP_LOCAL_PORT_RANGE_END.
505  *
506  * ipaddr & port are expected to be in the same byte order as in the pcb.
507  *
508  * @return lwIP error code.
509  * - ERR_OK. Successful. No error occured.
510  * - ERR_USE. The specified ipaddr and port are already bound to by
511  * another UDP PCB.
512  *
513  * @see udp_disconnect()
514  */
515 err_t
516 udp_bind(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
517 {
518   struct udp_pcb *ipcb;
519   u8_t rebind;
520
521   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, ("udp_bind(ipaddr = "));
522   ip_addr_debug_print(UDP_DEBUG, ipaddr);
523   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, (", port = %"U16_F")\n", port));
524
525   rebind = 0;
526   /* Check for double bind and rebind of the same pcb */
527   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
528     /* is this UDP PCB already on active list? */
529     if (pcb == ipcb) {
530       /* pcb may occur at most once in active list */
531       LWIP_ASSERT("rebind == 0", rebind == 0);
532       /* pcb already in list, just rebind */
533       rebind = 1;
534     }
535
536     /* this code does not allow upper layer to share a UDP port for
537        listening to broadcast or multicast traffic (See SO_REUSE_ADDR and
538        SO_REUSE_PORT under *BSD). TODO: See where it fits instead, OR
539        combine with implementation of UDP PCB flags. Leon Woestenberg. */
540 #ifdef LWIP_UDP_TODO
541     /* port matches that of PCB in list? */
542     else
543       if ((ipcb->local_port == port) &&
544           /* IP address matches, or one is IP_ADDR_ANY? */
545           (ip_addr_isany(&(ipcb->local_ip)) ||
546            ip_addr_isany(ipaddr) ||
547            ip_addr_cmp(&(ipcb->local_ip), ipaddr))) {
548         /* other PCB already binds to this local IP and port */
549         LWIP_DEBUGF(UDP_DEBUG,
550                     ("udp_bind: local port %"U16_F" already bound by another pcb\n", port));
551         return ERR_USE;
552       }
553 #endif
554   }
555
556   ip_addr_set(&pcb->local_ip, ipaddr);
557
558   /* no port specified? */
559   if (port == 0) {
560 #ifndef UDP_LOCAL_PORT_RANGE_START
561 #define UDP_LOCAL_PORT_RANGE_START 4096
562 #define UDP_LOCAL_PORT_RANGE_END   0x7fff
563 #endif
564     port = UDP_LOCAL_PORT_RANGE_START;
565     ipcb = udp_pcbs;
566     while ((ipcb != NULL) && (port != UDP_LOCAL_PORT_RANGE_END)) {
567       if (ipcb->local_port == port) {
568         /* port is already used by another udp_pcb */
569         port++;
570         /* restart scanning all udp pcbs */
571         ipcb = udp_pcbs;
572       } else
573         /* go on with next udp pcb */
574         ipcb = ipcb->next;
575     }
576     if (ipcb != NULL) {
577       /* no more ports available in local range */
578       LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n"));
579       return ERR_USE;
580     }
581   }
582   pcb->local_port = port;
583   snmp_insert_udpidx_tree(pcb);
584   /* pcb not active yet? */
585   if (rebind == 0) {
586     /* place the PCB on the active list if not already there */
587     pcb->next = udp_pcbs;
588     udp_pcbs = pcb;
589   }
590   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
591               ("udp_bind: bound to %"U16_F".%"U16_F".%"U16_F".%"U16_F", port %"U16_F"\n",
592                (u16_t)(ntohl(pcb->local_ip.addr) >> 24 & 0xff),
593                (u16_t)(ntohl(pcb->local_ip.addr) >> 16 & 0xff),
594                (u16_t)(ntohl(pcb->local_ip.addr) >> 8 & 0xff),
595                (u16_t)(ntohl(pcb->local_ip.addr) & 0xff), pcb->local_port));
596   return ERR_OK;
597 }
598 /**
599  * Connect an UDP PCB.
600  *
601  * This will associate the UDP PCB with the remote address.
602  *
603  * @param pcb UDP PCB to be connected with remote address ipaddr and port.
604  * @param ipaddr remote IP address to connect with.
605  * @param port remote UDP port to connect with.
606  *
607  * @return lwIP error code
608  *
609  * ipaddr & port are expected to be in the same byte order as in the pcb.
610  *
611  * The udp pcb is bound to a random local port if not already bound.
612  *
613  * @see udp_disconnect()
614  */
615 err_t
616 udp_connect(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
617 {
618   struct udp_pcb *ipcb;
619
620   if (pcb->local_port == 0) {
621     err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
622     if (err != ERR_OK)
623       return err;
624   }
625
626   ip_addr_set(&pcb->remote_ip, ipaddr);
627   pcb->remote_port = port;
628   pcb->flags |= UDP_FLAGS_CONNECTED;
629 /** TODO: this functionality belongs in upper layers */
630 #ifdef LWIP_UDP_TODO
631   /* Nail down local IP for netconn_addr()/getsockname() */
632   if (ip_addr_isany(&pcb->local_ip) && !ip_addr_isany(&pcb->remote_ip)) {
633     struct netif *netif;
634
635     if ((netif = ip_route(&(pcb->remote_ip))) == NULL) {
636       LWIP_DEBUGF(UDP_DEBUG, ("udp_connect: No route to 0x%lx\n", pcb->remote_ip.addr));
637       UDP_STATS_INC(udp.rterr);
638       return ERR_RTE;
639     }
640     /** TODO: this will bind the udp pcb locally, to the interface which
641         is used to route output packets to the remote address. However, we
642         might want to accept incoming packets on any interface! */
643     pcb->local_ip = netif->ip_addr;
644   } else if (ip_addr_isany(&pcb->remote_ip)) {
645     pcb->local_ip.addr = 0;
646   }
647 #endif
648   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
649               ("udp_connect: connected to %"U16_F".%"U16_F".%"U16_F".%"U16_F",port %"U16_F"\n",
650                (u16_t)(ntohl(pcb->remote_ip.addr) >> 24 & 0xff),
651                (u16_t)(ntohl(pcb->remote_ip.addr) >> 16 & 0xff),
652                (u16_t)(ntohl(pcb->remote_ip.addr) >> 8 & 0xff),
653                (u16_t)(ntohl(pcb->remote_ip.addr) & 0xff), pcb->remote_port));
654
655   /* Insert UDP PCB into the list of active UDP PCBs. */
656   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
657     if (pcb == ipcb) {
658       /* already on the list, just return */
659       return ERR_OK;
660     }
661   }
662   /* PCB not yet on the list, add PCB now */
663   pcb->next = udp_pcbs;
664   udp_pcbs = pcb;
665   return ERR_OK;
666 }
667
668 /**
669  * Disconnect a UDP PCB
670  *
671  * @param pcb the udp pcb to disconnect.
672  */
673 void
674 udp_disconnect(struct udp_pcb *pcb)
675 {
676   /* reset remote address association */
677   ip_addr_set(&pcb->remote_ip, IP_ADDR_ANY);
678   pcb->remote_port = 0;
679   /* mark PCB as unconnected */
680   pcb->flags &= ~UDP_FLAGS_CONNECTED;
681 }
682
683 /**
684  * Set a receive callback for a UDP PCB
685  *
686  * This callback will be called when receiving a datagram for the pcb.
687  *
688  * @param pcb the pcb for wich to set the recv callback
689  * @param recv function pointer of the callback function
690  * @param recv_arg additional argument to pass to the callback function
691  */
692 void
693 udp_recv(struct udp_pcb *pcb,
694          void (* recv)(void *arg, struct udp_pcb *upcb, struct pbuf *p,
695                        struct ip_addr *addr, u16_t port),
696          void *recv_arg)
697 {
698   /* remember recv() callback and user data */
699   pcb->recv = recv;
700   pcb->recv_arg = recv_arg;
701 }
702
703 /**
704  * Remove an UDP PCB.
705  *
706  * @param pcb UDP PCB to be removed. The PCB is removed from the list of
707  * UDP PCB's and the data structure is freed from memory.
708  *
709  * @see udp_new()
710  */
711 void
712 udp_remove(struct udp_pcb *pcb)
713 {
714   struct udp_pcb *pcb2;
715
716   snmp_delete_udpidx_tree(pcb);
717   /* pcb to be removed is first in list? */
718   if (udp_pcbs == pcb) {
719     /* make list start at 2nd pcb */
720     udp_pcbs = udp_pcbs->next;
721     /* pcb not 1st in list */
722   } else
723     for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
724       /* find pcb in udp_pcbs list */
725       if (pcb2->next != NULL && pcb2->next == pcb) {
726         /* remove pcb from list */
727         pcb2->next = pcb->next;
728       }
729     }
730   memp_free(MEMP_UDP_PCB, pcb);
731 }
732
733 /**
734  * Create a UDP PCB.
735  *
736  * @return The UDP PCB which was created. NULL if the PCB data structure
737  * could not be allocated.
738  *
739  * @see udp_remove()
740  */
741 struct udp_pcb *
742 udp_new(void)
743 {
744   struct udp_pcb *pcb;
745   pcb = memp_malloc(MEMP_UDP_PCB);
746   /* could allocate UDP PCB? */
747   if (pcb != NULL) {
748     /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0
749      * which means checksum is generated over the whole datagram per default
750      * (recommended as default by RFC 3828). */
751     /* initialize PCB to all zeroes */
752     memset(pcb, 0, sizeof(struct udp_pcb));
753     pcb->ttl = UDP_TTL;
754   }
755   return pcb;
756 }
757
758 #if UDP_DEBUG
759 /**
760  * Print UDP header information for debug purposes.
761  *
762  * @param udphdr pointer to the udp header in memory.
763  */
764 void
765 udp_debug_print(struct udp_hdr *udphdr)
766 {
767   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
768   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
769   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
770                           ntohs(udphdr->src), ntohs(udphdr->dest)));
771   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
772   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
773                           ntohs(udphdr->len), ntohs(udphdr->chksum)));
774   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
775 }
776 #endif /* UDP_DEBUG */
777
778 #endif /* LWIP_UDP */