Bonjour/Zerconf library

Dependencies:   mbed

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