📄 sockets.c
字号:
/** * @file * Sockets BSD-Like API module * *//* * 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> * * Improved by Marc Boucher <marc@mbsi.ca> and David Haas <dhaas@alum.rpi.edu> * */#include "lwip/opt.h"#if LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */#include "lwip/sockets.h"#include "lwip/api.h"#include "lwip/sys.h"#include "lwip/igmp.h"#include "lwip/inet.h"#include "lwip/tcp.h"#include "lwip/raw.h"#include "lwip/udp.h"#include "lwip/tcpip.h"#include "lwip/pbuf.h"#if LWIP_CHECKSUM_ON_COPY#include "lwip/inet_chksum.h"#endif#include <string.h>#define NUM_SOCKETS MEMP_NUM_NETCONN/** Contains all internal pointers and states used for a socket */struct lwip_sock { /** sockets currently are built on netconns, each socket has one netconn */ struct netconn *conn; /** data that was left from the previous read */ void *lastdata; /** offset in the data that was left from the previous read */ u16_t lastoffset; /** number of times data was received, set by event_callback(), tested by the receive and select functions */ s16_t rcvevent; /** number of times data was ACKed (free send buffer), set by event_callback(), tested by select */ u16_t sendevent; /** error happened for this socket, set by event_callback(), tested by select */ u16_t errevent; /** last error that occurred on this socket */ int err; /** counter of how many threads are waiting for this socket using select */ int select_waiting;};/** Description for a task waiting in select */struct lwip_select_cb { /** Pointer to the next waiting task */ struct lwip_select_cb *next; /** Pointer to the previous waiting task */ struct lwip_select_cb *prev; /** readset passed to select */ fd_set *readset; /** writeset passed to select */ fd_set *writeset; /** unimplemented: exceptset passed to select */ fd_set *exceptset; /** don't signal the same semaphore twice: set to 1 when signalled */ int sem_signalled; /** semaphore to wake up a task waiting for select */ sys_sem_t sem;};/** This struct is used to pass data to the set/getsockopt_internal * functions running in tcpip_thread context (only a void* is allowed) */struct lwip_setgetsockopt_data { /** socket struct for which to change options */ struct lwip_sock *sock;#ifdef LWIP_DEBUG /** socket index for which to change options */ int s;#endif /* LWIP_DEBUG */ /** level of the option to process */ int level; /** name of the option to process */ int optname; /** set: value to set the option to * get: value of the option is stored here */ void *optval; /** size of *optval */ socklen_t *optlen; /** if an error occures, it is temporarily stored here */ err_t err;};/** The global array of available sockets */static struct lwip_sock sockets[NUM_SOCKETS];/** The global list of tasks waiting for select */static struct lwip_select_cb *select_cb_list;/** This counter is increased from lwip_select when the list is chagned and checked in event_callback to see if it has changed. */static volatile int select_cb_ctr;/** Table to quickly map an lwIP error (err_t) to a socket error * by using -err as an index */static const int err_to_errno_table[] = { 0, /* ERR_OK 0 No error, everything OK. */ ENOMEM, /* ERR_MEM -1 Out of memory error. */ ENOBUFS, /* ERR_BUF -2 Buffer error. */ EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ EINVAL, /* ERR_VAL -6 Illegal value. */ EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ EADDRINUSE, /* ERR_USE -8 Address in use. */ EALREADY, /* ERR_ISCONN -9 Already connected. */ ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ ECONNRESET, /* ERR_RST -11 Connection reset. */ ENOTCONN, /* ERR_CLSD -12 Connection closed. */ ENOTCONN, /* ERR_CONN -13 Not connected. */ EIO, /* ERR_ARG -14 Illegal argument. */ -1, /* ERR_IF -15 Low-level netif error */};#define ERR_TO_ERRNO_TABLE_SIZE \ (sizeof(err_to_errno_table)/sizeof(err_to_errno_table[0]))#define err_to_errno(err) \ ((unsigned)(-(err)) < ERR_TO_ERRNO_TABLE_SIZE ? \ err_to_errno_table[-(err)] : EIO)#ifdef ERRNO#ifndef set_errno#define set_errno(err) errno = (err)#endif#else /* ERRNO */#define set_errno(err)#endif /* ERRNO */#define sock_set_errno(sk, e) do { \ sk->err = (e); \ set_errno(sk->err); \} while (0)/* Forward delcaration of some functions */static void event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len);static void lwip_getsockopt_internal(void *arg);static void lwip_setsockopt_internal(void *arg);/** * Initialize this module. This function has to be called before any other * functions in this module! */voidlwip_socket_init(void){}/** * Map a externally used socket index to the internal socket representation. * * @param s externally used socket index * @return struct lwip_sock for the socket or NULL if not found */static struct lwip_sock *get_socket(int s){ struct lwip_sock *sock; if ((s < 0) || (s >= NUM_SOCKETS)) { LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): invalid\n", s)); set_errno(EBADF); return NULL; } sock = &sockets[s]; if (!sock->conn) { LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): not active\n", s)); set_errno(EBADF); return NULL; } return sock;}/** * Same as get_socket but doesn't set errno * * @param s externally used socket index * @return struct lwip_sock for the socket or NULL if not found */static struct lwip_sock *tryget_socket(int s){ if ((s < 0) || (s >= NUM_SOCKETS)) { return NULL; } if (!sockets[s].conn) { return NULL; } return &sockets[s];}/** * Allocate a new socket for a given netconn. * * @param newconn the netconn for which to allocate a socket * @param accepted 1 if socket has been created by accept(), * 0 if socket has been created by socket() * @return the index of the new socket; -1 on error */static intalloc_socket(struct netconn *newconn, int accepted){ int i; SYS_ARCH_DECL_PROTECT(lev); /* allocate a new socket identifier */ for (i = 0; i < NUM_SOCKETS; ++i) { /* Protect socket array */ SYS_ARCH_PROTECT(lev); if (!sockets[i].conn) { sockets[i].conn = newconn; /* The socket is not yet known to anyone, so no need to protect after having marked it as used. */ SYS_ARCH_UNPROTECT(lev); sockets[i].lastdata = NULL; sockets[i].lastoffset = 0; sockets[i].rcvevent = 0; /* TCP sendbuf is empty, but the socket is not yet writable until connected * (unless it has been created by accept()). */ sockets[i].sendevent = (newconn->type == NETCONN_TCP ? (accepted != 0) : 1); sockets[i].errevent = 0; sockets[i].err = 0; sockets[i].select_waiting = 0; return i; } SYS_ARCH_UNPROTECT(lev); } return -1;}/** Free a socket. The socket's netconn must have been * delete before! * * @param sock the socket to free * @param is_tcp != 0 for TCP sockets, used to free lastdata */static voidfree_socket(struct lwip_sock *sock, int is_tcp){ void *lastdata; SYS_ARCH_DECL_PROTECT(lev); lastdata = sock->lastdata; sock->lastdata = NULL; sock->lastoffset = 0; sock->err = 0; /* Protect socket array */ SYS_ARCH_PROTECT(lev); sock->conn = NULL; SYS_ARCH_UNPROTECT(lev); /* don't use 'sock' after this line, as another task might have allocated it */ if (lastdata != NULL) { if (is_tcp) { pbuf_free((struct pbuf *)lastdata); } else { netbuf_delete((struct netbuf *)lastdata); } }}/* Below this, the well-known socket functions are implemented. * Use google.com or opengroup.org to get a good description :-) * * Exceptions are documented! */intlwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen){ struct lwip_sock *sock, *nsock; struct netconn *newconn; ip_addr_t naddr; u16_t port; int newsock; struct sockaddr_in sin; err_t err; SYS_ARCH_DECL_PROTECT(lev); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d)...\n", s)); sock = get_socket(s); if (!sock) { return -1; } if (netconn_is_nonblocking(sock->conn) && (sock->rcvevent <= 0)) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): returning EWOULDBLOCK\n", s)); sock_set_errno(sock, EWOULDBLOCK); return -1; } /* wait for a new connection */ err = netconn_accept(sock->conn, &newconn); if (err != ERR_OK) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): netconn_acept failed, err=%d\n", s, err)); sock_set_errno(sock, err_to_errno(err)); return -1; } LWIP_ASSERT("newconn != NULL", newconn != NULL); /* Prevent automatic window updates, we do this on our own! */ netconn_set_noautorecved(newconn, 1); /* get the IP address and port of the remote host */ err = netconn_peer(newconn, &naddr, &port); if (err != ERR_OK) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d): netconn_peer failed, err=%d\n", s, err)); netconn_delete(newconn); sock_set_errno(sock, err_to_errno(err)); return -1; } /* Note that POSIX only requires us to check addr is non-NULL. addrlen must * not be NULL if addr is valid. */ if (NULL != addr) { LWIP_ASSERT("addr valid but addrlen NULL", addrlen != NULL); memset(&sin, 0, sizeof(sin)); sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; sin.sin_port = htons(port); inet_addr_from_ipaddr(&sin.sin_addr, &naddr); if (*addrlen > sizeof(sin)) *addrlen = sizeof(sin); MEMCPY(addr, &sin, *addrlen); } newsock = alloc_socket(newconn, 1); if (newsock == -1) { netconn_delete(newconn); sock_set_errno(sock, ENFILE); return -1; } LWIP_ASSERT("invalid socket index", (newsock >= 0) && (newsock < NUM_SOCKETS)); LWIP_ASSERT("newconn->callback == event_callback", newconn->callback == event_callback); nsock = &sockets[newsock]; /* See event_callback: If data comes in right away after an accept, even * though the server task might not have created a new socket yet. * In that case, newconn->socket is counted down (newconn->socket--), * so nsock->rcvevent is >= 1 here! */ SYS_ARCH_PROTECT(lev); nsock->rcvevent += (s16_t)(-1 - newconn->socket); newconn->socket = newsock; SYS_ARCH_UNPROTECT(lev); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d addr=", s, newsock)); ip_addr_debug_print(SOCKETS_DEBUG, &naddr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", port)); sock_set_errno(sock, 0); return newsock;}intlwip_bind(int s, const struct sockaddr *name, socklen_t namelen){ struct lwip_sock *sock; ip_addr_t local_addr; u16_t local_port; err_t err; const struct sockaddr_in *name_in; sock = get_socket(s); if (!sock) { return -1; } /* check size, familiy and alignment of 'name' */ LWIP_ERROR("lwip_bind: invalid address", ((namelen == sizeof(struct sockaddr_in)) && ((name->sa_family) == AF_INET) && ((((mem_ptr_t)name) % 4) == 0)), sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); name_in = (const struct sockaddr_in *)(void*)name; inet_addr_to_ipaddr(&local_addr, &name_in->sin_addr); local_port = name_in->sin_port; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d, addr=", s)); ip_addr_debug_print(SOCKETS_DEBUG, &local_addr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", ntohs(local_port))); err = netconn_bind(sock->conn, &local_addr, ntohs(local_port)); if (err != ERR_OK) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) failed, err=%d\n", s, err)); sock_set_errno(sock, err_to_errno(err)); return -1; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d) succeeded\n", s)); sock_set_errno(sock, 0); return 0;}intlwip_close(int s){
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -