A version of LWIP, provided for backwards compatibility.

Dependents:   AA_DemoBoard DemoBoard HelloServerDemo DemoBoard_RangeIndicator ... more

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers udp.c Source File

udp.c

Go to the documentation of this file.
00001 /**
00002  * @file
00003  * User Datagram Protocol module
00004  *
00005  */
00006 
00007 /*
00008  * Copyright (c) 2001-2004 Swedish Institute of Computer Science.
00009  * All rights reserved.
00010  *
00011  * Redistribution and use in source and binary forms, with or without modification,
00012  * are permitted provided that the following conditions are met:
00013  *
00014  * 1. Redistributions of source code must retain the above copyright notice,
00015  *    this list of conditions and the following disclaimer.
00016  * 2. Redistributions in binary form must reproduce the above copyright notice,
00017  *    this list of conditions and the following disclaimer in the documentation
00018  *    and/or other materials provided with the distribution.
00019  * 3. The name of the author may not be used to endorse or promote products
00020  *    derived from this software without specific prior written permission.
00021  *
00022  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
00023  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
00024  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
00025  * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00026  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
00027  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
00028  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
00029  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
00030  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
00031  * OF SUCH DAMAGE.
00032  *
00033  * This file is part of the lwIP TCP/IP stack.
00034  *
00035  * Author: Adam Dunkels <adam@sics.se>
00036  *
00037  */
00038 
00039 
00040 /* udp.c
00041  *
00042  * The code for the User Datagram Protocol UDP & UDPLite (RFC 3828).
00043  *
00044  */
00045 
00046 /* @todo Check the use of '(struct udp_pcb).chksum_len_rx'!
00047  */
00048 
00049 #include "lwip/opt.h"
00050 
00051 #if LWIP_UDP /* don't build if not configured for use in lwipopts.h */
00052 
00053 #include "lwip/udp.h"
00054 #include "lwip/def.h"
00055 #include "lwip/memp.h"
00056 #include "lwip/inet.h"
00057 #include "lwip/inet_chksum.h"
00058 #include "lwip/ip_addr.h"
00059 #include "lwip/netif.h"
00060 #include "lwip/icmp.h"
00061 #include "lwip/stats.h"
00062 #include "lwip/snmp.h"
00063 #include "arch/perf.h"
00064 #include "lwip/dhcp.h"
00065 
00066 #include <string.h>
00067 
00068 /* The list of UDP PCBs */
00069 /* exported in udp.h (was static) */
00070 struct udp_pcb *udp_pcbs;
00071 
00072 /**
00073  * Process an incoming UDP datagram.
00074  *
00075  * Given an incoming UDP datagram (as a chain of pbufs) this function
00076  * finds a corresponding UDP PCB and hands over the pbuf to the pcbs
00077  * recv function. If no pcb is found or the datagram is incorrect, the
00078  * pbuf is freed.
00079  *
00080  * @param p pbuf to be demultiplexed to a UDP PCB.
00081  * @param inp network interface on which the datagram was received.
00082  *
00083  */
00084 void
00085 udp_input(struct pbuf *p, struct netif *inp)
00086 {
00087   struct udp_hdr *udphdr;
00088   struct udp_pcb *pcb, *prev;
00089   struct udp_pcb *uncon_pcb;
00090   struct ip_hdr *iphdr;
00091   u16_t src, dest;
00092   u8_t local_match;
00093 
00094   PERF_START;
00095 
00096   UDP_STATS_INC(udp.recv);
00097 
00098   iphdr = static_cast<struct ip_hdr *>(p->payload);
00099 
00100   /* Check minimum length (IP header + UDP header)
00101    * and move payload pointer to UDP header */
00102   if (p->tot_len < (IPH_HL(iphdr) * 4 + UDP_HLEN) || pbuf_header(p, -(s16_t)(IPH_HL(iphdr) * 4))) {
00103     /* drop short packets */
00104     LWIP_DEBUGF(UDP_DEBUG,
00105                 ("udp_input: short UDP datagram (%"U16_F" bytes) discarded\n", p->tot_len));
00106     UDP_STATS_INC(udp.lenerr);
00107     UDP_STATS_INC(udp.drop);
00108     snmp_inc_udpinerrors();
00109     pbuf_free(p);
00110     goto end;
00111   }
00112 
00113   udphdr = (struct udp_hdr *)p->payload;
00114 
00115   LWIP_DEBUGF(UDP_DEBUG, ("udp_input: received datagram of length %"U16_F"\n", p->tot_len));
00116 
00117   /* convert src and dest ports to host byte order */
00118   src = ntohs(udphdr->src);
00119   dest = ntohs(udphdr->dest);
00120 
00121   udp_debug_print(udphdr);
00122 
00123   /* print the UDP source and destination */
00124   LWIP_DEBUGF(UDP_DEBUG,
00125               ("udp (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") <-- "
00126                "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
00127                ip4_addr1(&iphdr->dest), ip4_addr2(&iphdr->dest),
00128                ip4_addr3(&iphdr->dest), ip4_addr4(&iphdr->dest), ntohs(udphdr->dest),
00129                ip4_addr1(&iphdr->src), ip4_addr2(&iphdr->src),
00130                ip4_addr3(&iphdr->src), ip4_addr4(&iphdr->src), ntohs(udphdr->src)));
00131 
00132 #if LWIP_DHCP
00133   pcb = NULL;
00134   /* when LWIP_DHCP is active, packets to DHCP_CLIENT_PORT may only be processed by
00135      the dhcp module, no other UDP pcb may use the local UDP port DHCP_CLIENT_PORT */
00136   if (dest == DHCP_CLIENT_PORT) {
00137     /* all packets for DHCP_CLIENT_PORT not coming from DHCP_SERVER_PORT are dropped! */
00138     if (src == DHCP_SERVER_PORT) {
00139       if ((inp->dhcp != NULL) && (inp->dhcp->pcb != NULL)) {
00140         /* accept the packe if 
00141            (- broadcast or directed to us) -> DHCP is link-layer-addressed, local ip is always ANY!
00142            - inp->dhcp->pcb->remote == ANY or iphdr->src */
00143         if ((ip_addr_isany(&inp->dhcp->pcb->remote_ip) ||
00144            ip_addr_cmp(&(inp->dhcp->pcb->remote_ip), &(iphdr->src)))) {
00145           pcb = inp->dhcp->pcb;
00146         }
00147       }
00148     }
00149   } else
00150 #endif /* LWIP_DHCP */
00151   {
00152     prev = NULL;
00153     local_match = 0;
00154     uncon_pcb = NULL;
00155     /* Iterate through the UDP pcb list for a matching pcb.
00156      * 'Perfect match' pcbs (connected to the remote port & ip address) are
00157      * preferred. If no perfect match is found, the first unconnected pcb that
00158      * matches the local port and ip address gets the datagram. */
00159     for (pcb = udp_pcbs; pcb != NULL; pcb = pcb->next) {
00160       local_match = 0;
00161       /* print the PCB local and remote address */
00162       LWIP_DEBUGF(UDP_DEBUG,
00163                   ("pcb (%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F") --- "
00164                    "(%"U16_F".%"U16_F".%"U16_F".%"U16_F", %"U16_F")\n",
00165                    ip4_addr1(&pcb->local_ip), ip4_addr2(&pcb->local_ip),
00166                    ip4_addr3(&pcb->local_ip), ip4_addr4(&pcb->local_ip), pcb->local_port,
00167                    ip4_addr1(&pcb->remote_ip), ip4_addr2(&pcb->remote_ip),
00168                    ip4_addr3(&pcb->remote_ip), ip4_addr4(&pcb->remote_ip), pcb->remote_port));
00169 
00170       /* compare PCB local addr+port to UDP destination addr+port */
00171       if ((pcb->local_port == dest) &&
00172           (ip_addr_isany(&pcb->local_ip) ||
00173            ip_addr_cmp(&(pcb->local_ip), &(iphdr->dest)) || 
00174 #if LWIP_IGMP
00175            ip_addr_ismulticast(&(iphdr->dest)) ||
00176 #endif /* LWIP_IGMP */
00177            ip_addr_isbroadcast(&(iphdr->dest), inp))) {
00178         local_match = 1;
00179         if ((uncon_pcb == NULL) && 
00180             ((pcb->flags & UDP_FLAGS_CONNECTED) == 0)) {
00181           /* the first unconnected matching PCB */     
00182           uncon_pcb = pcb;
00183         }
00184       }
00185       /* compare PCB remote addr+port to UDP source addr+port */
00186       if ((local_match != 0) &&
00187           (pcb->remote_port == src) &&
00188           (ip_addr_isany(&pcb->remote_ip) ||
00189            ip_addr_cmp(&(pcb->remote_ip), &(iphdr->src)))) {
00190         /* the first fully matching PCB */
00191         if (prev != NULL) {
00192           /* move the pcb to the front of udp_pcbs so that is
00193              found faster next time */
00194           prev->next = pcb->next;
00195           pcb->next = udp_pcbs;
00196           udp_pcbs = pcb;
00197         } else {
00198           UDP_STATS_INC(udp.cachehit);
00199         }
00200         break;
00201       }
00202       prev = pcb;
00203     }
00204     /* no fully matching pcb found? then look for an unconnected pcb */
00205     if (pcb == NULL) {
00206       pcb = uncon_pcb;
00207     }
00208   }
00209 
00210   /* Check checksum if this is a match or if it was directed at us. */
00211   if (pcb != NULL || ip_addr_cmp(&inp->ip_addr, &iphdr->dest)) {
00212     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: calculating checksum\n"));
00213 #if LWIP_UDPLITE
00214     if (IPH_PROTO(iphdr) == IP_PROTO_UDPLITE) {
00215       /* Do the UDP Lite checksum */
00216 #if CHECKSUM_CHECK_UDP
00217       u16_t chklen = ntohs(udphdr->len);
00218       if (chklen < sizeof(struct udp_hdr)) {
00219         if (chklen == 0) {
00220           /* For UDP-Lite, checksum length of 0 means checksum
00221              over the complete packet (See RFC 3828 chap. 3.1) */
00222           chklen = p->tot_len;
00223         } else {
00224           /* At least the UDP-Lite header must be covered by the
00225              checksum! (Again, see RFC 3828 chap. 3.1) */
00226           UDP_STATS_INC(udp.chkerr);
00227           UDP_STATS_INC(udp.drop);
00228           snmp_inc_udpinerrors();
00229           pbuf_free(p);
00230           goto end;
00231         }
00232       }
00233       if (inet_chksum_pseudo_partial(p, (struct ip_addr *)&(iphdr->src),
00234                              (struct ip_addr *)&(iphdr->dest),
00235                              IP_PROTO_UDPLITE, p->tot_len, chklen) != 0) {
00236         LWIP_DEBUGF(UDP_DEBUG | 2,
00237                     ("udp_input: UDP Lite datagram discarded due to failing checksum\n"));
00238         UDP_STATS_INC(udp.chkerr);
00239         UDP_STATS_INC(udp.drop);
00240         snmp_inc_udpinerrors();
00241         pbuf_free(p);
00242         goto end;
00243       }
00244 #endif /* CHECKSUM_CHECK_UDP */
00245     } else
00246 #endif /* LWIP_UDPLITE */
00247     {
00248 #if CHECKSUM_CHECK_UDP
00249       if (udphdr->chksum != 0) {
00250         if (inet_chksum_pseudo(p, (struct ip_addr *)&(iphdr->src),
00251                                (struct ip_addr *)&(iphdr->dest),
00252                                IP_PROTO_UDP, p->tot_len) != 0) {
00253           LWIP_DEBUGF(UDP_DEBUG | 2,
00254                       ("udp_input: UDP datagram discarded due to failing checksum\n"));
00255           UDP_STATS_INC(udp.chkerr);
00256           UDP_STATS_INC(udp.drop);
00257           snmp_inc_udpinerrors();
00258           pbuf_free(p);
00259           goto end;
00260         }
00261       }
00262 #endif /* CHECKSUM_CHECK_UDP */
00263     }
00264     if(pbuf_header(p, -UDP_HLEN)) {
00265       /* Can we cope with this failing? Just assert for now */
00266       LWIP_ASSERT("pbuf_header failed\n", 0);
00267       UDP_STATS_INC(udp.drop);
00268       snmp_inc_udpinerrors();
00269       pbuf_free(p);
00270       goto end;
00271     }
00272     if (pcb != NULL) {
00273       snmp_inc_udpindatagrams();
00274       /* callback */
00275       if (pcb->recv != NULL) {
00276         /* now the recv function is responsible for freeing p */
00277         struct ip_addr iphdrsrc;                                                  // __packed hack
00278         iphdrsrc.addr = iphdr->src.addr;
00279         pcb->recv(pcb->recv_arg, pcb, p, &iphdrsrc, src);
00280       } else {
00281         /* no recv function registered? then we have to free the pbuf! */
00282         pbuf_free(p);
00283         goto end;
00284       }
00285     } else {
00286       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE, ("udp_input: not for us.\n"));
00287 
00288 #if LWIP_ICMP
00289       /* No match was found, send ICMP destination port unreachable unless
00290          destination address was broadcast/multicast. */
00291       if (!ip_addr_isbroadcast(&(iphdr->dest), inp) &&
00292           !ip_addr_ismulticast(&iphdr->dest)) {
00293         /* move payload pointer back to ip header */
00294         pbuf_header(p, (IPH_HL(iphdr) * 4) + UDP_HLEN);
00295         LWIP_ASSERT("p->payload == iphdr", (p->payload == iphdr));
00296         icmp_dest_unreach(p, ICMP_DUR_PORT);
00297       }
00298 #endif /* LWIP_ICMP */
00299       UDP_STATS_INC(udp.proterr);
00300       UDP_STATS_INC(udp.drop);
00301       snmp_inc_udpnoports();
00302       pbuf_free(p);
00303     }
00304   } else {
00305     pbuf_free(p);
00306   }
00307 end:
00308   PERF_STOP("udp_input");
00309 }
00310 
00311 /**
00312  * Send data using UDP.
00313  *
00314  * @param pcb UDP PCB used to send the data.
00315  * @param p chain of pbuf's to be sent.
00316  *
00317  * The datagram will be sent to the current remote_ip & remote_port
00318  * stored in pcb. If the pcb is not bound to a port, it will
00319  * automatically be bound to a random port.
00320  *
00321  * @return lwIP error code.
00322  * - ERR_OK. Successful. No error occured.
00323  * - ERR_MEM. Out of memory.
00324  * - ERR_RTE. Could not find route to destination address.
00325  * - More errors could be returned by lower protocol layers.
00326  *
00327  * @see udp_disconnect() udp_sendto()
00328  */
00329 err_t
00330 udp_send(struct udp_pcb *pcb, struct pbuf *p)
00331 {
00332   /* send to the packet using remote ip and port stored in the pcb */
00333   return udp_sendto(pcb, p, &pcb->remote_ip, pcb->remote_port);
00334 }
00335 
00336 /**
00337  * Send data to a specified address using UDP.
00338  *
00339  * @param pcb UDP PCB used to send the data.
00340  * @param p chain of pbuf's to be sent.
00341  * @param dst_ip Destination IP address.
00342  * @param dst_port Destination UDP port.
00343  *
00344  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
00345  *
00346  * If the PCB already has a remote address association, it will
00347  * be restored after the data is sent.
00348  * 
00349  * @return lwIP error code (@see udp_send for possible error codes)
00350  *
00351  * @see udp_disconnect() udp_send()
00352  */
00353 err_t
00354 udp_sendto(struct udp_pcb *pcb, struct pbuf *p,
00355   struct ip_addr *dst_ip, u16_t dst_port)
00356 {
00357   struct netif *netif;
00358 
00359   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, ("udp_send\n"));
00360 
00361   /* find the outgoing network interface for this packet */
00362 #if LWIP_IGMP
00363   netif = ip_route((ip_addr_ismulticast(dst_ip))?(&(pcb->multicast_ip)):(dst_ip));
00364 #else
00365   netif = ip_route(dst_ip);
00366 #endif /* LWIP_IGMP */
00367 
00368   /* no outgoing network interface could be found? */
00369   if (netif == NULL) {
00370     LWIP_DEBUGF(UDP_DEBUG | 1, ("udp_send: No route to 0x%"X32_F"\n", dst_ip->addr));
00371     UDP_STATS_INC(udp.rterr);
00372     return ERR_RTE;
00373   }
00374   return udp_sendto_if(pcb, p, dst_ip, dst_port, netif);
00375 }
00376 
00377 /**
00378  * Send data to a specified address using UDP.
00379  * The netif used for sending can be specified.
00380  *
00381  * This function exists mainly for DHCP, to be able to send UDP packets
00382  * on a netif that is still down.
00383  *
00384  * @param pcb UDP PCB used to send the data.
00385  * @param p chain of pbuf's to be sent.
00386  * @param dst_ip Destination IP address.
00387  * @param dst_port Destination UDP port.
00388  * @param netif the netif used for sending.
00389  *
00390  * dst_ip & dst_port are expected to be in the same byte order as in the pcb.
00391  *
00392  * @return lwIP error code (@see udp_send for possible error codes)
00393  *
00394  * @see udp_disconnect() udp_send()
00395  */
00396 err_t
00397 udp_sendto_if(struct udp_pcb *pcb, struct pbuf *p,
00398   struct ip_addr *dst_ip, u16_t dst_port, struct netif *netif)
00399 {
00400   struct udp_hdr *udphdr;
00401   struct ip_addr *src_ip;
00402   err_t err;
00403   struct pbuf *q; /* q will be sent down the stack */
00404 
00405   /* if the PCB is not yet bound to a port, bind it here */
00406   if (pcb->local_port == 0) {
00407     LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: not yet bound to a port, binding now\n"));
00408     err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
00409     if (err != ERR_OK) {
00410       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: forced port bind failed\n"));
00411       return err;
00412     }
00413   }
00414 
00415   /* not enough space to add an UDP header to first pbuf in given p chain? */
00416   if (pbuf_header(p, UDP_HLEN)) {
00417     /* allocate header in a separate new pbuf */
00418     q = pbuf_alloc(PBUF_IP, UDP_HLEN, PBUF_RAM);
00419     /* new header pbuf could not be allocated? */
00420     if (q == NULL) {
00421       LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 2, ("udp_send: could not allocate header\n"));
00422       return ERR_MEM;
00423     }
00424     /* chain header q in front of given pbuf p */
00425     pbuf_chain(q, p);
00426     /* first pbuf q points to header pbuf */
00427     LWIP_DEBUGF(UDP_DEBUG,
00428                 ("udp_send: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
00429   } else {
00430     /* adding space for header within p succeeded */
00431     /* first pbuf q equals given pbuf */
00432     q = p;
00433     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: added header in given pbuf %p\n", (void *)p));
00434   }
00435   LWIP_ASSERT("check that first pbuf can hold struct udp_hdr",
00436               (q->len >= sizeof(struct udp_hdr)));
00437   /* q now represents the packet to be sent */
00438   udphdr = static_cast<struct udp_hdr *>(q->payload); // XXX: static_cast
00439   udphdr->src = htons(pcb->local_port);
00440   udphdr->dest = htons(dst_port);
00441   /* in UDP, 0 checksum means 'no checksum' */
00442   udphdr->chksum = 0x0000; 
00443 
00444   /* PCB local address is IP_ANY_ADDR? */
00445   if (ip_addr_isany(&pcb->local_ip)) {
00446     /* use outgoing network interface IP address as source address */
00447     src_ip = &(netif->ip_addr);
00448   } else {
00449     /* check if UDP PCB local IP address is correct
00450      * this could be an old address if netif->ip_addr has changed */
00451     if (!ip_addr_cmp(&(pcb->local_ip), &(netif->ip_addr))) {
00452       /* local_ip doesn't match, drop the packet */
00453       if (q != p) {
00454         /* free the header pbuf */
00455         pbuf_free(q);
00456         q = NULL;
00457         /* p is still referenced by the caller, and will live on */
00458       }
00459       return ERR_VAL;
00460     }
00461     /* use UDP PCB local IP address as source address */
00462     src_ip = &(pcb->local_ip);
00463   }
00464 
00465   LWIP_DEBUGF(UDP_DEBUG, ("udp_send: sending datagram of length %"U16_F"\n", q->tot_len));
00466 
00467 #if LWIP_UDPLITE
00468   /* UDP Lite protocol? */
00469   if (pcb->flags & UDP_FLAGS_UDPLITE) {
00470     u16_t chklen, chklen_hdr;
00471     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE packet length %"U16_F"\n", q->tot_len));
00472     /* set UDP message length in UDP header */
00473     chklen_hdr = chklen = pcb->chksum_len_tx;
00474     if ((chklen < sizeof(struct udp_hdr)) || (chklen > q->tot_len)) {
00475       if (chklen != 0) {
00476         LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP LITE pcb->chksum_len is illegal: %"U16_F"\n", chklen));
00477       }
00478       /* For UDP-Lite, checksum length of 0 means checksum
00479          over the complete packet. (See RFC 3828 chap. 3.1)
00480          At least the UDP-Lite header must be covered by the
00481          checksum, therefore, if chksum_len has an illegal
00482          value, we generate the checksum over the complete
00483          packet to be safe. */
00484       chklen_hdr = 0;
00485       chklen = q->tot_len;
00486     }
00487     udphdr->len = htons(chklen_hdr);
00488     /* calculate checksum */
00489 #if CHECKSUM_GEN_UDP
00490     udphdr->chksum = inet_chksum_pseudo_partial(q, src_ip, dst_ip,
00491                                         IP_PROTO_UDPLITE, q->tot_len, chklen);
00492     /* chksum zero must become 0xffff, as zero means 'no checksum' */
00493     if (udphdr->chksum == 0x0000)
00494       udphdr->chksum = 0xffff;
00495 #endif /* CHECKSUM_CHECK_UDP */
00496     /* output to IP */
00497     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDPLITE,)\n"));
00498 #if LWIP_NETIF_HWADDRHINT
00499     netif->addr_hint = &(pcb->addr_hint);
00500 #endif /* LWIP_NETIF_HWADDRHINT*/
00501     err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDPLITE, netif);    
00502 #if LWIP_NETIF_HWADDRHINT
00503     netif->addr_hint = NULL;
00504 #endif /* LWIP_NETIF_HWADDRHINT*/
00505   } else
00506 #endif /* LWIP_UDPLITE */
00507   {      /* UDP */
00508     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP packet length %"U16_F"\n", q->tot_len));
00509     udphdr->len = htons(q->tot_len);
00510     /* calculate checksum */
00511 #if CHECKSUM_GEN_UDP
00512     if ((pcb->flags & UDP_FLAGS_NOCHKSUM) == 0) {
00513       udphdr->chksum = inet_chksum_pseudo(q, src_ip, dst_ip, IP_PROTO_UDP, q->tot_len);
00514       /* chksum zero must become 0xffff, as zero means 'no checksum' */
00515       if (udphdr->chksum == 0x0000) udphdr->chksum = 0xffff;
00516     }
00517 #endif /* CHECKSUM_CHECK_UDP */
00518     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: UDP checksum 0x%04"X16_F"\n", udphdr->chksum));
00519     LWIP_DEBUGF(UDP_DEBUG, ("udp_send: ip_output_if (,,,,IP_PROTO_UDP,)\n"));
00520     /* output to IP */
00521 #if LWIP_NETIF_HWADDRHINT
00522     netif->addr_hint = &(pcb->addr_hint);
00523 #endif /* LWIP_NETIF_HWADDRHINT*/
00524     err = ip_output_if(q, src_ip, dst_ip, pcb->ttl, pcb->tos, IP_PROTO_UDP, netif);    
00525 #if LWIP_NETIF_HWADDRHINT
00526     netif->addr_hint = NULL;
00527 #endif /* LWIP_NETIF_HWADDRHINT*/
00528   }
00529   /* TODO: must this be increased even if error occured? */
00530   snmp_inc_udpoutdatagrams();
00531 
00532   /* did we chain a separate header pbuf earlier? */
00533   if (q != p) {
00534     /* free the header pbuf */
00535     pbuf_free(q);
00536     q = NULL;
00537     /* p is still referenced by the caller, and will live on */
00538   }
00539 
00540   UDP_STATS_INC(udp.xmit);
00541   return err;
00542 }
00543 
00544 /**
00545  * Bind an UDP PCB.
00546  *
00547  * @param pcb UDP PCB to be bound with a local address ipaddr and port.
00548  * @param ipaddr local IP address to bind with. Use IP_ADDR_ANY to
00549  * bind to all local interfaces.
00550  * @param port local UDP port to bind with. Use 0 to automatically bind
00551  * to a random port between UDP_LOCAL_PORT_RANGE_START and
00552  * UDP_LOCAL_PORT_RANGE_END.
00553  *
00554  * ipaddr & port are expected to be in the same byte order as in the pcb.
00555  *
00556  * @return lwIP error code.
00557  * - ERR_OK. Successful. No error occured.
00558  * - ERR_USE. The specified ipaddr and port are already bound to by
00559  * another UDP PCB.
00560  *
00561  * @see udp_disconnect()
00562  */
00563 err_t
00564 udp_bind(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
00565 {
00566   struct udp_pcb *ipcb;
00567   u8_t rebind;
00568 
00569   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, ("udp_bind(ipaddr = "));
00570   ip_addr_debug_print(UDP_DEBUG, ipaddr);
00571   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | 3, (", port = %"U16_F")\n", port));
00572 
00573   rebind = 0;
00574   /* Check for double bind and rebind of the same pcb */
00575   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
00576     /* is this UDP PCB already on active list? */
00577     if (pcb == ipcb) {
00578       /* pcb may occur at most once in active list */
00579       LWIP_ASSERT("rebind == 0", rebind == 0);
00580       /* pcb already in list, just rebind */
00581       rebind = 1;
00582     }
00583 
00584     /* this code does not allow upper layer to share a UDP port for
00585        listening to broadcast or multicast traffic (See SO_REUSE_ADDR and
00586        SO_REUSE_PORT under *BSD). TODO: See where it fits instead, OR
00587        combine with implementation of UDP PCB flags. Leon Woestenberg. */
00588 #ifdef LWIP_UDP_TODO
00589     /* port matches that of PCB in list? */
00590     else
00591       if ((ipcb->local_port == port) &&
00592           /* IP address matches, or one is IP_ADDR_ANY? */
00593           (ip_addr_isany(&(ipcb->local_ip)) ||
00594            ip_addr_isany(ipaddr) ||
00595            ip_addr_cmp(&(ipcb->local_ip), ipaddr))) {
00596         /* other PCB already binds to this local IP and port */
00597         LWIP_DEBUGF(UDP_DEBUG,
00598                     ("udp_bind: local port %"U16_F" already bound by another pcb\n", port));
00599         return ERR_USE;
00600       }
00601 #endif
00602   }
00603 
00604   ip_addr_set(&pcb->local_ip, ipaddr);
00605 
00606   /* no port specified? */
00607   if (port == 0) {
00608 #ifndef UDP_LOCAL_PORT_RANGE_START
00609 #define UDP_LOCAL_PORT_RANGE_START 4096
00610 #define UDP_LOCAL_PORT_RANGE_END   0x7fff
00611 #endif
00612     port = UDP_LOCAL_PORT_RANGE_START;
00613     ipcb = udp_pcbs;
00614     while ((ipcb != NULL) && (port != UDP_LOCAL_PORT_RANGE_END)) {
00615       if (ipcb->local_port == port) {
00616         /* port is already used by another udp_pcb */
00617         port++;
00618         /* restart scanning all udp pcbs */
00619         ipcb = udp_pcbs;
00620       } else
00621         /* go on with next udp pcb */
00622         ipcb = ipcb->next;
00623     }
00624     if (ipcb != NULL) {
00625       /* no more ports available in local range */
00626       LWIP_DEBUGF(UDP_DEBUG, ("udp_bind: out of free UDP ports\n"));
00627       return ERR_USE;
00628     }
00629   }
00630   pcb->local_port = port;
00631   snmp_insert_udpidx_tree(pcb);
00632   /* pcb not active yet? */
00633   if (rebind == 0) {
00634     /* place the PCB on the active list if not already there */
00635     pcb->next = udp_pcbs;
00636     udp_pcbs = pcb;
00637   }
00638   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
00639               ("udp_bind: bound to %"U16_F".%"U16_F".%"U16_F".%"U16_F", port %"U16_F"\n",
00640                (u16_t)(ntohl(pcb->local_ip.addr) >> 24 & 0xff),
00641                (u16_t)(ntohl(pcb->local_ip.addr) >> 16 & 0xff),
00642                (u16_t)(ntohl(pcb->local_ip.addr) >> 8 & 0xff),
00643                (u16_t)(ntohl(pcb->local_ip.addr) & 0xff), pcb->local_port));
00644   return ERR_OK;
00645 }
00646 /**
00647  * Connect an UDP PCB.
00648  *
00649  * This will associate the UDP PCB with the remote address.
00650  *
00651  * @param pcb UDP PCB to be connected with remote address ipaddr and port.
00652  * @param ipaddr remote IP address to connect with.
00653  * @param port remote UDP port to connect with.
00654  *
00655  * @return lwIP error code
00656  *
00657  * ipaddr & port are expected to be in the same byte order as in the pcb.
00658  *
00659  * The udp pcb is bound to a random local port if not already bound.
00660  *
00661  * @see udp_disconnect()
00662  */
00663 err_t
00664 udp_connect(struct udp_pcb *pcb, struct ip_addr *ipaddr, u16_t port)
00665 {
00666   struct udp_pcb *ipcb;
00667 
00668   if (pcb->local_port == 0) {
00669     err_t err = udp_bind(pcb, &pcb->local_ip, pcb->local_port);
00670     if (err != ERR_OK)
00671       return err;
00672   }
00673 
00674   ip_addr_set(&pcb->remote_ip, ipaddr);
00675   pcb->remote_port = port;
00676   pcb->flags |= UDP_FLAGS_CONNECTED;
00677 /** TODO: this functionality belongs in upper layers */
00678 #ifdef LWIP_UDP_TODO
00679   /* Nail down local IP for netconn_addr()/getsockname() */
00680   if (ip_addr_isany(&pcb->local_ip) && !ip_addr_isany(&pcb->remote_ip)) {
00681     struct netif *netif;
00682 
00683     if ((netif = ip_route(&(pcb->remote_ip))) == NULL) {
00684       LWIP_DEBUGF(UDP_DEBUG, ("udp_connect: No route to 0x%lx\n", pcb->remote_ip.addr));
00685       UDP_STATS_INC(udp.rterr);
00686       return ERR_RTE;
00687     }
00688     /** TODO: this will bind the udp pcb locally, to the interface which
00689         is used to route output packets to the remote address. However, we
00690         might want to accept incoming packets on any interface! */
00691     pcb->local_ip = netif->ip_addr;
00692   } else if (ip_addr_isany(&pcb->remote_ip)) {
00693     pcb->local_ip.addr = 0;
00694   }
00695 #endif
00696   LWIP_DEBUGF(UDP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
00697               ("udp_connect: connected to %"U16_F".%"U16_F".%"U16_F".%"U16_F",port %"U16_F"\n",
00698                (u16_t)(ntohl(pcb->remote_ip.addr) >> 24 & 0xff),
00699                (u16_t)(ntohl(pcb->remote_ip.addr) >> 16 & 0xff),
00700                (u16_t)(ntohl(pcb->remote_ip.addr) >> 8 & 0xff),
00701                (u16_t)(ntohl(pcb->remote_ip.addr) & 0xff), pcb->remote_port));
00702 
00703   /* Insert UDP PCB into the list of active UDP PCBs. */
00704   for (ipcb = udp_pcbs; ipcb != NULL; ipcb = ipcb->next) {
00705     if (pcb == ipcb) {
00706       /* already on the list, just return */
00707       return ERR_OK;
00708     }
00709   }
00710   /* PCB not yet on the list, add PCB now */
00711   pcb->next = udp_pcbs;
00712   udp_pcbs = pcb;
00713   return ERR_OK;
00714 }
00715 
00716 /**
00717  * Disconnect a UDP PCB
00718  *
00719  * @param pcb the udp pcb to disconnect.
00720  */
00721 void
00722 udp_disconnect(struct udp_pcb *pcb)
00723 {
00724   /* reset remote address association */
00725   ip_addr_set(&pcb->remote_ip, IP_ADDR_ANY);
00726   pcb->remote_port = 0;
00727   /* mark PCB as unconnected */
00728   pcb->flags &= ~UDP_FLAGS_CONNECTED;
00729 }
00730 
00731 /**
00732  * Set a receive callback for a UDP PCB
00733  *
00734  * This callback will be called when receiving a datagram for the pcb.
00735  *
00736  * @param pcb the pcb for wich to set the recv callback
00737  * @param recv function pointer of the callback function
00738  * @param recv_arg additional argument to pass to the callback function
00739  */
00740 void
00741 udp_recv(struct udp_pcb *pcb,
00742          void (* recv)(void *arg, struct udp_pcb *upcb, struct pbuf *p,
00743                        struct ip_addr *addr, u16_t port),
00744          void *recv_arg)
00745 {
00746   /* remember recv() callback and user data */
00747   pcb->recv = recv;
00748   pcb->recv_arg = recv_arg;
00749 }
00750 
00751 /**
00752  * Remove an UDP PCB.
00753  *
00754  * @param pcb UDP PCB to be removed. The PCB is removed from the list of
00755  * UDP PCB's and the data structure is freed from memory.
00756  *
00757  * @see udp_new()
00758  */
00759 void
00760 udp_remove(struct udp_pcb *pcb)
00761 {
00762   struct udp_pcb *pcb2;
00763 
00764   snmp_delete_udpidx_tree(pcb);
00765   /* pcb to be removed is first in list? */
00766   if (udp_pcbs == pcb) {
00767     /* make list start at 2nd pcb */
00768     udp_pcbs = udp_pcbs->next;
00769     /* pcb not 1st in list */
00770   } else
00771     for (pcb2 = udp_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
00772       /* find pcb in udp_pcbs list */
00773       if (pcb2->next != NULL && pcb2->next == pcb) {
00774         /* remove pcb from list */
00775         pcb2->next = pcb->next;
00776       }
00777     }
00778   memp_free(MEMP_UDP_PCB, pcb);
00779 }
00780 
00781 /**
00782  * Create a UDP PCB.
00783  *
00784  * @return The UDP PCB which was created. NULL if the PCB data structure
00785  * could not be allocated.
00786  *
00787  * @see udp_remove()
00788  */
00789 struct udp_pcb *
00790 udp_new(void)
00791 {
00792   struct udp_pcb *pcb;
00793   pcb = static_cast<struct udp_pcb *>(memp_malloc(MEMP_UDP_PCB)); // XXX: static_cast
00794   /* could allocate UDP PCB? */
00795   if (pcb != NULL) {
00796     /* UDP Lite: by initializing to all zeroes, chksum_len is set to 0
00797      * which means checksum is generated over the whole datagram per default
00798      * (recommended as default by RFC 3828). */
00799     /* initialize PCB to all zeroes */
00800     memset(pcb, 0, sizeof(struct udp_pcb));
00801     pcb->ttl = UDP_TTL;
00802   }
00803   return pcb;
00804 }
00805 
00806 #if UDP_DEBUG
00807 /**
00808  * Print UDP header information for debug purposes.
00809  *
00810  * @param udphdr pointer to the udp header in memory.
00811  */
00812 void
00813 udp_debug_print(struct udp_hdr *udphdr)
00814 {
00815   LWIP_DEBUGF(UDP_DEBUG, ("UDP header:\n"));
00816   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
00817   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     %5"U16_F"     | (src port, dest port)\n",
00818                           ntohs(udphdr->src), ntohs(udphdr->dest)));
00819   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
00820   LWIP_DEBUGF(UDP_DEBUG, ("|     %5"U16_F"     |     0x%04"X16_F"    | (len, chksum)\n",
00821                           ntohs(udphdr->len), ntohs(udphdr->chksum)));
00822   LWIP_DEBUGF(UDP_DEBUG, ("+-------------------------------+\n"));
00823 }
00824 #endif /* UDP_DEBUG */
00825 
00826 #endif /* LWIP_UDP */