tcpsock.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2001-2005 by egnite Software GmbH. All rights reserved.
00003  *
00004  * Redistribution and use in source and binary forms, with or without
00005  * modification, are permitted provided that the following conditions
00006  * are met:
00007  *
00008  * 1. Redistributions of source code must retain the above copyright
00009  *    notice, this list of conditions and the following disclaimer.
00010  * 2. Redistributions in binary form must reproduce the above copyright
00011  *    notice, this list of conditions and the following disclaimer in the
00012  *    documentation and/or other materials provided with the distribution.
00013  * 3. Neither the name of the copyright holders nor the names of
00014  *    contributors may be used to endorse or promote products derived
00015  *    from this software without specific prior written permission.
00016  *
00017  * THIS SOFTWARE IS PROVIDED BY EGNITE SOFTWARE GMBH AND CONTRIBUTORS
00018  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
00019  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
00020  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL EGNITE
00021  * SOFTWARE GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
00022  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
00023  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
00024  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
00025  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
00026  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
00027  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00028  * SUCH DAMAGE.
00029  *
00030  * For additional information see http://www.ethernut.de/
00031  *
00032  * -
00033  * Portions Copyright (C) 2000 David J. Hudson <dave@humbug.demon.co.uk>
00034  *
00035  * This file is distributed in the hope that it will be useful, but WITHOUT
00036  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00037  * FITNESS FOR A PARTICULAR PURPOSE.
00038  *
00039  * You can redistribute this file and/or modify it under the terms of the GNU
00040  * General Public License (GPL) as published by the Free Software Foundation;
00041  * either version 2 of the License, or (at your discretion) any later version.
00042  * See the accompanying file "copying-gpl.txt" for more details.
00043  *
00044  * As a special exception to the GPL, permission is granted for additional
00045  * uses of the text contained in this file.  See the accompanying file
00046  * "copying-liquorice.txt" for details.
00047  * -
00048  * Portions Copyright (c) 1983, 1993 by
00049  *  The Regents of the University of California.  All rights reserved.
00050  *
00051  * Redistribution and use in source and binary forms, with or without
00052  * modification, are permitted provided that the following conditions
00053  * are met:
00054  * 1. Redistributions of source code must retain the above copyright
00055  *    notice, this list of conditions and the following disclaimer.
00056  * 2. Redistributions in binary form must reproduce the above copyright
00057  *    notice, this list of conditions and the following disclaimer in the
00058  *    documentation and/or other materials provided with the distribution.
00059  * 3. Neither the name of the University nor the names of its contributors
00060  *    may be used to endorse or promote products derived from this software
00061  *    without specific prior written permission.
00062  *
00063  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
00064  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00065  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00066  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
00067  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00068  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
00069  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00070  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00071  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
00072  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00073  * SUCH DAMAGE.
00074  * -
00075  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
00076  *
00077  * Permission to use, copy, modify, and distribute this software for any
00078  * purpose with or without fee is hereby granted, provided that the above
00079  * copyright notice and this permission notice appear in all copies, and that
00080  * the name of Digital Equipment Corporation not be used in advertising or
00081  * publicity pertaining to distribution of the document or software without
00082  * specific, written prior permission.
00083  * 
00084  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
00085  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
00086  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
00087  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
00088  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
00089  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
00090  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
00091  * SOFTWARE.
00092  */
00093 
00094 /*
00095  * $Log: tcpsock.c,v $
00096  * Revision 1.24  2009/02/13 14:52:05  haraldkipp
00097  * Include memdebug.h for heap management debugging support.
00098  *
00099  * Revision 1.23  2009/02/06 15:40:29  haraldkipp
00100  * Using newly available strdup() and calloc().
00101  * Replaced NutHeap routines by standard malloc/free.
00102  * Replaced pointer value 0 by NULL.
00103  *
00104  * Revision 1.22  2008/08/20 06:57:00  haraldkipp
00105  * Implemented IP demultiplexer.
00106  *
00107  * Revision 1.21  2008/08/11 07:00:32  haraldkipp
00108  * BSD types replaced by stdint types (feature request #1282721).
00109  *
00110  * Revision 1.20  2008/04/18 13:32:00  haraldkipp
00111  * Changed size parameter from u_short to int, which is easier to handle
00112  * for 32-bit targets. You need to recompile your ARM code. No impact on
00113  * AVR expected
00114  * I changed u_int to int at some places to avoid some warnings during
00115  * compilation of Nut/Net.
00116  * libs.
00117  *
00118  * Revision 1.19  2006/10/08 16:48:22  haraldkipp
00119  * Documentation fixed
00120  *
00121  * Revision 1.18  2006/03/21 21:22:20  drsung
00122  * Enhancement made to TCP state machine. Now TCP options
00123  * are read from peer and at least the maximum segment size is stored.
00124  *
00125  * Revision 1.17  2005/10/24 11:00:16  haraldkipp
00126  * Integer division hack for ARM without CRT removed again.
00127  *
00128  * Revision 1.16  2005/08/02 17:47:03  haraldkipp
00129  * Major API documentation update.
00130  *
00131  * Revision 1.15  2005/04/30 16:42:42  chaac
00132  * Fixed bug in handling of NUTDEBUG. Added include for cfg/os.h. If NUTDEBUG
00133  * is defined in NutConf, it will make effect where it is used.
00134  *
00135  * Revision 1.14  2005/04/08 14:40:36  freckle
00136  * added <sys/types.h> (__APPLE__) and <netinet/in.h> (__linux__) for htons
00137  *
00138  * Revision 1.13  2005/04/05 17:58:02  haraldkipp
00139  * Avoid integer division on ARM platform as long as we run without crtlib.
00140  *
00141  * Revision 1.12  2005/02/04 17:16:45  haraldkipp
00142  * Stop searching when listening socket found
00143  *
00144  * Revision 1.11  2005/01/03 08:44:15  haraldkipp
00145  * Simplyfied NutTcpSend().
00146  *
00147  * Revision 1.10  2004/10/14 16:43:07  drsung
00148  * Fixed compiler warning "comparison between signed and unsigned"
00149  *
00150  * Revision 1.9  2004/07/30 19:54:46  drsung
00151  * Some code of TCP stack redesigned. Round trip time calculation is now
00152  * supported. Fixed several bugs in TCP state machine. Now TCP connections
00153  * should be more reliable under heavy traffic or poor physical connections.
00154  *
00155  * Revision 1.8  2004/03/16 16:48:45  haraldkipp
00156  * Added Jan Dubiec's H8/300 port.
00157  *
00158  * Revision 1.7  2004/01/28 12:11:57  drsung
00159  * Bugfix for ICCAVR ... again
00160  *
00161  * Revision 1.6  2004/01/28 07:11:38  drsung
00162  * Bugfix for ICCAVR
00163  *
00164  * Revision 1.5  2004/01/14 19:34:08  drsung
00165  * New TCP output buffer handling
00166  *
00167  * Revision 1.4  2003/11/04 17:58:18  haraldkipp
00168  * Removed volatile attibute from socket list
00169  *
00170  * Revision 1.3  2003/08/14 15:08:36  haraldkipp
00171  * Bugfix, TCP may reuse socket ports because of wrong byte order during compare.
00172  *
00173  * Revision 1.2  2003/07/13 19:23:59  haraldkipp
00174  * TCP transfer speed increased by changing the character receive buffer
00175  * in TCPSOCKET to a NETBUF queue.
00176  *
00177  * Revision 1.1.1.1  2003/05/09 14:41:44  haraldkipp
00178  * Initial using 3.2.1
00179  *
00180  * Revision 1.18  2003/02/04 18:14:57  harald
00181  * Version 3 released
00182  *
00183  * Revision 1.17  2002/09/15 17:07:05  harald
00184  * Allow application to read buffered data during close wait
00185  *
00186  * Revision 1.16  2002/09/03 17:43:15  harald
00187  * Configurable receive buffer size
00188  *
00189  * Revision 1.15  2002/08/16 17:54:57  harald
00190  * Count out of sequence drops
00191  *
00192  * Revision 1.14  2002/08/11 12:26:21  harald
00193  * ICC mods
00194  *
00195  * Revision 1.13  2002/06/26 17:29:36  harald
00196  * First pre-release with 2.4 stack
00197  *
00198  */
00199 
00200 #include <cfg/os.h>
00201 #include <sys/types.h>
00202 #include <string.h>
00203 #include <stdlib.h>
00204 
00205 #include <sys/atom.h>
00206 #include <sys/heap.h>
00207 #include <sys/thread.h>
00208 #include <sys/event.h>
00209 #include <sys/timer.h>
00210 
00211 #include <net/errno.h>
00212 #include <net/route.h>
00213 #include <netinet/in.h>
00214 #include <netinet/ip.h>
00215 #include <netinet/icmp.h>
00216 #include <netinet/ip_icmp.h>
00217 #include <netinet/ipcsum.h>
00218 #include <sys/socket.h>
00219 #include <netinet/tcp.h>
00220 #include <stdio.h>
00221 #include <io.h>
00222 #include <memdebug.h>
00223 
00224 #ifdef NUTDEBUG
00225 #include <net/netdebug.h>
00226 #endif
00227 
00228 #define TICK_RATE   1
00229 
00234 
00235 TCPSOCKET *tcpSocketList = 0;   
00237 static volatile uint16_t last_local_port = 4096; /* Unassigned local port. */
00238 
00239 static uint_fast8_t registered;
00240 
00241 void NutTcpDiscardBuffers(TCPSOCKET * sock)
00242 {
00243     NETBUF *nb;
00244     while ((nb = sock->so_rx_buf) != 0) {
00245         sock->so_rx_buf = nb->nb_next;
00246         NutNetBufFree(nb);
00247     }
00248     while ((nb = sock->so_tx_nbq) != 0) {
00249         sock->so_tx_nbq = nb->nb_next;
00250         NutNetBufFree(nb);
00251     }
00252     while ((nb = sock->so_rx_nbq) != 0) {
00253         sock->so_rx_nbq = nb->nb_next;
00254         NutNetBufFree(nb);
00255     }
00256 }
00257 
00258 
00270 void NutTcpDestroySocket(TCPSOCKET * sock)
00271 {
00272     TCPSOCKET *sp;
00273     TCPSOCKET *volatile *spp;
00274     
00275     //@@@printf ("[%04X] Calling destroy.\n", (u_short) sock);
00276 
00277     /*
00278      * Remove socket from the list.
00279      */
00280     sp = tcpSocketList;
00281     spp = &tcpSocketList;
00282     while (sp) {
00283         if (sp == sock) {
00284             *spp = sp->so_next;
00285             break;
00286         }
00287         spp = &sp->so_next;
00288         sp = sp->so_next;
00289     }
00290 
00291     /*
00292      * Free all memory occupied by the socket.
00293      */
00294     if (sp) {
00295         NutTcpDiscardBuffers(sock);
00296         if (sock->so_devocnt)
00297         {
00298             free(sock->so_devobuf);
00299             sock->so_devocnt = 0;
00300         }
00301         memset(sock, 0, sizeof(TCPSOCKET));
00302         free(sock);
00303     }
00304 }
00305 
00320 TCPSOCKET *NutTcpFindSocket(uint16_t lport, uint16_t rport, uint32_t raddr)
00321 {
00322     TCPSOCKET *sp;
00323     TCPSOCKET *sock = 0;
00324 
00325     /*
00326      * Try to find an exact match for the remote
00327      * address and port first.
00328      */
00329     for (sp = tcpSocketList; sp; sp = sp->so_next) {
00330         if (sp->so_local_port == lport) {
00331             if (sp->so_remote_addr == raddr && sp->so_remote_port == rport && sp->so_state != TCPS_CLOSED) {
00332                 sock = sp;
00333                 break;
00334             }
00335         }
00336     }
00337 
00338     /*
00339      * If no exact match exists, try a listening socket.
00340      * This part had been totally wrong, because it
00341      * didn't check the local port number and accepted
00342      * incoming requests on any port. Thanks to
00343      * Alejandro Lopez, who pointed this out.
00344      */
00345     if (sock == 0) {
00346         for (sp = tcpSocketList; sp; sp = sp->so_next) {
00347             if (sp->so_state == TCPS_LISTEN && sp->so_local_port == lport) {
00348                 sock = sp;
00349                 break;
00350             }
00351         }
00352     }
00353 
00354     return sock;
00355 }
00356 
00357 
00372 TCPSOCKET *NutTcpCreateSocket(void)
00373 {
00374     TCPSOCKET *sock = 0;
00375 
00376     if (!registered) {
00377         if (NutRegisterIpHandler(IPPROTO_TCP, NutTcpInput) || NutTcpInitStateMachine()) {
00378             return NULL;
00379         }
00380         registered = 1;
00381     }
00382     if ((sock = calloc(1, sizeof(TCPSOCKET))) != 0) {
00383         sock->so_state = TCPS_CLOSED;
00384 
00385         /*
00386             * Initialize the virtual device interface.
00387             */
00388         sock->so_devtype = IFTYP_TCPSOCK;
00389         sock->so_devread = NutTcpDeviceRead;
00390         sock->so_devwrite = NutTcpDeviceWrite;
00391 #ifdef __HARVARD_ARCH__
00392         sock->so_devwrite_P = NutTcpDeviceWrite_P;
00393 #endif
00394         sock->so_devioctl = NutTcpDeviceIOCtl;
00395 
00396         sock->so_tx_isn = NutGetTickCount();  /* Generate the ISN from the nut_ticks counter */
00397         sock->so_tx_una = sock->so_tx_isn;
00398         sock->so_tx_nxt = sock->so_tx_isn;
00399         sock->so_rx_bsz = sock->so_rx_win = TCP_WINSIZE;
00400 
00401         sock->so_mss = TCP_MSS;
00402         sock->so_rtto = 1000; /* Initial retransmission time out */
00403 
00404         sock->so_next = tcpSocketList;
00405 
00406         sock->so_devobsz = TCP_MSS; /* Default output buffer size is TCP_MSS bytes */
00407 
00408         tcpSocketList = sock;
00409     }
00410     return sock;
00411 }
00412 
00432 int NutTcpSetSockOpt(TCPSOCKET * sock, int optname, CONST void *optval, int optlen)
00433 {
00434     int rc = -1;
00435 
00436     if (sock == 0)
00437         return -1;
00438     switch (optname) {
00439 
00440     case TCP_MAXSEG:
00441         if (optval == 0 || optlen != sizeof(uint16_t))
00442             sock->so_last_error = EINVAL;
00443         else if (sock->so_state != TCPS_CLOSED) 
00444             sock->so_last_error = EISCONN;
00445         else {
00446             sock->so_mss = *((uint16_t *) optval);
00447             rc = 0;
00448         }
00449         break;
00450 
00451     case SO_RCVBUF:
00452         if (optval == 0 || optlen != sizeof(uint16_t))
00453             sock->so_last_error = EINVAL;
00454         else {
00455             sock->so_rx_bsz = *((uint16_t *) optval);
00456             sock->so_rx_win = sock->so_rx_bsz;
00457             rc = 0;
00458         }
00459         break;
00460 
00461     case SO_SNDTIMEO:
00462         if (optval == 0 || optlen != sizeof(uint32_t))
00463             sock->so_last_error = EINVAL;
00464         else {
00465             sock->so_write_to = *((uint32_t *) optval);
00466             rc = 0;
00467         }
00468         break;
00469 
00470     case SO_RCVTIMEO:
00471         if (optval == 0 || optlen != sizeof(uint32_t))
00472             sock->so_last_error = EINVAL;
00473         else {
00474             sock->so_read_to = *((uint32_t *) optval);
00475             rc = 0;
00476         }
00477         break;
00478 
00479     case SO_SNDBUF:
00480         if (optval == 0 || optlen != sizeof(uint16_t))
00481             sock->so_last_error = EINVAL;
00482         else {
00483             NutTcpDeviceWrite(sock, 0, 0);
00484             sock->so_devobsz = *((uint16_t *) optval);
00485             rc = 0;
00486         }
00487         break;
00488 
00489     default:
00490         sock->so_last_error = ENOPROTOOPT;
00491         break;
00492     }
00493     return rc;
00494 }
00495 
00515 int NutTcpGetSockOpt(TCPSOCKET * sock, int optname, void *optval, int optlen)
00516 {
00517     int rc = -1;
00518 
00519     if (sock == 0)
00520         return -1;
00521     switch (optname) {
00522 
00523     case TCP_MAXSEG:
00524         if (optval == 0 || optlen != sizeof(uint16_t))
00525             sock->so_last_error = EINVAL;
00526         else {
00527             *((uint16_t *) optval) = sock->so_mss;
00528             rc = 0;
00529         }
00530         break;
00531 
00532     case SO_RCVBUF:
00533         if (optval == 0 || optlen != sizeof(uint16_t))
00534             sock->so_last_error = EINVAL;
00535         else {
00536             *((uint16_t *) optval) = sock->so_rx_bsz;
00537             rc = 0;
00538         }
00539         break;
00540 
00541     case SO_SNDTIMEO:
00542         if (optval == 0 || optlen != sizeof(uint32_t))
00543             sock->so_last_error = EINVAL;
00544         else {
00545             *((uint32_t *) optval) = sock->so_write_to;
00546             rc = 0;
00547         }
00548         break;
00549 
00550     case SO_RCVTIMEO:
00551         if (optval == 0 || optlen != sizeof(uint32_t))
00552             sock->so_last_error = EINVAL;
00553         else {
00554             *((uint32_t *) optval) = sock->so_read_to;
00555             rc = 0;
00556         }
00557         break;
00558 
00559     case SO_SNDBUF:
00560         if (optval == 0 || optlen != sizeof(uint16_t))
00561             sock->so_last_error = EINVAL;
00562         else {
00563             *((uint16_t *) optval) = sock->so_devobsz;
00564             rc = 0;
00565         }
00566         break;
00567     default:
00568         sock->so_last_error = ENOPROTOOPT;
00569         break;
00570     }
00571     return rc;
00572 }
00573 
00592 int NutTcpConnect(TCPSOCKET * sock, uint32_t addr, uint16_t port)
00593 {
00594     TCPSOCKET *sp;
00595     NUTDEVICE *dev;
00596 
00597     if (sock == 0)
00598         return -1;
00599     /*
00600      * Despite RFC793 we do not allow a passive
00601      * open to become active.
00602      */
00603     if (sock->so_state == TCPS_LISTEN) {
00604         sock->so_last_error = EOPNOTSUPP;
00605         return -1;
00606     } else if (sock->so_state != TCPS_CLOSED) {
00607         sock->so_last_error = EISCONN;
00608         return -1;
00609     }
00610 
00611     /*
00612      * Find an unused local port.
00613      */
00614     do {
00615         if (++last_local_port == 0)
00616             last_local_port = 4096;
00617 
00618         sp = tcpSocketList;
00619         while (sp) {
00620             /* Thanks to Ralph Mason for fixing the byte order bug. */
00621             if (sp->so_local_port == htons(last_local_port))
00622                 break;
00623             sp = sp->so_next;
00624         }
00625     } while (sp);
00626 
00627     /*
00628      * OK - we've got a new port. Now fill
00629      * remaining parts of the socket structure.
00630      */
00631     sock->so_local_port = htons(last_local_port);
00632     sock->so_remote_port = htons(port);
00633     sock->so_remote_addr = addr;
00634 
00635     /*
00636      * Get local address for this destination.
00637      */
00638     if ((dev = NutIpRouteQuery(addr, 0)) != 0) {
00639         IFNET *nif = dev->dev_icb;
00640         sock->so_local_addr = nif->if_local_ip;
00641     } else {
00642         sock->so_last_error = EHOSTUNREACH;
00643         return -1;
00644     }
00645 
00646     /*
00647      * Trigger active open event for the state machine.
00648      * This will suspend the thread until synchronized.
00649      */
00650     return NutTcpStateActiveOpenEvent(sock);
00651 }
00652 
00668 int NutTcpAccept(TCPSOCKET * sock, uint16_t port)
00669 {
00670     sock->so_local_port = htons(port);
00671 
00672     return NutTcpStatePassiveOpenEvent(sock);
00673 }
00674 
00691 int NutTcpSend(TCPSOCKET * sock, CONST void *data, int len)
00692 {
00693     uint16_t unacked;
00694 
00695     /*
00696      * Check parameters.
00697      */
00698     NutThreadYield();
00699     
00700     if (sock == 0)
00701         return -1;
00702     if (data == 0 || len == 0)
00703         return 0;
00704 
00705     /*
00706      * Limit the transmission size to our maximum segment size.
00707      */
00708     if (len > sock->so_mss)
00709         len = sock->so_mss;
00710 
00711     for (;;) {
00712         /*
00713          * We can only send on an established connection.
00714          */
00715         if (sock->so_state != TCPS_ESTABLISHED) {
00716             sock->so_last_error = ENOTCONN;
00717             return -1;
00718         }
00719 
00720         /*
00721          * Limit the size of unacknowledged data to four full segments.
00722          * Also wait for peer's window open wide enough to take all our 
00723          * data. This also avoids silly window syndrome on our side.
00724          */
00725         unacked = sock->so_tx_nxt - sock->so_tx_una;
00726         if ((unacked >> 2) < sock->so_mss && len <= sock->so_tx_win - unacked) {
00727             break;
00728         }
00729         if (NutEventWait(&sock->so_tx_tq, sock->so_write_to)) {
00730             return 0;
00731         }
00732     }
00733     /*
00734      * The segment will be automatically retransmitted if not 
00735      * acknowledged in time. If this returns an error, it's a 
00736      * fatal one.
00737      */
00738     sock->so_tx_flags |= SO_ACK;
00739     if (NutTcpOutput(sock, data, len))
00740         return -1;
00741     return len;
00742 }
00743 
00761 int NutTcpReceive(TCPSOCKET * sock, void *data, int size)
00762 {
00763     int i;
00764 
00765     NutThreadYield();
00766     /*
00767      * Check parameters.
00768      */
00769     if (sock == 0)
00770         return -1;
00771     if (sock->so_state != TCPS_ESTABLISHED && sock->so_state != TCPS_CLOSE_WAIT) {
00772         sock->so_last_error = ENOTCONN;
00773         return -1;
00774     }
00775     if (data == 0 || size == 0)
00776         return 0;
00777 
00778     /*
00779      * Wait until any data arrived, a timeout occurs
00780      * or the connection terminates.
00781      */
00782     while (sock->so_rx_cnt - sock->so_rd_cnt == 0) {
00783         if (sock->so_state != TCPS_ESTABLISHED) {
00784             sock->so_last_error = ENOTCONN;
00785             return -1;
00786         }
00787         if (NutEventWait(&sock->so_rx_tq, sock->so_read_to))
00788             return 0;
00789     }
00790 
00791     if (size > sock->so_rx_cnt - sock->so_rd_cnt)
00792         size = sock->so_rx_cnt - sock->so_rd_cnt;
00793     if (size) {
00794         NETBUF *nb;
00795         uint16_t rd_cnt;         /* Bytes read from NETBUF. */
00796         uint16_t nb_cnt;         /* Bytes left in NETBUF. */
00797         uint16_t ab_cnt;         /* Total bytes in app buffer. */
00798         uint16_t mv_cnt;         /* Bytes to move to app buffer. */
00799 
00800         rd_cnt = sock->so_rd_cnt;
00801 
00802         ab_cnt = 0;
00803         while (ab_cnt < size) {
00804             nb = sock->so_rx_buf;
00805             nb_cnt = nb->nb_ap.sz - rd_cnt;
00806             mv_cnt = size - ab_cnt;
00807             if (mv_cnt > nb_cnt)
00808                 mv_cnt = nb_cnt;
00809             memcpy((char *) data + ab_cnt, (char *) (nb->nb_ap.vp) + rd_cnt, mv_cnt);
00810             ab_cnt += mv_cnt;
00811             rd_cnt += mv_cnt;
00812             if (mv_cnt >= nb_cnt) {
00813                 sock->so_rx_buf = nb->nb_next;
00814                 sock->so_rx_cnt -= rd_cnt;
00815                 NutNetBufFree(nb);
00816                 nb = sock->so_rx_buf;
00817                 rd_cnt = 0;
00818             }
00819         }
00820         sock->so_rd_cnt = rd_cnt;
00821 
00822         /*
00823          * Update our receive window.
00824          */
00825         if (sock->so_state == TCPS_ESTABLISHED) {
00826             i = sock->so_rx_win;
00827             if ((i += size) > sock->so_rx_bsz)
00828                 i = sock->so_rx_bsz;
00829 
00830             if (sock->so_rx_win <= sock->so_mss && i > sock->so_mss) {
00831                 sock->so_rx_win = i;
00832                 NutTcpStateWindowEvent(sock);
00833             } else {
00834                 sock->so_rx_win = i;
00835             }
00836         }
00837     }
00838     return size;
00839 }
00840 
00853 int NutTcpCloseSocket(TCPSOCKET * sock)
00854 {
00855     /* Flush buffer first */
00856     //@@@printf ("[%04X] Calling close\n", (u_short) sock);
00857     NutTcpDeviceWrite(sock, 0, 0);
00858     return NutTcpStateCloseEvent(sock);
00859 }
00860 
00909 int NutTcpError(TCPSOCKET * sock)
00910 {
00911     if (sock == 0)
00912         return ENOTSOCK;
00913     return sock->so_last_error;
00914 }
00915 
00935 int NutTcpDeviceRead(TCPSOCKET * sock, void *buffer, int size)
00936 {
00937     return NutTcpReceive(sock, buffer, size);
00938 }
00939 
00940 static int SendBuffer(TCPSOCKET * sock, CONST void *buffer, int size)
00941 {
00942     int rc;
00943     int bite;
00944 
00945     for (rc = 0; rc < size; rc += bite) {
00946         if ((bite = NutTcpSend(sock, (uint8_t *) buffer + rc, size - rc)) <= 0) {
00947             return -1;
00948         }
00949     }
00950     return rc;
00951 }
00952 
00975 int NutTcpDeviceWrite(TCPSOCKET * sock, CONST void *buf, int size)
00976 {
00977     int rc;
00978     uint16_t sz;
00979     /* hack alert for ICCAVR */
00980     uint8_t *buffer = (uint8_t*) buf;
00981 
00982     /*
00983      * Check parameters.
00984      */
00985     if (sock == 0)
00986         return -1;
00987     if (sock->so_state != TCPS_ESTABLISHED) {
00988         sock->so_last_error = ENOTCONN;
00989         return -1;
00990     }
00991 
00992     /* Flush buffer? */
00993     if (size == 0) {
00994         if (sock->so_devocnt) {
00995             if (SendBuffer(sock, sock->so_devobuf, sock->so_devocnt) < 0) {
00996                 free(sock->so_devobuf);
00997                 sock->so_devocnt = 0;
00998                 return -1;
00999             }
01000             free(sock->so_devobuf);
01001             sock->so_devocnt = 0;
01002         }
01003         return 0;
01004     }
01005 
01006     /* If we don't have a buffer so far... */
01007     if (sock->so_devocnt == 0) {
01008         /* If new data block is bigger or equal than buffer size
01009          * send first part of data to nic and store remaining
01010          * bytes in buffer
01011          */
01012         if ((uint16_t) size >= sock->so_devobsz) {
01013             rc = size % sock->so_devobsz;
01014             if (SendBuffer(sock, buffer, size - rc) < 0)
01015                 return -1;
01016             buffer += size - rc;
01017         } else
01018             rc = size;
01019 
01020         /* If there are some remainings bytes, allocate buffer
01021          * and store them
01022          */
01023         if (rc) {
01024             if (!(sock->so_devobuf = malloc(sock->so_devobsz)))
01025                 return -1;
01026             memcpy(sock->so_devobuf, buffer, rc);
01027             sock->so_devocnt = rc;
01028         }
01029         return size;
01030     }
01031 
01032     /* Check if new data fully fits in output buffer */
01033     if (sock->so_devocnt + size < sock->so_devobsz) {
01034         memcpy(sock->so_devobuf + sock->so_devocnt, buffer, size);
01035         sock->so_devocnt += size;
01036         return size;
01037     }
01038 
01039     /* Otherwise store first bytes of new data in buffer and flush
01040      * the buffer
01041      */
01042     sz = sock->so_devobsz - sock->so_devocnt;
01043     memcpy(sock->so_devobuf + sock->so_devocnt, buffer, sz);
01044     buffer += sz;
01045     if (SendBuffer(sock, sock->so_devobuf, sock->so_devobsz) < 0) {
01046         free(sock->so_devobuf);
01047         sock->so_devocnt = 0;
01048         return -1;
01049     }
01050 
01051     /* If remaining data is bigger or equal than buffer size
01052      * send first part of data to nic and later store remaining
01053      * bytes in buffer
01054      */
01055     sz = size - sz;
01056     if (sz >= sock->so_devobsz) {
01057         rc = size % sock->so_devobsz;
01058         if (SendBuffer(sock, buffer, sz - rc) < 0) {
01059             free(sock->so_devobuf);
01060             sock->so_devocnt = 0;
01061             return -1;
01062         }
01063         buffer += sz - rc;
01064     } else
01065         rc = sz;
01066 
01067     /* If there are some remainings bytes, store them in buffer
01068      */
01069     if (rc)
01070         memcpy(sock->so_devobuf, buffer, rc);
01071     else                        /* Otherwise free buffer */
01072         free(sock->so_devobuf);
01073     sock->so_devocnt = rc;
01074 
01075     return size;
01076 }
01077 
01102 #ifdef __HARVARD_ARCH__
01103 int NutTcpDeviceWrite_P(TCPSOCKET * sock, PGM_P buffer, int size)
01104 {
01105     int rc;
01106     char *rp = 0;
01107 
01108     /*
01109      * Hack alert. Neither do we handle out of memory correctly
01110      * nor do we pass the PGM pointer to lower levels.
01111      */
01112     if (size && (rp = NutHeapAlloc(size)) != 0)
01113         memcpy_P(rp, buffer, size);
01114     rc = NutTcpDeviceWrite(sock, rp, size);
01115     if (rp)
01116         NutHeapFree(rp);
01117 
01118     return rc;
01119 }
01120 #endif
01121 
01141 int NutTcpDeviceIOCtl(TCPSOCKET * sock, int cmd, void *param)
01142 {
01143     uint32_t *lvp = (uint32_t *) param;
01144     int rc = 0;
01145     
01146     switch (cmd) {
01147     case IOCTL_GETFILESIZE:
01148     case IOCTL_GETINBUFCOUNT:
01149         *lvp = (sock->so_rx_cnt - sock->so_rd_cnt);
01150         break;
01151     case IOCTL_GETOUTBUFCOUNT:
01152         *lvp = (sock->so_devocnt);
01153         break;
01154     default:
01155         rc = -1;
01156     }
01157     
01158     return rc;    
01159 }
01160 

© 2000-2007 by egnite Software GmbH - visit http://www.ethernut.de/