SAMV71 Xplained Ultra Software Package 1.4

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