📄 tcp.c
字号:
/** * @file * Transmission Control Protocol for IP * * This file contains common functions for the TCP implementation, such as functinos * for manipulating the data structures and the TCP timer functions. TCP functions * related to input and output is found in tcp_in.c and tcp_out.c respectively. * *//* * Copyright (c) 2001-2004 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */#include "opt.h"#if LWIP_TCP /* don't build if not configured for use in lwipopts.h */#include "def.h"#include "mem.h"#include "memp.h"#include "snmp.h"#include "tcp.h"#include "debug.h"#include "stats.h"#include <string.h>const char *tcp_state_str[] = { "CLOSED", "LISTEN", "SYN_SENT", "SYN_RCVD", "ESTABLISHED", "FIN_WAIT_1", "FIN_WAIT_2", "CLOSE_WAIT", "CLOSING", "LAST_ACK", "TIME_WAIT" };/* Incremented every coarse grained timer shot (typically every 500 ms). */u32_t tcp_ticks;const u8_t tcp_backoff[13] = { 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7}; /* Times per slowtmr hits */const u8_t tcp_persist_backoff[7] = { 3, 6, 12, 24, 48, 96, 120 };/* The TCP PCB lists. *//** List of all TCP PCBs bound but not yet (connected || listening) */struct tcp_pcb *tcp_bound_pcbs; /** List of all TCP PCBs in LISTEN state */union tcp_listen_pcbs_t tcp_listen_pcbs;/** List of all TCP PCBs that are in a state in which * they accept or send data. */struct tcp_pcb *tcp_active_pcbs; /** List of all TCP PCBs in TIME-WAIT state */struct tcp_pcb *tcp_tw_pcbs;struct tcp_pcb *tcp_tmp_pcb;static u8_t tcp_timer;static u16_t tcp_new_port(void);/** * Called periodically to dispatch TCP timers. * */voidtcp_tmr(void){ /* Call tcp_fasttmr() every 250 ms */ tcp_fasttmr(); if (++tcp_timer & 1) { /* Call tcp_tmr() every 500 ms, i.e., every other timer tcp_tmr() is called. */ tcp_slowtmr(); }}/** * Closes the connection held by the PCB. * * Listening pcbs are freed and may not be referenced any more. * Connection pcbs are freed if not yet connected and may not be referenced * any more. If a connection is established (at least SYN received or in * a closing state), the connection is closed, and put in a closing state. * The pcb is then automatically freed in tcp_slowtmr(). It is therefore * unsafe to reference it. * * @param pcb the tcp_pcb to close * @return ERR_OK if connection has been closed * another err_t if closing failed and pcb is not freed */err_ttcp_close(struct tcp_pcb *pcb){ err_t err;#if TCP_DEBUG LWIP_DEBUGF(TCP_DEBUG, ("tcp_close: closing in ")); tcp_debug_print_state(pcb->state);#endif /* TCP_DEBUG */ switch (pcb->state) { case CLOSED: /* Closing a pcb in the CLOSED state might seem erroneous, * however, it is in this state once allocated and as yet unused * and the user needs some way to free it should the need arise. * Calling tcp_close() with a pcb that has already been closed, (i.e. twice) * or for a pcb that has been used and then entered the CLOSED state * is erroneous, but this should never happen as the pcb has in those cases * been freed, and so any remaining handles are bogus. */ err = ERR_OK; TCP_RMV(&tcp_bound_pcbs, pcb); memp_free(MEMP_TCP_PCB, pcb); pcb = NULL; break; case LISTEN: err = ERR_OK; tcp_pcb_remove((struct tcp_pcb **)&tcp_listen_pcbs.pcbs, pcb); memp_free(MEMP_TCP_PCB_LISTEN, pcb); pcb = NULL; break; case SYN_SENT: err = ERR_OK; tcp_pcb_remove(&tcp_active_pcbs, pcb); memp_free(MEMP_TCP_PCB, pcb); pcb = NULL; snmp_inc_tcpattemptfails(); break; case SYN_RCVD: err = tcp_send_ctrl(pcb, TCP_FIN); if (err == ERR_OK) { snmp_inc_tcpattemptfails(); pcb->state = FIN_WAIT_1; } break; case ESTABLISHED: err = tcp_send_ctrl(pcb, TCP_FIN); if (err == ERR_OK) { snmp_inc_tcpestabresets(); pcb->state = FIN_WAIT_1; } break; case CLOSE_WAIT: err = tcp_send_ctrl(pcb, TCP_FIN); if (err == ERR_OK) { snmp_inc_tcpestabresets(); pcb->state = LAST_ACK; } break; default: /* Has already been closed, do nothing. */ err = ERR_OK; pcb = NULL; break; } if (pcb != NULL && err == ERR_OK) { /* To ensure all data has been sent when tcp_close returns, we have to make sure tcp_output doesn't fail. Since we don't really have to ensure all data has been sent when tcp_close returns (unsent data is sent from tcp timer functions, also), we don't care for the return value of tcp_output for now. */ /* @todo: When implementing SO_LINGER, this must be changed somehow: If SOF_LINGER is set, the data should be sent when tcp_close returns. */ tcp_output(pcb); } return err;}/** * Abandons a connection and optionally sends a RST to the remote * host. Deletes the local protocol control block. This is done when * a connection is killed because of shortage of memory. * * @param pcb the tcp_pcb to abort * @param reset boolean to indicate whether a reset should be sent */voidtcp_abandon(struct tcp_pcb *pcb, int reset){ u32_t seqno, ackno; u16_t remote_port, local_port; struct ip_addr remote_ip, local_ip;#if LWIP_CALLBACK_API void (* errf)(void *arg, err_t err);#endif /* LWIP_CALLBACK_API */ void *errf_arg; /* Figure out on which TCP PCB list we are, and remove us. If we are in an active state, call the receive function associated with the PCB with a NULL argument, and send an RST to the remote end. */ if (pcb->state == TIME_WAIT) { tcp_pcb_remove(&tcp_tw_pcbs, pcb); memp_free(MEMP_TCP_PCB, pcb); } else { seqno = pcb->snd_nxt; ackno = pcb->rcv_nxt; ip_addr_set(&local_ip, &(pcb->local_ip)); ip_addr_set(&remote_ip, &(pcb->remote_ip)); local_port = pcb->local_port; remote_port = pcb->remote_port;#if LWIP_CALLBACK_API errf = pcb->errf;#endif /* LWIP_CALLBACK_API */ errf_arg = pcb->callback_arg; tcp_pcb_remove(&tcp_active_pcbs, pcb); if (pcb->unacked != NULL) { tcp_segs_free(pcb->unacked); } if (pcb->unsent != NULL) { tcp_segs_free(pcb->unsent); }#if TCP_QUEUE_OOSEQ if (pcb->ooseq != NULL) { tcp_segs_free(pcb->ooseq); }#endif /* TCP_QUEUE_OOSEQ */ memp_free(MEMP_TCP_PCB, pcb); TCP_EVENT_ERR(errf, errf_arg, ERR_ABRT); if (reset) { LWIP_DEBUGF(TCP_RST_DEBUG, ("tcp_abandon: sending RST\r\n")); tcp_rst(seqno, ackno, &local_ip, &remote_ip, local_port, remote_port); } }}/** * Binds the connection to a local portnumber and IP address. If the * IP address is not given (i.e., ipaddr == NULL), the IP address of * the outgoing network interface is used instead. * * @param pcb the tcp_pcb to bind (no check is done whether this pcb is * already bound!) * @param ipaddr the local ip address to bind to (use IP_ADDR_ANY to bind * to any local address * @param port the local port to bind to * @return ERR_USE if the port is already in use * ERR_OK if bound */err_ttcp_bind(struct tcp_pcb *pcb, struct ip_addr *ipaddr, u16_t port){ struct tcp_pcb *cpcb; LWIP_ERROR("tcp_bind: can only bind in state CLOSED", pcb->state == CLOSED, return ERR_ISCONN); if (port == 0) { port = tcp_new_port(); } /* Check if the address already is in use. */ /* Check the listen pcbs. */ for(cpcb = (struct tcp_pcb *)tcp_listen_pcbs.pcbs; cpcb != NULL; cpcb = cpcb->next) { if (cpcb->local_port == port) { if (ip_addr_isany(&(cpcb->local_ip)) || ip_addr_isany(ipaddr) || ip_addr_cmp(&(cpcb->local_ip), ipaddr)) { return ERR_USE; } } } /* Check the connected pcbs. */ for(cpcb = tcp_active_pcbs; cpcb != NULL; cpcb = cpcb->next) { if (cpcb->local_port == port) { if (ip_addr_isany(&(cpcb->local_ip)) || ip_addr_isany(ipaddr) || ip_addr_cmp(&(cpcb->local_ip), ipaddr)) { return ERR_USE; } } } /* Check the bound, not yet connected pcbs. */ for(cpcb = tcp_bound_pcbs; cpcb != NULL; cpcb = cpcb->next) { if (cpcb->local_port == port) { if (ip_addr_isany(&(cpcb->local_ip)) || ip_addr_isany(ipaddr) || ip_addr_cmp(&(cpcb->local_ip), ipaddr)) { return ERR_USE; } } } /* @todo: until SO_REUSEADDR is implemented (see task #6995 on savannah), * we have to check the pcbs in TIME-WAIT state, also: */ for(cpcb = tcp_tw_pcbs; cpcb != NULL; cpcb = cpcb->next) { if (cpcb->local_port == port) { if (ip_addr_cmp(&(cpcb->local_ip), ipaddr)) { return ERR_USE; } } } if (!ip_addr_isany(ipaddr)) { pcb->local_ip = *ipaddr; } pcb->local_port = port; TCP_REG(&tcp_bound_pcbs, pcb); LWIP_DEBUGF(TCP_DEBUG, ("tcp_bind: bind to port %"U16_F"\r\n", port)); return ERR_OK;}#if LWIP_CALLBACK_API/** * Default accept callback if no accept callback is specified by the user. */static err_ttcp_accept_null(void *arg, struct tcp_pcb *pcb, err_t err){ LWIP_UNUSED_ARG(arg); LWIP_UNUSED_ARG(pcb); LWIP_UNUSED_ARG(err); return ERR_ABRT;}#endif /* LWIP_CALLBACK_API *//** * Set the state of the connection to be LISTEN, which means that it * is able to accept incoming connections. The protocol control block * is reallocated in order to consume less memory. Setting the * connection to LISTEN is an irreversible process. * * @param pcb the original tcp_pcb * @param backlog the incoming connections queue limit * @return tcp_pcb used for listening, consumes less memory. * * @note The original tcp_pcb is freed. This function therefore has to be * called like this: * tpcb = tcp_listen(tpcb); */struct tcp_pcb *tcp_listen_with_backlog(struct tcp_pcb *pcb, u8_t backlog){ struct tcp_pcb_listen *lpcb; LWIP_UNUSED_ARG(backlog); LWIP_ERROR("tcp_listen: pcb already connected", pcb->state == CLOSED, return NULL); /* already listening? */ if (pcb->state == LISTEN) { return pcb; } lpcb = memp_malloc(MEMP_TCP_PCB_LISTEN); if (lpcb == NULL) { return NULL; } lpcb->callback_arg = pcb->callback_arg; lpcb->local_port = pcb->local_port; lpcb->state = LISTEN; lpcb->so_options = pcb->so_options; lpcb->so_options |= SOF_ACCEPTCONN; lpcb->ttl = pcb->ttl; lpcb->tos = pcb->tos; ip_addr_set(&lpcb->local_ip, &pcb->local_ip); TCP_RMV(&tcp_bound_pcbs, pcb); memp_free(MEMP_TCP_PCB, pcb);#if LWIP_CALLBACK_API lpcb->accept = tcp_accept_null;#endif /* LWIP_CALLBACK_API */#if TCP_LISTEN_BACKLOG lpcb->accepts_pending = 0; lpcb->backlog = (backlog ? backlog : 1);#endif /* TCP_LISTEN_BACKLOG */ TCP_REG(&tcp_listen_pcbs.listen_pcbs, lpcb); return (struct tcp_pcb *)lpcb;}/** * Update the state that tracks the available window space to advertise. * * Returns how much extra window would be advertised if we sent an * update now. */u32_t tcp_update_rcv_ann_wnd(struct tcp_pcb *pcb){ u32_t new_right_edge = pcb->rcv_nxt + pcb->rcv_wnd; if (TCP_SEQ_GEQ(new_right_edge, pcb->rcv_ann_right_edge + LWIP_MIN((TCP_WND / 2), pcb->mss))) { /* we can advertise more window */ pcb->rcv_ann_wnd = pcb->rcv_wnd; return new_right_edge - pcb->rcv_ann_right_edge; } else { if (TCP_SEQ_GT(pcb->rcv_nxt, pcb->rcv_ann_right_edge)) { /* Can happen due to other end sending out of advertised window, * but within actual available (but not yet advertised) window */ pcb->rcv_ann_wnd = 0; } else { /* keep the right edge of window constant */ pcb->rcv_ann_wnd = pcb->rcv_ann_right_edge - pcb->rcv_nxt; } return 0; }}/** * This function should be called by the application when it has * processed the data. The purpose is to advertise a larger window * when the data has been processed. * * @param pcb the tcp_pcb for which data is read * @param len the amount of bytes that have been read by the application */voidtcp_recved(struct tcp_pcb *pcb, u16_t len){ int wnd_inflation; LWIP_ASSERT("tcp_recved: len would wrap rcv_wnd\r\n", len <= 0xffff - pcb->rcv_wnd ); pcb->rcv_wnd += len; if (pcb->rcv_wnd > TCP_WND) pcb->rcv_wnd = TCP_WND; wnd_inflation = tcp_update_rcv_ann_wnd(pcb); /* If the change in the right edge of window is significant (default * watermark is TCP_WND/2), then send an explicit update now. * Otherwise wait for a packet to be sent in the normal course of * events (or more window to be available later) */ if (wnd_inflation >= TCP_WND_UPDATE_THRESHOLD) tcp_ack_now(pcb); LWIP_DEBUGF(TCP_DEBUG, ("tcp_recved: recveived %"U16_F" bytes, wnd %"U16_F" (%"U16_F").\r\n", len, pcb->rcv_wnd, TCP_WND - pcb->rcv_wnd));}/** * A nastly hack featuring 'goto' statements that allocates a * new TCP local port. * * @return a new (free) local TCP port number */static u16_ttcp_new_port(void){ struct tcp_pcb *pcb;#ifndef TCP_LOCAL_PORT_RANGE_START#define TCP_LOCAL_PORT_RANGE_START 4096#define TCP_LOCAL_PORT_RANGE_END 0x7fff#endif static u16_t port = TCP_LOCAL_PORT_RANGE_START; again: if (++port > TCP_LOCAL_PORT_RANGE_END) { port = TCP_LOCAL_PORT_RANGE_START; } for(pcb = tcp_active_pcbs; pcb != NULL; pcb = pcb->next) { if (pcb->local_port == port) { goto again; } } for(pcb = tcp_tw_pcbs; pcb != NULL; pcb = pcb->next) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -