code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef FEC_5XXX_H_ #define FEC_5XXX_H_ #include "Std_Types.h" /* Interrupt Event register */ #define HEARTBEAT_ERROR 0x80000000U #define BABBLINGRECEIVER 0x40000000U #define BABBLINGTRANSMIT 0x20000000U #define GRACEFULSTOPACK 0x10000000U #define TRANSMITFRAMEINT 0x08000000U #define TRANSMITBUFINT 0x04000000U #define RECEIVEFRAMEINT 0x02000000U #define RECEIVEBUFINT 0x01000000U #define MIIIINT 0x00800000U #define ETHBUS_ERROR 0x00400000U #define LATECOLLISION 0x00200000U #define COLLISIONRETRYLIMIT 0x00100000U #define TRANSMITFIFOUNDERRUN 0x00080000U sint8 fec_mii_read(uint8 phyAddr, uint8 regAddr, uint16 * retVal); sint8 fec_mii_write(uint8 phyAddr, uint8 regAddr, uint32 data); sint8 fec_init(const uint8 *macAddr); uint8 fec_find_phy(uint8 startPhyAddr, uint8 endPhyAddr); sint8 fec_init_phy(void); sint8 fec_send(uint8 *buf, uint16 len); sint8 fec_recv(void); void fec_set_macaddr(const uint8 *macAddr); uint8 * fec_get_buffer_to_send(void); boolean fec_is_rx_data_available(void); void fec_enable_reception(void); void fec_linkUp(void); void fec_stop(void); #endif /* MPC5XXX_FEC_H_ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/mpc5xxx/fec_5xxx.h
C
unknown
1,931
#define LWIP_AR_MAJOR_VERSION 1 #define LWIP_AR_MINOR_VERSION 0 #define LWIP_AR_PATCH_VERSION 0 #define LWIP_SW_MAJOR_VERSION 1 #define LWIP_SW_MINOR_VERSION 0 #define LWIP_SW_PATCH_VERSION 0 /* New important lwip1.4.1 defines */ #define LWIP_TCPIP_CORE_LOCKING 1 #define LWIP_CHECKSUM_ON_COPY 1 #define LWIP_COMPAT_MUTEX_ALLOWED 1 /* We want to be notified when the link changes status. */ #define LWIP_NETIF_STATUS_CALLBACK 1 #define TCPIP_MBOX_SIZE 50 #define MEMP_NUM_NETBUF 10 #define MEMP_NUM_TCPIP_MSG_INPKT 20 /* Support IPV6(mandatory for doip) */ #define LWIP_IPV6 1 #include "LwIp_Cfg.h"
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/mpc5xxx/lwipopts.h
C
unknown
656
/* * tlb_init.c * * Created on: 11 feb 2011 * Author: jcar */ #include "Std_Types.h" #include "Cpu.h" #include "mpc55xx.h" /* size definitions */ #define SIZE_SHIFT 8 #define SIZE_1KB (0x0<<SIZE_SHIFT) #define SIZE_4KB (0x1<<SIZE_SHIFT) #define SIZE_16KB (0x2<<SIZE_SHIFT) #define SIZE_64KB (0x3<<SIZE_SHIFT) #define SIZE_256KB (0x4<<SIZE_SHIFT) #define SIZE_1MB (0x5<<SIZE_SHIFT) #define SIZE_4MB (0x6<<SIZE_SHIFT) #define SIZE_16MB (0x7<<SIZE_SHIFT) #define SIZE_64MB (0x8<<SIZE_SHIFT) #define SIZE_256MB (0x9<<SIZE_SHIFT) /* protection bits */ #define SUPER_RD 0x01 #define USER_RD 0x02 #define SUPER_WR 0x04 #define USER_WR 0x08 #define SUPER_EX 0x10 #define USER_EX 0x20 /* protection aliases */ #define FULL_USER (USER_RD|USER_WR|USER_EX) #define FULL_SUPER (SUPER_RD|SUPER_WR|SUPER_EX) #define FULL_ACCESS (FULL_USER|FULL_SUPER) /* wigme attributes */ #define WRITE_THROUGH 0x10 #define INHIBITED 0x08 #define MEMORY_COHERENCY 0x04 #define GUARDED 0x02 #define LITTLE_ENDIAN 0x01 #define LAST_ENTRY 0xffffffff struct tlb_entry { uint32_t base; uint32_t size; uint32_t prot; uint32_t wimge; }; #define TMP_ENTRY 15 static struct tlb_entry tlb[] = { {0x00000000, SIZE_16MB, FULL_ACCESS, INHIBITED|GUARDED}, /* FLASH */ {0xFFF00000, SIZE_1MB, FULL_SUPER, INHIBITED|GUARDED}, {0xC3F00000, SIZE_1MB, FULL_SUPER, INHIBITED|GUARDED}, {0x40000000, SIZE_64KB, FULL_ACCESS, MEMORY_COHERENCY}, /* cached ram */ {0x40010000, SIZE_4KB, FULL_ACCESS, MEMORY_COHERENCY}, {0x40011000, SIZE_4KB, FULL_ACCESS, MEMORY_COHERENCY}, {0x40012000, SIZE_4KB, FULL_ACCESS, MEMORY_COHERENCY}, {0x40013000, SIZE_4KB, FULL_ACCESS, INHIBITED|GUARDED}, /*non cached*/ {LAST_ENTRY, 0,0,0} /* no more entries */ }; #define VALID (1<<31) #define NOT_VALID (0<<31) #define TS0 (0<<12) #define TS1 (1<<12) #define ESEL_SHIFT 16 #define TLB1 (0x1<<28) static void asm_write_tlb(uint32_t mas0, uint32_t mas1, uint32_t mas2, uint32_t mas3) { set_spr(624,mas0); set_spr(625,mas1); set_spr(626,mas2); set_spr(627,mas3); #if defined __GNUC__ __asm__ __volatile__(".long 0x7C0007A4"); #elif defined __DCC__ __asm(".long 0x7C0007A4"); #elif defined __ghs__ __asm(" tlbwe"); #else #error Unsupported compiler #endif } static void write_tlb1_entry(int entry, int ts, uint32_t base, uint32_t size, uint32_t prot, uint32_t wimge) { asm_write_tlb(TLB1|(entry<<ESEL_SHIFT), /* mas0 */ VALID|ts|size, /* mas1 */ (base&0xfffff000)|wimge, /* mas2 */ (base&0xfffff000)|prot); /* mas3 */ } static void invalidate_tlb1_entry(int entry) { asm_write_tlb(TLB1|(entry<<ESEL_SHIFT), NOT_VALID, 0, 0); } static void set_l1csr0(uint32_t value) { sync(); set_spr(1010,value); sync(); } static uint32_t get_l1csr0(void) { uint32_t ret; sync(); ret = get_spr(1010); sync(); return ret; } #define L1CSRX_CE 0x00000001 /* L1 Cache Enabled */ #define L1CSRX_CFI 0x00000002 /* L1 Cache Flash Invalidate */ void init_mmu(void) { uint32 msr; int n; /* switch to ts == 1 if ts == 0 else bail*/ msr = get_msr(); if (msr & (MSR_IS|MSR_DS)) { return ; } /* setup a valid ts1 entry and switch ts*/ write_tlb1_entry(TMP_ENTRY, TS1, 0x00000000, SIZE_256MB, FULL_SUPER, 0); write_tlb1_entry(TMP_ENTRY+1, TS1, 0x40000000, SIZE_256KB, FULL_SUPER, 0); sync(); set_msr(msr | MSR_IS | MSR_DS); isync(); for (n = 0; tlb[n].base != LAST_ENTRY; n++) { write_tlb1_entry(n, TS0, tlb[n].base, tlb[n].size, tlb[n].prot, tlb[n].wimge); } /* invalidate the rest of the entries */ for (; n < 16; n++) { if (n != TMP_ENTRY) { invalidate_tlb1_entry(n); } } /* switch back to ts == 0 */ sync(); set_msr(msr); isync(); invalidate_tlb1_entry(TMP_ENTRY); invalidate_tlb1_entry(TMP_ENTRY+1); sync(); /* invalidate cache */ set_l1csr0(L1CSRX_CFI); while (get_l1csr0() & L1CSRX_CFI) { ; } /* enable */ set_l1csr0(L1CSRX_CE); }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/mpc5xxx/tlb_init.c
C
unknown
4,427
/** * @file * NetBIOS name service sample * */ /* * 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. * */ #include <string.h> #include "lwip/opt.h" #include <string.h> #if LWIP_UDP /* don't build if not configured for use in lwipopts.h */ #include "lwip/udp.h" #include "lwip/netif.h" /** This is an example implementation of a NetBIOS name server. * It responds to name queries for a configurable name. * Name resolving is not supported. * * Note that the device doesn't broadcast it's own name so can't * detect duplicate names! */ /** NetBIOS name of LWIP device */ #ifndef NETBIOS_LWIP_NAME #define NETBIOS_LWIP_NAME "NETBIOSLWIP" #endif /** default port number for "NetBIOS Name service */ #define NETBIOS_PORT 137 /** size of a NetBIOS name */ #define NETBIOS_NAME_LEN 16 /** The Time-To-Live for NetBIOS name responds (in seconds) * Default is 300000 seconds (3 days, 11 hours, 20 minutes) */ #define NETBIOS_NAME_TTL 300000 /** NetBIOS header flags */ #define NETB_HFLAG_RESPONSE 0x8000 #define NETB_HFLAG_OPCODE 0x7800 #define NETB_HFLAG_OPCODE_NAME_QUERY 0x0000 #define NETB_HFLAG_AUTHORATIVE 0x0400 #define NETB_HFLAG_TRUNCATED 0x0200 #define NETB_HFLAG_RECURS_DESIRED 0x0100 #define NETB_HFLAG_RECURS_AVAILABLE 0x0080 #define NETB_HFLAG_BROADCAST 0x0010 #define NETB_HFLAG_REPLYCODE 0x0008 #define NETB_HFLAG_REPLYCODE_NOERROR 0x0000 /** NetBIOS name flags */ #define NETB_NFLAG_UNIQUE 0x8000 #define NETB_NFLAG_NODETYPE 0x6000 #define NETB_NFLAG_NODETYPE_HNODE 0x6000 #define NETB_NFLAG_NODETYPE_MNODE 0x4000 #define NETB_NFLAG_NODETYPE_PNODE 0x2000 #define NETB_NFLAG_NODETYPE_BNODE 0x0000 /** NetBIOS message header */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct netbios_hdr { PACK_STRUCT_FIELD(u16_t trans_id); PACK_STRUCT_FIELD(u16_t flags); PACK_STRUCT_FIELD(u16_t questions); PACK_STRUCT_FIELD(u16_t answerRRs); PACK_STRUCT_FIELD(u16_t authorityRRs); PACK_STRUCT_FIELD(u16_t additionalRRs); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /** NetBIOS message name part */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct netbios_name_hdr { PACK_STRUCT_FIELD(u8_t nametype); PACK_STRUCT_FIELD(u8_t encname[(NETBIOS_NAME_LEN*2)+1]); PACK_STRUCT_FIELD(u16_t type); PACK_STRUCT_FIELD(u16_t class); PACK_STRUCT_FIELD(u32_t ttl); PACK_STRUCT_FIELD(u16_t datalen); PACK_STRUCT_FIELD(u16_t flags); PACK_STRUCT_FIELD(u32_t addr); } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /** NetBIOS message */ #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/bpstruct.h" #endif PACK_STRUCT_BEGIN struct netbios_resp { struct netbios_hdr resp_hdr; struct netbios_name_hdr resp_name; } PACK_STRUCT_STRUCT; PACK_STRUCT_END #ifdef PACK_STRUCT_USE_INCLUDES # include "arch/epstruct.h" #endif /** NetBIOS decoding name */ static int netbios_name_decoding( char *name_enc, char *name_dec, int name_dec_len) { char *pname; char cname; char cnbname; int index = 0; LWIP_UNUSED_ARG(name_dec_len); /* Start decoding netbios name. */ pname = name_enc; for (;;) { /* Every two characters of the first level-encoded name * turn into one character in the decoded name. */ cname = *pname; if (cname == '\0') break; /* no more characters */ if (cname == '.') break; /* scope ID follows */ if (cname < 'A' || cname > 'Z') { /* Not legal. */ return -1; } cname -= 'A'; cnbname = cname << 4; pname++; cname = *pname; if (cname == '\0' || cname == '.') { /* No more characters in the name - but we're in * the middle of a pair. Not legal. */ return -1; } if (cname < 'A' || cname > 'Z') { /* Not legal. */ return -1; } cname -= 'A'; cnbname |= cname; pname++; /* Do we have room to store the character? */ if (index < NETBIOS_NAME_LEN) { /* Yes - store the character. */ name_dec[index++] = (cnbname!=' '?cnbname:'\0'); } } return 0; } #if 0 /** NetBIOS encoding name */ static int netbios_name_encoding(char *name_enc, char *name_dec, int name_dec_len) { char *pname; char cname; unsigned char ucname; int index = 0; /* Start encoding netbios name. */ pname = name_enc; for (;;) { /* Every two characters of the first level-encoded name * turn into one character in the decoded name. */ cname = *pname; if (cname == '\0') break; /* no more characters */ if (cname == '.') break; /* scope ID follows */ if ((cname < 'A' || cname > 'Z') && (cname < '0' || cname > '9')) { /* Not legal. */ return -1; } /* Do we have room to store the character? */ if (index >= name_dec_len) { return -1; } /* Yes - store the character. */ ucname = cname; name_dec[index++] = ('A'+((ucname>>4) & 0x0F)); name_dec[index++] = ('A'+( ucname & 0x0F)); pname++; } /* Fill with "space" coding */ for (;index<name_dec_len-1;) { name_dec[index++] = 'C'; name_dec[index++] = 'A'; } /* Terminate string */ name_dec[index]='\0'; return 0; } #endif /** NetBIOS Name service recv callback */ static void netbios_recv(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) { LWIP_UNUSED_ARG(arg); /* if packet is valid */ if (p != NULL) { char netbios_name[NETBIOS_NAME_LEN+1]; struct netbios_hdr* netbios_hdr = p->payload; struct netbios_name_hdr* netbios_name_hdr = (struct netbios_name_hdr*)(netbios_hdr+1); /* we only answer if we got a default interface */ if (netif_default != NULL) { /* @todo: do we need to check answerRRs/authorityRRs/additionalRRs? */ /* if the packet is a NetBIOS name query question */ if (((ntohs(netbios_hdr->flags) & NETB_HFLAG_OPCODE) == NETB_HFLAG_OPCODE_NAME_QUERY) && ((ntohs(netbios_hdr->flags) & NETB_HFLAG_RESPONSE) == 0) && (ntohs(netbios_hdr->questions) == 1)) { /* decode the NetBIOS name */ netbios_name_decoding( (char*)(netbios_name_hdr->encname), netbios_name, sizeof(netbios_name)); /* if the packet is for us */ if (strcmp( netbios_name, NETBIOS_LWIP_NAME)==0) { struct pbuf *q; struct netbios_resp *resp; q = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct netbios_resp), PBUF_RAM); if (q != NULL) { resp = (struct netbios_resp*)q->payload; /* prepare NetBIOS header response */ resp->resp_hdr.trans_id = netbios_hdr->trans_id; resp->resp_hdr.flags = htons(NETB_HFLAG_RESPONSE | NETB_HFLAG_OPCODE_NAME_QUERY | NETB_HFLAG_AUTHORATIVE | NETB_HFLAG_RECURS_DESIRED); resp->resp_hdr.questions = 0; resp->resp_hdr.answerRRs = htons(1); resp->resp_hdr.authorityRRs = 0; resp->resp_hdr.additionalRRs = 0; /* prepare NetBIOS header datas */ MEMCPY( resp->resp_name.encname, netbios_name_hdr->encname, sizeof(netbios_name_hdr->encname)); resp->resp_name.nametype = netbios_name_hdr->nametype; resp->resp_name.type = netbios_name_hdr->type; resp->resp_name.class = netbios_name_hdr->class; resp->resp_name.ttl = htonl(NETBIOS_NAME_TTL); resp->resp_name.datalen = htons(sizeof(resp->resp_name.flags)+sizeof(resp->resp_name.addr)); resp->resp_name.flags = htons(NETB_NFLAG_NODETYPE_BNODE); resp->resp_name.addr = netif_default->ip_addr.addr; /* send the NetBIOS response */ udp_sendto(upcb, q, addr, port); /* free the "reference" pbuf */ pbuf_free(q); } } } } /* free the pbuf */ pbuf_free(p); } } void netbios_init(void) { struct udp_pcb *pcb; LWIP_ASSERT("NetBIOS name is too long!", strlen(NETBIOS_LWIP_NAME) < NETBIOS_NAME_LEN); pcb = udp_new(); if (pcb != NULL) { udp_bind(pcb, IP_ADDR_ANY, NETBIOS_PORT); udp_recv(pcb, netbios_recv, pcb); } } #endif /* LWIP_UDP */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/netbios.c
C
unknown
10,358
#ifndef __NETBIOS_H__ #define __NETBIOS_H__ void netbios_init(void); #endif /* __NETBIOS_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/netbios.h
C
unknown
104
/* * Copyright (c) 2001-2003 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> * */ /* lwIP includes. */ #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "Os.h" #include "Std_Types.h" #include "arch/sys_arch.h" #include "Mcu.h" #include <string.h> static void (*tcpip_thread)(void *arg) = NULL; #if !NO_SYS struct lwip_port_statsS { uint32 sem_new_err; uint32 mbox_trypost_err; uint32 mbox_tryfetch_empty; uint32 sem_new; uint32 sem_free; uint32 sem_wait; uint32 sem_wait_tmo; uint32 sem_signal; uint32 mbox_new; uint32 mbox_new_err; uint32 mbox_post; uint32 mbox_trypost; uint32 mbox_tryfetch; uint32 mbox_fetch; uint32 mbox_fetch_tmo; uint32 malloc; uint32 free; }; struct lwip_port_statsS lwip_port_stats; void __malloc_lock ( struct _reent *_r ) { Irq_Disable(); lwip_port_stats.malloc++; return; } void __malloc_unlock ( struct _reent *_r ) { lwip_port_stats.free++; Irq_Enable(); return; } #include "lwip/tcpip.h" /* This is the number of threads that can be started with sys_thread_new() * Cannot be modified at the moment. No need to support slip/ppp */ #define SYS_THREAD_MAX 1 /* This optional function does a "fast" critical region protection and returns the previous protection level. This function is only called during very short critical regions. An embedded system which supports ISR-based drivers might want to implement this function by disabling interrupts. Task-based systems might want to implement this by using a mutex or disabling tasking. This function should support recursive calls from the same task or interrupt. In other words, sys_arch_protect() could be called while already protected. In that case the return value indicates that it is already protected. sys_arch_protect() is only required if your port is supporting an operating system. */ sys_prot_t sys_arch_protect(void) { uint32_t val; Irq_Save(val); return val; } /* This optional function does a "fast" set of critical region protection to the value specified by pval. See the documentation for sys_arch_protect() for more information. This function is only required if your port is supporting an operating system. */ void sys_arch_unprotect(sys_prot_t pval) { Irq_Restore(pval); } u32_t sys_now(void) { return (u32_t)GetOsTick(); } /*-----------------------------------------------------------------------------------*/ // Creates an empty mailbox. err_t sys_mbox_new(sys_mbox_t *mbox, int size) { err_t rv; lwip_port_stats.mbox_new++; if(size==0){size=20;} *mbox = malloc( sizeof(OsMBoxType) + sizeof(OsMBoxMsg) * size ); if( mbox == NULL ) { rv = ERR_MEM; lwip_port_stats.mbox_new_err++; } else { memset(*mbox, 0, sizeof(OsMBoxType)); MBoxInit( *mbox, (OsMBoxMsg *)(((uint8 *)*mbox) + sizeof(OsMBoxType)), size); rv = ERR_OK; } return rv; } /*-----------------------------------------------------------------------------------*/ /* Deallocates a mailbox. If there are messages still present in the mailbox when the mailbox is deallocated, it is an indication of a programming error in lwIP and the developer should be notified. */ void sys_mbox_free(sys_mbox_t *mbox) { lwip_port_stats.sem_free++; free(*mbox); *mbox = SYS_MBOX_NULL; } /*-----------------------------------------------------------------------------------*/ /* void sys_mbox_post(sys_mbox_t mbox, void *msg) Posts the "msg" to the mailbox. This function have to block until the "msg" is really posted. */ void sys_mbox_post(sys_mbox_t *mbox, void *msg) { StatusType rv; lwip_port_stats.mbox_post++; rv = MBoxPost(*mbox,(OsMBoxMsg)msg); (void)rv; } /* err_t sys_mbox_trypost(sys_mbox_t mbox, void *msg) Try to post the "msg" to the mailbox. Returns ERR_MEM if this one is full, else, ERR_OK if the "msg" is posted. */ err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { err_t err = ERR_OK; StatusType rv; lwip_port_stats.mbox_trypost++; rv = MBoxPost(*mbox,(OsMBoxMsg)msg); if( rv == E_OS_FULL ) { lwip_port_stats.mbox_trypost_err++; err = ERR_MEM; } return err; } /* This is similar to sys_arch_mbox_fetch, however if a message is not present in the mailbox, it immediately returns with the code SYS_MBOX_EMPTY. On success 0 is returned. To allow for efficient implementations, this can be defined as a function-like macro in sys_arch.h instead of a normal function. For example, a naive implementation could be: #define sys_arch_mbox_tryfetch(mbox,msg) \ sys_arch_mbox_fetch(mbox,msg,1) although this would introduce unnecessary delays. */ u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg) { StatusType mRv; u32_t rv; lwip_port_stats.mbox_tryfetch++; mRv = MBoxFetchTmo(*mbox, (OsMBoxMsg *)msg, TMO_MIN ); if( mRv == E_OS_TIMEOUT ) { lwip_port_stats.mbox_tryfetch_empty++; rv = SYS_MBOX_EMPTY; } else { rv = 0; } return rv; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread until a message arrives in the mailbox, but does not block the thread longer than "timeout" milliseconds (similar to the sys_arch_sem_wait() function). The "msg" argument is a result parameter that is set by the function (i.e., by doing "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message should be dropped. The return values are the same as for the sys_arch_sem_wait() function: Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a timeout. Note that a function with a similar name, sys_mbox_fetch(), is implemented by lwIP. */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout_ms) { StatusType rv; u32_t diff; TickType start; imask_t flags; uint32 tmo; /* TODO: Not really sure about the locking here.... only needed to get the timeout correct */ Irq_Save(flags); lwip_port_stats.mbox_fetch++; start = GetOsTick(); /* TODO: MBox timeout is in ticks... */ tmo = (timeout_ms == 0) ? TMO_INFINITE : timeout_ms; rv = MBoxFetchTmo(*mbox,(OsMBoxMsg *)msg, tmo); if( rv == E_OS_TIMEOUT ) { return SYS_ARCH_TIMEOUT; lwip_port_stats.mbox_fetch_tmo++; } diff = GetOsTick() - start; Irq_Restore(flags); return diff; } /*-----------------------------------------------------------------------------------*/ // Creates and returns a new semaphore. The "count" argument specifies // the initial state of the semaphore. err_t sys_sem_new(sys_sem_t *sem, u8_t count) { lwip_port_stats.sem_new++; *sem = malloc( sizeof(OsSemType) ); if( *sem == NULL ) { lwip_port_stats.sem_new_err++; return ERR_MEM; } memset(*sem, 0, sizeof(OsSemType)); BSemInit(*sem,count); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread while waiting for the semaphore to be signaled. If the "timeout" argument is non-zero, the thread should only be blocked for the specified time (measured in milliseconds). If the timeout argument is non-zero, the return value is the number of milliseconds spent waiting for the semaphore to be signaled. If the semaphore wasn't signaled within the specified time, the return value is SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore (i.e., it was already signaled), the function may return zero. Notice that lwIP implements a function with a similar name, sys_sem_wait(), that uses the sys_arch_sem_wait() function. */ /** * Wait for a semaphore for the specified timeout. * @param sem the semaphore to wait for * @param timeout_ms timeout in milliseconds to wait (0 = wait forever) * * @return */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout_ms) { StatusType rv; u32_t diff; TickType start; imask_t flags; uint32 tmo; lwip_port_stats.sem_wait++; /* TODO: Not really sure about the locking here.... only needed to get the timeout correct */ Irq_Save(flags); start = GetOsTick(); tmo = (timeout_ms == 0) ? TMO_INFINITE : timeout_ms; /* TODO: MBox timeout is in ticks... */ rv = BSemWaitTmo(*sem, tmo); if( rv == E_OS_TIMEOUT ) { lwip_port_stats.sem_wait_tmo++; return SYS_ARCH_TIMEOUT; } diff = GetOsTick() - start; Irq_Restore(flags); return diff; } /*-----------------------------------------------------------------------------------*/ // Signals a semaphore void sys_sem_signal(sys_sem_t *sem) { lwip_port_stats.sem_signal++; BSemSignal(*sem); } /*-----------------------------------------------------------------------------------*/ // Deallocates a semaphore void sys_sem_free(sys_sem_t *sem) { lwip_port_stats.sem_free++; free(*sem); *sem = SYS_SEM_NULL; } /*-----------------------------------------------------------------------------------*/ // Initialize sys arch void sys_init(void) { } // Preinitialize sys arch void pre_sys_init(void) { } // TBD memory leak with invalid mbox? int sys_mbox_valid(sys_mbox_t *mbox) { return (*mbox == SYS_MBOX_NULL) ? 0 : 1; } void sys_mbox_set_invalid(sys_mbox_t *mbox) { *mbox = SYS_MBOX_NULL; } int sys_sem_valid(sys_sem_t *sem) { return (*sem != SYS_SEM_NULL); } void sys_sem_set_invalid(sys_sem_t *sem) { *sem = SYS_SEM_NULL; } /*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/ // TBD /*-----------------------------------------------------------------------------------*/ /* Starts a new thread with priority "prio" that will begin its execution in the function "thread()". The "arg" argument will be passed as an argument to the thread() function. The id of the new thread is returned. Both the id and the priority are system dependent. */ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio) { sys_thread_t CreatedTask = TASK_ID_tcpip_task; static uint8 iCall = 0; if( iCall == 0 ) { tcpip_thread = thread; } else { // We only support creating tcpip thread at the moment ErrorHook(E_OS_LIMIT); return 0; } // ActiveTask(TASK_ID_tcpip_task); /* Why not ActivateTask here ?? */ SetEvent(TASK_ID_tcpip_task,EVENT_MASK_START_TCPIP); // Start tcpip stack return CreatedTask; } #endif /* !NO_SYS */ // TCPIP task shell void tcpip_task(void) { for (;;) { WaitEvent(EVENT_MASK_START_TCPIP); ClearEvent(EVENT_MASK_START_TCPIP); if (tcpip_thread != NULL) { tcpip_thread(NULL); // Will never return } } }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/sys_arch.c
C
unknown
12,978
/* * Copyright (c) 2001-2003 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> * */ #ifndef __CC_H__ #define __CC_H__ #include "Std_Types.h" #include <stdio.h> #include <assert.h> #if defined(CFG_ZYNQ) || defined(CFG_JAC6) || defined(CFG_TC29X) #define BYTE_ORDER LITTLE_ENDIAN #else #define BYTE_ORDER BIG_ENDIAN #endif //typedef uint8 u8_t; //typedef sint8 s8_t; //typedef uint16 u16_t; //typedef sint16 s16_t; //typedef uint32 u32_t; //typedef sint32 s32_t; //typedef u32_t mem_ptr_t; typedef uint32 sys_prot_t; /* IMPROVEMENT - read it from compiler.h */ #define PACK_STRUCT_BEGIN #if defined(__GNUC__) #define PACK_STRUCT_STRUCT __attribute__ ((__packed__)) #elif defined (__ARMCC_VERSION) #define PACK_STRUCT_STRUCT __attribute__ ((packed)) #else #define PACK_STRUCT_STRUCT #endif #define PACK_STRUCT_END #define PACK_STRUCT_FIELD(x) x #define U16_F "u" #define S16_F "d" #define X16_F "x" #define U32_F "u" #define S32_F "d" #define X32_F "x" #define SZT_F "u" #define LWIP_PLATFORM_DIAG(x) printf x #define LWIP_PLATFORM_ASSERT(x) assert(0) #define LWIP_RAND (u32_t)rand #endif /* __CC_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/arch/cc.h
C
unknown
2,734
/* * Copyright (c) 2001-2003 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> * */ #ifndef __PERF_H__ #define __PERF_H__ #define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */ #endif /* __PERF_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/arch/perf.h
C
unknown
1,798
/* * Copyright (c) 2001-2003 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> * */ #ifndef __SYS_ARCH_H__ #define __SYS_ARCH_H__ #include "Os.h" #include "Std_Types.h" #include "mbox.h" #define SYS_MBOX_NULL NULL #define SYS_SEM_NULL NULL #define LWIP_COMPAT_MUTEX 1 void pre_sys_init(void); typedef OsSemType *sys_sem_t; typedef OsMBoxType *sys_mbox_t; typedef TaskType *sys_thread_t; #define sys_msleep(x) Sleep(x) #endif /* __SYS_ARCH_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/arch/sys_arch.h
C
unknown
2,033
/** * @file * Ethernet Interface Skeleton * */ /* * 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> * */ /* * This file is a skeleton for developing Ethernet network interface * drivers for lwIP. Add code to the low_level functions and do a * search-and-replace for the word "ethernetif" to replace it with * something that better describes your network interface. */ #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/pbuf.h" #include "lwip/sys.h" #include <lwip/stats.h> #include <lwip/snmp.h> #include "netif/etharp.h" #include "netif/ppp_oe.h" #include "lwip/err.h" #include "ethernetif.h" #include "lwip/ethip6.h" #include "lwip/tcpip.h" #include "Eth.h" #include "LwIpAdp.h" #include <string.h> #include "isr.h" #include "irq_types.h" #if defined(CFG_JAC6) #include "Eth_jacinto.h" #endif #if defined(CFG_AURIX) #include "Ifx_reg.h" #if defined(CFG_DRIVE_PX_B00) #include "Phy_Bcm89610.h" #endif #endif /* TCP and ARP timeouts */ volatile int tcp_end_time, arp_end_time; static uint8 phyAddress = 32u; /* Invalid address or Phy is not initialised in this context */ static boolean ethCtrlInitRun = FALSE; static boolean ethTrcvInitRun = FALSE; /* Define those to better describe your network interface. */ #define IFNAME0 's' #define IFNAME1 't' #define ETH_HEADER_SIZE 14u #define ETH_MAC_ADDR_SIZE 6u #define READ32(address) (*(vuint32_t *)(address)) #define WRITE32(address, val) (*(volatile uint32_t*)(address) = val) #define ETH_CTRL_INDEX 0u /* Assign HW_UNIT_0 to this index */ #define VLAN_HEADER_SIZE 4u #define BMCR_REGISTER 0u #define BMSR_REGISTER 1u #define AUTONEG_ADVERTISE_REGISTER 4u #define PHY_SOFT_RESET 0x8000u #define ENABLE_AUTO_NEGOTIATION 0x1000u #define ENABLE_100MBPS_DUPLEX 0x2100u #if defined(CFG_ETH_PHY_DP83848C) #define PHY_STATUS_REGISTER 0x10u #define PHY_STATUS_LINK 0x0001u #define PHY_STATUS_NO_AUTO_100 0x0005u #define PHY_STATUS_LOOPBACK 0x0008u #elif defined (CFG_ETH_PHY_TJA1100) #define PHY_STATUS_REGISTER 0x01u #define PHY_EXTENDED_STATUS_REGISTER 15u #define PHY_EXTENDED_CONTROL_REGISTER 17u #define PHY_CONFIG_REGISTER1 18u #define PHY_STATUS_LINK 0x0004u #define PHY_STATUS_NO_AUTO_100 0xE600u /*100BASE-T4,100BASE-X_FD,100BASE-X_HD,100BASE-T2_FD,100BASE-T2_HD*/ #define PHY_EXTENDED_STATUS_NO_AUTO_100 0x0080u #define PHY_CONFIG_EN_BIT (2u) #define PHY_CONFIG_MASTER_SLAVE_BIT (15u) #else /* CFG_ETH_PHY_DP83865 */ #if defined(CFG_DRIVE_PX_B00) #define PHY_STATUS_REGISTER 0x01u #else #define PHY_STATUS_REGISTER 0x11u #endif #define PHY_STATUS_LINK 0x0004u #define PHY_STATUS_NO_AUTO_100 0x000Eu #define PHY_STATUS_LOOPBACK 0x0040u #define RGMII_INBAND_STATUS_EN 0x0100U #endif #ifdef CFG_BRD_ZYNQ_ZC702 #define PORT_MIO_52 0xF80007D0 #define PORT_MIO_53 0xF80007D4 #endif #if defined(CFG_JAC6) #define GMAC_SW_MDIO_LINKSEL 0x00000080U #define GMAC_SW_MDIO_LINKINTENB 0x00000040U #define GMAC_SW_MDIO_PHYADDRMON_MASK 0x0000001FU #define ETH_CTRL_TX_FRAME_MIN_SIZE 60u #define ETH_CTRL_PAD #if defined(CFG_ETH_HW_SHARE) #define VLAN_TCI (0x0042u) #endif static GmacSw_HwRegType * const hwPtr = (GmacSw_HwRegType*) GMAC_SW_BASE; #endif /* Max wait cycles for actions to occur in busy wait***** */ #define ETH_MAX_BUSY_WAIT_CYCLES (uint32)1000 #define ETH_MDIO_WAIT_CYCLES 50u /* Macro for busy waiting for a while */ #define BUSY_WAIT_A_WHILE(_regPtr, _mask, _val, _retPtr)\ *(_retPtr) = E_NOT_OK;\ for( uint32 i = 0; i < ETH_MAX_BUSY_WAIT_CYCLES; i++) {\ if( (*(_regPtr) & (_mask)) == (_val) ) {\ *(_retPtr) = E_OK;\ break;\ }\ }\ #define ETH_LINK_CHECK /* internal defines for the internal config and test */ LinkState linkStatus = NO_LINK; /* Forward declarations. */ static err_t low_level_output(struct netif *netif, struct pbuf *p); static uint8 Eth_TransHw_findPhyAdrs(uint8 ctrlIdx,uint8 startPhyAddr, uint8 endPhyAddr); static Std_ReturnType Eth_TransHw_init(uint8 ctrlIdx); static struct netif *netIfPtr = NULL; /** * @brief Mock up function for ETH_IF : Frames reception routine * Call recurrently, Disable RX interrupt * @param None * @retval None */ void Ethernetif_RxFunc(void) { if((ethCtrlInitRun == FALSE) || (ethTrcvInitRun == FALSE)){ return; } #if defined(CFG_JAC6) || (CFG_AURIX) Eth_TransHw_linkUp(ETH_CTRL_INDEX); #endif if(linkStatus == LINK_UP){ #if defined(CFG_RH850) Eth_Receive(ETH_CTRL_INDEX); #else #if defined(CFG_JAC6) && defined(CFG_ETH_HW_SHARE) /* Interrupt mode is not sharable */ Eth_TxConfirmation(ETH_CTRL_INDEX); #endif Eth_RxStatusType rxStatus; /* unused */ Eth_Receive(ETH_CTRL_INDEX,&rxStatus); (void)rxStatus; #endif } } /** * @brief Mock up function for ETH_IF : Frames reception function * @param -- * @retval None */ void EthIf_RxIndication( uint8 CtrlIdx, Eth_FrameType FrameType, boolean IsBroadcast, uint8* PhysAddrPtr, Eth_DataType* DataPtr, uint16 LenByte ) { struct pbuf *p; uint8 macAdrs[ETH_MAC_ADDR_SIZE] = ETH_MAC_ADDR; uint8 macBroadcastAdrs[ETH_MAC_ADDR_SIZE] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; uint16 AdaptFrameType; uint16 AdaptFrameType1; #if ETH_PAD_SIZE len += ETH_PAD_SIZE; /* allow room for Ethernet padding */ #endif p = pbuf_alloc(PBUF_RAW, LenByte+ETH_HEADER_SIZE, PBUF_POOL); if (p != NULL){ #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif if(IsBroadcast == TRUE){ MEMCPY((uint8*)p->payload,macBroadcastAdrs,ETH_MAC_ADDR_SIZE); }else{ MEMCPY((uint8*)p->payload,macAdrs,ETH_MAC_ADDR_SIZE); } MEMCPY((uint8*)p->payload+ETH_MAC_ADDR_SIZE,PhysAddrPtr,ETH_MAC_ADDR_SIZE); #if defined(CFG_ZYNQ) || defined(CFG_JAC6) || defined(CFG_TC29X) AdaptFrameType = (uint16)(FrameType >> 8 ) + (uint16)(FrameType << 8); MEMCPY((uint8*)p->payload+(2*ETH_MAC_ADDR_SIZE),&AdaptFrameType,sizeof(uint16)); if(AdaptFrameType == PP_HTONS(ETHTYPE_VLAN)){ AdaptFrameType1 = (uint16)(DataPtr[2]) + (uint16)(DataPtr[3] << 8); MEMCPY((uint8*)p->payload+(2*ETH_MAC_ADDR_SIZE),&AdaptFrameType1,sizeof(uint16)); } #else MEMCPY((uint8*)p->payload+(2*ETH_MAC_ADDR_SIZE),&FrameType,sizeof(uint16)); #endif if(AdaptFrameType != PP_HTONS(ETHTYPE_VLAN)){ MEMCPY((uint8*)p->payload+ETH_HEADER_SIZE,DataPtr,LenByte); }else{ MEMCPY((uint8*)p->payload+ETH_HEADER_SIZE,&DataPtr[VLAN_HEADER_SIZE],(LenByte-VLAN_HEADER_SIZE)); } if(netIfPtr != NULL){ tcpip_input(p, netIfPtr); } }else{ /* Out of memory, Nothing to do but to through away data */ return; } } /** * @brief Mock up function for ETH_IF : Transmit conmfirmation * Doing nothing currently * @param None * @retval None */ void EthIf_TxConfirmation( uint8 CtrlIdx, uint8 BufIdx ) { /* done */ } void LwIP_EthernetIfStart(struct netif *netIf) { netIfPtr = netIf; } /** * In this function, the hardware should be initialized. * Called from ethernetif_init(). * * @param netif the already initialized lwip network interface structure * for this ethernetif */ static void low_level_init(struct netif *netif) { /* set MAC hardware address length */ netif->hwaddr_len = ETHARP_HWADDR_LEN; uint8_t MACaddr[6] = ETH_MAC_ADDR; netif->hwaddr[0] = MACaddr[0]; netif->hwaddr[1] = MACaddr[1]; netif->hwaddr[2] = MACaddr[2]; netif->hwaddr[3] = MACaddr[3]; netif->hwaddr[4] = MACaddr[4]; netif->hwaddr[5] = MACaddr[5]; /* maximum transfer unit */ netif->mtu = 1500; /* device capabilities */ /* don't set NETIF_FLAG_ETHARP if this device is not an ethernet one */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_LINK_UP | NETIF_FLAG_IGMP; } void ethernetif_pre_tcpip_init(void){ uint8_t MACaddr[6] = ETH_MAC_ADDR; #ifdef CFG_BRD_ZYNQ_ZC702 /* IMPROVE - port driver change is required*/ WRITE32(PORT_MIO_52,0x00001280); WRITE32(PORT_MIO_53,0x00001280); #endif #if defined(CFG_DRIVE_PX_B00) Phy_Bcm89610_Enable(); #endif if(E_OK == Eth_ControllerInit(ETH_CTRL_INDEX,0)){ ethCtrlInitRun = TRUE; } #if defined(CFG_ZYNQ) || defined(CFG_JAC6) #if (ETH_PHYS_ADRS_FILTER_API == STD_ON) Eth_UpdatePhysAddrFilter(ETH_CTRL_INDEX,MACaddr,ETH_ADD_TO_FILTER); #endif #endif #ifdef CHECKSUM_BY_HARDWARE /* Do nothing at the moment */ #endif // Eth_SetControllerMode(ETH_CTRL_INDEX,ETH_MODE_ACTIVE); #if defined(CFG_DRIVE_PX_B00) Phy_Bcm89610_Configure(); ethTrcvInitRun = TRUE; #else #if defined(CFG_JAC6) && (LWIP_TRCV_ADRS != 32u) phyAddress = LWIP_TRCV_ADRS; #else phyAddress = Eth_TransHw_findPhyAdrs(ETH_CTRL_INDEX,0,31); #endif if(phyAddress != 32u){ (void)Eth_TransHw_init(ETH_CTRL_INDEX); } #endif } /** * Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * * This function should be passed as a parameter to netif_add(). * * @param netif the lwip network interface structure for this ethernetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t ethernetif_init(struct netif *netif) { LWIP_ASSERT("netif != NULL", (netif != NULL)); /* * Initialize the snmp variables and counters inside the struct netif. * The last argument should be replaced with your link speed, in units * of bits per second. */ NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100000000); netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; /* We directly use etharp_output() here to save a function call. * You can instead declare your own function an call etharp_output() * from it if you have to do some checks before sending (e.g. if link * is available...) */ netif->output = etharp_output; netif->linkoutput = low_level_output; #if LWIP_IPV6 netif->output_ip6 = ethip6_output; #endif /* LWIP_IPV6 */ /* initialize the hardware */ low_level_init(netif); ethernetif_pre_tcpip_init(); LwIP_EthernetIfStart(netif); return ERR_OK; } /** * This function should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * * @param netif the lwip network interface structure for this ethernetif * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) * @return ERR_OK if the packet could be sent * an err_t value if the packet couldn't be sent * * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to * strange results. You might consider waiting for space in the DMA queue * to become availale since the stack doesn't retry to send a packet * dropped because of memory failure (except for the TCP timers). */ static err_t low_level_output(struct netif *netif, struct pbuf *p) { struct pbuf *q; int l = 0; uint8 *buffer; uint32 baseAddress; uint32_t cnt = 0; Eth_BufIdxType bufIndex = 0; uint16 lenByte = 0; Eth_FrameType frametype; BufReq_ReturnType bufRes; Std_ReturnType txRes; bufRes = Eth_ProvideTxBuffer(ETH_CTRL_INDEX, &bufIndex,(Eth_DataType **) &baseAddress, &lenByte); if(bufRes != BUFREQ_OK){ LWIP_DEBUGF(NETIF_DEBUG, ("send: buffer not available\n")); /* Try to increase the number of ETH TX buffers */ return ERR_MEM; } #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif buffer = (u8_t*)(baseAddress-ETH_HEADER_SIZE); #if defined(CFG_JAC6) && defined(CFG_ETH_HW_SHARE) for(q = p; q != NULL; q = q->next) { if(l == 0u){ SMEMCPY((u8_t*)buffer, q->payload, (ETH_MAC_ADDR_SIZE*2)); buffer[12] = (uint8)((ETHTYPE_VLAN >> 8u) & 0xFFu); /* 0x8100 */ buffer[13] = (uint8) (ETHTYPE_VLAN & 0xFFu); buffer[14] = (uint8)((VLAN_TCI >> 8u) & 0xFFu); buffer[15] = (uint8) (VLAN_TCI & 0xFFu); SMEMCPY((u8_t*)&buffer[(ETH_MAC_ADDR_SIZE*2)+VLAN_HEADER_SIZE], (q->payload+(ETH_MAC_ADDR_SIZE*2)), (q->len-(ETH_MAC_ADDR_SIZE*2))); l = ((q->len) + VLAN_HEADER_SIZE); }else{ SMEMCPY((u8_t*)&buffer[l], q->payload, q->len); l = l + q->len; } } #else for(q = p; q != NULL; q = q->next) { SMEMCPY((u8_t*)&buffer[l], q->payload, q->len); l = l + q->len; } #endif /* Try to send */ cnt = 0; #if defined(CFG_ZYNQ) || defined(CFG_JAC6) || defined(CFG_TC29X) frametype = ((buffer[12] << 8) + buffer[13] ); #else frametype = ((buffer[13] << 8) + buffer[12] ); #endif #if defined(ETH_CTRL_PAD) if(l < ETH_CTRL_TX_FRAME_MIN_SIZE){ for(uint8 i = l; i < ETH_CTRL_TX_FRAME_MIN_SIZE; i++){ buffer[i] = 0u; } l = ETH_CTRL_TX_FRAME_MIN_SIZE; } #endif txRes = Eth_Transmit(ETH_CTRL_INDEX,bufIndex,frametype,TRUE,(l-ETH_HEADER_SIZE),buffer); while(txRes == E_PENDING) { /* TXBD_READY bit set. Loop here and wait since frames will not be resend */ if(!(cnt % 500)){ Eth_TxConfirmation(ETH_CTRL_INDEX); /* only in POLLING mode */ txRes = Eth_Transmit(ETH_CTRL_INDEX,bufIndex,frametype,TRUE,(l-ETH_HEADER_SIZE),buffer); } cnt++; if(cnt > 1000000) { /* timeout, notify error and return */ LWIP_DEBUGF(NETIF_DEBUG, ("send: not ready\n")); return ERR_TIMEOUT; } } #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ #endif /* Return SUCCESS */ return ERR_OK; } /** * Fetch PHY address:: mock up function for ETH tranciever * @param startPhyAddr * @param endPhyAddr * @return phyAddr */ uint8 Eth_TransHw_findPhyAdrs(uint8 ctrlIdx, uint8 startPhyAddr, uint8 endPhyAddr) { uint8 phy_addr; for (phy_addr = 0; phy_addr <= endPhyAddr; phy_addr++) { #if !defined(CFG_JAC6) uint8 Status; uint16 Reg1; uint16 Reg2; #if defined (CFG_AURIX) Eth_ReadMii(ctrlIdx,phy_addr, 2, &Reg1); Eth_ReadMii(ctrlIdx,phy_addr,3, &Reg2); /* change it */ Status= ETH_OK; #else Status = Eth_ReadMii(ctrlIdx,phy_addr, 2, &Reg1); Status |= Eth_ReadMii(ctrlIdx,phy_addr,3, &Reg2); /* change it */ #endif if ((Status == ETH_OK) && (Reg1 > 0x0000) && (Reg1 < 0xffff) && (Reg2 > 0x0000) && (Reg2 < 0xffff)) { return phy_addr; } #else for( uint32 i = 0; i < ETH_MDIO_WAIT_CYCLES; i++); /* Provide some time for MDIO module to find the PHYs available */ if(hwPtr->MDIO.MDIO_ALIVE & (0x1u << phy_addr)){ return phy_addr; } #endif } return phy_addr; } /** * Link Setting up - Needed to be called from a cyclic routine * precondition - phyAddress is valid * @param ctrlIdx * @return */ void Eth_TransHw_linkUp(uint8 ctrlIdx) { if(phyAddress != 32u){ uint16 statusValue = 0; #if defined(CFG_JAC6) || defined(CFG_TC29X) Eth_ReadMii(ctrlIdx,phyAddress,PHY_STATUS_REGISTER,&statusValue); if((statusValue & PHY_STATUS_LINK ) != 0){ linkStatus = LINK_UP; }else{ linkStatus = LINK_DOWN; } LwIpAdp_LinkStateUpdate(linkStatus); #else uint16 regValue; if(linkStatus == NO_LINK) { /* Set auto neg advert register */ (void)Eth_WriteMii(ctrlIdx,phyAddress, AUTONEG_ADVERTISE_REGISTER, 0x01e1); // Enable and start auto-negotiation Eth_ReadMii(ctrlIdx,phyAddress,BMCR_REGISTER, &regValue); Eth_WriteMii(ctrlIdx,phyAddress,BMCR_REGISTER, (regValue | 0x1200)); linkStatus = AUTONEGOTIATE_RESTART; } // Wait for Auto-Neg complete flag Eth_ReadMii(ctrlIdx,phyAddress,BMSR_REGISTER,&statusValue); if((statusValue & 0x0020 )== 0x0020){ linkStatus = AUTONEGOTIATE_COMPLETE; } Eth_ReadMii(ctrlIdx,phyAddress,PHY_STATUS_REGISTER,&statusValue); if((statusValue & PHY_STATUS_LINK ) != 0){ linkStatus = LINK_UP; }else{ linkStatus = LINK_DOWN; } LwIpAdp_LinkStateUpdate(linkStatus); #endif }else{ phyAddress = Eth_TransHw_findPhyAdrs(ETH_CTRL_INDEX,0,31); if(phyAddress != 0x00){ (void)Eth_TransHw_init(ETH_CTRL_INDEX); } } } /** * @brief Mock up function for ETH Tranceiver : Initialise tranciever required * @param ctrlIdx * @retval Std_ReturnType */ Std_ReturnType Eth_TransHw_init(uint8 ctrlIdx) { if(ethCtrlInitRun != TRUE){ /* Tranciever is initialised after Eth controller initialisation */ return E_NOT_OK; } #if defined(CFG_ETH_PHY_DP83848C) || defined(CFG_ETH_PHY_DP83865) || defined(CFG_ETH_PHY_TJA1100) uint16 phyStatus; uint16 timeout; #if defined(CFG_ETH_PHY_TJA1100) uint16 extdPhyStatus; #endif uint16 regValue; /* Wait for completion */ timeout = 10000; /* Reset phy */ (void)Eth_WriteMii(ctrlIdx,phyAddress, BMCR_REGISTER, PHY_SOFT_RESET); for(volatile uint16 i=0; i < 1000; i++){}; #if defined(CFG_JAC6) /* ETH_NO_AUTO_NEG */ hwPtr->MDIO.MDIO_USERPHYSEL0 |= GMAC_SW_MDIO_LINKSEL; hwPtr->MDIO.MDIO_USERPHYSEL0 |= (GMAC_SW_MDIO_PHYADDRMON_MASK & phyAddress); (void)Eth_ReadMii (ctrlIdx,phyAddress, BMCR_REGISTER, &regValue); regValue &= ~ENABLE_AUTO_NEGOTIATION; // disable AN (void)Eth_WriteMii(ctrlIdx,phyAddress, BMCR_REGISTER, (regValue | ENABLE_100MBPS_DUPLEX)); for(volatile uint16 i=0; i < ETH_MDIO_WAIT_CYCLES; i++){}; do { for(volatile uint16 i=0; i < ETH_MDIO_WAIT_CYCLES; i++){}; if ((timeout--) == 0) { return E_NOT_OK; } Eth_ReadMii(ctrlIdx,phyAddress, PHY_STATUS_REGISTER, &phyStatus); #if defined (CFG_ETH_PHY_TJA1100) Eth_ReadMii(ctrlIdx,phyAddress, PHY_EXTENDED_STATUS_REGISTER, &extdPhyStatus); #endif }while #if !defined (CFG_ETH_PHY_TJA1100) ((phyStatus & PHY_STATUS_NO_AUTO_100) != PHY_STATUS_NO_AUTO_100); #else (((phyStatus & PHY_STATUS_NO_AUTO_100) == 0u) && ((extdPhyStatus & PHY_EXTENDED_STATUS_NO_AUTO_100) != PHY_EXTENDED_STATUS_NO_AUTO_100)); #endif #else //CFG_JAC6(ETH_NO_AUTO_NEG) end #ifdef ETH_LINK_CHECK Eth_TransHw_linkUp(ctrlIdx); #else /* Set auto neg advert register */ (void)Eth_WriteMii(ctrlIdx,phyAddress, AUTONEG_ADVERTISE_REGISTER, 0x01e1); /* enable auto-negotiation */ (void)Eth_ReadMii (ctrlIdx,phyAddress, BMCR_REGISTER, &regValue); (void)Eth_WriteMii(ctrlIdx,phyAddress, BMCR_REGISTER, (regValue | 0x1200)); do { for(volatile uint16 i=0; i < 1000; i++){ } if ((timeout--) == 0) { return E_NOT_OK; } if (Eth_ReadMii(ctrlIdx,phyAddress, BMSR_REGISTER, &phyStatus) != 0) { return E_NOT_OK; } if(phyStatus == 0xffff){ return E_NOT_OK; } } while (!(phyStatus & 0x0020)); // Should be 0x786D #endif //ETH_LINK_CHECK end #endif /* Auto negotiate end */ #ifdef ETH_PHYLOOPBACK /* physical line test */ (void)Eth_ReadMii (ctrlIdx,phyAddress, BMCR_REGISTER, &regValue); (void)Eth_WriteMii(ctrlIdx,phyAddress, BMCR_REGISTER, (regValue | 0x6100)); // loopback with speed 100 do { for(volatile uint16 i=0; i < 1000; i++){}; if ((timeout--) == 0) { return E_NOT_OK; } Eth_ReadMii(ctrlIdx,phyAddress, PHY_STATUS_REGISTER, &phyStatus); }while (!(phyStatus & PHY_STATUS_LOOPBACK)); #endif /* physical line test */ #else /* other phy */ /* PHY device - MARVELL-88E1111 */ #define RGMII_TXRX_CLK_DELAY 0x0030 #define ASYMMETRIC_PAUSE 0x0800 #define PAUSE 0x0400 #define LINKSPEED_1000MBPS 0x0040 #define LINKSPEED_100MBPS 0x2000 #define LINKSPEED_10MBPS 0x0000 uint16 Val = 0; uint32_t i; enum{ ETH_SPEED_10MBPS, ETH_SPEED_100MBPS, ETH_SPEED_1000MBPS }; uint16 speed = ETH_SPEED_100MBPS; Eth_WriteMii(ctrlIdx,phyAddress, 22, 2); //page adres Eth_ReadMii(ctrlIdx,phyAddress,21, &Val); Val |= RGMII_TXRX_CLK_DELAY; Eth_WriteMii(ctrlIdx,phyAddress, 21, Val); Eth_WriteMii(ctrlIdx,phyAddress, 22, 0 );// page adrs Eth_ReadMii(ctrlIdx,phyAddress, AUTONEG_ADVERTISE_REGISTER, &Val); Val |= RGMII_TXRX_CLK_DELAY;/* ASYMMETRIC_PAUSE ?? */ Val |= PAUSE; Eth_WriteMii(ctrlIdx,phyAddress, AUTONEG_ADVERTISE_REGISTER, Val); Eth_ReadMii(ctrlIdx, phyAddress, BMCR_REGISTER, &Val); Val &= ~LINKSPEED_1000MBPS; Val &= ~LINKSPEED_100MBPS; Val &= ~LINKSPEED_10MBPS; if(speed == ETH_SPEED_100MBPS) { Val |= LINKSPEED_100MBPS; } else if (speed == ETH_SPEED_1000MBPS) { Val |= LINKSPEED_1000MBPS; } else { Val |= LINKSPEED_10MBPS; } Eth_WriteMii( ctrlIdx,phyAddress, 9, 0); /* Dont advertise PHY speed of 1000 Mbps */ Eth_WriteMii(ctrlIdx,phyAddress, AUTONEG_ADVERTISE_REGISTER, 0x0100 |0x0080); // don't advertise 100mbps full duplex and 100mbps half resp Eth_WriteMii(ctrlIdx,phyAddress,BMCR_REGISTER, Val | 0x8000); // reset mask added for ( i=0; i < 100000; i++); #endif #if 0 /* Speed is set statically and configured */ Eth_Hw_SetSpeed(speed); #endif linkStatus = LINK_UP; LwIpAdp_LinkStateUpdate(LINK_UP); ethTrcvInitRun = TRUE; return E_OK; } void EthIf_GetPhysAddr( uint8 CtrlIdx, uint8* PhysAddrPtr ){ uint8 macAddr[6] = ETH_MAC_ADDR; PhysAddrPtr[0] = macAddr[0]; PhysAddrPtr[1] = macAddr[1]; PhysAddrPtr[2] = macAddr[2]; PhysAddrPtr[3] = macAddr[3]; PhysAddrPtr[4] = macAddr[4]; PhysAddrPtr[5] = macAddr[5]; } Std_ReturnType EthIf_UpdatePhysAddrFilter( uint8 CtrlIdx, const uint8* PhysAddrPtr, Eth_FilterActionType Action ){ return E_NOT_OK; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/ethernetif.c
C
unknown
24,879
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #ifndef __ETHERNETIF_H__ #define __ETHERNETIF_H__ #include "lwip/err.h" #include "lwip/netif.h" err_t ethernetif_init(struct netif *netif); void ethernetif_pre_tcpip_init(void); void Ethernetif_RxFunc(void); void Eth_TransHw_linkUp(uint8 ctrlIdx); /* ASR EthIf mockers */ #include "Eth_GeneralTypes.h" /* EthIf controller IDs */ #define EthIfConf_EthIfController_EthIfController 0u void EthIf_GetPhysAddr( uint8 CtrlIdx, uint8* PhysAddrPtr ); Std_ReturnType EthIf_UpdatePhysAddrFilter( uint8 CtrlIdx, const uint8* PhysAddrPtr, Eth_FilterActionType Action ); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/ethernetif.h
C
unknown
1,350
#ifndef ETH_LWIPOPTS_H_ #define ETH_LWIPOPTS_H_ #include "stddef.h" #define LWIP_AR_MAJOR_VERSION 1 #define LWIP_AR_MINOR_VERSION 0 #define LWIP_AR_PATCH_VERSION 0 #define LWIP_SW_MAJOR_VERSION 1 #define LWIP_SW_MINOR_VERSION 0 #define LWIP_SW_PATCH_VERSION 0 /* New important lwip1.4.1 defines */ #define LWIP_TCPIP_CORE_LOCKING 1 #define LWIP_CHECKSUM_ON_COPY 0 #define LWIP_COMPAT_MUTEX_ALLOWED 1 #define LWIP_SOCKET_SET_ERRNO 0 #define TCPIP_MBOX_SIZE 50 #define MEMP_NUM_NETBUF 10 #define MEMP_NUM_TCPIP_MSG_INPKT 20 /* We want to be notified when the link changes status. */ #define LWIP_NETIF_STATUS_CALLBACK 1 /* Support IPV6(mandatory for doip) */ #define LWIP_IPV6 0 void * __memcpy(void * dst, void const * src,size_t len); #include "LwIp_Cfg.h" #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/lwipopts.h
C
unknown
847
/*-------------------------------- Arctic Core ------------------------------ * Copyright (C) 2013, ArcCore AB, Sweden, www.arccore.com. * Contact: <contact@arccore.com> * * You may ONLY use this file: * 1)if you have a valid commercial ArcCore license and then in accordance with * the terms contained in the written license agreement between you and ArcCore, * or alternatively * 2)if you follow the terms found in GNU General Public License version 2 as * published by the Free Software Foundation and appearing in the file * LICENSE.GPL included in the packaging of this file or here * <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt> *-------------------------------- Arctic Core -----------------------------*/ #include "lwipopts.h" #include "Std_types.h" void * __memcpy(void * dst, void const * src, size_t len) { uint8 * pDst = (uint8 *) dst; uint8 const * pSrc = (uint8 const *) src; while (len--) { *pDst++ = *pSrc++; } return (dst); }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/tc29x/memhdl.c
C
unknown
1,030
/************************************************************************* fsdata.c generator for UIP0.9 Works with cc65 C compiler Based on the work of Adam Dunkels <adam@dunkels.com> The syntax has been left as-is, with respect to the perl version Supports for a maximum of 2 levels directory and 999 files in each directory For more information, please go to http://www.design4fpga.com ALL RIGHTS RESERVED, COPYRIGHT APRIL 2006, DESIGN4FPGA *************************************************************************/ /************************************************************************* REDISTRIBUTION OF THIS PIECE OF SOFTWARE IN SOURCE OR AS A BINARY FILE IS PERMITTED IF AND ONLY IF THE FOLLOWING RULES ARE OBSERVED: 1) THE REDISTRIBUTION FILE OR ARCHIVE SHOULD INCLUDE THIS README FILE AS WELL AS THE COPYRIGHT NOTICE. BY USING THIS SOFTWARE, YOU ARE ACKNOWLEDGING THAT YOU HAVE READ AND AGREED WITH THE FOLLOWING DISCLAIMER AND THE COPYRIGHT NOTICE ABOVE. DISCLAIMER: THIS PIECE OF SOFTWARE IS SUPPLIED ''AS IS'', WE (DESIGN4FPGA) SHALL NOT BE HELD RESPONSIBLE OR LIABLE FOR ANY RESULTING EVENTS THAT MIGHT HAPPEN DURING THE USE OF THIS PROGRAM IN PARTICULAR: 1) THE LOSS OF INFORMATION DUE TO THE USE OR MISUSE OF FS_GENERATOR.EXE 2) THE LOSS OF BUSINESS, STOCKS, MONEY, PEOPLE AND LIVES OR ANY UNFORTUNATE CIRCUMSTANCE THAT MAY PREVAIL AS A RESULT OF A SYSTEM FAILURE, DIRECTLY OR INDIRECTLY DUE TO THE USE OF FS_GENERATOR.EXE *************************************************************************/ #include "fsdata.h" static const char data_arccore_html[] = { 0x2f,0x61,0x72,0x63,0x63,0x6f,0x72,0x65, 0x2e,0x68,0x74,0x6d,0x6c,0x00,0x48,0x54, 0x54,0x50,0x2f,0x31,0x2e,0x30,0x20,0x32, 0x30,0x30,0x20,0x4f,0x4b,0x0d,0x0a,0x53, 0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x75, 0x49,0x50,0x2f,0x30,0x2e,0x39,0x20,0x28, 0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x64, 0x75,0x6e,0x6b,0x65,0x6c,0x73,0x2e,0x63, 0x6f,0x6d,0x2f,0x61,0x64,0x61,0x6d,0x2f, 0x75,0x69,0x70,0x2f,0x29,0x0d,0x0a,0x43, 0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74, 0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78, 0x74,0x2f,0x68,0x74,0x6d,0x6c,0x0d,0x0a, 0x0d,0x0a,0x3c,0x68,0x74,0x6d,0x6c,0x3e, 0x0d,0x0a,0x3c,0x68,0x65,0x61,0x64,0x3e, 0x0d,0x0a,0x20,0x20,0x3c,0x74,0x69,0x74, 0x6c,0x65,0x3e,0x41,0x72,0x63,0x74,0x69, 0x63,0x43,0x6f,0x72,0x65,0x20,0x4c,0x77, 0x69,0x70,0x20,0x65,0x78,0x61,0x6d,0x70, 0x6c,0x65,0x20,0x62,0x79,0x20,0x6a,0x6f, 0x6e,0x74,0x65,0x3c,0x2f,0x74,0x69,0x74, 0x6c,0x65,0x3e,0x0d,0x0a,0x3c,0x2f,0x68, 0x65,0x61,0x64,0x3e,0x0d,0x0a,0x3c,0x62, 0x6f,0x64,0x79,0x3e,0x0d,0x0a,0x20,0x20, 0x3c,0x70,0x3e,0x43,0x6f,0x75,0x6c,0x64, 0x20,0x62,0x65,0x20,0x6d,0x6f,0x72,0x65, 0x20,0x66,0x61,0x6e,0x63,0x79,0x2e,0x2e, 0x2e,0x3c,0x2f,0x70,0x3e,0x0d,0x0a,0x3c, 0x2f,0x62,0x6f,0x64,0x79,0x3e,0x0d,0x0a, 0x3c,0x2f,0x68,0x74,0x6d,0x6c,0x3e,0x0d, 0x0a,}; const struct fsdata_file file_arccore_html[] = {{NULL, data_arccore_html, data_arccore_html + 14, sizeof(data_arccore_html) - 14}}; #define FS_ROOT file_arccore_html #define FS_NUMFILES 1
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/utils/fsdata.c
C
unknown
3,231
/* * Copyright (c) 2001, 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. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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> * * $Id: fsdata.h,v 1.4.2.1 2003/10/04 22:54:06 adam Exp $ */ #ifndef __FSDATA_H__ #define __FSDATA_H__ struct fsdata_file { const struct fsdata_file *next; const char *name; const char *data; const int len; }; struct fsdata_file_noconst { struct fsdata_file *next; char *name; char *data; int len; }; #endif /* __FSDATA_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/ArcticCore/utils/fsdata.h
C
unknown
2,099
# # Copyright (c) 2001, 2002 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> # # CONTRIBAPPFILES: Contrib Applications. CONTRIBAPPFILES=$(CONTRIBDIR)/apps/httpserver/httpserver-netconn.c \ $(CONTRIBDIR)/apps/chargen/chargen.c \ $(CONTRIBDIR)/apps/udpecho/udpecho.c \ $(CONTRIBDIR)/apps/tcpecho/tcpecho.c \ $(CONTRIBDIR)/apps/shell/shell.c \ $(CONTRIBDIR)/apps/udpecho_raw/udpecho_raw.c \ $(CONTRIBDIR)/apps/tcpecho_raw/tcpecho_raw.c \ $(CONTRIBDIR)/apps/netio/netio.c \ $(CONTRIBDIR)/apps/ping/ping.c \ $(CONTRIBDIR)/apps/shell/shell.c \ $(CONTRIBDIR)/apps/snmp_private_mib/lwip_prvmib.c \ $(CONTRIBDIR)/apps/smtp/smtp.c \ $(CONTRIBDIR)/apps/socket_examples/socket_examples.c \ $(CONTRIBDIR)/apps/rtp/rtp.c
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/Filelists.mk
Makefile
unknown
2,263
# # Copyright (c) 2001, 2002 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> # #CC=gcc #CC=clang CCDEP?=$(CC) CFLAGS=-g -Wall -DLWIP_DEBUG -pedantic -Werror \ -Wparentheses -Wsequence-point -Wswitch-default \ -Wextra -Wundef -Wshadow -Wpointer-arith -Wcast-qual \ -Wc++-compat -Wwrite-strings -Wold-style-definition -Wcast-align \ -Wmissing-prototypes -Wredundant-decls -Wnested-externs -Wno-address \ -Wunreachable-code -Wuninitialized ifeq (,$(findstring clang,$(CC))) CFLAGS:=$(CFLAGS) -Wlogical-op # if GCC is newer than 4.8/4.9 you may use: #CFLAGS:=$(CFLAGS) -fsanitize=address -fstack-protector -fstack-check -fsanitize=undefined -fno-sanitize=alignment else # we cannot sanitize alignment on x86-64 targets because clang wants 64 bit alignment CFLAGS:=$(CFLAGS) -fsanitize=address -fsanitize=undefined -fno-sanitize=alignment -Wdocumentation endif # not used for now but interesting: # -Wpacked # -ansi # -std=c89 LDFLAGS=-pthread -lutil -lrt CONTRIBDIR?=../../.. LWIPARCH=$(CONTRIBDIR)/ports/unix/port ARFLAGS=rs #Set this to where you have the lwip core module checked out from git #default assumes it's a dir named lwip at the same level as the contrib module LWIPDIR=$(CONTRIBDIR)/../lwip/src CFLAGS+=-I. \ -I$(CONTRIBDIR) \ -I$(LWIPDIR)/include \ -I$(LWIPARCH)/include include $(CONTRIBDIR)/ports/Filelists.mk include $(LWIPDIR)/Filelists.mk # ARCHFILES: architecture specific files. ARCHFILES=$(LWIPARCH)/perf.c $(LWIPARCH)/sys_arch.c $(LWIPARCH)/netif/tapif.c $(LWIPARCH)/netif/tunif.c \ $(LWIPARCH)/netif/unixif.c $(LWIPARCH)/netif/list.c $(LWIPARCH)/netif/tcpdump.c \ $(LWIPARCH)/netif/delif.c $(LWIPARCH)/netif/sio.c $(LWIPARCH)/netif/fifo.c LWIPFILES=$(LWIPNOAPPSFILES) $(ARCHFILES) LWIPOBJS=$(notdir $(LWIPFILES:.c=.o)) LWIPLIBCOMMON=liblwipcommon.a $(LWIPLIBCOMMON): $(LWIPOBJS) $(AR) $(ARFLAGS) $(LWIPLIBCOMMON) $? APPFILES=$(CONTRIBAPPFILES) $(LWIPAPPFILES) APPLIB=liblwipapps.a APPOBJS=$(notdir $(APPFILES:.c=.o)) $(APPLIB): $(APPOBJS) $(AR) $(ARFLAGS) $(APPLIB) $? %.o: $(CC) $(CFLAGS) -c $(<:.o=.c)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/Common.mk
Makefile
unknown
3,640
# # Copyright (c) 2001, 2002 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> # all compile: lwip_unittests .PHONY: all clean check include ../Common.mk LDFLAGS:=$(LDFLAGS) -lcheck -lm -lsubunit CFLAGS:=$(CFLAGS) -DLWIP_NOASSERT_ON_ERROR -I/usr/include/check -I$(LWIPDIR)/../test/unit CODEDIR=../../../../lwip TESTDIR=$(CODEDIR)/test/unit TESTFILES=$(TESTDIR)/lwip_unittests.c $(TESTDIR)/udp/test_udp.c $(TESTDIR)/etharp/test_etharp.c $(TESTDIR)/tcp/tcp_helper.c \ $(TESTDIR)/tcp/test_tcp_oos.c $(TESTDIR)/tcp/test_tcp.c $(TESTDIR)/core/test_mem.c $(TESTDIR)/dhcp/test_dhcp.c \ $(TESTDIR)/core/test_pbuf.c $(TESTDIR)/mdns/test_mdns.c TESTOBJS=$(notdir $(TESTFILES:.c=.o)) clean: @rm -f *.o $(LWIPLIBCOMMON) $(APPLIB) lwip_unittests *.s .depend* *.core core depend dep: .depend include .depend .depend: $(LWIPFILES) $(APPFILES) $(TESTFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend lwip_unittests: .depend $(TESTOBJS) $(LWIPLIBCOMMON) $(APPLIB) $(CC) $(CFLAGS) -o lwip_unittests $(TESTOBJS) -Wl,--start-group $(LWIPLIBCOMMON) $(APPLIB) $(LDFLAGS) -Wl,--end-group check: lwip_unittests @./lwip_unittests
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/check/Makefile
Makefile
unknown
2,689
# # Copyright (c) 2001, 2002 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> # all compile: lwip_fuzz .PHONY: all clean include ../Common.mk CC=afl-gcc LDFLAGS:=$(LDFLAGS) -lm CFLAGS:=$(CFLAGS) -O0 clean: rm -f *.o $(LWIPLIBCOMMON) lwip_fuzz *.s .depend* *.core core depend dep: .depend include .depend .depend: fuzz.c $(LWIPFILES) $(APPFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend lwip_fuzz: .depend $(LWIPLIBCOMMON) fuzz.o $(CC) $(CFLAGS) -o lwip_fuzz fuzz.o $(LWIPLIBCOMMON) $(LDFLAGS)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/fuzz/Makefile
Makefile
unknown
2,063
/* * Copyright (c) 2001-2003 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: Erik Ekman <erik.ekman@verisure.com> * */ #include "lwip/init.h" #include "lwip/netif.h" #include "netif/etharp.h" #if LWIP_IPV6 #include "lwip/ethip6.h" #include "lwip/nd6.h" #endif #include <string.h> #include <stdio.h> /* no-op send function */ static err_t lwip_tx_func(struct netif *netif, struct pbuf *p) { LWIP_UNUSED_ARG(netif); LWIP_UNUSED_ARG(p); return ERR_OK; } static err_t testif_init(struct netif *netif) { netif->name[0] = 'f'; netif->name[1] = 'z'; netif->output = etharp_output; netif->linkoutput = lwip_tx_func; netif->mtu = 1500; netif->hwaddr_len = 6; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; netif->hwaddr[0] = 0x00; netif->hwaddr[1] = 0x23; netif->hwaddr[2] = 0xC1; netif->hwaddr[3] = 0xDE; netif->hwaddr[4] = 0xD0; netif->hwaddr[5] = 0x0D; #if LWIP_IPV6 netif->output_ip6 = ethip6_output; netif->ip6_autoconfig_enabled = 1; netif_create_ip6_linklocal_address(netif, 1); netif->flags |= NETIF_FLAG_MLD6; #endif return ERR_OK; } static void input_pkt(struct netif *netif, const u8_t *data, size_t len) { struct pbuf *p, *q; err_t err; LWIP_ASSERT("pkt too big", len <= 0xFFFF); p = pbuf_alloc(PBUF_RAW, (u16_t)len, PBUF_POOL); LWIP_ASSERT("alloc failed", p); for(q = p; q != NULL; q = q->next) { MEMCPY(q->payload, data, q->len); data += q->len; } err = netif->input(p, netif); if (err != ERR_OK) { pbuf_free(p); } } int main(int argc, char** argv) { struct netif net_test; ip4_addr_t addr; ip4_addr_t netmask; ip4_addr_t gw; u8_t pktbuf[2000]; size_t len; lwip_init(); IP4_ADDR(&addr, 172, 30, 115, 84); IP4_ADDR(&netmask, 255, 255, 255, 0); IP4_ADDR(&gw, 172, 30, 115, 1); netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input); netif_set_up(&net_test); #if LWIP_IPV6 nd6_tmr(); /* tick nd to join multicast groups */ #endif if(argc > 1) { FILE* f; const char* filename; printf("reading input from file... "); fflush(stdout); filename = argv[1]; LWIP_ASSERT("invalid filename", filename != NULL); f = fopen(filename, "rb"); LWIP_ASSERT("open failed", f != NULL); len = fread(pktbuf, 1, sizeof(pktbuf), f); fclose(f); printf("testing file: \"%s\"...\r\n", filename); } else { len = fread(pktbuf, 1, sizeof(pktbuf), stdin); } input_pkt(&net_test, pktbuf, len); return 0; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/fuzz/fuzz.c
C
unknown
4,123
/* * Copyright (c) 2001-2003 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: Simon Goldschmidt * */ #ifndef LWIP_HDR_LWIPOPTS_H__ #define LWIP_HDR_LWIPOPTS_H__ /* Prevent having to link sys_arch.c (we don't test the API layers in unit tests) */ #define NO_SYS 1 #define LWIP_NETCONN 0 #define LWIP_SOCKET 0 #define SYS_LIGHTWEIGHT_PROT 0 #define LWIP_IPV6 1 #define IPV6_FRAG_COPYHEADER 1 #define LWIP_IPV6_DUP_DETECT_ATTEMPTS 0 /* Enable DHCP to test it */ #define LWIP_DHCP 1 /* Turn off checksum verification of fuzzed data */ #define CHECKSUM_CHECK_IP 0 #define CHECKSUM_CHECK_UDP 0 #define CHECKSUM_CHECK_TCP 0 #define CHECKSUM_CHECK_ICMP 0 #define CHECKSUM_CHECK_ICMP6 0 /* Minimal changes to opt.h required for tcp unit tests: */ #define MEM_SIZE 16000 #define TCP_SND_QUEUELEN 40 #define MEMP_NUM_TCP_SEG TCP_SND_QUEUELEN #define TCP_SND_BUF (12 * TCP_MSS) #define TCP_WND (10 * TCP_MSS) #define LWIP_WND_SCALE 1 #define TCP_RCV_SCALE 0 #define PBUF_POOL_SIZE 400 /* pbuf tests need ~200KByte */ /* Minimal changes to opt.h required for etharp unit tests: */ #define ETHARP_SUPPORT_STATIC_ENTRIES 1 #endif /* LWIP_HDR_LWIPOPTS_H__ */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/fuzz/lwipopts.h
C
unknown
3,061
#!/bin/bash if [ -z "$1" ] then echo "This script will make pcap files from the afl-fuzz crash/hang files" echo "It needs hexdump and text2pcap" echo "Please give output directory as argument" exit 2 fi for i in `ls $1/crashes/id*` do PCAPNAME=`echo $i | grep pcap` if [ -z "$PCAPNAME" ]; then hexdump -C $i > $1/$$.tmp text2pcap $1/$$.tmp ${i}.pcap fi done for i in `ls $1/hangs/id*` do PCAPNAME=`echo $i | grep pcap` if [ -z "$PCAPNAME" ]; then hexdump -C $i > $1/$$.tmp text2pcap $1/$$.tmp ${i}.pcap fi done rm -f $1/$$.tmp echo echo "Created pcap files:" ls $1/*/*.pcap
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/fuzz/output_to_pcap.sh
Shell
unknown
626
# # Copyright (c) 2001, 2002 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> # UNIXLIB=liblwip.a all: $(UNIXLIB) .PHONY: all include ../Common.mk CFLAGS+=-fPIC clean: rm -f *.o $(LWIPLIBCOMMON) *.s .depend* *.core core depend dep: .depend include .depend $(UNIXLIB): $(LWIPLIBCOMMON) unixlib.o $(CC) -g -nostartfiles -shared -o $@ $^ .depend: unixlib.c $(LWIPFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/lib/Makefile
Makefile
unknown
1,980
/** * @file * * lwIP Options Configuration */ /* * 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> * */ #ifndef LWIP_LWIPOPTS_H #define LWIP_LWIPOPTS_H /* * Include user defined options first. Anything not defined in these files * will be set to standard values. Override anything you dont like! */ #include "lwipopts.h" #include "lwip/debug.h" /* ----------------------------------------------- ---------- Platform specific locking ---------- ----------------------------------------------- */ /** * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain * critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #define SYS_LIGHTWEIGHT_PROT 0 /** * NO_SYS==1: Provides VERY minimal functionality. Otherwise, * use lwIP facilities. */ #define NO_SYS 0 /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ /** * MEM_ALIGNMENT: should be set to the alignment of the CPU * 4 byte alignment -> #define MEM_ALIGNMENT 4 * 2 byte alignment -> #define MEM_ALIGNMENT 2 */ #define MEM_ALIGNMENT 1 /** * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE 1600 /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ #define MEMP_NUM_PBUF 16 /** * MEMP_NUM_RAW_PCB: Number of raw connection PCBs * (requires the LWIP_RAW option) */ #define MEMP_NUM_RAW_PCB 4 /** * MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One * per active UDP "connection". * (requires the LWIP_UDP option) */ #define MEMP_NUM_UDP_PCB 4 /** * MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_PCB 4 /** * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_PCB_LISTEN 4 /** * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_SEG 16 /** * MEMP_NUM_REASSDATA: the number of simultaneously IP packets queued for * reassembly (whole packets, not fragments!) */ #define MEMP_NUM_REASSDATA 1 /** * MEMP_NUM_ARP_QUEUE: the number of simulateously queued outgoing * packets (pbufs) that are waiting for an ARP request (to resolve * their destination address) to finish. * (requires the ARP_QUEUEING option) */ #define MEMP_NUM_ARP_QUEUE 2 /** * MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. * (requires NO_SYS==0) */ #define MEMP_NUM_SYS_TIMEOUT 3 /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ #define MEMP_NUM_NETBUF 2 /** * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) */ #define MEMP_NUM_NETCONN 4 /** * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used * for callback/timeout API communication. * (only needed if you use tcpip.c) */ #define MEMP_NUM_TCPIP_MSG_API 8 /** * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used * for incoming packets. * (only needed if you use tcpip.c) */ #define MEMP_NUM_TCPIP_MSG_INPKT 8 /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ #define PBUF_POOL_SIZE 8 /* --------------------------------- ---------- ARP options ---------- --------------------------------- */ /** * LWIP_ARP==1: Enable ARP functionality. */ #define LWIP_ARP 1 /* -------------------------------- ---------- IP options ---------- -------------------------------- */ /** * IP_FORWARD==1: Enables the ability to forward IP packets across network * interfaces. If you are going to run lwIP on a device with only one network * interface, define this to 0. */ #define IP_FORWARD 0 /** * IP_OPTIONS: Defines the behavior for IP options. * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). */ #define IP_OPTIONS_ALLOWED 1 /** * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that * this option does not affect outgoing packet sizes, which can be controlled * via IP_FRAG. */ #define IP_REASSEMBLY 1 /** * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note * that this option does not affect incoming packet sizes, which can be * controlled via IP_REASSEMBLY. */ #define IP_FRAG 1 /** * IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally) * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived * in this time, the whole packet is discarded. */ #define IP_REASS_MAXAGE 3 /** * IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled. * Since the received pbufs are enqueued, be sure to configure * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * packets even if the maximum amount of fragments is enqueued for reassembly! */ #define IP_REASS_MAX_PBUFS 4 /** * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP * fragmentation. Otherwise pbufs are allocated and reference the original * packet data to be fragmented. */ #define IP_FRAG_USES_STATIC_BUF 0 /** * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. */ #define IP_DEFAULT_TTL 255 /* ---------------------------------- ---------- ICMP options ---------- ---------------------------------- */ /** * LWIP_ICMP==1: Enable ICMP module inside the IP stack. * Be careful, disable that make your product non-compliant to RFC1122 */ #define LWIP_ICMP 1 /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ #define LWIP_RAW 1 /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ /** * LWIP_DHCP==1: Enable DHCP module. */ #define LWIP_DHCP 0 /* ------------------------------------ ---------- AUTOIP options ---------- ------------------------------------ */ /** * LWIP_AUTOIP==1: Enable AUTOIP module. */ #define LWIP_AUTOIP 0 /* ---------------------------------- ---------- SNMP options ---------- ---------------------------------- */ /** * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP * transport. */ #define LWIP_SNMP 0 /* ---------------------------------- ---------- IGMP options ---------- ---------------------------------- */ /** * LWIP_IGMP==1: Turn on IGMP module. */ #define LWIP_IGMP 0 /* ---------------------------------- ---------- DNS options ----------- ---------------------------------- */ /** * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * transport. */ #define LWIP_DNS 0 /* --------------------------------- ---------- UDP options ---------- --------------------------------- */ /** * LWIP_UDP==1: Turn on UDP. */ #define LWIP_UDP 1 /* --------------------------------- ---------- TCP options ---------- --------------------------------- */ /** * LWIP_TCP==1: Turn on TCP. */ #define LWIP_TCP 1 #define LWIP_LISTEN_BACKLOG 0 /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ /** * PBUF_LINK_HLEN: the number of bytes that should be allocated for a * link level header. The default is 14, the standard value for * Ethernet. */ #define PBUF_LINK_HLEN 16 /** * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is * designed to accomodate single full size TCP frame in one pbuf, including * TCP_MSS, IP header, and link header. * */ #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN) /* ------------------------------------ ---------- LOOPIF options ---------- ------------------------------------ */ /** * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c */ #define LWIP_HAVE_LOOPIF 0 /* ---------------------------------------------- ---------- Sequential layer options ---------- ---------------------------------------------- */ /** * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */ #define LWIP_NETCONN 1 /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ #define LWIP_SOCKET 1 /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ #define LWIP_STATS 0 /* --------------------------------- ---------- PPP options ---------- --------------------------------- */ /** * PPP_SUPPORT==1: Enable PPP. */ #define PPP_SUPPORT 0 /* Misc */ #endif /* LWIP_LWIPOPTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/lib/lwipopts.h
C
unknown
12,226
/* * Copyright (c) 2001-2003 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. * * Author: Kieran Mansley <kjm25@cam.ac.uk> * * $Id: unixlib.c,v 1.10 2010/02/17 16:52:30 goldsimon Exp $ */ /*-----------------------------------------------------------------------------------*/ /* unixlib.c * * The initialisation functions for a shared library * * You may need to configure this file to your own needs - it is only an example * of how lwIP can be used as a self initialising shared library. * * In particular, you should change the gateway, ipaddr, and netmask to be the values * you would like the stack to use. */ /*-----------------------------------------------------------------------------------*/ #include "lwip/init.h" #include "lwip/sys.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/pbuf.h" #include "lwip/tcp.h" #include "lwip/tcpip.h" #include "lwip/netif.h" #include "lwip/stats.h" #include "lwip/sockets.h" #include "netif/tapif.h" struct netif netif; void _init(void); void _fini(void); static void tcpip_init_done(void *arg) { ip_addr_t ipaddr, netmask, gateway; sys_sem_t *sem; sem = (sys_sem_t *)arg; /* CHANGE THESE to suit your own network configuration: */ IP4_ADDR(&gateway, 192,168,1,1); IP4_ADDR(&ipaddr, 192,168,1,2); IP4_ADDR(&netmask, 255,255,255,0); netif_set_default(netif_add(&netif, &ipaddr, &netmask, &gateway, NULL, tapif_init, tcpip_input)); netif_set_up(&netif); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif, 1); #endif sys_sem_signal(sem); } void _init(void){ sys_sem_t sem; if(sys_sem_new(&sem, 0) != ERR_OK) { LWIP_ASSERT("failed to create semaphore", 0); } tcpip_init(tcpip_init_done, &sem); sys_sem_wait(&sem); sys_sem_free(&sem); } void _fini(void){ }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/lib/unixlib.c
C
unknown
3,338
# # Copyright (c) 2001, 2002 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> # all ipv4 compile: echop .PHONY: all include ../Common.mk clean: rm -f *.o $(LWIPLIBCOMMON) $(APPLIB) echop .depend* *.core core depend dep: .depend include .depend .depend: main.c $(LWIPFILES) $(APPFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend echop: .depend $(LWIPLIBCOMMON) $(APPLIB) main.o $(APPFILES) $(CC) $(CFLAGS) -o echop main.o -Wl,--start-group $(APPLIB) $(LWIPLIBCOMMON) -Wl,--end-group $(LDFLAGS)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/minimal/Makefile
Makefile
unknown
2,056
/** * @file * * lwIP Options Configuration */ /* * 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> * */ #ifndef LWIP_LWIPOPTS_H #define LWIP_LWIPOPTS_H /* ----------------------------------------------- ---------- Platform specific locking ---------- ----------------------------------------------- */ /** * NO_SYS==1: Provides VERY minimal functionality. Otherwise, * use lwIP facilities. */ #define NO_SYS 1 /** * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain * critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #define SYS_LIGHTWEIGHT_PROT 0 /* ------------------------------------ ---------- Memory options ---------- ------------------------------------ */ /** * MEM_ALIGNMENT: should be set to the alignment of the CPU * 4 byte alignment -> #define MEM_ALIGNMENT 4 * 2 byte alignment -> #define MEM_ALIGNMENT 2 */ #define MEM_ALIGNMENT 1 /** * MEM_SIZE: the size of the heap memory. If the application will send * a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE 16000 /* ------------------------------------------------ ---------- Internal Memory Pool Sizes ---------- ------------------------------------------------ */ /** * MEMP_NUM_PBUF: the number of memp struct pbufs (used for PBUF_ROM and PBUF_REF). * If the application sends a lot of data out of ROM (or other static memory), * this should be set high. */ #define MEMP_NUM_PBUF 30 /** * MEMP_NUM_RAW_PCB: Number of raw connection PCBs * (requires the LWIP_RAW option) */ #define MEMP_NUM_RAW_PCB 4 /** * MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One * per active UDP "connection". * (requires the LWIP_UDP option) */ #define MEMP_NUM_UDP_PCB 4 /** * MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_PCB 2 /** * MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_PCB_LISTEN 8 /** * MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. * (requires the LWIP_TCP option) */ #define MEMP_NUM_TCP_SEG 16 /** * MEMP_NUM_ARP_QUEUE: the number of simulateously queued outgoing * packets (pbufs) that are waiting for an ARP request (to resolve * their destination address) to finish. * (requires the ARP_QUEUEING option) */ #define MEMP_NUM_ARP_QUEUE 2 /** * MEMP_NUM_SYS_TIMEOUT: the number of simultaneously active timeouts. * The default number of timeouts is calculated here for all enabled modules. * The formula expects settings to be either '0' or '1'. * * To this default value, 1 was added for the snmp_increment timer. */ #define MEMP_NUM_SYS_TIMEOUT (LWIP_TCP + IP_REASSEMBLY + LWIP_ARP + (2*LWIP_DHCP) + LWIP_AUTOIP + LWIP_IGMP + LWIP_DNS + PPP_SUPPORT + (LWIP_IPV6 ? (1 + LWIP_IPV6_REASS + LWIP_IPV6_MLD) : 0)) + 1 /** * MEMP_NUM_NETBUF: the number of struct netbufs. * (only needed if you use the sequential API, like api_lib.c) */ #define MEMP_NUM_NETBUF 0 /** * MEMP_NUM_NETCONN: the number of struct netconns. * (only needed if you use the sequential API, like api_lib.c) */ #define MEMP_NUM_NETCONN 0 /** * MEMP_NUM_TCPIP_MSG_API: the number of struct tcpip_msg, which are used * for callback/timeout API communication. * (only needed if you use tcpip.c) */ #define MEMP_NUM_TCPIP_MSG_API 0 /** * MEMP_NUM_TCPIP_MSG_INPKT: the number of struct tcpip_msg, which are used * for incoming packets. * (only needed if you use tcpip.c) */ #define MEMP_NUM_TCPIP_MSG_INPKT 0 /** * PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ #define PBUF_POOL_SIZE 32 /* --------------------------------- ---------- ARP options ---------- --------------------------------- */ /** * LWIP_ARP==1: Enable ARP functionality. */ #define LWIP_ARP 1 /* -------------------------------- ---------- IP options ---------- -------------------------------- */ /** * IP_FORWARD==1: Enables the ability to forward IP packets across network * interfaces. If you are going to run lwIP on a device with only one network * interface, define this to 0. */ #define IP_FORWARD 0 /** * IP_OPTIONS: Defines the behavior for IP options. * IP_OPTIONS==0_ALLOWED: All packets with IP options are dropped. * IP_OPTIONS==1_ALLOWED: IP options are allowed (but not parsed). */ #define IP_OPTIONS_ALLOWED 1 /** * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that * this option does not affect outgoing packet sizes, which can be controlled * via IP_FRAG. */ #define IP_REASSEMBLY 1 /** * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note * that this option does not affect incoming packet sizes, which can be * controlled via IP_REASSEMBLY. */ #define IP_FRAG 1 /** * IP_REASS_MAXAGE: Maximum time (in multiples of IP_TMR_INTERVAL - so seconds, normally) * a fragmented IP packet waits for all fragments to arrive. If not all fragments arrived * in this time, the whole packet is discarded. */ #define IP_REASS_MAXAGE 3 /** * IP_REASS_MAX_PBUFS: Total maximum amount of pbufs waiting to be reassembled. * Since the received pbufs are enqueued, be sure to configure * PBUF_POOL_SIZE > IP_REASS_MAX_PBUFS so that the stack is still able to receive * packets even if the maximum amount of fragments is enqueued for reassembly! */ #define IP_REASS_MAX_PBUFS 10 /** * IP_FRAG_USES_STATIC_BUF==1: Use a static MTU-sized buffer for IP * fragmentation. Otherwise pbufs are allocated and reference the original * packet data to be fragmented. */ #define IP_FRAG_USES_STATIC_BUF 0 /** * IP_DEFAULT_TTL: Default value for Time-To-Live used by transport layers. */ #define IP_DEFAULT_TTL 255 /* ---------------------------------- ---------- ICMP options ---------- ---------------------------------- */ /** * LWIP_ICMP==1: Enable ICMP module inside the IP stack. * Be careful, disable that make your product non-compliant to RFC1122 */ #define LWIP_ICMP 1 /** * ICMP_TTL: Default value for Time-To-Live used by ICMP packets. */ #define ICMP_TTL (IP_DEFAULT_TTL) /* --------------------------------- ---------- RAW options ---------- --------------------------------- */ /** * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. */ #define LWIP_RAW 0 /* ---------------------------------- ---------- DHCP options ---------- ---------------------------------- */ /** * LWIP_DHCP==1: Enable DHCP module. */ #define LWIP_DHCP 0 /* ------------------------------------ ---------- AUTOIP options ---------- ------------------------------------ */ /** * LWIP_AUTOIP==1: Enable AUTOIP module. */ #define LWIP_AUTOIP 0 /* ---------------------------------- ---------- SNMP options ---------- ---------------------------------- */ /** * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP * transport. */ #define LWIP_SNMP 1 #define LWIP_MIB2_CALLBACKS 0 #define MIB2_STATS 1 /* ---------------------------------- ---------- IGMP options ---------- ---------------------------------- */ /** * LWIP_IGMP==1: Turn on IGMP module. */ #define LWIP_IGMP 0 /* ---------------------------------- ---------- DNS options ----------- ---------------------------------- */ /** * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS * transport. */ #define LWIP_DNS 0 /* --------------------------------- ---------- UDP options ---------- --------------------------------- */ /** * LWIP_UDP==1: Turn on UDP. */ #define LWIP_UDP 1 /** * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) */ #define LWIP_UDPLITE 0 /** * UDP_TTL: Default Time-To-Live value. */ #define UDP_TTL (IP_DEFAULT_TTL) /* --------------------------------- ---------- TCP options ---------- --------------------------------- */ /** * LWIP_TCP==1: Turn on TCP. */ #define LWIP_TCP 1 /* ---------------------------------- ---------- Pbuf options ---------- ---------------------------------- */ /** * PBUF_LINK_HLEN: the number of bytes that should be allocated for a * link level header. The default is 14, the standard value for * Ethernet. */ #define PBUF_LINK_HLEN 16 /* ------------------------------------ ---------- LOOPIF options ---------- ------------------------------------ */ /** * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c */ #define LWIP_HAVE_LOOPIF 0 /* ---------------------------------------------- ---------- Sequential layer options ---------- ---------------------------------------------- */ /** * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) */ #define LWIP_NETCONN 0 /* ------------------------------------ ---------- Socket options ---------- ------------------------------------ */ /** * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) */ #define LWIP_SOCKET 0 /* ---------------------------------------- ---------- Statistics options ---------- ---------------------------------------- */ /** * LWIP_STATS==1: Enable statistics collection in lwip_stats. */ #define LWIP_STATS 1 /* --------------------------------------- ---------- Debugging options ---------- --------------------------------------- */ #define TAPIF_DEBUG LWIP_DBG_ON #define TUNIF_DEBUG LWIP_DBG_OFF #define UNIXIF_DEBUG LWIP_DBG_OFF #define DELIF_DEBUG LWIP_DBG_OFF #define SIO_FIFO_DEBUG LWIP_DBG_OFF #define TCPDUMP_DEBUG LWIP_DBG_ON #define API_LIB_DEBUG LWIP_DBG_ON #define API_MSG_DEBUG LWIP_DBG_ON #define TCPIP_DEBUG LWIP_DBG_ON #define NETIF_DEBUG LWIP_DBG_ON #define SOCKETS_DEBUG LWIP_DBG_ON #define DEMO_DEBUG LWIP_DBG_ON #define IP_DEBUG LWIP_DBG_ON #define IP_REASS_DEBUG LWIP_DBG_ON #define RAW_DEBUG LWIP_DBG_ON #define ICMP_DEBUG LWIP_DBG_ON #define UDP_DEBUG LWIP_DBG_ON #define TCP_DEBUG LWIP_DBG_ON #define TCP_INPUT_DEBUG LWIP_DBG_ON #define TCP_OUTPUT_DEBUG LWIP_DBG_ON #define TCP_RTO_DEBUG LWIP_DBG_ON #define TCP_CWND_DEBUG LWIP_DBG_ON #define TCP_WND_DEBUG LWIP_DBG_ON #define TCP_FR_DEBUG LWIP_DBG_ON #define TCP_QLEN_DEBUG LWIP_DBG_ON #define TCP_RST_DEBUG LWIP_DBG_ON extern unsigned char debug_flags; #define LWIP_DBG_TYPES_ON debug_flags #endif /* LWIP_LWIPOPTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/minimal/lwipopts.h
C
unknown
13,289
/* * Copyright (c) 2001-2003 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> * RT timer modifications by Christiaan Simons */ #include <unistd.h> #include <getopt.h> #include "lwip/init.h" #include "lwip/debug.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/sys.h" #include "lwip/timeouts.h" #include "lwip/stats.h" #include "lwip/ip.h" #include "lwip/ip4_frag.h" #include "lwip/udp.h" #include "lwip/tcp.h" #include "netif/tapif.h" #include "netif/etharp.h" #include "lwip/apps/snmp.h" #include "lwip/apps/snmp_mib2.h" #include "apps/snmp_private_mib/private_mib.h" #include "apps/udpecho_raw/udpecho_raw.h" #include "apps/tcpecho_raw/tcpecho_raw.h" /* (manual) host IP configuration */ static ip4_addr_t ipaddr, netmask, gw; #if LWIP_SNMP /* SNMP trap destination cmd option */ static unsigned char trap_flag; static ip_addr_t trap_addr; static const struct snmp_mib *mibs[] = { &mib2, &mib_private }; #endif /* nonstatic debug cmd option, exported in lwipopts.h */ unsigned char debug_flags; #if LWIP_SNMP /* enable == 1, disable == 2 */ u8_t snmpauthentraps_set = 2; #endif static struct option longopts[] = { /* turn on debugging output (if build with LWIP_DEBUG) */ {"debug", no_argument, NULL, 'd'}, /* help */ {"help", no_argument, NULL, 'h'}, /* gateway address */ {"gateway", required_argument, NULL, 'g'}, /* ip address */ {"ipaddr", required_argument, NULL, 'i'}, /* netmask */ {"netmask", required_argument, NULL, 'm'}, /* ping destination */ {"trap_destination", required_argument, NULL, 't'}, /* new command line options go here! */ {NULL, 0, NULL, 0} }; #define NUM_OPTS ((sizeof(longopts) / sizeof(struct option)) - 1) static void usage(void) { unsigned char i; printf("options:\n"); for (i = 0; i < NUM_OPTS; i++) { printf("-%c --%s\n",longopts[i].val, longopts[i].name); } } int main(int argc, char **argv) { struct netif netif; int ch; char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0}; /* startup defaults (may be overridden by one or more opts) */ IP4_ADDR(&gw, 192,168,0,1); IP4_ADDR(&ipaddr, 192,168,0,2); IP4_ADDR(&netmask, 255,255,255,0); #if LWIP_SNMP trap_flag = 0; #endif /* use debug flags defined by debug.h */ debug_flags = LWIP_DBG_OFF; while ((ch = getopt_long(argc, argv, "dhg:i:m:t:", longopts, NULL)) != -1) { switch (ch) { case 'd': debug_flags |= (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH|LWIP_DBG_HALT); break; case 'h': usage(); exit(0); break; case 'g': ip4addr_aton(optarg, &gw); break; case 'i': ip4addr_aton(optarg, &ipaddr); break; case 'm': ip4addr_aton(optarg, &netmask); break; case 't': #if LWIP_SNMP trap_flag = !0; /* @todo: remove this authentraps tweak when we have proper SET & non-volatile mem */ snmpauthentraps_set = 1; ipaddr_aton(optarg, &trap_addr); strncpy(ip_str, ipaddr_ntoa(&trap_addr),sizeof(ip_str)); printf("SNMP trap destination %s\n", ip_str); #endif break; default: usage(); break; } } argc -= optind; argv += optind; strncpy(ip_str, ip4addr_ntoa(&ipaddr), sizeof(ip_str)); strncpy(nm_str, ip4addr_ntoa(&netmask), sizeof(nm_str)); strncpy(gw_str, ip4addr_ntoa(&gw), sizeof(gw_str)); printf("Host at %s mask %s gateway %s\n", ip_str, nm_str, gw_str); #ifdef PERF perf_init("/tmp/minimal.perf"); #endif /* PERF */ lwip_init(); printf("TCP/IP initialized.\n"); netif_add(&netif, &ipaddr, &netmask, &gw, NULL, tapif_init, ethernet_input); netif_set_default(&netif); netif_set_up(&netif); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif, 1); #endif #if LWIP_SNMP /* initialize our private example MIB */ lwip_privmib_init(); /* snmp_trap_dst_ip_set(0,&trap_addr); */ /* snmp_trap_dst_enable(0,trap_flag); */ #if SNMP_LWIP_MIB2 #if SNMP_USE_NETCONN snmp_threadsync_init(&snmp_mib2_lwip_locks, snmp_mib2_lwip_synchronizer); #endif snmp_mib2_set_syscontact_readonly((const u8_t*)"root", NULL); snmp_mib2_set_syslocation_readonly((const u8_t*)"lwIP development PC", NULL); snmp_mib2_set_sysdescr((const u8_t*)"minimal example", NULL); #endif /* SNMP_LWIP_MIB2 */ /* snmp_set_snmpenableauthentraps(&snmpauthentraps_set); */ snmp_set_mibs(mibs, LWIP_ARRAYSIZE(mibs)); snmp_init(); #endif /* LWIP_SNMP */ udpecho_raw_init(); tcpecho_raw_init(); printf("Applications started.\n"); while (1) { /* poll netif, pass packet to lwIP */ tapif_select(&netif); sys_check_timeouts(); } return 0; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/minimal/main.c
C
unknown
6,476
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_ARCH_CC_H #define LWIP_ARCH_CC_H /* see https://sourceforge.net/p/predef/wiki/OperatingSystems/ */ #if defined __ANDROID__ #define LWIP_UNIX_ANDROID #elif defined __linux__ #define LWIP_UNIX_LINUX #elif defined __APPLE__ #define LWIP_UNIX_MACH #elif defined __OpenBSD__ #define LWIP_UNIX_OPENBSD #elif defined __CYGWIN__ #define LWIP_UNIX_CYGWIN #endif /* Include some files for defining library routines */ #include <string.h> #include <sys/time.h> #include <limits.h> #define LWIP_TIMEVAL_PRIVATE 0 /* Define platform endianness */ #ifndef BYTE_ORDER #define BYTE_ORDER LITTLE_ENDIAN #endif /* BYTE_ORDER */ /* Compiler hints for packing structures */ #define PACK_STRUCT_FIELD(x) x #define PACK_STRUCT_STRUCT __attribute__((packed)) #define PACK_STRUCT_BEGIN #define PACK_STRUCT_END /* prototypes for printf() and abort() */ #include <stdio.h> #include <stdlib.h> /* Plaform specific diagnostic output */ #define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) #define LWIP_PLATFORM_ASSERT(x) do {printf("Assertion \"%s\" failed at line %d in %s\n", \ x, __LINE__, __FILE__); fflush(NULL); abort();} while(0) #ifdef LWIP_NOASSERT_ON_ERROR #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ handler;}} while(0) #endif #define LWIP_RAND() ((u32_t)rand()) #if defined(LWIP_UNIX_ANDROID) && defined(FD_SET) typedef __kernel_fd_set fd_set; #endif struct sio_status_s; typedef struct sio_status_s sio_status_t; #define sio_fd_t sio_status_t* #define __sio_fd_t_defined #endif /* LWIP_ARCH_CC_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/arch/cc.h
C
unknown
3,281
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_ARCH_PERF_H #define LWIP_ARCH_PERF_H #include <sys/times.h> #ifdef PERF #define PERF_START { \ unsigned long __c1l, __c1h, __c2l, __c2h; \ __asm__(".byte 0x0f, 0x31" : "=a" (__c1l), "=d" (__c1h)) #define PERF_STOP(x) __asm__(".byte 0x0f, 0x31" : "=a" (__c2l), "=d" (__c2h)); \ perf_print(__c1l, __c1h, __c2l, __c2h, x);} /*#define PERF_START do { \ struct tms __perf_start, __perf_end; \ times(&__perf_start) #define PERF_STOP(x) times(&__perf_end); \ perf_print_times(&__perf_start, &__perf_end, x);\ } while(0)*/ #else /* PERF */ #define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */ #endif /* PERF */ void perf_print(unsigned long c1l, unsigned long c1h, unsigned long c2l, unsigned long c2h, char *key); void perf_print_times(struct tms *start, struct tms *end, char *key); void perf_init(char *fname); #endif /* LWIP_ARCH_PERF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/arch/perf.h
C
unknown
2,726
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_ARCH_SYS_ARCH_H #define LWIP_ARCH_SYS_ARCH_H #include <errno.h> #define SYS_MBOX_NULL NULL #define SYS_SEM_NULL NULL typedef u32_t sys_prot_t; struct sys_sem; typedef struct sys_sem * sys_sem_t; #define sys_sem_valid(sem) (((sem) != NULL) && (*(sem) != NULL)) #define sys_sem_set_invalid(sem) do { if((sem) != NULL) { *(sem) = NULL; }}while(0) struct sys_mutex; typedef struct sys_mutex * sys_mutex_t; #define sys_mutex_valid(mutex) sys_sem_valid(mutex) #define sys_mutex_set_invalid(mutex) sys_sem_set_invalid(mutex) struct sys_mbox; typedef struct sys_mbox * sys_mbox_t; #define sys_mbox_valid(mbox) sys_sem_valid(mbox) #define sys_mbox_set_invalid(mbox) sys_sem_set_invalid(mbox) struct sys_thread; typedef struct sys_thread * sys_thread_t; #endif /* LWIP_ARCH_SYS_ARCH_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/arch/sys_arch.h
C
unknown
2,488
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_DELIF_H #define LWIP_DELIF_H #include "lwip/netif.h" #include "lwip/pbuf.h" err_t delif_init(struct netif *netif); err_t delif_init_thread(struct netif *netif); #endif /* LWIP_DELIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/delif.h
C
unknown
1,854
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_DROPIF_H #define LWIP_DROPIF_H #include "lwip/netif.h" #include "lwip/pbuf.h" err_t dropif_init(struct netif *netif); #endif /* LWIP_DROPIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/dropif.h
C
unknown
1,811
#ifndef FIFO_H #define FIFO_H #include "lwip/sys.h" /** How many bytes in fifo */ #define FIFOSIZE 2048 /** fifo data structure, this one is passed to all fifo functions */ typedef struct fifo_t { u8_t data[FIFOSIZE+10]; /* data segment, +10 is a hack probably not needed.. FIXME! */ int dataslot; /* index to next char to be read */ int emptyslot; /* index to next empty slot */ int len; /* len probably not needed, may be calculated from dataslot and emptyslot in conjunction with FIFOSIZE */ sys_sem_t sem; /* semaphore protecting simultaneous data manipulation */ sys_sem_t getSem; /* sepaphore used to signal new data if getWaiting is set */ u8_t getWaiting; /* flag used to indicate that fifoget is waiting for data. fifoput is suposed to clear */ /* this flag prior to signaling the getSem semaphore */ } fifo_t; /** * Get a character from fifo * Blocking call. * @param fifo pointer to fifo data structure * @return character read from fifo */ u8_t fifoGet(fifo_t * fifo); /** * Get a character from fifo * Non blocking call. * @param fifo pointer to fifo data structure * @return character read from fifo, or < zero if non was available */ s16_t fifoGetNonBlock(fifo_t * fifo); /** * fifoput is called by the signalhandler when new data has arrived (or some other event is indicated) * fifoput reads directly from the serialport and is thus highly dependent on unix arch at this moment * @param fifo pointer to fifo data structure * @param fd unix file descriptor */ void fifoPut(fifo_t * fifo, int fd); /** * fifoinit initiate fifo * @param fifo pointer to fifo data structure, allocated by the user */ void fifoInit(fifo_t * fifo); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/fifo.h
C
unknown
1,768
#ifndef LWIP_LIST_H #define LWIP_LIST_H struct elem; struct list { struct elem *first, *last; int size, elems; }; struct elem { struct elem *next; void *data; }; struct list *list_new(int size); int list_push(struct list *list, void *data); void *list_pop(struct list *list); void *list_first(struct list *list); int list_elems(struct list *list); void list_delete(struct list *list); int list_remove(struct list *list, void *elem); void list_map(struct list *list, void (* func)(void *arg)); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/list.h
C
unknown
540
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_PCAPIF_H #define LWIP_PCAPIF_H #include "lwip/netif.h" err_t pcapif_init(struct netif *netif); #endif /* LWIP_PCAPIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/pcapif.h
C
unknown
1,785
#ifndef SIO_UNIX_H #define SIO_UNIX_H #include "lwip/sys.h" #include "lwip/netif.h" #include "netif/fifo.h" /*#include "netif/pppif.h"*/ struct sio_status_s { int fd; fifo_t myfifo; }; /* BAUDRATE is defined in sio.c as it is implementation specific */ /** Baudrates */ typedef enum sioBaudrates { SIO_BAUD_9600, SIO_BAUD_19200, SIO_BAUD_38400, SIO_BAUD_57600, SIO_BAUD_115200 } sioBaudrates; /** * Poll for a new character from incoming data stream * @param siostat siostatus struct, contains sio instance data, given by sio_open * @return char read from input stream, or < 0 if no char was available */ s16_t sio_poll(sio_status_t * siostat); /** * Parse incoming characters until a string str is recieved, blocking call * @param str zero terminated string to expect * @param siostat siostatus struct, contains sio instance data, given by sio_open */ void sio_expect_string(u8_t *str, sio_status_t * siostat); /** * Write a char to output data stream * @param str pointer to a zero terminated string * @param siostat siostatus struct, contains sio instance data, given by sio_open */ void sio_send_string(u8_t *str, sio_status_t * siostat); /** * Flush outbuffer (send everything in buffer now), useful if some layer below is * holding on to data, waitng to fill a buffer * @param siostat siostatus struct, contains sio instance data, given by sio_open */ void sio_flush( sio_status_t * siostat ); /** * Change baudrate of port, may close and reopen port * @param baud new baudrate * @param siostat siostatus struct, contains sio instance data, given by sio_open */ void sio_change_baud( sioBaudrates baud, sio_status_t * siostat ); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/sio.h
C
unknown
1,731
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_TAPIF_H #define LWIP_TAPIF_H #include "lwip/netif.h" err_t tapif_init(struct netif *netif); #if NO_SYS int tapif_select(struct netif *netif); #endif /* NO_SYS */ #endif /* LWIP_TAPIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/tapif.h
C
unknown
1,840
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_NETIF_TCPDUMP_H #define LWIP_NETIF_TCPDUMP_H #include "lwip/pbuf.h" void tcpdump_init(void); void tcpdump(struct pbuf *p); #endif /* LWIP_NETIF_TCPDUMP_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/tcpdump.h
C
unknown
1,821
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_TUNIF_H #define LWIP_TUNIF_H #include "lwip/netif.h" #include "lwip/pbuf.h" err_t tunif_init(struct netif *netif); #endif /* LWIP_TUNIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/tunif.h
C
unknown
1,807
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_UNIXIF_H #define LWIP_UNIXIF_H #include "lwip/netif.h" err_t unixif_init_server(struct netif *netif); err_t unixif_init_client(struct netif *netif); #endif /* LWIP_UNIXIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/include/netif/unixif.h
C
unknown
1,840
/* * Copyright (c) 2001-2003 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 "lwip/opt.h" #include "lwip/pbuf.h" #if !NO_SYS #include "lwip/debug.h" #include <stdlib.h> #include "lwip/def.h" #include "netif/delif.h" #ifdef LWIP_UNIX_LINUX #include "netif/tapif.h" #else /* LWIP_UNIX_LINUX */ #include "netif/tunif.h" #endif /* LWIP_UNIX_LINUX */ #include "lwip/sys.h" #include "lwip/timeouts.h" #ifndef DELIF_DEBUG #define DELIF_DEBUG LWIP_DBG_OFF #endif #define DELIF_INPUT_DROPRATE 0.1 #define DELIF_OUTPUT_DROPRATE 0.1 #define DELIF_INPUT_DELAY 500 /* Miliseconds. */ #define DELIF_OUTPUT_DELAY 500 /* Miliseconds. */ #define DELIF_TIMEOUT 10 struct delif { err_t (* input)(struct pbuf *p, struct netif *inp); struct netif *netif; }; struct delif_pbuf { struct delif_pbuf *next; struct pbuf *p; ip_addr_t ipaddr; unsigned int time; }; static struct delif_pbuf *input_list = NULL; static struct delif_pbuf *output_list = NULL; /*-----------------------------------------------------------------------------------*/ static void delif_input_timeout(void *arg) { struct netif *netif; struct delif *delif; struct delif_pbuf *dp; unsigned int timeout, now; timeout = DELIF_TIMEOUT; netif = (struct netif*)arg; delif = (struct delif*)netif->state; /* Check if there is anything on the input list. */ dp = input_list; while (dp != NULL) { now = sys_now(); if (dp->time <= now) { delif->input(dp->p, netif); if (dp->next != NULL) { if (dp->next->time > now) { timeout = dp->next->time - now; } else { timeout = 0; } LWIP_DEBUGF(DELIF_DEBUG, ("delif_output_timeout: timeout %u.\n", timeout)); } input_list = dp->next; free(dp); dp = input_list; } else { dp = dp->next; } } sys_timeout(timeout, delif_input_timeout, arg); } /*-----------------------------------------------------------------------------------*/ static void delif_output_timeout(void *arg) { struct netif *netif; struct delif *delif; struct delif_pbuf *dp; unsigned int timeout, now; timeout = DELIF_TIMEOUT; netif = (struct netif*)arg; delif = (struct delif*)netif->state; /* Check if there is anything on the output list. */ dp = output_list; while (dp != NULL) { now = sys_now(); if (dp->time <= now) { LWIP_DEBUGF(DELIF_DEBUG, ("delif_output_timeout: now %u dp->time %u\n", now, dp->time)); #if LWIP_IPV4 if(!IP_IS_V6_VAL(dp->ipaddr)) { delif->netif->output(delif->netif, dp->p, ip_2_ip4(&dp->ipaddr)); } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 if(IP_IS_V6_VAL(dp->ipaddr)) { delif->netif->output_ip6(delif->netif, dp->p, ip_2_ip6(&dp->ipaddr)); } #endif /* LWIP_IPV6 */ if (dp->next != NULL) { if (dp->next->time > now) { timeout = dp->next->time - now; } else { timeout = 0; } LWIP_DEBUGF(DELIF_DEBUG, ("delif_output_timeout: timeout %u.\n", timeout)); } pbuf_free(dp->p); output_list = dp->next; free(dp); dp = output_list; } else { dp = dp->next; } } sys_timeout(timeout, delif_output_timeout, arg); } /*-----------------------------------------------------------------------------------*/ static err_t delif_output(struct netif *netif, struct pbuf *p, const ip_addr_t *ipaddr) { struct delif_pbuf *dp, *np; char *data; LWIP_UNUSED_ARG(netif); LWIP_DEBUGF(DELIF_DEBUG, ("delif_output\n")); #ifdef DELIF_OUTPUT_DROPRATE if (((double)rand()/(double)RAND_MAX) < DELIF_OUTPUT_DROPRATE) { LWIP_DEBUGF(DELIF_DEBUG, ("delif_output: Packet dropped\n")); return ERR_BUF; } #endif /* DELIF_OUTPUT_DROPRATE */ LWIP_DEBUGF(DELIF_DEBUG, ("delif_output\n")); dp = (struct delif_pbuf*)malloc(sizeof(struct delif_pbuf)); data = (char*)malloc(p->tot_len); pbuf_copy_partial(p, data, p->tot_len, 0); dp->p = pbuf_alloc(PBUF_LINK, 0, PBUF_ROM); dp->p->payload = data; dp->p->len = p->tot_len; dp->p->tot_len = p->tot_len; dp->ipaddr = *ipaddr; dp->time = sys_now() + DELIF_OUTPUT_DELAY; dp->next = NULL; if (output_list == NULL) { output_list = dp; } else { for(np = output_list; np->next != NULL; np = np->next); np->next = dp; } return ERR_OK; } #if LWIP_IPV4 static err_t delif_output4(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr) { ip_addr_t ip; if (ipaddr != NULL) { ip_addr_copy_from_ip4(ip, *ipaddr); } else { ip = *IP_ADDR_ANY; } return delif_output(netif, p, &ip); } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 static err_t delif_output6(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr) { ip_addr_t ip; if (ipaddr != NULL) { ip_addr_copy_from_ip6(ip, *ipaddr); } else { ip = *IP6_ADDR_ANY; } return delif_output(netif, p, &ip); } #endif /* LWIP_IPV6 */ /*-----------------------------------------------------------------------------------*/ static err_t delif_input(struct pbuf *p, struct netif *inp) { struct delif_pbuf *dp, *np; LWIP_UNUSED_ARG(inp); LWIP_DEBUGF(DELIF_DEBUG, ("delif_input\n")); #ifdef DELIF_INPUT_DROPRATE if (((double)rand()/(double)RAND_MAX) < DELIF_INPUT_DROPRATE) { LWIP_DEBUGF(DELIF_DEBUG, ("delif_input: Packet dropped\n")); pbuf_free(p); return ERR_OK; } #endif /* DELIF_INPUT_DROPRATE */ dp = (struct delif_pbuf*)malloc(sizeof(struct delif_pbuf)); dp->p = p; dp->time = sys_now() + DELIF_INPUT_DELAY; dp->next = NULL; if (input_list == NULL) { input_list = dp; } else { for(np = input_list; np->next != NULL; np = np->next); np->next = dp; } return ERR_OK; } /*-----------------------------------------------------------------------------------*/ err_t delif_init(struct netif *netif) { struct delif *del; del = (struct delif*)malloc(sizeof(struct delif)); if (!del) { return ERR_MEM; } netif->state = del; netif->name[0] = 'd'; netif->name[1] = 'e'; #if LWIP_IPV4 netif->output = delif_output4; #endif /* LWIP_IPV4 */ #if LWIP_IPV6 netif->output_ip6 = delif_output6; #endif /* LWIP_IPV6 */ del->netif = (struct netif*)malloc(sizeof(struct netif)); if (!del->netif) { free(del); return ERR_MEM; } #ifdef LWIP_UNIX_LINUX tapif_init(del->netif); #else /* LWIP_UNIX_LINUX */ tunif_init(del->netif); #endif /* LWIP_UNIX_LINUX */ del->input = netif->input; del->netif->input = delif_input; sys_timeout(DELIF_TIMEOUT, delif_input_timeout, netif); sys_timeout(DELIF_TIMEOUT, delif_output_timeout, netif); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ static void delif_thread(void *arg) { struct netif *netif = (struct netif*)arg; struct delif *del; sys_sem_t sem; del = (struct delif*)netif->state; #ifdef LWIP_UNIX_LINUX tapif_init(del->netif); #else /* LWIP_UNIX_LINUX */ tunif_init(del->netif); #endif /* LWIP_UNIX_LINUX */ sys_timeout(DELIF_TIMEOUT, delif_input_timeout, netif); sys_timeout(DELIF_TIMEOUT, delif_output_timeout, netif); if(sys_sem_new(&sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } sys_sem_wait(&sem); } /*-----------------------------------------------------------------------------------*/ err_t delif_init_thread(struct netif *netif) { struct delif *del; LWIP_DEBUGF(DELIF_DEBUG, ("delif_init_thread\n")); del = (struct delif*)malloc(sizeof(struct delif)); if (!del) { return ERR_MEM; } netif->state = del; netif->name[0] = 'd'; netif->name[1] = 'e'; del->netif = (struct netif*)malloc(sizeof(struct netif)); if (!del->netif) { free(del); return ERR_MEM; } #if LWIP_IPV4 netif->output = delif_output4; netif_set_ipaddr(del->netif, netif_ip4_addr(netif)); netif_set_gw(del->netif, netif_ip4_gw(netif)); netif_set_netmask(del->netif, netif_ip4_netmask(netif)); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 { int i; netif->output_ip6 = delif_output6; for(i=0; i < LWIP_IPV6_NUM_ADDRESSES; i++) { netif_ip6_addr_set(del->netif, i, netif_ip6_addr(netif, i)); } } #endif /* LWIP_IPV6 */ del->input = netif->input; del->netif->input = delif_input; sys_thread_new("delif_thread", delif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ #endif /* !NO_SYS */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/delif.c
C
unknown
10,418
/* Author: Magnus Ivarsson <magnus.ivarsson@volvo.com> */ /* ---------------------------------------------- */ /* --- fifo 4 unix ------------------------------ */ /* ---------------------------------------------- */ #include "lwip/err.h" #include "netif/fifo.h" #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/arch.h" #include <unistd.h> #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif #ifndef SIO_FIFO_DEBUG #define SIO_FIFO_DEBUG LWIP_DBG_OFF #endif u8_t fifoGet(fifo_t * fifo) { u8_t c; sys_sem_wait(&fifo->sem); /* enter critical section */ if (fifo->dataslot == fifo->emptyslot) { fifo->getWaiting = TRUE; /* tell putFifo to signal us when data is available */ sys_sem_signal(&fifo->sem); /* leave critical section (allow input from serial port..) */ sys_sem_wait(&fifo->getSem); /* wait 4 data */ sys_sem_wait(&fifo->sem); /* reenter critical section */ } c = fifo->data[fifo->dataslot++]; fifo->len--; if (fifo->dataslot == FIFOSIZE) { fifo->dataslot = 0; } sys_sem_signal(&fifo->sem); /* leave critical section */ return c; } s16_t fifoGetNonBlock(fifo_t * fifo) { u16_t c; sys_sem_wait(&fifo->sem); /* enter critical section */ if (fifo->dataslot == fifo->emptyslot) { /* empty fifo */ c = -1; } else { c = fifo->data[fifo->dataslot++]; fifo->len--; if (fifo->dataslot == FIFOSIZE) { fifo->dataslot = 0; } } sys_sem_signal(&fifo->sem); /* leave critical section */ return c; } void fifoPut(fifo_t * fifo, int fd) { /* FIXME: mutex around struct data.. */ int cnt=0; sys_sem_wait(&fifo->sem ); /* enter critical */ LWIP_DEBUGF( SIO_FIFO_DEBUG,("fifoput: len%d dat%d empt%d --> ", fifo->len, fifo->dataslot, fifo->emptyslot ) ); if ( fifo->emptyslot < fifo->dataslot ) { cnt = read( fd, &fifo->data[fifo->emptyslot], fifo->dataslot - fifo->emptyslot ); } else { cnt = read( fd, &fifo->data[fifo->emptyslot], FIFOSIZE-fifo->emptyslot ); } fifo->emptyslot += cnt; fifo->len += cnt; LWIP_DEBUGF( SIO_FIFO_DEBUG,("len%d dat%d empt%d\n", fifo->len, fifo->dataslot, fifo->emptyslot ) ); if ( fifo->len > FIFOSIZE ) { printf( "ERROR: fifo overrun detected len=%d, flushing\n", fifo->len ); fifo->dataslot = 0; fifo->emptyslot = 0; fifo->len = 0; } if ( fifo->emptyslot == FIFOSIZE ) { fifo->emptyslot = 0; LWIP_DEBUGF( SIO_FIFO_DEBUG, ("(WRAP) ") ); sys_sem_signal(&fifo->sem ); /* leave critical */ fifoPut( fifo, fd ); return; } if ( fifo->getWaiting ) { fifo->getWaiting = FALSE; sys_sem_signal(&fifo->getSem ); } sys_sem_signal(&fifo->sem ); /* leave critical */ return; } void fifoInit(fifo_t * fifo) { fifo->dataslot = 0; fifo->emptyslot = 0; fifo->len = 0; if(sys_sem_new(&fifo->sem, 1) != ERR_OK) { /* critical section 1=free to enter */ LWIP_ASSERT("Failed to create semaphore", 0); } if(sys_sem_new(&fifo->getSem, 0) != ERR_OK) { /* 0 = no one waiting */ LWIP_ASSERT("Failed to create semaphore", 0); } fifo->getWaiting = FALSE; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/fifo.c
C
unknown
3,282
/* * Copyright (c) 2001-2003 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 <stdlib.h> #include <netif/list.h> /*-----------------------------------------------------------------------------------*/ struct list * list_new(int size) { struct list *list; list = (struct list *)malloc(sizeof(struct list)); list->first = list->last = NULL; list->size = size; list->elems = 0; return list; } /*-----------------------------------------------------------------------------------*/ int list_push(struct list *list, void *data) { struct elem *elem; if (list->elems < list->size) { elem = (struct elem *)malloc(sizeof(struct elem)); elem->data = data; elem->next = NULL; if (list->last != NULL) { list->last->next = elem; } list->last = elem; if (list->first == NULL) { list->first = elem; } list->elems++; return 1; } return 0; } /*-----------------------------------------------------------------------------------*/ void * list_pop(struct list *list) { struct elem *elem; void *data; if (list->elems > 0) { elem = list->first; if (elem == list->last) { list->last = elem->next; } list->first = elem->next; list->elems--; data = elem->data; free(elem); return data; } return NULL; } /*-----------------------------------------------------------------------------------*/ void * list_first(struct list *list) { return list->first; } /*-----------------------------------------------------------------------------------*/ int list_elems(struct list *list) { return list->elems; } /*-----------------------------------------------------------------------------------*/ void list_delete(struct list *list) { while (list_pop(list) != NULL); free(list); } /*-----------------------------------------------------------------------------------*/ int list_remove(struct list *list, void *elem) { struct elem *e, *p; p = NULL; for(e = list->first; e != NULL; e = e->next) { if (e->data == elem) { if (p != NULL) { p->next = e->next; } else { list->first = e->next; } if (list->last == e) { list->last = p; if (p != NULL) { p->next = NULL; } } free(e); list->elems--; return 1; } p = e; } return 0; } /*-----------------------------------------------------------------------------------*/ void list_map(struct list *list, void (* func)(void *arg)) { struct elem *e; for(e = list->first; e != NULL; e = e->next) { func(e->data); } } /*-----------------------------------------------------------------------------------*/
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/list.c
C
unknown
4,368
/* * Copyright (c) 2001-2003 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> * */ #ifndef linux /* Apparently, this doesn't work under Linux. */ #include "lwip/debug.h" #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pcap.h> #include "netif/etharp.h" #include "lwip/stats.h" #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "netif/unixif.h" #include "lwip/sys.h" #include "lwip/ip.h" #if defined(LWIP_DEBUG) && defined(LWIP_TCPDUMP) #include "netif/tcpdump.h" #endif /* LWIP_DEBUG && LWIP_TCPDUMP */ struct pcapif { pcap_t *pd; sys_sem_t sem; u8_t pkt[2048]; u32_t len; u32_t lasttime; struct pbuf *p; struct eth_addr *ethaddr; }; static char errbuf[PCAP_ERRBUF_SIZE]; /*-----------------------------------------------------------------------------------*/ static err_t pcapif_output(struct netif *netif, struct pbuf *p, ip_addr_t *ipaddr) { return ERR_OK; } /*-----------------------------------------------------------------------------------*/ static void timeout(void *arg) { struct netif *netif; struct pcapif *pcapif; struct pbuf *p; struct eth_hdr *ethhdr; netif = (struct netif *)arg; pcapif = netif->state; ethhdr = (struct eth_hdr *)pcapif->pkt; if (lwip_htons(ethhdr->type) != ETHTYPE_IP || ip_lookup(pcapif->pkt + 14, netif)) { /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_LINK, pcapif->len, PBUF_POOL); if (p != NULL) { pbuf_take(p, pcapif->pkt, pcapif->len); #if defined(LWIP_DEBUG) && defined(LWIP_TCPDUMP) tcpdump(p); #endif /* LWIP_DEBUG && LWIP_TCPDUMP */ ethhdr = p->payload; switch (lwip_htons(ethhdr->type)) { /* IP or ARP packet? */ case ETHTYPE_IP: case ETHTYPE_ARP: #if PPPOE_SUPPORT /* PPPoE packet? */ case ETHTYPE_PPPOEDISC: case ETHTYPE_PPPOE: #endif /* PPPOE_SUPPORT */ /* full packet send to tcpip_thread to process */ if (netif->input(p, netif) != ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n")); pbuf_free(p); p = NULL; } break; default: pbuf_free(p); break; } } } else { printf("ip_lookup dropped\n"); } sys_sem_signal(&pcapif->sem); } /*-----------------------------------------------------------------------------------*/ static void callback(u_char *arg, const struct pcap_pkthdr *hdr, const u_char *pkt) { struct netif *netif; struct pcapif *pcapif; u32_t time, lasttime; netif = (struct netif *)arg; pcapif = netif->state; pcapif->len = hdr->len; bcopy(pkt, pcapif->pkt, hdr->len); time = hdr->ts.tv_sec * 1000 + hdr->ts.tv_usec / 1000; lasttime = pcapif->lasttime; pcapif->lasttime = time; if (lasttime == 0) { sys_timeout(1000, timeout, netif); } else { sys_timeout(time - lasttime, timeout, netif); } } /*-----------------------------------------------------------------------------------*/ static void pcapif_thread(void *arg) { struct netif *netif; struct pcapif *pcapif; netif = arg; pcapif = netif->state; while (1) { pcap_loop(pcapif->pd, 1, callback, (u_char *)netif); sys_sem_wait(&pcapif->sem); if (pcapif->p != NULL) { netif->input(pcapif->p, netif); } } } /*-----------------------------------------------------------------------------------*/ err_t pcapif_init(struct netif *netif) { struct pcapif *p; p = malloc(sizeof(struct pcapif)); if (p == NULL) return ERR_MEM; netif->state = p; netif->name[0] = 'p'; netif->name[1] = 'c'; netif->output = pcapif_output; p->pd = pcap_open_offline("pcapdump", errbuf); if (p->pd == NULL) { printf("pcapif_init: failed %s\n", errbuf); return ERR_IF; } if(sys_sem_new(&p->sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } p->p = NULL; p->lasttime = 0; sys_thread_new("pcapif_thread", pcapif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ #endif /* linux */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/pcapif.c
C
unknown
6,106
/* Author: Magnus Ivarsson <magnus.ivarsson@volvo.com> */ /* to get rid of implicit function declarations */ #define _XOPEN_SOURCE 600 #define _GNU_SOURCE #include "netif/sio.h" #include "netif/fifo.h" #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/arch.h" #include "lwip/sio.h" #include "netif/ppp/ppp_opts.h" /* Following #undefs are here to keep compiler from issuing warnings about them being double defined. (They are defined in lwip/inet.h as well as the Unix #includes below.) */ #undef htonl #undef ntohl #undef htons #undef ntohs #undef HTONL #undef NTOHL #undef HTONS #undef NTOHS #include <stdlib.h> #include <stdio.h> #if defined(LWIP_UNIX_OPENBSD) #include <util.h> #endif #include <termios.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #include <sys/signal.h> #include <sys/types.h> #ifndef LWIP_HAVE_SLIPIF #define LWIP_HAVE_SLIPIF 0 #endif #if (PPP_SUPPORT || LWIP_HAVE_SLIPIF) && defined(LWIP_UNIX_LINUX) #include <pty.h> #endif /*#define BAUDRATE B19200 */ /*#define BAUDRATE B57600 */ #define BAUDRATE B115200 #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif /* for all of you who dont define SIO_DEBUG in debug.h */ #ifndef SIO_DEBUG #define SIO_DEBUG 0 #endif /* typedef struct siostruct_t */ /* { */ /* sio_status_t *sio; */ /* } siostruct_t; */ /** array of ((siostruct*)netif->state)->sio structs */ static sio_status_t statusar[4]; #if ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) /* --private-functions----------------------------------------------------------------- */ /** * Signal handler for ttyXX0 to indicate bytes received * one per interface is needed since we cannot send a instance number / pointer as callback argument (?) */ static void signal_handler_IO_0( int status ) { LWIP_UNUSED_ARG(status); LWIP_DEBUGF(SIO_DEBUG, ("SigHand: rxSignal channel 0\n")); fifoPut( &statusar[0].myfifo, statusar[0].fd ); } /** * Signal handler for ttyXX1 to indicate bytes received * one per interface is needed since we cannot send a instance number / pointer as callback argument (?) */ static void signal_handler_IO_1( int status ) { LWIP_UNUSED_ARG(status); LWIP_DEBUGF(SIO_DEBUG, ("SigHand: rxSignal channel 1\n")); fifoPut( &statusar[1].myfifo, statusar[1].fd ); } #endif /* ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) */ /** * Initiation of serial device * @param device string with the device name and path, eg. "/dev/ttyS0" * @param devnum device number * @param siostat status * @return file handle to serial dev. */ static int sio_init( char * device, int devnum, sio_status_t * siostat ) { struct termios oldtio,newtio; #if ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) struct sigaction saio; /* definition of signal action */ #endif int fd; LWIP_UNUSED_ARG(siostat); LWIP_UNUSED_ARG(devnum); /* open the device to be non-blocking (read will return immediately) */ fd = open( device, O_RDWR | O_NOCTTY | O_NONBLOCK ); if ( fd < 0 ) { perror( device ); exit( -1 ); } #if ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) /* install the signal handler before making the device asynchronous */ switch ( devnum ) { case 0: LWIP_DEBUGF( SIO_DEBUG, ("sioinit, signal_handler_IO_0\n") ); saio.sa_handler = signal_handler_IO_0; break; case 1: LWIP_DEBUGF( SIO_DEBUG, ("sioinit, signal_handler_IO_1\n") ); saio.sa_handler = signal_handler_IO_1; break; default: LWIP_DEBUGF( SIO_DEBUG,("sioinit, devnum not allowed\n") ); break; } saio.sa_flags = 0; #if defined(LWIP_UNIX_LINUX) saio.sa_restorer = NULL; #endif /* LWIP_UNIX_LINUX */ sigaction( SIGIO,&saio,NULL ); /* allow the process to receive SIGIO */ if ( fcntl( fd, F_SETOWN, getpid( ) ) != 0) { perror( device ); exit( -1 ); } /* Make the file descriptor asynchronous (the manual page says only O_APPEND and O_NONBLOCK, will work with F_SETFL...) */ if ( fcntl( fd, F_SETFL, FASYNC ) != 0) { perror( device ); exit( -1 ); } #else if ( fcntl( fd, F_SETFL, 0 ) != 0) { perror( device ); exit( -1 ); } #endif /* ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) */ tcgetattr( fd,&oldtio ); /* save current port settings */ /* set new port settings */ /* see 'man termios' for further settings */ memset(&newtio, 0, sizeof(newtio)); newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD | CRTSCTS; newtio.c_iflag = 0; newtio.c_oflag = 0; newtio.c_lflag = 0; /*ECHO; */ newtio.c_cc[VMIN] = 1; /* Read 1 byte at a time, no timer */ newtio.c_cc[VTIME] = 0; tcsetattr( fd,TCSANOW,&newtio ); tcflush( fd, TCIOFLUSH ); return fd; } /** * */ static void sio_speed( int fd, int speed ) { struct termios oldtio,newtio; /* int fd; */ LWIP_DEBUGF(SIO_DEBUG, ("sio_speed[%d]: baudcode:%d enter\n", fd, speed)); if ( fd < 0 ) { LWIP_DEBUGF(SIO_DEBUG, ("sio_speed[%d]: fd ERROR\n", fd)); exit( -1 ); } tcgetattr( fd,&oldtio ); /* get current port settings */ /* set new port settings * see 'man termios' for further settings */ memset(&newtio, 0, sizeof(newtio)); newtio.c_cflag = speed | CS8 | CLOCAL | CREAD; /* | CRTSCTS; */ newtio.c_iflag = 0; newtio.c_oflag = 0; newtio.c_lflag = 0; /*ECHO; */ newtio.c_cc[VMIN] = 1; /* Read 1 byte at a time, no timer */ newtio.c_cc[VTIME] = 0; tcsetattr( fd,TCSANOW,&newtio ); tcflush( fd, TCIOFLUSH ); LWIP_DEBUGF(SIO_DEBUG, ("sio_speed[%d]: leave\n", fd)); } /* --public-functions----------------------------------------------------------------------------- */ void sio_send( u8_t c, sio_status_t * siostat ) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio; */ if ( write( siostat->fd, &c, 1 ) <= 0 ) { LWIP_DEBUGF(SIO_DEBUG, ("sio_send[%d]: write refused\n", siostat->fd)); } } void sio_send_string( u8_t *str, sio_status_t * siostat ) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio; */ int len = strlen( (const char *)str ); if ( write( siostat->fd, str, len ) <= 0 ) { LWIP_DEBUGF(SIO_DEBUG, ("sio_send_string[%d]: write refused\n", siostat->fd)); } LWIP_DEBUGF(SIO_DEBUG, ("sio_send_string[%d]: sent: %s\n", siostat->fd, str)); } void sio_flush( sio_status_t * siostat ) { LWIP_UNUSED_ARG(siostat); /* not implemented in unix as it is not needed */ /*sio_status_t * siostat = ((siostruct_t*)netif->state)->sio; */ } #if ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) /*u8_t sio_recv( struct netif * netif )*/ u8_t sio_recv( sio_status_t * siostat ) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio; */ return fifoGet( &(siostat->myfifo) ); } s16_t sio_poll(sio_status_t * siostat) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio;*/ return fifoGetNonBlock( &(siostat->myfifo) ); } void sio_expect_string( u8_t *str, sio_status_t * siostat ) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio;*/ u8_t c; int finger=0; LWIP_DEBUGF(SIO_DEBUG, ("sio_expect_string[%d]: %s\n", siostat->fd, str)); while ( 1 ) { c=fifoGet( &(siostat->myfifo) ); LWIP_DEBUGF(SIO_DEBUG, ("_%c", c)); if ( c==str[finger] ) { finger++; } else if ( finger > 0 ) { /*it might fit in the beginning? */ if ( str[0] == c ) { finger = 1; } } if ( 0 == str[finger] ) break; /* done, we have a match */ } LWIP_DEBUGF(SIO_DEBUG, ("sio_expect_string[%d]: [match]\n", siostat->fd)); } #endif /* ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) */ #if (PPP_SUPPORT || LWIP_HAVE_SLIPIF) u32_t sio_write(sio_status_t * siostat, u8_t *buf, u32_t size) { ssize_t wsz = write( siostat->fd, buf, size ); return wsz < 0 ? 0 : wsz; } u32_t sio_read(sio_status_t * siostat, u8_t *buf, u32_t size) { ssize_t rsz = read( siostat->fd, buf, size ); return rsz < 0 ? 0 : rsz; } void sio_read_abort(sio_status_t * siostat) { LWIP_UNUSED_ARG(siostat); printf("sio_read_abort[%d]: not yet implemented for unix\n", siostat->fd); } #endif /* (PPP_SUPPORT || LWIP_HAVE_SLIPIF) */ sio_fd_t sio_open(u8_t devnum) { char dev[20]; /* would be nice with dynamic memory alloc */ sio_status_t * siostate = &statusar[ devnum ]; /* siostruct_t * tmp; */ /* tmp = (siostruct_t*)(netif->state); */ /* tmp->sio = siostate; */ /* tmp = (siostruct_t*)(netif->state); */ /* ((sio_status_t*)(tmp->sio))->fd = 0; */ LWIP_DEBUGF(SIO_DEBUG, ("sio_open: for devnum %d\n", devnum)); #if ! (PPP_SUPPORT || LWIP_HAVE_SLIPIF) fifoInit( &siostate->myfifo ); #endif /* ! PPP_SUPPORT */ snprintf( dev, sizeof(dev), "/dev/ttyS%d", devnum ); if ( (devnum == 1) || (devnum == 0) ) { if ( ( siostate->fd = sio_init( dev, devnum, siostate ) ) == 0 ) { LWIP_DEBUGF(SIO_DEBUG, ("sio_open: ERROR opening serial device dev=%s\n", dev)); abort( ); return NULL; } LWIP_DEBUGF(SIO_DEBUG, ("sio_open[%d]: dev=%s open.\n", siostate->fd, dev)); } #if PPP_SUPPORT else if (devnum == 2) { pid_t childpid; char name[256]; childpid = forkpty(&siostate->fd, name, NULL, NULL); if(childpid < 0) { perror("forkpty"); exit (1); } if(childpid == 0) { execl("/usr/sbin/pppd", "pppd", "ms-dns", "198.168.100.7", "local", "crtscts", "debug", #ifdef LWIP_PPP_CHAP_TEST "auth", "require-chap", "remotename", "lwip", #else "noauth", #endif #if LWIP_IPV6 "+ipv6", #endif "192.168.1.1:192.168.1.2", NULL); perror("execl pppd"); exit (1); } else { LWIP_DEBUGF(SIO_DEBUG, ("sio_open[%d]: spawned pppd pid %d on %s\n", siostate->fd, childpid, name)); } } #endif #if LWIP_HAVE_SLIPIF else if (devnum == 3) { pid_t childpid; /* create PTY pair */ siostate->fd = posix_openpt(O_RDWR | O_NOCTTY); if (siostate->fd < 0) { perror("open pty master"); exit (1); } if (grantpt(siostate->fd) != 0) { perror("grant pty master"); exit (1); } if (unlockpt(siostate->fd) != 0) { perror("unlock pty master"); exit (1); } LWIP_DEBUGF(SIO_DEBUG, ("sio_open[%d]: for %s\n", siostate->fd, ptsname(siostate->fd))); /* fork for slattach */ childpid = fork(); if(childpid < 0) { perror("fork"); exit (1); } if(childpid == 0) { /* esteblish SLIP interface on host side connected to PTY slave */ execl("/sbin/slattach", "slattach", "-d", "-v", "-L", "-p", "slip", ptsname(siostate->fd), NULL); perror("execl slattach"); exit (1); } else { int ret; char buf[1024]; LWIP_DEBUGF(SIO_DEBUG, ("sio_open[%d]: spawned slattach pid %d on %s\n", siostate->fd, childpid, ptsname(siostate->fd))); /* wait a moment for slattach startup */ sleep(1); /* configure SLIP interface on host side as P2P interface */ snprintf(buf, sizeof(buf), "/sbin/ifconfig sl0 mtu %d %s pointopoint %s up", SLIP_MAX_SIZE, "192.168.2.1", "192.168.2.2"); LWIP_DEBUGF(SIO_DEBUG, ("sio_open[%d]: system(\"%s\");\n", siostate->fd, buf)); ret = system(buf); if (ret < 0) { perror("ifconfig failed"); exit(1); } } } #endif /* LWIP_HAVE_SLIPIF */ else { LWIP_DEBUGF(SIO_DEBUG, ("sio_open: device %s (%d) is not supported\n", dev, devnum)); return NULL; } return siostate; } /** * */ void sio_change_baud( sioBaudrates baud, sio_status_t * siostat ) { /* sio_status_t * siostat = ((siostruct_t*)netif->state)->sio;*/ LWIP_DEBUGF(SIO_DEBUG, ("sio_change_baud[%d]\n", siostat->fd)); switch ( baud ) { case SIO_BAUD_9600: sio_speed( siostat->fd, B9600 ); break; case SIO_BAUD_19200: sio_speed( siostat->fd, B19200 ); break; case SIO_BAUD_38400: sio_speed( siostat->fd, B38400 ); break; case SIO_BAUD_57600: sio_speed( siostat->fd, B57600 ); break; case SIO_BAUD_115200: sio_speed( siostat->fd, B115200 ); break; default: LWIP_DEBUGF(SIO_DEBUG, ("sio_change_baud[%d]: Unknown baudrate, code:%d\n", siostat->fd, baud)); break; } }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/sio.c
C
unknown
12,365
/* * Copyright (c) 2001-2003 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 <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/time.h> #include <sys/uio.h> #include <sys/socket.h> #include "lwip/opt.h" #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/ip.h" #include "lwip/mem.h" #include "lwip/stats.h" #include "lwip/snmp.h" #include "lwip/pbuf.h" #include "lwip/sys.h" #include "lwip/timeouts.h" #include "netif/etharp.h" #include "lwip/ethip6.h" #if defined(LWIP_DEBUG) && defined(LWIP_TCPDUMP) #include "netif/tcpdump.h" #endif /* LWIP_DEBUG && LWIP_TCPDUMP */ #include "netif/tapif.h" #define IFCONFIG_BIN "/sbin/ifconfig " #if defined(LWIP_UNIX_LINUX) #include <sys/ioctl.h> #include <linux/if.h> #include <linux/if_tun.h> /* * Creating a tap interface requires special privileges. If the interfaces * is created in advance with `tunctl -u <user>` it can be opened as a regular * user. The network must already be configured. If DEVTAP_IF is defined it * will be opened instead of creating a new tap device. * * You can also use PRECONFIGURED_TAPIF environment variable to do so. */ #ifndef DEVTAP_DEFAULT_IF #define DEVTAP_DEFAULT_IF "tap0" #endif #ifndef DEVTAP #define DEVTAP "/dev/net/tun" #endif #define NETMASK_ARGS "netmask %d.%d.%d.%d" #define IFCONFIG_ARGS "tap0 inet %d.%d.%d.%d " NETMASK_ARGS #elif defined(LWIP_UNIX_OPENBSD) #define DEVTAP "/dev/tun0" #define NETMASK_ARGS "netmask %d.%d.%d.%d" #define IFCONFIG_ARGS "tun0 inet %d.%d.%d.%d " NETMASK_ARGS " link0" #else /* others */ #define DEVTAP "/dev/tap0" #define NETMASK_ARGS "netmask %d.%d.%d.%d" #define IFCONFIG_ARGS "tap0 inet %d.%d.%d.%d " NETMASK_ARGS #endif /* Define those to better describe your network interface. */ #define IFNAME0 't' #define IFNAME1 'p' #ifndef TAPIF_DEBUG #define TAPIF_DEBUG LWIP_DBG_OFF #endif struct tapif { /* Add whatever per-interface state that is needed here. */ int fd; }; /* Forward declarations. */ static void tapif_input(struct netif *netif); #if !NO_SYS static void tapif_thread(void *arg); #endif /* !NO_SYS */ /*-----------------------------------------------------------------------------------*/ static void low_level_init(struct netif *netif) { struct tapif *tapif; #if LWIP_IPV4 int ret; char buf[1024]; #endif /* LWIP_IPV4 */ char *preconfigured_tapif = getenv("PRECONFIGURED_TAPIF"); tapif = (struct tapif *)netif->state; /* Obtain MAC address from network interface. */ /* (We just fake an address...) */ netif->hwaddr[0] = 0x02; netif->hwaddr[1] = 0x12; netif->hwaddr[2] = 0x34; netif->hwaddr[3] = 0x56; netif->hwaddr[4] = 0x78; netif->hwaddr[5] = 0xab; netif->hwaddr_len = 6; /* device capabilities */ netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP; tapif->fd = open(DEVTAP, O_RDWR); LWIP_DEBUGF(TAPIF_DEBUG, ("tapif_init: fd %d\n", tapif->fd)); if (tapif->fd == -1) { #ifdef LWIP_UNIX_LINUX perror("tapif_init: try running \"modprobe tun\" or rebuilding your kernel with CONFIG_TUN; cannot open "DEVTAP); #else /* LWIP_UNIX_LINUX */ perror("tapif_init: cannot open "DEVTAP); #endif /* LWIP_UNIX_LINUX */ exit(1); } #ifdef LWIP_UNIX_LINUX { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); if (preconfigured_tapif) { strncpy(ifr.ifr_name, preconfigured_tapif, sizeof(ifr.ifr_name)); } else { strncpy(ifr.ifr_name, DEVTAP_DEFAULT_IF, sizeof(ifr.ifr_name)); } ifr.ifr_name[sizeof(ifr.ifr_name)-1] = 0; /* ensure \0 termination */ ifr.ifr_flags = IFF_TAP|IFF_NO_PI; if (ioctl(tapif->fd, TUNSETIFF, (void *) &ifr) < 0) { perror("tapif_init: "DEVTAP" ioctl TUNSETIFF"); exit(1); } } #endif /* LWIP_UNIX_LINUX */ netif_set_link_up(netif); if (preconfigured_tapif == NULL) { #if LWIP_IPV4 snprintf(buf, 1024, IFCONFIG_BIN IFCONFIG_ARGS, ip4_addr1(netif_ip4_gw(netif)), ip4_addr2(netif_ip4_gw(netif)), ip4_addr3(netif_ip4_gw(netif)), ip4_addr4(netif_ip4_gw(netif)) #ifdef NETMASK_ARGS , ip4_addr1(netif_ip4_netmask(netif)), ip4_addr2(netif_ip4_netmask(netif)), ip4_addr3(netif_ip4_netmask(netif)), ip4_addr4(netif_ip4_netmask(netif)) #endif /* NETMASK_ARGS */ ); LWIP_DEBUGF(TAPIF_DEBUG, ("tapif_init: system(\"%s\");\n", buf)); ret = system(buf); if (ret < 0) { perror("ifconfig failed"); exit(1); } if (ret != 0) { printf("ifconfig returned %d\n", ret); } #else /* LWIP_IPV4 */ perror("todo: support IPv6 support for non-preconfigured tapif"); exit(1); #endif /* LWIP_IPV4 */ } #if !NO_SYS sys_thread_new("tapif_thread", tapif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); #endif /* !NO_SYS */ } /*-----------------------------------------------------------------------------------*/ /* * low_level_output(): * * Should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * */ /*-----------------------------------------------------------------------------------*/ static err_t low_level_output(struct netif *netif, struct pbuf *p) { struct tapif *tapif = (struct tapif *)netif->state; char buf[1514]; ssize_t written; #if 0 if (((double)rand()/(double)RAND_MAX) < 0.2) { printf("drop output\n"); return ERR_OK; } #endif /* initiate transfer(); */ pbuf_copy_partial(p, buf, p->tot_len, 0); /* signal that packet should be sent(); */ written = write(tapif->fd, buf, p->tot_len); if (written == -1) { MIB2_STATS_NETIF_INC(netif, ifoutdiscards); perror("tapif: write"); } else { MIB2_STATS_NETIF_ADD(netif, ifoutoctets, written); } return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* * low_level_input(): * * Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * */ /*-----------------------------------------------------------------------------------*/ static struct pbuf * low_level_input(struct netif *netif) { struct pbuf *p; u16_t len; char buf[1514]; struct tapif *tapif = (struct tapif *)netif->state; /* Obtain the size of the packet and put it into the "len" variable. */ len = read(tapif->fd, buf, sizeof(buf)); if (len == (u16_t)-1) { perror("read returned -1"); exit(1); } MIB2_STATS_NETIF_ADD(netif, ifinoctets, len); #if 0 if (((double)rand()/(double)RAND_MAX) < 0.2) { printf("drop\n"); return NULL; } #endif /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); if (p != NULL) { pbuf_take(p, buf, len); /* acknowledge that packet has been read(); */ } else { /* drop packet(); */ MIB2_STATS_NETIF_INC(netif, ifindiscards); LWIP_DEBUGF(NETIF_DEBUG, ("tapif_input: could not allocate pbuf\n")); } return p; } /*-----------------------------------------------------------------------------------*/ /* * tapif_input(): * * This function should be called when a packet is ready to be read * from the interface. It uses the function low_level_input() that * should handle the actual reception of bytes from the network * interface. * */ /*-----------------------------------------------------------------------------------*/ static void tapif_input(struct netif *netif) { struct pbuf *p = low_level_input(netif); if (p == NULL) { #if LINK_STATS LINK_STATS_INC(link.recv); #endif /* LINK_STATS */ LWIP_DEBUGF(TAPIF_DEBUG, ("tapif_input: low_level_input returned NULL\n")); return; } if (netif->input(p, netif) != ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("tapif_input: netif input error\n")); pbuf_free(p); } } /*-----------------------------------------------------------------------------------*/ /* * tapif_init(): * * Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * */ /*-----------------------------------------------------------------------------------*/ err_t tapif_init(struct netif *netif) { struct tapif *tapif = (struct tapif *)mem_malloc(sizeof(struct tapif)); if (tapif == NULL) { LWIP_DEBUGF(NETIF_DEBUG, ("tapif_init: out of memory for tapif\n")); return ERR_MEM; } netif->state = tapif; MIB2_INIT_NETIF(netif, snmp_ifType_other, 100000000); netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; #if LWIP_IPV4 netif->output = etharp_output; #endif /* LWIP_IPV4 */ #if LWIP_IPV6 netif->output_ip6 = ethip6_output; #endif /* LWIP_IPV6 */ netif->linkoutput = low_level_output; netif->mtu = 1500; low_level_init(netif); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ #if NO_SYS int tapif_select(struct netif *netif) { fd_set fdset; int ret; struct timeval tv; struct tapif *tapif; u32_t msecs = sys_timeouts_sleeptime(); tapif = (struct tapif *)netif->state; tv.tv_sec = msecs / 1000; tv.tv_usec = (msecs % 1000) * 1000; FD_ZERO(&fdset); FD_SET(tapif->fd, &fdset); ret = select(tapif->fd + 1, &fdset, NULL, NULL, &tv); if (ret > 0) { tapif_input(netif); } return ret; } #else /* NO_SYS */ static void tapif_thread(void *arg) { struct netif *netif; struct tapif *tapif; fd_set fdset; int ret; netif = (struct netif *)arg; tapif = (struct tapif *)netif->state; while(1) { FD_ZERO(&fdset); FD_SET(tapif->fd, &fdset); /* Wait for a packet to arrive. */ ret = select(tapif->fd + 1, &fdset, NULL, NULL, NULL); if(ret == 1) { /* Handle incoming packet. */ tapif_input(netif); } else if(ret == -1) { perror("tapif_thread: select"); } } } #endif /* NO_SYS */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/tapif.c
C
unknown
12,012
/* * Copyright (c) 2001-2003 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 <stdio.h> #include "lwip/opt.h" #if (LWIP_IPV4 || LWIP_IPV6) && LWIP_TCP /* @todo: fix IPv6 */ #include "netif/tcpdump.h" #include "lwip/ip.h" #include "lwip/ip4.h" #include "lwip/ip6.h" #include "lwip/ip_addr.h" #include "lwip/priv/tcp_priv.h" #include "lwip/udp.h" #include "lwip/inet.h" #include "lwip/inet_chksum.h" #ifndef TCPDUMP_DEBUG #define TCPDUMP_DEBUG LWIP_DBG_OFF #endif static FILE *file = NULL; /*-----------------------------------------------------------------------------------*/ void tcpdump_init(void) { #define TCPDUMP_FNAME "/tmp/tcpdump" file = fopen(TCPDUMP_FNAME, "w"); if (file == NULL) { perror("tcpdump_init: cannot open \""TCPDUMP_FNAME"\" for writing"); } LWIP_DEBUGF(TCPDUMP_DEBUG, ("tcpdump: file %s\n", TCPDUMP_FNAME)); } /*-----------------------------------------------------------------------------------*/ void tcpdump(struct pbuf *p) { #if LWIP_IPV4 ip_addr_t src, dst; struct ip_hdr *iphdr; #if LWIP_UDP struct udp_hdr *udphdr; #endif #if LWIP_TCP struct tcp_hdr *tcphdr; char flags[5]; int i; int len; int offset; #endif if (file == NULL) { return; } iphdr = (struct ip_hdr *)p->payload; #if LWIP_IPV6 if(IPH_V(iphdr) == 6) { struct ip6_hdr *ip6hdr = (struct ip6_hdr*)iphdr; ip_addr_copy_from_ip6(src, ip6hdr->src); ip_addr_copy_from_ip6(dst, ip6hdr->dest); fprintf(file, "%s > %s: (IPv6, unsupported) ", ip_ntoa(&src), ip_ntoa(&dst)); return; /* not supported */ } #endif if(IPH_V(iphdr) == 4) { ip_addr_copy_from_ip4(src, iphdr->src); ip_addr_copy_from_ip4(dst, iphdr->dest); } switch (IPH_PROTO(iphdr)) { #if LWIP_TCP case IP_PROTO_TCP: tcphdr = (struct tcp_hdr *)((char *)iphdr + IPH_HL(iphdr)); pbuf_header(p, -IP_HLEN); if (ip_chksum_pseudo(p, IP_PROTO_TCP, p->tot_len, &src, &dst) != 0) { LWIP_DEBUGF(TCPDUMP_DEBUG, ("tcpdump: IP checksum failed!\n")); /* fprintf(file, "chksum 0x%lx ", tcphdr->chksum); tcphdr->chksum = 0; fprintf(file, "should be 0x%lx ", inet_chksum_pseudo(p, (ip_addr_t *)&(iphdr->src), (ip_addr_t *)&(iphdr->dest), IP_PROTO_TCP, p->tot_len));*/ fprintf(file, "!chksum "); } i = 0; if (TCPH_FLAGS(tcphdr) & TCP_SYN) { flags[i++] = 'S'; } if (TCPH_FLAGS(tcphdr) & TCP_PSH) { flags[i++] = 'P'; } if (TCPH_FLAGS(tcphdr) & TCP_FIN) { flags[i++] = 'F'; } if (TCPH_FLAGS(tcphdr) & TCP_RST) { flags[i++] = 'R'; } if (i == 0) { flags[i++] = '.'; } flags[i++] = 0; fprintf(file, "%s.%u > %s.%u: ", ip_ntoa(&src), lwip_ntohs(tcphdr->src), ip_ntoa(&dst), lwip_ntohs(tcphdr->dest)); offset = TCPH_HDRLEN(tcphdr); len = lwip_ntohs(IPH_LEN(iphdr)) - offset * 4 - IP_HLEN; if (len != 0 || flags[0] != '.') { fprintf(file, "%s %u:%u(%u) ", flags, lwip_ntohl(tcphdr->seqno), lwip_ntohl(tcphdr->seqno) + len, len); } if (TCPH_FLAGS(tcphdr) & TCP_ACK) { fprintf(file, "ack %u ", lwip_ntohl(tcphdr->ackno)); } fprintf(file, "wnd %u\n", lwip_ntohs(tcphdr->wnd)); fflush(file); pbuf_header(p, IP_HLEN); break; #endif /* LWIP_TCP */ #if LWIP_UDP case IP_PROTO_UDP: udphdr = (struct udp_hdr *)((char *)iphdr + IPH_HL(iphdr)); pbuf_header(p, -IP_HLEN); if (ip_chksum_pseudo(p, IP_PROTO_UDP, p->tot_len, &src, &dst) != 0) { LWIP_DEBUGF(TCPDUMP_DEBUG, ("tcpdump: IP checksum failed!\n")); /* fprintf(file, "chksum 0x%lx ", tcphdr->chksum); tcphdr->chksum = 0; fprintf(file, "should be 0x%lx ", ip_chksum_pseudo(p, &src, &dst, IP_PROTO_TCP, p->tot_len));*/ fprintf(file, "!chksum "); } fprintf(file, "%s.%u > %s.%u: ", ip_ntoa(&src), lwip_ntohs(udphdr->src), ip_ntoa(&dst), lwip_ntohs(udphdr->dest)); fprintf(file, "U "); len = lwip_ntohs(IPH_LEN(iphdr)) - sizeof(struct udp_hdr) - IP_HLEN; fprintf(file, " %d\n", len); fflush(file); pbuf_header(p, IP_HLEN); break; #endif /* LWIP_UDP */ default: LWIP_DEBUGF(TCPDUMP_DEBUG, ("unhandled IP protocol: %d\n", (int)IPH_PROTO(iphdr))); break; } #else LWIP_UNUSED_ARG(p); #endif } #endif /* LWIP_IPV4 && LWIP_TCP */ /*-----------------------------------------------------------------------------------*/
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/tcpdump.c
C
unknown
6,243
/* * Copyright (c) 2001-2003 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 "netif/tunif.h" #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/socket.h> #include "lwip/debug.h" #include "lwip/opt.h" #include "lwip/def.h" #include "lwip/ip.h" #include "lwip/mem.h" #include "lwip/netif.h" #include "lwip/pbuf.h" #include "lwip/sys.h" #if LWIP_IPV4 /* @todo: IPv6 */ #if !NO_SYS #define IFNAME0 't' #define IFNAME1 'n' #ifndef TUNIF_DEBUG #define TUNIF_DEBUG LWIP_DBG_OFF #endif #define IFCONFIG_CALL "/sbin/ifconfig tun0 inet %d.%d.%d.%d %d.%d.%d.%d" struct tunif { /* Add whatever per-interface state that is needed here. */ int fd; }; /* Forward declarations. */ static void tunif_input(struct netif *netif); static err_t tunif_output(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr); static void tunif_thread(void *data); /*-----------------------------------------------------------------------------------*/ static void low_level_init(struct netif *netif) { struct tunif *tunif; char buf[sizeof(IFCONFIG_CALL) + 50]; tunif = (struct tunif *)netif->state; /* Obtain MAC address from network interface. */ /* Do whatever else is needed to initialize interface. */ tunif->fd = open("/dev/tun0", O_RDWR); LWIP_DEBUGF(TUNIF_DEBUG, ("tunif_init: fd %d\n", tunif->fd)); if (tunif->fd == -1) { perror("tunif_init"); exit(1); } sprintf(buf, IFCONFIG_CALL, ip4_addr1(netif_ip4_gw(netif)), ip4_addr2(netif_ip4_gw(netif)), ip4_addr3(netif_ip4_gw(netif)), ip4_addr4(netif_ip4_gw(netif)), ip4_addr1(netif_ip4_addr(netif)), ip4_addr2(netif_ip4_addr(netif)), ip4_addr3(netif_ip4_addr(netif)), ip4_addr4(netif_ip4_addr(netif))); LWIP_DEBUGF(TUNIF_DEBUG, ("tunif_init: system(\"%s\");\n", buf)); system(buf); sys_thread_new("tunif_thread", tunif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); } /*-----------------------------------------------------------------------------------*/ /* * low_level_output(): * * Should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * */ /*-----------------------------------------------------------------------------------*/ static err_t low_level_output(struct tunif *tunif, struct pbuf *p) { char buf[1500]; int rnd_val; /* initiate transfer(); */ rnd_val = rand(); if (((double)rnd_val/(double)RAND_MAX) < 0.4) { printf("drop\n"); return ERR_OK; } pbuf_copy_partial(p, buf, p->tot_len, 0); /* signal that packet should be sent(); */ if (write(tunif->fd, buf, p->tot_len) == -1) { perror("tunif: write"); } return ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* * low_level_input(): * * Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * */ /*-----------------------------------------------------------------------------------*/ static struct pbuf * low_level_input(struct tunif *tunif) { struct pbuf *p; ssize_t len; char buf[1500]; /* Obtain the size of the packet and put it into the "len" variable. */ len = read(tunif->fd, buf, sizeof(buf)); if((len <= 0) || (len > 0xffff)) { return NULL; } /* if (((double)rand()/(double)RAND_MAX) < 0.1) { printf("drop\n"); return NULL; }*/ /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_LINK, (u16_t)len, PBUF_POOL); if (p != NULL) { pbuf_take(p, buf, (u16_t)len); /* acknowledge that packet has been read(); */ } else { /* drop packet(); */ } return p; } /*-----------------------------------------------------------------------------------*/ static void tunif_thread(void *arg) { struct netif *netif; struct tunif *tunif; fd_set fdset; int ret; netif = (struct netif *)arg; tunif = (struct tunif *)netif->state; while (1) { FD_ZERO(&fdset); FD_SET(tunif->fd, &fdset); /* Wait for a packet to arrive. */ ret = select(tunif->fd + 1, &fdset, NULL, NULL, NULL); if (ret == 1) { /* Handle incoming packet. */ tunif_input(netif); } else if (ret == -1) { perror("tunif_thread: select"); } } } /*-----------------------------------------------------------------------------------*/ /* * tunif_output(): * * This function is called by the TCP/IP stack when an IP packet * should be sent. It calls the function called low_level_output() to * do the actuall transmission of the packet. * */ /*-----------------------------------------------------------------------------------*/ static err_t tunif_output(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr) { struct tunif *tunif; LWIP_UNUSED_ARG(ipaddr); tunif = (struct tunif *)netif->state; return low_level_output(tunif, p); } /*-----------------------------------------------------------------------------------*/ /* * tunif_input(): * * This function should be called when a packet is ready to be read * from the interface. It uses the function low_level_input() that * should handle the actual reception of bytes from the network * interface. * */ /*-----------------------------------------------------------------------------------*/ static void tunif_input(struct netif *netif) { struct tunif *tunif; struct pbuf *p; tunif = (struct tunif *)netif->state; p = low_level_input(tunif); if (p == NULL) { LWIP_DEBUGF(TUNIF_DEBUG, ("tunif_input: low_level_input returned NULL\n")); return; } #if 0 /* CS: ip_lookup() was removed */ if (ip_lookup(p->payload, netif)) { #endif netif->input(p, netif); #if 0 } #endif } /*-----------------------------------------------------------------------------------*/ /* * tunif_init(): * * Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * */ /*-----------------------------------------------------------------------------------*/ err_t tunif_init(struct netif *netif) { struct tunif *tunif; tunif = (struct tunif *)mem_malloc(sizeof(struct tunif)); if (!tunif) { return ERR_MEM; } netif->state = tunif; netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; netif->output = tunif_output; low_level_init(netif); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ #endif /* !NO_SYS */ #endif /* LWIP_IPV4 */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/tunif.c
C
unknown
8,606
/* * Copyright (c) 2001-2003 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 "lwip/debug.h" #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> /*#include <netinet/in.h> */ /*#include <arpa/inet.h> */ #include "lwip/stats.h" #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "netif/list.h" #include "netif/unixif.h" #include "lwip/sys.h" #include "lwip/timeouts.h" #if LWIP_IPV4 /* @todo: IPv6 */ #if !NO_SYS #include "netif/tcpdump.h" #define UNIXIF_BPS 512000 #define UNIXIF_QUEUELEN 6 /*#define UNIXIF_DROP_FIRST */ #ifndef UNIXIF_DEBUG #define UNIXIF_DEBUG LWIP_DBG_OFF #endif struct unixif_buf { struct pbuf *p; unsigned short len, tot_len; void *payload; }; struct unixif { int fd; sys_sem_t sem; struct list *q; }; static void unixif_thread(void *arg); static void unixif_thread2(void *arg); /*-----------------------------------------------------------------------------------*/ static int unix_socket_client(const char *name) { int fd; #if !defined(LWIP_UNIX_LINUX) && !defined(LWIP_UNIX_CYGWIN) && !defined(__CYGWIN__) int len; #endif struct sockaddr_un unix_addr; /* create a Unix domain stream socket */ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("unixif: unix_socket_client: socket"); return(-1); } /* fill socket address structure w/our address */ memset(&unix_addr, 0, sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; snprintf(unix_addr.sun_path, sizeof(unix_addr.sun_path), "%s%05d", "/var/tmp/", getpid()); #if !defined(LWIP_UNIX_LINUX) && !defined(LWIP_UNIX_CYGWIN) && !defined(__CYGWIN__) len = sizeof(unix_addr.sun_len) + sizeof(unix_addr.sun_family) + strlen(unix_addr.sun_path) + 1; unix_addr.sun_len = len; #endif /* LWIP_UNIX_LINUX */ unlink(unix_addr.sun_path); /* in case it already exists */ if (bind(fd, (struct sockaddr *) &unix_addr, sizeof(struct sockaddr_un)) < 0) { perror("unixif: unix_socket_client: socket"); return(-1); } if (chmod(unix_addr.sun_path, S_IRWXU | S_IRWXO) < 0) { perror("unixif: unix_socket_client: socket"); return(-1); } /* fill socket address structure w/server's addr */ memset(&unix_addr, 0, sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; strncpy(unix_addr.sun_path, name, sizeof(unix_addr.sun_path)); unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0; /* ensure \0 termination */ #if !defined(LWIP_UNIX_LINUX) && !defined(LWIP_UNIX_CYGWIN) && !defined(__CYGWIN__) len = sizeof(unix_addr.sun_len) + sizeof(unix_addr.sun_family) + strlen(unix_addr.sun_path) + 1; unix_addr.sun_len = len; #endif /* LWIP_UNIX_LINUX */ if (connect(fd, (struct sockaddr *) &unix_addr, sizeof(struct sockaddr_un)) < 0) { perror("unixif: unix_socket_client: socket"); return(-1); } return(fd); } /*-----------------------------------------------------------------------------------*/ static int unix_socket_server(const char *name) { int fd; #if !defined(LWIP_UNIX_LINUX) && !defined(LWIP_UNIX_CYGWIN) && !defined(__CYGWIN__) int len; #endif struct sockaddr_un unix_addr; /* create a Unix domain stream socket */ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("unixif: unix_socket_server: socket"); return(-1); } unlink(name); /* in case it already exists */ /* fill in socket address structure */ memset(&unix_addr, 0, sizeof(unix_addr)); unix_addr.sun_family = AF_UNIX; strncpy(unix_addr.sun_path, name, sizeof(unix_addr.sun_path)); unix_addr.sun_path[sizeof(unix_addr.sun_path)-1] = 0; /* ensure \0 termination */ #if !defined(LWIP_UNIX_LINUX) && !defined(LWIP_UNIX_CYGWIN) && !defined(__CYGWIN__) len = sizeof(unix_addr.sun_len) + sizeof(unix_addr.sun_family) + strlen(unix_addr.sun_path) + 1; unix_addr.sun_len = len; #endif /* LWIP_UNIX_LINUX */ /* bind the name to the descriptor */ if (bind(fd, (struct sockaddr *) &unix_addr, sizeof(struct sockaddr_un)) < 0) { perror("unixif: unix_socket_server: bind"); return(-1); } if (chmod(unix_addr.sun_path, S_IRWXU | S_IRWXO) < 0) { perror("unixif: unix_socket_server: chmod"); return(-1); } if (listen(fd, 5) < 0) { /* tell kernel we're a server */ perror("unixif: unix_socket_server: listen"); return(-1); } return(fd); } /*-----------------------------------------------------------------------------------*/ static void unixif_input_handler(void *data) { struct netif *netif; struct unixif *unixif; char buf[1532]; int len, plen; struct pbuf *p; netif = (struct netif *)data; unixif = (struct unixif *)netif->state; len = read(unixif->fd, &plen, sizeof(int)); if (len == -1) { perror("unixif_irq_handler: read"); abort(); } LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_irq_handler: len == %d plen == %d bytes\n", len, plen)); if (len == sizeof(int)) { if (plen < 20 || plen > 1500) { LWIP_DEBUGF(UNIXIF_DEBUG, ("plen %d!\n", plen)); return; } len = read(unixif->fd, buf, plen); if (len == -1) { perror("unixif_irq_handler: read"); abort(); } LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_irq_handler: read %d bytes\n", len)); p = pbuf_alloc(PBUF_LINK, len, PBUF_POOL); if (p != NULL) { pbuf_take(p, buf, len); pbuf_realloc(p, len); LINK_STATS_INC(link.recv); #if LWIP_IPV4 && LWIP_TCP tcpdump(p); #endif netif->input(p, netif); } else { LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_irq_handler: could not allocate pbuf\n")); } } } /*-----------------------------------------------------------------------------------*/ static void unixif_thread(void *arg) { struct netif *netif; struct unixif *unixif; LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_thread: started.\n")); netif = (struct netif *)arg; unixif = (struct unixif *)netif->state; while (1) { sys_sem_wait(&unixif->sem); unixif_input_handler(netif); } } /*-----------------------------------------------------------------------------------*/ static void unixif_thread2(void *arg) { struct netif *netif; struct unixif *unixif; fd_set fdset; LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_thread2: started.\n")); netif = (struct netif *)arg; unixif = (struct unixif *)netif->state; while (1) { FD_ZERO(&fdset); FD_SET(unixif->fd, &fdset); if (select(unixif->fd + 1, &fdset, NULL, NULL, NULL) > 0) { sys_sem_signal(&unixif->sem); } } } /*-----------------------------------------------------------------------------------*/ static void unixif_output_timeout(void *arg); static err_t unixif_output(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr) { struct unixif *unixif; struct unixif_buf *buf; LWIP_UNUSED_ARG(ipaddr); unixif = (struct unixif *)netif->state; buf = (struct unixif_buf *)malloc(sizeof(struct unixif_buf)); buf->p = p; buf->len = p->len; buf->tot_len = p->tot_len; buf->payload = p->payload; if (list_elems(unixif->q) == 0) { pbuf_ref(p); list_push(unixif->q, buf); sys_timeout((double)p->tot_len * 8000.0 / UNIXIF_BPS, unixif_output_timeout, netif); LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_output: first on list\n")); } else { pbuf_ref(p); if (list_push(unixif->q, buf) == 0) { #ifdef UNIXIF_DROP_FIRST struct unixif_buf *buf2; buf2 = list_pop(unixif->q); pbuf_free(buf2->p); free(buf2); list_push(unixif->q, buf); #else free(buf); pbuf_free(p); LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_output: drop\n")); #endif /* UNIXIF_DROP_FIRST */ LINK_STATS_INC(link.drop); } else { LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_output: on list\n")); } } return ERR_OK; } /*-----------------------------------------------------------------------------------*/ static void unixif_output_timeout(void *arg) { struct pbuf *p, *q; int i, j, len; unsigned short plen, ptot_len; struct unixif_buf *buf; void *payload; struct netif *netif; struct unixif *unixif; char *data; netif = (struct netif *)arg; unixif = (struct unixif *)netif->state; LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_output_timeout\n")); /* buf = unixif->q[0]; unixif->q[0] = unixif->q[1]; unixif->q[1] = NULL;*/ buf = (struct unixif_buf *)list_pop(unixif->q); p = buf->p; plen = p->len; ptot_len = p->tot_len; payload = p->payload; p->len = buf->len; p->tot_len = buf->tot_len; p->payload = buf->payload; if (p->tot_len == 0) { LWIP_DEBUGF(UNIXIF_DEBUG, ("p->len!\n")); abort(); } data = (char *)malloc(p->tot_len); i = 0; for(q = p; q != NULL; q = q->next) { for(j = 0; j < q->len; j++) { data[i] = ((char *)q->payload)[j]; i++; } } LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_output: sending %d (%d) bytes\n", p->len, p->tot_len)); len = p->tot_len; if (write(unixif->fd, &len, sizeof(int)) == -1) { perror("unixif_output: write"); abort(); } if (write(unixif->fd, data, p->tot_len) == -1) { perror("unixif_output: write"); abort(); } #if LWIP_IPV4 && LWIP_TCP tcpdump(p); #endif LINK_STATS_INC(link.xmit); free(data); free(buf); p->len = plen; p->tot_len = ptot_len; p->payload = payload; pbuf_free(p); /* if (unixif->q[0] != NULL) { sys_timeout(unixif->q[0]->tot_len * 8000 / UNIXIF_BPS, unixif_output_timeout, netif); }*/ if (list_elems(unixif->q) > 0) { sys_timeout(((struct unixif_buf *)list_first(unixif->q))->tot_len * 8000.0 / UNIXIF_BPS, unixif_output_timeout, netif); } } /*-----------------------------------------------------------------------------------*/ err_t unixif_init_server(struct netif *netif) { int fd, fd2; struct sockaddr_un addr; socklen_t len; struct unixif *unixif; fd = unix_socket_server("/tmp/unixif"); if (fd == -1) { perror("unixif_server"); abort(); } LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_server: fd %d\n", fd)); unixif = (struct unixif *)malloc(sizeof(struct unixif)); if (!unixif) { return ERR_MEM; } netif->state = unixif; netif->name[0] = 'u'; netif->name[1] = 'n'; netif->output = unixif_output; unixif->q = list_new(UNIXIF_QUEUELEN); printf("Now run ./simnode.\n"); len = sizeof(addr); fd2 = accept(fd, (struct sockaddr *)&addr, &len); if (fd2 == -1) { perror("unixif_accept"); abort(); } LWIP_DEBUGF(UNIXIF_DEBUG, ("unixif_accept: %d\n", fd2)); unixif->fd = fd2; if(sys_sem_new(&unixif->sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } sys_thread_new("unixif_thread", unixif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); sys_thread_new("unixif_thread2", unixif_thread2, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ err_t unixif_init_client(struct netif *netif) { struct unixif *unixif; unixif = (struct unixif *)malloc(sizeof(struct unixif)); if (!unixif) { return ERR_MEM; } netif->state = unixif; netif->name[0] = 'u'; netif->name[1] = 'n'; netif->output = unixif_output; unixif->fd = unix_socket_client("/tmp/unixif"); if (unixif->fd == -1) { perror("unixif_init"); abort(); } unixif->q = list_new(UNIXIF_QUEUELEN); if(sys_sem_new(&unixif->sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } sys_thread_new("unixif_thread", unixif_thread, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); sys_thread_new("unixif_thread2", unixif_thread2, netif, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); return ERR_OK; } /*-----------------------------------------------------------------------------------*/ #endif /* !NO_SYS */ #endif /* LWIP_IPV4 */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/netif/unixif.c
C
unknown
14,084
/* * Copyright (c) 2001-2003 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 "arch/perf.h" #include <stdio.h> static FILE *f; void perf_print(unsigned long c1l, unsigned long c1h, unsigned long c2l, unsigned long c2h, char *key) { unsigned long sub_ms, sub_ls; sub_ms = c2h - c1h; sub_ls = c2l - c1l; if (c2l < c1l) sub_ms--; fprintf(f, "%s: %.8lu%.8lu\n", key, sub_ms, sub_ls); fflush(NULL); } void perf_print_times(struct tms *start, struct tms *end, char *key) { fprintf(f, "%s: %lu\n", key, end->tms_stime - start->tms_stime); fflush(NULL); } void perf_init(char *fname) { f = fopen(fname, "w"); }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/perf.c
C
unknown
2,248
/* * Copyright (c) 2001-2003 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> * */ /* * Wed Apr 17 16:05:29 EDT 2002 (James Roth) * * - Fixed an unlikely sys_thread_new() race condition. * * - Made current_thread() work with threads which where * not created with sys_thread_new(). This includes * the main thread and threads made with pthread_create(). * * - Catch overflows where more than SYS_MBOX_SIZE messages * are waiting to be read. The sys_mbox_post() routine * will block until there is more room instead of just * leaking messages. */ #include "lwip/debug.h" #include <string.h> #include <sys/time.h> #include <sys/types.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include "lwip/def.h" #ifdef LWIP_UNIX_MACH #include <mach/mach.h> #include <mach/mach_time.h> #endif #include "lwip/sys.h" #include "lwip/opt.h" #include "lwip/stats.h" static void get_monotonic_time(struct timespec *ts) { #ifdef LWIP_UNIX_MACH /* darwin impl (no CLOCK_MONOTONIC) */ uint64_t t = mach_absolute_time(); mach_timebase_info_data_t timebase_info = {0, 0}; mach_timebase_info(&timebase_info); uint64_t nano = (t * timebase_info.numer) / (timebase_info.denom); uint64_t sec = nano/1000000000L; nano -= sec * 1000000000L; ts->tv_sec = sec; ts->tv_nsec = nano; #else clock_gettime(CLOCK_MONOTONIC, ts); #endif } #if !NO_SYS static struct sys_thread *threads = NULL; static pthread_mutex_t threads_mutex = PTHREAD_MUTEX_INITIALIZER; struct sys_mbox_msg { struct sys_mbox_msg *next; void *msg; }; #define SYS_MBOX_SIZE 128 struct sys_mbox { int first, last; void *msgs[SYS_MBOX_SIZE]; struct sys_sem *not_empty; struct sys_sem *not_full; struct sys_sem *mutex; int wait_send; }; struct sys_sem { unsigned int c; pthread_condattr_t condattr; pthread_cond_t cond; pthread_mutex_t mutex; }; struct sys_mutex { pthread_mutex_t mutex; }; struct sys_thread { struct sys_thread *next; pthread_t pthread; }; #if SYS_LIGHTWEIGHT_PROT static pthread_mutex_t lwprot_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t lwprot_thread = (pthread_t)0xDEAD; static int lwprot_count = 0; #endif /* SYS_LIGHTWEIGHT_PROT */ static struct sys_sem *sys_sem_new_internal(u8_t count); static void sys_sem_free_internal(struct sys_sem *sem); static u32_t cond_wait(pthread_cond_t * cond, pthread_mutex_t * mutex, u32_t timeout); /*-----------------------------------------------------------------------------------*/ /* Threads */ static struct sys_thread * introduce_thread(pthread_t id) { struct sys_thread *thread; thread = (struct sys_thread *)malloc(sizeof(struct sys_thread)); if (thread != NULL) { pthread_mutex_lock(&threads_mutex); thread->next = threads; thread->pthread = id; threads = thread; pthread_mutex_unlock(&threads_mutex); } return thread; } sys_thread_t sys_thread_new(const char *name, lwip_thread_fn function, void *arg, int stacksize, int prio) { int code; pthread_t tmp; struct sys_thread *st = NULL; LWIP_UNUSED_ARG(name); LWIP_UNUSED_ARG(stacksize); LWIP_UNUSED_ARG(prio); code = pthread_create(&tmp, NULL, (void *(*)(void *)) function, arg); if (0 == code) { st = introduce_thread(tmp); } if (NULL == st) { LWIP_DEBUGF(SYS_DEBUG, ("sys_thread_new: pthread_create %d, st = 0x%lx", code, (unsigned long)st)); abort(); } return st; } /*-----------------------------------------------------------------------------------*/ /* Mailbox */ err_t sys_mbox_new(struct sys_mbox **mb, int size) { struct sys_mbox *mbox; LWIP_UNUSED_ARG(size); mbox = (struct sys_mbox *)malloc(sizeof(struct sys_mbox)); if (mbox == NULL) { return ERR_MEM; } mbox->first = mbox->last = 0; mbox->not_empty = sys_sem_new_internal(0); mbox->not_full = sys_sem_new_internal(0); mbox->mutex = sys_sem_new_internal(1); mbox->wait_send = 0; SYS_STATS_INC_USED(mbox); *mb = mbox; return ERR_OK; } void sys_mbox_free(struct sys_mbox **mb) { if ((mb != NULL) && (*mb != SYS_MBOX_NULL)) { struct sys_mbox *mbox = *mb; SYS_STATS_DEC(mbox.used); sys_arch_sem_wait(&mbox->mutex, 0); sys_sem_free_internal(mbox->not_empty); sys_sem_free_internal(mbox->not_full); sys_sem_free_internal(mbox->mutex); mbox->not_empty = mbox->not_full = mbox->mutex = NULL; /* LWIP_DEBUGF("sys_mbox_free: mbox 0x%lx\n", mbox); */ free(mbox); } } err_t sys_mbox_trypost(struct sys_mbox **mb, void *msg) { u8_t first; struct sys_mbox *mbox; LWIP_ASSERT("invalid mbox", (mb != NULL) && (*mb != NULL)); mbox = *mb; sys_arch_sem_wait(&mbox->mutex, 0); LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_trypost: mbox %p msg %p\n", (void *)mbox, (void *)msg)); if ((mbox->last + 1) >= (mbox->first + SYS_MBOX_SIZE)) { sys_sem_signal(&mbox->mutex); return ERR_MEM; } mbox->msgs[mbox->last % SYS_MBOX_SIZE] = msg; if (mbox->last == mbox->first) { first = 1; } else { first = 0; } mbox->last++; if (first) { sys_sem_signal(&mbox->not_empty); } sys_sem_signal(&mbox->mutex); return ERR_OK; } void sys_mbox_post(struct sys_mbox **mb, void *msg) { u8_t first; struct sys_mbox *mbox; LWIP_ASSERT("invalid mbox", (mb != NULL) && (*mb != NULL)); mbox = *mb; sys_arch_sem_wait(&mbox->mutex, 0); LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_post: mbox %p msg %p\n", (void *)mbox, (void *)msg)); while ((mbox->last + 1) >= (mbox->first + SYS_MBOX_SIZE)) { mbox->wait_send++; sys_sem_signal(&mbox->mutex); sys_arch_sem_wait(&mbox->not_full, 0); sys_arch_sem_wait(&mbox->mutex, 0); mbox->wait_send--; } mbox->msgs[mbox->last % SYS_MBOX_SIZE] = msg; if (mbox->last == mbox->first) { first = 1; } else { first = 0; } mbox->last++; if (first) { sys_sem_signal(&mbox->not_empty); } sys_sem_signal(&mbox->mutex); } u32_t sys_arch_mbox_tryfetch(struct sys_mbox **mb, void **msg) { struct sys_mbox *mbox; LWIP_ASSERT("invalid mbox", (mb != NULL) && (*mb != NULL)); mbox = *mb; sys_arch_sem_wait(&mbox->mutex, 0); if (mbox->first == mbox->last) { sys_sem_signal(&mbox->mutex); return SYS_MBOX_EMPTY; } if (msg != NULL) { LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_tryfetch: mbox %p msg %p\n", (void *)mbox, *msg)); *msg = mbox->msgs[mbox->first % SYS_MBOX_SIZE]; } else{ LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_tryfetch: mbox %p, null msg\n", (void *)mbox)); } mbox->first++; if (mbox->wait_send) { sys_sem_signal(&mbox->not_full); } sys_sem_signal(&mbox->mutex); return 0; } u32_t sys_arch_mbox_fetch(struct sys_mbox **mb, void **msg, u32_t timeout) { u32_t time_needed = 0; struct sys_mbox *mbox; LWIP_ASSERT("invalid mbox", (mb != NULL) && (*mb != NULL)); mbox = *mb; /* The mutex lock is quick so we don't bother with the timeout stuff here. */ sys_arch_sem_wait(&mbox->mutex, 0); while (mbox->first == mbox->last) { sys_sem_signal(&mbox->mutex); /* We block while waiting for a mail to arrive in the mailbox. We must be prepared to timeout. */ if (timeout != 0) { time_needed = sys_arch_sem_wait(&mbox->not_empty, timeout); if (time_needed == SYS_ARCH_TIMEOUT) { return SYS_ARCH_TIMEOUT; } } else { sys_arch_sem_wait(&mbox->not_empty, 0); } sys_arch_sem_wait(&mbox->mutex, 0); } if (msg != NULL) { LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_fetch: mbox %p msg %p\n", (void *)mbox, *msg)); *msg = mbox->msgs[mbox->first % SYS_MBOX_SIZE]; } else{ LWIP_DEBUGF(SYS_DEBUG, ("sys_mbox_fetch: mbox %p, null msg\n", (void *)mbox)); } mbox->first++; if (mbox->wait_send) { sys_sem_signal(&mbox->not_full); } sys_sem_signal(&mbox->mutex); return time_needed; } /*-----------------------------------------------------------------------------------*/ /* Semaphore */ static struct sys_sem * sys_sem_new_internal(u8_t count) { struct sys_sem *sem; sem = (struct sys_sem *)malloc(sizeof(struct sys_sem)); if (sem != NULL) { sem->c = count; pthread_condattr_init(&(sem->condattr)); #if !(defined(LWIP_UNIX_MACH) || (defined(LWIP_UNIX_ANDROID) && __ANDROID_API__ < 21)) pthread_condattr_setclock(&(sem->condattr), CLOCK_MONOTONIC); #endif pthread_cond_init(&(sem->cond), &(sem->condattr)); pthread_mutex_init(&(sem->mutex), NULL); } return sem; } err_t sys_sem_new(struct sys_sem **sem, u8_t count) { SYS_STATS_INC_USED(sem); *sem = sys_sem_new_internal(count); if (*sem == NULL) { return ERR_MEM; } return ERR_OK; } static u32_t cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, u32_t timeout) { struct timespec rtime1, rtime2, ts; int ret; if (timeout == 0) { pthread_cond_wait(cond, mutex); return 0; } /* Get a timestamp and add the timeout value. */ get_monotonic_time(&rtime1); #if defined(LWIP_UNIX_MACH) || (defined(LWIP_UNIX_ANDROID) && __ANDROID_API__ < 21) ts.tv_sec = timeout / 1000L; ts.tv_nsec = (timeout % 1000L) * 1000000L; ret = pthread_cond_timedwait_relative_np(cond, mutex, &ts); #else ts.tv_sec = rtime1.tv_sec + timeout / 1000L; ts.tv_nsec = rtime1.tv_nsec + (timeout % 1000L) * 1000000L; if (ts.tv_nsec >= 1000000000L) { ts.tv_sec++; ts.tv_nsec -= 1000000000L; } ret = pthread_cond_timedwait(cond, mutex, &ts); #endif if (ret == ETIMEDOUT) { return SYS_ARCH_TIMEOUT; } /* Calculate for how long we waited for the cond. */ get_monotonic_time(&rtime2); ts.tv_sec = rtime2.tv_sec - rtime1.tv_sec; ts.tv_nsec = rtime2.tv_nsec - rtime1.tv_nsec; if (ts.tv_nsec < 0) { ts.tv_sec--; ts.tv_nsec += 1000000000L; } return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; } u32_t sys_arch_sem_wait(struct sys_sem **s, u32_t timeout) { u32_t time_needed = 0; struct sys_sem *sem; LWIP_ASSERT("invalid sem", (s != NULL) && (*s != NULL)); sem = *s; pthread_mutex_lock(&(sem->mutex)); while (sem->c <= 0) { if (timeout > 0) { time_needed = cond_wait(&(sem->cond), &(sem->mutex), timeout); if (time_needed == SYS_ARCH_TIMEOUT) { pthread_mutex_unlock(&(sem->mutex)); return SYS_ARCH_TIMEOUT; } /* pthread_mutex_unlock(&(sem->mutex)); return time_needed; */ } else { cond_wait(&(sem->cond), &(sem->mutex), 0); } } sem->c--; pthread_mutex_unlock(&(sem->mutex)); return (u32_t)time_needed; } void sys_sem_signal(struct sys_sem **s) { struct sys_sem *sem; LWIP_ASSERT("invalid sem", (s != NULL) && (*s != NULL)); sem = *s; pthread_mutex_lock(&(sem->mutex)); sem->c++; if (sem->c > 1) { sem->c = 1; } pthread_cond_broadcast(&(sem->cond)); pthread_mutex_unlock(&(sem->mutex)); } static void sys_sem_free_internal(struct sys_sem *sem) { pthread_cond_destroy(&(sem->cond)); pthread_condattr_destroy(&(sem->condattr)); pthread_mutex_destroy(&(sem->mutex)); free(sem); } void sys_sem_free(struct sys_sem **sem) { if ((sem != NULL) && (*sem != SYS_SEM_NULL)) { SYS_STATS_DEC(sem.used); sys_sem_free_internal(*sem); } } /*-----------------------------------------------------------------------------------*/ /* Mutex */ /** Create a new mutex * @param mutex pointer to the mutex to create * @return a new mutex */ err_t sys_mutex_new(struct sys_mutex **mutex) { struct sys_mutex *mtx; mtx = (struct sys_mutex *)malloc(sizeof(struct sys_mutex)); if (mtx != NULL) { pthread_mutex_init(&(mtx->mutex), NULL); *mutex = mtx; return ERR_OK; } else { return ERR_MEM; } } /** Lock a mutex * @param mutex the mutex to lock */ void sys_mutex_lock(struct sys_mutex **mutex) { pthread_mutex_lock(&((*mutex)->mutex)); } /** Unlock a mutex * @param mutex the mutex to unlock */ void sys_mutex_unlock(struct sys_mutex **mutex) { pthread_mutex_unlock(&((*mutex)->mutex)); } /** Delete a mutex * @param mutex the mutex to delete */ void sys_mutex_free(struct sys_mutex **mutex) { pthread_mutex_destroy(&((*mutex)->mutex)); free(*mutex); } #endif /* !NO_SYS */ /*-----------------------------------------------------------------------------------*/ /* Time */ u32_t sys_now(void) { struct timespec ts; get_monotonic_time(&ts); return ts.tv_sec * 1000L + ts.tv_nsec / 1000000L; } u32_t sys_jiffies(void) { struct timespec ts; get_monotonic_time(&ts); return ts.tv_sec * 1000000000L + ts.tv_nsec; } /*-----------------------------------------------------------------------------------*/ /* Init */ void sys_init(void) { } /*-----------------------------------------------------------------------------------*/ /* Critical section */ #if SYS_LIGHTWEIGHT_PROT /** sys_prot_t sys_arch_protect(void) This optional function does a "fast" critical region protection and returns the previous protection level. This function is only called during very short critical regions. An embedded system which supports ISR-based drivers might want to implement this function by disabling interrupts. Task-based systems might want to implement this by using a mutex or disabling tasking. This function should support recursive calls from the same task or interrupt. In other words, sys_arch_protect() could be called while already protected. In that case the return value indicates that it is already protected. sys_arch_protect() is only required if your port is supporting an operating system. */ sys_prot_t sys_arch_protect(void) { /* Note that for the UNIX port, we are using a lightweight mutex, and our * own counter (which is locked by the mutex). The return code is not actually * used. */ if (lwprot_thread != pthread_self()) { /* We are locking the mutex where it has not been locked before * * or is being locked by another thread */ pthread_mutex_lock(&lwprot_mutex); lwprot_thread = pthread_self(); lwprot_count = 1; } else /* It is already locked by THIS thread */ lwprot_count++; return 0; } /** void sys_arch_unprotect(sys_prot_t pval) This optional function does a "fast" set of critical region protection to the value specified by pval. See the documentation for sys_arch_protect() for more information. This function is only required if your port is supporting an operating system. */ void sys_arch_unprotect(sys_prot_t pval) { LWIP_UNUSED_ARG(pval); if (lwprot_thread == pthread_self()) { if (--lwprot_count == 0) { lwprot_thread = (pthread_t) 0xDEAD; pthread_mutex_unlock(&lwprot_mutex); } } } #endif /* SYS_LIGHTWEIGHT_PROT */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/port/sys_arch.c
C
unknown
16,984
#!/bin/bash # Run me using "source setup-tapif" to get exported PRECONFIGURED_TAPIF variable # Alternatively, add "export PRECONFIGURED_TAPIF=tap0" to ~/.bashrc # http://backreference.org/2010/03/26/tuntap-interface-tutorial/ # After executing this script, start unixsim/simhost. # Enter 192.168.0.2 or "http://simhost.local/" (Zeroconf) # in your webbrowser to see simhost webpage. sudo ip tuntap add dev tap0 mode tap user `whoami` sudo ip link set tap0 up sudo ip addr add 192.168.0.1/24 dev tap0 export PRECONFIGURED_TAPIF=tap0
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/setup-tapif
Shell
unknown
551
# # Copyright (c) 2001, 2002 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> # all compile: simhost simrouter simnode .PHONY: all include ../Common.mk clean: rm -f *.o $(LWIPLIBCOMMON) $(APPLIB) simhost simnode simrouter *.s .depend* *.core core depend dep: .depend include .depend .depend: simhost.c simnode.c simrouter.c $(LWIPFILES) $(APPFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || rm -f .depend simhost: .depend $(LWIPLIBCOMMON) $(APPLIB) simhost.o $(CC) $(CFLAGS) -o simhost simhost.o -Wl,--start-group $(APPLIB) $(LWIPLIBCOMMON) -Wl,--end-group $(LDFLAGS) simrouter: .depend $(LWIPLIBCOMMON) $(APPLIB) simrouter.o $(CC) $(CFLAGS) -o simrouter simrouter.o -Wl,--start-group $(APPLIB) $(LWIPLIBCOMMON) -Wl,--end-group $(LDFLAGS) simnode: .depend $(LWIPLIBCOMMON) $(APPLIB) simnode.o $(CC) $(CFLAGS) -o simnode simnode.o -Wl,--start-group $(APPLIB) $(LWIPLIBCOMMON) -Wl,--end-group $(LDFLAGS)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/unixsim/Makefile
Makefile
unknown
2,463
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_LWIPOPTS_H #define LWIP_LWIPOPTS_H #include "lwip/arch.h" #define LWIP_IPV4 1 #define LWIP_IPV6 1 #define LWIP_DBG_MIN_LEVEL 0 #define LWIP_COMPAT_SOCKETS 1 #define TAPIF_DEBUG LWIP_DBG_ON #define TUNIF_DEBUG LWIP_DBG_OFF #define UNIXIF_DEBUG LWIP_DBG_OFF #define DELIF_DEBUG LWIP_DBG_OFF #define SIO_FIFO_DEBUG LWIP_DBG_OFF #define TCPDUMP_DEBUG LWIP_DBG_ON #define SLIP_DEBUG LWIP_DBG_OFF #define PPP_DEBUG LWIP_DBG_OFF #define MEM_DEBUG LWIP_DBG_OFF #define MEMP_DEBUG LWIP_DBG_OFF #define PBUF_DEBUG LWIP_DBG_OFF #define API_LIB_DEBUG LWIP_DBG_ON #define API_MSG_DEBUG LWIP_DBG_ON #define TCPIP_DEBUG LWIP_DBG_ON #define NETIF_DEBUG LWIP_DBG_ON #define SOCKETS_DEBUG LWIP_DBG_ON #define DEMO_DEBUG LWIP_DBG_ON #define IP_DEBUG LWIP_DBG_ON #define IP_REASS_DEBUG LWIP_DBG_ON #define RAW_DEBUG LWIP_DBG_ON #define ICMP_DEBUG LWIP_DBG_ON #define UDP_DEBUG LWIP_DBG_ON #define TCP_DEBUG LWIP_DBG_ON #define TCP_INPUT_DEBUG LWIP_DBG_ON #define TCP_OUTPUT_DEBUG LWIP_DBG_ON #define TCP_RTO_DEBUG LWIP_DBG_ON #define TCP_CWND_DEBUG LWIP_DBG_ON #define TCP_WND_DEBUG LWIP_DBG_ON #define TCP_FR_DEBUG LWIP_DBG_ON #define TCP_QLEN_DEBUG LWIP_DBG_ON #define TCP_RST_DEBUG LWIP_DBG_ON extern unsigned char debug_flags; #define LWIP_DBG_TYPES_ON debug_flags #define NO_SYS 0 #define LWIP_SOCKET (NO_SYS==0) #define LWIP_NETCONN (NO_SYS==0) #define SO_REUSE 1 #define IP_SOF_BROADCAST_RECV 1 #define IP_SOF_BROADCAST 1 #define SO_REUSE_RXTOALL 1 /* ---------- Memory options ---------- */ /* MEM_ALIGNMENT: should be set to the alignment of the CPU for which lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2 byte alignment -> define MEM_ALIGNMENT to 2. */ /* MSVC port: intel processors don't need 4-byte alignment, but are faster that way! */ #define MEM_ALIGNMENT 4 /* MEM_SIZE: the size of the heap memory. If the application will send a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE 10240 /* MEMP_NUM_PBUF: the number of memp struct pbufs. If the application sends a lot of data out of ROM (or other static memory), this should be set high. */ #define MEMP_NUM_PBUF 16 /* MEMP_NUM_RAW_PCB: the number of UDP protocol control blocks. One per active RAW "connection". */ #define MEMP_NUM_RAW_PCB 3 /* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One per active UDP "connection". */ #define MEMP_NUM_UDP_PCB 6 /* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. */ #define MEMP_NUM_TCP_PCB 5 /* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. */ #define MEMP_NUM_TCP_PCB_LISTEN 8 /* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. */ #define MEMP_NUM_TCP_SEG 16 /* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. */ #define MEMP_NUM_SYS_TIMEOUT 12 /* The following four are used only with the sequential API and can be set to 0 if the application only will use the raw API. */ /* MEMP_NUM_NETBUF: the number of struct netbufs. */ #define MEMP_NUM_NETBUF 2 /* MEMP_NUM_NETCONN: the number of struct netconns. */ #define MEMP_NUM_NETCONN 10 /* MEMP_NUM_TCPIP_MSG_*: the number of struct tcpip_msg, which is used for sequential API communication and incoming packets. Used in src/api/tcpip.c. */ #define MEMP_NUM_TCPIP_MSG_API 16 #define MEMP_NUM_TCPIP_MSG_INPKT 16 #define MEMP_OVERFLOW_CHECK 1 /* ---------- Pbuf options ---------- */ /* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ #define PBUF_POOL_SIZE 200 /* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ #define PBUF_POOL_BUFSIZE 128 /* PBUF_LINK_HLEN: the number of bytes that should be allocated for a link level header. */ #define PBUF_LINK_HLEN 16 /** SYS_LIGHTWEIGHT_PROT * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection * for certain critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #define SYS_LIGHTWEIGHT_PROT 1 #define LWIP_TCPIP_TIMEOUT 1 /* ---------- TCP options ---------- */ #define LWIP_TCP 1 #define TCP_TTL 255 #define TCP_LISTEN_BACKLOG 1 /* Controls if TCP should queue segments that arrive out of order. Define to 0 if your device is low on memory. */ #define TCP_QUEUE_OOSEQ 1 /* TCP Maximum segment size. */ #define TCP_MSS 1024 /* TCP sender buffer space (bytes). */ #define TCP_SND_BUF 2048 /* TCP sender buffer space (pbufs). This must be at least = 2 * TCP_SND_BUF/TCP_MSS for things to work. */ #define TCP_SND_QUEUELEN (4 * TCP_SND_BUF/TCP_MSS) /* TCP writable space (bytes). This must be less than or equal to TCP_SND_BUF. It is the amount of space which must be available in the tcp snd_buf for select to return writable */ #define TCP_SNDLOWAT (TCP_SND_BUF/2) /* TCP receive window. */ #define TCP_WND 8096 /* Maximum number of retransmissions of data segments. */ #define TCP_MAXRTX 12 /* Maximum number of retransmissions of SYN segments. */ #define TCP_SYNMAXRTX 4 /* ---------- ARP options ---------- */ #define LWIP_ARP 1 #define ARP_TABLE_SIZE 10 #define ARP_QUEUEING 1 /* ---------- IP options ---------- */ /* Define IP_FORWARD to 1 if you wish to have the ability to forward IP packets across network interfaces. If you are going to run lwIP on a device with only one network interface, define this to 0. */ #define IP_FORWARD 1 /* IP reassembly and segmentation.These are orthogonal even * if they both deal with IP fragments */ #define IP_REASSEMBLY 1 #define IP_REASS_MAX_PBUFS 10 #define MEMP_NUM_REASSDATA 10 #define IP_FRAG 1 #define IPV6_FRAG_COPYHEADER 1 #define LWIP_IGMP (LWIP_IPV4) /* ---------- ICMP options ---------- */ #define ICMP_TTL 255 /* ---------- DHCP options ---------- */ /* Define LWIP_DHCP to 1 if you want DHCP configuration of interfaces. */ #define LWIP_DHCP 0 #define LWIP_DHCP_GET_NTP_SRV (LWIP_DHCP) /* 1 if you want to do an ARP check on the offered address (recommended if using DHCP). */ #define DHCP_DOES_ARP_CHECK (LWIP_DHCP) /* ---------- AUTOIP options ------- */ #define LWIP_AUTOIP (LWIP_DHCP) #define LWIP_DHCP_AUTOIP_COOP (LWIP_DHCP) #define LWIP_DHCP_AUTOIP_COOP_TRIES 3 /* ---------- SNTP options --------- */ extern void sntp_set_system_time(u32_t sec); #define SNTP_SET_SYSTEM_TIME(s) sntp_set_system_time(s) /* ---------- SNMP options ---------- */ #define LWIP_SNMP 1 #define MIB2_STATS LWIP_SNMP #define SNMP_USE_NETCONN LWIP_NETCONN #define SNMP_USE_RAW (!LWIP_NETCONN) /* ---------- DNS options ---------- */ #define LWIP_DNS 1 /* ---------- MDNS options ---------- */ #define LWIP_MDNS_RESPONDER 1 #define LWIP_NUM_NETIF_CLIENT_DATA (LWIP_MDNS_RESPONDER) /* ---------- UDP options ---------- */ #define LWIP_UDP 1 #define UDP_TTL 255 /* ---------- RAW options ---------- */ #define LWIP_RAW 1 #define RAW_TTL 255 /* ---------- Statistics options ---------- */ /* individual STATS options can be turned off by defining them to 0 * (e.g #define TCP_STATS 0). All of them are turned off if LWIP_STATS * is 0 * */ #define LWIP_STATS 1 #define LWIP_NETIF_API 1 #define LWIP_NETIF_STATUS_CALLBACK 1 #define LWIP_NETIF_HOSTNAME 0 /* ---------- SLIP options ---------- */ #define LWIP_HAVE_SLIPIF 1 /* Set > 0 for SLIP */ /* Maximum packet size that is received by this netif */ #define SLIP_MAX_SIZE 1500 #define sio_tryread sio_read /* ---------- 6LoWPAN options ---------- */ #define LWIP_6LOWPAN 1 /* ---------- PPP options ---------- */ #define PPP_SUPPORT 1 /* Set > 0 for PPP */ #define MPPE_SUPPORT PPP_SUPPORT #define PPPOE_SUPPORT PPP_SUPPORT #define PPPOL2TP_SUPPORT PPP_SUPPORT #define PPPOS_SUPPORT PPP_SUPPORT #if PPP_SUPPORT > 0 #define NUM_PPP 1 /* Max PPP sessions. */ /* Select modules to enable. Ideally these would be set in the makefile but * we're limited by the command line length so you need to modify the settings * in this file. */ #define PAP_SUPPORT 1 /* Set > 0 for PAP. */ #define CHAP_SUPPORT 1 /* Set > 0 for CHAP. */ #define MSCHAP_SUPPORT 0 /* Set > 0 for MSCHAP (NOT FUNCTIONAL!) */ #define CBCP_SUPPORT 0 /* Set > 0 for CBCP (NOT FUNCTIONAL!) */ #define CCP_SUPPORT 0 /* Set > 0 for CCP (NOT FUNCTIONAL!) */ #define VJ_SUPPORT 1 /* Set > 0 for VJ header compression. */ #define MD5_SUPPORT 1 /* Set > 0 for MD5 (see also CHAP) */ /* * Timeouts. */ #define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */ #define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ #define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ #define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ #define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ #define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ #define CHAP_DEFTIMEOUT 6 /* Timeout time in seconds */ #define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */ /* Interval in seconds between keepalive echo requests, 0 to disable. */ #if 1 #define LCP_ECHOINTERVAL 0 #else #define LCP_ECHOINTERVAL 10 #endif /* Number of unanswered echo requests before failure. */ #define LCP_MAXECHOFAILS 3 /* Max Xmit idle time (in jiffies) before resend flag char. */ #define PPP_MAXIDLEFLAG 100 /* * Packet sizes * * Note - lcp shouldn't be allowed to negotiate stuff outside these * limits. See lcp.h in the pppd directory. * (XXX - these constants should simply be shared by lcp.c instead * of living in lcp.h) */ #define PPP_MTU 1500 /* Default MTU (size of Info field) */ #if 0 #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) #else #define PPP_MAXMTU 1500 /* Largest MTU we allow */ #endif #define PPP_MINMTU 64 #define PPP_MRU 1500 /* default MRU = max length of info field */ #define PPP_MAXMRU 1500 /* Largest MRU we allow */ #define PPP_DEFMRU 296 /* Try for this */ #define PPP_MINMRU 128 /* No MRUs below this */ #define MAXNAMELEN 256 /* max length of hostname or name for auth */ #define MAXSECRETLEN 256 /* max length of password or secret */ #endif /* PPP_SUPPORT > 0 */ #define LWIP_HTTPD_SSI 1 #endif /* LWIP_LWIPOPTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/unixsim/lwipopts.h
C
unknown
12,949
/* * Copyright (c) 2001-2003 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 <unistd.h> #include <fcntl.h> #include <getopt.h> #include <time.h> #include "lwip/opt.h" #include "lwip/init.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/sys.h" #include "lwip/timeouts.h" #include "lwip/ip_addr.h" #include "lwip/dns.h" #include "lwip/dhcp.h" #include "lwip/stats.h" #include "lwip/tcp.h" #include "lwip/inet_chksum.h" #include "lwip/tcpip.h" #include "lwip/sockets.h" #include "netif/tapif.h" #include "netif/tunif.h" #include "netif/unixif.h" #include "netif/dropif.h" #include "netif/pcapif.h" #include "netif/tcpdump.h" #ifndef LWIP_HAVE_SLIPIF #define LWIP_HAVE_SLIPIF 0 #endif #if LWIP_HAVE_SLIPIF #include "netif/slipif.h" #define SLIP_PTY_TEST 1 #endif #if PPP_SUPPORT #include "netif/ppp/pppos.h" #include "lwip/sio.h" #define PPP_PTY_TEST 1 #include <termios.h> #endif #include "lwip/ip_addr.h" #include "arch/perf.h" #include "lwip/apps/httpd.h" #include "apps/udpecho/udpecho.h" #include "apps/tcpecho/tcpecho.h" #include "apps/shell/shell.h" #include "apps/chargen/chargen.h" #include "apps/netio/netio.h" #include "lwip/apps/netbiosns.h" #include "lwip/apps/mdns.h" #include "lwip/apps/sntp.h" #include "lwip/apps/snmp.h" #include "lwip/apps/snmp_mib2.h" #include "apps/snmp_private_mib/private_mib.h" #include "lwip/apps/tftp_server.h" #if LWIP_RAW #include "lwip/icmp.h" #include "lwip/raw.h" #endif #if LWIP_SNMP static const struct snmp_mib *mibs[] = { &mib2, &mib_private }; #endif /* LWIP_SNMP */ #if LWIP_IPV4 /* (manual) host IP configuration */ static ip_addr_t ipaddr, netmask, gw; #endif /* LWIP_IPV4 */ struct netif netif; /* ping out destination cmd option */ static unsigned char ping_flag; static ip_addr_t ping_addr; /* nonstatic debug cmd option, exported in lwipopts.h */ unsigned char debug_flags; /** @todo add options for selecting netif, starting DHCP client etc */ static struct option longopts[] = { /* turn on debugging output (if build with LWIP_DEBUG) */ {"debug", no_argument, NULL, 'd'}, /* help */ {"help", no_argument, NULL, 'h'}, #if LWIP_IPV4 /* gateway address */ {"gateway", required_argument, NULL, 'g'}, /* ip address */ {"ipaddr", required_argument, NULL, 'i'}, /* netmask */ {"netmask", required_argument, NULL, 'm'}, /* ping destination */ {"ping", required_argument, NULL, 'p'}, #endif /* LWIP_IPV4 */ /* new command line options go here! */ {NULL, 0, NULL, 0} }; #define NUM_OPTS ((sizeof(longopts) / sizeof(struct option)) - 1) static void init_netifs(void); static void usage(void) { unsigned char i; printf("options:\n"); for (i = 0; i < NUM_OPTS; i++) { printf("-%c --%s\n",longopts[i].val, longopts[i].name); } } #if 0 static void tcp_debug_timeout(void *data) { LWIP_UNUSED_ARG(data); #if TCP_DEBUG tcp_debug_print_pcbs(); #endif /* TCP_DEBUG */ sys_timeout(5000, tcp_debug_timeout, NULL); } #endif void sntp_set_system_time(u32_t sec) { char buf[32]; struct tm current_time_val; time_t current_time = (time_t)sec; localtime_r(&current_time, &current_time_val); strftime(buf, sizeof(buf), "%d.%m.%Y %H:%M:%S", &current_time_val); printf("SNTP time: %s\n", buf); } #if LWIP_MDNS_RESPONDER static void srv_txt(struct mdns_service *service, void *txt_userdata) { err_t res; LWIP_UNUSED_ARG(txt_userdata); res = mdns_resp_add_service_txtitem(service, "path=/", 6); LWIP_ERROR("mdns add service txt failed\n", (res == ERR_OK), return); } #endif #if LWIP_UDP static void* tftp_open(const char* fname, const char* mode, u8_t is_write) { LWIP_UNUSED_ARG(mode); if (is_write) { return (void*)fopen(fname, "wb"); } else { return (void*)fopen(fname, "rb"); } } static void tftp_close(void* handle) { fclose((FILE*)handle); } static int tftp_read(void* handle, void* buf, int bytes) { if (fread(buf, 1, bytes, (FILE*)handle) != (size_t)bytes) { return -1; } return 0; } static int tftp_write(void* handle, struct pbuf* p) { while (p != NULL) { if (fwrite(p->payload, 1, p->len, (FILE*)handle) != (size_t)p->len) { return -1; } p = p->next; } return 0; } static const struct tftp_context tftp = { tftp_open, tftp_close, tftp_read, tftp_write }; #endif /* LWIP_UDP */ static void tcpip_init_done(void *arg) { sys_sem_t *sem; sem = (sys_sem_t *)arg; init_netifs(); #if LWIP_IPV4 netbiosns_set_name("simhost"); netbiosns_init(); #endif /* LWIP_IPV4 */ sntp_setoperatingmode(SNTP_OPMODE_POLL); #if LWIP_DHCP sntp_servermode_dhcp(1); /* get SNTP server via DHCP */ #else /* LWIP_DHCP */ #if LWIP_IPV4 sntp_setserver(0, netif_ip_gw4(&netif)); #endif /* LWIP_IPV4 */ #endif /* LWIP_DHCP */ sntp_init(); #if LWIP_SNMP lwip_privmib_init(); #if SNMP_LWIP_MIB2 #if SNMP_USE_NETCONN snmp_threadsync_init(&snmp_mib2_lwip_locks, snmp_mib2_lwip_synchronizer); #endif /* SNMP_USE_NETCONN */ snmp_mib2_set_syscontact_readonly((const u8_t*)"root", NULL); snmp_mib2_set_syslocation_readonly((const u8_t*)"lwIP development PC", NULL); snmp_mib2_set_sysdescr((const u8_t*)"simhost", NULL); #endif /* SNMP_LWIP_MIB2 */ snmp_set_mibs(mibs, LWIP_ARRAYSIZE(mibs)); snmp_init(); #endif /* LWIP_SNMP */ #if LWIP_MDNS_RESPONDER mdns_resp_init(); mdns_resp_add_netif(&netif, "simhost", 3600); mdns_resp_add_service(&netif, "myweb", "_http", DNSSD_PROTO_TCP, 80, 3600, srv_txt, NULL); #endif #if LWIP_UDP tftp_init(&tftp); #endif /* LWIP_UDP */ sys_sem_signal(sem); } /*-----------------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------------------*/ #if LWIP_SOCKET /* Ping using the socket api */ static int seq_num; static void ping_send(int s, const ip_addr_t *addr) { struct icmp_echo_hdr *iecho; struct sockaddr_storage to; if (!(iecho = (struct icmp_echo_hdr *)malloc(sizeof(struct icmp_echo_hdr)))) return; ICMPH_TYPE_SET(iecho,ICMP_ECHO); iecho->chksum = 0; iecho->seqno = lwip_htons(seq_num); iecho->chksum = inet_chksum(iecho, sizeof(*iecho)); #if LWIP_IPV4 if(!IP_IS_V6(addr)) { struct sockaddr_in *to4 = (struct sockaddr_in*)&to; to4->sin_len = sizeof(to); to4->sin_family = AF_INET; inet_addr_from_ipaddr(&to4->sin_addr, ip_2_ip4(addr)); } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 if(IP_IS_V6(addr)) { struct sockaddr_in6 *to6 = (struct sockaddr_in6*)&to; to6->sin6_len = sizeof(to); to6->sin6_family = AF_INET6; inet6_addr_from_ip6addr(&to6->sin6_addr, ip_2_ip6(addr)); } #endif /* LWIP_IPV6 */ lwip_sendto(s, iecho, sizeof(*iecho), 0, (struct sockaddr*)&to, sizeof(to)); free(iecho); seq_num++; } static void ping_recv(int s, const ip_addr_t *addr) { char buf[200]; socklen_t fromlen; int len; struct sockaddr_storage from; ip_addr_t ip_from; LWIP_UNUSED_ARG(addr); len = lwip_recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen); #if LWIP_IPV4 if(!IP_IS_V6(addr)) { struct sockaddr_in *from4 = (struct sockaddr_in*)&from; inet_addr_to_ipaddr(ip_2_ip4(&ip_from), &from4->sin_addr); } #endif /* LWIP_IPV4 */ #if LWIP_IPV6 if(IP_IS_V6(addr)) { struct sockaddr_in6 *from6 = (struct sockaddr_in6*)&from; inet6_addr_to_ip6addr(ip_2_ip6(&ip_from), &from6->sin6_addr); } #endif /* LWIP_IPV6 */ printf("Received %d bytes from %s\n", len, ipaddr_ntoa(&ip_from)); } static void ping_thread(void *arg) { int s; LWIP_UNUSED_ARG(arg); if ((s = lwip_socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP)) < 0) { return; } while (1) { printf("sending ping\n"); ping_send(s,&ping_addr); ping_recv(s,&ping_addr); sleep(1); } } #endif /* LWIP_SOCKET */ #if LWIP_HAVE_SLIPIF /* (manual) host IP configuration */ #if LWIP_IPV4 static ip_addr_t ipaddr_slip, netmask_slip, gw_slip; #endif /* LWIP_IPV4 */ struct netif slipif; #endif /* LWIP_HAVE_SLIPIF */ #if PPP_SUPPORT sio_fd_t ppp_sio; ppp_pcb *ppp; struct netif pppos_netif; static void pppos_rx_thread(void *arg) { u32_t len; u8_t buffer[128]; LWIP_UNUSED_ARG(arg); /* Please read the "PPPoS input path" chapter in the PPP documentation. */ while (1) { len = sio_read(ppp_sio, buffer, sizeof(buffer)); if (len > 0) { /* Pass received raw characters from PPPoS to be decoded through lwIP * TCPIP thread using the TCPIP API. This is thread safe in all cases * but you should avoid passing data byte after byte. */ pppos_input_tcpip(ppp, buffer, len); } } } static void ppp_link_status_cb(ppp_pcb *pcb, int err_code, void *ctx) { struct netif *pppif = ppp_netif(pcb); LWIP_UNUSED_ARG(ctx); switch(err_code) { case PPPERR_NONE: /* No error. */ { #if LWIP_DNS const ip_addr_t *ns; #endif /* LWIP_DNS */ fprintf(stderr, "ppp_link_status_cb: PPPERR_NONE\n\r"); #if LWIP_IPV4 fprintf(stderr, " our_ip4addr = %s\n\r", ip4addr_ntoa(netif_ip4_addr(pppif))); fprintf(stderr, " his_ipaddr = %s\n\r", ip4addr_ntoa(netif_ip4_gw(pppif))); fprintf(stderr, " netmask = %s\n\r", ip4addr_ntoa(netif_ip4_netmask(pppif))); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 fprintf(stderr, " our_ip6addr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); #endif /* LWIP_IPV6 */ #if LWIP_DNS ns = dns_getserver(0); fprintf(stderr, " dns1 = %s\n\r", ipaddr_ntoa(ns)); ns = dns_getserver(1); fprintf(stderr, " dns2 = %s\n\r", ipaddr_ntoa(ns)); #endif /* LWIP_DNS */ #if PPP_IPV6_SUPPORT fprintf(stderr, " our6_ipaddr = %s\n\r", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); #endif /* PPP_IPV6_SUPPORT */ } break; case PPPERR_PARAM: /* Invalid parameter. */ printf("ppp_link_status_cb: PPPERR_PARAM\n"); break; case PPPERR_OPEN: /* Unable to open PPP session. */ printf("ppp_link_status_cb: PPPERR_OPEN\n"); break; case PPPERR_DEVICE: /* Invalid I/O device for PPP. */ printf("ppp_link_status_cb: PPPERR_DEVICE\n"); break; case PPPERR_ALLOC: /* Unable to allocate resources. */ printf("ppp_link_status_cb: PPPERR_ALLOC\n"); break; case PPPERR_USER: /* User interrupt. */ printf("ppp_link_status_cb: PPPERR_USER\n"); break; case PPPERR_CONNECT: /* Connection lost. */ printf("ppp_link_status_cb: PPPERR_CONNECT\n"); break; case PPPERR_AUTHFAIL: /* Failed authentication challenge. */ printf("ppp_link_status_cb: PPPERR_AUTHFAIL\n"); break; case PPPERR_PROTOCOL: /* Failed to meet protocol. */ printf("ppp_link_status_cb: PPPERR_PROTOCOL\n"); break; case PPPERR_PEERDEAD: /* Connection timeout. */ printf("ppp_link_status_cb: PPPERR_PEERDEAD\n"); break; case PPPERR_IDLETIMEOUT: /* Idle Timeout. */ printf("ppp_link_status_cb: PPPERR_IDLETIMEOUT\n"); break; case PPPERR_CONNECTTIME: /* PPPERR_CONNECTTIME. */ printf("ppp_link_status_cb: PPPERR_CONNECTTIME\n"); break; case PPPERR_LOOPBACK: /* Connection timeout. */ printf("ppp_link_status_cb: PPPERR_LOOPBACK\n"); break; default: printf("ppp_link_status_cb: unknown errCode %d\n", err_code); break; } } static u32_t ppp_output_cb(ppp_pcb *pcb, u8_t *data, u32_t len, void *ctx) { LWIP_UNUSED_ARG(pcb); LWIP_UNUSED_ARG(ctx); return sio_write(ppp_sio, data, len); } #endif #if LWIP_NETIF_STATUS_CALLBACK static void netif_status_callback(struct netif *nif) { printf("NETIF: %c%c%d is %s\n", nif->name[0], nif->name[1], nif->num, netif_is_up(nif) ? "UP" : "DOWN"); #if LWIP_IPV4 printf("IPV4: Host at %s ", ip4addr_ntoa(netif_ip4_addr(nif))); printf("mask %s ", ip4addr_ntoa(netif_ip4_netmask(nif))); printf("gateway %s\n", ip4addr_ntoa(netif_ip4_gw(nif))); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 printf("IPV6: Host at %s\n", ip6addr_ntoa(netif_ip6_addr(nif, 0))); #endif /* LWIP_IPV6 */ #if LWIP_NETIF_HOSTNAME printf("FQDN: %s\n", netif_get_hostname(nif)); #endif /* LWIP_NETIF_HOSTNAME */ #if LWIP_MDNS_RESPONDER mdns_resp_netif_settings_changed(nif); #endif } #endif /* LWIP_NETIF_STATUS_CALLBACK */ static void init_netifs(void) { #if LWIP_HAVE_SLIPIF #if SLIP_PTY_TEST u8_t siodev_slip = 3; #else u8_t siodev_slip = 0; #endif #if LWIP_IPV4 netif_add(&slipif, ip_2_ip4(&ipaddr_slip), ip_2_ip4(&netmask_slip), ip_2_ip4(&gw_slip), (void*)&siodev_slip, slipif_init, tcpip_input); #else /* LWIP_IPV4 */ netif_add(&slipif, (void*)&siodev_slip, slipif_init, tcpip_input); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 netif_create_ip6_linklocal_address(&slipif, 1); #endif #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&slipif, netif_status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ netif_set_link_up(&slipif); netif_set_up(&slipif); #endif /* LWIP_HAVE_SLIPIF */ #if PPP_SUPPORT #if PPP_PTY_TEST ppp_sio = sio_open(2); #else ppp_sio = sio_open(0); #endif if(!ppp_sio) { perror("Error opening device: "); exit(1); } ppp = pppos_create(&pppos_netif, ppp_output_cb, ppp_link_status_cb, NULL); if (!ppp) { printf("Could not create PPP control interface"); exit(1); } #ifdef LWIP_PPP_CHAP_TEST ppp_set_auth(ppp, PPPAUTHTYPE_CHAP, "lwip", "mysecret"); #endif ppp_connect(ppp, 0); #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&pppos_netif, netif_status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ #endif /* PPP_SUPPORT */ #if LWIP_IPV4 #if LWIP_DHCP IP_ADDR4(&gw, 0,0,0,0); IP_ADDR4(&ipaddr, 0,0,0,0); IP_ADDR4(&netmask, 0,0,0,0); #endif /* LWIP_DHCP */ netif_add(&netif, ip_2_ip4(&ipaddr), ip_2_ip4(&netmask), ip_2_ip4(&gw), NULL, tapif_init, tcpip_input); #else /* LWIP_IPV4 */ netif_add(&netif, NULL, tapif_init, tcpip_input); #endif /* LWIP_IPV4 */ #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif, 1); netif.ip6_autoconfig_enabled = 1; #endif #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&netif, netif_status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ netif_set_default(&netif); netif_set_up(&netif); #if LWIP_DHCP dhcp_start(&netif); #endif /* LWIP_DHCP */ #if 0 /* Only used for testing purposes: */ netif_add(&ipaddr, &netmask, &gw, NULL, pcapif_init, tcpip_input); #endif #if LWIP_TCP netio_init(); #endif #if LWIP_TCP && LWIP_NETCONN tcpecho_init(); shell_init(); httpd_init(); #endif #if LWIP_UDP && LWIP_NETCONN udpecho_init(); #endif #if LWIP_SOCKET chargen_init(); #endif /* sys_timeout(5000, tcp_debug_timeout, NULL);*/ } /*-----------------------------------------------------------------------------------*/ static void main_thread(void *arg) { sys_sem_t sem; LWIP_UNUSED_ARG(arg); if(sys_sem_new(&sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } tcpip_init(tcpip_init_done, &sem); sys_sem_wait(&sem); printf("TCP/IP initialized.\n"); #if LWIP_SOCKET if(ping_flag) { sys_thread_new("ping_thread", ping_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); } #endif printf("Applications started.\n"); #ifdef MEM_PERF mem_perf_init("/tmp/memstats.client"); #endif /* MEM_PERF */ #if 0 stats_display(); #endif #if PPP_SUPPORT /* Block forever. */ sys_thread_new("pppos_rx_thread", pppos_rx_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); sys_sem_wait(&sem); #endif } /*-----------------------------------------------------------------------------------*/ int main(int argc, char **argv) { int ch; char ip_str[16] = {0}; /* startup defaults (may be overridden by one or more opts) */ #if LWIP_IPV4 IP_ADDR4(&gw, 192,168, 0,1); IP_ADDR4(&netmask, 255,255,255,0); IP_ADDR4(&ipaddr, 192,168, 0,2); #if LWIP_HAVE_SLIPIF IP_ADDR4(&gw_slip, 192,168, 2, 1); IP_ADDR4(&netmask_slip, 255,255,255,255); IP_ADDR4(&ipaddr_slip, 192,168, 2, 2); #endif #endif /* LWIP_IPV4 */ ping_flag = 0; /* use debug flags defined by debug.h */ debug_flags = LWIP_DBG_OFF; while ((ch = getopt_long(argc, argv, "dhg:i:m:p:", longopts, NULL)) != -1) { switch (ch) { case 'd': debug_flags |= (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH|LWIP_DBG_HALT); break; case 'h': usage(); exit(0); break; #if LWIP_IPV4 case 'g': ipaddr_aton(optarg, &gw); break; case 'i': ipaddr_aton(optarg, &ipaddr); break; case 'm': ipaddr_aton(optarg, &netmask); break; #endif /* LWIP_IPV4 */ case 'p': ping_flag = !0; ipaddr_aton(optarg, &ping_addr); strncpy(ip_str,ipaddr_ntoa(&ping_addr),sizeof(ip_str)); ip_str[sizeof(ip_str)-1] = 0; /* ensure \0 termination */ printf("Using %s to ping\n", ip_str); break; default: usage(); break; } } argc -= optind; argv += optind; #ifdef PERF perf_init("/tmp/simhost.perf"); #endif /* PERF */ printf("System initialized.\n"); sys_thread_new("main_thread", main_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); pause(); return 0; } /*-----------------------------------------------------------------------------------*/
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/unixsim/simhost.c
C
unknown
19,847
/* * Copyright (c) 2001-2003 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 "lwip/debug.h" #include <unistd.h> #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/sys.h" #include "lwip/tcp.h" #include "lwip/priv/tcp_priv.h" /* for tcp_debug_print_pcbs() */ #include "lwip/timeouts.h" #include "lwip/stats.h" #include "lwip/tcpip.h" #include "netif/unixif.h" #include "netif/dropif.h" #include "netif/tcpdump.h" #include "lwip/ip_addr.h" #include "arch/perf.h" #include "lwip/apps/httpd.h" #include "apps/udpecho/udpecho.h" #include "apps/tcpecho/tcpecho.h" #include "apps/shell/shell.h" #if LWIP_IPV4 /* @todo: IPv6 */ /* nonstatic debug cmd option, exported in lwipopts.h */ unsigned char debug_flags; /*-----------------------------------------------------------------------------------*/ static void tcp_timeout(void *data) { LWIP_UNUSED_ARG(data); #if TCP_DEBUG && LWIP_TCP tcp_debug_print_pcbs(); #endif /* TCP_DEBUG */ sys_timeout(5000, tcp_timeout, NULL); } /*-----------------------------------------------------------------------------------*/ struct netif netif_unix; /*-----------------------------------------------------------------------------------*/ static void tcpip_init_done(void *arg) { ip4_addr_t ipaddr, netmask, gw; sys_sem_t *sem; sem = (sys_sem_t *)arg; IP4_ADDR(&gw, 192,168,1,1); IP4_ADDR(&ipaddr, 192,168,1,2); IP4_ADDR(&netmask, 255,255,255,0); netif_set_default(netif_add(&netif_unix, &ipaddr, &netmask, &gw, NULL, unixif_init_client, tcpip_input)); netif_set_up(&netif_unix); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif_unix, 1); #endif /* netif_set_default(netif_add(&ipaddr, &netmask, &gw, NULL, sioslipif_init1, tcpip_input)); */ #if LWIP_NETCONN tcpecho_init(); shell_init(); #if LWIP_IPV4 && LWIP_TCP httpd_init(); #endif udpecho_init(); #endif printf("Applications started.\n"); sys_timeout(5000, tcp_timeout, NULL); sys_sem_signal(sem); } /*-----------------------------------------------------------------------------------*/ static void main_thread(void *arg) { sys_sem_t sem; LWIP_UNUSED_ARG(arg); if(sys_sem_new(&sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } tcpip_init(tcpip_init_done, &sem); sys_sem_wait(&sem); printf("TCP/IP initialized.\n"); #ifdef MEM_PERF mem_perf_init("/tmp/memstats.client"); #endif /* MEM_PERF */ /* Block forever. */ sys_sem_wait(&sem); } /*-----------------------------------------------------------------------------------*/ int main(void) { #ifdef PERF perf_init("/tmp/client.perf"); #endif /* PERF */ #if LWIP_IPV4 && LWIP_TCP tcpdump_init(); #endif printf("System initialized.\n"); sys_thread_new("main_thread", main_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); pause(); return 0; } #else /* LWIP_IPV4 */ int main(int argc, char **argv) { LWIP_UNUSED_ARG(argc); LWIP_UNUSED_ARG(argv); printf("simnode only works with IPv4\n"); return 0; } #endif /* LWIP_IPV4 */ /* dummy, because SNTP is pulled in via LWIP_DHCP_GET_NTP_SRV */ void sntp_set_system_time(u32_t sec) { LWIP_UNUSED_ARG(sec); } /*-----------------------------------------------------------------------------------*/
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/unixsim/simnode.c
C
unknown
4,978
/* * Copyright (c) 2001-2003 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 "lwip/debug.h" #include <unistd.h> #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/sys.h" #include "lwip/tcp.h" #include "lwip/priv/tcp_priv.h" /* for tcp_debug_print_pcbs() */ #include "lwip/timeouts.h" #include "lwip/stats.h" #include "lwip/tcpip.h" #include "netif/tapif.h" #include "netif/unixif.h" #include "netif/dropif.h" #include "netif/tcpdump.h" #include "lwip/ip_addr.h" #include "arch/perf.h" #include "lwip/apps/httpd.h" #include "apps/udpecho/udpecho.h" #include "apps/tcpecho/tcpecho.h" #include "apps/shell/shell.h" #if LWIP_IPV4 /* @todo: IPv6 */ /* nonstatic debug cmd option, exported in lwipopts.h */ unsigned char debug_flags; /*-----------------------------------------------------------------------------------*/ static void tcp_timeout(void *data) { LWIP_UNUSED_ARG(data); #if TCP_DEBUG && LWIP_TCP tcp_debug_print_pcbs(); #endif /* TCP_DEBUG */ sys_timeout(5000, tcp_timeout, NULL); } /*-----------------------------------------------------------------------------------*/ struct netif netif_tap, netif_unix; /*-----------------------------------------------------------------------------------*/ static void tcpip_init_done(void *arg) { ip4_addr_t ipaddr, netmask, gw; sys_sem_t *sem; sem = (sys_sem_t *)arg; IP4_ADDR(&gw, 192,168,0,1); IP4_ADDR(&ipaddr, 192,168,0,2); IP4_ADDR(&netmask, 255,255,255,0); netif_set_default(netif_add(&netif_tap, &ipaddr, &netmask, &gw, NULL, tapif_init, tcpip_input)); netif_set_up(&netif_tap); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif_tap, 1); #endif IP4_ADDR(&gw, 192,168,1,1); IP4_ADDR(&ipaddr, 192,168,1,1); IP4_ADDR(&netmask, 255,255,255,0); netif_set_default(netif_add(&netif_unix, &ipaddr, &netmask, &gw, NULL, unixif_init_server, tcpip_input)); netif_set_up(&netif_unix); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif_unix, 1); #endif system("route add 192.168.1.1 192.168.0.2"); system("route add 192.168.1.2 192.168.0.2"); /*netif_set_default(netif_add(&ipaddr, &netmask, &gw, NULL, sioslipif_init1, tcpip_input)); */ #if LWIP_NETCONN tcpecho_init(); shell_init(); #if LWIP_IPV4 && LWIP_TCP httpd_init(); #endif udpecho_init(); #endif printf("Applications started.\n"); sys_timeout(5000, tcp_timeout, NULL); sys_sem_signal(sem); } static void main_thread(void *arg) { sys_sem_t sem; LWIP_UNUSED_ARG(arg); if(sys_sem_new(&sem, 0) != ERR_OK) { LWIP_ASSERT("Failed to create semaphore", 0); } tcpip_init(tcpip_init_done, &sem); sys_sem_wait(&sem); printf("TCP/IP initialized.\n"); #ifdef MEM_PERF mem_perf_init("/tmp/memstats.client"); #endif /* MEM_PERF */ /* Block forever. */ sys_sem_wait(&sem); } /*-----------------------------------------------------------------------------------*/ int main(void) { #ifdef PERF perf_init("/tmp/client.perf"); #endif /* PERF */ #if LWIP_IPV4 && LWIP_TCP tcpdump_init(); #endif printf("System initialized.\n"); sys_thread_new("main_thread", main_thread, NULL, DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO); pause(); return 0; } #else /* LWIP_IPV4 */ int main(int argc, char **argv) { LWIP_UNUSED_ARG(argc); LWIP_UNUSED_ARG(argv); printf("simrouter only works with IPv4\n"); return 0; } #endif /* LWIP_IPV4 */ /* dummy, because SNTP is pulled in via LWIP_DHCP_GET_NTP_SRV */ void sntp_set_system_time(u32_t sec) { LWIP_UNUSED_ARG(sec); } /*-----------------------------------------------------------------------------------*/
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/unix/unixsim/simrouter.c
C
unknown
5,379
/* config.h for check-0.9.8 on win32 under MSVC/MinGW */ #ifdef _MSC_VER typedef unsigned int pid_t; typedef unsigned int uint32_t; #define ssize_t size_t #define snprintf _snprintf #define HAVE_DECL_STRDUP 1 #define HAVE_DECL_FILENO 1 #define HAVE_DECL_PUTENV 1 #define _CRT_SECURE_NO_WARNINGS /* disable some warnings */ #pragma warning (disable: 4090) /* const assigned to non-const */ #pragma warning (disable: 4996) /* fileno is deprecated */ #endif /* _ MSC_VER */ #define LWIP_UNITTESTS_NOFORK #include <io.h>
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/check/config.h
C
unknown
553
#ifndef LWIP_SYS__TIME_H #define LWIP_SYS__TIME_H #include <stdlib.h> /* time_t */ struct timeval { time_t tv_sec; /* seconds */ long tv_usec; /* and microseconds */ }; int gettimeofday(struct timeval* tp, void* tzp); #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/check/sys/time.h
C
unknown
265
#include <time.h> #include <windows.h> #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif #include "config.h" struct timezone { int tz_minuteswest; /* minutes W of Greenwich */ int tz_dsttime; /* type of dst correction */ }; int gettimeofday(struct timeval *tv, struct timezone *tz) { FILETIME ft; unsigned __int64 tmpres = 0; static int tzflag; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; /*converting file time to unix epoch*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tmpres /= 10; /*convert into microseconds*/ tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } if (NULL != tz) { if (!tzflag) { _tzset(); tzflag++; } tz->tz_minuteswest = _timezone / 60; tz->tz_dsttime = _daylight; } return 0; } struct tm * localtime_r(const time_t *timer, struct tm *result) { struct tm *local_result; local_result = localtime (timer); if (local_result == NULL || result == NULL) return NULL; MEMCPY (result, local_result, sizeof (result)); return result; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/check/time.c
C
unknown
1,381
#ifndef LWIP_UNISTD_H #define LWIP_UNISTD_H /* include io.h for read() and write() */ #include <io.h> #endif
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/check/unistd.h
C
unknown
118
#pragma pack(push,1)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/arch/bpstruct.h
C
unknown
22
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_ARCH_CC_H #define LWIP_ARCH_CC_H #include <stdio.h> /* printf, fflush, FILE */ #include <stdlib.h> /* abort */ #include <limits.h> #ifdef _MSC_VER #pragma warning (disable: 4127) /* conditional expression is constant */ #pragma warning (disable: 4996) /* 'strncpy' was declared deprecated */ #pragma warning (disable: 4103) /* structure packing changed by including file */ #pragma warning (disable: 4820) /* 'x' bytes padding added after data member 'y' */ #endif #define LWIP_PROVIDE_ERRNO /* Define platform endianness (might already be defined) */ #ifndef BYTE_ORDER #define BYTE_ORDER LITTLE_ENDIAN #endif /* BYTE_ORDER */ typedef int sys_prot_t; #ifdef _MSC_VER /* define _INTPTR for Win32 MSVC stdint.h */ #define _INTPTR 2 /* Do not use lwIP default definitions for format strings * because these do not work with MSVC 2010 compiler (no inttypes.h) */ #define LWIP_NO_INTTYPES_H 1 /* Define (sn)printf formatters for these lwIP types */ #define X8_F "02x" #define U16_F "hu" #define U32_F "lu" #define S32_F "ld" #define X32_F "lx" #define S16_F "hd" #define X16_F "hx" #define SZT_F "lu" #endif /* _MSC_VER */ /* Compiler hints for packing structures */ #define PACK_STRUCT_STRUCT #define PACK_STRUCT_USE_INCLUDES /* Plaform specific diagnostic output */ #define LWIP_PLATFORM_DIAG(x) do { printf x; } while(0) #define LWIP_PLATFORM_ASSERT(x) do { printf("Assertion \"%s\" failed at line %d in %s\n", \ x, __LINE__, __FILE__); fflush(NULL); abort(); } while(0) #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ printf("Assertion \"%s\" failed at line %d in %s\n", message, __LINE__, __FILE__); \ fflush(NULL);handler;} } while(0) #ifdef _MSC_VER /* C runtime functions redefined */ #define snprintf _snprintf #define strdup _strdup #endif #define LWIP_RAND() ((u32_t)rand()) #define PPP_INCLUDE_SETTINGS_HEADER #endif /* LWIP_ARCH_CC_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/arch/cc.h
C
unknown
3,662
#pragma pack(pop)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/arch/epstruct.h
C
unknown
19
/* * Copyright (c) 2001, 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. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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> * */ #ifndef LWIP_PERF_H #define LWIP_PERF_H #define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */ #endif /* LWIP_PERF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/arch/perf.h
C
unknown
1,899
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_ARCH_SYS_ARCH_H #define LWIP_ARCH_SYS_ARCH_H /* HANDLE is used for sys_sem_t but we won't include windows.h */ struct _sys_sem { void *sem; }; typedef struct _sys_sem sys_sem_t; #define sys_sem_valid(sema) (((sema) != NULL) && ((sema)->sem != NULL) && ((sema)->sem != (void*)-1)) #define sys_sem_set_invalid(sema) ((sema)->sem = NULL) /* HANDLE is used for sys_mutex_t but we won't include windows.h */ struct _sys_mut { void *mut; }; typedef struct _sys_mut sys_mutex_t; #define sys_mutex_valid(mutex) (((mutex) != NULL) && ((mutex)->mut != NULL) && ((mutex)->mut != (void*)-1)) #define sys_mutex_set_invalid(mutex) ((mutex)->mut = NULL) #ifndef MAX_QUEUE_ENTRIES #define MAX_QUEUE_ENTRIES 100 #endif struct lwip_mbox { void* sem; void* q_mem[MAX_QUEUE_ENTRIES]; u32_t head, tail; }; typedef struct lwip_mbox sys_mbox_t; #define SYS_MBOX_NULL NULL #define sys_mbox_valid(mbox) ((mbox != NULL) && ((mbox)->sem != NULL) && ((mbox)->sem != (void*)-1)) #define sys_mbox_set_invalid(mbox) ((mbox)->sem = NULL) /* DWORD (thread id) is used for sys_thread_t but we won't include windows.h */ typedef u32_t sys_thread_t; sys_sem_t* sys_arch_netconn_sem_get(void); void sys_arch_netconn_sem_alloc(void); void sys_arch_netconn_sem_free(void); #define LWIP_NETCONN_THREAD_SEM_GET() sys_arch_netconn_sem_get() #define LWIP_NETCONN_THREAD_SEM_ALLOC() sys_arch_netconn_sem_alloc() #define LWIP_NETCONN_THREAD_SEM_FREE() sys_arch_netconn_sem_free() #endif /* LWIP_ARCH_SYS_ARCH_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/arch/sys_arch.h
C
unknown
3,188
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_LWIPOPTS_H #define LWIP_LWIPOPTS_H #define LWIP_IPV4 1 #define LWIP_IPV6 1 #define NO_SYS 0 #define LWIP_SOCKET (NO_SYS==0) #define LWIP_NETCONN (NO_SYS==0) #define LWIP_IGMP LWIP_IPV4 #define LWIP_ICMP LWIP_IPV4 #define LWIP_SNMP LWIP_UDP #define MIB2_STATS LWIP_SNMP #define LWIP_DNS LWIP_UDP #define LWIP_MDNS_RESPONDER LWIP_UDP #define LWIP_NUM_NETIF_CLIENT_DATA (LWIP_MDNS_RESPONDER) #define LWIP_HAVE_LOOPIF 1 #define LWIP_NETIF_LOOPBACK 1 #define LWIP_LOOPBACK_MAX_PBUFS 10 #define TCP_LISTEN_BACKLOG 1 #define LWIP_COMPAT_SOCKETS 1 #define LWIP_SO_RCVTIMEO 1 #define LWIP_SO_RCVBUF 1 #define LWIP_TCPIP_CORE_LOCKING 1 #define LWIP_NETIF_LINK_CALLBACK 1 #define LWIP_NETIF_STATUS_CALLBACK 1 #ifdef LWIP_DEBUG #define LWIP_DBG_MIN_LEVEL 0 #define PPP_DEBUG LWIP_DBG_OFF #define MEM_DEBUG LWIP_DBG_OFF #define MEMP_DEBUG LWIP_DBG_OFF #define PBUF_DEBUG LWIP_DBG_OFF #define API_LIB_DEBUG LWIP_DBG_OFF #define API_MSG_DEBUG LWIP_DBG_OFF #define TCPIP_DEBUG LWIP_DBG_OFF #define NETIF_DEBUG LWIP_DBG_OFF #define SOCKETS_DEBUG LWIP_DBG_OFF #define DNS_DEBUG LWIP_DBG_OFF #define AUTOIP_DEBUG LWIP_DBG_OFF #define DHCP_DEBUG LWIP_DBG_OFF #define IP_DEBUG LWIP_DBG_OFF #define IP_REASS_DEBUG LWIP_DBG_OFF #define ICMP_DEBUG LWIP_DBG_OFF #define IGMP_DEBUG LWIP_DBG_OFF #define UDP_DEBUG LWIP_DBG_OFF #define TCP_DEBUG LWIP_DBG_OFF #define TCP_INPUT_DEBUG LWIP_DBG_OFF #define TCP_OUTPUT_DEBUG LWIP_DBG_OFF #define TCP_RTO_DEBUG LWIP_DBG_OFF #define TCP_CWND_DEBUG LWIP_DBG_OFF #define TCP_WND_DEBUG LWIP_DBG_OFF #define TCP_FR_DEBUG LWIP_DBG_OFF #define TCP_QLEN_DEBUG LWIP_DBG_OFF #define TCP_RST_DEBUG LWIP_DBG_OFF #endif #define LWIP_DBG_TYPES_ON (LWIP_DBG_ON|LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_FRESH|LWIP_DBG_HALT) /* ---------- Memory options ---------- */ /* MEM_ALIGNMENT: should be set to the alignment of the CPU for which lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2 byte alignment -> define MEM_ALIGNMENT to 2. */ /* MSVC port: intel processors don't need 4-byte alignment, but are faster that way! */ #define MEM_ALIGNMENT 4 /* MEM_SIZE: the size of the heap memory. If the application will send a lot of data that needs to be copied, this should be set high. */ #define MEM_SIZE 10240 /* MEMP_NUM_PBUF: the number of memp struct pbufs. If the application sends a lot of data out of ROM (or other static memory), this should be set high. */ #define MEMP_NUM_PBUF 16 /* MEMP_NUM_RAW_PCB: the number of UDP protocol control blocks. One per active RAW "connection". */ #define MEMP_NUM_RAW_PCB 3 /* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One per active UDP "connection". */ #define MEMP_NUM_UDP_PCB 4 /* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP connections. */ #define MEMP_NUM_TCP_PCB 5 /* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP connections. */ #define MEMP_NUM_TCP_PCB_LISTEN 8 /* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP segments. */ #define MEMP_NUM_TCP_SEG 16 /* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active timeouts. */ #define MEMP_NUM_SYS_TIMEOUT 15 /* The following four are used only with the sequential API and can be set to 0 if the application only will use the raw API. */ /* MEMP_NUM_NETBUF: the number of struct netbufs. */ #define MEMP_NUM_NETBUF 2 /* MEMP_NUM_NETCONN: the number of struct netconns. */ #define MEMP_NUM_NETCONN 10 /* MEMP_NUM_TCPIP_MSG_*: the number of struct tcpip_msg, which is used for sequential API communication and incoming packets. Used in src/api/tcpip.c. */ #define MEMP_NUM_TCPIP_MSG_API 16 #define MEMP_NUM_TCPIP_MSG_INPKT 16 /* ---------- Pbuf options ---------- */ /* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ #define PBUF_POOL_SIZE 160 /* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ #define PBUF_POOL_BUFSIZE 128 /* PBUF_LINK_HLEN: the number of bytes that should be allocated for a link level header. */ #define PBUF_LINK_HLEN 16 /** SYS_LIGHTWEIGHT_PROT * define SYS_LIGHTWEIGHT_PROT in lwipopts.h if you want inter-task protection * for certain critical regions during buffer allocation, deallocation and memory * allocation and deallocation. */ #define SYS_LIGHTWEIGHT_PROT (NO_SYS==0) /* ---------- TCP options ---------- */ #define LWIP_TCP 1 #define TCP_TTL 255 /* Controls if TCP should queue segments that arrive out of order. Define to 0 if your device is low on memory. */ #define TCP_QUEUE_OOSEQ 1 /* TCP Maximum segment size. */ #define TCP_MSS 1024 /* TCP sender buffer space (bytes). */ #define TCP_SND_BUF 2048 /* TCP sender buffer space (pbufs). This must be at least = 2 * TCP_SND_BUF/TCP_MSS for things to work. */ #define TCP_SND_QUEUELEN (4 * TCP_SND_BUF/TCP_MSS) /* TCP writable space (bytes). This must be less than or equal to TCP_SND_BUF. It is the amount of space which must be available in the tcp snd_buf for select to return writable */ #define TCP_SNDLOWAT (TCP_SND_BUF/2) /* TCP receive window. */ #define TCP_WND 8096 /* Maximum number of retransmissions of data segments. */ #define TCP_MAXRTX 12 /* Maximum number of retransmissions of SYN segments. */ #define TCP_SYNMAXRTX 4 /* ---------- ARP options ---------- */ #define LWIP_ARP 1 #define ARP_TABLE_SIZE 10 #define ARP_QUEUEING 1 /* ---------- IP options ---------- */ /* Define IP_FORWARD to 1 if you wish to have the ability to forward IP packets across network interfaces. If you are going to run lwIP on a device with only one network interface, define this to 0. */ #define IP_FORWARD 1 /* IP reassembly and segmentation.These are orthogonal even * if they both deal with IP fragments */ #define IP_REASSEMBLY 1 #define IP_REASS_MAX_PBUFS 10 #define MEMP_NUM_REASSDATA 10 #define IP_FRAG 1 /* ---------- ICMP options ---------- */ #define ICMP_TTL 255 /* ---------- DHCP options ---------- */ /* Define LWIP_DHCP to 1 if you want DHCP configuration of interfaces. */ #define LWIP_DHCP 1 /* 1 if you want to do an ARP check on the offered address (recommended). */ #define DHCP_DOES_ARP_CHECK (LWIP_DHCP) /* ---------- AUTOIP options ------- */ #define LWIP_AUTOIP (LWIP_DHCP) #define LWIP_DHCP_AUTOIP_COOP (LWIP_DHCP && LWIP_AUTOIP) /* ---------- UDP options ---------- */ #define LWIP_UDP 1 #define LWIP_UDPLITE LWIP_UDP #define UDP_TTL 255 /* ---------- RAW options ---------- */ #define LWIP_RAW 1 /* ---------- Statistics options ---------- */ #define LWIP_STATS 1 #define LWIP_STATS_DISPLAY 1 #if LWIP_STATS #define LINK_STATS 1 #define IP_STATS 1 #define ICMP_STATS 1 #define IGMP_STATS 1 #define IPFRAG_STATS 1 #define UDP_STATS 1 #define TCP_STATS 1 #define MEM_STATS 1 #define MEMP_STATS 1 #define PBUF_STATS 1 #define SYS_STATS 1 #endif /* LWIP_STATS */ /* ---------- PPP options ---------- */ #define PPP_SUPPORT 1 /* Set > 0 for PPP */ #if PPP_SUPPORT #define NUM_PPP 1 /* Max PPP sessions. */ /* Select modules to enable. Ideally these would be set in the makefile but * we're limited by the command line length so you need to modify the settings * in this file. */ #define PPPOE_SUPPORT 1 #define PPPOS_SUPPORT 1 #define PAP_SUPPORT 1 /* Set > 0 for PAP. */ #define CHAP_SUPPORT 1 /* Set > 0 for CHAP. */ #define MSCHAP_SUPPORT 0 /* Set > 0 for MSCHAP */ #define CBCP_SUPPORT 0 /* Set > 0 for CBCP (NOT FUNCTIONAL!) */ #define CCP_SUPPORT 0 /* Set > 0 for CCP */ #define VJ_SUPPORT 1 /* Set > 0 for VJ header compression. */ #define MD5_SUPPORT 1 /* Set > 0 for MD5 (see also CHAP) */ #endif /* PPP_SUPPORT */ #endif /* LWIP_LWIPOPTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/lwipopts.h
C
unknown
10,890
#ifdef _MSC_VER #pragma warning (disable: 4242) /* PPP only: conversion from 'x' to 'y', possible loss of data */ #pragma warning (disable: 4244) /* PPP only: conversion from 'x' to 'y', possible loss of data (again?) */ #pragma warning (disable: 4310) /* PPP only: cast truncates constant value */ #pragma warning (disable: 4706) /* PPP only: assignment within conditional expression */ #endif /* MSC_VER */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/include/ppp_settings.h
C
unknown
416
/* OPTIONAL: Pools to replace heap allocation * Optional: Pools can be used instead of the heap for mem_malloc. If * so, these should be defined here, in increasing order according to * the pool element size. * * LWIP_MALLOC_MEMPOOL(number_elements, element_size) */ #if MEM_USE_POOLS LWIP_MALLOC_MEMPOOL_START LWIP_MALLOC_MEMPOOL(100, 256) LWIP_MALLOC_MEMPOOL(50, 512) LWIP_MALLOC_MEMPOOL(20, 1024) LWIP_MALLOC_MEMPOOL(20, 1536) LWIP_MALLOC_MEMPOOL_END #endif /* MEM_USE_POOLS */ /* Optional: Your custom pools can go here if you would like to use * lwIP's memory pools for anything else. */ LWIP_MEMPOOL(SYS_MBOX, 22, 100, "SYS_MBOX")
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/lwippools.h
C
unknown
667
# # Copyright (c) 2001, 2002 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> # CCDEP=gcc CC=gcc CFLAGS=-g -Wall -DLWIP_DEBUG -pedantic -Werror \ -Wparentheses -Wsequence-point -Wswitch-default \ -Wextra -Wundef -Wshadow -Wpointer-arith -Wcast-qual \ -Wc++-compat -Wwrite-strings -Wold-style-definition -Wcast-align \ -Wmissing-prototypes -Wredundant-decls -Wnested-externs -Wno-address \ -Wunreachable-code -Wuninitialized -Wlogical-op -Wno-format # -Wno-format: GCC complains about non-standard 64 bit modifier needed for MSVC runtime # not used for now but interesting: # -Wpacked # -ansi # -std=c89 LDFLAGS=-L$(PCAP_DIR)/lib -lwpcap -lpacket CONTRIBDIR=../../.. LWIPARCH=$(CONTRIBDIR)/ports/win32 ARFLAGS=rs #Set this to where you have the lwip core module checked out from CVS #default assumes it's a dir named lwip at the same level as the contrib module LWIPDIR=$(CONTRIBDIR)/../lwip/src PCAPDIR=$(PCAP_DIR)/Include CFLAGS+=-I. \ -I.. \ -I$(CONTRIBDIR) \ -I$(PCAPDIR) \ -I$(LWIPDIR)/include \ -I$(LWIPARCH)/include include $(CONTRIBDIR)/ports/Filelists.mk include $(LWIPDIR)/Filelists.mk # ARCHFILES: Architecture specific files. ARCHFILES=$(LWIPARCH)/sys_arch.c $(LWIPARCH)/test.c $(LWIPARCH)/pcapif.c \ $(LWIPARCH)/pcapif_helper.c $(LWIPARCH)/sio.c # LWIPFILES: All the above. LWIPFILES=$(LWIPNOAPPSFILES) $(ARCHFILES) LWIPOBJS=$(notdir $(LWIPFILES:.c=.o)) LWIPLIBCOMMON=liblwipcommon.a $(LWIPLIBCOMMON): $(LWIPOBJS) $(AR) $(ARFLAGS) $(LWIPLIBCOMMON) $? APPFILES=$(CONTRIBAPPFILES) $(LWIPAPPFILES) APPLIB=liblwipapps.a APPOBJS=$(notdir $(APPFILES:.c=.o)) $(APPLIB): $(APPOBJS) $(AR) $(ARFLAGS) $(APPLIB) $? %.o: $(CC) $(CFLAGS) -c $(<:.o=.c) pcapif.o: $(CC) $(CFLAGS) -Wno-error -Wno-redundant-decls -c $(<:.o=.c) pcapif_helper.o: $(CC) $(CFLAGS) -std=c99 -Wno-redundant-decls -c $(<:.o=.c)
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/mingw/Common.mk
Makefile
unknown
3,414
# # Copyright (c) 2001, 2002 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> # all ipv4 compile: test .PHONY: all include Common.mk clean: cmd /c del /q *.o $(LWIPLIBCOMMON) $(APPLIB) test.exe *.s .depend* depend dep: .depend include .depend .depend: $(LWIPFILES) $(APPFILES) $(CCDEP) $(CFLAGS) -MM $^ > .depend || cmd /c del .depend test: .depend $(LWIPLIBCOMMON) $(APPLIB) test.o $(CC) $(CFLAGS) -o test test.o -Wl,--start-group $(APPLIB) $(LWIPLIBCOMMON) -Wl,--end-group $(LDFLAGS) -Xlinker -Map=test.map
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/mingw/Makefile
Makefile
unknown
2,062
/** * pcapif.c - This file is part of lwIP pcapif * **************************************************************************** * * This file is derived from an example in lwIP with the following license: * * Copyright (c) 2001, 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. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``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 INSTITUTE OR CONTRIBUTORS 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. * */ /* include the port-dependent configuration */ #include "lwipcfg_msvc.h" #include <stdlib.h> #include <stdio.h> #ifdef _MSC_VER #pragma warning( push, 3 ) #include "pcap.h" #pragma warning ( pop ) #else /* e.g. mingw */ #define _MSC_VER 1500 #include "pcap.h" #undef _MSC_VER #endif #include "lwip/opt.h" #if LWIP_ETHERNET #include "pcapif.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/mem.h" #include "lwip/pbuf.h" #include "lwip/stats.h" #include "lwip/sys.h" #include "lwip/ip.h" #include "lwip/snmp.h" #include "lwip/tcpip.h" #include "lwip/timeouts.h" #include "lwip/ethip6.h" #include "lwip/etharp.h" /* For compatibility with old pcap */ #ifndef PCAP_OPENFLAG_PROMISCUOUS #define PCAP_OPENFLAG_PROMISCUOUS 1 #endif /** Set this to 0 to receive all multicast ethernet destination addresses */ #ifndef PCAPIF_FILTER_GROUP_ADDRESSES #define PCAPIF_FILTER_GROUP_ADDRESSES 1 #endif /** Set this to 1 to receive all frames (also unicast to other addresses; this is only needed for test purposes) */ #ifndef PCAPIF_RECEIVE_PROMISCUOUS #define PCAPIF_RECEIVE_PROMISCUOUS 0 #endif /* Define those to better describe your network interface. For now, we use 'e0', 'e1', 'e2' and so on */ #define IFNAME0 'e' #define IFNAME1 '0' /** index of the network adapter to use for lwIP */ #ifndef PACKET_LIB_ADAPTER_NR #define PACKET_LIB_ADAPTER_NR 0 #endif /** If 1, check link state and report it to lwIP. * If 0, don't check link state (lwIP link state is always UP). */ #ifndef PCAPIF_HANDLE_LINKSTATE #define PCAPIF_HANDLE_LINKSTATE 1 #endif /** If 1, use PBUF_REF for RX (for testing purposes mainly). * For this, LWIP_SUPPORT_CUSTOM_PBUF must be enabled. */ #ifndef PCAPIF_RX_REF #define PCAPIF_RX_REF 0 #endif /** This can be used when netif->state is used for something else in your * application (e.g. when wrapping a class around this interface). Just * make sure this define returns the state pointer set by * pcapif_low_level_init() (e.g. by using an offset or a callback). */ #ifndef PCAPIF_GET_STATE_PTR #define PCAPIF_GET_STATE_PTR(netif) ((netif)->state) #endif #if PCAPIF_HANDLE_LINKSTATE #include "pcapif_helper.h" /* Define "PHY" delay when "link up" */ #ifndef PCAPIF_LINKUP_DELAY #define PCAPIF_LINKUP_DELAY 0 #endif /* Define PCAPIF_RX_LOCK_LWIP and PCAPIF_RX_UNLOCK_LWIP if you need to lock the lwIP core before/after pbuf_alloc() or netif->input() are called on RX. */ #ifndef PCAPIF_RX_LOCK_LWIP #define PCAPIF_RX_LOCK_LWIP() #endif #ifndef PCAPIF_RX_UNLOCK_LWIP #define PCAPIF_RX_UNLOCK_LWIP() #endif #define PCAPIF_LINKCHECK_INTERVAL_MS 500 /* link state notification macro */ #if PCAPIF_LINKUP_DELAY #define PCAPIF_NOTIFY_LINKSTATE(netif, linkfunc) sys_timeout(PCAPIF_LINKUP_DELAY, (sys_timeout_handler)linkfunc, netif) #else /* PHY_LINKUP_DELAY */ #define PCAPIF_NOTIFY_LINKSTATE(netif, linkfunc) linkfunc(netif) #endif /* PHY_LINKUP_DELAY */ #endif /* PCAPIF_HANDLE_LINKSTATE */ #define ETH_MIN_FRAME_LEN 60U #define ETH_MAX_FRAME_LEN 1518U #define ADAPTER_NAME_LEN 128 #define ADAPTER_DESC_LEN 128 /* Packet Adapter informations */ struct pcapif_private { void *input_fn_arg; pcap_t *adapter; char name[ADAPTER_NAME_LEN]; char description[ADAPTER_DESC_LEN]; int shutdown_called; #if PCAPIF_RX_USE_THREAD volatile int rx_run; volatile int rx_running; #endif /* PCAPIF_RX_USE_THREAD */ #if PCAPIF_HANDLE_LINKSTATE struct pcapifh_linkstate *link_state; enum pcapifh_link_event last_link_event; #endif /* PCAPIF_HANDLE_LINKSTATE */ }; #if PCAPIF_RX_REF struct pcapif_pbuf_custom { struct pbuf_custom pc; struct pbuf* p; }; #endif /* PCAPIF_RX_REF */ /* Forward declarations. */ static void pcapif_input(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *packet); #ifdef PACKET_LIB_GET_ADAPTER_NETADDRESS /** Get the index of an adapter by its network address * * @param netaddr network address of the adapter (e.g. 192.168.1.0) * @return index of the adapter or negative on error */ static int get_adapter_index_from_addr(struct in_addr *netaddr, char *guid, size_t guid_len) { pcap_if_t *alldevs; pcap_if_t *d; char errbuf[PCAP_ERRBUF_SIZE+1]; int index = 0; memset(guid, 0, guid_len); /* Retrieve the interfaces list */ if (pcap_findalldevs(&alldevs, errbuf) == -1) { printf("Error in pcap_findalldevs: %s\n", errbuf); return -1; } /* Scan the list printing every entry */ for (d = alldevs; d != NULL; d = d->next, index++) { pcap_addr_t *a; for(a = d->addresses; a != NULL; a = a->next) { if (a->addr->sa_family == AF_INET) { ULONG a_addr = ((struct sockaddr_in *)a->addr)->sin_addr.s_addr; ULONG a_netmask = ((struct sockaddr_in *)a->netmask)->sin_addr.s_addr; ULONG a_netaddr = a_addr & a_netmask; ULONG addr = (*netaddr).s_addr; if (a_netaddr == addr) { int ret = -1; char name[128]; char *start, *end; size_t len = strlen(d->name); if(len > 127) { len = 127; } MEMCPY(name, d->name, len); name[len] = 0; start = strstr(name, "{"); if (start != NULL) { end = strstr(start, "}"); if (end != NULL) { size_t len = end - start + 1; MEMCPY(guid, start, len); ret = index; } } pcap_freealldevs(alldevs); return ret; } } } } printf("Network address not found.\n"); pcap_freealldevs(alldevs); return -1; } #endif /* PACKET_LIB_GET_ADAPTER_NETADDRESS */ #if defined(PACKET_LIB_GET_ADAPTER_NETADDRESS) || defined(PACKET_LIB_ADAPTER_GUID) /** Get the index of an adapter by its GUID * * @param adapter_guid GUID of the adapter * @return index of the adapter or negative on error */ static int get_adapter_index(const char* adapter_guid) { pcap_if_t *alldevs; pcap_if_t *d; char errbuf[PCAP_ERRBUF_SIZE+1]; int idx = 0; /* Retrieve the interfaces list */ if (pcap_findalldevs(&alldevs, errbuf) == -1) { printf("Error in pcap_findalldevs: %s\n", errbuf); return -1; } /* Scan the list and compare name vs. adapter_guid */ for (d = alldevs; d != NULL; d = d->next, idx++) { if(strstr(d->name, adapter_guid)) { pcap_freealldevs(alldevs); return idx; } } /* not found, dump all adapters */ printf("%d available adapters:\n", idx); for (d = alldevs, idx = 0; d != NULL; d = d->next, idx++) { printf("- %d: %s\n", idx, d->name); } pcap_freealldevs(alldevs); return -1; } #endif /* defined(PACKET_LIB_GET_ADAPTER_NETADDRESS) || defined(PACKET_LIB_ADAPTER_GUID) */ static pcap_t* pcapif_open_adapter(const char* adapter_name, char* errbuf) { pcap_t* adapter = pcap_open_live(adapter_name,/* name of the device */ 65536, /* portion of the packet to capture */ /* 65536 guarantees that the whole packet will be captured on all the link layers */ PCAP_OPENFLAG_PROMISCUOUS,/* promiscuous mode */ #if PCAPIF_RX_USE_THREAD /*-*/1, /* don't wait at all for lower latency */ #else 1, /* wait 1 ms in ethernetif_poll */ #endif errbuf); /* error buffer */ return adapter; } #if !PCAPIF_RX_USE_THREAD static void pcap_reopen_adapter(struct pcapif_private *pa) { char errbuf[PCAP_ERRBUF_SIZE+1]; pcap_if_t *alldevs; if (pa->adapter != NULL) { pcap_close(pa->adapter); pa->adapter = NULL; } if (pcap_findalldevs(&alldevs, errbuf) != -1) { pcap_if_t *d; for (d = alldevs; d != NULL; d = d->next) { if (!strcmp(d->name, pa->name)) { pa->adapter = pcapif_open_adapter(pa->name, errbuf); if (pa->adapter == NULL) { printf("failed to reopen pcap adapter after failure: %s\n", errbuf); } break; } } pcap_freealldevs(alldevs); } } #endif /** * Open a network adapter and set it up for packet input * * @param adapter_num the index of the adapter to use * @param arg argument to pass to input * @return an adapter handle on success, NULL on failure */ static struct pcapif_private* pcapif_init_adapter(int adapter_num, void *arg) { int i; int number_of_adapters; struct pcapif_private *pa; char errbuf[PCAP_ERRBUF_SIZE+1]; pcap_if_t *alldevs; pcap_if_t *d; pcap_if_t *used_adapter = NULL; pa = (struct pcapif_private *)malloc(sizeof(struct pcapif_private)); if (!pa) { printf("Unable to alloc the adapter!\n"); return NULL; } memset(pa, 0, sizeof(struct pcapif_private)); pa->input_fn_arg = arg; /* Retrieve the interfaces list */ if (pcap_findalldevs(&alldevs, errbuf) == -1) { free(pa); return NULL; /* no adapters found */ } /* get number of adapters and adapter pointer */ for (d = alldevs, number_of_adapters = 0; d != NULL; d = d->next, number_of_adapters++) { if (number_of_adapters == adapter_num) { char *desc = d->description; size_t len; len = strlen(d->name); LWIP_ASSERT("len < ADAPTER_NAME_LEN", len < ADAPTER_NAME_LEN); strcpy(pa->name, d->name); used_adapter = d; /* format vendor description */ if (desc != NULL) { len = strlen(desc); if (strstr(desc, " ' on local host") != NULL) { len -= 16; } else if (strstr(desc, "' on local host") != NULL) { len -= 15; } if (strstr(desc, "Network adapter '") == desc) { len -= 17; desc += 17; } len = LWIP_MIN(len, ADAPTER_DESC_LEN-1); while ((desc[len-1] == ' ') || (desc[len-1] == '\t')) { /* don't copy trailing whitespace */ len--; } strncpy(pa->description, desc, len); pa->description[len] = 0; } else { strcpy(pa->description, "<no_desc>"); } } } #ifndef PCAPIF_LIB_QUIET /* Scan the list printing every entry */ for (d = alldevs, i = 0; d != NULL; d = d->next, i++) { char *desc = d->description; char descBuf[128]; size_t len; const char* devname = d->name; if (d->name == NULL) { devname = "<unnamed>"; } else { if (strstr(devname, "\\Device\\") == devname) { /* windows: strip the first part */ devname += 8; } } printf("%2i: %s\n", i, devname); if (desc != NULL) { /* format vendor description */ len = strlen(desc); if (strstr(desc, " ' on local host") != NULL) { len -= 16; } else if (strstr(desc, "' on local host") != NULL) { len -= 15; } if (strstr(desc, "Network adapter '") == desc) { len -= 17; desc += 17; } len = LWIP_MIN(len, 127); while ((desc[len-1] == ' ') || (desc[len-1] == '\t')) { /* don't copy trailing whitespace */ len--; } strncpy(descBuf, desc, len); descBuf[len] = 0; printf(" Desc: \"%s\"\n", descBuf); } } #endif /* PCAPIF_LIB_QUIET */ /* invalid adapter index -> check this after printing the adapters */ if (adapter_num < 0) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); pcap_freealldevs(alldevs); return NULL; } /* adapter index out of range */ if (adapter_num >= number_of_adapters) { printf("Invalid adapter_num: %d\n", adapter_num); free(pa); pcap_freealldevs(alldevs); return NULL; } #ifndef PCAPIF_LIB_QUIET printf("Using adapter_num: %d\n", adapter_num); #endif /* PCAPIF_LIB_QUIET */ /* set up the selected adapter */ LWIP_ASSERT("used_adapter != NULL", used_adapter != NULL); /* Open the device */ pa->adapter = pcapif_open_adapter(used_adapter->name, errbuf); if (pa->adapter == NULL) { printf("\nUnable to open the adapter. %s is not supported by pcap (\"%s\").\n", used_adapter->name, errbuf); /* Free the device list */ pcap_freealldevs(alldevs); free(pa); return NULL; } printf("Using adapter: \"%s\"\n", pa->description); pcap_freealldevs(alldevs); #if PCAPIF_HANDLE_LINKSTATE pa->link_state = pcapifh_linkstate_init(pa->name); pa->last_link_event = PCAPIF_LINKEVENT_UNKNOWN; #endif /* PCAPIF_HANDLE_LINKSTATE */ return pa; } #if PCAPIF_HANDLE_LINKSTATE static void pcapif_check_linkstate(void *netif_ptr) { struct netif *netif = (struct netif*)netif_ptr; struct pcapif_private *pa = (struct pcapif_private*)PCAPIF_GET_STATE_PTR(netif); enum pcapifh_link_event le; le = pcapifh_linkstate_get(pa->link_state); if (pa->last_link_event != le) { pa->last_link_event = le; switch (le) { case PCAPIF_LINKEVENT_UP: { PCAPIF_NOTIFY_LINKSTATE(netif, netif_set_link_up); break; } case PCAPIF_LINKEVENT_DOWN: { PCAPIF_NOTIFY_LINKSTATE(netif, netif_set_link_down); break; } case PCAPIF_LINKEVENT_UNKNOWN: /* fall through */ default: break; } } sys_timeout(PCAPIF_LINKCHECK_INTERVAL_MS, pcapif_check_linkstate, netif); } #endif /* PCAPIF_HANDLE_LINKSTATE */ /** * Close the adapter (no more packets can be sent or received) * * @param netif netif to shutdown */ void pcapif_shutdown(struct netif *netif) { struct pcapif_private *pa = (struct pcapif_private*)PCAPIF_GET_STATE_PTR(netif); if (pa) { #if PCAPIF_RX_USE_THREAD pa->rx_run = 0; #endif /* PCAPIF_RX_USE_THREAD */ if (pa->adapter) { pcap_breakloop(pa->adapter); pcap_close(pa->adapter); } #if PCAPIF_RX_USE_THREAD /* wait for rxthread to end */ while(pa->rx_running); #endif /* PCAPIF_RX_USE_THREAD */ #if PCAPIF_HANDLE_LINKSTATE pcapifh_linkstate_close(pa->link_state); #endif /* PCAPIF_HANDLE_LINKSTATE */ free(pa); } } #if PCAPIF_RX_USE_THREAD /** RX running in its own thread */ static void pcapif_input_thread(void *arg) { struct netif *netif = (struct netif *)arg; struct pcapif_private *pa = (struct pcapif_private*)PCAPIF_GET_STATE_PTR(netif); do { struct pcap_pkthdr pkt_header; const u_char *packet = pcap_next(pa->adapter, &pkt_header); if(packet != NULL) { pcapif_input((u_char*)pa, &pkt_header, packet); } } while (pa->rx_run); pa->rx_running = 0; } #endif /* PCAPIF_RX_USE_THREAD */ /** Low-level initialization: find the correct adapter and initialize it. */ static void pcapif_low_level_init(struct netif *netif) { u8_t my_mac_addr[ETH_HWADDR_LEN] = LWIP_MAC_ADDR_BASE; int adapter_num = PACKET_LIB_ADAPTER_NR; struct pcapif_private *pa; #ifdef PACKET_LIB_GET_ADAPTER_NETADDRESS ip4_addr_t netaddr; #define GUID_LEN 128 char guid[GUID_LEN + 1]; #endif /* PACKET_LIB_GET_ADAPTER_NETADDRESS */ /* If 'state' is != NULL at this point, we assume it is an 'int' giving the index of the adapter to use (+ 1 because 0==NULL is invalid). This can be used to instantiate multiple PCAP drivers. */ if (netif->state != NULL) { adapter_num = ((int)(size_t)netif->state) - 1; if (adapter_num < 0) { printf("ERROR: invalid adapter index \"%d\"!\n", adapter_num); LWIP_ASSERT("ERROR initializing network adapter!\n", 0); return; } } #ifdef PACKET_LIB_GET_ADAPTER_NETADDRESS memset(&guid, 0, sizeof(guid)); PACKET_LIB_GET_ADAPTER_NETADDRESS(&netaddr); if (get_adapter_index_from_addr((struct in_addr *)&netaddr, guid, GUID_LEN) < 0) { printf("ERROR initializing network adapter, failed to get GUID for network address %s\n", ip4addr_ntoa(&netaddr)); LWIP_ASSERT("ERROR initializing network adapter, failed to get GUID for network address!", 0); return; } adapter_num = get_adapter_index(guid); if (adapter_num < 0) { printf("ERROR finding network adapter with GUID \"%s\"!\n", guid); LWIP_ASSERT("ERROR finding network adapter with expected GUID!", 0); return; } #else /* PACKET_LIB_GET_ADAPTER_NETADDRESS */ #ifdef PACKET_LIB_ADAPTER_GUID /* get adapter index for guid string */ adapter_num = get_adapter_index(PACKET_LIB_ADAPTER_GUID); if (adapter_num < 0) { printf("ERROR finding network adapter with GUID \"%s\"!\n", PACKET_LIB_ADAPTER_GUID); LWIP_ASSERT("ERROR initializing network adapter!\n", 0); return; } #endif /* PACKET_LIB_ADAPTER_GUID */ #endif /* PACKET_LIB_GET_ADAPTER_NETADDRESS */ /* Do whatever else is needed to initialize interface. */ pa = pcapif_init_adapter(adapter_num, netif); if (pa == NULL) { printf("ERROR initializing network adapter %d!\n", adapter_num); LWIP_ASSERT("ERROR initializing network adapter!", 0); return; } netif->state = pa; /* change the MAC address to a unique value so that multiple ethernetifs are supported */ /* @todo: this does NOT support multiple processes using this adapter! */ my_mac_addr[ETH_HWADDR_LEN - 1] += netif->num; /* Copy MAC addr */ SMEMCPY(&netif->hwaddr, my_mac_addr, ETH_HWADDR_LEN); /* get the initial link state of the selected interface */ #if PCAPIF_HANDLE_LINKSTATE pa->last_link_event = pcapifh_linkstate_get(pa->link_state); if (pa->last_link_event == PCAPIF_LINKEVENT_DOWN) { netif_set_link_down(netif); } else { netif_set_link_up(netif); } sys_timeout(PCAPIF_LINKCHECK_INTERVAL_MS, pcapif_check_linkstate, netif); #endif /* PCAPIF_HANDLE_LINKSTATE */ #if PCAPIF_RX_USE_THREAD pa->rx_run = 1; pa->rx_running = 1; sys_thread_new("pcapif_rxthread", pcapif_input_thread, netif, 0, 0); #endif LWIP_DEBUGF(NETIF_DEBUG, ("pcapif: eth_addr %02X%02X%02X%02X%02X%02X\n",netif->hwaddr[0],netif->hwaddr[1],netif->hwaddr[2],netif->hwaddr[3],netif->hwaddr[4],netif->hwaddr[5])); } /** low_level_output(): * Transmit a packet. The packet is contained in the pbuf that is passed to * the function. This pbuf might be chained. */ static err_t pcapif_low_level_output(struct netif *netif, struct pbuf *p) { struct pbuf *q; unsigned char buffer[ETH_MAX_FRAME_LEN + ETH_PAD_SIZE]; unsigned char *buf = buffer; unsigned char *ptr; struct eth_hdr *ethhdr; u16_t tot_len = p->tot_len - ETH_PAD_SIZE; struct pcapif_private *pa = (struct pcapif_private*)PCAPIF_GET_STATE_PTR(netif); #if defined(LWIP_DEBUG) && LWIP_NETIF_TX_SINGLE_PBUF && !(LWIP_IPV4 && IP_FRAG) && (LWIP_IPV6 && LWIP_IPV6_FRAG) LWIP_ASSERT("p->next == NULL && p->len == p->tot_len", p->next == NULL && p->len == p->tot_len); #endif /* initiate transfer */ if ((p->len == p->tot_len) && (p->len >= ETH_MIN_FRAME_LEN + ETH_PAD_SIZE)) { /* no pbuf chain, don't have to copy -> faster */ buf = &((unsigned char*)p->payload)[ETH_PAD_SIZE]; } else { /* pbuf chain, copy into contiguous buffer */ if (p->tot_len >= sizeof(buffer)) { LINK_STATS_INC(link.lenerr); LINK_STATS_INC(link.drop); MIB2_STATS_NETIF_INC(netif, ifoutdiscards); return ERR_BUF; } ptr = buffer; for(q = p; q != NULL; q = q->next) { /* Send the data from the pbuf to the interface, one pbuf at a time. The size of the data in each pbuf is kept in the ->len variable. */ /* send data from(q->payload, q->len); */ LWIP_DEBUGF(NETIF_DEBUG, ("netif: send ptr %p q->payload %p q->len %i q->next %p\n", ptr, q->payload, (int)q->len, (void*)q->next)); if (q == p) { MEMCPY(ptr, &((char*)q->payload)[ETH_PAD_SIZE], q->len - ETH_PAD_SIZE); ptr += q->len - ETH_PAD_SIZE; } else { MEMCPY(ptr, q->payload, q->len); ptr += q->len; } } } if (tot_len < ETH_MIN_FRAME_LEN) { /* ensure minimal frame length */ memset(&buf[tot_len], 0, ETH_MIN_FRAME_LEN - tot_len); tot_len = ETH_MIN_FRAME_LEN; } /* signal that packet should be sent */ if (pcap_sendpacket(pa->adapter, buf, tot_len) < 0) { LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); MIB2_STATS_NETIF_INC(netif, ifoutdiscards); return ERR_BUF; } LINK_STATS_INC(link.xmit); MIB2_STATS_NETIF_ADD(netif, ifoutoctets, tot_len); ethhdr = (struct eth_hdr *)p->payload; if ((ethhdr->dest.addr[0] & 1) != 0) { /* broadcast or multicast packet*/ MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts); } else { /* unicast packet */ MIB2_STATS_NETIF_INC(netif, ifoutucastpkts); } return ERR_OK; } /** low_level_input(): Allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. */ static struct pbuf * pcapif_low_level_input(struct netif *netif, const void *packet, int packet_len) { struct pbuf *p, *q; int start; int length = packet_len; const struct eth_addr *dest = (const struct eth_addr*)packet; const struct eth_addr *src = dest + 1; int unicast; #if PCAPIF_FILTER_GROUP_ADDRESSES && !PCAPIF_RECEIVE_PROMISCUOUS const u8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; const u8_t ipv4mcast[] = {0x01, 0x00, 0x5e}; const u8_t ipv6mcast[] = {0x33, 0x33}; #endif /* PCAPIF_FILTER_GROUP_ADDRESSES && !PCAPIF_RECEIVE_PROMISCUOUS */ /* Don't let feedback packets through (limitation in winpcap?) */ if(!memcmp(src, netif->hwaddr, ETH_HWADDR_LEN)) { /* don't update counters here! */ return NULL; } unicast = ((dest->addr[0] & 0x01) == 0); #if !PCAPIF_RECEIVE_PROMISCUOUS /* MAC filter: only let my MAC or non-unicast through (pcap receives loopback traffic, too) */ if (memcmp(dest, &netif->hwaddr, ETH_HWADDR_LEN) && #if PCAPIF_FILTER_GROUP_ADDRESSES (memcmp(dest, ipv4mcast, 3) || ((dest->addr[3] & 0x80) != 0)) && memcmp(dest, ipv6mcast, 2) && memcmp(dest, bcast, 6) #else /* PCAPIF_FILTER_GROUP_ADDRESSES */ unicast #endif /* PCAPIF_FILTER_GROUP_ADDRESSES */ ) { /* don't update counters here! */ return NULL; } #endif /* !PCAPIF_RECEIVE_PROMISCUOUS */ /* We allocate a pbuf chain of pbufs from the pool. */ p = pbuf_alloc(PBUF_RAW, (u16_t)length + ETH_PAD_SIZE, PBUF_POOL); LWIP_DEBUGF(NETIF_DEBUG, ("netif: recv length %i p->tot_len %i\n", length, (int)p->tot_len)); if (p != NULL) { /* We iterate over the pbuf chain until we have read the entire packet into the pbuf. */ start = 0; for (q = p; q != NULL; q = q->next) { u16_t copy_len = q->len; /* Read enough bytes to fill this pbuf in the chain. The available data in the pbuf is given by the q->len variable. */ /* read data into(q->payload, q->len); */ LWIP_DEBUGF(NETIF_DEBUG, ("netif: recv start %i length %i q->payload %p q->len %i q->next %p\n", start, length, q->payload, (int)q->len, (void*)q->next)); if (q == p) { #if ETH_PAD_SIZE LWIP_ASSERT("q->len >= ETH_PAD_SIZE", q->len >= ETH_PAD_SIZE); copy_len -= ETH_PAD_SIZE; #endif /* ETH_PAD_SIZE*/ MEMCPY(&((char*)q->payload)[ETH_PAD_SIZE], &((const char*)packet)[start], copy_len); } else { MEMCPY(q->payload, &((const char*)packet)[start], copy_len); } start += copy_len; length -= copy_len; if (length <= 0) { break; } } LINK_STATS_INC(link.recv); MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len - ETH_PAD_SIZE); if (unicast) { MIB2_STATS_NETIF_INC(netif, ifinucastpkts); } else { MIB2_STATS_NETIF_INC(netif, ifinnucastpkts); } } else { /* drop packet */ LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); MIB2_STATS_NETIF_INC(netif, ifindiscards); } return p; } #if PCAPIF_RX_REF static void pcapif_rx_pbuf_free_custom(struct pbuf *p) { struct pcapif_pbuf_custom* ppc; LWIP_ASSERT("NULL pointer", p != NULL); ppc = (struct pcapif_pbuf_custom*)p; LWIP_ASSERT("NULL pointer", ppc->p != NULL); pbuf_free(ppc->p); ppc->p = NULL; mem_free(p); } static struct pbuf* pcapif_rx_ref(struct pbuf* p) { struct pcapif_pbuf_custom* ppc; struct pbuf* q; LWIP_ASSERT("NULL pointer", p != NULL); LWIP_ASSERT("chained pbuf not supported here", p->next == NULL); ppc = (struct pcapif_pbuf_custom*)mem_malloc(sizeof(struct pcapif_pbuf_custom)); LWIP_ASSERT("out of memory for RX", ppc != NULL); ppc->pc.custom_free_function = pcapif_rx_pbuf_free_custom; ppc->p = p; q = pbuf_alloced_custom(PBUF_RAW, p->tot_len, PBUF_REF, &ppc->pc, p->payload, p->tot_len); LWIP_ASSERT("pbuf_alloced_custom returned NULL", q != NULL); return q; } #endif /* PCAPIF_RX_REF */ /** pcapif_input: This function is called when a packet is ready to be read * from the interface. It uses the function low_level_input() that should * handle the actual reception of bytes from the network interface. */ static void pcapif_input(u_char *user, const struct pcap_pkthdr *pkt_header, const u_char *packet) { struct pcapif_private *pa = (struct pcapif_private*)user; int packet_len = pkt_header->caplen; struct netif *netif = (struct netif *)pa->input_fn_arg; struct pbuf *p; PCAPIF_RX_LOCK_LWIP(); /* move received packet into a new pbuf */ p = pcapif_low_level_input(netif, packet, packet_len); /* if no packet could be read, silently ignore this */ if (p != NULL) { #if PCAPIF_RX_REF p = pcapif_rx_ref(p); #endif /* pass all packets to ethernet_input, which decides what packets it supports */ if (netif->input(p, netif) != ERR_OK) { LWIP_DEBUGF(NETIF_DEBUG, ("ethernetif_input: IP input error\n")); pbuf_free(p); } } PCAPIF_RX_UNLOCK_LWIP(); } /** * pcapif_init(): initialization function, pass to netif_add(). */ err_t pcapif_init(struct netif *netif) { static int ethernetif_index; int local_index; SYS_ARCH_DECL_PROTECT(lev); SYS_ARCH_PROTECT(lev); local_index = ethernetif_index++; SYS_ARCH_UNPROTECT(lev); netif->name[0] = IFNAME0; netif->name[1] = (char)(IFNAME1 + local_index); netif->linkoutput = pcapif_low_level_output; #if LWIP_IPV4 #if LWIP_ARP netif->output = etharp_output; #else /* LWIP_ARP */ netif->output = NULL; /* not used for PPPoE */ #endif /* LWIP_ARP */ #endif /* LWIP_IPV4 */ #if LWIP_IPV6 netif->output_ip6 = ethip6_output; #endif /* LWIP_IPV6 */ #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif_set_hostname(netif, "lwip"); #endif /* LWIP_NETIF_HOSTNAME */ netif->mtu = 1500; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP; netif->hwaddr_len = ETH_HWADDR_LEN; NETIF_INIT_SNMP(netif, snmp_ifType_ethernet_csmacd, 100000000); /* sets link up or down based on current status */ pcapif_low_level_init(netif); return ERR_OK; } #if !PCAPIF_RX_USE_THREAD void pcapif_poll(struct netif *netif) { struct pcapif_private *pa = (struct pcapif_private*)PCAPIF_GET_STATE_PTR(netif); int ret; do { if (pa->adapter != NULL) { ret = pcap_dispatch(pa->adapter, -1, pcapif_input, (u_char*)pa); } else { ret = -1; } if (ret < 0) { /* error (e.g. adapter removed or resume from standby), try to reopen the adapter */ pcap_reopen_adapter(pa); } } while (ret > 0); } #endif /* !PCAPIF_RX_USE_THREAD */ #endif /* LWIP_ETHERNET */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/pcapif.c
C
unknown
30,222
#ifndef LWIP_PCAPIF_H #define LWIP_PCAPIF_H #ifdef __cplusplus extern "C" { #endif #include "lwip/err.h" /** Set to 1 to let rx use an own thread (only for NO_SYS==0). * If set to 0, ethernetif_poll is used to poll for packets. */ #ifndef PCAPIF_RX_USE_THREAD #define PCAPIF_RX_USE_THREAD !NO_SYS #endif #if PCAPIF_RX_USE_THREAD && NO_SYS #error "Can't create a dedicated RX thread with NO_SYS==1" #endif struct netif; err_t pcapif_init (struct netif *netif); void pcapif_shutdown(struct netif *netif); #if !PCAPIF_RX_USE_THREAD void pcapif_poll (struct netif *netif); #endif /* !PCAPIF_RX_USE_THREAD */ #ifdef __cplusplus } #endif #endif /* LWIP_PCAPIF_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/pcapif.h
C
unknown
708
/** * pcapif_helper.c - This file is part of lwIP pcapif and provides helper functions * for managing the link state. */ #include "pcapif_helper.h" #include <stdlib.h> #include <stdio.h> #include "lwip/arch.h" #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #ifdef _MSC_VER #pragma warning( push, 3 ) #endif #include <windows.h> #include <packet32.h> #include <ntddndis.h> #ifdef _MSC_VER #pragma warning ( pop ) #endif struct pcapifh_linkstate { LPADAPTER lpAdapter; PPACKET_OID_DATA ppacket_oid_data; }; struct pcapifh_linkstate* pcapifh_linkstate_init(char *adapter_name) { struct pcapifh_linkstate* state = (struct pcapifh_linkstate*)malloc(sizeof(struct pcapifh_linkstate)); if (state != NULL) { memset(state, 0, sizeof(struct pcapifh_linkstate)); state->ppacket_oid_data = (PPACKET_OID_DATA)malloc(sizeof(PACKET_OID_DATA) + sizeof(NDIS_MEDIA_STATE)); if (state->ppacket_oid_data == NULL) { free(state); state = NULL; } else { state->lpAdapter = PacketOpenAdapter((char*)adapter_name); if ((state->lpAdapter == NULL) || (state->lpAdapter->hFile == INVALID_HANDLE_VALUE)) { /* failed to open adapter */ free(state); state = NULL; } } } return state; } enum pcapifh_link_event pcapifh_linkstate_get(struct pcapifh_linkstate* state) { enum pcapifh_link_event ret = PCAPIF_LINKEVENT_UNKNOWN; if (state != NULL) { state->ppacket_oid_data->Oid = OID_GEN_MEDIA_CONNECT_STATUS; state->ppacket_oid_data->Length = sizeof(NDIS_MEDIA_STATE); if (PacketRequest(state->lpAdapter, FALSE, state->ppacket_oid_data)) { NDIS_MEDIA_STATE fNdisMediaState; fNdisMediaState = (*((PNDIS_MEDIA_STATE)(state->ppacket_oid_data->Data))); ret = ((fNdisMediaState == NdisMediaStateConnected) ? PCAPIF_LINKEVENT_UP : PCAPIF_LINKEVENT_DOWN); } } return ret; } void pcapifh_linkstate_close(struct pcapifh_linkstate* state) { if (state != NULL) { if (state->lpAdapter != NULL) { PacketCloseAdapter(state->lpAdapter); } if (state->ppacket_oid_data != NULL) { free(state->ppacket_oid_data); } free(state); } } #else /* WIN32 */ /* @todo: add linux/unix implementation? */ struct pcapifh_linkstate { u8_t empty; }; struct pcapifh_linkstate* pcapifh_linkstate_init(char *adapter_name) { LWIP_UNUSED_ARG(adapter_name); return NULL; } enum pcapifh_link_event pcapifh_linkstate_get(struct pcapifh_linkstate* state) { LWIP_UNUSED_ARG(state); return PCAPIF_LINKEVENT_UP; } void pcapifh_linkstate_close(struct pcapifh_linkstate* state) { LWIP_UNUSED_ARG(state); } #endif /* WIN32 */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/pcapif_helper.c
C
unknown
2,745
#ifndef LWIP_PCAPIF_HELPER_H #define LWIP_PCAPIF_HELPER_H #ifdef __cplusplus extern "C" { #endif struct pcapifh_linkstate; enum pcapifh_link_event { PCAPIF_LINKEVENT_UNKNOWN, PCAPIF_LINKEVENT_UP, PCAPIF_LINKEVENT_DOWN }; struct pcapifh_linkstate* pcapifh_linkstate_init(char *adapter_name); enum pcapifh_link_event pcapifh_linkstate_get(struct pcapifh_linkstate* state); void pcapifh_linkstate_close(struct pcapifh_linkstate* state); #ifdef __cplusplus } #endif #endif /* LWIP_PCAPIF_HELPER_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/pcapif_helper.h
C
unknown
532
/* * Copyright (c) 2001-2003 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. * */ #include <lwip/opt.h> #include <lwip/sys.h> #include <lwip/sio.h> #include <stdio.h> #include <stdarg.h> #ifdef _MSC_VER #pragma warning (push, 3) #endif #include <windows.h> #ifdef _MSC_VER #pragma warning (pop) #endif #include "lwipcfg_msvc.h" /** When 1, use COM ports, when 0, use named pipes (for simulation). */ #ifndef SIO_USE_COMPORT #define SIO_USE_COMPORT 1 #endif /** If SIO_USE_COMPORT==1, use COMx, if 0, use a pipe (default) */ #if SIO_USE_COMPORT #define SIO_DEVICENAME "\\\\.\\COM" #else #define SIO_DEVICENAME "\\\\.\\pipe\\lwip" #endif #if SIO_USE_COMPORT #ifndef SIO_COMPORT_SPEED #define SIO_COMPORT_SPEED 115200 #endif #ifndef SIO_COMPORT_BYTESIZE #define SIO_COMPORT_BYTESIZE 8 #endif #ifndef SIO_COMPORT_STOPBITS #define SIO_COMPORT_STOPBITS 0 /* ONESTOPBIT */ #endif #ifndef SIO_COMPORT_PARITY #define SIO_COMPORT_PARITY 0 /* NOPARITY */ #endif #endif /* SIO_USE_COMPORT */ static int sio_abort = 0; /* \\.\pipe\lwip0 */ /* pppd /dev/ttyS0 logfile mylog debug nocrtscts local noauth noccp ms-dns 212.27.54.252 192.168.0.4:192.168.0.5 */ /** * SIO_DEBUG: Enable debugging for SIO. */ #ifndef SIO_DEBUG #define SIO_DEBUG LWIP_DBG_OFF #endif #if SIO_USE_COMPORT /** When using a real COM port, set up the * serial line settings (baudrate etc.) */ static BOOL sio_setup(HANDLE fd) { COMMTIMEOUTS cto; DCB dcb; /* set up baudrate and other communication settings */ memset(&dcb, 0, sizeof(dcb)); /* Obtain the DCB structure for the device */ if (!GetCommState(fd, &dcb)) { return FALSE; } /* Set the new data */ dcb.BaudRate = SIO_COMPORT_SPEED; dcb.ByteSize = SIO_COMPORT_BYTESIZE; dcb.StopBits = 0; /* ONESTOPBIT */ dcb.Parity = 0; /* NOPARITY */ dcb.fParity = 0; /* parity is not used */ /* do not use flow control */ /*dcb.fOutxDsrFlow = dcb.fDtrControl = 0; dcb.fOutxCtsFlow = dcb.fRtsControl = 0; dcb.fErrorChar = dcb.fNull = 0; dcb.fInX = dcb.fOutX = 0; dcb.XonChar = dcb.XoffChar = 0; dcb.XonLim = dcb.XoffLim = 100;*/ /* Set the new DCB structure */ if (!SetCommState(fd, &dcb)) { return FALSE; } memset(&cto, 0, sizeof(cto)); if(!GetCommTimeouts(fd, &cto)) { return FALSE; } /* change read timeout, leave write timeout as it is */ cto.ReadIntervalTimeout = 1; cto.ReadTotalTimeoutMultiplier = 0; cto.ReadTotalTimeoutConstant = 1; /* 1 ms */ if(!SetCommTimeouts(fd, &cto)) { return FALSE; } return TRUE; } #endif /* SIO_USE_COMPORT */ /** * Opens a serial device for communication. * * @param devnum device number * @return handle to serial device if successful, NULL otherwise */ sio_fd_t sio_open(u8_t devnum) { HANDLE fileHandle = INVALID_HANDLE_VALUE; CHAR fileName[256]; LWIP_DEBUGF(SIO_DEBUG, ("sio_open(%lu)\n", (DWORD)devnum)); #if SIO_USE_COMPORT _snprintf(fileName, 255, SIO_DEVICENAME"%lu", (DWORD)(devnum)); #else /* SIO_USE_COMPORT */ _snprintf(fileName, 255, SIO_DEVICENAME"%lu", (DWORD)(devnum & ~1)); if ((devnum & 1) == 0) { fileHandle = CreateNamedPipe(fileName, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_NOWAIT, PIPE_UNLIMITED_INSTANCES, 102400, 102400, 100, NULL); } else #endif /* SIO_USE_COMPORT */ { fileHandle = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } if (fileHandle != INVALID_HANDLE_VALUE) { sio_abort = 0; #if !SIO_USE_COMPORT if (devnum & 1) { DWORD mode = PIPE_NOWAIT; if (!SetNamedPipeHandleState(fileHandle, &mode, NULL, NULL)) { LWIP_DEBUGF(SIO_DEBUG, ("sio_open(%lu): SetNamedPipeHandleState failed. GetLastError() returns %d\n", (DWORD)devnum, GetLastError())); } } else #endif /* !SIO_USE_COMPORT */ { FlushFileBuffers(fileHandle); } #if SIO_USE_COMPORT if(!sio_setup(fileHandle)) { CloseHandle(fileHandle); LWIP_DEBUGF(SIO_DEBUG, ("sio_open(%lu): sio_setup failed. GetLastError() returns %lu\n", (DWORD)devnum, GetLastError())); return NULL; } #endif /* SIO_USE_COMPORT */ LWIP_DEBUGF(SIO_DEBUG, ("sio_open: file \"%s\" successfully opened.\n", fileName)); printf("sio_open: file \"%s\" (%d) successfully opened: 0x%08x\n", fileName, devnum, (unsigned int)(size_t)fileHandle); return (sio_fd_t)(fileHandle); } LWIP_DEBUGF(SIO_DEBUG, ("sio_open(%lu) failed. GetLastError() returns %lu\n", (DWORD)devnum, GetLastError())); printf("sio_open(%lu) failed. GetLastError() returns %lu\n", (DWORD)devnum, GetLastError()); return NULL; } /** * Sends a single character to the serial device. * * @param c character to send * @param fd serial device handle * * @note This function will block until the character can be sent. */ void sio_send(u8_t c, sio_fd_t fd) { DWORD dwNbBytesWritten = 0; LWIP_DEBUGF(SIO_DEBUG, ("sio_send(%lu)\n", (DWORD)c)); while ((!WriteFile((HANDLE)(fd), &c, 1, &dwNbBytesWritten, NULL)) || (dwNbBytesWritten < 1)) { } } /** * Receives a single character from the serial device. * * @param fd serial device handle * * @note This function will block until a character is received. */ u8_t sio_recv(sio_fd_t fd) { DWORD dwNbBytesReadden = 0; u8_t byte = 0; LWIP_DEBUGF(SIO_DEBUG, ("sio_recv()\n")); while ((sio_abort == 0) && ((!ReadFile((HANDLE)(fd), &byte, 1, &dwNbBytesReadden, NULL)) || (dwNbBytesReadden < 1))); LWIP_DEBUGF(SIO_DEBUG, ("sio_recv()=%lu\n", (DWORD)byte)); return byte; } /** * Reads from the serial device. * * @param fd serial device handle * @param data pointer to data buffer for receiving * @param len maximum length (in bytes) of data to receive * @return number of bytes actually received - may be 0 if aborted by sio_read_abort * * @note This function will block until data can be received. The blocking * can be cancelled by calling sio_read_abort(). */ u32_t sio_read(sio_fd_t fd, u8_t* data, u32_t len) { BOOL ret; DWORD dwNbBytesReadden = 0; LWIP_DEBUGF(SIO_DEBUG, ("sio_read()...\n")); ret = ReadFile((HANDLE)(fd), data, len, &dwNbBytesReadden, NULL); LWIP_DEBUGF(SIO_DEBUG, ("sio_read()=%lu bytes -> %d\n", dwNbBytesReadden, ret)); return dwNbBytesReadden; } /** * Tries to read from the serial device. Same as sio_read but returns * immediately if no data is available and never blocks. * * @param fd serial device handle * @param data pointer to data buffer for receiving * @param len maximum length (in bytes) of data to receive * @return number of bytes actually received */ u32_t sio_tryread(sio_fd_t fd, u8_t* data, u32_t len) { /* @todo: implement non-blocking read */ BOOL ret; DWORD dwNbBytesReadden = 0; LWIP_DEBUGF(SIO_DEBUG, ("sio_read()...\n")); ret = ReadFile((HANDLE)(fd), data, len, &dwNbBytesReadden, NULL); LWIP_DEBUGF(SIO_DEBUG, ("sio_read()=%lu bytes -> %d\n", dwNbBytesReadden, ret)); return dwNbBytesReadden; } /** * Writes to the serial device. * * @param fd serial device handle * @param data pointer to data to send * @param len length (in bytes) of data to send * @return number of bytes actually sent * * @note This function will block until all data can be sent. */ u32_t sio_write(sio_fd_t fd, u8_t* data, u32_t len) { BOOL ret; DWORD dwNbBytesWritten = 0; LWIP_DEBUGF(SIO_DEBUG, ("sio_write()...\n")); ret = WriteFile((HANDLE)(fd), data, len, &dwNbBytesWritten, NULL); LWIP_DEBUGF(SIO_DEBUG, ("sio_write()=%lu bytes -> %d\n", dwNbBytesWritten, ret)); return dwNbBytesWritten; } /** * Aborts a blocking sio_read() call. * @todo: This currently ignores fd and aborts all reads * * @param fd serial device handle */ void sio_read_abort(sio_fd_t fd) { LWIP_UNUSED_ARG(fd); LWIP_DEBUGF(SIO_DEBUG, ("sio_read_abort() !!!!!...\n")); sio_abort = 1; return; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/sio.c
C
unknown
9,646
/* * Copyright (c) 2001-2003 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> * Simon Goldschmidt * */ #include <stdlib.h> #include <stdio.h> /* sprintf() for task names */ #ifdef _MSC_VER #pragma warning (push, 3) #endif #include <windows.h> #ifdef _MSC_VER #pragma warning (pop) #endif #include <time.h> #include <lwip/opt.h> #include <lwip/arch.h> #include <lwip/stats.h> #include <lwip/debug.h> #include <lwip/sys.h> /* These functions are used from NO_SYS also, for precise timer triggering */ LARGE_INTEGER freq, sys_start_time; #define SYS_INITIALIZED() (freq.QuadPart != 0) DWORD netconn_sem_tls_index; static void sys_init_timing(void) { QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&sys_start_time); } static LONGLONG sys_get_ms_longlong(void) { LONGLONG ret; LARGE_INTEGER now; #if NO_SYS if (!SYS_INITIALIZED()) { sys_init(); LWIP_ASSERT("initialization failed", SYS_INITIALIZED()); } #endif /* NO_SYS */ QueryPerformanceCounter(&now); ret = now.QuadPart-sys_start_time.QuadPart; return (u32_t)(((ret)*1000)/freq.QuadPart); } u32_t sys_jiffies(void) { return (u32_t)sys_get_ms_longlong(); } u32_t sys_now(void) { return (u32_t)sys_get_ms_longlong(); } CRITICAL_SECTION critSec; static void InitSysArchProtect(void) { InitializeCriticalSection(&critSec); } sys_prot_t sys_arch_protect(void) { #if NO_SYS if (!SYS_INITIALIZED()) { sys_init(); LWIP_ASSERT("initialization failed", SYS_INITIALIZED()); } #endif EnterCriticalSection(&critSec); return 0; } void sys_arch_unprotect(sys_prot_t pval) { LWIP_UNUSED_ARG(pval); LeaveCriticalSection(&critSec); } static void msvc_sys_init(void) { srand((unsigned int)time(0)); sys_init_timing(); InitSysArchProtect(); netconn_sem_tls_index = TlsAlloc(); LWIP_ASSERT("TlsAlloc failed", netconn_sem_tls_index != TLS_OUT_OF_INDEXES); } void sys_init(void) { msvc_sys_init(); } #if !NO_SYS struct threadlist { lwip_thread_fn function; void *arg; DWORD id; struct threadlist *next; }; struct threadlist *lwip_win32_threads = NULL; err_t sys_sem_new(sys_sem_t *sem, u8_t count) { HANDLE new_sem = NULL; LWIP_ASSERT("sem != NULL", sem != NULL); new_sem = CreateSemaphore(0, count, 100000, 0); LWIP_ASSERT("Error creating semaphore", new_sem != NULL); if(new_sem != NULL) { SYS_STATS_INC_USED(sem); #if LWIP_STATS && SYS_STATS LWIP_ASSERT("sys_sem_new() counter overflow", lwip_stats.sys.sem.used != 0 ); #endif /* LWIP_STATS && SYS_STATS*/ sem->sem = new_sem; return ERR_OK; } /* failed to allocate memory... */ SYS_STATS_INC(sem.err); sem->sem = NULL; return ERR_MEM; } void sys_sem_free(sys_sem_t *sem) { /* parameter check */ LWIP_ASSERT("sem != NULL", sem != NULL); LWIP_ASSERT("sem->sem != NULL", sem->sem != NULL); LWIP_ASSERT("sem->sem != INVALID_HANDLE_VALUE", sem->sem != INVALID_HANDLE_VALUE); CloseHandle(sem->sem); SYS_STATS_DEC(sem.used); #if LWIP_STATS && SYS_STATS LWIP_ASSERT("sys_sem_free() closed more than created", lwip_stats.sys.sem.used != (u16_t)-1); #endif /* LWIP_STATS && SYS_STATS */ sem->sem = NULL; } u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { DWORD ret; LONGLONG starttime, endtime; LWIP_ASSERT("sem != NULL", sem != NULL); LWIP_ASSERT("sem->sem != NULL", sem->sem != NULL); LWIP_ASSERT("sem->sem != INVALID_HANDLE_VALUE", sem->sem != INVALID_HANDLE_VALUE); if(!timeout) { /* wait infinite */ starttime = sys_get_ms_longlong(); ret = WaitForSingleObject(sem->sem, INFINITE); LWIP_ASSERT("Error waiting for semaphore", ret == WAIT_OBJECT_0); endtime = sys_get_ms_longlong(); /* return the time we waited for the sem */ return (u32_t)(endtime - starttime); } else { starttime = sys_get_ms_longlong(); ret = WaitForSingleObject(sem->sem, timeout); LWIP_ASSERT("Error waiting for semaphore", (ret == WAIT_OBJECT_0) || (ret == WAIT_TIMEOUT)); if(ret == WAIT_OBJECT_0) { endtime = sys_get_ms_longlong(); /* return the time we waited for the sem */ return (u32_t)(endtime - starttime); } else { /* timeout */ return SYS_ARCH_TIMEOUT; } } } void sys_sem_signal(sys_sem_t *sem) { DWORD ret; LWIP_ASSERT("sem != NULL", sem != NULL); LWIP_ASSERT("sem->sem != NULL", sem->sem != NULL); LWIP_ASSERT("sem->sem != INVALID_HANDLE_VALUE", sem->sem != INVALID_HANDLE_VALUE); ret = ReleaseSemaphore(sem->sem, 1, NULL); LWIP_ASSERT("Error releasing semaphore", ret != 0); } err_t sys_mutex_new(sys_mutex_t *mutex) { HANDLE new_mut = NULL; LWIP_ASSERT("mutex != NULL", mutex != NULL); new_mut = CreateMutex(NULL, FALSE, NULL); LWIP_ASSERT("Error creating mutex", new_mut != NULL); if(new_mut != NULL) { SYS_STATS_INC_USED(mutex); #if LWIP_STATS && SYS_STATS LWIP_ASSERT("sys_mutex_new() counter overflow", lwip_stats.sys.mutex.used != 0 ); #endif /* LWIP_STATS && SYS_STATS*/ mutex->mut = new_mut; return ERR_OK; } /* failed to allocate memory... */ SYS_STATS_INC(mutex.err); mutex->mut = NULL; return ERR_MEM; } void sys_mutex_free(sys_mutex_t *mutex) { /* parameter check */ LWIP_ASSERT("mutex != NULL", mutex != NULL); LWIP_ASSERT("mutex->mut != NULL", mutex->mut != NULL); LWIP_ASSERT("mutex->mut != INVALID_HANDLE_VALUE", mutex->mut != INVALID_HANDLE_VALUE); CloseHandle(mutex->mut); SYS_STATS_DEC(mutex.used); #if LWIP_STATS && SYS_STATS LWIP_ASSERT("sys_mutex_free() closed more than created", lwip_stats.sys.mutex.used != (u16_t)-1); #endif /* LWIP_STATS && SYS_STATS */ mutex->mut = NULL; } void sys_mutex_lock(sys_mutex_t *mutex) { DWORD ret; LWIP_ASSERT("mutex != NULL", mutex != NULL); LWIP_ASSERT("mutex->mut != NULL", mutex->mut != NULL); LWIP_ASSERT("mutex->mut != INVALID_HANDLE_VALUE", mutex->mut != INVALID_HANDLE_VALUE); /* wait infinite */ ret = WaitForSingleObject(mutex->mut, INFINITE); LWIP_ASSERT("Error waiting for mutex", ret == WAIT_OBJECT_0); } void sys_mutex_unlock(sys_mutex_t *mutex) { LWIP_ASSERT("mutex != NULL", mutex != NULL); LWIP_ASSERT("mutex->mut != NULL", mutex->mut != NULL); LWIP_ASSERT("mutex->mut != INVALID_HANDLE_VALUE", mutex->mut != INVALID_HANDLE_VALUE); /* wait infinite */ if(!ReleaseMutex(mutex->mut)) { LWIP_ASSERT("Error releasing mutex", 0); } } #ifdef _MSC_VER const DWORD MS_VC_EXCEPTION=0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; /* Must be 0x1000. */ LPCSTR szName; /* Pointer to name (in user addr space). */ DWORD dwThreadID; /* Thread ID (-1=caller thread). */ DWORD dwFlags; /* Reserved for future use, must be zero. */ } THREADNAME_INFO; #pragma pack(pop) static void SetThreadName(DWORD dwThreadID, const char* threadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } } #else /* _MSC_VER */ static void SetThreadName(DWORD dwThreadID, const char* threadName) { LWIP_UNUSED_ARG(dwThreadID); LWIP_UNUSED_ARG(threadName); } #endif /* _MSC_VER */ static void sys_thread_function(void* arg) { struct threadlist* t = (struct threadlist*)arg; #if LWIP_NETCONN_SEM_PER_THREAD sys_arch_netconn_sem_alloc(); #endif t->function(t->arg); #if LWIP_NETCONN_SEM_PER_THREAD sys_arch_netconn_sem_free(); #endif } sys_thread_t sys_thread_new(const char *name, lwip_thread_fn function, void *arg, int stacksize, int prio) { struct threadlist *new_thread; HANDLE h; SYS_ARCH_DECL_PROTECT(lev); LWIP_UNUSED_ARG(name); LWIP_UNUSED_ARG(stacksize); LWIP_UNUSED_ARG(prio); new_thread = (struct threadlist*)malloc(sizeof(struct threadlist)); LWIP_ASSERT("new_thread != NULL", new_thread != NULL); if(new_thread != NULL) { new_thread->function = function; new_thread->arg = arg; SYS_ARCH_PROTECT(lev); new_thread->next = lwip_win32_threads; lwip_win32_threads = new_thread; h = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)sys_thread_function, new_thread, 0, &(new_thread->id)); LWIP_ASSERT("h != 0", h != 0); LWIP_ASSERT("h != -1", h != INVALID_HANDLE_VALUE); SetThreadName(new_thread->id, name); SYS_ARCH_UNPROTECT(lev); return new_thread->id; } return 0; } err_t sys_mbox_new(sys_mbox_t *mbox, int size) { LWIP_ASSERT("mbox != NULL", mbox != NULL); LWIP_UNUSED_ARG(size); mbox->sem = CreateSemaphore(0, 0, MAX_QUEUE_ENTRIES, 0); LWIP_ASSERT("Error creating semaphore", mbox->sem != NULL); if(mbox->sem == NULL) { SYS_STATS_INC(mbox.err); return ERR_MEM; } memset(&mbox->q_mem, 0, sizeof(u32_t)*MAX_QUEUE_ENTRIES); mbox->head = 0; mbox->tail = 0; SYS_STATS_INC_USED(mbox); #if LWIP_STATS && SYS_STATS LWIP_ASSERT("sys_mbox_new() counter overflow", lwip_stats.sys.mbox.used != 0 ); #endif /* LWIP_STATS && SYS_STATS */ return ERR_OK; } void sys_mbox_free(sys_mbox_t *mbox) { /* parameter check */ LWIP_ASSERT("mbox != NULL", mbox != NULL); LWIP_ASSERT("mbox->sem != NULL", mbox->sem != NULL); LWIP_ASSERT("mbox->sem != INVALID_HANDLE_VALUE", mbox->sem != INVALID_HANDLE_VALUE); CloseHandle(mbox->sem); SYS_STATS_DEC(mbox.used); #if LWIP_STATS && SYS_STATS LWIP_ASSERT( "sys_mbox_free() ", lwip_stats.sys.mbox.used!= (u16_t)-1 ); #endif /* LWIP_STATS && SYS_STATS */ mbox->sem = NULL; } void sys_mbox_post(sys_mbox_t *q, void *msg) { DWORD ret; SYS_ARCH_DECL_PROTECT(lev); /* parameter check */ LWIP_ASSERT("q != SYS_MBOX_NULL", q != SYS_MBOX_NULL); LWIP_ASSERT("q->sem != NULL", q->sem != NULL); LWIP_ASSERT("q->sem != INVALID_HANDLE_VALUE", q->sem != INVALID_HANDLE_VALUE); SYS_ARCH_PROTECT(lev); q->q_mem[q->head] = msg; (q->head)++; if (q->head >= MAX_QUEUE_ENTRIES) { q->head = 0; } LWIP_ASSERT("mbox is full!", q->head != q->tail); ret = ReleaseSemaphore(q->sem, 1, 0); LWIP_ASSERT("Error releasing sem", ret != 0); SYS_ARCH_UNPROTECT(lev); } err_t sys_mbox_trypost(sys_mbox_t *q, void *msg) { u32_t new_head; DWORD ret; SYS_ARCH_DECL_PROTECT(lev); /* parameter check */ LWIP_ASSERT("q != SYS_MBOX_NULL", q != SYS_MBOX_NULL); LWIP_ASSERT("q->sem != NULL", q->sem != NULL); LWIP_ASSERT("q->sem != INVALID_HANDLE_VALUE", q->sem != INVALID_HANDLE_VALUE); SYS_ARCH_PROTECT(lev); new_head = q->head + 1; if (new_head >= MAX_QUEUE_ENTRIES) { new_head = 0; } if (new_head == q->tail) { SYS_ARCH_UNPROTECT(lev); return ERR_MEM; } q->q_mem[q->head] = msg; q->head = new_head; LWIP_ASSERT("mbox is full!", q->head != q->tail); ret = ReleaseSemaphore(q->sem, 1, 0); LWIP_ASSERT("Error releasing sem", ret != 0); SYS_ARCH_UNPROTECT(lev); return ERR_OK; } u32_t sys_arch_mbox_fetch(sys_mbox_t *q, void **msg, u32_t timeout) { DWORD ret; LONGLONG starttime, endtime; SYS_ARCH_DECL_PROTECT(lev); /* parameter check */ LWIP_ASSERT("q != SYS_MBOX_NULL", q != SYS_MBOX_NULL); LWIP_ASSERT("q->sem != NULL", q->sem != NULL); LWIP_ASSERT("q->sem != INVALID_HANDLE_VALUE", q->sem != INVALID_HANDLE_VALUE); if (timeout == 0) { timeout = INFINITE; } starttime = sys_get_ms_longlong(); if ((ret = WaitForSingleObject(q->sem, timeout)) == WAIT_OBJECT_0) { SYS_ARCH_PROTECT(lev); if(msg != NULL) { *msg = q->q_mem[q->tail]; } (q->tail)++; if (q->tail >= MAX_QUEUE_ENTRIES) { q->tail = 0; } SYS_ARCH_UNPROTECT(lev); endtime = sys_get_ms_longlong(); return (u32_t)(endtime - starttime); } else { LWIP_ASSERT("Error waiting for sem", ret == WAIT_TIMEOUT); if(msg != NULL) { *msg = NULL; } return SYS_ARCH_TIMEOUT; } } u32_t sys_arch_mbox_tryfetch(sys_mbox_t *q, void **msg) { DWORD ret; SYS_ARCH_DECL_PROTECT(lev); /* parameter check */ LWIP_ASSERT("q != SYS_MBOX_NULL", q != SYS_MBOX_NULL); LWIP_ASSERT("q->sem != NULL", q->sem != NULL); LWIP_ASSERT("q->sem != INVALID_HANDLE_VALUE", q->sem != INVALID_HANDLE_VALUE); if ((ret = WaitForSingleObject(q->sem, 0)) == WAIT_OBJECT_0) { SYS_ARCH_PROTECT(lev); if(msg != NULL) { *msg = q->q_mem[q->tail]; } (q->tail)++; if (q->tail >= MAX_QUEUE_ENTRIES) { q->tail = 0; } SYS_ARCH_UNPROTECT(lev); return 0; } else { LWIP_ASSERT("Error waiting for sem", ret == WAIT_TIMEOUT); if(msg != NULL) { *msg = NULL; } return SYS_ARCH_TIMEOUT; } } #if LWIP_NETCONN_SEM_PER_THREAD sys_sem_t* sys_arch_netconn_sem_get(void) { LPVOID tls_data = TlsGetValue(netconn_sem_tls_index); return (sys_sem_t*)tls_data; } void sys_arch_netconn_sem_alloc(void) { sys_sem_t *sem; err_t err; BOOL done; sem = (sys_sem_t*)malloc(sizeof(sys_sem_t)); LWIP_ASSERT("failed to allocate memory for TLS semaphore", sem != NULL); err = sys_sem_new(sem, 0); LWIP_ASSERT("failed to initialise TLS semaphore", err == ERR_OK); done = TlsSetValue(netconn_sem_tls_index, sem); LWIP_UNUSED_ARG(done); LWIP_ASSERT("failed to initialise TLS semaphore storage", done == TRUE); } void sys_arch_netconn_sem_free(void) { LPVOID tls_data = TlsGetValue(netconn_sem_tls_index); if (tls_data != NULL) { BOOL done; free(tls_data); done = TlsSetValue(netconn_sem_tls_index, NULL); LWIP_UNUSED_ARG(done); LWIP_ASSERT("failed to de-init TLS semaphore storage", done == TRUE); } } #endif /* LWIP_NETCONN_SEM_PER_THREAD */ #endif /* !NO_SYS */
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/sys_arch.c
C
unknown
15,676
/* * Copyright (c) 2001,2002 Florian Schulze. * 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. Neither the name of the authors nor the names of the contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``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 AUTHORS OR CONTRIBUTORS 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. * * test.c - This file is part of lwIP test * */ /* C runtime includes */ #include <stdio.h> #include <stdarg.h> #include <time.h> #include <string.h> #include <conio.h> /* lwIP core includes */ #include "lwip/opt.h" #include "lwip/sys.h" #include "lwip/timeouts.h" #include "lwip/debug.h" #include "lwip/stats.h" #include "lwip/init.h" #include "lwip/tcpip.h" #include "lwip/netif.h" #include "lwip/api.h" #include "lwip/tcp.h" #include "lwip/udp.h" #include "lwip/dns.h" #include "lwip/dhcp.h" #include "lwip/autoip.h" /* lwIP netif includes */ #include "lwip/etharp.h" #include "netif/ethernet.h" /* applications includes */ #include "lwip/apps/lwiperf.h" #include "lwip/apps/netbiosns.h" #include "lwip/apps/sntp.h" #include "lwip/apps/httpd.h" #include "lwip/apps/mdns.h" #include "apps/httpserver/httpserver-netconn.h" #include "apps/netio/netio.h" #include "apps/ping/ping.h" #include "apps/rtp/rtp.h" #include "apps/chargen/chargen.h" #include "apps/shell/shell.h" #include "apps/tcpecho/tcpecho.h" #include "apps/udpecho/udpecho.h" #include "apps/tcpecho_raw/tcpecho_raw.h" #include "apps/socket_examples/socket_examples.h" #if NO_SYS /* ... then we need information about the timer intervals: */ #include "lwip/ip4_frag.h" #include "lwip/igmp.h" #endif /* NO_SYS */ #include "netif/ppp/ppp_opts.h" #if PPP_SUPPORT /* PPP includes */ #include "lwip/sio.h" #include "netif/ppp/pppapi.h" #include "netif/ppp/pppos.h" #include "netif/ppp/pppoe.h" #if !NO_SYS && !LWIP_PPP_API #error With NO_SYS==0, LWIP_PPP_API==1 is required. #endif #endif /* PPP_SUPPORT */ /* include the port-dependent configuration */ #include "lwipcfg_msvc.h" /** Define this to 1 to enable a PCAP interface as default interface. */ #ifndef USE_PCAPIF #define USE_PCAPIF 1 #endif /** Define this to 1 or 2 to support 1 or 2 SLIP interfaces. */ #ifndef USE_SLIPIF #define USE_SLIPIF 0 #endif /** Use an ethernet adapter? Default to enabled if PCAPIF or PPPoE are used. */ #ifndef USE_ETHERNET #define USE_ETHERNET (USE_PCAPIF || PPPOE_SUPPORT) #endif /** Use an ethernet adapter for TCP/IP? By default only if PCAPIF is used. */ #ifndef USE_ETHERNET_TCPIP #define USE_ETHERNET_TCPIP (USE_PCAPIF) #endif #if USE_ETHERNET #include "pcapif.h" #endif /* USE_ETHERNET */ #if USE_SLIPIF #include <netif/slipif.h> #endif /* USE_SLIPIF */ #ifndef USE_DHCP #define USE_DHCP LWIP_DHCP #endif #ifndef USE_AUTOIP #define USE_AUTOIP LWIP_AUTOIP #endif /* globales variables for netifs */ #if USE_ETHERNET /* THE ethernet interface */ struct netif netif; #if LWIP_DHCP /* dhcp struct for the ethernet netif */ struct dhcp netif_dhcp; #endif /* LWIP_DHCP */ #if LWIP_AUTOIP /* autoip struct for the ethernet netif */ struct autoip netif_autoip; #endif /* LWIP_AUTOIP */ #endif /* USE_ETHERNET */ #if PPP_SUPPORT /* THE PPP PCB */ ppp_pcb *ppp; /* THE PPP interface */ struct netif ppp_netif; /* THE PPP descriptor */ u8_t sio_idx = 0; sio_fd_t ppp_sio; #endif /* PPP_SUPPORT */ #if USE_SLIPIF struct netif slipif1; #if USE_SLIPIF > 1 struct netif slipif2; #endif /* USE_SLIPIF > 1 */ #endif /* USE_SLIPIF */ #if PPP_SUPPORT static void pppLinkStatusCallback(ppp_pcb *pcb, int errCode, void *ctx) { struct netif *pppif = ppp_netif(pcb); LWIP_UNUSED_ARG(ctx); switch(errCode) { case PPPERR_NONE: { /* No error. */ printf("pppLinkStatusCallback: PPPERR_NONE\n"); #if LWIP_IPV4 printf(" our_ipaddr = %s\n", ip4addr_ntoa(netif_ip4_addr(pppif))); printf(" his_ipaddr = %s\n", ip4addr_ntoa(netif_ip4_gw(pppif))); printf(" netmask = %s\n", ip4addr_ntoa(netif_ip4_netmask(pppif))); #endif /* LWIP_IPV4 */ #if LWIP_DNS printf(" dns1 = %s\n", ipaddr_ntoa(dns_getserver(0))); printf(" dns2 = %s\n", ipaddr_ntoa(dns_getserver(1))); #endif /* LWIP_DNS */ #if PPP_IPV6_SUPPORT printf(" our6_ipaddr = %s\n", ip6addr_ntoa(netif_ip6_addr(pppif, 0))); #endif /* PPP_IPV6_SUPPORT */ break; } case PPPERR_PARAM: { /* Invalid parameter. */ printf("pppLinkStatusCallback: PPPERR_PARAM\n"); break; } case PPPERR_OPEN: { /* Unable to open PPP session. */ printf("pppLinkStatusCallback: PPPERR_OPEN\n"); break; } case PPPERR_DEVICE: { /* Invalid I/O device for PPP. */ printf("pppLinkStatusCallback: PPPERR_DEVICE\n"); break; } case PPPERR_ALLOC: { /* Unable to allocate resources. */ printf("pppLinkStatusCallback: PPPERR_ALLOC\n"); break; } case PPPERR_USER: { /* User interrupt. */ printf("pppLinkStatusCallback: PPPERR_USER\n"); break; } case PPPERR_CONNECT: { /* Connection lost. */ printf("pppLinkStatusCallback: PPPERR_CONNECT\n"); break; } case PPPERR_AUTHFAIL: { /* Failed authentication challenge. */ printf("pppLinkStatusCallback: PPPERR_AUTHFAIL\n"); break; } case PPPERR_PROTOCOL: { /* Failed to meet protocol. */ printf("pppLinkStatusCallback: PPPERR_PROTOCOL\n"); break; } case PPPERR_PEERDEAD: { /* Connection timeout */ printf("pppLinkStatusCallback: PPPERR_PEERDEAD\n"); break; } case PPPERR_IDLETIMEOUT: { /* Idle Timeout */ printf("pppLinkStatusCallback: PPPERR_IDLETIMEOUT\n"); break; } case PPPERR_CONNECTTIME: { /* Max connect time reached */ printf("pppLinkStatusCallback: PPPERR_CONNECTTIME\n"); break; } case PPPERR_LOOPBACK: { /* Loopback detected */ printf("pppLinkStatusCallback: PPPERR_LOOPBACK\n"); break; } default: { printf("pppLinkStatusCallback: unknown errCode %d\n", errCode); break; } } } #if PPPOS_SUPPORT static u32_t ppp_output_cb(ppp_pcb *pcb, u8_t *data, u32_t len, void *ctx) { LWIP_UNUSED_ARG(pcb); LWIP_UNUSED_ARG(ctx); return sio_write(ppp_sio, data, len); } #endif /* PPPOS_SUPPORT */ #endif /* PPP_SUPPORT */ #if LWIP_NETIF_STATUS_CALLBACK static void status_callback(struct netif *state_netif) { if (netif_is_up(state_netif)) { #if LWIP_IPV4 printf("status_callback==UP, local interface IP is %s\n", ip4addr_ntoa(netif_ip4_addr(state_netif))); #else printf("status_callback==UP\n"); #endif #if LWIP_MDNS_RESPONDER mdns_resp_netif_settings_changed(state_netif); #endif } else { printf("status_callback==DOWN\n"); } } #endif /* LWIP_NETIF_STATUS_CALLBACK */ #if LWIP_NETIF_LINK_CALLBACK static void link_callback(struct netif *state_netif) { if (netif_is_link_up(state_netif)) { printf("link_callback==UP\n"); } else { printf("link_callback==DOWN\n"); } } #endif /* LWIP_NETIF_LINK_CALLBACK */ /* This function initializes all network interfaces */ static void msvc_netif_init(void) { #if LWIP_IPV4 && USE_ETHERNET ip4_addr_t ipaddr, netmask, gw; #endif /* LWIP_IPV4 && USE_ETHERNET */ #if USE_SLIPIF u8_t num_slip1 = 0; #if LWIP_IPV4 ip4_addr_t ipaddr_slip1, netmask_slip1, gw_slip1; #endif #if USE_SLIPIF > 1 u8_t num_slip2 = 1; #if LWIP_IPV4 ip4_addr_t ipaddr_slip2, netmask_slip2, gw_slip2; #endif #endif /* USE_SLIPIF > 1 */ #endif /* USE_SLIPIF */ #if USE_DHCP || USE_AUTOIP err_t err; #endif #if PPP_SUPPORT const char *username = NULL, *password = NULL; #ifdef PPP_USERNAME username = PPP_USERNAME; #endif #ifdef PPP_PASSWORD password = PPP_PASSWORD; #endif printf("ppp_connect: COM%d\n", (int)sio_idx); #if PPPOS_SUPPORT ppp_sio = sio_open(sio_idx); if (ppp_sio == NULL) { printf("sio_open error\n"); } else { ppp = pppos_create(&ppp_netif, ppp_output_cb, pppLinkStatusCallback, NULL); if (ppp == NULL) { printf("pppos_create error\n"); } else { ppp_set_auth(ppp, PPPAUTHTYPE_ANY, username, password); ppp_connect(ppp, 0); } } #endif /* PPPOS_SUPPORT */ #endif /* PPP_SUPPORT */ #if USE_ETHERNET #if LWIP_IPV4 #define NETIF_ADDRS &ipaddr, &netmask, &gw, ip4_addr_set_zero(&gw); ip4_addr_set_zero(&ipaddr); ip4_addr_set_zero(&netmask); #if USE_ETHERNET_TCPIP #if USE_DHCP printf("Starting lwIP, local interface IP is dhcp-enabled\n"); #elif USE_AUTOIP printf("Starting lwIP, local interface IP is autoip-enabled\n"); #else /* USE_DHCP */ LWIP_PORT_INIT_GW(&gw); LWIP_PORT_INIT_IPADDR(&ipaddr); LWIP_PORT_INIT_NETMASK(&netmask); printf("Starting lwIP, local interface IP is %s\n", ip4addr_ntoa(&ipaddr)); #endif /* USE_DHCP */ #endif /* USE_ETHERNET_TCPIP */ #else /* LWIP_IPV4 */ #define NETIF_ADDRS printf("Starting lwIP, IPv4 disable\n"); #endif /* LWIP_IPV4 */ #if NO_SYS netif_set_default(netif_add(&netif, NETIF_ADDRS NULL, pcapif_init, netif_input)); #else /* NO_SYS */ netif_set_default(netif_add(&netif, NETIF_ADDRS NULL, pcapif_init, tcpip_input)); #endif /* NO_SYS */ #if LWIP_IPV6 netif_create_ip6_linklocal_address(&netif, 1); printf("ip6 linklocal address: "); ip6_addr_debug_print(0xFFFFFFFF & ~LWIP_DBG_HALT, netif_ip6_addr(&netif, 0)); printf("\n"); #endif /* LWIP_IPV6 */ #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&netif, status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ #if LWIP_NETIF_LINK_CALLBACK netif_set_link_callback(&netif, link_callback); #endif /* LWIP_NETIF_LINK_CALLBACK */ #if USE_ETHERNET_TCPIP #if LWIP_AUTOIP autoip_set_struct(&netif, &netif_autoip); #endif /* LWIP_AUTOIP */ #if LWIP_DHCP dhcp_set_struct(&netif, &netif_dhcp); #endif /* LWIP_DHCP */ netif_set_up(&netif); #if USE_DHCP err = dhcp_start(&netif); LWIP_ASSERT("dhcp_start failed", err == ERR_OK); #elif USE_AUTOIP err = autoip_start(&netif); LWIP_ASSERT("autoip_start failed", err == ERR_OK); #endif /* USE_DHCP */ #else /* USE_ETHERNET_TCPIP */ /* Use ethernet for PPPoE only */ netif.flags &= ~(NETIF_FLAG_ETHARP | NETIF_FLAG_IGMP); /* no ARP */ netif.flags |= NETIF_FLAG_ETHERNET; /* but pure ethernet */ #endif /* USE_ETHERNET_TCPIP */ #if PPP_SUPPORT && PPPOE_SUPPORT /* start PPPoE after ethernet netif is added! */ ppp = pppoe_create(&ppp_netif, &netif, NULL, NULL, pppLinkStatusCallback, NULL); if (ppp == NULL) { printf("pppos_create error\n"); } else { ppp_set_auth(ppp, PPPAUTHTYPE_ANY, username, password); ppp_connect(ppp, 0); } #endif /* PPP_SUPPORT && PPPOE_SUPPORT */ #endif /* USE_ETHERNET */ #if USE_SLIPIF #if LWIP_IPV4 #define SLIP1_ADDRS &ipaddr_slip1, &netmask_slip1, &gw_slip1, LWIP_PORT_INIT_SLIP1_IPADDR(&ipaddr_slip1); LWIP_PORT_INIT_SLIP1_GW(&gw_slip1); LWIP_PORT_INIT_SLIP1_NETMASK(&netmask_slip1); printf("Starting lwIP slipif, local interface IP is %s\n", ip4addr_ntoa(&ipaddr_slip1)); #else #define SLIP1_ADDRS printf("Starting lwIP slipif\n"); #endif #if defined(SIO_USE_COMPORT) && SIO_USE_COMPORT num_slip1++; /* COM ports cannot be 0-based */ #endif netif_add(&slipif1, SLIP1_ADDRS &num_slip1, slipif_init, ip_input); #if !USE_ETHERNET netif_set_default(&slipif1); #endif /* !USE_ETHERNET */ #if LWIP_IPV6 netif_create_ip6_linklocal_address(&slipif1, 1); printf("SLIP ip6 linklocal address: "); ip6_addr_debug_print(0xFFFFFFFF & ~LWIP_DBG_HALT, netif_ip6_addr(&slipif1, 0)); printf("\n"); #endif /* LWIP_IPV6 */ #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&slipif1, status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ #if LWIP_NETIF_LINK_CALLBACK netif_set_link_callback(&slipif1, link_callback); #endif /* LWIP_NETIF_LINK_CALLBACK */ netif_set_up(&slipif1); #if USE_SLIPIF > 1 #if LWIP_IPV4 #define SLIP2_ADDRS &ipaddr_slip2, &netmask_slip2, &gw_slip2, LWIP_PORT_INIT_SLIP2_IPADDR(&ipaddr_slip2); LWIP_PORT_INIT_SLIP2_GW(&gw_slip2); LWIP_PORT_INIT_SLIP2_NETMASK(&netmask_slip2); printf("Starting lwIP SLIP if #2, local interface IP is %s\n", ip4addr_ntoa(&ipaddr_slip2)); #else #define SLIP2_ADDRS printf("Starting lwIP SLIP if #2\n"); #endif #if defined(SIO_USE_COMPORT) && SIO_USE_COMPORT num_slip2++; /* COM ports cannot be 0-based */ #endif netif_add(&slipif2, SLIP2_ADDRS &num_slip2, slipif_init, ip_input); #if LWIP_IPV6 netif_create_ip6_linklocal_address(&slipif1, 1); printf("SLIP2 ip6 linklocal address: "); ip6_addr_debug_print(0xFFFFFFFF & ~LWIP_DBG_HALT, netif_ip6_addr(&slipif2, 0)); printf("\n"); #endif /* LWIP_IPV6 */ #if LWIP_NETIF_STATUS_CALLBACK netif_set_status_callback(&slipif2, status_callback); #endif /* LWIP_NETIF_STATUS_CALLBACK */ #if LWIP_NETIF_LINK_CALLBACK netif_set_link_callback(&slipif2, link_callback); #endif /* LWIP_NETIF_LINK_CALLBACK */ netif_set_up(&slipif2); #endif /* USE_SLIPIF > 1*/ #endif /* USE_SLIPIF */ } #if LWIP_DNS_APP && LWIP_DNS static void dns_found(const char *name, const ip_addr_t *addr, void *arg) { LWIP_UNUSED_ARG(arg); printf("%s: %s\n", name, addr ? ipaddr_ntoa(addr) : "<not found>"); } static void dns_dorequest(void *arg) { const char* dnsname = "3com.com"; ip_addr_t dnsresp; LWIP_UNUSED_ARG(arg); if (dns_gethostbyname(dnsname, &dnsresp, dns_found, 0) == ERR_OK) { dns_found(dnsname, &dnsresp, 0); } } #endif /* LWIP_DNS_APP && LWIP_DNS */ #if LWIP_LWIPERF_APP static void lwiperf_report(void *arg, enum lwiperf_report_type report_type, const ip_addr_t* local_addr, u16_t local_port, const ip_addr_t* remote_addr, u16_t remote_port, u32_t bytes_transferred, u32_t ms_duration, u32_t bandwidth_kbitpsec) { LWIP_UNUSED_ARG(arg); LWIP_UNUSED_ARG(local_addr); LWIP_UNUSED_ARG(local_port); printf("IPERF report: type=%d, remote: %s:%d, total bytes: %lu, duration in ms: %lu, kbits/s: %lu\n", (int)report_type, ipaddr_ntoa(remote_addr), (int)remote_port, bytes_transferred, ms_duration, bandwidth_kbitpsec); } #endif /* LWIP_LWIPERF_APP */ #if LWIP_MDNS_RESPONDER static void srv_txt(struct mdns_service *service, void *txt_userdata) { err_t res = mdns_resp_add_service_txtitem(service, "path=/", 6); LWIP_ERROR("mdns add service txt failed\n", (res == ERR_OK), return); LWIP_UNUSED_ARG(txt_userdata); } #endif /* This function initializes applications */ static void apps_init(void) { #if LWIP_DNS_APP && LWIP_DNS /* wait until the netif is up (for dhcp, autoip or ppp) */ sys_timeout(5000, dns_dorequest, NULL); #endif /* LWIP_DNS_APP && LWIP_DNS */ #if LWIP_CHARGEN_APP && LWIP_SOCKET chargen_init(); #endif /* LWIP_CHARGEN_APP && LWIP_SOCKET */ #if LWIP_PING_APP && LWIP_RAW && LWIP_ICMP ping_init(); #endif /* LWIP_PING_APP && LWIP_RAW && LWIP_ICMP */ #if LWIP_NETBIOS_APP && LWIP_UDP netbiosns_init(); #ifndef NETBIOS_LWIP_NAME #if LWIP_NETIF_HOSTNAME netbiosns_set_name(netif_default->hostname); #else netbiosns_set_name("NETBIOSLWIPDEV"); #endif #endif #endif /* LWIP_NETBIOS_APP && LWIP_UDP */ #if LWIP_HTTPD_APP && LWIP_TCP #ifdef LWIP_HTTPD_APP_NETCONN http_server_netconn_init(); #else /* LWIP_HTTPD_APP_NETCONN */ httpd_init(); #endif /* LWIP_HTTPD_APP_NETCONN */ #endif /* LWIP_HTTPD_APP && LWIP_TCP */ #if LWIP_MDNS_RESPONDER mdns_resp_init(); #if LWIP_NETIF_HOSTNAME mdns_resp_add_netif(netif_default, netif_default->hostname, 3600); #else mdns_resp_add_netif(netif_default, "lwip", 3600); #endif mdns_resp_add_service(netif_default, "lwipweb", "_http", DNSSD_PROTO_TCP, HTTPD_SERVER_PORT, 3600, srv_txt, NULL); #endif #if LWIP_NETIO_APP && LWIP_TCP netio_init(); #endif /* LWIP_NETIO_APP && LWIP_TCP */ #if LWIP_RTP_APP && LWIP_SOCKET && LWIP_IGMP rtp_init(); #endif /* LWIP_RTP_APP && LWIP_SOCKET && LWIP_IGMP */ #if LWIP_SNTP_APP && LWIP_SOCKET sntp_init(); #endif /* LWIP_SNTP_APP && LWIP_SOCKET */ #if LWIP_SHELL_APP && LWIP_NETCONN shell_init(); #endif /* LWIP_SHELL_APP && LWIP_NETCONN */ #if LWIP_TCPECHO_APP #if LWIP_NETCONN && defined(LWIP_TCPECHO_APP_NETCONN) tcpecho_init(); #else /* LWIP_NETCONN && defined(LWIP_TCPECHO_APP_NETCONN) */ tcpecho_raw_init(); #endif #endif /* LWIP_TCPECHO_APP && LWIP_NETCONN */ #if LWIP_UDPECHO_APP && LWIP_NETCONN udpecho_init(); #endif /* LWIP_UDPECHO_APP && LWIP_NETCONN */ #if LWIP_LWIPERF_APP lwiperf_start_tcp_server_default(lwiperf_report, NULL); #endif #if LWIP_SOCKET_EXAMPLES_APP && LWIP_SOCKET socket_examples_init(); #endif /* LWIP_SOCKET_EXAMPLES_APP && LWIP_SOCKET */ #ifdef LWIP_APP_INIT LWIP_APP_INIT(); #endif } /* This function initializes this lwIP test. When NO_SYS=1, this is done in * the main_loop context (there is no other one), when NO_SYS=0, this is done * in the tcpip_thread context */ static void test_init(void * arg) { /* remove compiler warning */ #if NO_SYS LWIP_UNUSED_ARG(arg); #else /* NO_SYS */ sys_sem_t *init_sem; LWIP_ASSERT("arg != NULL", arg != NULL); init_sem = (sys_sem_t*)arg; #endif /* NO_SYS */ /* init randomizer again (seed per thread) */ srand((unsigned int)time(0)); /* init network interfaces */ msvc_netif_init(); /* init apps */ apps_init(); #if !NO_SYS sys_sem_signal(init_sem); #endif /* !NO_SYS */ } /* This is somewhat different to other ports: we have a main loop here: * a dedicated task that waits for packets to arrive. This would normally be * done from interrupt context with embedded hardware, but we don't get an * interrupt in windows for that :-) */ static void main_loop(void) { #if !NO_SYS err_t err; sys_sem_t init_sem; #endif /* NO_SYS */ #if PPP_SUPPORT #if !USE_ETHERNET int count; u8_t rxbuf[1024]; #endif volatile int callClosePpp = 0; #endif /* PPP_SUPPORT */ /* initialize lwIP stack, network interfaces and applications */ #if NO_SYS lwip_init(); test_init(NULL); #else /* NO_SYS */ err = sys_sem_new(&init_sem, 0); LWIP_ASSERT("failed to create init_sem", err == ERR_OK); tcpip_init(test_init, &init_sem); /* we have to wait for initialization to finish before * calling update_adapter()! */ sys_sem_wait(&init_sem); sys_sem_free(&init_sem); #endif /* NO_SYS */ #if (LWIP_SOCKET || LWIP_NETCONN) && LWIP_NETCONN_SEM_PER_THREAD netconn_thread_init(); #endif /* MAIN LOOP for driver update (and timers if NO_SYS) */ while (!_kbhit()) { #if NO_SYS /* handle timers (already done in tcpip.c when NO_SYS=0) */ sys_check_timeouts(); #endif /* NO_SYS */ #if USE_ETHERNET #if !PCAPIF_RX_USE_THREAD /* check for packets and link status*/ pcapif_poll(&netif); /* When pcapif_poll comes back, there are not packets, so sleep to prevent 100% CPU load. Don't do this in an embedded system since it increases latency! */ sys_msleep(1); #else /* !PCAPIF_RX_USE_THREAD */ sys_msleep(50); #endif /* !PCAPIF_RX_USE_THREAD */ #else /* USE_ETHERNET */ /* try to read characters from serial line and pass them to PPPoS */ count = sio_read(ppp_sio, (u8_t*)rxbuf, 1024); if(count > 0) { pppos_input(ppp, rxbuf, count); } else { /* nothing received, give other tasks a chance to run */ sys_msleep(1); } #endif /* USE_ETHERNET */ #if USE_SLIPIF slipif_poll(&slipif1); #if USE_SLIPIF > 1 slipif_poll(&slipif2); #endif /* USE_SLIPIF > 1 */ #endif /* USE_SLIPIF */ #if ENABLE_LOOPBACK && !LWIP_NETIF_LOOPBACK_MULTITHREADING /* check for loopback packets on all netifs */ netif_poll_all(); #endif /* ENABLE_LOOPBACK && !LWIP_NETIF_LOOPBACK_MULTITHREADING */ #if PPP_SUPPORT { int do_hup = 0; if(do_hup) { ppp_close(ppp, 1); do_hup = 0; } } if(callClosePpp && ppp) { /* make sure to disconnect PPP before stopping the program... */ callClosePpp = 0; #if NO_SYS ppp_close(ppp, 0); #else pppapi_close(ppp, 0); #endif ppp = NULL; } #endif /* PPP_SUPPORT */ } #if PPP_SUPPORT if(ppp) { u32_t started; printf("Closing PPP connection...\n"); /* make sure to disconnect PPP before stopping the program... */ #if NO_SYS ppp_close(ppp, 0); #else pppapi_close(ppp, 0); #endif ppp = NULL; /* Wait for some time to let PPP finish... */ started = sys_now(); do { #if USE_ETHERNET && !PCAPIF_RX_USE_THREAD pcapif_poll(&netif); #else /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */ sys_msleep(50); #endif /* USE_ETHERNET && !PCAPIF_RX_USE_THREAD */ /* @todo: need a better check here: only wait until PPP is down */ } while(sys_now() - started < 5000); } #endif /* PPP_SUPPORT */ #if (LWIP_SOCKET || LWIP_NETCONN) && LWIP_NETCONN_SEM_PER_THREAD netconn_thread_cleanup(); #endif #if USE_ETHERNET /* release the pcap library... */ pcapif_shutdown(&netif); #endif /* USE_ETHERNET */ } #if PPP_SUPPORT && PPPOS_SUPPORT int main(int argc, char **argv) #else /* PPP_SUPPORT && PPPOS_SUPPORT */ int main(void) #endif /* PPP_SUPPORT && PPPOS_SUPPORT */ { #if PPP_SUPPORT && PPPOS_SUPPORT if(argc > 1) { sio_idx = (u8_t)atoi(argv[1]); } printf("Using serial port %d for PPP\n", sio_idx); #endif /* PPP_SUPPORT && PPPOS_SUPPORT */ /* no stdio-buffering, please! */ setvbuf(stdout, NULL,_IONBF, 0); main_loop(); return 0; }
2301_81045437/classic-platform
communication/lwip-2.0.3/contrib/ports/win32/test.c
C
unknown
23,197
void eth_mac_irq() { /* Service MAC IRQ here */ /* Allocate pbuf from pool (avoid using heap in interrupts) */ struct pbuf* p = pbuf_alloc(PBUF_RAW, eth_data_count, PBUF_POOL); if(p != NULL) { /* Copy ethernet frame into pbuf */ pbuf_take(p, eth_data, eth_data_count); /* Put in a queue which is processed in main loop */ if(!queue_try_put(&queue, p)) { /* queue is full -> packet loss */ pbuf_free(p); } } } static err_t netif_output(struct netif *netif, struct pbuf *p) { LINK_STATS_INC(link.xmit); /* Update SNMP stats (only if you use SNMP) */ MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p->tot_len); int unicast = ((p->payload[0] & 0x01) == 0); if (unicast) { MIB2_STATS_NETIF_INC(netif, ifoutucastpkts); } else { MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts); } lock_interrupts(); pbuf_copy_partial(p, mac_send_buffer, p->tot_len, 0); /* Start MAC transmit here */ unlock_interrupts(); return ERR_OK; } static void netif_status_callback(struct netif *netif) { printf("netif status changed %s\n", ip4addr_ntoa(netif_ip4_addr(netif))); } static err_t netif_init(struct netif *netif) { netif->linkoutput = netif_output; netif->output = etharp_output; netif->output_ip6 = ethip6_output; netif->mtu = ETHERNET_MTU; netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP | NETIF_FLAG_MLD6; MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, 100000000); SMEMCPY(netif->hwaddr, your_mac_address_goes_here, sizeof(netif->hwaddr)); netif->hwaddr_len = sizeof(netif->hwaddr); return ERR_OK; } void main(void) { struct netif netif; lwip_init(); netif_add(&netif, IP4_ADDR_ANY, IP4_ADDR_ANY, IP4_ADDR_ANY, NULL, netif_init, netif_input); netif.name[0] = 'e'; netif.name[1] = '0'; netif_create_ip6_linklocal_address(&netif, 1); netif.ip6_autoconfig_enabled = 1; netif_set_status_callback(&netif, netif_status_callback); netif_set_default(&netif); netif_set_up(&netif); /* Start DHCP and HTTPD */ dhcp_start(&netif ); httpd_init(); while(1) { /* Check link state, e.g. via MDIO communication with PHY */ if(link_state_changed()) { if(link_is_up()) { netif_set_link_up(&netif); } else { netif_set_link_down(&netif); } } /* Check for received frames, feed them to lwIP */ lock_interrupts(); struct pbuf* p = queue_try_get(&queue); unlock_interrupts(); if(p != NULL) { LINK_STATS_INC(link.recv); /* Update SNMP stats (only if you use SNMP) */ MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len); int unicast = ((p->payload[0] & 0x01) == 0); if (unicast) { MIB2_STATS_NETIF_INC(netif, ifinucastpkts); } else { MIB2_STATS_NETIF_INC(netif, ifinnucastpkts); } if(netif.input(p, &netif) != ERR_OK) { pbuf_free(p); } } /* Cyclic lwIP timers check */ sys_check_timeouts(); /* your application goes here */ } }
2301_81045437/classic-platform
communication/lwip-2.0.3/doc/NO_SYS_SampleCode.c
C
unknown
3,190
doxygen lwip.Doxyfile
2301_81045437/classic-platform
communication/lwip-2.0.3/doc/doxygen/generate.bat
Batchfile
unknown
23
#!/bin/sh doxygen lwip.Doxyfile
2301_81045437/classic-platform
communication/lwip-2.0.3/doc/doxygen/generate.sh
Shell
unknown
36
/** * @defgroup lwip lwIP * * @defgroup infrastructure Infrastructure * * @defgroup callbackstyle_api Callback-style APIs * Non thread-safe APIs, callback style for maximum performance and minimum * memory footprint. * * @defgroup sequential_api Sequential-style APIs * Sequential-style APIs, blocking functions. More overhead, but can be called * from any thread except TCPIP thread. * * @defgroup addons Addons * * @defgroup apps Applications */ /** * @mainpage Overview * @verbinclude "README" */ /** * @page upgrading Upgrading * @verbinclude "UPGRADING" */ /** * @page changelog Changelog * @verbinclude "CHANGELOG" */ /** * @page contrib How to contribute to lwIP * @verbinclude "contrib.txt" */ /** * @page pitfalls Common pitfalls * * Multiple Execution Contexts in lwIP code * ======================================== * * The most common source of lwIP problems is to have multiple execution contexts * inside the lwIP code. * * lwIP can be used in two basic modes: @ref lwip_nosys (no OS/RTOS * running on target system) or @ref lwip_os (there is an OS running * on the target system). * * Mainloop Mode * ------------- * In mainloop mode, only @ref callbackstyle_api can be used. * The user has two possibilities to ensure there is only one * exection context at a time in lwIP: * * 1) Deliver RX ethernet packets directly in interrupt context to lwIP * by calling netif->input directly in interrupt. This implies all lwIP * callback functions are called in IRQ context, which may cause further * problems in application code: IRQ is blocked for a long time, multiple * execution contexts in application code etc. When the application wants * to call lwIP, it only needs to disable interrupts during the call. * If timers are involved, even more locking code is needed to lock out * timer IRQ and ethernet IRQ from each other, assuming these may be nested. * * 2) Run lwIP in a mainloop. There is example code here: @ref lwip_nosys. * lwIP is _ONLY_ called from mainloop callstacks here. The ethernet IRQ * has to put received telegrams into a queue which is polled in the * mainloop. Ensure lwIP is _NEVER_ called from an interrupt, e.g. * some SPI IRQ wants to forward data to udp_send() or tcp_write()! * * OS Mode * ------- * In OS mode, @ref callbackstyle_api AND @ref sequential_api can be used. * @ref sequential_api are designed to be called from threads other than * the TCPIP thread, so there is nothing to consider here. * But @ref callbackstyle_api functions must _ONLY_ be called from * TCPIP thread. It is a common error to call these from other threads * or from IRQ contexts. ​Ethernet RX needs to deliver incoming packets * in the correct way by sending a message to TCPIP thread, this is * implemented in tcpip_input().​​ * Again, ensure lwIP is _NEVER_ called from an interrupt, e.g. * some SPI IRQ wants to forward data to udp_send() or tcp_write()! * * 1) tcpip_callback() can be used get called back from TCPIP thread, * it is safe to call any @ref callbackstyle_api from there. * * 2) Use @ref LWIP_TCPIP_CORE_LOCKING. All @ref callbackstyle_api * functions can be called when lwIP core lock is aquired, see * @ref LOCK_TCPIP_CORE() and @ref UNLOCK_TCPIP_CORE(). * These macros cannot be used in an interrupt context! * Note the OS must correctly handle priority inversion for this. */ /** * @page bugs Reporting bugs * Please report bugs in the lwIP bug tracker at savannah.\n * BEFORE submitting, please check if the bug has already been reported!\n * https://savannah.nongnu.org/bugs/?group=lwip */ /** * @defgroup lwip_nosys Mainloop mode ("NO_SYS") * @ingroup lwip * Use this mode if you do not run an OS on your system. \#define NO_SYS to 1. * Feed incoming packets to netif->input(pbuf, netif) function from mainloop, * *not* *from* *interrupt* *context*. You can allocate a @ref pbuf in interrupt * context and put them into a queue which is processed from mainloop.\n * Call sys_check_timeouts() periodically in the mainloop.\n * Porting: implement all functions in @ref sys_time, @ref sys_prot and * @ref compiler_abstraction.\n * You can only use @ref callbackstyle_api in this mode.\n * Sample code:\n * @include NO_SYS_SampleCode.c */ /** * @defgroup lwip_os OS mode (TCPIP thread) * @ingroup lwip * Use this mode if you run an OS on your system. It is recommended to * use an RTOS that correctly handles priority inversion and * to use @ref LWIP_TCPIP_CORE_LOCKING.\n * Porting: implement all functions in @ref sys_layer.\n * You can use @ref callbackstyle_api together with @ref tcpip_callback, * and all @ref sequential_api. */ /** * @page raw_api lwIP API * @verbinclude "rawapi.txt" */
2301_81045437/classic-platform
communication/lwip-2.0.3/doc/doxygen/main_page.h
C
unknown
4,958
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Redirection</title> <meta http-equiv="refresh" content="0; url=html/index.html" /> </head> <body> <a href="html/index.html">index.html</a> </body> </html>
2301_81045437/classic-platform
communication/lwip-2.0.3/doc/doxygen/output/index.html
HTML
unknown
351
# # Copyright (c) 2001, 2002 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> # # COREFILES, CORE4FILES: The minimum set of files needed for lwIP. COREFILES=$(LWIPDIR)/core/init.c \ $(LWIPDIR)/core/def.c \ $(LWIPDIR)/core/dns.c \ $(LWIPDIR)/core/inet_chksum.c \ $(LWIPDIR)/core/ip.c \ $(LWIPDIR)/core/mem.c \ $(LWIPDIR)/core/memp.c \ $(LWIPDIR)/core/netif.c \ $(LWIPDIR)/core/pbuf.c \ $(LWIPDIR)/core/raw.c \ $(LWIPDIR)/core/stats.c \ $(LWIPDIR)/core/sys.c \ $(LWIPDIR)/core/tcp.c \ $(LWIPDIR)/core/tcp_in.c \ $(LWIPDIR)/core/tcp_out.c \ $(LWIPDIR)/core/timeouts.c \ $(LWIPDIR)/core/udp.c CORE4FILES=$(LWIPDIR)/core/ipv4/autoip.c \ $(LWIPDIR)/core/ipv4/dhcp.c \ $(LWIPDIR)/core/ipv4/etharp.c \ $(LWIPDIR)/core/ipv4/icmp.c \ $(LWIPDIR)/core/ipv4/igmp.c \ $(LWIPDIR)/core/ipv4/ip4_frag.c \ $(LWIPDIR)/core/ipv4/ip4.c \ $(LWIPDIR)/core/ipv4/ip4_addr.c CORE6FILES=$(LWIPDIR)/core/ipv6/dhcp6.c \ $(LWIPDIR)/core/ipv6/ethip6.c \ $(LWIPDIR)/core/ipv6/icmp6.c \ $(LWIPDIR)/core/ipv6/inet6.c \ $(LWIPDIR)/core/ipv6/ip6.c \ $(LWIPDIR)/core/ipv6/ip6_addr.c \ $(LWIPDIR)/core/ipv6/ip6_frag.c \ $(LWIPDIR)/core/ipv6/mld6.c \ $(LWIPDIR)/core/ipv6/nd6.c # APIFILES: The files which implement the sequential and socket APIs. APIFILES=$(LWIPDIR)/api/api_lib.c \ $(LWIPDIR)/api/api_msg.c \ $(LWIPDIR)/api/err.c \ $(LWIPDIR)/api/netbuf.c \ $(LWIPDIR)/api/netdb.c \ $(LWIPDIR)/api/netifapi.c \ $(LWIPDIR)/api/sockets.c \ $(LWIPDIR)/api/tcpip.c # NETIFFILES: Files implementing various generic network interface functions NETIFFILES=$(LWIPDIR)/netif/ethernet.c \ $(LWIPDIR)/netif/slipif.c # SIXLOWPAN: 6LoWPAN SIXLOWPAN=$(LWIPDIR)/netif/lowpan6.c \ # PPPFILES: PPP PPPFILES=$(LWIPDIR)/netif/ppp/auth.c \ $(LWIPDIR)/netif/ppp/ccp.c \ $(LWIPDIR)/netif/ppp/chap-md5.c \ $(LWIPDIR)/netif/ppp/chap_ms.c \ $(LWIPDIR)/netif/ppp/chap-new.c \ $(LWIPDIR)/netif/ppp/demand.c \ $(LWIPDIR)/netif/ppp/eap.c \ $(LWIPDIR)/netif/ppp/ecp.c \ $(LWIPDIR)/netif/ppp/eui64.c \ $(LWIPDIR)/netif/ppp/fsm.c \ $(LWIPDIR)/netif/ppp/ipcp.c \ $(LWIPDIR)/netif/ppp/ipv6cp.c \ $(LWIPDIR)/netif/ppp/lcp.c \ $(LWIPDIR)/netif/ppp/magic.c \ $(LWIPDIR)/netif/ppp/mppe.c \ $(LWIPDIR)/netif/ppp/multilink.c \ $(LWIPDIR)/netif/ppp/ppp.c \ $(LWIPDIR)/netif/ppp/pppapi.c \ $(LWIPDIR)/netif/ppp/pppcrypt.c \ $(LWIPDIR)/netif/ppp/pppoe.c \ $(LWIPDIR)/netif/ppp/pppol2tp.c \ $(LWIPDIR)/netif/ppp/pppos.c \ $(LWIPDIR)/netif/ppp/upap.c \ $(LWIPDIR)/netif/ppp/utils.c \ $(LWIPDIR)/netif/ppp/vj.c \ $(LWIPDIR)/netif/ppp/polarssl/arc4.c \ $(LWIPDIR)/netif/ppp/polarssl/des.c \ $(LWIPDIR)/netif/ppp/polarssl/md4.c \ $(LWIPDIR)/netif/ppp/polarssl/md5.c \ $(LWIPDIR)/netif/ppp/polarssl/sha1.c # LWIPNOAPPSFILES: All LWIP files without apps LWIPNOAPPSFILES=$(COREFILES) \ $(CORE4FILES) \ $(CORE6FILES) \ $(APIFILES) \ $(NETIFFILES) \ $(PPPFILES) \ $(SIXLOWPAN) # SNMPFILES: SNMPv2c agent SNMPFILES=$(LWIPDIR)/apps/snmp/snmp_asn1.c \ $(LWIPDIR)/apps/snmp/snmp_core.c \ $(LWIPDIR)/apps/snmp/snmp_mib2.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_icmp.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_interfaces.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_ip.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_snmp.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_system.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_tcp.c \ $(LWIPDIR)/apps/snmp/snmp_mib2_udp.c \ $(LWIPDIR)/apps/snmp/snmp_msg.c \ $(LWIPDIR)/apps/snmp/snmpv3.c \ $(LWIPDIR)/apps/snmp/snmp_netconn.c \ $(LWIPDIR)/apps/snmp/snmp_pbuf_stream.c \ $(LWIPDIR)/apps/snmp/snmp_raw.c \ $(LWIPDIR)/apps/snmp/snmp_scalar.c \ $(LWIPDIR)/apps/snmp/snmp_table.c \ $(LWIPDIR)/apps/snmp/snmp_threadsync.c \ $(LWIPDIR)/apps/snmp/snmp_traps.c \ $(LWIPDIR)/apps/snmp/snmpv3_mbedtls.c \ $(LWIPDIR)/apps/snmp/snmpv3_dummy.c # HTTPDFILES: HTTP server HTTPDFILES=$(LWIPDIR)/apps/httpd/fs.c \ $(LWIPDIR)/apps/httpd/httpd.c # LWIPERFFILES: IPERF server LWIPERFFILES=$(LWIPDIR)/apps/lwiperf/lwiperf.c # SNTPFILES: SNTP client SNTPFILES=$(LWIPDIR)/apps/sntp/sntp.c # MDNSFILES: MDNS responder MDNSFILES=$(LWIPDIR)/apps/mdns/mdns.c # NETBIOSNSFILES: NetBIOS name server NETBIOSNSFILES=$(LWIPDIR)/apps/netbiosns/netbiosns.c # TFTPFILES: TFTP server files TFTPFILES=$(LWIPDIR)/apps/tftp/tftp_server.c # MQTTFILES: MQTT client files MQTTFILES=$(LWIPDIR)/apps/mqtt/mqtt.c # LWIPAPPFILES: All LWIP APPs LWIPAPPFILES=$(SNMPFILES) \ $(HTTPDFILES) \ $(LWIPERFFILES) \ $(SNTPFILES) \ $(MDNSFILES) \ $(NETBIOSNSFILES) \ $(TFTPFILES) \ $(MQTTFILES)
2301_81045437/classic-platform
communication/lwip-2.0.3/src/Filelists.mk
Makefile
unknown
6,121
/** * @file * Sequential API External module * * @defgroup netconn Netconn API * @ingroup sequential_api * Thread-safe, to be called from non-TCPIP threads only. * TX/RX handling based on @ref netbuf (containing @ref pbuf) * to avoid copying data around. * * @defgroup netconn_common Common functions * @ingroup netconn * For use with TCP and UDP * * @defgroup netconn_tcp TCP only * @ingroup netconn * TCP only functions * * @defgroup netconn_udp UDP only * @ingroup netconn * UDP only functions */ /* * 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> */ /* This is the part of the API that is linked with the application */ #include "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include "lwip/api.h" #include "lwip/memp.h" #include "lwip/ip.h" #include "lwip/raw.h" #include "lwip/udp.h" #include "lwip/priv/api_msg.h" #include "lwip/priv/tcp_priv.h" #include "lwip/priv/tcpip_priv.h" #include <string.h> #define API_MSG_VAR_REF(name) API_VAR_REF(name) #define API_MSG_VAR_DECLARE(name) API_VAR_DECLARE(struct api_msg, name) #define API_MSG_VAR_ALLOC(name) API_VAR_ALLOC(struct api_msg, MEMP_API_MSG, name, ERR_MEM) #define API_MSG_VAR_ALLOC_RETURN_NULL(name) API_VAR_ALLOC(struct api_msg, MEMP_API_MSG, name, NULL) #define API_MSG_VAR_FREE(name) API_VAR_FREE(MEMP_API_MSG, name) static err_t netconn_close_shutdown(struct netconn *conn, u8_t how); /** * Call the lower part of a netconn_* function * This function is then running in the thread context * of tcpip_thread and has exclusive access to lwIP core code. * * @param fn function to call * @param apimsg a struct containing the function to call and its parameters * @return ERR_OK if the function was called, another err_t if not */ static err_t netconn_apimsg(tcpip_callback_fn fn, struct api_msg *apimsg) { err_t err; #ifdef LWIP_DEBUG /* catch functions that don't set err */ apimsg->err = ERR_VAL; #endif /* LWIP_DEBUG */ #if LWIP_NETCONN_SEM_PER_THREAD apimsg->op_completed_sem = LWIP_NETCONN_THREAD_SEM_GET(); #endif /* LWIP_NETCONN_SEM_PER_THREAD */ err = tcpip_send_msg_wait_sem(fn, apimsg, LWIP_API_MSG_SEM(apimsg)); if (err == ERR_OK) { return apimsg->err; } return err; } /** * Create a new netconn (of a specific type) that has a callback function. * The corresponding pcb is also created. * * @param t the type of 'connection' to create (@see enum netconn_type) * @param proto the IP protocol for RAW IP pcbs * @param callback a function to call on status changes (RX available, TX'ed) * @return a newly allocated struct netconn or * NULL on memory error */ struct netconn* netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, netconn_callback callback) { struct netconn *conn; API_MSG_VAR_DECLARE(msg); API_MSG_VAR_ALLOC_RETURN_NULL(msg); conn = netconn_alloc(t, callback); if (conn != NULL) { err_t err; API_MSG_VAR_REF(msg).msg.n.proto = proto; API_MSG_VAR_REF(msg).conn = conn; err = netconn_apimsg(lwip_netconn_do_newconn, &API_MSG_VAR_REF(msg)); if (err != ERR_OK) { LWIP_ASSERT("freeing conn without freeing pcb", conn->pcb.tcp == NULL); LWIP_ASSERT("conn has no recvmbox", sys_mbox_valid(&conn->recvmbox)); #if LWIP_TCP LWIP_ASSERT("conn->acceptmbox shouldn't exist", !sys_mbox_valid(&conn->acceptmbox)); #endif /* LWIP_TCP */ #if !LWIP_NETCONN_SEM_PER_THREAD LWIP_ASSERT("conn has no op_completed", sys_sem_valid(&conn->op_completed)); sys_sem_free(&conn->op_completed); #endif /* !LWIP_NETCONN_SEM_PER_THREAD */ sys_mbox_free(&conn->recvmbox); memp_free(MEMP_NETCONN, conn); API_MSG_VAR_FREE(msg); return NULL; } } API_MSG_VAR_FREE(msg); return conn; } /** * @ingroup netconn_common * Close a netconn 'connection' and free its resources. * UDP and RAW connection are completely closed, TCP pcbs might still be in a waitstate * after this returns. * * @param conn the netconn to delete * @return ERR_OK if the connection was deleted */ err_t netconn_delete(struct netconn *conn) { err_t err; API_MSG_VAR_DECLARE(msg); /* No ASSERT here because possible to get a (conn == NULL) if we got an accept error */ if (conn == NULL) { return ERR_OK; } API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; #if LWIP_SO_SNDTIMEO || LWIP_SO_LINGER /* get the time we started, which is later compared to sys_now() + conn->send_timeout */ API_MSG_VAR_REF(msg).msg.sd.time_started = sys_now(); #else /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ #if LWIP_TCP API_MSG_VAR_REF(msg).msg.sd.polls_left = ((LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT + TCP_SLOW_INTERVAL - 1) / TCP_SLOW_INTERVAL) + 1; #endif /* LWIP_TCP */ #endif /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ err = netconn_apimsg(lwip_netconn_do_delconn, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); if (err != ERR_OK) { return err; } netconn_free(conn); return ERR_OK; } /** * Get the local or remote IP address and port of a netconn. * For RAW netconns, this returns the protocol instead of a port! * * @param conn the netconn to query * @param addr a pointer to which to save the IP address * @param port a pointer to which to save the port (or protocol for RAW) * @param local 1 to get the local IP address, 0 to get the remote one * @return ERR_CONN for invalid connections * ERR_OK if the information was retrieved */ err_t netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_getaddr: invalid conn", (conn != NULL), return ERR_ARG;); LWIP_ERROR("netconn_getaddr: invalid addr", (addr != NULL), return ERR_ARG;); LWIP_ERROR("netconn_getaddr: invalid port", (port != NULL), return ERR_ARG;); API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.ad.local = local; #if LWIP_MPU_COMPATIBLE err = netconn_apimsg(lwip_netconn_do_getaddr, &API_MSG_VAR_REF(msg)); *addr = msg->msg.ad.ipaddr; *port = msg->msg.ad.port; #else /* LWIP_MPU_COMPATIBLE */ msg.msg.ad.ipaddr = addr; msg.msg.ad.port = port; err = netconn_apimsg(lwip_netconn_do_getaddr, &msg); #endif /* LWIP_MPU_COMPATIBLE */ API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_common * Bind a netconn to a specific local IP address and port. * Binding one netconn twice might not always be checked correctly! * * @param conn the netconn to bind * @param addr the local IP address to bind the netconn to * (use IP4_ADDR_ANY/IP6_ADDR_ANY to bind to all addresses) * @param port the local port to bind the netconn to (not used for RAW) * @return ERR_OK if bound, any other err_t on failure */ err_t netconn_bind(struct netconn *conn, const ip_addr_t *addr, u16_t port) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_bind: invalid conn", (conn != NULL), return ERR_ARG;); #if LWIP_IPV4 /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */ if (addr == NULL) { addr = IP4_ADDR_ANY; } #endif /* LWIP_IPV4 */ #if LWIP_IPV4 && LWIP_IPV6 /* "Socket API like" dual-stack support: If IP to bind to is IP6_ADDR_ANY, * and NETCONN_FLAG_IPV6_V6ONLY is 0, use IP_ANY_TYPE to bind */ if ((netconn_get_ipv6only(conn) == 0) && ip_addr_cmp(addr, IP6_ADDR_ANY)) { addr = IP_ANY_TYPE; } #endif /* LWIP_IPV4 && LWIP_IPV6 */ API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.bc.ipaddr = API_MSG_VAR_REF(addr); API_MSG_VAR_REF(msg).msg.bc.port = port; err = netconn_apimsg(lwip_netconn_do_bind, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_common * Connect a netconn to a specific remote IP address and port. * * @param conn the netconn to connect * @param addr the remote IP address to connect to * @param port the remote port to connect to (no used for RAW) * @return ERR_OK if connected, return value of tcp_/udp_/raw_connect otherwise */ err_t netconn_connect(struct netconn *conn, const ip_addr_t *addr, u16_t port) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_connect: invalid conn", (conn != NULL), return ERR_ARG;); #if LWIP_IPV4 /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */ if (addr == NULL) { addr = IP4_ADDR_ANY; } #endif /* LWIP_IPV4 */ API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.bc.ipaddr = API_MSG_VAR_REF(addr); API_MSG_VAR_REF(msg).msg.bc.port = port; err = netconn_apimsg(lwip_netconn_do_connect, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_udp * Disconnect a netconn from its current peer (only valid for UDP netconns). * * @param conn the netconn to disconnect * @return See @ref err_t */ err_t netconn_disconnect(struct netconn *conn) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_disconnect: invalid conn", (conn != NULL), return ERR_ARG;); API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; err = netconn_apimsg(lwip_netconn_do_disconnect, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_tcp * Set a TCP netconn into listen mode * * @param conn the tcp netconn to set to listen mode * @param backlog the listen backlog, only used if TCP_LISTEN_BACKLOG==1 * @return ERR_OK if the netconn was set to listen (UDP and RAW netconns * don't return any error (yet?)) */ err_t netconn_listen_with_backlog(struct netconn *conn, u8_t backlog) { #if LWIP_TCP API_MSG_VAR_DECLARE(msg); err_t err; /* This does no harm. If TCP_LISTEN_BACKLOG is off, backlog is unused. */ LWIP_UNUSED_ARG(backlog); LWIP_ERROR("netconn_listen: invalid conn", (conn != NULL), return ERR_ARG;); API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; #if TCP_LISTEN_BACKLOG API_MSG_VAR_REF(msg).msg.lb.backlog = backlog; #endif /* TCP_LISTEN_BACKLOG */ err = netconn_apimsg(lwip_netconn_do_listen, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; #else /* LWIP_TCP */ LWIP_UNUSED_ARG(conn); LWIP_UNUSED_ARG(backlog); return ERR_ARG; #endif /* LWIP_TCP */ } /** * @ingroup netconn_tcp * Accept a new connection on a TCP listening netconn. * * @param conn the TCP listen netconn * @param new_conn pointer where the new connection is stored * @return ERR_OK if a new connection has been received or an error * code otherwise */ err_t netconn_accept(struct netconn *conn, struct netconn **new_conn) { #if LWIP_TCP void *accept_ptr; struct netconn *newconn; #if TCP_LISTEN_BACKLOG API_MSG_VAR_DECLARE(msg); #endif /* TCP_LISTEN_BACKLOG */ LWIP_ERROR("netconn_accept: invalid pointer", (new_conn != NULL), return ERR_ARG;); *new_conn = NULL; LWIP_ERROR("netconn_accept: invalid conn", (conn != NULL), return ERR_ARG;); if (ERR_IS_FATAL(conn->last_err)) { /* don't recv on fatal errors: this might block the application task waiting on acceptmbox forever! */ return conn->last_err; } if (!sys_mbox_valid(&conn->acceptmbox)) { return ERR_CLSD; } #if TCP_LISTEN_BACKLOG API_MSG_VAR_ALLOC(msg); #endif /* TCP_LISTEN_BACKLOG */ #if LWIP_SO_RCVTIMEO if (sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, conn->recv_timeout) == SYS_ARCH_TIMEOUT) { #if TCP_LISTEN_BACKLOG API_MSG_VAR_FREE(msg); #endif /* TCP_LISTEN_BACKLOG */ return ERR_TIMEOUT; } #else sys_arch_mbox_fetch(&conn->acceptmbox, &accept_ptr, 0); #endif /* LWIP_SO_RCVTIMEO*/ newconn = (struct netconn *)accept_ptr; /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0); if (accept_ptr == &netconn_aborted) { /* a connection has been aborted: out of pcbs or out of netconns during accept */ /* @todo: set netconn error, but this would be fatal and thus block further accepts */ #if TCP_LISTEN_BACKLOG API_MSG_VAR_FREE(msg); #endif /* TCP_LISTEN_BACKLOG */ return ERR_ABRT; } if (newconn == NULL) { /* connection has been aborted */ /* in this special case, we set the netconn error from application thread, as on a ready-to-accept listening netconn, there should not be anything running in tcpip_thread */ NETCONN_SET_SAFE_ERR(conn, ERR_CLSD); #if TCP_LISTEN_BACKLOG API_MSG_VAR_FREE(msg); #endif /* TCP_LISTEN_BACKLOG */ return ERR_CLSD; } #if TCP_LISTEN_BACKLOG /* Let the stack know that we have accepted the connection. */ API_MSG_VAR_REF(msg).conn = newconn; /* don't care for the return value of lwip_netconn_do_recv */ netconn_apimsg(lwip_netconn_do_accepted, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); #endif /* TCP_LISTEN_BACKLOG */ *new_conn = newconn; /* don't set conn->last_err: it's only ERR_OK, anyway */ return ERR_OK; #else /* LWIP_TCP */ LWIP_UNUSED_ARG(conn); LWIP_UNUSED_ARG(new_conn); return ERR_ARG; #endif /* LWIP_TCP */ } /** * @ingroup netconn_common * Receive data: actual implementation that doesn't care whether pbuf or netbuf * is received * * @param conn the netconn from which to receive data * @param new_buf pointer where a new pbuf/netbuf is stored when received data * @return ERR_OK if data has been received, an error code otherwise (timeout, * memory error or another error) */ static err_t netconn_recv_data(struct netconn *conn, void **new_buf) { void *buf = NULL; u16_t len; #if LWIP_TCP API_MSG_VAR_DECLARE(msg); #if LWIP_MPU_COMPATIBLE msg = NULL; #endif #endif /* LWIP_TCP */ LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;); *new_buf = NULL; LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;); #if LWIP_TCP #if (LWIP_UDP || LWIP_RAW) if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) #endif /* (LWIP_UDP || LWIP_RAW) */ { if (!sys_mbox_valid(&conn->recvmbox)) { /* This happens when calling this function after receiving FIN */ return sys_mbox_valid(&conn->acceptmbox) ? ERR_CONN : ERR_CLSD; } } #endif /* LWIP_TCP */ LWIP_ERROR("netconn_recv: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;); if (ERR_IS_FATAL(conn->last_err)) { /* don't recv on fatal errors: this might block the application task waiting on recvmbox forever! */ /* @todo: this does not allow us to fetch data that has been put into recvmbox before the fatal error occurred - is that a problem? */ return conn->last_err; } #if LWIP_TCP #if (LWIP_UDP || LWIP_RAW) if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) #endif /* (LWIP_UDP || LWIP_RAW) */ { API_MSG_VAR_ALLOC(msg); } #endif /* LWIP_TCP */ #if LWIP_SO_RCVTIMEO if (sys_arch_mbox_fetch(&conn->recvmbox, &buf, conn->recv_timeout) == SYS_ARCH_TIMEOUT) { #if LWIP_TCP #if (LWIP_UDP || LWIP_RAW) if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) #endif /* (LWIP_UDP || LWIP_RAW) */ { API_MSG_VAR_FREE(msg); } #endif /* LWIP_TCP */ return ERR_TIMEOUT; } #else sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0); #endif /* LWIP_SO_RCVTIMEO*/ #if LWIP_TCP #if (LWIP_UDP || LWIP_RAW) if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) #endif /* (LWIP_UDP || LWIP_RAW) */ { /* Let the stack know that we have taken the data. */ /* @todo: Speedup: Don't block and wait for the answer here (to prevent multiple thread-switches). */ API_MSG_VAR_REF(msg).conn = conn; if (buf != NULL) { API_MSG_VAR_REF(msg).msg.r.len = ((struct pbuf *)buf)->tot_len; } else { API_MSG_VAR_REF(msg).msg.r.len = 1; } /* don't care for the return value of lwip_netconn_do_recv */ netconn_apimsg(lwip_netconn_do_recv, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); /* If we are closed, we indicate that we no longer wish to use the socket */ if (buf == NULL) { API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0); if (conn->pcb.ip == NULL) { /* race condition: RST during recv */ return conn->last_err == ERR_OK ? ERR_RST : conn->last_err; } /* RX side is closed, so deallocate the recvmbox */ netconn_close_shutdown(conn, NETCONN_SHUT_RD); /* Don' store ERR_CLSD as conn->err since we are only half-closed */ return ERR_CLSD; } len = ((struct pbuf *)buf)->tot_len; } #endif /* LWIP_TCP */ #if LWIP_TCP && (LWIP_UDP || LWIP_RAW) else #endif /* LWIP_TCP && (LWIP_UDP || LWIP_RAW) */ #if (LWIP_UDP || LWIP_RAW) { LWIP_ASSERT("buf != NULL", buf != NULL); len = netbuf_len((struct netbuf*)buf); } #endif /* (LWIP_UDP || LWIP_RAW) */ #if LWIP_SO_RCVBUF SYS_ARCH_DEC(conn->recv_avail, len); #endif /* LWIP_SO_RCVBUF */ /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVMINUS, len); LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_recv_data: received %p, len=%"U16_F"\n", buf, len)); *new_buf = buf; /* don't set conn->last_err: it's only ERR_OK, anyway */ return ERR_OK; } /** * @ingroup netconn_tcp * Receive data (in form of a pbuf) from a TCP netconn * * @param conn the netconn from which to receive data * @param new_buf pointer where a new pbuf is stored when received data * @return ERR_OK if data has been received, an error code otherwise (timeout, * memory error or another error) * ERR_ARG if conn is not a TCP netconn */ err_t netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf) { LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL) && NETCONNTYPE_GROUP(netconn_type(conn)) == NETCONN_TCP, return ERR_ARG;); return netconn_recv_data(conn, (void **)new_buf); } /** * @ingroup netconn_common * Receive data (in form of a netbuf containing a packet buffer) from a netconn * * @param conn the netconn from which to receive data * @param new_buf pointer where a new netbuf is stored when received data * @return ERR_OK if data has been received, an error code otherwise (timeout, * memory error or another error) */ err_t netconn_recv(struct netconn *conn, struct netbuf **new_buf) { #if LWIP_TCP struct netbuf *buf = NULL; err_t err; #endif /* LWIP_TCP */ LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;); *new_buf = NULL; LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;); #if LWIP_TCP #if (LWIP_UDP || LWIP_RAW) if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) #endif /* (LWIP_UDP || LWIP_RAW) */ { struct pbuf *p = NULL; /* This is not a listening netconn, since recvmbox is set */ buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); if (buf == NULL) { return ERR_MEM; } err = netconn_recv_data(conn, (void **)&p); if (err != ERR_OK) { memp_free(MEMP_NETBUF, buf); return err; } LWIP_ASSERT("p != NULL", p != NULL); buf->p = p; buf->ptr = p; buf->port = 0; ip_addr_set_zero(&buf->addr); *new_buf = buf; /* don't set conn->last_err: it's only ERR_OK, anyway */ return ERR_OK; } #endif /* LWIP_TCP */ #if LWIP_TCP && (LWIP_UDP || LWIP_RAW) else #endif /* LWIP_TCP && (LWIP_UDP || LWIP_RAW) */ { #if (LWIP_UDP || LWIP_RAW) return netconn_recv_data(conn, (void **)new_buf); #endif /* (LWIP_UDP || LWIP_RAW) */ } } /** * @ingroup netconn_udp * Send data (in form of a netbuf) to a specific remote IP address and port. * Only to be used for UDP and RAW netconns (not TCP). * * @param conn the netconn over which to send data * @param buf a netbuf containing the data to send * @param addr the remote IP address to which to send the data * @param port the remote port to which to send the data * @return ERR_OK if data was sent, any other err_t on error */ err_t netconn_sendto(struct netconn *conn, struct netbuf *buf, const ip_addr_t *addr, u16_t port) { if (buf != NULL) { ip_addr_set(&buf->addr, addr); buf->port = port; return netconn_send(conn, buf); } return ERR_VAL; } /** * @ingroup netconn_udp * Send data over a UDP or RAW netconn (that is already connected). * * @param conn the UDP or RAW netconn over which to send data * @param buf a netbuf containing the data to send * @return ERR_OK if data was sent, any other err_t on error */ err_t netconn_send(struct netconn *conn, struct netbuf *buf) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_send: invalid conn", (conn != NULL), return ERR_ARG;); LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %"U16_F" bytes\n", buf->p->tot_len)); API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.b = buf; err = netconn_apimsg(lwip_netconn_do_send, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_tcp * Send data over a TCP netconn. * * @param conn the TCP netconn over which to send data * @param dataptr pointer to the application buffer that contains the data to send * @param size size of the application data to send * @param apiflags combination of following flags : * - NETCONN_COPY: data will be copied into memory belonging to the stack * - NETCONN_MORE: for TCP connection, PSH flag will be set on last segment sent * - NETCONN_DONTBLOCK: only write the data if all data can be written at once * @param bytes_written pointer to a location that receives the number of written bytes * @return ERR_OK if data was sent, any other err_t on error */ err_t netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size, u8_t apiflags, size_t *bytes_written) { API_MSG_VAR_DECLARE(msg); err_t err; u8_t dontblock; LWIP_ERROR("netconn_write: invalid conn", (conn != NULL), return ERR_ARG;); LWIP_ERROR("netconn_write: invalid conn->type", (NETCONNTYPE_GROUP(conn->type)== NETCONN_TCP), return ERR_VAL;); if (size == 0) { return ERR_OK; } dontblock = netconn_is_nonblocking(conn) || (apiflags & NETCONN_DONTBLOCK); #if LWIP_SO_SNDTIMEO if (conn->send_timeout != 0) { dontblock = 1; } #endif /* LWIP_SO_SNDTIMEO */ if (dontblock && !bytes_written) { /* This implies netconn_write() cannot be used for non-blocking send, since it has no way to return the number of bytes written. */ return ERR_VAL; } API_MSG_VAR_ALLOC(msg); /* non-blocking write sends as much */ API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.w.dataptr = dataptr; API_MSG_VAR_REF(msg).msg.w.apiflags = apiflags; API_MSG_VAR_REF(msg).msg.w.len = size; #if LWIP_SO_SNDTIMEO if (conn->send_timeout != 0) { /* get the time we started, which is later compared to sys_now() + conn->send_timeout */ API_MSG_VAR_REF(msg).msg.w.time_started = sys_now(); } else { API_MSG_VAR_REF(msg).msg.w.time_started = 0; } #endif /* LWIP_SO_SNDTIMEO */ /* For locking the core: this _can_ be delayed on low memory/low send buffer, but if it is, this is done inside api_msg.c:do_write(), so we can use the non-blocking version here. */ err = netconn_apimsg(lwip_netconn_do_write, &API_MSG_VAR_REF(msg)); if ((err == ERR_OK) && (bytes_written != NULL)) { if (dontblock) { /* nonblocking write: maybe the data has been sent partly */ *bytes_written = API_MSG_VAR_REF(msg).msg.w.len; } else { /* blocking call succeeded: all data has been sent if it */ *bytes_written = size; } } API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_tcp * Close or shutdown a TCP netconn (doesn't delete it). * * @param conn the TCP netconn to close or shutdown * @param how fully close or only shutdown one side? * @return ERR_OK if the netconn was closed, any other err_t on error */ static err_t netconn_close_shutdown(struct netconn *conn, u8_t how) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_UNUSED_ARG(how); LWIP_ERROR("netconn_close: invalid conn", (conn != NULL), return ERR_ARG;); API_MSG_VAR_ALLOC(msg); API_MSG_VAR_REF(msg).conn = conn; #if LWIP_TCP /* shutting down both ends is the same as closing */ API_MSG_VAR_REF(msg).msg.sd.shut = how; #if LWIP_SO_SNDTIMEO || LWIP_SO_LINGER /* get the time we started, which is later compared to sys_now() + conn->send_timeout */ API_MSG_VAR_REF(msg).msg.sd.time_started = sys_now(); #else /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ API_MSG_VAR_REF(msg).msg.sd.polls_left = ((LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT + TCP_SLOW_INTERVAL - 1) / TCP_SLOW_INTERVAL) + 1; #endif /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ #endif /* LWIP_TCP */ err = netconn_apimsg(lwip_netconn_do_close, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } /** * @ingroup netconn_tcp * Close a TCP netconn (doesn't delete it). * * @param conn the TCP netconn to close * @return ERR_OK if the netconn was closed, any other err_t on error */ err_t netconn_close(struct netconn *conn) { /* shutting down both ends is the same as closing */ return netconn_close_shutdown(conn, NETCONN_SHUT_RDWR); } /** * @ingroup netconn_tcp * Shut down one or both sides of a TCP netconn (doesn't delete it). * * @param conn the TCP netconn to shut down * @param shut_rx shut down the RX side (no more read possible after this) * @param shut_tx shut down the TX side (no more write possible after this) * @return ERR_OK if the netconn was closed, any other err_t on error */ err_t netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx) { return netconn_close_shutdown(conn, (shut_rx ? NETCONN_SHUT_RD : 0) | (shut_tx ? NETCONN_SHUT_WR : 0)); } #if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) /** * @ingroup netconn_udp * Join multicast groups for UDP netconns. * * @param conn the UDP netconn for which to change multicast addresses * @param multiaddr IP address of the multicast group to join or leave * @param netif_addr the IP address of the network interface on which to send * the igmp message * @param join_or_leave flag whether to send a join- or leave-message * @return ERR_OK if the action was taken, any err_t on error */ err_t netconn_join_leave_group(struct netconn *conn, const ip_addr_t *multiaddr, const ip_addr_t *netif_addr, enum netconn_igmp join_or_leave) { API_MSG_VAR_DECLARE(msg); err_t err; LWIP_ERROR("netconn_join_leave_group: invalid conn", (conn != NULL), return ERR_ARG;); API_MSG_VAR_ALLOC(msg); #if LWIP_IPV4 /* Don't propagate NULL pointer (IP_ADDR_ANY alias) to subsequent functions */ if (multiaddr == NULL) { multiaddr = IP4_ADDR_ANY; } if (netif_addr == NULL) { netif_addr = IP4_ADDR_ANY; } #endif /* LWIP_IPV4 */ API_MSG_VAR_REF(msg).conn = conn; API_MSG_VAR_REF(msg).msg.jl.multiaddr = API_MSG_VAR_REF(multiaddr); API_MSG_VAR_REF(msg).msg.jl.netif_addr = API_MSG_VAR_REF(netif_addr); API_MSG_VAR_REF(msg).msg.jl.join_or_leave = join_or_leave; err = netconn_apimsg(lwip_netconn_do_join_leave_group, &API_MSG_VAR_REF(msg)); API_MSG_VAR_FREE(msg); return err; } #endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ #if LWIP_DNS /** * @ingroup netconn_common * Execute a DNS query, only one IP address is returned * * @param name a string representation of the DNS host name to query * @param addr a preallocated ip_addr_t where to store the resolved IP address * @param dns_addrtype IP address type (IPv4 / IPv6) * @return ERR_OK: resolving succeeded * ERR_MEM: memory error, try again later * ERR_ARG: dns client not initialized or invalid hostname * ERR_VAL: dns server response was invalid */ #if LWIP_IPV4 && LWIP_IPV6 err_t netconn_gethostbyname_addrtype(const char *name, ip_addr_t *addr, u8_t dns_addrtype) #else err_t netconn_gethostbyname(const char *name, ip_addr_t *addr) #endif { API_VAR_DECLARE(struct dns_api_msg, msg); #if !LWIP_MPU_COMPATIBLE sys_sem_t sem; #endif /* LWIP_MPU_COMPATIBLE */ err_t err; err_t cberr; LWIP_ERROR("netconn_gethostbyname: invalid name", (name != NULL), return ERR_ARG;); LWIP_ERROR("netconn_gethostbyname: invalid addr", (addr != NULL), return ERR_ARG;); #if LWIP_MPU_COMPATIBLE if (strlen(name) >= DNS_MAX_NAME_LENGTH) { return ERR_ARG; } #endif API_VAR_ALLOC(struct dns_api_msg, MEMP_DNS_API_MSG, msg, ERR_MEM); #if LWIP_MPU_COMPATIBLE strncpy(API_VAR_REF(msg).name, name, DNS_MAX_NAME_LENGTH-1); API_VAR_REF(msg).name[DNS_MAX_NAME_LENGTH-1] = 0; #else /* LWIP_MPU_COMPATIBLE */ msg.err = &err; msg.sem = &sem; API_VAR_REF(msg).addr = API_VAR_REF(addr); API_VAR_REF(msg).name = name; #endif /* LWIP_MPU_COMPATIBLE */ #if LWIP_IPV4 && LWIP_IPV6 API_VAR_REF(msg).dns_addrtype = dns_addrtype; #endif /* LWIP_IPV4 && LWIP_IPV6 */ #if LWIP_NETCONN_SEM_PER_THREAD API_VAR_REF(msg).sem = LWIP_NETCONN_THREAD_SEM_GET(); #else /* LWIP_NETCONN_SEM_PER_THREAD*/ err = sys_sem_new(API_EXPR_REF(API_VAR_REF(msg).sem), 0); if (err != ERR_OK) { API_VAR_FREE(MEMP_DNS_API_MSG, msg); return err; } #endif /* LWIP_NETCONN_SEM_PER_THREAD */ cberr = tcpip_callback(lwip_netconn_do_gethostbyname, &API_VAR_REF(msg)); if (cberr != ERR_OK) { #if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_free(API_EXPR_REF(API_VAR_REF(msg).sem)); #endif /* !LWIP_NETCONN_SEM_PER_THREAD */ API_VAR_FREE(MEMP_DNS_API_MSG, msg); return cberr; } sys_sem_wait(API_EXPR_REF_SEM(API_VAR_REF(msg).sem)); #if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_free(API_EXPR_REF(API_VAR_REF(msg).sem)); #endif /* !LWIP_NETCONN_SEM_PER_THREAD */ #if LWIP_MPU_COMPATIBLE *addr = msg->addr; err = msg->err; #endif /* LWIP_MPU_COMPATIBLE */ API_VAR_FREE(MEMP_DNS_API_MSG, msg); return err; } #endif /* LWIP_DNS*/ #if LWIP_NETCONN_SEM_PER_THREAD void netconn_thread_init(void) { sys_sem_t *sem = LWIP_NETCONN_THREAD_SEM_GET(); if ((sem == NULL) || !sys_sem_valid(sem)) { /* call alloc only once */ LWIP_NETCONN_THREAD_SEM_ALLOC(); LWIP_ASSERT("LWIP_NETCONN_THREAD_SEM_ALLOC() failed", sys_sem_valid(LWIP_NETCONN_THREAD_SEM_GET())); } } void netconn_thread_cleanup(void) { sys_sem_t *sem = LWIP_NETCONN_THREAD_SEM_GET(); if ((sem != NULL) && sys_sem_valid(sem)) { /* call free only once */ LWIP_NETCONN_THREAD_SEM_FREE(); } } #endif /* LWIP_NETCONN_SEM_PER_THREAD */ #endif /* LWIP_NETCONN */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/api_lib.c
C
unknown
33,032
/** * @file * Sequential API Internal 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> * */ #include "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include "lwip/priv/api_msg.h" #include "lwip/ip.h" #include "lwip/ip_addr.h" #include "lwip/udp.h" #include "lwip/tcp.h" #include "lwip/raw.h" #include "lwip/memp.h" #include "lwip/igmp.h" #include "lwip/dns.h" #include "lwip/mld6.h" #include "lwip/priv/tcpip_priv.h" #include <string.h> /* netconns are polled once per second (e.g. continue write on memory error) */ #define NETCONN_TCP_POLL_INTERVAL 2 #define SET_NONBLOCKING_CONNECT(conn, val) do { if (val) { \ (conn)->flags |= NETCONN_FLAG_IN_NONBLOCKING_CONNECT; \ } else { \ (conn)->flags &= ~ NETCONN_FLAG_IN_NONBLOCKING_CONNECT; }} while(0) #define IN_NONBLOCKING_CONNECT(conn) (((conn)->flags & NETCONN_FLAG_IN_NONBLOCKING_CONNECT) != 0) /* forward declarations */ #if LWIP_TCP #if LWIP_TCPIP_CORE_LOCKING #define WRITE_DELAYED , 1 #define WRITE_DELAYED_PARAM , u8_t delayed #else /* LWIP_TCPIP_CORE_LOCKING */ #define WRITE_DELAYED #define WRITE_DELAYED_PARAM #endif /* LWIP_TCPIP_CORE_LOCKING */ static err_t lwip_netconn_do_writemore(struct netconn *conn WRITE_DELAYED_PARAM); static err_t lwip_netconn_do_close_internal(struct netconn *conn WRITE_DELAYED_PARAM); #endif #if LWIP_TCPIP_CORE_LOCKING #define TCPIP_APIMSG_ACK(m) NETCONN_SET_SAFE_ERR((m)->conn, (m)->err) #else /* LWIP_TCPIP_CORE_LOCKING */ #define TCPIP_APIMSG_ACK(m) do { NETCONN_SET_SAFE_ERR((m)->conn, (m)->err); sys_sem_signal(LWIP_API_MSG_SEM(m)); } while(0) #endif /* LWIP_TCPIP_CORE_LOCKING */ #if LWIP_TCP u8_t netconn_aborted; #endif /* LWIP_TCP */ #if LWIP_RAW /** * Receive callback function for RAW netconns. * Doesn't 'eat' the packet, only copies it and sends it to * conn->recvmbox * * @see raw.h (struct raw_pcb.recv) for parameters and return value */ static u8_t recv_raw(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr) { struct pbuf *q; struct netbuf *buf; struct netconn *conn; LWIP_UNUSED_ARG(addr); conn = (struct netconn *)arg; if ((conn != NULL) && sys_mbox_valid(&conn->recvmbox)) { #if LWIP_SO_RCVBUF int recv_avail; SYS_ARCH_GET(conn->recv_avail, recv_avail); if ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize) { return 0; } #endif /* LWIP_SO_RCVBUF */ /* copy the whole packet into new pbufs */ q = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); if (q != NULL) { if (pbuf_copy(q, p) != ERR_OK) { pbuf_free(q); q = NULL; } } if (q != NULL) { u16_t len; buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); if (buf == NULL) { pbuf_free(q); return 0; } buf->p = q; buf->ptr = q; ip_addr_copy(buf->addr, *ip_current_src_addr()); buf->port = pcb->protocol; len = q->tot_len; if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) { netbuf_delete(buf); return 0; } else { #if LWIP_SO_RCVBUF SYS_ARCH_INC(conn->recv_avail, len); #endif /* LWIP_SO_RCVBUF */ /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); } } } return 0; /* do not eat the packet */ } #endif /* LWIP_RAW*/ #if LWIP_UDP /** * Receive callback function for UDP netconns. * Posts the packet to conn->recvmbox or deletes it on memory error. * * @see udp.h (struct udp_pcb.recv) for parameters */ static void recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) { struct netbuf *buf; struct netconn *conn; u16_t len; #if LWIP_SO_RCVBUF int recv_avail; #endif /* LWIP_SO_RCVBUF */ LWIP_UNUSED_ARG(pcb); /* only used for asserts... */ LWIP_ASSERT("recv_udp must have a pcb argument", pcb != NULL); LWIP_ASSERT("recv_udp must have an argument", arg != NULL); conn = (struct netconn *)arg; if (conn == NULL) { pbuf_free(p); return; } LWIP_ASSERT("recv_udp: recv for wrong pcb!", conn->pcb.udp == pcb); #if LWIP_SO_RCVBUF SYS_ARCH_GET(conn->recv_avail, recv_avail); if (!sys_mbox_valid(&conn->recvmbox) || ((recv_avail + (int)(p->tot_len)) > conn->recv_bufsize)) { #else /* LWIP_SO_RCVBUF */ if (!sys_mbox_valid(&conn->recvmbox)) { #endif /* LWIP_SO_RCVBUF */ pbuf_free(p); return; } buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); if (buf == NULL) { pbuf_free(p); return; } else { buf->p = p; buf->ptr = p; ip_addr_set(&buf->addr, addr); buf->port = port; #if LWIP_NETBUF_RECVINFO { /* get the UDP header - always in the first pbuf, ensured by udp_input */ const struct udp_hdr* udphdr = (const struct udp_hdr*)ip_next_header_ptr(); #if LWIP_CHECKSUM_ON_COPY buf->flags = NETBUF_FLAG_DESTADDR; #endif /* LWIP_CHECKSUM_ON_COPY */ ip_addr_set(&buf->toaddr, ip_current_dest_addr()); buf->toport_chksum = udphdr->dest; } #endif /* LWIP_NETBUF_RECVINFO */ } len = p->tot_len; if (sys_mbox_trypost(&conn->recvmbox, buf) != ERR_OK) { netbuf_delete(buf); return; } else { #if LWIP_SO_RCVBUF SYS_ARCH_INC(conn->recv_avail, len); #endif /* LWIP_SO_RCVBUF */ /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); } } #endif /* LWIP_UDP */ #if LWIP_TCP /** * Receive callback function for TCP netconns. * Posts the packet to conn->recvmbox, but doesn't delete it on errors. * * @see tcp.h (struct tcp_pcb.recv) for parameters and return value */ static err_t recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { struct netconn *conn; u16_t len; LWIP_UNUSED_ARG(pcb); LWIP_ASSERT("recv_tcp must have a pcb argument", pcb != NULL); LWIP_ASSERT("recv_tcp must have an argument", arg != NULL); conn = (struct netconn *)arg; if (conn == NULL) { return ERR_VAL; } LWIP_ASSERT("recv_tcp: recv for wrong pcb!", conn->pcb.tcp == pcb); if (!sys_mbox_valid(&conn->recvmbox)) { /* recvmbox already deleted */ if (p != NULL) { tcp_recved(pcb, p->tot_len); pbuf_free(p); } return ERR_OK; } /* Unlike for UDP or RAW pcbs, don't check for available space using recv_avail since that could break the connection (data is already ACKed) */ /* don't overwrite fatal errors! */ if (err != ERR_OK) { NETCONN_SET_SAFE_ERR(conn, err); } if (p != NULL) { len = p->tot_len; } else { len = 0; } if (sys_mbox_trypost(&conn->recvmbox, p) != ERR_OK) { /* don't deallocate p: it is presented to us later again from tcp_fasttmr! */ return ERR_MEM; } else { #if LWIP_SO_RCVBUF SYS_ARCH_INC(conn->recv_avail, len); #endif /* LWIP_SO_RCVBUF */ /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, len); } return ERR_OK; } /** * Poll callback function for TCP netconns. * Wakes up an application thread that waits for a connection to close * or data to be sent. The application thread then takes the * appropriate action to go on. * * Signals the conn->sem. * netconn_close waits for conn->sem if closing failed. * * @see tcp.h (struct tcp_pcb.poll) for parameters and return value */ static err_t poll_tcp(void *arg, struct tcp_pcb *pcb) { struct netconn *conn = (struct netconn *)arg; LWIP_UNUSED_ARG(pcb); LWIP_ASSERT("conn != NULL", (conn != NULL)); if (conn->state == NETCONN_WRITE) { lwip_netconn_do_writemore(conn WRITE_DELAYED); } else if (conn->state == NETCONN_CLOSE) { #if !LWIP_SO_SNDTIMEO && !LWIP_SO_LINGER if (conn->current_msg && conn->current_msg->msg.sd.polls_left) { conn->current_msg->msg.sd.polls_left--; } #endif /* !LWIP_SO_SNDTIMEO && !LWIP_SO_LINGER */ lwip_netconn_do_close_internal(conn WRITE_DELAYED); } /* @todo: implement connect timeout here? */ /* Did a nonblocking write fail before? Then check available write-space. */ if (conn->flags & NETCONN_FLAG_CHECK_WRITESPACE) { /* If the queued byte- or pbuf-count drops below the configured low-water limit, let select mark this pcb as writable again. */ if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) && (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) { conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE; API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); } } return ERR_OK; } /** * Sent callback function for TCP netconns. * Signals the conn->sem and calls API_EVENT. * netconn_write waits for conn->sem if send buffer is low. * * @see tcp.h (struct tcp_pcb.sent) for parameters and return value */ static err_t sent_tcp(void *arg, struct tcp_pcb *pcb, u16_t len) { struct netconn *conn = (struct netconn *)arg; LWIP_UNUSED_ARG(pcb); LWIP_ASSERT("conn != NULL", (conn != NULL)); if (conn) { if (conn->state == NETCONN_WRITE) { lwip_netconn_do_writemore(conn WRITE_DELAYED); } else if (conn->state == NETCONN_CLOSE) { lwip_netconn_do_close_internal(conn WRITE_DELAYED); } /* If the queued byte- or pbuf-count drops below the configured low-water limit, let select mark this pcb as writable again. */ if ((conn->pcb.tcp != NULL) && (tcp_sndbuf(conn->pcb.tcp) > TCP_SNDLOWAT) && (tcp_sndqueuelen(conn->pcb.tcp) < TCP_SNDQUEUELOWAT)) { conn->flags &= ~NETCONN_FLAG_CHECK_WRITESPACE; API_EVENT(conn, NETCONN_EVT_SENDPLUS, len); } } return ERR_OK; } /** * Error callback function for TCP netconns. * Signals conn->sem, posts to all conn mboxes and calls API_EVENT. * The application thread has then to decide what to do. * * @see tcp.h (struct tcp_pcb.err) for parameters */ static void err_tcp(void *arg, err_t err) { struct netconn *conn; enum netconn_state old_state; conn = (struct netconn *)arg; LWIP_ASSERT("conn != NULL", (conn != NULL)); conn->pcb.tcp = NULL; /* reset conn->state now before waking up other threads */ old_state = conn->state; conn->state = NETCONN_NONE; if (old_state == NETCONN_CLOSE) { /* RST during close: let close return success & dealloc the netconn */ err = ERR_OK; NETCONN_SET_SAFE_ERR(conn, ERR_OK); } else { /* no check since this is always fatal! */ SYS_ARCH_SET(conn->last_err, err); } /* @todo: the type of NETCONN_EVT created should depend on 'old_state' */ /* Notify the user layer about a connection error. Used to signal select. */ API_EVENT(conn, NETCONN_EVT_ERROR, 0); /* Try to release selects pending on 'read' or 'write', too. They will get an error if they actually try to read or write. */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); /* pass NULL-message to recvmbox to wake up pending recv */ if (sys_mbox_valid(&conn->recvmbox)) { /* use trypost to prevent deadlock */ sys_mbox_trypost(&conn->recvmbox, NULL); } /* pass NULL-message to acceptmbox to wake up pending accept */ if (sys_mbox_valid(&conn->acceptmbox)) { /* use trypost to preven deadlock */ sys_mbox_trypost(&conn->acceptmbox, NULL); } if ((old_state == NETCONN_WRITE) || (old_state == NETCONN_CLOSE) || (old_state == NETCONN_CONNECT)) { /* calling lwip_netconn_do_writemore/lwip_netconn_do_close_internal is not necessary since the pcb has already been deleted! */ int was_nonblocking_connect = IN_NONBLOCKING_CONNECT(conn); SET_NONBLOCKING_CONNECT(conn, 0); if (!was_nonblocking_connect) { sys_sem_t* op_completed_sem; /* set error return code */ LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); conn->current_msg->err = err; op_completed_sem = LWIP_API_MSG_SEM(conn->current_msg); LWIP_ASSERT("inavlid op_completed_sem", sys_sem_valid(op_completed_sem)); conn->current_msg = NULL; /* wake up the waiting task */ NETCONN_SET_SAFE_ERR(conn, err); sys_sem_signal(op_completed_sem); } } else { LWIP_ASSERT("conn->current_msg == NULL", conn->current_msg == NULL); } } /** * Setup a tcp_pcb with the correct callback function pointers * and their arguments. * * @param conn the TCP netconn to setup */ static void setup_tcp(struct netconn *conn) { struct tcp_pcb *pcb; pcb = conn->pcb.tcp; tcp_arg(pcb, conn); tcp_recv(pcb, recv_tcp); tcp_sent(pcb, sent_tcp); tcp_poll(pcb, poll_tcp, NETCONN_TCP_POLL_INTERVAL); tcp_err(pcb, err_tcp); } /** * Accept callback function for TCP netconns. * Allocates a new netconn and posts that to conn->acceptmbox. * * @see tcp.h (struct tcp_pcb_listen.accept) for parameters and return value */ static err_t accept_function(void *arg, struct tcp_pcb *newpcb, err_t err) { struct netconn *newconn; struct netconn *conn = (struct netconn *)arg; if (conn == NULL) { return ERR_VAL; } if (!sys_mbox_valid(&conn->acceptmbox)) { LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: acceptmbox already deleted\n")); return ERR_VAL; } if (newpcb == NULL) { /* out-of-pcbs during connect: pass on this error to the application */ if (sys_mbox_trypost(&conn->acceptmbox, &netconn_aborted) == ERR_OK) { /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); } return ERR_VAL; } LWIP_DEBUGF(API_MSG_DEBUG, ("accept_function: newpcb->tate: %s\n", tcp_debug_state_str(newpcb->state))); /* We have to set the callback here even though * the new socket is unknown. newconn->socket is marked as -1. */ newconn = netconn_alloc(conn->type, conn->callback); if (newconn == NULL) { /* outof netconns: pass on this error to the application */ if (sys_mbox_trypost(&conn->acceptmbox, &netconn_aborted) == ERR_OK) { /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); } return ERR_MEM; } newconn->pcb.tcp = newpcb; setup_tcp(newconn); /* no protection: when creating the pcb, the netconn is not yet known to the application thread */ newconn->last_err = err; /* handle backlog counter */ tcp_backlog_delayed(newpcb); if (sys_mbox_trypost(&conn->acceptmbox, newconn) != ERR_OK) { /* When returning != ERR_OK, the pcb is aborted in tcp_process(), so do nothing here! */ /* remove all references to this netconn from the pcb */ struct tcp_pcb* pcb = newconn->pcb.tcp; tcp_arg(pcb, NULL); tcp_recv(pcb, NULL); tcp_sent(pcb, NULL); tcp_poll(pcb, NULL, 0); tcp_err(pcb, NULL); /* remove reference from to the pcb from this netconn */ newconn->pcb.tcp = NULL; /* no need to drain since we know the recvmbox is empty. */ sys_mbox_free(&newconn->recvmbox); sys_mbox_set_invalid(&newconn->recvmbox); netconn_free(newconn); return ERR_MEM; } else { /* Register event with callback */ API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); } return ERR_OK; } #endif /* LWIP_TCP */ /** * Create a new pcb of a specific type. * Called from lwip_netconn_do_newconn(). * * @param msg the api_msg_msg describing the connection type */ static void pcb_new(struct api_msg *msg) { enum lwip_ip_addr_type iptype = IPADDR_TYPE_V4; LWIP_ASSERT("pcb_new: pcb already allocated", msg->conn->pcb.tcp == NULL); #if LWIP_IPV6 && LWIP_IPV4 /* IPv6: Dual-stack by default, unless netconn_set_ipv6only() is called */ if(NETCONNTYPE_ISIPV6(netconn_type(msg->conn))) { iptype = IPADDR_TYPE_ANY; } #endif /* Allocate a PCB for this connection */ switch(NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: msg->conn->pcb.raw = raw_new_ip_type(iptype, msg->msg.n.proto); if (msg->conn->pcb.raw != NULL) { #if LWIP_IPV6 /* ICMPv6 packets should always have checksum calculated by the stack as per RFC 3542 chapter 3.1 */ if (NETCONNTYPE_ISIPV6(msg->conn->type) && msg->conn->pcb.raw->protocol == IP6_NEXTH_ICMP6) { msg->conn->pcb.raw->chksum_reqd = 1; msg->conn->pcb.raw->chksum_offset = 2; } #endif /* LWIP_IPV6 */ raw_recv(msg->conn->pcb.raw, recv_raw, msg->conn); } break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: msg->conn->pcb.udp = udp_new_ip_type(iptype); if (msg->conn->pcb.udp != NULL) { #if LWIP_UDPLITE if (NETCONNTYPE_ISUDPLITE(msg->conn->type)) { udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE); } #endif /* LWIP_UDPLITE */ if (NETCONNTYPE_ISUDPNOCHKSUM(msg->conn->type)) { udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM); } udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); } break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: msg->conn->pcb.tcp = tcp_new_ip_type(iptype); if (msg->conn->pcb.tcp != NULL) { setup_tcp(msg->conn); } break; #endif /* LWIP_TCP */ default: /* Unsupported netconn type, e.g. protocol disabled */ msg->err = ERR_VAL; return; } if (msg->conn->pcb.ip == NULL) { msg->err = ERR_MEM; } } /** * Create a new pcb of a specific type inside a netconn. * Called from netconn_new_with_proto_and_callback. * * @param m the api_msg_msg describing the connection type */ void lwip_netconn_do_newconn(void *m) { struct api_msg *msg = (struct api_msg*)m; msg->err = ERR_OK; if (msg->conn->pcb.tcp == NULL) { pcb_new(msg); } /* Else? This "new" connection already has a PCB allocated. */ /* Is this an error condition? Should it be deleted? */ /* We currently just are happy and return. */ TCPIP_APIMSG_ACK(msg); } /** * Create a new netconn (of a specific type) that has a callback function. * The corresponding pcb is NOT created! * * @param t the type of 'connection' to create (@see enum netconn_type) * @param callback a function to call on status changes (RX available, TX'ed) * @return a newly allocated struct netconn or * NULL on memory error */ struct netconn* netconn_alloc(enum netconn_type t, netconn_callback callback) { struct netconn *conn; int size; conn = (struct netconn *)memp_malloc(MEMP_NETCONN); if (conn == NULL) { return NULL; } conn->last_err = ERR_OK; conn->type = t; conn->pcb.tcp = NULL; /* If all sizes are the same, every compiler should optimize this switch to nothing */ switch(NETCONNTYPE_GROUP(t)) { #if LWIP_RAW case NETCONN_RAW: size = DEFAULT_RAW_RECVMBOX_SIZE; break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: size = DEFAULT_UDP_RECVMBOX_SIZE; break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: size = DEFAULT_TCP_RECVMBOX_SIZE; break; #endif /* LWIP_TCP */ default: LWIP_ASSERT("netconn_alloc: undefined netconn_type", 0); goto free_and_return; } if (sys_mbox_new(&conn->recvmbox, size) != ERR_OK) { goto free_and_return; } #if !LWIP_NETCONN_SEM_PER_THREAD if (sys_sem_new(&conn->op_completed, 0) != ERR_OK) { sys_mbox_free(&conn->recvmbox); goto free_and_return; } #endif #if LWIP_TCP sys_mbox_set_invalid(&conn->acceptmbox); #endif conn->state = NETCONN_NONE; #if LWIP_SOCKET /* initialize socket to -1 since 0 is a valid socket */ conn->socket = -1; #endif /* LWIP_SOCKET */ conn->callback = callback; #if LWIP_TCP conn->current_msg = NULL; conn->write_offset = 0; #endif /* LWIP_TCP */ #if LWIP_SO_SNDTIMEO conn->send_timeout = 0; #endif /* LWIP_SO_SNDTIMEO */ #if LWIP_SO_RCVTIMEO conn->recv_timeout = 0; #endif /* LWIP_SO_RCVTIMEO */ #if LWIP_SO_RCVBUF conn->recv_bufsize = RECV_BUFSIZE_DEFAULT; conn->recv_avail = 0; #endif /* LWIP_SO_RCVBUF */ #if LWIP_SO_LINGER conn->linger = -1; #endif /* LWIP_SO_LINGER */ conn->flags = 0; return conn; free_and_return: memp_free(MEMP_NETCONN, conn); return NULL; } /** * Delete a netconn and all its resources. * The pcb is NOT freed (since we might not be in the right thread context do this). * * @param conn the netconn to free */ void netconn_free(struct netconn *conn) { LWIP_ASSERT("PCB must be deallocated outside this function", conn->pcb.tcp == NULL); LWIP_ASSERT("recvmbox must be deallocated before calling this function", !sys_mbox_valid(&conn->recvmbox)); #if LWIP_TCP LWIP_ASSERT("acceptmbox must be deallocated before calling this function", !sys_mbox_valid(&conn->acceptmbox)); #endif /* LWIP_TCP */ #if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_free(&conn->op_completed); sys_sem_set_invalid(&conn->op_completed); #endif memp_free(MEMP_NETCONN, conn); } /** * Delete rcvmbox and acceptmbox of a netconn and free the left-over data in * these mboxes * * @param conn the netconn to free * @bytes_drained bytes drained from recvmbox * @accepts_drained pending connections drained from acceptmbox */ static void netconn_drain(struct netconn *conn) { void *mem; #if LWIP_TCP struct pbuf *p; #endif /* LWIP_TCP */ /* This runs in tcpip_thread, so we don't need to lock against rx packets */ /* Delete and drain the recvmbox. */ if (sys_mbox_valid(&conn->recvmbox)) { while (sys_mbox_tryfetch(&conn->recvmbox, &mem) != SYS_MBOX_EMPTY) { #if LWIP_TCP if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) { if (mem != NULL) { p = (struct pbuf*)mem; /* pcb might be set to NULL already by err_tcp() */ if (conn->pcb.tcp != NULL) { tcp_recved(conn->pcb.tcp, p->tot_len); } pbuf_free(p); } } else #endif /* LWIP_TCP */ { netbuf_delete((struct netbuf *)mem); } } sys_mbox_free(&conn->recvmbox); sys_mbox_set_invalid(&conn->recvmbox); } /* Delete and drain the acceptmbox. */ #if LWIP_TCP if (sys_mbox_valid(&conn->acceptmbox)) { while (sys_mbox_tryfetch(&conn->acceptmbox, &mem) != SYS_MBOX_EMPTY) { if (mem != &netconn_aborted) { struct netconn *newconn = (struct netconn *)mem; /* Only tcp pcbs have an acceptmbox, so no need to check conn->type */ /* pcb might be set to NULL already by err_tcp() */ /* drain recvmbox */ netconn_drain(newconn); if (newconn->pcb.tcp != NULL) { tcp_abort(newconn->pcb.tcp); newconn->pcb.tcp = NULL; } netconn_free(newconn); } } sys_mbox_free(&conn->acceptmbox); sys_mbox_set_invalid(&conn->acceptmbox); } #endif /* LWIP_TCP */ } #if LWIP_TCP /** * Internal helper function to close a TCP netconn: since this sometimes * doesn't work at the first attempt, this function is called from multiple * places. * * @param conn the TCP netconn to close */ static err_t lwip_netconn_do_close_internal(struct netconn *conn WRITE_DELAYED_PARAM) { err_t err; u8_t shut, shut_rx, shut_tx, close; u8_t close_finished = 0; struct tcp_pcb* tpcb; #if LWIP_SO_LINGER u8_t linger_wait_required = 0; #endif /* LWIP_SO_LINGER */ LWIP_ASSERT("invalid conn", (conn != NULL)); LWIP_ASSERT("this is for tcp netconns only", (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP)); LWIP_ASSERT("conn must be in state NETCONN_CLOSE", (conn->state == NETCONN_CLOSE)); LWIP_ASSERT("pcb already closed", (conn->pcb.tcp != NULL)); LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); tpcb = conn->pcb.tcp; shut = conn->current_msg->msg.sd.shut; shut_rx = shut & NETCONN_SHUT_RD; shut_tx = shut & NETCONN_SHUT_WR; /* shutting down both ends is the same as closing (also if RD or WR side was shut down before already) */ if (shut == NETCONN_SHUT_RDWR) { close = 1; } else if (shut_rx && ((tpcb->state == FIN_WAIT_1) || (tpcb->state == FIN_WAIT_2) || (tpcb->state == CLOSING))) { close = 1; } else if (shut_tx && ((tpcb->flags & TF_RXCLOSED) != 0)) { close = 1; } else { close = 0; } /* Set back some callback pointers */ if (close) { tcp_arg(tpcb, NULL); } if (tpcb->state == LISTEN) { tcp_accept(tpcb, NULL); } else { /* some callbacks have to be reset if tcp_close is not successful */ if (shut_rx) { tcp_recv(tpcb, NULL); tcp_accept(tpcb, NULL); } if (shut_tx) { tcp_sent(tpcb, NULL); } if (close) { tcp_poll(tpcb, NULL, 0); tcp_err(tpcb, NULL); } } /* Try to close the connection */ if (close) { #if LWIP_SO_LINGER /* check linger possibilites before calling tcp_close */ err = ERR_OK; /* linger enabled/required at all? (i.e. is there untransmitted data left?) */ if ((conn->linger >= 0) && (conn->pcb.tcp->unsent || conn->pcb.tcp->unacked)) { if ((conn->linger == 0)) { /* data left but linger prevents waiting */ tcp_abort(tpcb); tpcb = NULL; } else if (conn->linger > 0) { /* data left and linger says we should wait */ if (netconn_is_nonblocking(conn)) { /* data left on a nonblocking netconn -> cannot linger */ err = ERR_WOULDBLOCK; } else if ((s32_t)(sys_now() - conn->current_msg->msg.sd.time_started) >= (conn->linger * 1000)) { /* data left but linger timeout has expired (this happens on further calls to this function through poll_tcp */ tcp_abort(tpcb); tpcb = NULL; } else { /* data left -> need to wait for ACK after successful close */ linger_wait_required = 1; } } } if ((err == ERR_OK) && (tpcb != NULL)) #endif /* LWIP_SO_LINGER */ { err = tcp_close(tpcb); } } else { err = tcp_shutdown(tpcb, shut_rx, shut_tx); } if (err == ERR_OK) { close_finished = 1; #if LWIP_SO_LINGER if (linger_wait_required) { /* wait for ACK of all unsent/unacked data by just getting called again */ close_finished = 0; err = ERR_INPROGRESS; } #endif /* LWIP_SO_LINGER */ } else { if (err == ERR_MEM) { /* Closing failed because of memory shortage, try again later. Even for nonblocking netconns, we have to wait since no standard socket application is prepared for close failing because of resource shortage. Check the timeout: this is kind of an lwip addition to the standard sockets: we wait for some time when failing to allocate a segment for the FIN */ #if LWIP_SO_SNDTIMEO || LWIP_SO_LINGER s32_t close_timeout = LWIP_TCP_CLOSE_TIMEOUT_MS_DEFAULT; #if LWIP_SO_SNDTIMEO if (conn->send_timeout > 0) { close_timeout = conn->send_timeout; } #endif /* LWIP_SO_SNDTIMEO */ #if LWIP_SO_LINGER if (conn->linger >= 0) { /* use linger timeout (seconds) */ close_timeout = conn->linger * 1000U; } #endif if ((s32_t)(sys_now() - conn->current_msg->msg.sd.time_started) >= close_timeout) { #else /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ if (conn->current_msg->msg.sd.polls_left == 0) { #endif /* LWIP_SO_SNDTIMEO || LWIP_SO_LINGER */ close_finished = 1; if (close) { /* in this case, we want to RST the connection */ tcp_abort(tpcb); err = ERR_OK; } } } else { /* Closing failed for a non-memory error: give up */ close_finished = 1; } } if (close_finished) { /* Closing done (succeeded, non-memory error, nonblocking error or timeout) */ sys_sem_t* op_completed_sem = LWIP_API_MSG_SEM(conn->current_msg); conn->current_msg->err = err; conn->current_msg = NULL; conn->state = NETCONN_NONE; if (err == ERR_OK) { if (close) { /* Set back some callback pointers as conn is going away */ conn->pcb.tcp = NULL; /* Trigger select() in socket layer. Make sure everybody notices activity on the connection, error first! */ API_EVENT(conn, NETCONN_EVT_ERROR, 0); } if (shut_rx) { API_EVENT(conn, NETCONN_EVT_RCVPLUS, 0); } if (shut_tx) { API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); } } NETCONN_SET_SAFE_ERR(conn, err); #if LWIP_TCPIP_CORE_LOCKING if (delayed) #endif { /* wake up the application task */ sys_sem_signal(op_completed_sem); } return ERR_OK; } if (!close_finished) { /* Closing failed and we want to wait: restore some of the callbacks */ /* Closing of listen pcb will never fail! */ LWIP_ASSERT("Closing a listen pcb may not fail!", (tpcb->state != LISTEN)); if (shut_tx) { tcp_sent(tpcb, sent_tcp); } /* when waiting for close, set up poll interval to 500ms */ tcp_poll(tpcb, poll_tcp, 1); tcp_err(tpcb, err_tcp); tcp_arg(tpcb, conn); /* don't restore recv callback: we don't want to receive any more data */ } /* If closing didn't succeed, we get called again either from poll_tcp or from sent_tcp */ LWIP_ASSERT("err != ERR_OK", err != ERR_OK); return err; } #endif /* LWIP_TCP */ /** * Delete the pcb inside a netconn. * Called from netconn_delete. * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_delconn(void *m) { struct api_msg *msg = (struct api_msg*)m; enum netconn_state state = msg->conn->state; LWIP_ASSERT("netconn state error", /* this only happens for TCP netconns */ (state == NETCONN_NONE) || (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP)); #if LWIP_NETCONN_FULLDUPLEX /* In full duplex mode, blocking write/connect is aborted with ERR_CLSD */ if (state != NETCONN_NONE) { if ((state == NETCONN_WRITE) || ((state == NETCONN_CONNECT) && !IN_NONBLOCKING_CONNECT(msg->conn))) { /* close requested, abort running write/connect */ sys_sem_t* op_completed_sem; LWIP_ASSERT("msg->conn->current_msg != NULL", msg->conn->current_msg != NULL); op_completed_sem = LWIP_API_MSG_SEM(msg->conn->current_msg); msg->conn->current_msg->err = ERR_CLSD; msg->conn->current_msg = NULL; msg->conn->write_offset = 0; msg->conn->state = NETCONN_NONE; NETCONN_SET_SAFE_ERR(msg->conn, ERR_CLSD); sys_sem_signal(op_completed_sem); } } #else /* LWIP_NETCONN_FULLDUPLEX */ if (((state != NETCONN_NONE) && (state != NETCONN_LISTEN) && (state != NETCONN_CONNECT)) || ((state == NETCONN_CONNECT) && !IN_NONBLOCKING_CONNECT(msg->conn))) { /* This means either a blocking write or blocking connect is running (nonblocking write returns and sets state to NONE) */ msg->err = ERR_INPROGRESS; } else #endif /* LWIP_NETCONN_FULLDUPLEX */ { LWIP_ASSERT("blocking connect in progress", (state != NETCONN_CONNECT) || IN_NONBLOCKING_CONNECT(msg->conn)); msg->err = ERR_OK; /* Drain and delete mboxes */ netconn_drain(msg->conn); if (msg->conn->pcb.tcp != NULL) { switch (NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: raw_remove(msg->conn->pcb.raw); break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: msg->conn->pcb.udp->recv_arg = NULL; udp_remove(msg->conn->pcb.udp); break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && msg->conn->write_offset == 0); msg->conn->state = NETCONN_CLOSE; msg->msg.sd.shut = NETCONN_SHUT_RDWR; msg->conn->current_msg = msg; #if LWIP_TCPIP_CORE_LOCKING if (lwip_netconn_do_close_internal(msg->conn, 0) != ERR_OK) { LWIP_ASSERT("state!", msg->conn->state == NETCONN_CLOSE); UNLOCK_TCPIP_CORE(); sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); LOCK_TCPIP_CORE(); LWIP_ASSERT("state!", msg->conn->state == NETCONN_NONE); } #else /* LWIP_TCPIP_CORE_LOCKING */ lwip_netconn_do_close_internal(msg->conn); #endif /* LWIP_TCPIP_CORE_LOCKING */ /* API_EVENT is called inside lwip_netconn_do_close_internal, before releasing the application thread, so we can return at this point! */ return; #endif /* LWIP_TCP */ default: break; } msg->conn->pcb.tcp = NULL; } /* tcp netconns don't come here! */ /* @todo: this lets select make the socket readable and writable, which is wrong! errfd instead? */ API_EVENT(msg->conn, NETCONN_EVT_RCVPLUS, 0); API_EVENT(msg->conn, NETCONN_EVT_SENDPLUS, 0); } if (sys_sem_valid(LWIP_API_MSG_SEM(msg))) { TCPIP_APIMSG_ACK(msg); } } /** * Bind a pcb contained in a netconn * Called from netconn_bind. * * @param m the api_msg_msg pointing to the connection and containing * the IP address and port to bind to */ void lwip_netconn_do_bind(void *m) { struct api_msg *msg = (struct api_msg*)m; if (ERR_IS_FATAL(msg->conn->last_err)) { msg->err = msg->conn->last_err; } else { msg->err = ERR_VAL; if (msg->conn->pcb.tcp != NULL) { switch (NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: msg->err = raw_bind(msg->conn->pcb.raw, API_EXPR_REF(msg->msg.bc.ipaddr)); break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: msg->err = udp_bind(msg->conn->pcb.udp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port); break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: msg->err = tcp_bind(msg->conn->pcb.tcp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port); break; #endif /* LWIP_TCP */ default: break; } } } TCPIP_APIMSG_ACK(msg); } #if LWIP_TCP /** * TCP callback function if a connection (opened by tcp_connect/lwip_netconn_do_connect) has * been established (or reset by the remote host). * * @see tcp.h (struct tcp_pcb.connected) for parameters and return values */ static err_t lwip_netconn_do_connected(void *arg, struct tcp_pcb *pcb, err_t err) { struct netconn *conn; int was_blocking; sys_sem_t* op_completed_sem = NULL; LWIP_UNUSED_ARG(pcb); conn = (struct netconn *)arg; if (conn == NULL) { return ERR_VAL; } LWIP_ASSERT("conn->state == NETCONN_CONNECT", conn->state == NETCONN_CONNECT); LWIP_ASSERT("(conn->current_msg != NULL) || conn->in_non_blocking_connect", (conn->current_msg != NULL) || IN_NONBLOCKING_CONNECT(conn)); if (conn->current_msg != NULL) { conn->current_msg->err = err; op_completed_sem = LWIP_API_MSG_SEM(conn->current_msg); } if ((NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) && (err == ERR_OK)) { setup_tcp(conn); } was_blocking = !IN_NONBLOCKING_CONNECT(conn); SET_NONBLOCKING_CONNECT(conn, 0); LWIP_ASSERT("blocking connect state error", (was_blocking && op_completed_sem != NULL) || (!was_blocking && op_completed_sem == NULL)); conn->current_msg = NULL; conn->state = NETCONN_NONE; NETCONN_SET_SAFE_ERR(conn, ERR_OK); API_EVENT(conn, NETCONN_EVT_SENDPLUS, 0); if (was_blocking) { sys_sem_signal(op_completed_sem); } return ERR_OK; } #endif /* LWIP_TCP */ /** * Connect a pcb contained inside a netconn * Called from netconn_connect. * * @param m the api_msg_msg pointing to the connection and containing * the IP address and port to connect to */ void lwip_netconn_do_connect(void *m) { struct api_msg *msg = (struct api_msg*)m; if (msg->conn->pcb.tcp == NULL) { /* This may happen when calling netconn_connect() a second time */ msg->err = ERR_CLSD; } else { switch (NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: msg->err = raw_connect(msg->conn->pcb.raw, API_EXPR_REF(msg->msg.bc.ipaddr)); break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: msg->err = udp_connect(msg->conn->pcb.udp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port); break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: /* Prevent connect while doing any other action. */ if (msg->conn->state == NETCONN_CONNECT) { msg->err = ERR_ALREADY; } else if (msg->conn->state != NETCONN_NONE) { msg->err = ERR_ISCONN; } else { setup_tcp(msg->conn); msg->err = tcp_connect(msg->conn->pcb.tcp, API_EXPR_REF(msg->msg.bc.ipaddr), msg->msg.bc.port, lwip_netconn_do_connected); if (msg->err == ERR_OK) { u8_t non_blocking = netconn_is_nonblocking(msg->conn); msg->conn->state = NETCONN_CONNECT; SET_NONBLOCKING_CONNECT(msg->conn, non_blocking); if (non_blocking) { msg->err = ERR_INPROGRESS; } else { msg->conn->current_msg = msg; /* sys_sem_signal() is called from lwip_netconn_do_connected (or err_tcp()), when the connection is established! */ #if LWIP_TCPIP_CORE_LOCKING LWIP_ASSERT("state!", msg->conn->state == NETCONN_CONNECT); UNLOCK_TCPIP_CORE(); sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); LOCK_TCPIP_CORE(); LWIP_ASSERT("state!", msg->conn->state != NETCONN_CONNECT); #endif /* LWIP_TCPIP_CORE_LOCKING */ return; } } } break; #endif /* LWIP_TCP */ default: LWIP_ERROR("Invalid netconn type", 0, do{ msg->err = ERR_VAL; }while(0)); break; } } /* For all other protocols, netconn_connect() calls TCPIP_APIMSG(), so use TCPIP_APIMSG_ACK() here. */ TCPIP_APIMSG_ACK(msg); } /** * Disconnect a pcb contained inside a netconn * Only used for UDP netconns. * Called from netconn_disconnect. * * @param m the api_msg_msg pointing to the connection to disconnect */ void lwip_netconn_do_disconnect(void *m) { struct api_msg *msg = (struct api_msg*)m; #if LWIP_UDP if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) { udp_disconnect(msg->conn->pcb.udp); msg->err = ERR_OK; } else #endif /* LWIP_UDP */ { msg->err = ERR_VAL; } TCPIP_APIMSG_ACK(msg); } #if LWIP_TCP /** * Set a TCP pcb contained in a netconn into listen mode * Called from netconn_listen. * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_listen(void *m) { struct api_msg *msg = (struct api_msg*)m; if (ERR_IS_FATAL(msg->conn->last_err)) { msg->err = msg->conn->last_err; } else { msg->err = ERR_CONN; if (msg->conn->pcb.tcp != NULL) { if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP) { if (msg->conn->state == NETCONN_NONE) { struct tcp_pcb* lpcb; if (msg->conn->pcb.tcp->state != CLOSED) { /* connection is not closed, cannot listen */ msg->err = ERR_VAL; } else { err_t err; u8_t backlog; #if TCP_LISTEN_BACKLOG backlog = msg->msg.lb.backlog; #else /* TCP_LISTEN_BACKLOG */ backlog = TCP_DEFAULT_LISTEN_BACKLOG; #endif /* TCP_LISTEN_BACKLOG */ #if LWIP_IPV4 && LWIP_IPV6 /* "Socket API like" dual-stack support: If IP to listen to is IP6_ADDR_ANY, * and NETCONN_FLAG_IPV6_V6ONLY is NOT set, use IP_ANY_TYPE to listen */ if (ip_addr_cmp(&msg->conn->pcb.ip->local_ip, IP6_ADDR_ANY) && (netconn_get_ipv6only(msg->conn) == 0)) { /* change PCB type to IPADDR_TYPE_ANY */ IP_SET_TYPE_VAL(msg->conn->pcb.tcp->local_ip, IPADDR_TYPE_ANY); IP_SET_TYPE_VAL(msg->conn->pcb.tcp->remote_ip, IPADDR_TYPE_ANY); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ lpcb = tcp_listen_with_backlog_and_err(msg->conn->pcb.tcp, backlog, &err); if (lpcb == NULL) { /* in this case, the old pcb is still allocated */ msg->err = err; } else { /* delete the recvmbox and allocate the acceptmbox */ if (sys_mbox_valid(&msg->conn->recvmbox)) { /** @todo: should we drain the recvmbox here? */ sys_mbox_free(&msg->conn->recvmbox); sys_mbox_set_invalid(&msg->conn->recvmbox); } msg->err = ERR_OK; if (!sys_mbox_valid(&msg->conn->acceptmbox)) { msg->err = sys_mbox_new(&msg->conn->acceptmbox, DEFAULT_ACCEPTMBOX_SIZE); } if (msg->err == ERR_OK) { msg->conn->state = NETCONN_LISTEN; msg->conn->pcb.tcp = lpcb; tcp_arg(msg->conn->pcb.tcp, msg->conn); tcp_accept(msg->conn->pcb.tcp, accept_function); } else { /* since the old pcb is already deallocated, free lpcb now */ tcp_close(lpcb); msg->conn->pcb.tcp = NULL; } } } } else if (msg->conn->state == NETCONN_LISTEN) { /* already listening, allow updating of the backlog */ msg->err = ERR_OK; tcp_backlog_set(msg->conn->pcb.tcp, msg->msg.lb.backlog); } } else { msg->err = ERR_ARG; } } } TCPIP_APIMSG_ACK(msg); } #endif /* LWIP_TCP */ /** * Send some data on a RAW or UDP pcb contained in a netconn * Called from netconn_send * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_send(void *m) { struct api_msg *msg = (struct api_msg*)m; if (ERR_IS_FATAL(msg->conn->last_err)) { msg->err = msg->conn->last_err; } else { msg->err = ERR_CONN; if (msg->conn->pcb.tcp != NULL) { switch (NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: if (ip_addr_isany(&msg->msg.b->addr) || IP_IS_ANY_TYPE_VAL(msg->msg.b->addr)) { msg->err = raw_send(msg->conn->pcb.raw, msg->msg.b->p); } else { msg->err = raw_sendto(msg->conn->pcb.raw, msg->msg.b->p, &msg->msg.b->addr); } break; #endif #if LWIP_UDP case NETCONN_UDP: #if LWIP_CHECKSUM_ON_COPY && CHECKSUM_GEN_UDP if (ip_addr_isany(&msg->msg.b->addr) || IP_IS_ANY_TYPE_VAL(msg->msg.b->addr)) { msg->err = udp_send_chksum(msg->conn->pcb.udp, msg->msg.b->p, msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum); } else { msg->err = udp_sendto_chksum(msg->conn->pcb.udp, msg->msg.b->p, &msg->msg.b->addr, msg->msg.b->port, msg->msg.b->flags & NETBUF_FLAG_CHKSUM, msg->msg.b->toport_chksum); } #else /* LWIP_CHECKSUM_ON_COPY */ if (ip_addr_isany_val(msg->msg.b->addr) || IP_IS_ANY_TYPE_VAL(msg->msg.b->addr)) { msg->err = udp_send(msg->conn->pcb.udp, msg->msg.b->p); } else { msg->err = udp_sendto(msg->conn->pcb.udp, msg->msg.b->p, &msg->msg.b->addr, msg->msg.b->port); } #endif /* LWIP_CHECKSUM_ON_COPY */ break; #endif /* LWIP_UDP */ default: break; } } } TCPIP_APIMSG_ACK(msg); } #if LWIP_TCP /** * Indicate data has been received from a TCP pcb contained in a netconn * Called from netconn_recv * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_recv(void *m) { struct api_msg *msg = (struct api_msg*)m; msg->err = ERR_OK; if (msg->conn->pcb.tcp != NULL) { if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP) { u32_t remaining = msg->msg.r.len; do { u16_t recved = (remaining > 0xffff) ? 0xffff : (u16_t)remaining; tcp_recved(msg->conn->pcb.tcp, recved); remaining -= recved; } while (remaining != 0); } } TCPIP_APIMSG_ACK(msg); } #if TCP_LISTEN_BACKLOG /** Indicate that a TCP pcb has been accepted * Called from netconn_accept * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_accepted(void *m) { struct api_msg *msg = (struct api_msg*)m; msg->err = ERR_OK; if (msg->conn->pcb.tcp != NULL) { if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP) { tcp_backlog_accepted(msg->conn->pcb.tcp); } } TCPIP_APIMSG_ACK(msg); } #endif /* TCP_LISTEN_BACKLOG */ /** * See if more data needs to be written from a previous call to netconn_write. * Called initially from lwip_netconn_do_write. If the first call can't send all data * (because of low memory or empty send-buffer), this function is called again * from sent_tcp() or poll_tcp() to send more data. If all data is sent, the * blocking application thread (waiting in netconn_write) is released. * * @param conn netconn (that is currently in state NETCONN_WRITE) to process * @return ERR_OK * ERR_MEM if LWIP_TCPIP_CORE_LOCKING=1 and sending hasn't yet finished */ static err_t lwip_netconn_do_writemore(struct netconn *conn WRITE_DELAYED_PARAM) { err_t err; const void *dataptr; u16_t len, available; u8_t write_finished = 0; size_t diff; u8_t dontblock; u8_t apiflags; LWIP_ASSERT("conn != NULL", conn != NULL); LWIP_ASSERT("conn->state == NETCONN_WRITE", (conn->state == NETCONN_WRITE)); LWIP_ASSERT("conn->current_msg != NULL", conn->current_msg != NULL); LWIP_ASSERT("conn->pcb.tcp != NULL", conn->pcb.tcp != NULL); LWIP_ASSERT("conn->write_offset < conn->current_msg->msg.w.len", conn->write_offset < conn->current_msg->msg.w.len); apiflags = conn->current_msg->msg.w.apiflags; dontblock = netconn_is_nonblocking(conn) || (apiflags & NETCONN_DONTBLOCK); #if LWIP_SO_SNDTIMEO if ((conn->send_timeout != 0) && ((s32_t)(sys_now() - conn->current_msg->msg.w.time_started) >= conn->send_timeout)) { write_finished = 1; if (conn->write_offset == 0) { /* nothing has been written */ err = ERR_WOULDBLOCK; conn->current_msg->msg.w.len = 0; } else { /* partial write */ err = ERR_OK; conn->current_msg->msg.w.len = conn->write_offset; conn->write_offset = 0; } } else #endif /* LWIP_SO_SNDTIMEO */ { dataptr = (const u8_t*)conn->current_msg->msg.w.dataptr + conn->write_offset; diff = conn->current_msg->msg.w.len - conn->write_offset; if (diff > 0xffffUL) { /* max_u16_t */ len = 0xffff; apiflags |= TCP_WRITE_FLAG_MORE; } else { len = (u16_t)diff; } available = tcp_sndbuf(conn->pcb.tcp); if (available < len) { /* don't try to write more than sendbuf */ len = available; if (dontblock) { if (!len) { err = ERR_WOULDBLOCK; goto err_mem; } } else { apiflags |= TCP_WRITE_FLAG_MORE; } } LWIP_ASSERT("lwip_netconn_do_writemore: invalid length!", ((conn->write_offset + len) <= conn->current_msg->msg.w.len)); err = tcp_write(conn->pcb.tcp, dataptr, len, apiflags); /* if OK or memory error, check available space */ if ((err == ERR_OK) || (err == ERR_MEM)) { err_mem: if (dontblock && (len < conn->current_msg->msg.w.len)) { /* non-blocking write did not write everything: mark the pcb non-writable and let poll_tcp check writable space to mark the pcb writable again */ API_EVENT(conn, NETCONN_EVT_SENDMINUS, len); conn->flags |= NETCONN_FLAG_CHECK_WRITESPACE; } else if ((tcp_sndbuf(conn->pcb.tcp) <= TCP_SNDLOWAT) || (tcp_sndqueuelen(conn->pcb.tcp) >= TCP_SNDQUEUELOWAT)) { /* The queued byte- or pbuf-count exceeds the configured low-water limit, let select mark this pcb as non-writable. */ API_EVENT(conn, NETCONN_EVT_SENDMINUS, len); } } if (err == ERR_OK) { err_t out_err; conn->write_offset += len; if ((conn->write_offset == conn->current_msg->msg.w.len) || dontblock) { /* return sent length */ conn->current_msg->msg.w.len = conn->write_offset; /* everything was written */ write_finished = 1; } out_err = tcp_output(conn->pcb.tcp); if (ERR_IS_FATAL(out_err) || (out_err == ERR_RTE)) { /* If tcp_output fails with fatal error or no route is found, don't try writing any more but return the error to the application thread. */ err = out_err; write_finished = 1; conn->current_msg->msg.w.len = 0; } } else if (err == ERR_MEM) { /* If ERR_MEM, we wait for sent_tcp or poll_tcp to be called. For blocking sockets, we do NOT return to the application thread, since ERR_MEM is only a temporary error! Non-blocking will remain non-writable until sent_tcp/poll_tcp is called */ /* tcp_write returned ERR_MEM, try tcp_output anyway */ err_t out_err = tcp_output(conn->pcb.tcp); if (ERR_IS_FATAL(out_err) || (out_err == ERR_RTE)) { /* If tcp_output fails with fatal error or no route is found, don't try writing any more but return the error to the application thread. */ err = out_err; write_finished = 1; conn->current_msg->msg.w.len = 0; } else if (dontblock) { /* non-blocking write is done on ERR_MEM */ err = ERR_WOULDBLOCK; write_finished = 1; conn->current_msg->msg.w.len = 0; } } else { /* On errors != ERR_MEM, we don't try writing any more but return the error to the application thread. */ write_finished = 1; conn->current_msg->msg.w.len = 0; } } if (write_finished) { /* everything was written: set back connection state and back to application task */ sys_sem_t* op_completed_sem = LWIP_API_MSG_SEM(conn->current_msg); conn->current_msg->err = err; conn->current_msg = NULL; conn->write_offset = 0; conn->state = NETCONN_NONE; NETCONN_SET_SAFE_ERR(conn, err); #if LWIP_TCPIP_CORE_LOCKING if (delayed) #endif { sys_sem_signal(op_completed_sem); } } #if LWIP_TCPIP_CORE_LOCKING else { return ERR_MEM; } #endif return ERR_OK; } #endif /* LWIP_TCP */ /** * Send some data on a TCP pcb contained in a netconn * Called from netconn_write * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_write(void *m) { struct api_msg *msg = (struct api_msg*)m; if (ERR_IS_FATAL(msg->conn->last_err)) { msg->err = msg->conn->last_err; } else { if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP) { #if LWIP_TCP if (msg->conn->state != NETCONN_NONE) { /* netconn is connecting, closing or in blocking write */ msg->err = ERR_INPROGRESS; } else if (msg->conn->pcb.tcp != NULL) { msg->conn->state = NETCONN_WRITE; /* set all the variables used by lwip_netconn_do_writemore */ LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && msg->conn->write_offset == 0); LWIP_ASSERT("msg->msg.w.len != 0", msg->msg.w.len != 0); msg->conn->current_msg = msg; msg->conn->write_offset = 0; #if LWIP_TCPIP_CORE_LOCKING if (lwip_netconn_do_writemore(msg->conn, 0) != ERR_OK) { LWIP_ASSERT("state!", msg->conn->state == NETCONN_WRITE); UNLOCK_TCPIP_CORE(); sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); LOCK_TCPIP_CORE(); LWIP_ASSERT("state!", msg->conn->state != NETCONN_WRITE); } #else /* LWIP_TCPIP_CORE_LOCKING */ lwip_netconn_do_writemore(msg->conn); #endif /* LWIP_TCPIP_CORE_LOCKING */ /* for both cases: if lwip_netconn_do_writemore was called, don't ACK the APIMSG since lwip_netconn_do_writemore ACKs it! */ return; } else { msg->err = ERR_CONN; } #else /* LWIP_TCP */ msg->err = ERR_VAL; #endif /* LWIP_TCP */ #if (LWIP_UDP || LWIP_RAW) } else { msg->err = ERR_VAL; #endif /* (LWIP_UDP || LWIP_RAW) */ } } TCPIP_APIMSG_ACK(msg); } /** * Return a connection's local or remote address * Called from netconn_getaddr * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_getaddr(void *m) { struct api_msg *msg = (struct api_msg*)m; if (msg->conn->pcb.ip != NULL) { if (msg->msg.ad.local) { ip_addr_copy(API_EXPR_DEREF(msg->msg.ad.ipaddr), msg->conn->pcb.ip->local_ip); } else { ip_addr_copy(API_EXPR_DEREF(msg->msg.ad.ipaddr), msg->conn->pcb.ip->remote_ip); } msg->err = ERR_OK; switch (NETCONNTYPE_GROUP(msg->conn->type)) { #if LWIP_RAW case NETCONN_RAW: if (msg->msg.ad.local) { API_EXPR_DEREF(msg->msg.ad.port) = msg->conn->pcb.raw->protocol; } else { /* return an error as connecting is only a helper for upper layers */ msg->err = ERR_CONN; } break; #endif /* LWIP_RAW */ #if LWIP_UDP case NETCONN_UDP: if (msg->msg.ad.local) { API_EXPR_DEREF(msg->msg.ad.port) = msg->conn->pcb.udp->local_port; } else { if ((msg->conn->pcb.udp->flags & UDP_FLAGS_CONNECTED) == 0) { msg->err = ERR_CONN; } else { API_EXPR_DEREF(msg->msg.ad.port) = msg->conn->pcb.udp->remote_port; } } break; #endif /* LWIP_UDP */ #if LWIP_TCP case NETCONN_TCP: if ((msg->msg.ad.local == 0) && ((msg->conn->pcb.tcp->state == CLOSED) || (msg->conn->pcb.tcp->state == LISTEN))) { /* pcb is not connected and remote name is requested */ msg->err = ERR_CONN; } else { API_EXPR_DEREF(msg->msg.ad.port) = (msg->msg.ad.local ? msg->conn->pcb.tcp->local_port : msg->conn->pcb.tcp->remote_port); } break; #endif /* LWIP_TCP */ default: LWIP_ASSERT("invalid netconn_type", 0); break; } } else { msg->err = ERR_CONN; } TCPIP_APIMSG_ACK(msg); } /** * Close or half-shutdown a TCP pcb contained in a netconn * Called from netconn_close * In contrast to closing sockets, the netconn is not deallocated. * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_close(void *m) { struct api_msg *msg = (struct api_msg*)m; #if LWIP_TCP enum netconn_state state = msg->conn->state; /* First check if this is a TCP netconn and if it is in a correct state (LISTEN doesn't support half shutdown) */ if ((msg->conn->pcb.tcp != NULL) && (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_TCP) && ((msg->msg.sd.shut == NETCONN_SHUT_RDWR) || (state != NETCONN_LISTEN))) { /* Check if we are in a connected state */ if (state == NETCONN_CONNECT) { /* TCP connect in progress: cannot shutdown */ msg->err = ERR_CONN; } else if (state == NETCONN_WRITE) { #if LWIP_NETCONN_FULLDUPLEX if (msg->msg.sd.shut & NETCONN_SHUT_WR) { /* close requested, abort running write */ sys_sem_t* write_completed_sem; LWIP_ASSERT("msg->conn->current_msg != NULL", msg->conn->current_msg != NULL); write_completed_sem = LWIP_API_MSG_SEM(msg->conn->current_msg); msg->conn->current_msg->err = ERR_CLSD; msg->conn->current_msg = NULL; msg->conn->write_offset = 0; msg->conn->state = NETCONN_NONE; state = NETCONN_NONE; NETCONN_SET_SAFE_ERR(msg->conn, ERR_CLSD); sys_sem_signal(write_completed_sem); } else { LWIP_ASSERT("msg->msg.sd.shut == NETCONN_SHUT_RD", msg->msg.sd.shut == NETCONN_SHUT_RD); /* In this case, let the write continue and do not interfere with conn->current_msg or conn->state! */ msg->err = tcp_shutdown(msg->conn->pcb.tcp, 1, 0); } } if (state == NETCONN_NONE) { #else /* LWIP_NETCONN_FULLDUPLEX */ msg->err = ERR_INPROGRESS; } else { #endif /* LWIP_NETCONN_FULLDUPLEX */ if (msg->msg.sd.shut & NETCONN_SHUT_RD) { /* Drain and delete mboxes */ netconn_drain(msg->conn); } LWIP_ASSERT("already writing or closing", msg->conn->current_msg == NULL && msg->conn->write_offset == 0); msg->conn->state = NETCONN_CLOSE; msg->conn->current_msg = msg; #if LWIP_TCPIP_CORE_LOCKING if (lwip_netconn_do_close_internal(msg->conn, 0) != ERR_OK) { LWIP_ASSERT("state!", msg->conn->state == NETCONN_CLOSE); UNLOCK_TCPIP_CORE(); sys_arch_sem_wait(LWIP_API_MSG_SEM(msg), 0); LOCK_TCPIP_CORE(); LWIP_ASSERT("state!", msg->conn->state == NETCONN_NONE); } #else /* LWIP_TCPIP_CORE_LOCKING */ lwip_netconn_do_close_internal(msg->conn); #endif /* LWIP_TCPIP_CORE_LOCKING */ /* for tcp netconns, lwip_netconn_do_close_internal ACKs the message */ return; } } else #endif /* LWIP_TCP */ { msg->err = ERR_CONN; } TCPIP_APIMSG_ACK(msg); } #if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) /** * Join multicast groups for UDP netconns. * Called from netconn_join_leave_group * * @param m the api_msg_msg pointing to the connection */ void lwip_netconn_do_join_leave_group(void *m) { struct api_msg *msg = (struct api_msg*)m; if (ERR_IS_FATAL(msg->conn->last_err)) { msg->err = msg->conn->last_err; } else { if (msg->conn->pcb.tcp != NULL) { if (NETCONNTYPE_GROUP(msg->conn->type) == NETCONN_UDP) { #if LWIP_UDP #if LWIP_IPV6 && LWIP_IPV6_MLD if (NETCONNTYPE_ISIPV6(msg->conn->type)) { if (msg->msg.jl.join_or_leave == NETCONN_JOIN) { msg->err = mld6_joingroup(ip_2_ip6(API_EXPR_REF(msg->msg.jl.netif_addr)), ip_2_ip6(API_EXPR_REF(msg->msg.jl.multiaddr))); } else { msg->err = mld6_leavegroup(ip_2_ip6(API_EXPR_REF(msg->msg.jl.netif_addr)), ip_2_ip6(API_EXPR_REF(msg->msg.jl.multiaddr))); } } else #endif /* LWIP_IPV6 && LWIP_IPV6_MLD */ { #if LWIP_IGMP if (msg->msg.jl.join_or_leave == NETCONN_JOIN) { msg->err = igmp_joingroup(ip_2_ip4(API_EXPR_REF(msg->msg.jl.netif_addr)), ip_2_ip4(API_EXPR_REF(msg->msg.jl.multiaddr))); } else { msg->err = igmp_leavegroup(ip_2_ip4(API_EXPR_REF(msg->msg.jl.netif_addr)), ip_2_ip4(API_EXPR_REF(msg->msg.jl.multiaddr))); } #endif /* LWIP_IGMP */ } #endif /* LWIP_UDP */ #if (LWIP_TCP || LWIP_RAW) } else { msg->err = ERR_VAL; #endif /* (LWIP_TCP || LWIP_RAW) */ } } else { msg->err = ERR_CONN; } } TCPIP_APIMSG_ACK(msg); } #endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */ #if LWIP_DNS /** * Callback function that is called when DNS name is resolved * (or on timeout). A waiting application thread is waked up by * signaling the semaphore. */ static void lwip_netconn_do_dns_found(const char *name, const ip_addr_t *ipaddr, void *arg) { struct dns_api_msg *msg = (struct dns_api_msg*)arg; /* we trust the internal implementation to be correct :-) */ LWIP_UNUSED_ARG(name); if (ipaddr == NULL) { /* timeout or memory error */ API_EXPR_DEREF(msg->err) = ERR_VAL; } else { /* address was resolved */ API_EXPR_DEREF(msg->err) = ERR_OK; API_EXPR_DEREF(msg->addr) = *ipaddr; } /* wake up the application task waiting in netconn_gethostbyname */ sys_sem_signal(API_EXPR_REF_SEM(msg->sem)); } /** * Execute a DNS query * Called from netconn_gethostbyname * * @param arg the dns_api_msg pointing to the query */ void lwip_netconn_do_gethostbyname(void *arg) { struct dns_api_msg *msg = (struct dns_api_msg*)arg; u8_t addrtype = #if LWIP_IPV4 && LWIP_IPV6 msg->dns_addrtype; #else LWIP_DNS_ADDRTYPE_DEFAULT; #endif API_EXPR_DEREF(msg->err) = dns_gethostbyname_addrtype(msg->name, API_EXPR_REF(msg->addr), lwip_netconn_do_dns_found, msg, addrtype); if (API_EXPR_DEREF(msg->err) != ERR_INPROGRESS) { /* on error or immediate success, wake up the application * task waiting in netconn_gethostbyname */ sys_sem_signal(API_EXPR_REF_SEM(msg->sem)); } } #endif /* LWIP_DNS */ #endif /* LWIP_NETCONN */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/api_msg.c
C
unknown
63,115
/** * @file * Error Management 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> * */ #include "lwip/err.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/errno.h" #if !NO_SYS /** 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_ALREADY -9 Already connecting. */ EISCONN, /* ERR_ISCONN -10 Conn already established.*/ ENOTCONN, /* ERR_CONN -11 Not connected. */ -1, /* ERR_IF -12 Low-level netif error */ ECONNABORTED, /* ERR_ABRT -13 Connection aborted. */ ECONNRESET, /* ERR_RST -14 Connection reset. */ ENOTCONN, /* ERR_CLSD -15 Connection closed. */ EIO /* ERR_ARG -16 Illegal argument. */ }; int err_to_errno(err_t err) { if ((err > 0) || (-err >= (err_t)LWIP_ARRAYSIZE(err_to_errno_table))) { return EIO; } return err_to_errno_table[-err]; } #endif /* !NO_SYS */ #ifdef LWIP_DEBUG static const char *err_strerr[] = { "Ok.", /* ERR_OK 0 */ "Out of memory error.", /* ERR_MEM -1 */ "Buffer error.", /* ERR_BUF -2 */ "Timeout.", /* ERR_TIMEOUT -3 */ "Routing problem.", /* ERR_RTE -4 */ "Operation in progress.", /* ERR_INPROGRESS -5 */ "Illegal value.", /* ERR_VAL -6 */ "Operation would block.", /* ERR_WOULDBLOCK -7 */ "Address in use.", /* ERR_USE -8 */ "Already connecting.", /* ERR_ALREADY -9 */ "Already connected.", /* ERR_ISCONN -10 */ "Not connected.", /* ERR_CONN -11 */ "Low-level netif error.", /* ERR_IF -12 */ "Connection aborted.", /* ERR_ABRT -13 */ "Connection reset.", /* ERR_RST -14 */ "Connection closed.", /* ERR_CLSD -15 */ "Illegal argument." /* ERR_ARG -16 */ }; /** * Convert an lwip internal error to a string representation. * * @param err an lwip internal err_t * @return a string representation for err */ const char * lwip_strerr(err_t err) { if ((err > 0) || (-err >= (err_t)LWIP_ARRAYSIZE(err_strerr))) { return "Unknown error."; } return err_strerr[-err]; } #endif /* LWIP_DEBUG */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/err.c
C
unknown
4,853
/** * @file * Network buffer management * * @defgroup netbuf Network buffers * @ingroup netconn * Network buffer descriptor for @ref netconn. Based on @ref pbuf internally * to avoid copying data around.\n * Buffers must not be shared accross multiple threads, all functions except * netbuf_new() and netbuf_delete() are not thread-safe. */ /* * 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 "lwip/opt.h" #if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */ #include "lwip/netbuf.h" #include "lwip/memp.h" #include <string.h> /** * @ingroup netbuf * Create (allocate) and initialize a new netbuf. * The netbuf doesn't yet contain a packet buffer! * * @return a pointer to a new netbuf * NULL on lack of memory */ struct netbuf *netbuf_new(void) { struct netbuf *buf; buf = (struct netbuf *)memp_malloc(MEMP_NETBUF); if (buf != NULL) { memset(buf, 0, sizeof(struct netbuf)); } return buf; } /** * @ingroup netbuf * Deallocate a netbuf allocated by netbuf_new(). * * @param buf pointer to a netbuf allocated by netbuf_new() */ void netbuf_delete(struct netbuf *buf) { if (buf != NULL) { if (buf->p != NULL) { pbuf_free(buf->p); buf->p = buf->ptr = NULL; } memp_free(MEMP_NETBUF, buf); } } /** * @ingroup netbuf * Allocate memory for a packet buffer for a given netbuf. * * @param buf the netbuf for which to allocate a packet buffer * @param size the size of the packet buffer to allocate * @return pointer to the allocated memory * NULL if no memory could be allocated */ void * netbuf_alloc(struct netbuf *buf, u16_t size) { LWIP_ERROR("netbuf_alloc: invalid buf", (buf != NULL), return NULL;); /* Deallocate any previously allocated memory. */ if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); if (buf->p == NULL) { return NULL; } LWIP_ASSERT("check that first pbuf can hold size", (buf->p->len >= size)); buf->ptr = buf->p; return buf->p->payload; } /** * @ingroup netbuf * Free the packet buffer included in a netbuf * * @param buf pointer to the netbuf which contains the packet buffer to free */ void netbuf_free(struct netbuf *buf) { LWIP_ERROR("netbuf_free: invalid buf", (buf != NULL), return;); if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = buf->ptr = NULL; } /** * @ingroup netbuf * Let a netbuf reference existing (non-volatile) data. * * @param buf netbuf which should reference the data * @param dataptr pointer to the data to reference * @param size size of the data * @return ERR_OK if data is referenced * ERR_MEM if data couldn't be referenced due to lack of memory */ err_t netbuf_ref(struct netbuf *buf, const void *dataptr, u16_t size) { LWIP_ERROR("netbuf_ref: invalid buf", (buf != NULL), return ERR_ARG;); if (buf->p != NULL) { pbuf_free(buf->p); } buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF); if (buf->p == NULL) { buf->ptr = NULL; return ERR_MEM; } ((struct pbuf_rom*)buf->p)->payload = dataptr; buf->p->len = buf->p->tot_len = size; buf->ptr = buf->p; return ERR_OK; } /** * @ingroup netbuf * Chain one netbuf to another (@see pbuf_chain) * * @param head the first netbuf * @param tail netbuf to chain after head, freed by this function, may not be reference after returning */ void netbuf_chain(struct netbuf *head, struct netbuf *tail) { LWIP_ERROR("netbuf_chain: invalid head", (head != NULL), return;); LWIP_ERROR("netbuf_chain: invalid tail", (tail != NULL), return;); pbuf_cat(head->p, tail->p); head->ptr = head->p; memp_free(MEMP_NETBUF, tail); } /** * @ingroup netbuf * Get the data pointer and length of the data inside a netbuf. * * @param buf netbuf to get the data from * @param dataptr pointer to a void pointer where to store the data pointer * @param len pointer to an u16_t where the length of the data is stored * @return ERR_OK if the information was retrieved, * ERR_BUF on error. */ err_t netbuf_data(struct netbuf *buf, void **dataptr, u16_t *len) { LWIP_ERROR("netbuf_data: invalid buf", (buf != NULL), return ERR_ARG;); LWIP_ERROR("netbuf_data: invalid dataptr", (dataptr != NULL), return ERR_ARG;); LWIP_ERROR("netbuf_data: invalid len", (len != NULL), return ERR_ARG;); if (buf->ptr == NULL) { return ERR_BUF; } *dataptr = buf->ptr->payload; *len = buf->ptr->len; return ERR_OK; } /** * @ingroup netbuf * Move the current data pointer of a packet buffer contained in a netbuf * to the next part. * The packet buffer itself is not modified. * * @param buf the netbuf to modify * @return -1 if there is no next part * 1 if moved to the next part but now there is no next part * 0 if moved to the next part and there are still more parts */ s8_t netbuf_next(struct netbuf *buf) { LWIP_ERROR("netbuf_next: invalid buf", (buf != NULL), return -1;); if (buf->ptr->next == NULL) { return -1; } buf->ptr = buf->ptr->next; if (buf->ptr->next == NULL) { return 1; } return 0; } /** * @ingroup netbuf * Move the current data pointer of a packet buffer contained in a netbuf * to the beginning of the packet. * The packet buffer itself is not modified. * * @param buf the netbuf to modify */ void netbuf_first(struct netbuf *buf) { LWIP_ERROR("netbuf_first: invalid buf", (buf != NULL), return;); buf->ptr = buf->p; } #endif /* LWIP_NETCONN */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/netbuf.c
C
unknown
7,289
/** * @file * API functions for name resolving * * @defgroup netdbapi NETDB API * @ingroup socket */ /* * 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: Simon Goldschmidt * */ #include "lwip/netdb.h" #if LWIP_DNS && LWIP_SOCKET #include "lwip/err.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/ip_addr.h" #include "lwip/api.h" #include "lwip/dns.h" #include <string.h> /* memset */ #include <stdlib.h> /* atoi */ /** helper struct for gethostbyname_r to access the char* buffer */ struct gethostbyname_r_helper { ip_addr_t *addr_list[2]; ip_addr_t addr; char *aliases; }; /** h_errno is exported in netdb.h for access by applications. */ #if LWIP_DNS_API_DECLARE_H_ERRNO int h_errno; #endif /* LWIP_DNS_API_DECLARE_H_ERRNO */ /** define "hostent" variables storage: 0 if we use a static (but unprotected) * set of variables for lwip_gethostbyname, 1 if we use a local storage */ #ifndef LWIP_DNS_API_HOSTENT_STORAGE #define LWIP_DNS_API_HOSTENT_STORAGE 0 #endif /** define "hostent" variables storage */ #if LWIP_DNS_API_HOSTENT_STORAGE #define HOSTENT_STORAGE #else #define HOSTENT_STORAGE static #endif /* LWIP_DNS_API_STATIC_HOSTENT */ /** * Returns an entry containing addresses of address family AF_INET * for the host with name name. * Due to dns_gethostbyname limitations, only one address is returned. * * @param name the hostname to resolve * @return an entry containing addresses of address family AF_INET * for the host with name name */ struct hostent* lwip_gethostbyname(const char *name) { err_t err; ip_addr_t addr; /* buffer variables for lwip_gethostbyname() */ HOSTENT_STORAGE struct hostent s_hostent; HOSTENT_STORAGE char *s_aliases; HOSTENT_STORAGE ip_addr_t s_hostent_addr; HOSTENT_STORAGE ip_addr_t *s_phostent_addr[2]; HOSTENT_STORAGE char s_hostname[DNS_MAX_NAME_LENGTH + 1]; /* query host IP address */ err = netconn_gethostbyname(name, &addr); if (err != ERR_OK) { LWIP_DEBUGF(DNS_DEBUG, ("lwip_gethostbyname(%s) failed, err=%d\n", name, err)); h_errno = HOST_NOT_FOUND; return NULL; } /* fill hostent */ s_hostent_addr = addr; s_phostent_addr[0] = &s_hostent_addr; s_phostent_addr[1] = NULL; strncpy(s_hostname, name, DNS_MAX_NAME_LENGTH); s_hostname[DNS_MAX_NAME_LENGTH] = 0; s_hostent.h_name = s_hostname; s_aliases = NULL; s_hostent.h_aliases = &s_aliases; s_hostent.h_addrtype = AF_INET; s_hostent.h_length = sizeof(ip_addr_t); s_hostent.h_addr_list = (char**)&s_phostent_addr; #if DNS_DEBUG /* dump hostent */ LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_name == %s\n", s_hostent.h_name)); LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_aliases == %p\n", (void*)s_hostent.h_aliases)); /* h_aliases are always empty */ LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addrtype == %d\n", s_hostent.h_addrtype)); LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_length == %d\n", s_hostent.h_length)); LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list == %p\n", (void*)s_hostent.h_addr_list)); if (s_hostent.h_addr_list != NULL) { u8_t idx; for (idx=0; s_hostent.h_addr_list[idx]; idx++) { LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i] == %p\n", idx, s_hostent.h_addr_list[idx])); LWIP_DEBUGF(DNS_DEBUG, ("hostent.h_addr_list[%i]-> == %s\n", idx, ipaddr_ntoa((ip_addr_t*)s_hostent.h_addr_list[idx]))); } } #endif /* DNS_DEBUG */ #if LWIP_DNS_API_HOSTENT_STORAGE /* this function should return the "per-thread" hostent after copy from s_hostent */ return sys_thread_hostent(&s_hostent); #else return &s_hostent; #endif /* LWIP_DNS_API_HOSTENT_STORAGE */ } /** * Thread-safe variant of lwip_gethostbyname: instead of using a static * buffer, this function takes buffer and errno pointers as arguments * and uses these for the result. * * @param name the hostname to resolve * @param ret pre-allocated struct where to store the result * @param buf pre-allocated buffer where to store additional data * @param buflen the size of buf * @param result pointer to a hostent pointer that is set to ret on success * and set to zero on error * @param h_errnop pointer to an int where to store errors (instead of modifying * the global h_errno) * @return 0 on success, non-zero on error, additional error information * is stored in *h_errnop instead of h_errno to be thread-safe */ int lwip_gethostbyname_r(const char *name, struct hostent *ret, char *buf, size_t buflen, struct hostent **result, int *h_errnop) { err_t err; struct gethostbyname_r_helper *h; char *hostname; size_t namelen; int lh_errno; if (h_errnop == NULL) { /* ensure h_errnop is never NULL */ h_errnop = &lh_errno; } if (result == NULL) { /* not all arguments given */ *h_errnop = EINVAL; return -1; } /* first thing to do: set *result to nothing */ *result = NULL; if ((name == NULL) || (ret == NULL) || (buf == NULL)) { /* not all arguments given */ *h_errnop = EINVAL; return -1; } namelen = strlen(name); if (buflen < (sizeof(struct gethostbyname_r_helper) + namelen + 1 + (MEM_ALIGNMENT - 1))) { /* buf can't hold the data needed + a copy of name */ *h_errnop = ERANGE; return -1; } h = (struct gethostbyname_r_helper*)LWIP_MEM_ALIGN(buf); hostname = ((char*)h) + sizeof(struct gethostbyname_r_helper); /* query host IP address */ err = netconn_gethostbyname(name, &h->addr); if (err != ERR_OK) { LWIP_DEBUGF(DNS_DEBUG, ("lwip_gethostbyname(%s) failed, err=%d\n", name, err)); *h_errnop = HOST_NOT_FOUND; return -1; } /* copy the hostname into buf */ MEMCPY(hostname, name, namelen); hostname[namelen] = 0; /* fill hostent */ h->addr_list[0] = &h->addr; h->addr_list[1] = NULL; h->aliases = NULL; ret->h_name = hostname; ret->h_aliases = &h->aliases; ret->h_addrtype = AF_INET; ret->h_length = sizeof(ip_addr_t); ret->h_addr_list = (char**)&h->addr_list; /* set result != NULL */ *result = ret; /* return success */ return 0; } /** * Frees one or more addrinfo structures returned by getaddrinfo(), along with * any additional storage associated with those structures. If the ai_next field * of the structure is not null, the entire list of structures is freed. * * @param ai struct addrinfo to free */ void lwip_freeaddrinfo(struct addrinfo *ai) { struct addrinfo *next; while (ai != NULL) { next = ai->ai_next; memp_free(MEMP_NETDB, ai); ai = next; } } /** * Translates the name of a service location (for example, a host name) and/or * a service name and returns a set of socket addresses and associated * information to be used in creating a socket with which to address the * specified service. * Memory for the result is allocated internally and must be freed by calling * lwip_freeaddrinfo()! * * Due to a limitation in dns_gethostbyname, only the first address of a * host is returned. * Also, service names are not supported (only port numbers)! * * @param nodename descriptive name or address string of the host * (may be NULL -> local address) * @param servname port number as string of NULL * @param hints structure containing input values that set socktype and protocol * @param res pointer to a pointer where to store the result (set to NULL on failure) * @return 0 on success, non-zero on failure * * @todo: implement AI_V4MAPPED, AI_ADDRCONFIG */ int lwip_getaddrinfo(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { err_t err; ip_addr_t addr; struct addrinfo *ai; struct sockaddr_storage *sa = NULL; int port_nr = 0; size_t total_size; size_t namelen = 0; int ai_family; if (res == NULL) { return EAI_FAIL; } *res = NULL; if ((nodename == NULL) && (servname == NULL)) { return EAI_NONAME; } if (hints != NULL) { ai_family = hints->ai_family; if ((ai_family != AF_UNSPEC) #if LWIP_IPV4 && (ai_family != AF_INET) #endif /* LWIP_IPV4 */ #if LWIP_IPV6 && (ai_family != AF_INET6) #endif /* LWIP_IPV6 */ ) { return EAI_FAMILY; } } else { ai_family = AF_UNSPEC; } if (servname != NULL) { /* service name specified: convert to port number * @todo?: currently, only ASCII integers (port numbers) are supported (AI_NUMERICSERV)! */ port_nr = atoi(servname); if ((port_nr <= 0) || (port_nr > 0xffff)) { return EAI_SERVICE; } } if (nodename != NULL) { /* service location specified, try to resolve */ if ((hints != NULL) && (hints->ai_flags & AI_NUMERICHOST)) { /* no DNS lookup, just parse for an address string */ if (!ipaddr_aton(nodename, &addr)) { return EAI_NONAME; } #if LWIP_IPV4 && LWIP_IPV6 if ((IP_IS_V6_VAL(addr) && ai_family == AF_INET) || (IP_IS_V4_VAL(addr) && ai_family == AF_INET6)) { return EAI_NONAME; } #endif /* LWIP_IPV4 && LWIP_IPV6 */ } else { #if LWIP_IPV4 && LWIP_IPV6 /* AF_UNSPEC: prefer IPv4 */ u8_t type = NETCONN_DNS_IPV4_IPV6; if (ai_family == AF_INET) { type = NETCONN_DNS_IPV4; } else if (ai_family == AF_INET6) { type = NETCONN_DNS_IPV6; } #endif /* LWIP_IPV4 && LWIP_IPV6 */ err = netconn_gethostbyname_addrtype(nodename, &addr, type); if (err != ERR_OK) { return EAI_FAIL; } } } else { /* service location specified, use loopback address */ if ((hints != NULL) && (hints->ai_flags & AI_PASSIVE)) { ip_addr_set_any(ai_family == AF_INET6, &addr); } else { ip_addr_set_loopback(ai_family == AF_INET6, &addr); } } total_size = sizeof(struct addrinfo) + sizeof(struct sockaddr_storage); if (nodename != NULL) { namelen = strlen(nodename); if (namelen > DNS_MAX_NAME_LENGTH) { /* invalid name length */ return EAI_FAIL; } LWIP_ASSERT("namelen is too long", total_size + namelen + 1 > total_size); total_size += namelen + 1; } /* If this fails, please report to lwip-devel! :-) */ LWIP_ASSERT("total_size <= NETDB_ELEM_SIZE: please report this!", total_size <= NETDB_ELEM_SIZE); ai = (struct addrinfo *)memp_malloc(MEMP_NETDB); if (ai == NULL) { return EAI_MEMORY; } memset(ai, 0, total_size); /* cast through void* to get rid of alignment warnings */ sa = (struct sockaddr_storage *)(void*)((u8_t*)ai + sizeof(struct addrinfo)); if (IP_IS_V6_VAL(addr)) { #if LWIP_IPV6 struct sockaddr_in6 *sa6 = (struct sockaddr_in6*)sa; /* set up sockaddr */ inet6_addr_from_ip6addr(&sa6->sin6_addr, ip_2_ip6(&addr)); sa6->sin6_family = AF_INET6; sa6->sin6_len = sizeof(struct sockaddr_in6); sa6->sin6_port = lwip_htons((u16_t)port_nr); ai->ai_family = AF_INET6; #endif /* LWIP_IPV6 */ } else { #if LWIP_IPV4 struct sockaddr_in *sa4 = (struct sockaddr_in*)sa; /* set up sockaddr */ inet_addr_from_ip4addr(&sa4->sin_addr, ip_2_ip4(&addr)); sa4->sin_family = AF_INET; sa4->sin_len = sizeof(struct sockaddr_in); sa4->sin_port = lwip_htons((u16_t)port_nr); ai->ai_family = AF_INET; #endif /* LWIP_IPV4 */ } /* set up addrinfo */ if (hints != NULL) { /* copy socktype & protocol from hints if specified */ ai->ai_socktype = hints->ai_socktype; ai->ai_protocol = hints->ai_protocol; } if (nodename != NULL) { /* copy nodename to canonname if specified */ ai->ai_canonname = ((char*)ai + sizeof(struct addrinfo) + sizeof(struct sockaddr_storage)); MEMCPY(ai->ai_canonname, nodename, namelen); ai->ai_canonname[namelen] = 0; } ai->ai_addrlen = sizeof(struct sockaddr_storage); ai->ai_addr = (struct sockaddr*)sa; *res = ai; return 0; } #endif /* LWIP_DNS && LWIP_SOCKET */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/netdb.c
C
unknown
13,662
/** * @file * Network Interface Sequential API module * * @defgroup netifapi NETIF API * @ingroup sequential_api * Thread-safe functions to be called from non-TCPIP threads * * @defgroup netifapi_netif NETIF related * @ingroup netifapi * To be called from non-TCPIP threads */ /* * 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. * */ #include "lwip/opt.h" #if LWIP_NETIF_API /* don't build if not configured for use in lwipopts.h */ #include "lwip/netifapi.h" #include "lwip/memp.h" #include "lwip/priv/tcpip_priv.h" #define NETIFAPI_VAR_REF(name) API_VAR_REF(name) #define NETIFAPI_VAR_DECLARE(name) API_VAR_DECLARE(struct netifapi_msg, name) #define NETIFAPI_VAR_ALLOC(name) API_VAR_ALLOC(struct netifapi_msg, MEMP_NETIFAPI_MSG, name, ERR_MEM) #define NETIFAPI_VAR_FREE(name) API_VAR_FREE(MEMP_NETIFAPI_MSG, name) /** * Call netif_add() inside the tcpip_thread context. */ static err_t netifapi_do_netif_add(struct tcpip_api_call_data *m) { /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct netifapi_msg */ struct netifapi_msg *msg = (struct netifapi_msg*)(void*)m; if (!netif_add( msg->netif, #if LWIP_IPV4 API_EXPR_REF(msg->msg.add.ipaddr), API_EXPR_REF(msg->msg.add.netmask), API_EXPR_REF(msg->msg.add.gw), #endif /* LWIP_IPV4 */ msg->msg.add.state, msg->msg.add.init, msg->msg.add.input)) { return ERR_IF; } else { return ERR_OK; } } #if LWIP_IPV4 /** * Call netif_set_addr() inside the tcpip_thread context. */ static err_t netifapi_do_netif_set_addr(struct tcpip_api_call_data *m) { /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct netifapi_msg */ struct netifapi_msg *msg = (struct netifapi_msg*)(void*)m; netif_set_addr( msg->netif, API_EXPR_REF(msg->msg.add.ipaddr), API_EXPR_REF(msg->msg.add.netmask), API_EXPR_REF(msg->msg.add.gw)); return ERR_OK; } #endif /* LWIP_IPV4 */ /** * Call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) inside the * tcpip_thread context. */ static err_t netifapi_do_netif_common(struct tcpip_api_call_data *m) { /* cast through void* to silence alignment warnings. * We know it works because the structs have been instantiated as struct netifapi_msg */ struct netifapi_msg *msg = (struct netifapi_msg*)(void*)m; if (msg->msg.common.errtfunc != NULL) { return msg->msg.common.errtfunc(msg->netif); } else { msg->msg.common.voidfunc(msg->netif); return ERR_OK; } } /** * @ingroup netifapi_netif * Call netif_add() in a thread-safe way by running that function inside the * tcpip_thread context. * * @note for params @see netif_add() */ err_t netifapi_netif_add(struct netif *netif, #if LWIP_IPV4 const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw, #endif /* LWIP_IPV4 */ void *state, netif_init_fn init, netif_input_fn input) { err_t err; NETIFAPI_VAR_DECLARE(msg); NETIFAPI_VAR_ALLOC(msg); #if LWIP_IPV4 if (ipaddr == NULL) { ipaddr = IP4_ADDR_ANY4; } if (netmask == NULL) { netmask = IP4_ADDR_ANY4; } if (gw == NULL) { gw = IP4_ADDR_ANY4; } #endif /* LWIP_IPV4 */ NETIFAPI_VAR_REF(msg).netif = netif; #if LWIP_IPV4 NETIFAPI_VAR_REF(msg).msg.add.ipaddr = NETIFAPI_VAR_REF(ipaddr); NETIFAPI_VAR_REF(msg).msg.add.netmask = NETIFAPI_VAR_REF(netmask); NETIFAPI_VAR_REF(msg).msg.add.gw = NETIFAPI_VAR_REF(gw); #endif /* LWIP_IPV4 */ NETIFAPI_VAR_REF(msg).msg.add.state = state; NETIFAPI_VAR_REF(msg).msg.add.init = init; NETIFAPI_VAR_REF(msg).msg.add.input = input; err = tcpip_api_call(netifapi_do_netif_add, &API_VAR_REF(msg).call); NETIFAPI_VAR_FREE(msg); return err; } #if LWIP_IPV4 /** * @ingroup netifapi_netif * Call netif_set_addr() in a thread-safe way by running that function inside the * tcpip_thread context. * * @note for params @see netif_set_addr() */ err_t netifapi_netif_set_addr(struct netif *netif, const ip4_addr_t *ipaddr, const ip4_addr_t *netmask, const ip4_addr_t *gw) { err_t err; NETIFAPI_VAR_DECLARE(msg); NETIFAPI_VAR_ALLOC(msg); if (ipaddr == NULL) { ipaddr = IP4_ADDR_ANY4; } if (netmask == NULL) { netmask = IP4_ADDR_ANY4; } if (gw == NULL) { gw = IP4_ADDR_ANY4; } NETIFAPI_VAR_REF(msg).netif = netif; NETIFAPI_VAR_REF(msg).msg.add.ipaddr = NETIFAPI_VAR_REF(ipaddr); NETIFAPI_VAR_REF(msg).msg.add.netmask = NETIFAPI_VAR_REF(netmask); NETIFAPI_VAR_REF(msg).msg.add.gw = NETIFAPI_VAR_REF(gw); err = tcpip_api_call(netifapi_do_netif_set_addr, &API_VAR_REF(msg).call); NETIFAPI_VAR_FREE(msg); return err; } #endif /* LWIP_IPV4 */ /** * call the "errtfunc" (or the "voidfunc" if "errtfunc" is NULL) in a thread-safe * way by running that function inside the tcpip_thread context. * * @note use only for functions where there is only "netif" parameter. */ err_t netifapi_netif_common(struct netif *netif, netifapi_void_fn voidfunc, netifapi_errt_fn errtfunc) { err_t err; NETIFAPI_VAR_DECLARE(msg); NETIFAPI_VAR_ALLOC(msg); NETIFAPI_VAR_REF(msg).netif = netif; NETIFAPI_VAR_REF(msg).msg.common.voidfunc = voidfunc; NETIFAPI_VAR_REF(msg).msg.common.errtfunc = errtfunc; err = tcpip_api_call(netifapi_do_netif_common, &API_VAR_REF(msg).call); NETIFAPI_VAR_FREE(msg); return err; } #endif /* LWIP_NETIF_API */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/netifapi.c
C
unknown
7,333
/** * @file * Sockets BSD-Like API module * * @defgroup socket Socket API * @ingroup sequential_api * BSD-style socket API.\n * Thread-safe, to be called from non-TCPIP threads only.\n * Can be activated by defining @ref LWIP_SOCKET to 1.\n * Header is in posix/sys/socket.h\b */ /* * 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/memp.h" #include "lwip/pbuf.h" #include "lwip/priv/tcpip_priv.h" #if LWIP_CHECKSUM_ON_COPY #include "lwip/inet_chksum.h" #endif #include <string.h> /* If the netconn API is not required publicly, then we include the necessary files here to get the implementation */ #if !LWIP_NETCONN #undef LWIP_NETCONN #define LWIP_NETCONN 1 #include "api_msg.c" #include "api_lib.c" #include "netbuf.c" #undef LWIP_NETCONN #define LWIP_NETCONN 0 #endif #if LWIP_IPV4 #define IP4ADDR_PORT_TO_SOCKADDR(sin, ipaddr, port) do { \ (sin)->sin_len = sizeof(struct sockaddr_in); \ (sin)->sin_family = AF_INET; \ (sin)->sin_port = lwip_htons((port)); \ inet_addr_from_ip4addr(&(sin)->sin_addr, ipaddr); \ memset((sin)->sin_zero, 0, SIN_ZERO_LEN); }while(0) #define SOCKADDR4_TO_IP4ADDR_PORT(sin, ipaddr, port) do { \ inet_addr_to_ip4addr(ip_2_ip4(ipaddr), &((sin)->sin_addr)); \ (port) = lwip_ntohs((sin)->sin_port); }while(0) #endif /* LWIP_IPV4 */ #if LWIP_IPV6 #define IP6ADDR_PORT_TO_SOCKADDR(sin6, ipaddr, port) do { \ (sin6)->sin6_len = sizeof(struct sockaddr_in6); \ (sin6)->sin6_family = AF_INET6; \ (sin6)->sin6_port = lwip_htons((port)); \ (sin6)->sin6_flowinfo = 0; \ inet6_addr_from_ip6addr(&(sin6)->sin6_addr, ipaddr); \ (sin6)->sin6_scope_id = 0; }while(0) #define SOCKADDR6_TO_IP6ADDR_PORT(sin6, ipaddr, port) do { \ inet6_addr_to_ip6addr(ip_2_ip6(ipaddr), &((sin6)->sin6_addr)); \ (port) = lwip_ntohs((sin6)->sin6_port); }while(0) #endif /* LWIP_IPV6 */ #if LWIP_IPV4 && LWIP_IPV6 static void sockaddr_to_ipaddr_port(const struct sockaddr* sockaddr, ip_addr_t* ipaddr, u16_t* port); #define IS_SOCK_ADDR_LEN_VALID(namelen) (((namelen) == sizeof(struct sockaddr_in)) || \ ((namelen) == sizeof(struct sockaddr_in6))) #define IS_SOCK_ADDR_TYPE_VALID(name) (((name)->sa_family == AF_INET) || \ ((name)->sa_family == AF_INET6)) #define SOCK_ADDR_TYPE_MATCH(name, sock) \ ((((name)->sa_family == AF_INET) && !(NETCONNTYPE_ISIPV6((sock)->conn->type))) || \ (((name)->sa_family == AF_INET6) && (NETCONNTYPE_ISIPV6((sock)->conn->type)))) #define IPADDR_PORT_TO_SOCKADDR(sockaddr, ipaddr, port) do { \ if (IP_IS_V6(ipaddr)) { \ IP6ADDR_PORT_TO_SOCKADDR((struct sockaddr_in6*)(void*)(sockaddr), ip_2_ip6(ipaddr), port); \ } else { \ IP4ADDR_PORT_TO_SOCKADDR((struct sockaddr_in*)(void*)(sockaddr), ip_2_ip4(ipaddr), port); \ } } while(0) #define SOCKADDR_TO_IPADDR_PORT(sockaddr, ipaddr, port) sockaddr_to_ipaddr_port(sockaddr, ipaddr, &(port)) #define DOMAIN_TO_NETCONN_TYPE(domain, type) (((domain) == AF_INET) ? \ (type) : (enum netconn_type)((type) | NETCONN_TYPE_IPV6)) #elif LWIP_IPV6 /* LWIP_IPV4 && LWIP_IPV6 */ #define IS_SOCK_ADDR_LEN_VALID(namelen) ((namelen) == sizeof(struct sockaddr_in6)) #define IS_SOCK_ADDR_TYPE_VALID(name) ((name)->sa_family == AF_INET6) #define SOCK_ADDR_TYPE_MATCH(name, sock) 1 #define IPADDR_PORT_TO_SOCKADDR(sockaddr, ipaddr, port) \ IP6ADDR_PORT_TO_SOCKADDR((struct sockaddr_in6*)(void*)(sockaddr), ip_2_ip6(ipaddr), port) #define SOCKADDR_TO_IPADDR_PORT(sockaddr, ipaddr, port) \ SOCKADDR6_TO_IP6ADDR_PORT((const struct sockaddr_in6*)(const void*)(sockaddr), ipaddr, port) #define DOMAIN_TO_NETCONN_TYPE(domain, netconn_type) (netconn_type) #else /*-> LWIP_IPV4: LWIP_IPV4 && LWIP_IPV6 */ #define IS_SOCK_ADDR_LEN_VALID(namelen) ((namelen) == sizeof(struct sockaddr_in)) #define IS_SOCK_ADDR_TYPE_VALID(name) ((name)->sa_family == AF_INET) #define SOCK_ADDR_TYPE_MATCH(name, sock) 1 #define IPADDR_PORT_TO_SOCKADDR(sockaddr, ipaddr, port) \ IP4ADDR_PORT_TO_SOCKADDR((struct sockaddr_in*)(void*)(sockaddr), ip_2_ip4(ipaddr), port) #define SOCKADDR_TO_IPADDR_PORT(sockaddr, ipaddr, port) \ SOCKADDR4_TO_IP4ADDR_PORT((const struct sockaddr_in*)(const void*)(sockaddr), ipaddr, port) #define DOMAIN_TO_NETCONN_TYPE(domain, netconn_type) (netconn_type) #endif /* LWIP_IPV6 */ #define IS_SOCK_ADDR_TYPE_VALID_OR_UNSPEC(name) (((name)->sa_family == AF_UNSPEC) || \ IS_SOCK_ADDR_TYPE_VALID(name)) #define SOCK_ADDR_TYPE_MATCH_OR_UNSPEC(name, sock) (((name)->sa_family == AF_UNSPEC) || \ SOCK_ADDR_TYPE_MATCH(name, sock)) #define IS_SOCK_ADDR_ALIGNED(name) ((((mem_ptr_t)(name)) % 4) == 0) #define LWIP_SOCKOPT_CHECK_OPTLEN(optlen, opttype) do { if ((optlen) < sizeof(opttype)) { return EINVAL; }}while(0) #define LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, optlen, opttype) do { \ LWIP_SOCKOPT_CHECK_OPTLEN(optlen, opttype); \ if ((sock)->conn == NULL) { return EINVAL; } }while(0) #define LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, opttype) do { \ LWIP_SOCKOPT_CHECK_OPTLEN(optlen, opttype); \ if (((sock)->conn == NULL) || ((sock)->conn->pcb.tcp == NULL)) { return EINVAL; } }while(0) #define LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, opttype, netconntype) do { \ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, opttype); \ if (NETCONNTYPE_GROUP(netconn_type((sock)->conn)) != netconntype) { return ENOPROTOOPT; } }while(0) #define LWIP_SETGETSOCKOPT_DATA_VAR_REF(name) API_VAR_REF(name) #define LWIP_SETGETSOCKOPT_DATA_VAR_DECLARE(name) API_VAR_DECLARE(struct lwip_setgetsockopt_data, name) #define LWIP_SETGETSOCKOPT_DATA_VAR_FREE(name) API_VAR_FREE(MEMP_SOCKET_SETGETSOCKOPT_DATA, name) #if LWIP_MPU_COMPATIBLE #define LWIP_SETGETSOCKOPT_DATA_VAR_ALLOC(name, sock) do { \ name = (struct lwip_setgetsockopt_data *)memp_malloc(MEMP_SOCKET_SETGETSOCKOPT_DATA); \ if (name == NULL) { \ sock_set_errno(sock, ENOMEM); \ return -1; \ } }while(0) #else /* LWIP_MPU_COMPATIBLE */ #define LWIP_SETGETSOCKOPT_DATA_VAR_ALLOC(name, sock) #endif /* LWIP_MPU_COMPATIBLE */ #if LWIP_SO_SNDRCVTIMEO_NONSTANDARD #define LWIP_SO_SNDRCVTIMEO_OPTTYPE int #define LWIP_SO_SNDRCVTIMEO_SET(optval, val) (*(int *)(optval) = (val)) #define LWIP_SO_SNDRCVTIMEO_GET_MS(optval) ((s32_t)*(const int*)(optval)) #else #define LWIP_SO_SNDRCVTIMEO_OPTTYPE struct timeval #define LWIP_SO_SNDRCVTIMEO_SET(optval, val) do { \ s32_t loc = (val); \ ((struct timeval *)(optval))->tv_sec = (loc) / 1000U; \ ((struct timeval *)(optval))->tv_usec = ((loc) % 1000U) * 1000U; }while(0) #define LWIP_SO_SNDRCVTIMEO_GET_MS(optval) ((((const struct timeval *)(optval))->tv_sec * 1000U) + (((const struct timeval *)(optval))->tv_usec / 1000U)) #endif #define NUM_SOCKETS MEMP_NUM_NETCONN /** This is overridable for the rare case where more than 255 threads * select on the same socket... */ #ifndef SELWAIT_T #define SELWAIT_T u8_t #endif /** 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 (in fact, all our errnos fit into an u8_t) */ u8_t err; /** counter of how many threads are waiting for this socket using select */ SELWAIT_T select_waiting; }; #if LWIP_NETCONN_SEM_PER_THREAD #define SELECT_SEM_T sys_sem_t* #define SELECT_SEM_PTR(sem) (sem) #else /* LWIP_NETCONN_SEM_PER_THREAD */ #define SELECT_SEM_T sys_sem_t #define SELECT_SEM_PTR(sem) (&(sem)) #endif /* LWIP_NETCONN_SEM_PER_THREAD */ /** 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 */ SELECT_SEM_T sem; }; /** A struct sockaddr replacement that has the same alignment as sockaddr_in/ * sockaddr_in6 if instantiated. */ union sockaddr_aligned { struct sockaddr sa; #if LWIP_IPV6 struct sockaddr_in6 sin6; #endif /* LWIP_IPV6 */ #if LWIP_IPV4 struct sockaddr_in sin; #endif /* LWIP_IPV4 */ }; #if LWIP_IGMP /* Define the number of IPv4 multicast memberships, default is one per socket */ #ifndef LWIP_SOCKET_MAX_MEMBERSHIPS #define LWIP_SOCKET_MAX_MEMBERSHIPS NUM_SOCKETS #endif /* This is to keep track of IP_ADD_MEMBERSHIP calls to drop the membership when a socket is closed */ struct lwip_socket_multicast_pair { /** the socket */ struct lwip_sock* sock; /** the interface address */ ip4_addr_t if_addr; /** the group address */ ip4_addr_t multi_addr; }; struct lwip_socket_multicast_pair socket_ipv4_multicast_memberships[LWIP_SOCKET_MAX_MEMBERSHIPS]; static int lwip_socket_register_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr); static void lwip_socket_unregister_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr); static void lwip_socket_drop_registered_memberships(int s); #endif /* LWIP_IGMP */ /** 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 changed and checked in event_callback to see if it has changed. */ static volatile int select_cb_ctr; #if LWIP_SOCKET_SET_ERRNO #ifndef set_errno #define set_errno(err) do { if (err) { errno = (err); } } while(0) #endif #else /* LWIP_SOCKET_SET_ERRNO */ #define set_errno(err) #endif /* LWIP_SOCKET_SET_ERRNO */ #define sock_set_errno(sk, e) do { \ const int sockerr = (e); \ sk->err = (u8_t)sockerr; \ set_errno(sockerr); \ } while (0) /* Forward declaration of some functions */ static void event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len); #if !LWIP_TCPIP_CORE_LOCKING static void lwip_getsockopt_callback(void *arg); static void lwip_setsockopt_callback(void *arg); #endif static u8_t lwip_getsockopt_impl(int s, int level, int optname, void *optval, socklen_t *optlen); static u8_t lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_t optlen); #if LWIP_IPV4 && LWIP_IPV6 static void sockaddr_to_ipaddr_port(const struct sockaddr* sockaddr, ip_addr_t* ipaddr, u16_t* port) { if ((sockaddr->sa_family) == AF_INET6) { SOCKADDR6_TO_IP6ADDR_PORT((const struct sockaddr_in6*)(const void*)(sockaddr), ipaddr, *port); ipaddr->type = IPADDR_TYPE_V6; } else { SOCKADDR4_TO_IP4ADDR_PORT((const struct sockaddr_in*)(const void*)(sockaddr), ipaddr, *port); ipaddr->type = IPADDR_TYPE_V4; } } #endif /* LWIP_IPV4 && LWIP_IPV6 */ /** LWIP_NETCONN_SEM_PER_THREAD==1: initialize thread-local semaphore */ void lwip_socket_thread_init(void) { netconn_thread_init(); } /** LWIP_NETCONN_SEM_PER_THREAD==1: destroy thread-local semaphore */ void lwip_socket_thread_cleanup(void) { netconn_thread_cleanup(); } /** * 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; s -= LWIP_SOCKET_OFFSET; if ((s < 0) || (s >= NUM_SOCKETS)) { LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): invalid\n", s + LWIP_SOCKET_OFFSET)); set_errno(EBADF); return NULL; } sock = &sockets[s]; if (!sock->conn) { LWIP_DEBUGF(SOCKETS_DEBUG, ("get_socket(%d): not active\n", s + LWIP_SOCKET_OFFSET)); 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) { s -= LWIP_SOCKET_OFFSET; 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 int alloc_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].select_waiting == 0)) { 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 = (NETCONNTYPE_GROUP(newconn->type) == NETCONN_TCP ? (accepted != 0) : 1); sockets[i].errevent = 0; sockets[i].err = 0; return i + LWIP_SOCKET_OFFSET; } 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 void free_socket(struct lwip_sock *sock, int is_tcp) { void *lastdata; lastdata = sock->lastdata; sock->lastdata = NULL; sock->lastoffset = 0; sock->err = 0; /* Protect socket array */ SYS_ARCH_SET(sock->conn, NULL); /* 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! */ int lwip_accept(int s, struct sockaddr *addr, socklen_t *addrlen) { struct lwip_sock *sock, *nsock; struct netconn *newconn; ip_addr_t naddr; u16_t port = 0; int newsock; 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)); set_errno(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)); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { sock_set_errno(sock, EOPNOTSUPP); } else if (err == ERR_CLSD) { sock_set_errno(sock, EINVAL); } else { sock_set_errno(sock, err_to_errno(err)); } return -1; } LWIP_ASSERT("newconn != NULL", newconn != NULL); newsock = alloc_socket(newconn, 1); if (newsock == -1) { netconn_delete(newconn); sock_set_errno(sock, ENFILE); return -1; } LWIP_ASSERT("invalid socket index", (newsock >= LWIP_SOCKET_OFFSET) && (newsock < NUM_SOCKETS + LWIP_SOCKET_OFFSET)); LWIP_ASSERT("newconn->callback == event_callback", newconn->callback == event_callback); nsock = &sockets[newsock - LWIP_SOCKET_OFFSET]; /* 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); /* Note that POSIX only requires us to check addr is non-NULL. addrlen must * not be NULL if addr is valid. */ if (addr != NULL) { union sockaddr_aligned tempaddr; /* 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); free_socket(nsock, 1); sock_set_errno(sock, err_to_errno(err)); return -1; } LWIP_ASSERT("addr valid but addrlen NULL", addrlen != NULL); IPADDR_PORT_TO_SOCKADDR(&tempaddr, &naddr, port); if (*addrlen > tempaddr.sa.sa_len) { *addrlen = tempaddr.sa.sa_len; } MEMCPY(addr, &tempaddr, *addrlen); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d addr=", s, newsock)); ip_addr_debug_print_val(SOCKETS_DEBUG, naddr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", port)); } else { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_accept(%d) returning new sock=%d", s, newsock)); } sock_set_errno(sock, 0); return newsock; } int lwip_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; sock = get_socket(s); if (!sock) { return -1; } if (!SOCK_ADDR_TYPE_MATCH(name, sock)) { /* sockaddr does not match socket type (IPv4/IPv6) */ sock_set_errno(sock, err_to_errno(ERR_VAL)); return -1; } /* check size, family and alignment of 'name' */ LWIP_ERROR("lwip_bind: invalid address", (IS_SOCK_ADDR_LEN_VALID(namelen) && IS_SOCK_ADDR_TYPE_VALID(name) && IS_SOCK_ADDR_ALIGNED(name)), sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); LWIP_UNUSED_ARG(namelen); SOCKADDR_TO_IPADDR_PORT(name, &local_addr, local_port); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_bind(%d, addr=", s)); ip_addr_debug_print_val(SOCKETS_DEBUG, local_addr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", local_port)); #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */ if (IP_IS_V6_VAL(local_addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&local_addr))) { unmap_ipv4_mapped_ipv6(ip_2_ip4(&local_addr), ip_2_ip6(&local_addr)); IP_SET_TYPE_VAL(local_addr, IPADDR_TYPE_V4); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ err = netconn_bind(sock->conn, &local_addr, 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; } int lwip_close(int s) { struct lwip_sock *sock; int is_tcp = 0; err_t err; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_close(%d)\n", s)); sock = get_socket(s); if (!sock) { return -1; } if (sock->conn != NULL) { is_tcp = NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP; } else { LWIP_ASSERT("sock->lastdata == NULL", sock->lastdata == NULL); } #if LWIP_IGMP /* drop all possibly joined IGMP memberships */ lwip_socket_drop_registered_memberships(s); #endif /* LWIP_IGMP */ err = netconn_delete(sock->conn); if (err != ERR_OK) { sock_set_errno(sock, err_to_errno(err)); return -1; } free_socket(sock, is_tcp); set_errno(0); return 0; } int lwip_connect(int s, const struct sockaddr *name, socklen_t namelen) { struct lwip_sock *sock; err_t err; sock = get_socket(s); if (!sock) { return -1; } if (!SOCK_ADDR_TYPE_MATCH_OR_UNSPEC(name, sock)) { /* sockaddr does not match socket type (IPv4/IPv6) */ sock_set_errno(sock, err_to_errno(ERR_VAL)); return -1; } LWIP_UNUSED_ARG(namelen); if (name->sa_family == AF_UNSPEC) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, AF_UNSPEC)\n", s)); err = netconn_disconnect(sock->conn); } else { ip_addr_t remote_addr; u16_t remote_port; /* check size, family and alignment of 'name' */ LWIP_ERROR("lwip_connect: invalid address", IS_SOCK_ADDR_LEN_VALID(namelen) && IS_SOCK_ADDR_TYPE_VALID_OR_UNSPEC(name) && IS_SOCK_ADDR_ALIGNED(name), sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); SOCKADDR_TO_IPADDR_PORT(name, &remote_addr, remote_port); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d, addr=", s)); ip_addr_debug_print_val(SOCKETS_DEBUG, remote_addr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", remote_port)); #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */ if (IP_IS_V6_VAL(remote_addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&remote_addr))) { unmap_ipv4_mapped_ipv6(ip_2_ip4(&remote_addr), ip_2_ip6(&remote_addr)); IP_SET_TYPE_VAL(remote_addr, IPADDR_TYPE_V4); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ err = netconn_connect(sock->conn, &remote_addr, remote_port); } if (err != ERR_OK) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) failed, err=%d\n", s, err)); sock_set_errno(sock, err_to_errno(err)); return -1; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_connect(%d) succeeded\n", s)); sock_set_errno(sock, 0); return 0; } /** * Set a socket into listen mode. * The socket may not have been used for another connection previously. * * @param s the socket to set to listening mode * @param backlog (ATTENTION: needs TCP_LISTEN_BACKLOG=1) * @return 0 on success, non-zero on failure */ int lwip_listen(int s, int backlog) { struct lwip_sock *sock; err_t err; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d, backlog=%d)\n", s, backlog)); sock = get_socket(s); if (!sock) { return -1; } /* limit the "backlog" parameter to fit in an u8_t */ backlog = LWIP_MIN(LWIP_MAX(backlog, 0), 0xff); err = netconn_listen_with_backlog(sock->conn, (u8_t)backlog); if (err != ERR_OK) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_listen(%d) failed, err=%d\n", s, err)); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { sock_set_errno(sock, EOPNOTSUPP); return -1; } sock_set_errno(sock, err_to_errno(err)); return -1; } sock_set_errno(sock, 0); return 0; } int lwip_recvfrom(int s, void *mem, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen) { struct lwip_sock *sock; void *buf = NULL; struct pbuf *p; u16_t buflen, copylen; int off = 0; u8_t done = 0; err_t err; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d, %p, %"SZT_F", 0x%x, ..)\n", s, mem, len, flags)); sock = get_socket(s); if (!sock) { return -1; } do { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: top while sock->lastdata=%p\n", sock->lastdata)); /* Check if there is data left from the last recv operation. */ if (sock->lastdata) { buf = sock->lastdata; } else { /* If this is non-blocking call, then check first */ if (((flags & MSG_DONTWAIT) || netconn_is_nonblocking(sock->conn)) && (sock->rcvevent <= 0)) { if (off > 0) { /* already received data, return that */ sock_set_errno(sock, 0); return off; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): returning EWOULDBLOCK\n", s)); set_errno(EWOULDBLOCK); return -1; } /* No data was left from the previous operation, so we try to get some from the network. */ if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { err = netconn_recv_tcp_pbuf(sock->conn, (struct pbuf **)&buf); } else { err = netconn_recv(sock->conn, (struct netbuf **)&buf); } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: netconn_recv err=%d, netbuf=%p\n", err, buf)); if (err != ERR_OK) { if (off > 0) { if (err == ERR_CLSD) { /* closed but already received data, ensure select gets the FIN, too */ event_callback(sock->conn, NETCONN_EVT_RCVPLUS, 0); } /* already received data, return that */ sock_set_errno(sock, 0); return off; } /* We should really do some error checking here. */ LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): buf == NULL, error is \"%s\"!\n", s, lwip_strerr(err))); sock_set_errno(sock, err_to_errno(err)); if (err == ERR_CLSD) { return 0; } else { return -1; } } LWIP_ASSERT("buf != NULL", buf != NULL); sock->lastdata = buf; } if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { p = (struct pbuf *)buf; } else { p = ((struct netbuf *)buf)->p; } buflen = p->tot_len; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: buflen=%"U16_F" len=%"SZT_F" off=%d sock->lastoffset=%"U16_F"\n", buflen, len, off, sock->lastoffset)); buflen -= sock->lastoffset; if (len > buflen) { copylen = buflen; } else { copylen = (u16_t)len; } /* copy the contents of the received buffer into the supplied memory pointer mem */ pbuf_copy_partial(p, (u8_t*)mem + off, copylen, sock->lastoffset); off += copylen; if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { LWIP_ASSERT("invalid copylen, len would underflow", len >= copylen); len -= copylen; if ((len <= 0) || (p->flags & PBUF_FLAG_PUSH) || (sock->rcvevent <= 0) || ((flags & MSG_PEEK) != 0)) { done = 1; } } else { done = 1; } /* Check to see from where the data was.*/ if (done) { #if !SOCKETS_DEBUG if (from && fromlen) #endif /* !SOCKETS_DEBUG */ { u16_t port; ip_addr_t tmpaddr; ip_addr_t *fromaddr; union sockaddr_aligned saddr; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom(%d): addr=", s)); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { fromaddr = &tmpaddr; netconn_getaddr(sock->conn, fromaddr, &port, 0); } else { port = netbuf_fromport((struct netbuf *)buf); fromaddr = netbuf_fromaddr((struct netbuf *)buf); } #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Map IPv4 addresses to IPv4 mapped IPv6 */ if (NETCONNTYPE_ISIPV6(netconn_type(sock->conn)) && IP_IS_V4(fromaddr)) { ip4_2_ipv4_mapped_ipv6(ip_2_ip6(fromaddr), ip_2_ip4(fromaddr)); IP_SET_TYPE(fromaddr, IPADDR_TYPE_V6); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ IPADDR_PORT_TO_SOCKADDR(&saddr, fromaddr, port); ip_addr_debug_print(SOCKETS_DEBUG, fromaddr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F" len=%d\n", port, off)); #if SOCKETS_DEBUG if (from && fromlen) #endif /* SOCKETS_DEBUG */ { if (*fromlen > saddr.sa.sa_len) { *fromlen = saddr.sa.sa_len; } MEMCPY(from, &saddr, *fromlen); } } } /* If we don't peek the incoming message... */ if ((flags & MSG_PEEK) == 0) { /* If this is a TCP socket, check if there is data left in the buffer. If so, it should be saved in the sock structure for next time around. */ if ((NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) && (buflen - copylen > 0)) { sock->lastdata = buf; sock->lastoffset += copylen; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: lastdata now netbuf=%p\n", buf)); } else { sock->lastdata = NULL; sock->lastoffset = 0; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_recvfrom: deleting netbuf=%p\n", buf)); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { pbuf_free((struct pbuf *)buf); } else { netbuf_delete((struct netbuf *)buf); } buf = NULL; } } } while (!done); sock_set_errno(sock, 0); return off; } int lwip_read(int s, void *mem, size_t len) { return lwip_recvfrom(s, mem, len, 0, NULL, NULL); } int lwip_recv(int s, void *mem, size_t len, int flags) { return lwip_recvfrom(s, mem, len, flags, NULL, NULL); } int lwip_send(int s, const void *data, size_t size, int flags) { struct lwip_sock *sock; err_t err; u8_t write_flags; size_t written; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d, data=%p, size=%"SZT_F", flags=0x%x)\n", s, data, size, flags)); sock = get_socket(s); if (!sock) { return -1; } if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { #if (LWIP_UDP || LWIP_RAW) return lwip_sendto(s, data, size, flags, NULL, 0); #else /* (LWIP_UDP || LWIP_RAW) */ sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1; #endif /* (LWIP_UDP || LWIP_RAW) */ } write_flags = NETCONN_COPY | ((flags & MSG_MORE) ? NETCONN_MORE : 0) | ((flags & MSG_DONTWAIT) ? NETCONN_DONTBLOCK : 0); written = 0; err = netconn_write_partly(sock->conn, data, size, write_flags, &written); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_send(%d) err=%d written=%"SZT_F"\n", s, err, written)); sock_set_errno(sock, err_to_errno(err)); return (err == ERR_OK ? (int)written : -1); } int lwip_sendmsg(int s, const struct msghdr *msg, int flags) { struct lwip_sock *sock; int i; #if LWIP_TCP u8_t write_flags; size_t written; #endif int size = 0; err_t err = ERR_OK; sock = get_socket(s); if (!sock) { return -1; } LWIP_ERROR("lwip_sendmsg: invalid msghdr", msg != NULL, sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); LWIP_UNUSED_ARG(msg->msg_control); LWIP_UNUSED_ARG(msg->msg_controllen); LWIP_UNUSED_ARG(msg->msg_flags); LWIP_ERROR("lwip_sendmsg: invalid msghdr iov", (msg->msg_iov != NULL && msg->msg_iovlen != 0), sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { #if LWIP_TCP write_flags = NETCONN_COPY | ((flags & MSG_MORE) ? NETCONN_MORE : 0) | ((flags & MSG_DONTWAIT) ? NETCONN_DONTBLOCK : 0); for (i = 0; i < msg->msg_iovlen; i++) { u8_t apiflags = write_flags; if (i + 1 < msg->msg_iovlen) { apiflags |= NETCONN_MORE; } written = 0; err = netconn_write_partly(sock->conn, msg->msg_iov[i].iov_base, msg->msg_iov[i].iov_len, write_flags, &written); if (err == ERR_OK) { size += written; /* check that the entire IO vector was accepected, if not return a partial write */ if (written != msg->msg_iov[i].iov_len) break; } /* none of this IO vector was accepted, but previous was, return partial write and conceal ERR_WOULDBLOCK */ else if (err == ERR_WOULDBLOCK && size > 0) { err = ERR_OK; /* let ERR_WOULDBLOCK persist on the netconn since we are returning ERR_OK */ break; } else { size = -1; break; } } sock_set_errno(sock, err_to_errno(err)); return size; #else /* LWIP_TCP */ sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1; #endif /* LWIP_TCP */ } /* else, UDP and RAW NETCONNs */ #if LWIP_UDP || LWIP_RAW { struct netbuf *chain_buf; LWIP_UNUSED_ARG(flags); LWIP_ERROR("lwip_sendmsg: invalid msghdr name", (((msg->msg_name == NULL) && (msg->msg_namelen == 0)) || IS_SOCK_ADDR_LEN_VALID(msg->msg_namelen)) , sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); /* initialize chain buffer with destination */ chain_buf = netbuf_new(); if (!chain_buf) { sock_set_errno(sock, err_to_errno(ERR_MEM)); return -1; } if (msg->msg_name) { u16_t remote_port; SOCKADDR_TO_IPADDR_PORT((const struct sockaddr *)msg->msg_name, &chain_buf->addr, remote_port); netbuf_fromport(chain_buf) = remote_port; } #if LWIP_NETIF_TX_SINGLE_PBUF for (i = 0; i < msg->msg_iovlen; i++) { size += msg->msg_iov[i].iov_len; } /* Allocate a new netbuf and copy the data into it. */ if (netbuf_alloc(chain_buf, (u16_t)size) == NULL) { err = ERR_MEM; } else { /* flatten the IO vectors */ size_t offset = 0; for (i = 0; i < msg->msg_iovlen; i++) { MEMCPY(&((u8_t*)chain_buf->p->payload)[offset], msg->msg_iov[i].iov_base, msg->msg_iov[i].iov_len); offset += msg->msg_iov[i].iov_len; } #if LWIP_CHECKSUM_ON_COPY { /* This can be improved by using LWIP_CHKSUM_COPY() and aggregating the checksum for each IO vector */ u16_t chksum = ~inet_chksum_pbuf(chain_buf->p); netbuf_set_chksum(chain_buf, chksum); } #endif /* LWIP_CHECKSUM_ON_COPY */ err = ERR_OK; } #else /* LWIP_NETIF_TX_SINGLE_PBUF */ /* create a chained netbuf from the IO vectors. NOTE: we assemble a pbuf chain manually to avoid having to allocate, chain, and delete a netbuf for each iov */ for (i = 0; i < msg->msg_iovlen; i++) { struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_REF); if (p == NULL) { err = ERR_MEM; /* let netbuf_delete() cleanup chain_buf */ break; } p->payload = msg->msg_iov[i].iov_base; LWIP_ASSERT("iov_len < u16_t", msg->msg_iov[i].iov_len <= 0xFFFF); p->len = p->tot_len = (u16_t)msg->msg_iov[i].iov_len; /* netbuf empty, add new pbuf */ if (chain_buf->p == NULL) { chain_buf->p = chain_buf->ptr = p; /* add pbuf to existing pbuf chain */ } else { pbuf_cat(chain_buf->p, p); } } /* save size of total chain */ if (err == ERR_OK) { size = netbuf_len(chain_buf); } #endif /* LWIP_NETIF_TX_SINGLE_PBUF */ if (err == ERR_OK) { #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */ if (IP_IS_V6_VAL(chain_buf->addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&chain_buf->addr))) { unmap_ipv4_mapped_ipv6(ip_2_ip4(&chain_buf->addr), ip_2_ip6(&chain_buf->addr)); IP_SET_TYPE_VAL(chain_buf->addr, IPADDR_TYPE_V4); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ /* send the data */ err = netconn_send(sock->conn, chain_buf); } /* deallocated the buffer */ netbuf_delete(chain_buf); sock_set_errno(sock, err_to_errno(err)); return (err == ERR_OK ? size : -1); } #else /* LWIP_UDP || LWIP_RAW */ sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1; #endif /* LWIP_UDP || LWIP_RAW */ } int lwip_sendto(int s, const void *data, size_t size, int flags, const struct sockaddr *to, socklen_t tolen) { struct lwip_sock *sock; err_t err; u16_t short_size; u16_t remote_port; struct netbuf buf; sock = get_socket(s); if (!sock) { return -1; } if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) == NETCONN_TCP) { #if LWIP_TCP return lwip_send(s, data, size, flags); #else /* LWIP_TCP */ LWIP_UNUSED_ARG(flags); sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1; #endif /* LWIP_TCP */ } /* @todo: split into multiple sendto's? */ LWIP_ASSERT("lwip_sendto: size must fit in u16_t", size <= 0xffff); short_size = (u16_t)size; LWIP_ERROR("lwip_sendto: invalid address", (((to == NULL) && (tolen == 0)) || (IS_SOCK_ADDR_LEN_VALID(tolen) && IS_SOCK_ADDR_TYPE_VALID(to) && IS_SOCK_ADDR_ALIGNED(to))), sock_set_errno(sock, err_to_errno(ERR_ARG)); return -1;); LWIP_UNUSED_ARG(tolen); /* initialize a buffer */ buf.p = buf.ptr = NULL; #if LWIP_CHECKSUM_ON_COPY buf.flags = 0; #endif /* LWIP_CHECKSUM_ON_COPY */ if (to) { SOCKADDR_TO_IPADDR_PORT(to, &buf.addr, remote_port); } else { remote_port = 0; ip_addr_set_any(NETCONNTYPE_ISIPV6(netconn_type(sock->conn)), &buf.addr); } netbuf_fromport(&buf) = remote_port; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_sendto(%d, data=%p, short_size=%"U16_F", flags=0x%x to=", s, data, short_size, flags)); ip_addr_debug_print(SOCKETS_DEBUG, &buf.addr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F"\n", remote_port)); /* make the buffer point to the data that should be sent */ #if LWIP_NETIF_TX_SINGLE_PBUF /* Allocate a new netbuf and copy the data into it. */ if (netbuf_alloc(&buf, short_size) == NULL) { err = ERR_MEM; } else { #if LWIP_CHECKSUM_ON_COPY if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_RAW) { u16_t chksum = LWIP_CHKSUM_COPY(buf.p->payload, data, short_size); netbuf_set_chksum(&buf, chksum); } else #endif /* LWIP_CHECKSUM_ON_COPY */ { MEMCPY(buf.p->payload, data, short_size); } err = ERR_OK; } #else /* LWIP_NETIF_TX_SINGLE_PBUF */ err = netbuf_ref(&buf, data, short_size); #endif /* LWIP_NETIF_TX_SINGLE_PBUF */ if (err == ERR_OK) { #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Unmap IPv4 mapped IPv6 addresses */ if (IP_IS_V6_VAL(buf.addr) && ip6_addr_isipv4mappedipv6(ip_2_ip6(&buf.addr))) { unmap_ipv4_mapped_ipv6(ip_2_ip4(&buf.addr), ip_2_ip6(&buf.addr)); IP_SET_TYPE_VAL(buf.addr, IPADDR_TYPE_V4); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ /* send the data */ err = netconn_send(sock->conn, &buf); } /* deallocated the buffer */ netbuf_free(&buf); sock_set_errno(sock, err_to_errno(err)); return (err == ERR_OK ? short_size : -1); } int lwip_socket(int domain, int type, int protocol) { struct netconn *conn; int i; LWIP_UNUSED_ARG(domain); /* @todo: check this */ /* create a netconn */ switch (type) { case SOCK_RAW: conn = netconn_new_with_proto_and_callback(DOMAIN_TO_NETCONN_TYPE(domain, NETCONN_RAW), (u8_t)protocol, event_callback); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_RAW, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); break; case SOCK_DGRAM: conn = netconn_new_with_callback(DOMAIN_TO_NETCONN_TYPE(domain, ((protocol == IPPROTO_UDPLITE) ? NETCONN_UDPLITE : NETCONN_UDP)) , event_callback); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_DGRAM, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); break; case SOCK_STREAM: conn = netconn_new_with_callback(DOMAIN_TO_NETCONN_TYPE(domain, NETCONN_TCP), event_callback); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%s, SOCK_STREAM, %d) = ", domain == PF_INET ? "PF_INET" : "UNKNOWN", protocol)); break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_socket(%d, %d/UNKNOWN, %d) = -1\n", domain, type, protocol)); set_errno(EINVAL); return -1; } if (!conn) { LWIP_DEBUGF(SOCKETS_DEBUG, ("-1 / ENOBUFS (could not create netconn)\n")); set_errno(ENOBUFS); return -1; } i = alloc_socket(conn, 0); if (i == -1) { netconn_delete(conn); set_errno(ENFILE); return -1; } conn->socket = i; LWIP_DEBUGF(SOCKETS_DEBUG, ("%d\n", i)); set_errno(0); return i; } int lwip_write(int s, const void *data, size_t size) { return lwip_send(s, data, size, 0); } int lwip_writev(int s, const struct iovec *iov, int iovcnt) { struct msghdr msg; msg.msg_name = NULL; msg.msg_namelen = 0; /* Hack: we have to cast via number to cast from 'const' pointer to non-const. Blame the opengroup standard for this inconsistency. */ msg.msg_iov = LWIP_CONST_CAST(struct iovec *, iov); msg.msg_iovlen = iovcnt; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_flags = 0; return lwip_sendmsg(s, &msg, 0); } /** * Go through the readset and writeset lists and see which socket of the sockets * set in the sets has events. On return, readset, writeset and exceptset have * the sockets enabled that had events. * * @param maxfdp1 the highest socket index in the sets * @param readset_in set of sockets to check for read events * @param writeset_in set of sockets to check for write events * @param exceptset_in set of sockets to check for error events * @param readset_out set of sockets that had read events * @param writeset_out set of sockets that had write events * @param exceptset_out set os sockets that had error events * @return number of sockets that had events (read/write/exception) (>= 0) */ static int lwip_selscan(int maxfdp1, fd_set *readset_in, fd_set *writeset_in, fd_set *exceptset_in, fd_set *readset_out, fd_set *writeset_out, fd_set *exceptset_out) { int i, nready = 0; fd_set lreadset, lwriteset, lexceptset; struct lwip_sock *sock; SYS_ARCH_DECL_PROTECT(lev); FD_ZERO(&lreadset); FD_ZERO(&lwriteset); FD_ZERO(&lexceptset); /* Go through each socket in each list to count number of sockets which currently match */ for (i = LWIP_SOCKET_OFFSET; i < maxfdp1; i++) { /* if this FD is not in the set, continue */ if (!(readset_in && FD_ISSET(i, readset_in)) && !(writeset_in && FD_ISSET(i, writeset_in)) && !(exceptset_in && FD_ISSET(i, exceptset_in))) { continue; } /* First get the socket's status (protected)... */ SYS_ARCH_PROTECT(lev); sock = tryget_socket(i); if (sock != NULL) { void* lastdata = sock->lastdata; s16_t rcvevent = sock->rcvevent; u16_t sendevent = sock->sendevent; u16_t errevent = sock->errevent; SYS_ARCH_UNPROTECT(lev); /* ... then examine it: */ /* See if netconn of this socket is ready for read */ if (readset_in && FD_ISSET(i, readset_in) && ((lastdata != NULL) || (rcvevent > 0))) { FD_SET(i, &lreadset); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for reading\n", i)); nready++; } /* See if netconn of this socket is ready for write */ if (writeset_in && FD_ISSET(i, writeset_in) && (sendevent != 0)) { FD_SET(i, &lwriteset); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for writing\n", i)); nready++; } /* See if netconn of this socket had an error */ if (exceptset_in && FD_ISSET(i, exceptset_in) && (errevent != 0)) { FD_SET(i, &lexceptset); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_selscan: fd=%d ready for exception\n", i)); nready++; } } else { SYS_ARCH_UNPROTECT(lev); /* continue on to next FD in list */ } } /* copy local sets to the ones provided as arguments */ *readset_out = lreadset; *writeset_out = lwriteset; *exceptset_out = lexceptset; LWIP_ASSERT("nready >= 0", nready >= 0); return nready; } int lwip_select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout) { u32_t waitres = 0; int nready; fd_set lreadset, lwriteset, lexceptset; u32_t msectimeout; struct lwip_select_cb select_cb; int i; int maxfdp2; #if LWIP_NETCONN_SEM_PER_THREAD int waited = 0; #endif SYS_ARCH_DECL_PROTECT(lev); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select(%d, %p, %p, %p, tvsec=%"S32_F" tvusec=%"S32_F")\n", maxfdp1, (void *)readset, (void *) writeset, (void *) exceptset, timeout ? (s32_t)timeout->tv_sec : (s32_t)-1, timeout ? (s32_t)timeout->tv_usec : (s32_t)-1)); /* Go through each socket in each list to count number of sockets which currently match */ nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); /* If we don't have any current events, then suspend if we are supposed to */ if (!nready) { if (timeout && timeout->tv_sec == 0 && timeout->tv_usec == 0) { LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: no timeout, returning 0\n")); /* This is OK as the local fdsets are empty and nready is zero, or we would have returned earlier. */ goto return_copy_fdsets; } /* None ready: add our semaphore to list: We don't actually need any dynamic memory. Our entry on the list is only valid while we are in this function, so it's ok to use local variables. */ select_cb.next = NULL; select_cb.prev = NULL; select_cb.readset = readset; select_cb.writeset = writeset; select_cb.exceptset = exceptset; select_cb.sem_signalled = 0; #if LWIP_NETCONN_SEM_PER_THREAD select_cb.sem = LWIP_NETCONN_THREAD_SEM_GET(); #else /* LWIP_NETCONN_SEM_PER_THREAD */ if (sys_sem_new(&select_cb.sem, 0) != ERR_OK) { /* failed to create semaphore */ set_errno(ENOMEM); return -1; } #endif /* LWIP_NETCONN_SEM_PER_THREAD */ /* Protect the select_cb_list */ SYS_ARCH_PROTECT(lev); /* Put this select_cb on top of list */ select_cb.next = select_cb_list; if (select_cb_list != NULL) { select_cb_list->prev = &select_cb; } select_cb_list = &select_cb; /* Increasing this counter tells event_callback that the list has changed. */ select_cb_ctr++; /* Now we can safely unprotect */ SYS_ARCH_UNPROTECT(lev); /* Increase select_waiting for each socket we are interested in */ maxfdp2 = maxfdp1; for (i = LWIP_SOCKET_OFFSET; i < maxfdp1; i++) { if ((readset && FD_ISSET(i, readset)) || (writeset && FD_ISSET(i, writeset)) || (exceptset && FD_ISSET(i, exceptset))) { struct lwip_sock *sock; SYS_ARCH_PROTECT(lev); sock = tryget_socket(i); if (sock != NULL) { sock->select_waiting++; LWIP_ASSERT("sock->select_waiting > 0", sock->select_waiting > 0); } else { /* Not a valid socket */ nready = -1; maxfdp2 = i; SYS_ARCH_UNPROTECT(lev); break; } SYS_ARCH_UNPROTECT(lev); } } if (nready >= 0) { /* Call lwip_selscan again: there could have been events between the last scan (without us on the list) and putting us on the list! */ nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); if (!nready) { /* Still none ready, just wait to be woken */ if (timeout == 0) { /* Wait forever */ msectimeout = 0; } else { msectimeout = ((timeout->tv_sec * 1000) + ((timeout->tv_usec + 500)/1000)); if (msectimeout == 0) { /* Wait 1ms at least (0 means wait forever) */ msectimeout = 1; } } waitres = sys_arch_sem_wait(SELECT_SEM_PTR(select_cb.sem), msectimeout); #if LWIP_NETCONN_SEM_PER_THREAD waited = 1; #endif } } /* Decrease select_waiting for each socket we are interested in */ for (i = LWIP_SOCKET_OFFSET; i < maxfdp2; i++) { if ((readset && FD_ISSET(i, readset)) || (writeset && FD_ISSET(i, writeset)) || (exceptset && FD_ISSET(i, exceptset))) { struct lwip_sock *sock; SYS_ARCH_PROTECT(lev); sock = tryget_socket(i); if (sock != NULL) { /* for now, handle select_waiting==0... */ LWIP_ASSERT("sock->select_waiting > 0", sock->select_waiting > 0); if (sock->select_waiting > 0) { sock->select_waiting--; } } else { /* Not a valid socket */ nready = -1; } SYS_ARCH_UNPROTECT(lev); } } /* Take us off the list */ SYS_ARCH_PROTECT(lev); if (select_cb.next != NULL) { select_cb.next->prev = select_cb.prev; } if (select_cb_list == &select_cb) { LWIP_ASSERT("select_cb.prev == NULL", select_cb.prev == NULL); select_cb_list = select_cb.next; } else { LWIP_ASSERT("select_cb.prev != NULL", select_cb.prev != NULL); select_cb.prev->next = select_cb.next; } /* Increasing this counter tells event_callback that the list has changed. */ select_cb_ctr++; SYS_ARCH_UNPROTECT(lev); #if LWIP_NETCONN_SEM_PER_THREAD if (select_cb.sem_signalled && (!waited || (waitres == SYS_ARCH_TIMEOUT))) { /* don't leave the thread-local semaphore signalled */ sys_arch_sem_wait(select_cb.sem, 1); } #else /* LWIP_NETCONN_SEM_PER_THREAD */ sys_sem_free(&select_cb.sem); #endif /* LWIP_NETCONN_SEM_PER_THREAD */ if (nready < 0) { /* This happens when a socket got closed while waiting */ set_errno(EBADF); return -1; } if (waitres == SYS_ARCH_TIMEOUT) { /* Timeout */ LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: timeout expired\n")); /* This is OK as the local fdsets are empty and nready is zero, or we would have returned earlier. */ goto return_copy_fdsets; } /* See what's set */ nready = lwip_selscan(maxfdp1, readset, writeset, exceptset, &lreadset, &lwriteset, &lexceptset); } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_select: nready=%d\n", nready)); return_copy_fdsets: set_errno(0); if (readset) { *readset = lreadset; } if (writeset) { *writeset = lwriteset; } if (exceptset) { *exceptset = lexceptset; } return nready; } /** * Callback registered in the netconn layer for each socket-netconn. * Processes recvevent (data available) and wakes up tasks waiting for select. */ static void event_callback(struct netconn *conn, enum netconn_evt evt, u16_t len) { int s; struct lwip_sock *sock; struct lwip_select_cb *scb; int last_select_cb_ctr; SYS_ARCH_DECL_PROTECT(lev); LWIP_UNUSED_ARG(len); /* Get socket */ if (conn) { s = conn->socket; if (s < 0) { /* Data comes in right away after an accept, even though * the server task might not have created a new socket yet. * Just count down (or up) if that's the case and we * will use the data later. Note that only receive events * can happen before the new socket is set up. */ SYS_ARCH_PROTECT(lev); if (conn->socket < 0) { if (evt == NETCONN_EVT_RCVPLUS) { conn->socket--; } SYS_ARCH_UNPROTECT(lev); return; } s = conn->socket; SYS_ARCH_UNPROTECT(lev); } sock = get_socket(s); if (!sock) { return; } } else { return; } SYS_ARCH_PROTECT(lev); /* Set event as required */ switch (evt) { case NETCONN_EVT_RCVPLUS: sock->rcvevent++; break; case NETCONN_EVT_RCVMINUS: sock->rcvevent--; break; case NETCONN_EVT_SENDPLUS: sock->sendevent = 1; break; case NETCONN_EVT_SENDMINUS: sock->sendevent = 0; break; case NETCONN_EVT_ERROR: sock->errevent = 1; break; default: LWIP_ASSERT("unknown event", 0); break; } if (sock->select_waiting == 0) { /* noone is waiting for this socket, no need to check select_cb_list */ SYS_ARCH_UNPROTECT(lev); return; } /* Now decide if anyone is waiting for this socket */ /* NOTE: This code goes through the select_cb_list list multiple times ONLY IF a select was actually waiting. We go through the list the number of waiting select calls + 1. This list is expected to be small. */ /* At this point, SYS_ARCH is still protected! */ again: for (scb = select_cb_list; scb != NULL; scb = scb->next) { /* remember the state of select_cb_list to detect changes */ last_select_cb_ctr = select_cb_ctr; if (scb->sem_signalled == 0) { /* semaphore not signalled yet */ int do_signal = 0; /* Test this select call for our socket */ if (sock->rcvevent > 0) { if (scb->readset && FD_ISSET(s, scb->readset)) { do_signal = 1; } } if (sock->sendevent != 0) { if (!do_signal && scb->writeset && FD_ISSET(s, scb->writeset)) { do_signal = 1; } } if (sock->errevent != 0) { if (!do_signal && scb->exceptset && FD_ISSET(s, scb->exceptset)) { do_signal = 1; } } if (do_signal) { scb->sem_signalled = 1; /* Don't call SYS_ARCH_UNPROTECT() before signaling the semaphore, as this might lead to the select thread taking itself off the list, invalidating the semaphore. */ sys_sem_signal(SELECT_SEM_PTR(scb->sem)); } } /* unlock interrupts with each step */ SYS_ARCH_UNPROTECT(lev); /* this makes sure interrupt protection time is short */ SYS_ARCH_PROTECT(lev); if (last_select_cb_ctr != select_cb_ctr) { /* someone has changed select_cb_list, restart at the beginning */ goto again; } } SYS_ARCH_UNPROTECT(lev); } /** * Close one end of a full-duplex connection. */ int lwip_shutdown(int s, int how) { struct lwip_sock *sock; err_t err; u8_t shut_rx = 0, shut_tx = 0; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_shutdown(%d, how=%d)\n", s, how)); sock = get_socket(s); if (!sock) { return -1; } if (sock->conn != NULL) { if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { sock_set_errno(sock, EOPNOTSUPP); return -1; } } else { sock_set_errno(sock, ENOTCONN); return -1; } if (how == SHUT_RD) { shut_rx = 1; } else if (how == SHUT_WR) { shut_tx = 1; } else if (how == SHUT_RDWR) { shut_rx = 1; shut_tx = 1; } else { sock_set_errno(sock, EINVAL); return -1; } err = netconn_shutdown(sock->conn, shut_rx, shut_tx); sock_set_errno(sock, err_to_errno(err)); return (err == ERR_OK ? 0 : -1); } static int lwip_getaddrname(int s, struct sockaddr *name, socklen_t *namelen, u8_t local) { struct lwip_sock *sock; union sockaddr_aligned saddr; ip_addr_t naddr; u16_t port; err_t err; sock = get_socket(s); if (!sock) { return -1; } /* get the IP address and port */ err = netconn_getaddr(sock->conn, &naddr, &port, local); if (err != ERR_OK) { sock_set_errno(sock, err_to_errno(err)); return -1; } #if LWIP_IPV4 && LWIP_IPV6 /* Dual-stack: Map IPv4 addresses to IPv4 mapped IPv6 */ if (NETCONNTYPE_ISIPV6(netconn_type(sock->conn)) && IP_IS_V4_VAL(naddr)) { ip4_2_ipv4_mapped_ipv6(ip_2_ip6(&naddr), ip_2_ip4(&naddr)); IP_SET_TYPE_VAL(naddr, IPADDR_TYPE_V6); } #endif /* LWIP_IPV4 && LWIP_IPV6 */ IPADDR_PORT_TO_SOCKADDR(&saddr, &naddr, port); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getaddrname(%d, addr=", s)); ip_addr_debug_print_val(SOCKETS_DEBUG, naddr); LWIP_DEBUGF(SOCKETS_DEBUG, (" port=%"U16_F")\n", port)); if (*namelen > saddr.sa.sa_len) { *namelen = saddr.sa.sa_len; } MEMCPY(name, &saddr, *namelen); sock_set_errno(sock, 0); return 0; } int lwip_getpeername(int s, struct sockaddr *name, socklen_t *namelen) { return lwip_getaddrname(s, name, namelen, 0); } int lwip_getsockname(int s, struct sockaddr *name, socklen_t *namelen) { return lwip_getaddrname(s, name, namelen, 1); } int lwip_getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen) { u8_t err; struct lwip_sock *sock = get_socket(s); #if !LWIP_TCPIP_CORE_LOCKING LWIP_SETGETSOCKOPT_DATA_VAR_DECLARE(data); #endif /* !LWIP_TCPIP_CORE_LOCKING */ if (!sock) { return -1; } if ((NULL == optval) || (NULL == optlen)) { sock_set_errno(sock, EFAULT); return -1; } #if LWIP_TCPIP_CORE_LOCKING /* core-locking can just call the -impl function */ LOCK_TCPIP_CORE(); err = lwip_getsockopt_impl(s, level, optname, optval, optlen); UNLOCK_TCPIP_CORE(); #else /* LWIP_TCPIP_CORE_LOCKING */ #if LWIP_MPU_COMPATIBLE /* MPU_COMPATIBLE copies the optval data, so check for max size here */ if (*optlen > LWIP_SETGETSOCKOPT_MAXOPTLEN) { sock_set_errno(sock, ENOBUFS); return -1; } #endif /* LWIP_MPU_COMPATIBLE */ LWIP_SETGETSOCKOPT_DATA_VAR_ALLOC(data, sock); LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).s = s; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).level = level; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optname = optname; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optlen = *optlen; #if !LWIP_MPU_COMPATIBLE LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optval.p = optval; #endif /* !LWIP_MPU_COMPATIBLE */ LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).err = 0; #if LWIP_NETCONN_SEM_PER_THREAD LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem = LWIP_NETCONN_THREAD_SEM_GET(); #else LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem = &sock->conn->op_completed; #endif err = tcpip_callback(lwip_getsockopt_callback, &LWIP_SETGETSOCKOPT_DATA_VAR_REF(data)); if (err != ERR_OK) { LWIP_SETGETSOCKOPT_DATA_VAR_FREE(data); sock_set_errno(sock, err_to_errno(err)); return -1; } sys_arch_sem_wait((sys_sem_t*)(LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem), 0); /* write back optlen and optval */ *optlen = LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optlen; #if LWIP_MPU_COMPATIBLE MEMCPY(optval, LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optval, LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optlen); #endif /* LWIP_MPU_COMPATIBLE */ /* maybe lwip_getsockopt_internal has changed err */ err = LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).err; LWIP_SETGETSOCKOPT_DATA_VAR_FREE(data); #endif /* LWIP_TCPIP_CORE_LOCKING */ sock_set_errno(sock, err); return err ? -1 : 0; } #if !LWIP_TCPIP_CORE_LOCKING /** lwip_getsockopt_callback: only used without CORE_LOCKING * to get into the tcpip_thread */ static void lwip_getsockopt_callback(void *arg) { struct lwip_setgetsockopt_data *data; LWIP_ASSERT("arg != NULL", arg != NULL); data = (struct lwip_setgetsockopt_data*)arg; data->err = lwip_getsockopt_impl(data->s, data->level, data->optname, #if LWIP_MPU_COMPATIBLE data->optval, #else /* LWIP_MPU_COMPATIBLE */ data->optval.p, #endif /* LWIP_MPU_COMPATIBLE */ &data->optlen); sys_sem_signal((sys_sem_t*)(data->completed_sem)); } #endif /* LWIP_TCPIP_CORE_LOCKING */ /** lwip_getsockopt_impl: the actual implementation of getsockopt: * same argument as lwip_getsockopt, either called directly or through callback */ static u8_t lwip_getsockopt_impl(int s, int level, int optname, void *optval, socklen_t *optlen) { u8_t err = 0; struct lwip_sock *sock = tryget_socket(s); if (!sock) { return EBADF; } switch (level) { /* Level: SOL_SOCKET */ case SOL_SOCKET: switch (optname) { #if LWIP_TCP case SO_ACCEPTCONN: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, int); if (NETCONNTYPE_GROUP(sock->conn->type) != NETCONN_TCP) { return ENOPROTOOPT; } if ((sock->conn->pcb.tcp != NULL) && (sock->conn->pcb.tcp->state == LISTEN)) { *(int*)optval = 1; } else { *(int*)optval = 0; } break; #endif /* LWIP_TCP */ /* The option flags */ case SO_BROADCAST: case SO_KEEPALIVE: #if SO_REUSE case SO_REUSEADDR: #endif /* SO_REUSE */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, int); *(int*)optval = ip_get_option(sock->conn->pcb.ip, optname); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, optname=0x%x, ..) = %s\n", s, optname, (*(int*)optval?"on":"off"))); break; case SO_TYPE: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, int); switch (NETCONNTYPE_GROUP(netconn_type(sock->conn))) { case NETCONN_RAW: *(int*)optval = SOCK_RAW; break; case NETCONN_TCP: *(int*)optval = SOCK_STREAM; break; case NETCONN_UDP: *(int*)optval = SOCK_DGRAM; break; default: /* unrecognized socket type */ *(int*)optval = netconn_type(sock->conn); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE): unrecognized socket type %d\n", s, *(int *)optval)); } /* switch (netconn_type(sock->conn)) */ LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_TYPE) = %d\n", s, *(int *)optval)); break; case SO_ERROR: LWIP_SOCKOPT_CHECK_OPTLEN(*optlen, int); /* only overwrite ERR_OK or temporary errors */ if (((sock->err == 0) || (sock->err == EINPROGRESS)) && (sock->conn != NULL)) { sock_set_errno(sock, err_to_errno(sock->conn->last_err)); } *(int *)optval = (sock->err == 0xFF ? (int)-1 : (int)sock->err); sock->err = 0; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, SO_ERROR) = %d\n", s, *(int *)optval)); break; #if LWIP_SO_SNDTIMEO case SO_SNDTIMEO: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, LWIP_SO_SNDRCVTIMEO_OPTTYPE); LWIP_SO_SNDRCVTIMEO_SET(optval, netconn_get_sendtimeout(sock->conn)); break; #endif /* LWIP_SO_SNDTIMEO */ #if LWIP_SO_RCVTIMEO case SO_RCVTIMEO: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, LWIP_SO_SNDRCVTIMEO_OPTTYPE); LWIP_SO_SNDRCVTIMEO_SET(optval, netconn_get_recvtimeout(sock->conn)); break; #endif /* LWIP_SO_RCVTIMEO */ #if LWIP_SO_RCVBUF case SO_RCVBUF: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, int); *(int *)optval = netconn_get_recvbufsize(sock->conn); break; #endif /* LWIP_SO_RCVBUF */ #if LWIP_SO_LINGER case SO_LINGER: { s16_t conn_linger; struct linger* linger = (struct linger*)optval; LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, struct linger); conn_linger = sock->conn->linger; if (conn_linger >= 0) { linger->l_onoff = 1; linger->l_linger = (int)conn_linger; } else { linger->l_onoff = 0; linger->l_linger = 0; } } break; #endif /* LWIP_SO_LINGER */ #if LWIP_UDP case SO_NO_CHECK: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, *optlen, int, NETCONN_UDP); #if LWIP_UDPLITE if ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0) { /* this flag is only available for UDP, not for UDP lite */ return EAFNOSUPPORT; } #endif /* LWIP_UDPLITE */ *(int*)optval = (udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_NOCHKSUM) ? 1 : 0; break; #endif /* LWIP_UDP*/ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; /* Level: IPPROTO_IP */ case IPPROTO_IP: switch (optname) { case IP_TTL: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, int); *(int*)optval = sock->conn->pcb.ip->ttl; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TTL) = %d\n", s, *(int *)optval)); break; case IP_TOS: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, int); *(int*)optval = sock->conn->pcb.ip->tos; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_TOS) = %d\n", s, *(int *)optval)); break; #if LWIP_MULTICAST_TX_OPTIONS case IP_MULTICAST_TTL: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, u8_t); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_UDP) { return ENOPROTOOPT; } *(u8_t*)optval = udp_get_multicast_ttl(sock->conn->pcb.udp); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_TTL) = %d\n", s, *(int *)optval)); break; case IP_MULTICAST_IF: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, struct in_addr); if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_UDP) { return ENOPROTOOPT; } inet_addr_from_ip4addr((struct in_addr*)optval, udp_get_multicast_netif_addr(sock->conn->pcb.udp)); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_IF) = 0x%"X32_F"\n", s, *(u32_t *)optval)); break; case IP_MULTICAST_LOOP: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, u8_t); if ((sock->conn->pcb.udp->flags & UDP_FLAGS_MULTICAST_LOOP) != 0) { *(u8_t*)optval = 1; } else { *(u8_t*)optval = 0; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, IP_MULTICAST_LOOP) = %d\n", s, *(int *)optval)); break; #endif /* LWIP_MULTICAST_TX_OPTIONS */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #if LWIP_TCP /* Level: IPPROTO_TCP */ case IPPROTO_TCP: /* Special case: all IPPROTO_TCP option take an int */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, *optlen, int, NETCONN_TCP); if (sock->conn->pcb.tcp->state == LISTEN) { return EINVAL; } switch (optname) { case TCP_NODELAY: *(int*)optval = tcp_nagle_disabled(sock->conn->pcb.tcp); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_NODELAY) = %s\n", s, (*(int*)optval)?"on":"off") ); break; case TCP_KEEPALIVE: *(int*)optval = (int)sock->conn->pcb.tcp->keep_idle; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) = %d\n", s, *(int *)optval)); break; #if LWIP_TCP_KEEPALIVE case TCP_KEEPIDLE: *(int*)optval = (int)(sock->conn->pcb.tcp->keep_idle/1000); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_KEEPIDLE) = %d\n", s, *(int *)optval)); break; case TCP_KEEPINTVL: *(int*)optval = (int)(sock->conn->pcb.tcp->keep_intvl/1000); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_KEEPINTVL) = %d\n", s, *(int *)optval)); break; case TCP_KEEPCNT: *(int*)optval = (int)sock->conn->pcb.tcp->keep_cnt; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, TCP_KEEPCNT) = %d\n", s, *(int *)optval)); break; #endif /* LWIP_TCP_KEEPALIVE */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_TCP */ #if LWIP_IPV6 /* Level: IPPROTO_IPV6 */ case IPPROTO_IPV6: switch (optname) { case IPV6_V6ONLY: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, *optlen, int); *(int*)optval = (netconn_get_ipv6only(sock->conn) ? 1 : 0); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IPV6, IPV6_V6ONLY) = %d\n", s, *(int *)optval)); break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_IPV6, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_IPV6 */ #if LWIP_UDP && LWIP_UDPLITE /* Level: IPPROTO_UDPLITE */ case IPPROTO_UDPLITE: /* Special case: all IPPROTO_UDPLITE option take an int */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, *optlen, int); /* If this is no UDP lite socket, ignore any options. */ if (!NETCONNTYPE_ISUDPLITE(netconn_type(sock->conn))) { return ENOPROTOOPT; } switch (optname) { case UDPLITE_SEND_CSCOV: *(int*)optval = sock->conn->pcb.udp->chksum_len_tx; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) = %d\n", s, (*(int*)optval)) ); break; case UDPLITE_RECV_CSCOV: *(int*)optval = sock->conn->pcb.udp->chksum_len_rx; LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) = %d\n", s, (*(int*)optval)) ); break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_UDP */ /* Level: IPPROTO_RAW */ case IPPROTO_RAW: switch (optname) { #if LWIP_IPV6 && LWIP_RAW case IPV6_CHECKSUM: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, *optlen, int, NETCONN_RAW); if (sock->conn->pcb.raw->chksum_reqd == 0) { *(int *)optval = -1; } else { *(int *)optval = sock->conn->pcb.raw->chksum_offset; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_RAW, IPV6_CHECKSUM) = %d\n", s, (*(int*)optval)) ); break; #endif /* LWIP_IPV6 && LWIP_RAW */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, IPPROTO_RAW, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_getsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname)); err = ENOPROTOOPT; break; } /* switch (level) */ return err; } int lwip_setsockopt(int s, int level, int optname, const void *optval, socklen_t optlen) { u8_t err = 0; struct lwip_sock *sock = get_socket(s); #if !LWIP_TCPIP_CORE_LOCKING LWIP_SETGETSOCKOPT_DATA_VAR_DECLARE(data); #endif /* !LWIP_TCPIP_CORE_LOCKING */ if (!sock) { return -1; } if (NULL == optval) { sock_set_errno(sock, EFAULT); return -1; } #if LWIP_TCPIP_CORE_LOCKING /* core-locking can just call the -impl function */ LOCK_TCPIP_CORE(); err = lwip_setsockopt_impl(s, level, optname, optval, optlen); UNLOCK_TCPIP_CORE(); #else /* LWIP_TCPIP_CORE_LOCKING */ #if LWIP_MPU_COMPATIBLE /* MPU_COMPATIBLE copies the optval data, so check for max size here */ if (optlen > LWIP_SETGETSOCKOPT_MAXOPTLEN) { sock_set_errno(sock, ENOBUFS); return -1; } #endif /* LWIP_MPU_COMPATIBLE */ LWIP_SETGETSOCKOPT_DATA_VAR_ALLOC(data, sock); LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).s = s; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).level = level; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optname = optname; LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optlen = optlen; #if LWIP_MPU_COMPATIBLE MEMCPY(LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optval, optval, optlen); #else /* LWIP_MPU_COMPATIBLE */ LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).optval.pc = (const void*)optval; #endif /* LWIP_MPU_COMPATIBLE */ LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).err = 0; #if LWIP_NETCONN_SEM_PER_THREAD LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem = LWIP_NETCONN_THREAD_SEM_GET(); #else LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem = &sock->conn->op_completed; #endif err = tcpip_callback(lwip_setsockopt_callback, &LWIP_SETGETSOCKOPT_DATA_VAR_REF(data)); if (err != ERR_OK) { LWIP_SETGETSOCKOPT_DATA_VAR_FREE(data); sock_set_errno(sock, err_to_errno(err)); return -1; } sys_arch_sem_wait((sys_sem_t*)(LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).completed_sem), 0); /* maybe lwip_getsockopt_internal has changed err */ err = LWIP_SETGETSOCKOPT_DATA_VAR_REF(data).err; LWIP_SETGETSOCKOPT_DATA_VAR_FREE(data); #endif /* LWIP_TCPIP_CORE_LOCKING */ sock_set_errno(sock, err); return err ? -1 : 0; } #if !LWIP_TCPIP_CORE_LOCKING /** lwip_setsockopt_callback: only used without CORE_LOCKING * to get into the tcpip_thread */ static void lwip_setsockopt_callback(void *arg) { struct lwip_setgetsockopt_data *data; LWIP_ASSERT("arg != NULL", arg != NULL); data = (struct lwip_setgetsockopt_data*)arg; data->err = lwip_setsockopt_impl(data->s, data->level, data->optname, #if LWIP_MPU_COMPATIBLE data->optval, #else /* LWIP_MPU_COMPATIBLE */ data->optval.pc, #endif /* LWIP_MPU_COMPATIBLE */ data->optlen); sys_sem_signal((sys_sem_t*)(data->completed_sem)); } #endif /* LWIP_TCPIP_CORE_LOCKING */ /** lwip_setsockopt_impl: the actual implementation of setsockopt: * same argument as lwip_setsockopt, either called directly or through callback */ static u8_t lwip_setsockopt_impl(int s, int level, int optname, const void *optval, socklen_t optlen) { u8_t err = 0; struct lwip_sock *sock = tryget_socket(s); if (!sock) { return EBADF; } switch (level) { /* Level: SOL_SOCKET */ case SOL_SOCKET: switch (optname) { /* SO_ACCEPTCONN is get-only */ /* The option flags */ case SO_BROADCAST: case SO_KEEPALIVE: #if SO_REUSE case SO_REUSEADDR: #endif /* SO_REUSE */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, int); if (*(const int*)optval) { ip_set_option(sock->conn->pcb.ip, optname); } else { ip_reset_option(sock->conn->pcb.ip, optname); } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, optname=0x%x, ..) -> %s\n", s, optname, (*(const int*)optval?"on":"off"))); break; /* SO_TYPE is get-only */ /* SO_ERROR is get-only */ #if LWIP_SO_SNDTIMEO case SO_SNDTIMEO: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, optlen, LWIP_SO_SNDRCVTIMEO_OPTTYPE); netconn_set_sendtimeout(sock->conn, LWIP_SO_SNDRCVTIMEO_GET_MS(optval)); break; #endif /* LWIP_SO_SNDTIMEO */ #if LWIP_SO_RCVTIMEO case SO_RCVTIMEO: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, optlen, LWIP_SO_SNDRCVTIMEO_OPTTYPE); netconn_set_recvtimeout(sock->conn, (int)LWIP_SO_SNDRCVTIMEO_GET_MS(optval)); break; #endif /* LWIP_SO_RCVTIMEO */ #if LWIP_SO_RCVBUF case SO_RCVBUF: LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, optlen, int); netconn_set_recvbufsize(sock->conn, *(const int*)optval); break; #endif /* LWIP_SO_RCVBUF */ #if LWIP_SO_LINGER case SO_LINGER: { const struct linger* linger = (const struct linger*)optval; LWIP_SOCKOPT_CHECK_OPTLEN_CONN(sock, optlen, struct linger); if (linger->l_onoff) { int lingersec = linger->l_linger; if (lingersec < 0) { return EINVAL; } if (lingersec > 0xFFFF) { lingersec = 0xFFFF; } sock->conn->linger = (s16_t)lingersec; } else { sock->conn->linger = -1; } } break; #endif /* LWIP_SO_LINGER */ #if LWIP_UDP case SO_NO_CHECK: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_UDP); #if LWIP_UDPLITE if ((udp_flags(sock->conn->pcb.udp) & UDP_FLAGS_UDPLITE) != 0) { /* this flag is only available for UDP, not for UDP lite */ return EAFNOSUPPORT; } #endif /* LWIP_UDPLITE */ if (*(const int*)optval) { udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) | UDP_FLAGS_NOCHKSUM); } else { udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) & ~UDP_FLAGS_NOCHKSUM); } break; #endif /* LWIP_UDP */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, SOL_SOCKET, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; /* Level: IPPROTO_IP */ case IPPROTO_IP: switch (optname) { case IP_TTL: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, int); sock->conn->pcb.ip->ttl = (u8_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TTL, ..) -> %d\n", s, sock->conn->pcb.ip->ttl)); break; case IP_TOS: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, int); sock->conn->pcb.ip->tos = (u8_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, IP_TOS, ..)-> %d\n", s, sock->conn->pcb.ip->tos)); break; #if LWIP_MULTICAST_TX_OPTIONS case IP_MULTICAST_TTL: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, u8_t, NETCONN_UDP); udp_set_multicast_ttl(sock->conn->pcb.udp, (u8_t)(*(const u8_t*)optval)); break; case IP_MULTICAST_IF: { ip4_addr_t if_addr; LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, struct in_addr, NETCONN_UDP); inet_addr_to_ip4addr(&if_addr, (const struct in_addr*)optval); udp_set_multicast_netif_addr(sock->conn->pcb.udp, &if_addr); } break; case IP_MULTICAST_LOOP: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, u8_t, NETCONN_UDP); if (*(const u8_t*)optval) { udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) | UDP_FLAGS_MULTICAST_LOOP); } else { udp_setflags(sock->conn->pcb.udp, udp_flags(sock->conn->pcb.udp) & ~UDP_FLAGS_MULTICAST_LOOP); } break; #endif /* LWIP_MULTICAST_TX_OPTIONS */ #if LWIP_IGMP case IP_ADD_MEMBERSHIP: case IP_DROP_MEMBERSHIP: { /* If this is a TCP or a RAW socket, ignore these options. */ /* @todo: assign membership to this socket so that it is dropped when closing the socket */ err_t igmp_err; const struct ip_mreq *imr = (const struct ip_mreq *)optval; ip4_addr_t if_addr; ip4_addr_t multi_addr; LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, struct ip_mreq, NETCONN_UDP); inet_addr_to_ip4addr(&if_addr, &imr->imr_interface); inet_addr_to_ip4addr(&multi_addr, &imr->imr_multiaddr); if (optname == IP_ADD_MEMBERSHIP) { if (!lwip_socket_register_membership(s, &if_addr, &multi_addr)) { /* cannot track membership (out of memory) */ err = ENOMEM; igmp_err = ERR_OK; } else { igmp_err = igmp_joingroup(&if_addr, &multi_addr); } } else { igmp_err = igmp_leavegroup(&if_addr, &multi_addr); lwip_socket_unregister_membership(s, &if_addr, &multi_addr); } if (igmp_err != ERR_OK) { err = EADDRNOTAVAIL; } } break; #endif /* LWIP_IGMP */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IP, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #if LWIP_TCP /* Level: IPPROTO_TCP */ case IPPROTO_TCP: /* Special case: all IPPROTO_TCP option take an int */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_TCP); if (sock->conn->pcb.tcp->state == LISTEN) { return EINVAL; } switch (optname) { case TCP_NODELAY: if (*(const int*)optval) { tcp_nagle_disable(sock->conn->pcb.tcp); } else { tcp_nagle_enable(sock->conn->pcb.tcp); } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_NODELAY) -> %s\n", s, (*(const int *)optval)?"on":"off") ); break; case TCP_KEEPALIVE: sock->conn->pcb.tcp->keep_idle = (u32_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPALIVE) -> %"U32_F"\n", s, sock->conn->pcb.tcp->keep_idle)); break; #if LWIP_TCP_KEEPALIVE case TCP_KEEPIDLE: sock->conn->pcb.tcp->keep_idle = 1000*(u32_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPIDLE) -> %"U32_F"\n", s, sock->conn->pcb.tcp->keep_idle)); break; case TCP_KEEPINTVL: sock->conn->pcb.tcp->keep_intvl = 1000*(u32_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPINTVL) -> %"U32_F"\n", s, sock->conn->pcb.tcp->keep_intvl)); break; case TCP_KEEPCNT: sock->conn->pcb.tcp->keep_cnt = (u32_t)(*(const int*)optval); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, TCP_KEEPCNT) -> %"U32_F"\n", s, sock->conn->pcb.tcp->keep_cnt)); break; #endif /* LWIP_TCP_KEEPALIVE */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_TCP, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_TCP*/ #if LWIP_IPV6 /* Level: IPPROTO_IPV6 */ case IPPROTO_IPV6: switch (optname) { case IPV6_V6ONLY: LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_TCP); if (*(const int*)optval) { netconn_set_ipv6only(sock->conn, 1); } else { netconn_set_ipv6only(sock->conn, 0); } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IPV6, IPV6_V6ONLY, ..) -> %d\n", s, (netconn_get_ipv6only(sock->conn) ? 1 : 0))); break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_IPV6, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_IPV6 */ #if LWIP_UDP && LWIP_UDPLITE /* Level: IPPROTO_UDPLITE */ case IPPROTO_UDPLITE: /* Special case: all IPPROTO_UDPLITE option take an int */ LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB(sock, optlen, int); /* If this is no UDP lite socket, ignore any options. */ if (!NETCONNTYPE_ISUDPLITE(netconn_type(sock->conn))) { return ENOPROTOOPT; } switch (optname) { case UDPLITE_SEND_CSCOV: if ((*(const int*)optval != 0) && ((*(const int*)optval < 8) || (*(const int*)optval > 0xffff))) { /* don't allow illegal values! */ sock->conn->pcb.udp->chksum_len_tx = 8; } else { sock->conn->pcb.udp->chksum_len_tx = (u16_t)*(const int*)optval; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV) -> %d\n", s, (*(const int*)optval)) ); break; case UDPLITE_RECV_CSCOV: if ((*(const int*)optval != 0) && ((*(const int*)optval < 8) || (*(const int*)optval > 0xffff))) { /* don't allow illegal values! */ sock->conn->pcb.udp->chksum_len_rx = 8; } else { sock->conn->pcb.udp->chksum_len_rx = (u16_t)*(const int*)optval; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV) -> %d\n", s, (*(const int*)optval)) ); break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_UDPLITE, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; #endif /* LWIP_UDP */ /* Level: IPPROTO_RAW */ case IPPROTO_RAW: switch (optname) { #if LWIP_IPV6 && LWIP_RAW case IPV6_CHECKSUM: /* It should not be possible to disable the checksum generation with ICMPv6 * as per RFC 3542 chapter 3.1 */ if(sock->conn->pcb.raw->protocol == IPPROTO_ICMPV6) { return EINVAL; } LWIP_SOCKOPT_CHECK_OPTLEN_CONN_PCB_TYPE(sock, optlen, int, NETCONN_RAW); if (*(const int *)optval < 0) { sock->conn->pcb.raw->chksum_reqd = 0; } else if (*(const int *)optval & 1) { /* Per RFC3542, odd offsets are not allowed */ return EINVAL; } else { sock->conn->pcb.raw->chksum_reqd = 1; sock->conn->pcb.raw->chksum_offset = (u16_t)*(const int *)optval; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_RAW, IPV6_CHECKSUM, ..) -> %d\n", s, sock->conn->pcb.raw->chksum_reqd)); break; #endif /* LWIP_IPV6 && LWIP_RAW */ default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, IPPROTO_RAW, UNIMPL: optname=0x%x, ..)\n", s, optname)); err = ENOPROTOOPT; break; } /* switch (optname) */ break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_setsockopt(%d, level=0x%x, UNIMPL: optname=0x%x, ..)\n", s, level, optname)); err = ENOPROTOOPT; break; } /* switch (level) */ return err; } int lwip_ioctl(int s, long cmd, void *argp) { struct lwip_sock *sock = get_socket(s); u8_t val; #if LWIP_SO_RCVBUF u16_t buflen = 0; int recv_avail; #endif /* LWIP_SO_RCVBUF */ if (!sock) { return -1; } switch (cmd) { #if LWIP_SO_RCVBUF || LWIP_FIONREAD_LINUXMODE case FIONREAD: if (!argp) { sock_set_errno(sock, EINVAL); return -1; } #if LWIP_FIONREAD_LINUXMODE if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { struct pbuf *p; if (sock->lastdata) { p = ((struct netbuf *)sock->lastdata)->p; *((int*)argp) = p->tot_len - sock->lastoffset; } else { struct netbuf *rxbuf; err_t err; if (sock->rcvevent <= 0) { *((int*)argp) = 0; } else { err = netconn_recv(sock->conn, &rxbuf); if (err != ERR_OK) { *((int*)argp) = 0; } else { sock->lastdata = rxbuf; sock->lastoffset = 0; *((int*)argp) = rxbuf->p->tot_len; } } } return 0; } #endif /* LWIP_FIONREAD_LINUXMODE */ #if LWIP_SO_RCVBUF /* we come here if either LWIP_FIONREAD_LINUXMODE==0 or this is a TCP socket */ SYS_ARCH_GET(sock->conn->recv_avail, recv_avail); if (recv_avail < 0) { recv_avail = 0; } *((int*)argp) = recv_avail; /* Check if there is data left from the last recv operation. /maq 041215 */ if (sock->lastdata) { struct pbuf *p = (struct pbuf *)sock->lastdata; if (NETCONNTYPE_GROUP(netconn_type(sock->conn)) != NETCONN_TCP) { p = ((struct netbuf *)p)->p; } buflen = p->tot_len; buflen -= sock->lastoffset; *((int*)argp) += buflen; } LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONREAD, %p) = %"U16_F"\n", s, argp, *((u16_t*)argp))); sock_set_errno(sock, 0); return 0; #else /* LWIP_SO_RCVBUF */ break; #endif /* LWIP_SO_RCVBUF */ #endif /* LWIP_SO_RCVBUF || LWIP_FIONREAD_LINUXMODE */ case (long)FIONBIO: val = 0; if (argp && *(u32_t*)argp) { val = 1; } netconn_set_nonblocking(sock->conn, val); LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, FIONBIO, %d)\n", s, val)); sock_set_errno(sock, 0); return 0; default: break; } /* switch (cmd) */ LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_ioctl(%d, UNIMPL: 0x%lx, %p)\n", s, cmd, argp)); sock_set_errno(sock, ENOSYS); /* not yet implemented */ return -1; } /** A minimal implementation of fcntl. * Currently only the commands F_GETFL and F_SETFL are implemented. * Only the flag O_NONBLOCK is implemented. */ int lwip_fcntl(int s, int cmd, int val) { struct lwip_sock *sock = get_socket(s); int ret = -1; if (!sock) { return -1; } switch (cmd) { case F_GETFL: ret = netconn_is_nonblocking(sock->conn) ? O_NONBLOCK : 0; sock_set_errno(sock, 0); break; case F_SETFL: if ((val & ~O_NONBLOCK) == 0) { /* only O_NONBLOCK, all other bits are zero */ netconn_set_nonblocking(sock->conn, val & O_NONBLOCK); ret = 0; sock_set_errno(sock, 0); } else { sock_set_errno(sock, ENOSYS); /* not yet implemented */ } break; default: LWIP_DEBUGF(SOCKETS_DEBUG, ("lwip_fcntl(%d, UNIMPL: %d, %d)\n", s, cmd, val)); sock_set_errno(sock, ENOSYS); /* not yet implemented */ break; } return ret; } #if LWIP_IGMP /** Register a new IGMP membership. On socket close, the membership is dropped automatically. * * ATTENTION: this function is called from tcpip_thread (or under CORE_LOCK). * * @return 1 on success, 0 on failure */ static int lwip_socket_register_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr) { struct lwip_sock *sock = get_socket(s); int i; if (!sock) { return 0; } for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) { if (socket_ipv4_multicast_memberships[i].sock == NULL) { socket_ipv4_multicast_memberships[i].sock = sock; ip4_addr_copy(socket_ipv4_multicast_memberships[i].if_addr, *if_addr); ip4_addr_copy(socket_ipv4_multicast_memberships[i].multi_addr, *multi_addr); return 1; } } return 0; } /** Unregister a previously registered membership. This prevents dropping the membership * on socket close. * * ATTENTION: this function is called from tcpip_thread (or under CORE_LOCK). */ static void lwip_socket_unregister_membership(int s, const ip4_addr_t *if_addr, const ip4_addr_t *multi_addr) { struct lwip_sock *sock = get_socket(s); int i; if (!sock) { return; } for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) { if ((socket_ipv4_multicast_memberships[i].sock == sock) && ip4_addr_cmp(&socket_ipv4_multicast_memberships[i].if_addr, if_addr) && ip4_addr_cmp(&socket_ipv4_multicast_memberships[i].multi_addr, multi_addr)) { socket_ipv4_multicast_memberships[i].sock = NULL; ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].if_addr); ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].multi_addr); return; } } } /** Drop all memberships of a socket that were not dropped explicitly via setsockopt. * * ATTENTION: this function is NOT called from tcpip_thread (or under CORE_LOCK). */ static void lwip_socket_drop_registered_memberships(int s) { struct lwip_sock *sock = get_socket(s); int i; if (!sock) { return; } for (i = 0; i < LWIP_SOCKET_MAX_MEMBERSHIPS; i++) { if (socket_ipv4_multicast_memberships[i].sock == sock) { ip_addr_t multi_addr, if_addr; ip_addr_copy_from_ip4(multi_addr, socket_ipv4_multicast_memberships[i].multi_addr); ip_addr_copy_from_ip4(if_addr, socket_ipv4_multicast_memberships[i].if_addr); socket_ipv4_multicast_memberships[i].sock = NULL; ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].if_addr); ip4_addr_set_zero(&socket_ipv4_multicast_memberships[i].multi_addr); netconn_join_leave_group(sock->conn, &multi_addr, &if_addr, NETCONN_LEAVE); } } } #endif /* LWIP_IGMP */ int lwip_geterr(int s) { int res; struct lwip_sock *sock; sock = get_socket(s); if (!sock) { res = -1; }else{ res = sock->conn->last_err; } return res; } #endif /* LWIP_SOCKET */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/sockets.c
C
unknown
95,660
/** * @file * Sequential API Main thread 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> * */ #include "lwip/opt.h" #if !NO_SYS /* don't build if not configured for use in lwipopts.h */ #include "lwip/priv/tcpip_priv.h" #include "lwip/sys.h" #include "lwip/memp.h" #include "lwip/mem.h" #include "lwip/init.h" #include "lwip/ip.h" #include "lwip/pbuf.h" #include "lwip/etharp.h" #include "netif/ethernet.h" #define TCPIP_MSG_VAR_REF(name) API_VAR_REF(name) #define TCPIP_MSG_VAR_DECLARE(name) API_VAR_DECLARE(struct tcpip_msg, name) #define TCPIP_MSG_VAR_ALLOC(name) API_VAR_ALLOC(struct tcpip_msg, MEMP_TCPIP_MSG_API, name, ERR_MEM) #define TCPIP_MSG_VAR_FREE(name) API_VAR_FREE(MEMP_TCPIP_MSG_API, name) /* global variables */ static tcpip_init_done_fn tcpip_init_done; static void *tcpip_init_done_arg; static sys_mbox_t mbox; #if LWIP_TCPIP_CORE_LOCKING /** The global semaphore to lock the stack. */ sys_mutex_t lock_tcpip_core; #endif /* LWIP_TCPIP_CORE_LOCKING */ #if LWIP_TIMERS /* wait for a message, timeouts are processed while waiting */ #define TCPIP_MBOX_FETCH(mbox, msg) sys_timeouts_mbox_fetch(mbox, msg) #else /* LWIP_TIMERS */ /* wait for a message with timers disabled (e.g. pass a timer-check trigger into tcpip_thread) */ #define TCPIP_MBOX_FETCH(mbox, msg) sys_mbox_fetch(mbox, msg) #endif /* LWIP_TIMERS */ /** * The main lwIP thread. This thread has exclusive access to lwIP core functions * (unless access to them is not locked). Other threads communicate with this * thread using message boxes. * * It also starts all the timers to make sure they are running in the right * thread context. * * @param arg unused argument */ static void tcpip_thread(void *arg) { struct tcpip_msg *msg; LWIP_UNUSED_ARG(arg); if (tcpip_init_done != NULL) { tcpip_init_done(tcpip_init_done_arg); } LOCK_TCPIP_CORE(); while (1) { /* MAIN Loop */ UNLOCK_TCPIP_CORE(); LWIP_TCPIP_THREAD_ALIVE(); /* wait for a message, timeouts are processed while waiting */ TCPIP_MBOX_FETCH(&mbox, (void **)&msg); LOCK_TCPIP_CORE(); if (msg == NULL) { LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: invalid message: NULL\n")); LWIP_ASSERT("tcpip_thread: invalid message", 0); continue; } switch (msg->type) { #if !LWIP_TCPIP_CORE_LOCKING case TCPIP_MSG_API: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: API message %p\n", (void *)msg)); msg->msg.api_msg.function(msg->msg.api_msg.msg); break; case TCPIP_MSG_API_CALL: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: API CALL message %p\n", (void *)msg)); msg->msg.api_call.arg->err = msg->msg.api_call.function(msg->msg.api_call.arg); sys_sem_signal(msg->msg.api_call.sem); break; #endif /* !LWIP_TCPIP_CORE_LOCKING */ #if !LWIP_TCPIP_CORE_LOCKING_INPUT case TCPIP_MSG_INPKT: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: PACKET %p\n", (void *)msg)); msg->msg.inp.input_fn(msg->msg.inp.p, msg->msg.inp.netif); memp_free(MEMP_TCPIP_MSG_INPKT, msg); break; #endif /* !LWIP_TCPIP_CORE_LOCKING_INPUT */ #if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS case TCPIP_MSG_TIMEOUT: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: TIMEOUT %p\n", (void *)msg)); sys_timeout(msg->msg.tmo.msecs, msg->msg.tmo.h, msg->msg.tmo.arg); memp_free(MEMP_TCPIP_MSG_API, msg); break; case TCPIP_MSG_UNTIMEOUT: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: UNTIMEOUT %p\n", (void *)msg)); sys_untimeout(msg->msg.tmo.h, msg->msg.tmo.arg); memp_free(MEMP_TCPIP_MSG_API, msg); break; #endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ case TCPIP_MSG_CALLBACK: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: CALLBACK %p\n", (void *)msg)); msg->msg.cb.function(msg->msg.cb.ctx); memp_free(MEMP_TCPIP_MSG_API, msg); break; case TCPIP_MSG_CALLBACK_STATIC: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: CALLBACK_STATIC %p\n", (void *)msg)); msg->msg.cb.function(msg->msg.cb.ctx); break; default: LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: invalid message: %d\n", msg->type)); LWIP_ASSERT("tcpip_thread: invalid message", 0); break; } } } /** * Pass a received packet to tcpip_thread for input processing * * @param p the received packet * @param inp the network interface on which the packet was received * @param input_fn input function to call */ err_t tcpip_inpkt(struct pbuf *p, struct netif *inp, netif_input_fn input_fn) { #if LWIP_TCPIP_CORE_LOCKING_INPUT err_t ret; LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_inpkt: PACKET %p/%p\n", (void *)p, (void *)inp)); LOCK_TCPIP_CORE(); ret = input_fn(p, inp); UNLOCK_TCPIP_CORE(); return ret; #else /* LWIP_TCPIP_CORE_LOCKING_INPUT */ struct tcpip_msg *msg; LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_INPKT); if (msg == NULL) { return ERR_MEM; } msg->type = TCPIP_MSG_INPKT; msg->msg.inp.p = p; msg->msg.inp.netif = inp; msg->msg.inp.input_fn = input_fn; if (sys_mbox_trypost(&mbox, msg) != ERR_OK) { memp_free(MEMP_TCPIP_MSG_INPKT, msg); return ERR_MEM; } return ERR_OK; #endif /* LWIP_TCPIP_CORE_LOCKING_INPUT */ } /** * @ingroup lwip_os * Pass a received packet to tcpip_thread for input processing with * ethernet_input or ip_input. Don't call directly, pass to netif_add() * and call netif->input(). * * @param p the received packet, p->payload pointing to the Ethernet header or * to an IP header (if inp doesn't have NETIF_FLAG_ETHARP or * NETIF_FLAG_ETHERNET flags) * @param inp the network interface on which the packet was received */ err_t tcpip_input(struct pbuf *p, struct netif *inp) { #if LWIP_ETHERNET if (inp->flags & (NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET)) { return tcpip_inpkt(p, inp, ethernet_input); } else #endif /* LWIP_ETHERNET */ return tcpip_inpkt(p, inp, ip_input); } /** * Call a specific function in the thread context of * tcpip_thread for easy access synchronization. * A function called in that way may access lwIP core code * without fearing concurrent access. * * @param function the function to call * @param ctx parameter passed to f * @param block 1 to block until the request is posted, 0 to non-blocking mode * @return ERR_OK if the function was called, another err_t if not */ err_t tcpip_callback_with_block(tcpip_callback_fn function, void *ctx, u8_t block) { struct tcpip_msg *msg; LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); if (msg == NULL) { return ERR_MEM; } msg->type = TCPIP_MSG_CALLBACK; msg->msg.cb.function = function; msg->msg.cb.ctx = ctx; if (block) { sys_mbox_post(&mbox, msg); } else { if (sys_mbox_trypost(&mbox, msg) != ERR_OK) { memp_free(MEMP_TCPIP_MSG_API, msg); return ERR_MEM; } } return ERR_OK; } #if LWIP_TCPIP_TIMEOUT && LWIP_TIMERS /** * call sys_timeout in tcpip_thread * * @param msecs time in milliseconds for timeout * @param h function to be called on timeout * @param arg argument to pass to timeout function h * @return ERR_MEM on memory error, ERR_OK otherwise */ err_t tcpip_timeout(u32_t msecs, sys_timeout_handler h, void *arg) { struct tcpip_msg *msg; LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); if (msg == NULL) { return ERR_MEM; } msg->type = TCPIP_MSG_TIMEOUT; msg->msg.tmo.msecs = msecs; msg->msg.tmo.h = h; msg->msg.tmo.arg = arg; sys_mbox_post(&mbox, msg); return ERR_OK; } /** * call sys_untimeout in tcpip_thread * * @param h function to be called on timeout * @param arg argument to pass to timeout function h * @return ERR_MEM on memory error, ERR_OK otherwise */ err_t tcpip_untimeout(sys_timeout_handler h, void *arg) { struct tcpip_msg *msg; LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); if (msg == NULL) { return ERR_MEM; } msg->type = TCPIP_MSG_UNTIMEOUT; msg->msg.tmo.h = h; msg->msg.tmo.arg = arg; sys_mbox_post(&mbox, msg); return ERR_OK; } #endif /* LWIP_TCPIP_TIMEOUT && LWIP_TIMERS */ /** * Sends a message to TCPIP thread to call a function. Caller thread blocks on * on a provided semaphore, which ist NOT automatically signalled by TCPIP thread, * this has to be done by the user. * It is recommended to use LWIP_TCPIP_CORE_LOCKING since this is the way * with least runtime overhead. * * @param fn function to be called from TCPIP thread * @param apimsg argument to API function * @param sem semaphore to wait on * @return ERR_OK if the function was called, another err_t if not */ err_t tcpip_send_msg_wait_sem(tcpip_callback_fn fn, void *apimsg, sys_sem_t* sem) { #if LWIP_TCPIP_CORE_LOCKING LWIP_UNUSED_ARG(sem); LOCK_TCPIP_CORE(); fn(apimsg); UNLOCK_TCPIP_CORE(); return ERR_OK; #else /* LWIP_TCPIP_CORE_LOCKING */ TCPIP_MSG_VAR_DECLARE(msg); LWIP_ASSERT("semaphore not initialized", sys_sem_valid(sem)); LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); TCPIP_MSG_VAR_ALLOC(msg); TCPIP_MSG_VAR_REF(msg).type = TCPIP_MSG_API; TCPIP_MSG_VAR_REF(msg).msg.api_msg.function = fn; TCPIP_MSG_VAR_REF(msg).msg.api_msg.msg = apimsg; sys_mbox_post(&mbox, &TCPIP_MSG_VAR_REF(msg)); sys_arch_sem_wait(sem, 0); TCPIP_MSG_VAR_FREE(msg); return ERR_OK; #endif /* LWIP_TCPIP_CORE_LOCKING */ } /** * Synchronously calls function in TCPIP thread and waits for its completion. * It is recommended to use LWIP_TCPIP_CORE_LOCKING (preferred) or * LWIP_NETCONN_SEM_PER_THREAD. * If not, a semaphore is created and destroyed on every call which is usually * an expensive/slow operation. * @param fn Function to call * @param call Call parameters * @return Return value from tcpip_api_call_fn */ err_t tcpip_api_call(tcpip_api_call_fn fn, struct tcpip_api_call_data *call) { #if LWIP_TCPIP_CORE_LOCKING err_t err; LOCK_TCPIP_CORE(); err = fn(call); UNLOCK_TCPIP_CORE(); return err; #else /* LWIP_TCPIP_CORE_LOCKING */ TCPIP_MSG_VAR_DECLARE(msg); #if !LWIP_NETCONN_SEM_PER_THREAD err_t err = sys_sem_new(&call->sem, 0); if (err != ERR_OK) { return err; } #endif /* LWIP_NETCONN_SEM_PER_THREAD */ LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); TCPIP_MSG_VAR_ALLOC(msg); TCPIP_MSG_VAR_REF(msg).type = TCPIP_MSG_API_CALL; TCPIP_MSG_VAR_REF(msg).msg.api_call.arg = call; TCPIP_MSG_VAR_REF(msg).msg.api_call.function = fn; #if LWIP_NETCONN_SEM_PER_THREAD TCPIP_MSG_VAR_REF(msg).msg.api_call.sem = LWIP_NETCONN_THREAD_SEM_GET(); #else /* LWIP_NETCONN_SEM_PER_THREAD */ TCPIP_MSG_VAR_REF(msg).msg.api_call.sem = &call->sem; #endif /* LWIP_NETCONN_SEM_PER_THREAD */ sys_mbox_post(&mbox, &TCPIP_MSG_VAR_REF(msg)); sys_arch_sem_wait(TCPIP_MSG_VAR_REF(msg).msg.api_call.sem, 0); TCPIP_MSG_VAR_FREE(msg); #if !LWIP_NETCONN_SEM_PER_THREAD sys_sem_free(&call->sem); #endif /* LWIP_NETCONN_SEM_PER_THREAD */ return call->err; #endif /* LWIP_TCPIP_CORE_LOCKING */ } /** * Allocate a structure for a static callback message and initialize it. * This is intended to be used to send "static" messages from interrupt context. * * @param function the function to call * @param ctx parameter passed to function * @return a struct pointer to pass to tcpip_trycallback(). */ struct tcpip_callback_msg* tcpip_callbackmsg_new(tcpip_callback_fn function, void *ctx) { struct tcpip_msg *msg = (struct tcpip_msg *)memp_malloc(MEMP_TCPIP_MSG_API); if (msg == NULL) { return NULL; } msg->type = TCPIP_MSG_CALLBACK_STATIC; msg->msg.cb.function = function; msg->msg.cb.ctx = ctx; return (struct tcpip_callback_msg*)msg; } /** * Free a callback message allocated by tcpip_callbackmsg_new(). * * @param msg the message to free */ void tcpip_callbackmsg_delete(struct tcpip_callback_msg* msg) { memp_free(MEMP_TCPIP_MSG_API, msg); } /** * Try to post a callback-message to the tcpip_thread mbox * This is intended to be used to send "static" messages from interrupt context. * * @param msg pointer to the message to post * @return sys_mbox_trypost() return code */ err_t tcpip_trycallback(struct tcpip_callback_msg* msg) { LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(mbox)); return sys_mbox_trypost(&mbox, msg); } /** * @ingroup lwip_os * Initialize this module: * - initialize all sub modules * - start the tcpip_thread * * @param initfunc a function to call when tcpip_thread is running and finished initializing * @param arg argument to pass to initfunc */ void tcpip_init(tcpip_init_done_fn initfunc, void *arg) { lwip_init(); tcpip_init_done = initfunc; tcpip_init_done_arg = arg; if (sys_mbox_new(&mbox, TCPIP_MBOX_SIZE) != ERR_OK) { LWIP_ASSERT("failed to create tcpip_thread mbox", 0); } #if LWIP_TCPIP_CORE_LOCKING if (sys_mutex_new(&lock_tcpip_core) != ERR_OK) { LWIP_ASSERT("failed to create lock_tcpip_core", 0); } #endif /* LWIP_TCPIP_CORE_LOCKING */ sys_thread_new(TCPIP_THREAD_NAME, tcpip_thread, NULL, TCPIP_THREAD_STACKSIZE, TCPIP_THREAD_PRIO); } /** * Simple callback function used with tcpip_callback to free a pbuf * (pbuf_free has a wrong signature for tcpip_callback) * * @param p The pbuf (chain) to be dereferenced. */ static void pbuf_free_int(void *p) { struct pbuf *q = (struct pbuf *)p; pbuf_free(q); } /** * A simple wrapper function that allows you to free a pbuf from interrupt context. * * @param p The pbuf (chain) to be dereferenced. * @return ERR_OK if callback could be enqueued, an err_t if not */ err_t pbuf_free_callback(struct pbuf *p) { return tcpip_callback_with_block(pbuf_free_int, p, 0); } /** * A simple wrapper function that allows you to free heap memory from * interrupt context. * * @param m the heap memory to free * @return ERR_OK if callback could be enqueued, an err_t if not */ err_t mem_free_callback(void *m) { return tcpip_callback_with_block(mem_free, m, 0); } #endif /* !NO_SYS */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/api/tcpip_lwip.c
C
unknown
16,227
<html> <head><title>lwIP - A Lightweight TCP/IP Stack</title></head> <body bgcolor="white" text="black"> <table width="100%"> <tr valign="top"><td width="80"> <a href="http://www.sics.se/"><img src="/img/sics.gif" border="0" alt="SICS logo" title="SICS logo"></a> </td><td width="500"> <h1>lwIP - A Lightweight TCP/IP Stack</h1> <h2>404 - Page not found</h2> <p> Sorry, the page you are requesting was not found on this server. </p> </td><td> &nbsp; </td></tr> </table> </body> </html>
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/fs/404.html
HTML
unknown
565
<html> <head><title>lwIP - A Lightweight TCP/IP Stack</title></head> <body bgcolor="white" text="black"> <table width="100%"> <tr valign="top"><td width="80"> <a href="http://www.sics.se/"><img src="/img/sics.gif" border="0" alt="SICS logo" title="SICS logo"></a> </td><td width="500"> <h1>lwIP - A Lightweight TCP/IP Stack</h1> <p> The web page you are watching was served by a simple web server running on top of the lightweight TCP/IP stack <a href="http://www.sics.se/~adam/lwip/">lwIP</a>. </p> <p> lwIP is an open source implementation of the TCP/IP protocol suite that was originally written by <a href="http://www.sics.se/~adam/lwip/">Adam Dunkels of the Swedish Institute of Computer Science</a> but now is being actively developed by a team of developers distributed world-wide. Since it's release, lwIP has spurred a lot of interest and has been ported to several platforms and operating systems. lwIP can be used either with or without an underlying OS. </p> <p> The focus of the lwIP TCP/IP implementation is to reduce the RAM usage while still having a full scale TCP. This makes lwIP suitable for use in embedded systems with tens of kilobytes of free RAM and room for around 40 kilobytes of code ROM. </p> <p> More information about lwIP can be found at the lwIP homepage at <a href="http://savannah.nongnu.org/projects/lwip/">http://savannah.nongnu.org/projects/lwip/</a> or at the lwIP wiki at <a href="http://lwip.wikia.com/">http://lwip.wikia.com/</a>. </p> </td><td> &nbsp; </td></tr> </table> </body> </html>
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/fs/index.html
HTML
unknown
1,751
/* * Copyright (c) 2001-2003 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 "lwip/apps/httpd_opts.h" #include "lwip/def.h" #include "lwip/apps/fs.h" #include "fsdata.h" #include <string.h> #if HTTPD_USE_CUSTOM_FSDATA #include "fsdata_custom.c" #else /* HTTPD_USE_CUSTOM_FSDATA */ #include "fsdata.c" #endif /* HTTPD_USE_CUSTOM_FSDATA */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_CUSTOM_FILES int fs_open_custom(struct fs_file *file, const char *name); void fs_close_custom(struct fs_file *file); #if LWIP_HTTPD_FS_ASYNC_READ u8_t fs_canread_custom(struct fs_file *file); u8_t fs_wait_read_custom(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); int fs_read_async_custom(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg); #else /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_read_custom(struct fs_file *file, char *buffer, int count); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #endif /* LWIP_HTTPD_CUSTOM_FILES */ /*-----------------------------------------------------------------------------------*/ err_t fs_open(struct fs_file *file, const char *name) { const struct fsdata_file *f; if ((file == NULL) || (name == NULL)) { return ERR_ARG; } #if LWIP_HTTPD_CUSTOM_FILES if (fs_open_custom(file, name)) { file->is_custom_file = 1; return ERR_OK; } file->is_custom_file = 0; #endif /* LWIP_HTTPD_CUSTOM_FILES */ for (f = FS_ROOT; f != NULL; f = f->next) { if (!strcmp(name, (const char *)f->name)) { file->data = (const char *)f->data; file->len = f->len; file->index = f->len; file->pextension = NULL; file->flags = f->flags; #if HTTPD_PRECALCULATED_CHECKSUM file->chksum_count = f->chksum_count; file->chksum = f->chksum; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ #if LWIP_HTTPD_FILE_STATE file->state = fs_state_init(file, name); #endif /* #if LWIP_HTTPD_FILE_STATE */ return ERR_OK; } } /* file not found */ return ERR_VAL; } /*-----------------------------------------------------------------------------------*/ void fs_close(struct fs_file *file) { #if LWIP_HTTPD_CUSTOM_FILES if (file->is_custom_file) { fs_close_custom(file); } #endif /* LWIP_HTTPD_CUSTOM_FILES */ #if LWIP_HTTPD_FILE_STATE fs_state_free(file, file->state); #endif /* #if LWIP_HTTPD_FILE_STATE */ LWIP_UNUSED_ARG(file); } /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_DYNAMIC_FILE_READ #if LWIP_HTTPD_FS_ASYNC_READ int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg) #else /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_read(struct fs_file *file, char *buffer, int count) #endif /* LWIP_HTTPD_FS_ASYNC_READ */ { int read; if(file->index == file->len) { return FS_READ_EOF; } #if LWIP_HTTPD_FS_ASYNC_READ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #if LWIP_HTTPD_CUSTOM_FILES if (file->is_custom_file) { #if LWIP_HTTPD_FS_ASYNC_READ return fs_read_async_custom(file, buffer, count, callback_fn, callback_arg); #else /* LWIP_HTTPD_FS_ASYNC_READ */ return fs_read_custom(file, buffer, count); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ } #endif /* LWIP_HTTPD_CUSTOM_FILES */ read = file->len - file->index; if(read > count) { read = count; } MEMCPY(buffer, (file->data + file->index), read); file->index += read; return(read); } #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_FS_ASYNC_READ int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg) { if (file != NULL) { #if LWIP_HTTPD_FS_ASYNC_READ #if LWIP_HTTPD_CUSTOM_FILES if (!fs_canread_custom(file)) { if (fs_wait_read_custom(file, callback_fn, callback_arg)) { return 0; } } #else /* LWIP_HTTPD_CUSTOM_FILES */ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_CUSTOM_FILES */ #endif /* LWIP_HTTPD_FS_ASYNC_READ */ } return 1; } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ /*-----------------------------------------------------------------------------------*/ int fs_bytes_left(struct fs_file *file) { return file->len - file->index; }
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/fs.c
C
unknown
6,110
#include "lwip/apps/fs.h" #include "lwip/def.h" #include "fsdata.h" #define file_NULL (struct fsdata_file *) NULL static const unsigned int dummy_align__img_sics_gif = 0; static const unsigned char data__img_sics_gif[] = { /* /img/sics.gif (14 chars) */ 0x2f,0x69,0x6d,0x67,0x2f,0x73,0x69,0x63,0x73,0x2e,0x67,0x69,0x66,0x00,0x00,0x00, /* HTTP header */ /* "HTTP/1.0 200 OK " (17 bytes) */ 0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x30,0x20,0x32,0x30,0x30,0x20,0x4f,0x4b,0x0d, 0x0a, /* "Server: lwIP/1.3.1 (http://savannah.nongnu.org/projects/lwip) " (63 bytes) */ 0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x6c,0x77,0x49,0x50,0x2f,0x31,0x2e,0x33, 0x2e,0x31,0x20,0x28,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x73,0x61,0x76,0x61,0x6e, 0x6e,0x61,0x68,0x2e,0x6e,0x6f,0x6e,0x67,0x6e,0x75,0x2e,0x6f,0x72,0x67,0x2f,0x70, 0x72,0x6f,0x6a,0x65,0x63,0x74,0x73,0x2f,0x6c,0x77,0x69,0x70,0x29,0x0d,0x0a, /* "Content-type: image/gif " (27 bytes) */ 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x3a,0x20,0x69,0x6d, 0x61,0x67,0x65,0x2f,0x67,0x69,0x66,0x0d,0x0a,0x0d,0x0a, /* raw file data (724 bytes) */ 0x47,0x49,0x46,0x38,0x39,0x61,0x46,0x00,0x22,0x00,0xa5,0x00,0x00,0xd9,0x2b,0x39, 0x6a,0x6a,0x6a,0xbf,0xbf,0xbf,0x93,0x93,0x93,0x0f,0x0f,0x0f,0xb0,0xb0,0xb0,0xa6, 0xa6,0xa6,0x80,0x80,0x80,0x76,0x76,0x76,0x1e,0x1e,0x1e,0x9d,0x9d,0x9d,0x2e,0x2e, 0x2e,0x49,0x49,0x49,0x54,0x54,0x54,0x8a,0x8a,0x8a,0x60,0x60,0x60,0xc6,0xa6,0x99, 0xbd,0xb5,0xb2,0xc2,0xab,0xa1,0xd9,0x41,0x40,0xd5,0x67,0x55,0xc0,0xb0,0xaa,0xd5, 0x5e,0x4e,0xd6,0x50,0x45,0xcc,0x93,0x7d,0xc8,0xa1,0x90,0xce,0x8b,0x76,0xd2,0x7b, 0x65,0xd1,0x84,0x6d,0xc9,0x99,0x86,0x3a,0x3a,0x3a,0x00,0x00,0x00,0xb8,0xb8,0xb8, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x2c,0x00,0x00, 0x00,0x00,0x46,0x00,0x22,0x00,0x00,0x06,0xfe,0x40,0x90,0x70,0x48,0x2c,0x1a,0x8f, 0xc8,0xa4,0x72,0xc9,0x6c,0x3a,0x9f,0xd0,0xa8,0x74,0x4a,0xad,0x5a,0xaf,0xd8,0xac, 0x76,0xa9,0x40,0x04,0xbe,0x83,0xe2,0x60,0x3c,0x50,0x20,0x0d,0x8e,0x6f,0x00,0x31, 0x28,0x1c,0x0d,0x07,0xb5,0xc3,0x60,0x75,0x24,0x3e,0xf8,0xfc,0x87,0x11,0x06,0xe9, 0x3d,0x46,0x07,0x0b,0x7a,0x7a,0x7c,0x43,0x06,0x1e,0x84,0x78,0x0b,0x07,0x6e,0x51, 0x01,0x8a,0x84,0x08,0x7e,0x79,0x80,0x87,0x89,0x91,0x7a,0x93,0x0a,0x04,0x99,0x78, 0x96,0x4f,0x03,0x9e,0x79,0x01,0x94,0x9f,0x43,0x9c,0xa3,0xa4,0x05,0x77,0xa3,0xa0, 0x4e,0x98,0x79,0x0b,0x1e,0x83,0xa4,0xa6,0x1f,0x96,0x05,0x9d,0xaa,0x78,0x01,0x07, 0x84,0x04,0x1e,0x1e,0xbb,0xb8,0x51,0x84,0x0e,0x43,0x05,0x07,0x77,0xa5,0x7f,0x42, 0xb1,0xb2,0x01,0x63,0x08,0x0d,0xbb,0x01,0x0c,0x7a,0x0d,0x44,0x0e,0xd8,0xaf,0x4c, 0x05,0x7a,0x04,0x47,0x07,0x07,0xb7,0x80,0xa2,0xe1,0x7d,0x44,0x05,0x01,0x04,0x01, 0xd0,0xea,0x87,0x93,0x4f,0xe0,0x9a,0x49,0xce,0xd8,0x79,0x04,0x66,0x20,0x15,0x10, 0x10,0x11,0x92,0x29,0x80,0xb6,0xc0,0x91,0x15,0x45,0x1e,0x90,0x19,0x71,0x46,0xa8, 0x5c,0x04,0x0e,0x00,0x22,0x4e,0xe8,0x40,0x24,0x9f,0x3e,0x04,0x06,0xa7,0x58,0xd4, 0x93,0xa0,0x1c,0x91,0x3f,0xe8,0xf0,0x88,0x03,0xb1,0x21,0xa2,0x49,0x00,0x19,0x86, 0xfc,0x52,0x44,0xe0,0x01,0x9d,0x29,0x21,0x15,0x25,0x50,0xf7,0x67,0x25,0x1e,0x06, 0xfd,0x4e,0x9a,0xb4,0x90,0xac,0x15,0xfa,0xcb,0x52,0x53,0x1e,0x8c,0xf2,0xf8,0x07, 0x92,0x2d,0x08,0x3a,0x4d,0x12,0x49,0x95,0x49,0xdb,0x14,0x04,0xc4,0x14,0x85,0x29, 0xaa,0xe7,0x01,0x08,0xa4,0x49,0x01,0x14,0x51,0xe0,0x53,0x91,0xd5,0x29,0x06,0x1a, 0x64,0x02,0xf4,0xc7,0x81,0x9e,0x05,0x20,0x22,0x64,0xa5,0x30,0xae,0xab,0x9e,0x97, 0x53,0xd8,0xb9,0xfd,0x50,0xef,0x93,0x02,0x42,0x74,0x34,0xe8,0x9c,0x20,0x21,0xc9, 0x01,0x68,0x78,0xe6,0x55,0x29,0x20,0x56,0x4f,0x4c,0x40,0x51,0x71,0x82,0xc0,0x70, 0x21,0x22,0x85,0xbe,0x4b,0x1c,0x44,0x05,0xea,0xa4,0x01,0xbf,0x22,0xb5,0xf0,0x1c, 0x06,0x51,0x38,0x8f,0xe0,0x22,0xec,0x18,0xac,0x39,0x22,0xd4,0xd6,0x93,0x44,0x01, 0x32,0x82,0xc8,0xfc,0x61,0xb3,0x01,0x45,0x0c,0x2e,0x83,0x30,0xd0,0x0e,0x17,0x24, 0x0f,0x70,0x85,0x94,0xee,0x05,0x05,0x53,0x4b,0x32,0x1b,0x3f,0x98,0xd3,0x1d,0x29, 0x81,0xb0,0xae,0x1e,0x8c,0x7e,0x68,0xe0,0x60,0x5a,0x54,0x8f,0xb0,0x78,0x69,0x73, 0x06,0xa2,0x00,0x6b,0x57,0xca,0x3d,0x11,0x50,0xbd,0x04,0x30,0x4b,0x3a,0xd4,0xab, 0x5f,0x1f,0x9b,0x3d,0x13,0x74,0x27,0x88,0x3c,0x25,0xe0,0x17,0xbe,0x7a,0x79,0x45, 0x0d,0x0c,0xb0,0x8b,0xda,0x90,0xca,0x80,0x06,0x5d,0x17,0x60,0x1c,0x22,0x4c,0xd8, 0x57,0x22,0x06,0x20,0x00,0x98,0x07,0x08,0xe4,0x56,0x80,0x80,0x1c,0xc5,0xb7,0xc5, 0x82,0x0c,0x36,0xe8,0xe0,0x83,0x10,0x46,0x28,0xe1,0x84,0x14,0x56,0x68,0xa1,0x10, 0x41,0x00,0x00,0x3b,}; static const unsigned int dummy_align__404_html = 1; static const unsigned char data__404_html[] = { /* /404.html (10 chars) */ 0x2f,0x34,0x30,0x34,0x2e,0x68,0x74,0x6d,0x6c,0x00,0x00,0x00, /* HTTP header */ /* "HTTP/1.0 404 File not found " (29 bytes) */ 0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x30,0x20,0x34,0x30,0x34,0x20,0x46,0x69,0x6c, 0x65,0x20,0x6e,0x6f,0x74,0x20,0x66,0x6f,0x75,0x6e,0x64,0x0d,0x0a, /* "Server: lwIP/1.3.1 (http://savannah.nongnu.org/projects/lwip) " (63 bytes) */ 0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x6c,0x77,0x49,0x50,0x2f,0x31,0x2e,0x33, 0x2e,0x31,0x20,0x28,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x73,0x61,0x76,0x61,0x6e, 0x6e,0x61,0x68,0x2e,0x6e,0x6f,0x6e,0x67,0x6e,0x75,0x2e,0x6f,0x72,0x67,0x2f,0x70, 0x72,0x6f,0x6a,0x65,0x63,0x74,0x73,0x2f,0x6c,0x77,0x69,0x70,0x29,0x0d,0x0a, /* "Content-type: text/html " (27 bytes) */ 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x3a,0x20,0x74,0x65, 0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x0d,0x0a,0x0d,0x0a, /* raw file data (565 bytes) */ 0x3c,0x68,0x74,0x6d,0x6c,0x3e,0x0d,0x0a,0x3c,0x68,0x65,0x61,0x64,0x3e,0x3c,0x74, 0x69,0x74,0x6c,0x65,0x3e,0x6c,0x77,0x49,0x50,0x20,0x2d,0x20,0x41,0x20,0x4c,0x69, 0x67,0x68,0x74,0x77,0x65,0x69,0x67,0x68,0x74,0x20,0x54,0x43,0x50,0x2f,0x49,0x50, 0x20,0x53,0x74,0x61,0x63,0x6b,0x3c,0x2f,0x74,0x69,0x74,0x6c,0x65,0x3e,0x3c,0x2f, 0x68,0x65,0x61,0x64,0x3e,0x0d,0x0a,0x3c,0x62,0x6f,0x64,0x79,0x20,0x62,0x67,0x63, 0x6f,0x6c,0x6f,0x72,0x3d,0x22,0x77,0x68,0x69,0x74,0x65,0x22,0x20,0x74,0x65,0x78, 0x74,0x3d,0x22,0x62,0x6c,0x61,0x63,0x6b,0x22,0x3e,0x0d,0x0a,0x0d,0x0a,0x20,0x20, 0x20,0x20,0x3c,0x74,0x61,0x62,0x6c,0x65,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22, 0x31,0x30,0x30,0x25,0x22,0x3e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x74, 0x72,0x20,0x76,0x61,0x6c,0x69,0x67,0x6e,0x3d,0x22,0x74,0x6f,0x70,0x22,0x3e,0x3c, 0x74,0x64,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x38,0x30,0x22,0x3e,0x09,0x20, 0x20,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x61,0x20,0x68,0x72,0x65,0x66,0x3d,0x22,0x68, 0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x73,0x69,0x63,0x73,0x2e,0x73, 0x65,0x2f,0x22,0x3e,0x3c,0x69,0x6d,0x67,0x20,0x73,0x72,0x63,0x3d,0x22,0x2f,0x69, 0x6d,0x67,0x2f,0x73,0x69,0x63,0x73,0x2e,0x67,0x69,0x66,0x22,0x0d,0x0a,0x09,0x20, 0x20,0x62,0x6f,0x72,0x64,0x65,0x72,0x3d,0x22,0x30,0x22,0x20,0x61,0x6c,0x74,0x3d, 0x22,0x53,0x49,0x43,0x53,0x20,0x6c,0x6f,0x67,0x6f,0x22,0x20,0x74,0x69,0x74,0x6c, 0x65,0x3d,0x22,0x53,0x49,0x43,0x53,0x20,0x6c,0x6f,0x67,0x6f,0x22,0x3e,0x3c,0x2f, 0x61,0x3e,0x0d,0x0a,0x09,0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x74,0x64,0x20,0x77,0x69, 0x64,0x74,0x68,0x3d,0x22,0x35,0x30,0x30,0x22,0x3e,0x09,0x20,0x20,0x0d,0x0a,0x09, 0x20,0x20,0x3c,0x68,0x31,0x3e,0x6c,0x77,0x49,0x50,0x20,0x2d,0x20,0x41,0x20,0x4c, 0x69,0x67,0x68,0x74,0x77,0x65,0x69,0x67,0x68,0x74,0x20,0x54,0x43,0x50,0x2f,0x49, 0x50,0x20,0x53,0x74,0x61,0x63,0x6b,0x3c,0x2f,0x68,0x31,0x3e,0x0d,0x0a,0x09,0x20, 0x20,0x3c,0x68,0x32,0x3e,0x34,0x30,0x34,0x20,0x2d,0x20,0x50,0x61,0x67,0x65,0x20, 0x6e,0x6f,0x74,0x20,0x66,0x6f,0x75,0x6e,0x64,0x3c,0x2f,0x68,0x32,0x3e,0x0d,0x0a, 0x09,0x20,0x20,0x3c,0x70,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x53,0x6f,0x72, 0x72,0x79,0x2c,0x20,0x74,0x68,0x65,0x20,0x70,0x61,0x67,0x65,0x20,0x79,0x6f,0x75, 0x20,0x61,0x72,0x65,0x20,0x72,0x65,0x71,0x75,0x65,0x73,0x74,0x69,0x6e,0x67,0x20, 0x77,0x61,0x73,0x20,0x6e,0x6f,0x74,0x20,0x66,0x6f,0x75,0x6e,0x64,0x20,0x6f,0x6e, 0x20,0x74,0x68,0x69,0x73,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x73,0x65,0x72,0x76, 0x65,0x72,0x2e,0x20,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x2f,0x70,0x3e,0x0d,0x0a,0x09, 0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x74,0x64,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x26,0x6e, 0x62,0x73,0x70,0x3b,0x0d,0x0a,0x09,0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x2f,0x74,0x72, 0x3e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x2f,0x74,0x61,0x62,0x6c,0x65, 0x3e,0x0d,0x0a,0x3c,0x2f,0x62,0x6f,0x64,0x79,0x3e,0x0d,0x0a,0x3c,0x2f,0x68,0x74, 0x6d,0x6c,0x3e,0x0d,0x0a,}; static const unsigned int dummy_align__index_html = 2; static const unsigned char data__index_html[] = { /* /index.html (12 chars) */ 0x2f,0x69,0x6e,0x64,0x65,0x78,0x2e,0x68,0x74,0x6d,0x6c,0x00, /* HTTP header */ /* "HTTP/1.0 200 OK " (17 bytes) */ 0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x30,0x20,0x32,0x30,0x30,0x20,0x4f,0x4b,0x0d, 0x0a, /* "Server: lwIP/1.3.1 (http://savannah.nongnu.org/projects/lwip) " (63 bytes) */ 0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x6c,0x77,0x49,0x50,0x2f,0x31,0x2e,0x33, 0x2e,0x31,0x20,0x28,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x73,0x61,0x76,0x61,0x6e, 0x6e,0x61,0x68,0x2e,0x6e,0x6f,0x6e,0x67,0x6e,0x75,0x2e,0x6f,0x72,0x67,0x2f,0x70, 0x72,0x6f,0x6a,0x65,0x63,0x74,0x73,0x2f,0x6c,0x77,0x69,0x70,0x29,0x0d,0x0a, /* "Content-type: text/html " (27 bytes) */ 0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x74,0x79,0x70,0x65,0x3a,0x20,0x74,0x65, 0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x0d,0x0a,0x0d,0x0a, /* raw file data (1751 bytes) */ 0x3c,0x68,0x74,0x6d,0x6c,0x3e,0x0d,0x0a,0x3c,0x68,0x65,0x61,0x64,0x3e,0x3c,0x74, 0x69,0x74,0x6c,0x65,0x3e,0x6c,0x77,0x49,0x50,0x20,0x2d,0x20,0x41,0x20,0x4c,0x69, 0x67,0x68,0x74,0x77,0x65,0x69,0x67,0x68,0x74,0x20,0x54,0x43,0x50,0x2f,0x49,0x50, 0x20,0x53,0x74,0x61,0x63,0x6b,0x3c,0x2f,0x74,0x69,0x74,0x6c,0x65,0x3e,0x3c,0x2f, 0x68,0x65,0x61,0x64,0x3e,0x0d,0x0a,0x3c,0x62,0x6f,0x64,0x79,0x20,0x62,0x67,0x63, 0x6f,0x6c,0x6f,0x72,0x3d,0x22,0x77,0x68,0x69,0x74,0x65,0x22,0x20,0x74,0x65,0x78, 0x74,0x3d,0x22,0x62,0x6c,0x61,0x63,0x6b,0x22,0x3e,0x0d,0x0a,0x0d,0x0a,0x20,0x20, 0x20,0x20,0x3c,0x74,0x61,0x62,0x6c,0x65,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22, 0x31,0x30,0x30,0x25,0x22,0x3e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x74, 0x72,0x20,0x76,0x61,0x6c,0x69,0x67,0x6e,0x3d,0x22,0x74,0x6f,0x70,0x22,0x3e,0x3c, 0x74,0x64,0x20,0x77,0x69,0x64,0x74,0x68,0x3d,0x22,0x38,0x30,0x22,0x3e,0x09,0x20, 0x20,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x61,0x20,0x68,0x72,0x65,0x66,0x3d,0x22,0x68, 0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x73,0x69,0x63,0x73,0x2e,0x73, 0x65,0x2f,0x22,0x3e,0x3c,0x69,0x6d,0x67,0x20,0x73,0x72,0x63,0x3d,0x22,0x2f,0x69, 0x6d,0x67,0x2f,0x73,0x69,0x63,0x73,0x2e,0x67,0x69,0x66,0x22,0x0d,0x0a,0x09,0x20, 0x20,0x62,0x6f,0x72,0x64,0x65,0x72,0x3d,0x22,0x30,0x22,0x20,0x61,0x6c,0x74,0x3d, 0x22,0x53,0x49,0x43,0x53,0x20,0x6c,0x6f,0x67,0x6f,0x22,0x20,0x74,0x69,0x74,0x6c, 0x65,0x3d,0x22,0x53,0x49,0x43,0x53,0x20,0x6c,0x6f,0x67,0x6f,0x22,0x3e,0x3c,0x2f, 0x61,0x3e,0x0d,0x0a,0x09,0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x74,0x64,0x20,0x77,0x69, 0x64,0x74,0x68,0x3d,0x22,0x35,0x30,0x30,0x22,0x3e,0x09,0x20,0x20,0x0d,0x0a,0x09, 0x20,0x20,0x3c,0x68,0x31,0x3e,0x6c,0x77,0x49,0x50,0x20,0x2d,0x20,0x41,0x20,0x4c, 0x69,0x67,0x68,0x74,0x77,0x65,0x69,0x67,0x68,0x74,0x20,0x54,0x43,0x50,0x2f,0x49, 0x50,0x20,0x53,0x74,0x61,0x63,0x6b,0x3c,0x2f,0x68,0x31,0x3e,0x0d,0x0a,0x09,0x20, 0x20,0x3c,0x70,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x77, 0x65,0x62,0x20,0x70,0x61,0x67,0x65,0x20,0x79,0x6f,0x75,0x20,0x61,0x72,0x65,0x20, 0x77,0x61,0x74,0x63,0x68,0x69,0x6e,0x67,0x20,0x77,0x61,0x73,0x20,0x73,0x65,0x72, 0x76,0x65,0x64,0x20,0x62,0x79,0x20,0x61,0x20,0x73,0x69,0x6d,0x70,0x6c,0x65,0x20, 0x77,0x65,0x62,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x73,0x65,0x72,0x76,0x65,0x72, 0x20,0x72,0x75,0x6e,0x6e,0x69,0x6e,0x67,0x20,0x6f,0x6e,0x20,0x74,0x6f,0x70,0x20, 0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x6c,0x69,0x67,0x68,0x74,0x77,0x65,0x69,0x67, 0x68,0x74,0x20,0x54,0x43,0x50,0x2f,0x49,0x50,0x20,0x73,0x74,0x61,0x63,0x6b,0x20, 0x3c,0x61,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x68,0x72,0x65,0x66,0x3d,0x22,0x68, 0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77,0x77,0x2e,0x73,0x69,0x63,0x73,0x2e,0x73, 0x65,0x2f,0x7e,0x61,0x64,0x61,0x6d,0x2f,0x6c,0x77,0x69,0x70,0x2f,0x22,0x3e,0x6c, 0x77,0x49,0x50,0x3c,0x2f,0x61,0x3e,0x2e,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x2f,0x70, 0x3e,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x70,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20, 0x6c,0x77,0x49,0x50,0x20,0x69,0x73,0x20,0x61,0x6e,0x20,0x6f,0x70,0x65,0x6e,0x20, 0x73,0x6f,0x75,0x72,0x63,0x65,0x20,0x69,0x6d,0x70,0x6c,0x65,0x6d,0x65,0x6e,0x74, 0x61,0x74,0x69,0x6f,0x6e,0x20,0x6f,0x66,0x20,0x74,0x68,0x65,0x20,0x54,0x43,0x50, 0x2f,0x49,0x50,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x70,0x72,0x6f,0x74,0x6f,0x63, 0x6f,0x6c,0x20,0x73,0x75,0x69,0x74,0x65,0x20,0x74,0x68,0x61,0x74,0x20,0x77,0x61, 0x73,0x20,0x6f,0x72,0x69,0x67,0x69,0x6e,0x61,0x6c,0x6c,0x79,0x20,0x77,0x72,0x69, 0x74,0x74,0x65,0x6e,0x20,0x62,0x79,0x20,0x3c,0x61,0x0d,0x0a,0x09,0x20,0x20,0x20, 0x20,0x68,0x72,0x65,0x66,0x3d,0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x77,0x77, 0x77,0x2e,0x73,0x69,0x63,0x73,0x2e,0x73,0x65,0x2f,0x7e,0x61,0x64,0x61,0x6d,0x2f, 0x6c,0x77,0x69,0x70,0x2f,0x22,0x3e,0x41,0x64,0x61,0x6d,0x20,0x44,0x75,0x6e,0x6b, 0x65,0x6c,0x73,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x6f,0x66,0x20,0x74,0x68,0x65, 0x20,0x53,0x77,0x65,0x64,0x69,0x73,0x68,0x20,0x49,0x6e,0x73,0x74,0x69,0x74,0x75, 0x74,0x65,0x20,0x6f,0x66,0x20,0x43,0x6f,0x6d,0x70,0x75,0x74,0x65,0x72,0x20,0x53, 0x63,0x69,0x65,0x6e,0x63,0x65,0x3c,0x2f,0x61,0x3e,0x20,0x62,0x75,0x74,0x20,0x6e, 0x6f,0x77,0x20,0x69,0x73,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x62,0x65,0x69,0x6e, 0x67,0x20,0x61,0x63,0x74,0x69,0x76,0x65,0x6c,0x79,0x20,0x64,0x65,0x76,0x65,0x6c, 0x6f,0x70,0x65,0x64,0x20,0x62,0x79,0x20,0x61,0x20,0x74,0x65,0x61,0x6d,0x20,0x6f, 0x66,0x20,0x64,0x65,0x76,0x65,0x6c,0x6f,0x70,0x65,0x72,0x73,0x0d,0x0a,0x09,0x20, 0x20,0x20,0x20,0x64,0x69,0x73,0x74,0x72,0x69,0x62,0x75,0x74,0x65,0x64,0x20,0x77, 0x6f,0x72,0x6c,0x64,0x2d,0x77,0x69,0x64,0x65,0x2e,0x20,0x53,0x69,0x6e,0x63,0x65, 0x20,0x69,0x74,0x27,0x73,0x20,0x72,0x65,0x6c,0x65,0x61,0x73,0x65,0x2c,0x20,0x6c, 0x77,0x49,0x50,0x20,0x68,0x61,0x73,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x73,0x70, 0x75,0x72,0x72,0x65,0x64,0x20,0x61,0x20,0x6c,0x6f,0x74,0x20,0x6f,0x66,0x20,0x69, 0x6e,0x74,0x65,0x72,0x65,0x73,0x74,0x20,0x61,0x6e,0x64,0x20,0x68,0x61,0x73,0x20, 0x62,0x65,0x65,0x6e,0x20,0x70,0x6f,0x72,0x74,0x65,0x64,0x20,0x74,0x6f,0x20,0x73, 0x65,0x76,0x65,0x72,0x61,0x6c,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x70,0x6c,0x61, 0x74,0x66,0x6f,0x72,0x6d,0x73,0x20,0x61,0x6e,0x64,0x20,0x6f,0x70,0x65,0x72,0x61, 0x74,0x69,0x6e,0x67,0x20,0x73,0x79,0x73,0x74,0x65,0x6d,0x73,0x2e,0x20,0x6c,0x77, 0x49,0x50,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x75,0x73,0x65,0x64,0x20,0x65, 0x69,0x74,0x68,0x65,0x72,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x77,0x69,0x74,0x68, 0x20,0x6f,0x72,0x20,0x77,0x69,0x74,0x68,0x6f,0x75,0x74,0x20,0x61,0x6e,0x20,0x75, 0x6e,0x64,0x65,0x72,0x6c,0x79,0x69,0x6e,0x67,0x20,0x4f,0x53,0x2e,0x0d,0x0a,0x09, 0x20,0x20,0x3c,0x2f,0x70,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x70,0x3e,0x0d,0x0a, 0x09,0x20,0x20,0x20,0x20,0x54,0x68,0x65,0x20,0x66,0x6f,0x63,0x75,0x73,0x20,0x6f, 0x66,0x20,0x74,0x68,0x65,0x20,0x6c,0x77,0x49,0x50,0x20,0x54,0x43,0x50,0x2f,0x49, 0x50,0x20,0x69,0x6d,0x70,0x6c,0x65,0x6d,0x65,0x6e,0x74,0x61,0x74,0x69,0x6f,0x6e, 0x20,0x69,0x73,0x20,0x74,0x6f,0x20,0x72,0x65,0x64,0x75,0x63,0x65,0x0d,0x0a,0x09, 0x20,0x20,0x20,0x20,0x74,0x68,0x65,0x20,0x52,0x41,0x4d,0x20,0x75,0x73,0x61,0x67, 0x65,0x20,0x77,0x68,0x69,0x6c,0x65,0x20,0x73,0x74,0x69,0x6c,0x6c,0x20,0x68,0x61, 0x76,0x69,0x6e,0x67,0x20,0x61,0x20,0x66,0x75,0x6c,0x6c,0x20,0x73,0x63,0x61,0x6c, 0x65,0x20,0x54,0x43,0x50,0x2e,0x20,0x54,0x68,0x69,0x73,0x0d,0x0a,0x09,0x20,0x20, 0x20,0x20,0x6d,0x61,0x6b,0x65,0x73,0x20,0x6c,0x77,0x49,0x50,0x20,0x73,0x75,0x69, 0x74,0x61,0x62,0x6c,0x65,0x20,0x66,0x6f,0x72,0x20,0x75,0x73,0x65,0x20,0x69,0x6e, 0x20,0x65,0x6d,0x62,0x65,0x64,0x64,0x65,0x64,0x20,0x73,0x79,0x73,0x74,0x65,0x6d, 0x73,0x20,0x77,0x69,0x74,0x68,0x20,0x74,0x65,0x6e,0x73,0x0d,0x0a,0x09,0x20,0x20, 0x20,0x20,0x6f,0x66,0x20,0x6b,0x69,0x6c,0x6f,0x62,0x79,0x74,0x65,0x73,0x20,0x6f, 0x66,0x20,0x66,0x72,0x65,0x65,0x20,0x52,0x41,0x4d,0x20,0x61,0x6e,0x64,0x20,0x72, 0x6f,0x6f,0x6d,0x20,0x66,0x6f,0x72,0x20,0x61,0x72,0x6f,0x75,0x6e,0x64,0x20,0x34, 0x30,0x20,0x6b,0x69,0x6c,0x6f,0x62,0x79,0x74,0x65,0x73,0x0d,0x0a,0x09,0x20,0x20, 0x20,0x20,0x6f,0x66,0x20,0x63,0x6f,0x64,0x65,0x20,0x52,0x4f,0x4d,0x2e,0x0d,0x0a, 0x09,0x20,0x20,0x3c,0x2f,0x70,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x70,0x3e,0x0d, 0x0a,0x09,0x20,0x20,0x20,0x20,0x4d,0x6f,0x72,0x65,0x20,0x69,0x6e,0x66,0x6f,0x72, 0x6d,0x61,0x74,0x69,0x6f,0x6e,0x20,0x61,0x62,0x6f,0x75,0x74,0x20,0x6c,0x77,0x49, 0x50,0x20,0x63,0x61,0x6e,0x20,0x62,0x65,0x20,0x66,0x6f,0x75,0x6e,0x64,0x20,0x61, 0x74,0x20,0x74,0x68,0x65,0x20,0x6c,0x77,0x49,0x50,0x0d,0x0a,0x09,0x20,0x20,0x20, 0x20,0x68,0x6f,0x6d,0x65,0x70,0x61,0x67,0x65,0x20,0x61,0x74,0x20,0x3c,0x61,0x0d, 0x0a,0x09,0x20,0x20,0x20,0x20,0x68,0x72,0x65,0x66,0x3d,0x22,0x68,0x74,0x74,0x70, 0x3a,0x2f,0x2f,0x73,0x61,0x76,0x61,0x6e,0x6e,0x61,0x68,0x2e,0x6e,0x6f,0x6e,0x67, 0x6e,0x75,0x2e,0x6f,0x72,0x67,0x2f,0x70,0x72,0x6f,0x6a,0x65,0x63,0x74,0x73,0x2f, 0x6c,0x77,0x69,0x70,0x2f,0x22,0x3e,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x73,0x61, 0x76,0x61,0x6e,0x6e,0x61,0x68,0x2e,0x6e,0x6f,0x6e,0x67,0x6e,0x75,0x2e,0x6f,0x72, 0x67,0x2f,0x70,0x72,0x6f,0x6a,0x65,0x63,0x74,0x73,0x2f,0x6c,0x77,0x69,0x70,0x2f, 0x3c,0x2f,0x61,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x6f,0x72,0x20,0x61,0x74, 0x20,0x74,0x68,0x65,0x20,0x6c,0x77,0x49,0x50,0x20,0x77,0x69,0x6b,0x69,0x20,0x61, 0x74,0x20,0x3c,0x61,0x0d,0x0a,0x09,0x20,0x20,0x20,0x20,0x68,0x72,0x65,0x66,0x3d, 0x22,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x6c,0x77,0x69,0x70,0x2e,0x77,0x69,0x6b, 0x69,0x61,0x2e,0x63,0x6f,0x6d,0x2f,0x22,0x3e,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f, 0x6c,0x77,0x69,0x70,0x2e,0x77,0x69,0x6b,0x69,0x61,0x2e,0x63,0x6f,0x6d,0x2f,0x3c, 0x2f,0x61,0x3e,0x2e,0x0d,0x0a,0x09,0x20,0x20,0x3c,0x2f,0x70,0x3e,0x0d,0x0a,0x09, 0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x74,0x64,0x3e,0x0d,0x0a,0x09,0x20,0x20,0x26,0x6e, 0x62,0x73,0x70,0x3b,0x0d,0x0a,0x09,0x3c,0x2f,0x74,0x64,0x3e,0x3c,0x2f,0x74,0x72, 0x3e,0x0d,0x0a,0x20,0x20,0x20,0x20,0x20,0x20,0x3c,0x2f,0x74,0x61,0x62,0x6c,0x65, 0x3e,0x0d,0x0a,0x3c,0x2f,0x62,0x6f,0x64,0x79,0x3e,0x0d,0x0a,0x3c,0x2f,0x68,0x74, 0x6d,0x6c,0x3e,0x0d,0x0a,0x0d,0x0a,}; const struct fsdata_file file__img_sics_gif[] = { { file_NULL, data__img_sics_gif, data__img_sics_gif + 16, sizeof(data__img_sics_gif) - 16, 1, }}; const struct fsdata_file file__404_html[] = { { file__img_sics_gif, data__404_html, data__404_html + 12, sizeof(data__404_html) - 12, 1, }}; const struct fsdata_file file__index_html[] = { { file__404_html, data__index_html, data__index_html + 12, sizeof(data__index_html) - 12, 1, }}; #define FS_ROOT file__index_html #define FS_NUMFILES 3
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/fsdata.c
C
unknown
19,261
/* * Copyright (c) 2001-2003 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> * */ #ifndef LWIP_FSDATA_H #define LWIP_FSDATA_H #include "lwip/apps/httpd_opts.h" #include "lwip/apps/fs.h" struct fsdata_file { const struct fsdata_file *next; const unsigned char *name; const unsigned char *data; int len; u8_t flags; #if HTTPD_PRECALCULATED_CHECKSUM u16_t chksum_count; const struct fsdata_chksum *chksum; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ }; #endif /* LWIP_FSDATA_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/fsdata.h
C
unknown
2,068
/** * @file * LWIP HTTP server implementation */ /* * Copyright (c) 2001-2003 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> * Simon Goldschmidt * */ /** * @defgroup httpd HTTP server * @ingroup apps * * This httpd supports for a * rudimentary server-side-include facility which will replace tags of the form * <!--#tag--> in any file whose extension is .shtml, .shtm or .ssi with * strings provided by an include handler whose pointer is provided to the * module via function http_set_ssi_handler(). * Additionally, a simple common * gateway interface (CGI) handling mechanism has been added to allow clients * to hook functions to particular request URIs. * * To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h. * To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h. * * By default, the server assumes that HTTP headers are already present in * each file stored in the file system. By defining LWIP_HTTPD_DYNAMIC_HEADERS in * lwipopts.h, this behavior can be changed such that the server inserts the * headers automatically based on the extension of the file being served. If * this mode is used, be careful to ensure that the file system image used * does not already contain the header information. * * File system images without headers can be created using the makefsfile * tool with the -h command line option. * * * Notes about valid SSI tags * -------------------------- * * The following assumptions are made about tags used in SSI markers: * * 1. No tag may contain '-' or whitespace characters within the tag name. * 2. Whitespace is allowed between the tag leadin "<!--#" and the start of * the tag name and between the tag name and the leadout string "-->". * 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters. * * Notes on CGI usage * ------------------ * * The simple CGI support offered here works with GET method requests only * and can handle up to 16 parameters encoded into the URI. The handler * function may not write directly to the HTTP output but must return a * filename that the HTTP server will send to the browser as a response to * the incoming CGI request. * * * * The list of supported file types is quite short, so if makefsdata complains * about an unknown extension, make sure to add it (and its doctype) to * the 'g_psHTTPHeaders' list. */ #include "lwip/init.h" #include "lwip/apps/httpd.h" #include "lwip/debug.h" #include "lwip/stats.h" #include "lwip/apps/fs.h" #include "httpd_structs.h" #include "lwip/def.h" #include "lwip/ip.h" #include "lwip/tcp.h" #include <string.h> /* memset */ #include <stdlib.h> /* atoi */ #include <stdio.h> #if LWIP_TCP && LWIP_CALLBACK_API /** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */ #define MIN_REQ_LEN 7 #define CRLF "\r\n" #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE #define HTTP11_CONNECTIONKEEPALIVE "Connection: keep-alive" #define HTTP11_CONNECTIONKEEPALIVE2 "Connection: Keep-Alive" #endif /** These defines check whether tcp_write has to copy data or not */ /** This was TI's check whether to let TCP copy data or not * \#define HTTP_IS_DATA_VOLATILE(hs) ((hs->file < (char *)0x20000000) ? 0 : TCP_WRITE_FLAG_COPY) */ #ifndef HTTP_IS_DATA_VOLATILE #if LWIP_HTTPD_SSI /* Copy for SSI files, no copy for non-SSI files */ #define HTTP_IS_DATA_VOLATILE(hs) ((hs)->ssi ? TCP_WRITE_FLAG_COPY : 0) #else /* LWIP_HTTPD_SSI */ /** Default: don't copy if the data is sent from file-system directly */ #define HTTP_IS_DATA_VOLATILE(hs) (((hs->file != NULL) && (hs->handle != NULL) && (hs->file == \ (const char*)hs->handle->data + hs->handle->len - hs->left)) \ ? 0 : TCP_WRITE_FLAG_COPY) #endif /* LWIP_HTTPD_SSI */ #endif /** Default: headers are sent from ROM */ #ifndef HTTP_IS_HDR_VOLATILE #define HTTP_IS_HDR_VOLATILE(hs, ptr) 0 #endif /* Return values for http_send_*() */ #define HTTP_DATA_TO_SEND_BREAK 2 #define HTTP_DATA_TO_SEND_CONTINUE 1 #define HTTP_NO_DATA_TO_SEND 0 typedef struct { const char *name; u8_t shtml; } default_filename; const default_filename g_psDefaultFilenames[] = { {"/index.shtml", 1 }, {"/index.ssi", 1 }, {"/index.shtm", 1 }, {"/index.html", 0 }, {"/index.htm", 0 } }; #define NUM_DEFAULT_FILENAMES (sizeof(g_psDefaultFilenames) / \ sizeof(default_filename)) #if LWIP_HTTPD_SUPPORT_REQUESTLIST /** HTTP request is copied here from pbufs for simple parsing */ static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH+1]; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_SUPPORT_POST #if LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN > LWIP_HTTPD_MAX_REQUEST_URI_LEN #define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN #endif #endif #ifndef LWIP_HTTPD_URI_BUF_LEN #define LWIP_HTTPD_URI_BUF_LEN LWIP_HTTPD_MAX_REQUEST_URI_LEN #endif #if LWIP_HTTPD_URI_BUF_LEN /* Filename for response file to send when POST is finished or * search for default files when a directory is requested. */ static char http_uri_buf[LWIP_HTTPD_URI_BUF_LEN+1]; #endif #if LWIP_HTTPD_DYNAMIC_HEADERS /* The number of individual strings that comprise the headers sent before each * requested file. */ #define NUM_FILE_HDR_STRINGS 5 #define HDR_STRINGS_IDX_HTTP_STATUS 0 /* e.g. "HTTP/1.0 200 OK\r\n" */ #define HDR_STRINGS_IDX_SERVER_NAME 1 /* e.g. "Server: "HTTPD_SERVER_AGENT"\r\n" */ #define HDR_STRINGS_IDX_CONTENT_LEN_KEPALIVE 2 /* e.g. "Content-Length: xy\r\n" and/or "Connection: keep-alive\r\n" */ #define HDR_STRINGS_IDX_CONTENT_LEN_NR 3 /* the byte count, when content-length is used */ #define HDR_STRINGS_IDX_CONTENT_TYPE 4 /* the content type (or default answer content type including default document) */ /* The dynamically generated Content-Length buffer needs space for CRLF + NULL */ #define LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET 3 #ifndef LWIP_HTTPD_MAX_CONTENT_LEN_SIZE /* The dynamically generated Content-Length buffer shall be able to work with ~953 MB (9 digits) */ #define LWIP_HTTPD_MAX_CONTENT_LEN_SIZE (9 + LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET) #endif #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SSI #define HTTPD_LAST_TAG_PART 0xFFFF enum tag_check_state { TAG_NONE, /* Not processing an SSI tag */ TAG_LEADIN, /* Tag lead in "<!--#" being processed */ TAG_FOUND, /* Tag name being read, looking for lead-out start */ TAG_LEADOUT, /* Tag lead out "-->" being processed */ TAG_SENDING /* Sending tag replacement string */ }; struct http_ssi_state { const char *parsed; /* Pointer to the first unparsed byte in buf. */ #if !LWIP_HTTPD_SSI_INCLUDE_TAG const char *tag_started;/* Pointer to the first opening '<' of the tag. */ #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ const char *tag_end; /* Pointer to char after the closing '>' of the tag. */ u32_t parse_left; /* Number of unparsed bytes in buf. */ u16_t tag_index; /* Counter used by tag parsing state machine */ u16_t tag_insert_len; /* Length of insert in string tag_insert */ #if LWIP_HTTPD_SSI_MULTIPART u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */ #endif /* LWIP_HTTPD_SSI_MULTIPART */ u8_t tag_name_len; /* Length of the tag name in string tag_name */ char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */ char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */ enum tag_check_state tag_state; /* State of the tag processor */ }; #endif /* LWIP_HTTPD_SSI */ struct http_state { #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED struct http_state *next; #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ struct fs_file file_handle; struct fs_file *handle; const char *file; /* Pointer to first unsent byte in buf. */ struct tcp_pcb *pcb; #if LWIP_HTTPD_SUPPORT_REQUESTLIST struct pbuf *req; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_DYNAMIC_FILE_READ char *buf; /* File read buffer. */ int buf_len; /* Size of file read buffer, buf. */ #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ u32_t left; /* Number of unsent bytes in buf. */ u8_t retries; #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE u8_t keepalive; #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ #if LWIP_HTTPD_SSI struct http_ssi_state *ssi; #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */ char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */ #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_DYNAMIC_HEADERS const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */ char hdr_content_len[LWIP_HTTPD_MAX_CONTENT_LEN_SIZE]; u16_t hdr_pos; /* The position of the first unsent header byte in the current string */ u16_t hdr_index; /* The index of the hdr string currently being sent. */ #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_TIMING u32_t time_started; #endif /* LWIP_HTTPD_TIMING */ #if LWIP_HTTPD_SUPPORT_POST u32_t post_content_len_left; #if LWIP_HTTPD_POST_MANUAL_WND u32_t unrecved_bytes; u8_t no_auto_wnd; u8_t post_finished; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ #endif /* LWIP_HTTPD_SUPPORT_POST*/ }; #if HTTPD_USE_MEM_POOL LWIP_MEMPOOL_DECLARE(HTTPD_STATE, MEMP_NUM_PARALLEL_HTTPD_CONNS, sizeof(struct http_state), "HTTPD_STATE") #if LWIP_HTTPD_SSI LWIP_MEMPOOL_DECLARE(HTTPD_SSI_STATE, MEMP_NUM_PARALLEL_HTTPD_SSI_CONNS, sizeof(struct http_ssi_state), "HTTPD_SSI_STATE") #define HTTP_FREE_SSI_STATE(x) LWIP_MEMPOOL_FREE(HTTPD_SSI_STATE, (x)) #define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)LWIP_MEMPOOL_ALLOC(HTTPD_SSI_STATE) #endif /* LWIP_HTTPD_SSI */ #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)LWIP_MEMPOOL_ALLOC(HTTPD_STATE) #define HTTP_FREE_HTTP_STATE(x) LWIP_MEMPOOL_FREE(HTTPD_STATE, (x)) #else /* HTTPD_USE_MEM_POOL */ #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)mem_malloc(sizeof(struct http_state)) #define HTTP_FREE_HTTP_STATE(x) mem_free(x) #if LWIP_HTTPD_SSI #define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state)) #define HTTP_FREE_SSI_STATE(x) mem_free(x) #endif /* LWIP_HTTPD_SSI */ #endif /* HTTPD_USE_MEM_POOL */ static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs); static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn); static err_t http_find_file(struct http_state *hs, const char *uri, int is_09); static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check, char* params); static err_t http_poll(void *arg, struct tcp_pcb *pcb); static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs); #if LWIP_HTTPD_FS_ASYNC_READ static void http_continue(void *connection); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #if LWIP_HTTPD_SSI /* SSI insert handler function pointer. */ tSSIHandler g_pfnSSIHandler; #if !LWIP_HTTPD_SSI_RAW int g_iNumTags; const char **g_ppcTags; #endif /* !LWIP_HTTPD_SSI_RAW */ #define LEN_TAG_LEAD_IN 5 const char * const g_pcTagLeadIn = "<!--#"; #define LEN_TAG_LEAD_OUT 3 const char * const g_pcTagLeadOut = "-->"; #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI /* CGI handler information */ const tCGI *g_pCGIs; int g_iNumCGIs; int http_cgi_paramcount; #define http_cgi_params hs->params #define http_cgi_param_vals hs->param_vals #elif LWIP_HTTPD_CGI_SSI char *http_cgi_params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */ char *http_cgi_param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */ #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED /** global list of active HTTP connections, use to kill the oldest when running out of memory */ static struct http_state *http_connections; static void http_add_connection(struct http_state *hs) { /* add the connection to the list */ hs->next = http_connections; http_connections = hs; } static void http_remove_connection(struct http_state *hs) { /* take the connection off the list */ if (http_connections) { if (http_connections == hs) { http_connections = hs->next; } else { struct http_state *last; for(last = http_connections; last->next != NULL; last = last->next) { if (last->next == hs) { last->next = hs->next; break; } } } } } static void http_kill_oldest_connection(u8_t ssi_required) { struct http_state *hs = http_connections; struct http_state *hs_free_next = NULL; while(hs && hs->next) { #if LWIP_HTTPD_SSI if (ssi_required) { if (hs->next->ssi != NULL) { hs_free_next = hs; } } else #else /* LWIP_HTTPD_SSI */ LWIP_UNUSED_ARG(ssi_required); #endif /* LWIP_HTTPD_SSI */ { hs_free_next = hs; } LWIP_ASSERT("broken list", hs != hs->next); hs = hs->next; } if (hs_free_next != NULL) { LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL); LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL); /* send RST when killing a connection because of memory shortage */ http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */ } } #else /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ #define http_add_connection(hs) #define http_remove_connection(hs) #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ #if LWIP_HTTPD_SSI /** Allocate as struct http_ssi_state. */ static struct http_ssi_state* http_ssi_state_alloc(void) { struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE(); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED if (ret == NULL) { http_kill_oldest_connection(1); ret = HTTP_ALLOC_SSI_STATE(); } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ if (ret != NULL) { memset(ret, 0, sizeof(struct http_ssi_state)); } return ret; } /** Free a struct http_ssi_state. */ static void http_ssi_state_free(struct http_ssi_state *ssi) { if (ssi != NULL) { HTTP_FREE_SSI_STATE(ssi); } } #endif /* LWIP_HTTPD_SSI */ /** Initialize a struct http_state. */ static void http_state_init(struct http_state* hs) { /* Initialize the structure. */ memset(hs, 0, sizeof(struct http_state)); #if LWIP_HTTPD_DYNAMIC_HEADERS /* Indicate that the headers are not yet valid */ hs->hdr_index = NUM_FILE_HDR_STRINGS; #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ } /** Allocate a struct http_state. */ static struct http_state* http_state_alloc(void) { struct http_state *ret = HTTP_ALLOC_HTTP_STATE(); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED if (ret == NULL) { http_kill_oldest_connection(0); ret = HTTP_ALLOC_HTTP_STATE(); } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ if (ret != NULL) { http_state_init(ret); http_add_connection(ret); } return ret; } /** Free a struct http_state. * Also frees the file data if dynamic. */ static void http_state_eof(struct http_state *hs) { if(hs->handle) { #if LWIP_HTTPD_TIMING u32_t ms_needed = sys_now() - hs->time_started; u32_t needed = LWIP_MAX(1, (ms_needed/100)); LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n", ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed))); #endif /* LWIP_HTTPD_TIMING */ fs_close(hs->handle); hs->handle = NULL; } #if LWIP_HTTPD_DYNAMIC_FILE_READ if (hs->buf != NULL) { mem_free(hs->buf); hs->buf = NULL; } #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ #if LWIP_HTTPD_SSI if (hs->ssi) { http_ssi_state_free(hs->ssi); hs->ssi = NULL; } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_SUPPORT_REQUESTLIST if (hs->req) { pbuf_free(hs->req); hs->req = NULL; } #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ } /** Free a struct http_state. * Also frees the file data if dynamic. */ static void http_state_free(struct http_state *hs) { if (hs != NULL) { http_state_eof(hs); http_remove_connection(hs); HTTP_FREE_HTTP_STATE(hs); } } /** Call tcp_write() in a loop trying smaller and smaller length * * @param pcb tcp_pcb to send * @param ptr Data to send * @param length Length of data to send (in/out: on return, contains the * amount of data sent) * @param apiflags directly passed to tcp_write * @return the return value of tcp_write */ static err_t http_write(struct tcp_pcb *pcb, const void* ptr, u16_t *length, u8_t apiflags) { u16_t len, max_len; err_t err; LWIP_ASSERT("length != NULL", length != NULL); len = *length; if (len == 0) { return ERR_OK; } /* We cannot send more data than space available in the send buffer. */ max_len = tcp_sndbuf(pcb); if (max_len < len) { len = max_len; } #ifdef HTTPD_MAX_WRITE_LEN /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ max_len = HTTPD_MAX_WRITE_LEN(pcb); if(len > max_len) { len = max_len; } #endif /* HTTPD_MAX_WRITE_LEN */ do { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying go send %d bytes\n", len)); err = tcp_write(pcb, ptr, len, apiflags); if (err == ERR_MEM) { if ((tcp_sndbuf(pcb) == 0) || (tcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) { /* no need to try smaller sizes */ len = 1; } else { len /= 2; } LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed, trying less (%d bytes)\n", len)); } } while ((err == ERR_MEM) && (len > 1)); if (err == ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len)); *length = len; } else { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err))); *length = 0; } #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE /* ensure nagle is normally enabled (only disabled for persistent connections when all data has been enqueued but the connection stays open for the next request */ tcp_nagle_enable(pcb); #endif return err; } /** * The connection shall be actively closed (using RST to close from fault states). * Reset the sent- and recv-callbacks. * * @param pcb the tcp pcb to reset callbacks * @param hs connection state to free */ static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn) { err_t err; LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void*)pcb)); #if LWIP_HTTPD_SUPPORT_POST if (hs != NULL) { if ((hs->post_content_len_left != 0) #if LWIP_HTTPD_POST_MANUAL_WND || ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0)) #endif /* LWIP_HTTPD_POST_MANUAL_WND */ ) { /* make sure the post code knows that the connection is closed */ http_uri_buf[0] = 0; httpd_post_finished(hs, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN); } } #endif /* LWIP_HTTPD_SUPPORT_POST*/ tcp_arg(pcb, NULL); tcp_recv(pcb, NULL); tcp_err(pcb, NULL); tcp_poll(pcb, NULL, 0); tcp_sent(pcb, NULL); if (hs != NULL) { http_state_free(hs); } if (abort_conn) { tcp_abort(pcb); return ERR_OK; } err = tcp_close(pcb); if (err != ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void*)pcb)); /* error closing, try again later in poll */ tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); } return err; } /** * The connection shall be actively closed. * Reset the sent- and recv-callbacks. * * @param pcb the tcp pcb to reset callbacks * @param hs connection state to free */ static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs) { return http_close_or_abort_conn(pcb, hs, 0); } /** End of file: either close the connection (Connection: close) or * close the file (Connection: keep-alive) */ static void http_eof(struct tcp_pcb *pcb, struct http_state *hs) { /* HTTP/1.1 persistent connection? (Not supported for SSI) */ #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if (hs->keepalive) { http_remove_connection(hs); http_state_eof(hs); http_state_init(hs); /* restore state: */ hs->pcb = pcb; hs->keepalive = 1; http_add_connection(hs); /* ensure nagle doesn't interfere with sending all data as fast as possible: */ tcp_nagle_disable(pcb); } else #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ { http_close_conn(pcb, hs); } } #if LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI /** * Extract URI parameters from the parameter-part of an URI in the form * "test.cgi?x=y" @todo: better explanation! * Pointers to the parameters are stored in hs->param_vals. * * @param hs http connection state * @param params pointer to the NULL-terminated parameter string from the URI * @return number of parameters extracted */ static int extract_uri_parameters(struct http_state *hs, char *params) { char *pair; char *equals; int loop; LWIP_UNUSED_ARG(hs); /* If we have no parameters at all, return immediately. */ if(!params || (params[0] == '\0')) { return(0); } /* Get a pointer to our first parameter */ pair = params; /* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the * remainder (if any) */ for(loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) { /* Save the name of the parameter */ http_cgi_params[loop] = pair; /* Remember the start of this name=value pair */ equals = pair; /* Find the start of the next name=value pair and replace the delimiter * with a 0 to terminate the previous pair string. */ pair = strchr(pair, '&'); if(pair) { *pair = '\0'; pair++; } else { /* We didn't find a new parameter so find the end of the URI and * replace the space with a '\0' */ pair = strchr(equals, ' '); if(pair) { *pair = '\0'; } /* Revert to NULL so that we exit the loop as expected. */ pair = NULL; } /* Now find the '=' in the previous pair, replace it with '\0' and save * the parameter value string. */ equals = strchr(equals, '='); if(equals) { *equals = '\0'; http_cgi_param_vals[loop] = equals + 1; } else { http_cgi_param_vals[loop] = NULL; } } return loop; } #endif /* LWIP_HTTPD_CGI || LWIP_HTTPD_CGI_SSI */ #if LWIP_HTTPD_SSI /** * Insert a tag (found in an shtml in the form of "<!--#tagname-->" into the file. * The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement * should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN). * The amount of data written is stored to ssi->tag_insert_len. * * @todo: return tag_insert_len - maybe it can be removed from struct http_state? * * @param hs http connection state */ static void get_tag_insert(struct http_state *hs) { #if LWIP_HTTPD_SSI_RAW const char* tag; #else /* LWIP_HTTPD_SSI_RAW */ int tag; #endif /* LWIP_HTTPD_SSI_RAW */ size_t len; struct http_ssi_state *ssi; #if LWIP_HTTPD_SSI_MULTIPART u16_t current_tag_part; #endif /* LWIP_HTTPD_SSI_MULTIPART */ LWIP_ASSERT("hs != NULL", hs != NULL); ssi = hs->ssi; LWIP_ASSERT("ssi != NULL", ssi != NULL); #if LWIP_HTTPD_SSI_MULTIPART current_tag_part = ssi->tag_part; ssi->tag_part = HTTPD_LAST_TAG_PART; #endif /* LWIP_HTTPD_SSI_MULTIPART */ #if LWIP_HTTPD_SSI_RAW tag = ssi->tag_name; #endif if(g_pfnSSIHandler #if !LWIP_HTTPD_SSI_RAW && g_ppcTags && g_iNumTags #endif /* !LWIP_HTTPD_SSI_RAW */ ) { /* Find this tag in the list we have been provided. */ #if LWIP_HTTPD_SSI_RAW { #else /* LWIP_HTTPD_SSI_RAW */ for(tag = 0; tag < g_iNumTags; tag++) { if(strcmp(ssi->tag_name, g_ppcTags[tag]) == 0) #endif /* LWIP_HTTPD_SSI_RAW */ { ssi->tag_insert_len = g_pfnSSIHandler(tag, ssi->tag_insert, LWIP_HTTPD_MAX_TAG_INSERT_LEN #if LWIP_HTTPD_SSI_MULTIPART , current_tag_part, &ssi->tag_part #endif /* LWIP_HTTPD_SSI_MULTIPART */ #if LWIP_HTTPD_FILE_STATE , (hs->handle ? hs->handle->state : NULL) #endif /* LWIP_HTTPD_FILE_STATE */ ); #if LWIP_HTTPD_SSI_RAW if (ssi->tag_insert_len != HTTPD_SSI_TAG_UNKNOWN) #endif /* LWIP_HTTPD_SSI_RAW */ { return; } } } } /* If we drop out, we were asked to serve a page which contains tags that * we don't have a handler for. Merely echo back the tags with an error * marker. */ #define UNKNOWN_TAG1_TEXT "<b>***UNKNOWN TAG " #define UNKNOWN_TAG1_LEN 18 #define UNKNOWN_TAG2_TEXT "***</b>" #define UNKNOWN_TAG2_LEN 7 len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name), LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN))); MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN); MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len); MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN); ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0; len = strlen(ssi->tag_insert); LWIP_ASSERT("len <= 0xffff", len <= 0xffff); ssi->tag_insert_len = (u16_t)len; } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_DYNAMIC_HEADERS /** * Generate the relevant HTTP headers for the given filename and write * them into the supplied buffer. */ static void get_http_headers(struct http_state *hs, const char *uri) { size_t content_type; char *tmp; char *ext; char *vars; u8_t add_content_len; /* In all cases, the second header we send is the server identification so set it here. */ hs->hdrs[HDR_STRINGS_IDX_SERVER_NAME] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER]; hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEPALIVE] = NULL; hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = NULL; /* Is this a normal file or the special case we use to send back the default "404: Page not found" response? */ if (uri == NULL) { hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if (hs->keepalive) { hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML_PERSISTENT]; } else #endif { hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaderStrings[DEFAULT_404_HTML]; } /* Set up to send the first header string. */ hs->hdr_index = 0; hs->hdr_pos = 0; return; } /* We are dealing with a particular filename. Look for one other special case. We assume that any filename with "404" in it must be indicative of a 404 server error whereas all other files require the 200 OK header. */ if (strstr(uri, "404")) { hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; } else if (strstr(uri, "400")) { hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST]; } else if (strstr(uri, "501")) { hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL]; } else { hs->hdrs[HDR_STRINGS_IDX_HTTP_STATUS] = g_psHTTPHeaderStrings[HTTP_HDR_OK]; } /* Determine if the URI has any variables and, if so, temporarily remove them. */ vars = strchr(uri, '?'); if(vars) { *vars = '\0'; } /* Get a pointer to the file extension. We find this by looking for the last occurrence of "." in the filename passed. */ ext = NULL; tmp = strchr(uri, '.'); while (tmp) { ext = tmp + 1; tmp = strchr(ext, '.'); } if (ext != NULL) { /* Now determine the content type and add the relevant header for that. */ for (content_type = 0; content_type < NUM_HTTP_HEADERS; content_type++) { /* Have we found a matching extension? */ if(!lwip_stricmp(g_psHTTPHeaders[content_type].extension, ext)) { break; } } } else { content_type = NUM_HTTP_HEADERS; } /* Reinstate the parameter marker if there was one in the original URI. */ if (vars) { *vars = '?'; } #if LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI /* Does the URL passed have any file extension? If not, we assume it is a special-case URL used for control state notification and we do not send any HTTP headers with the response. */ if (!ext) { /* Force the header index to a value indicating that all headers have already been sent. */ hs->hdr_index = NUM_FILE_HDR_STRINGS; return; } #endif /* LWIP_HTTPD_OMIT_HEADER_FOR_EXTENSIONLESS_URI */ add_content_len = 1; /* Did we find a matching extension? */ if(content_type < NUM_HTTP_HEADERS) { /* yes, store it */ hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = g_psHTTPHeaders[content_type].content_type; } else if (!ext) { /* no, no extension found -> use binary transfer to prevent the browser adding '.txt' on save */ hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_APP; } else { /* No - use the default, plain text file type. */ hs->hdrs[HDR_STRINGS_IDX_CONTENT_TYPE] = HTTP_HDR_DEFAULT_TYPE; } /* Add content-length header? */ #if LWIP_HTTPD_SSI if (hs->ssi != NULL) { add_content_len = 0; /* @todo: get maximum file length from SSI */ } else #endif /* LWIP_HTTPD_SSI */ if ((hs->handle == NULL) || ((hs->handle->flags & (FS_FILE_FLAGS_HEADER_INCLUDED|FS_FILE_FLAGS_HEADER_PERSISTENT)) == FS_FILE_FLAGS_HEADER_INCLUDED)) { add_content_len = 0; } if (add_content_len) { size_t len; lwip_itoa(hs->hdr_content_len, (size_t)LWIP_HTTPD_MAX_CONTENT_LEN_SIZE, hs->handle->len); len = strlen(hs->hdr_content_len); if (len <= LWIP_HTTPD_MAX_CONTENT_LEN_SIZE - LWIP_HTTPD_MAX_CONTENT_LEN_OFFSET) { SMEMCPY(&hs->hdr_content_len[len], CRLF "\0", 3); hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_NR] = hs->hdr_content_len; } else { add_content_len = 0; } } #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if (add_content_len) { hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_KEEPALIVE_LEN]; } else { hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONN_CLOSE]; } #else /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ if (add_content_len) { hs->hdrs[HDR_STRINGS_IDX_CONTENT_LEN_KEPALIVE] = g_psHTTPHeaderStrings[HTTP_HDR_CONTENT_LENGTH]; } #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ /* Set up to send the first header string. */ hs->hdr_index = 0; hs->hdr_pos = 0; } /** Sub-function of http_send(): send dynamic headers * * @returns: - HTTP_NO_DATA_TO_SEND: no new data has been enqueued * - HTTP_DATA_TO_SEND_CONTINUE: continue with sending HTTP body * - HTTP_DATA_TO_SEND_BREAK: data has been enqueued, headers pending, * so don't send HTTP body yet */ static u8_t http_send_headers(struct tcp_pcb *pcb, struct http_state *hs) { err_t err; u16_t len; u8_t data_to_send = HTTP_NO_DATA_TO_SEND; u16_t hdrlen, sendlen; /* How much data can we send? */ len = tcp_sndbuf(pcb); sendlen = len; while(len && (hs->hdr_index < NUM_FILE_HDR_STRINGS) && sendlen) { const void *ptr; u16_t old_sendlen; u8_t apiflags; /* How much do we have to send from the current header? */ hdrlen = (u16_t)strlen(hs->hdrs[hs->hdr_index]); /* How much of this can we send? */ sendlen = (len < (hdrlen - hs->hdr_pos)) ? len : (hdrlen - hs->hdr_pos); /* Send this amount of data or as much as we can given memory * constraints. */ ptr = (const void *)(hs->hdrs[hs->hdr_index] + hs->hdr_pos); old_sendlen = sendlen; apiflags = HTTP_IS_HDR_VOLATILE(hs, ptr); if (hs->hdr_index == HDR_STRINGS_IDX_CONTENT_LEN_NR) { /* content-length is always volatile */ apiflags |= TCP_WRITE_FLAG_COPY; } if (hs->hdr_index < NUM_FILE_HDR_STRINGS - 1) { apiflags |= TCP_WRITE_FLAG_MORE; } err = http_write(pcb, ptr, &sendlen, apiflags); if ((err == ERR_OK) && (old_sendlen != sendlen)) { /* Remember that we added some more data to be transmitted. */ data_to_send = HTTP_DATA_TO_SEND_CONTINUE; } else if (err != ERR_OK) { /* special case: http_write does not try to send 1 byte */ sendlen = 0; } /* Fix up the header position for the next time round. */ hs->hdr_pos += sendlen; len -= sendlen; /* Have we finished sending this string? */ if(hs->hdr_pos == hdrlen) { /* Yes - move on to the next one */ hs->hdr_index++; /* skip headers that are NULL (not all headers are required) */ while ((hs->hdr_index < NUM_FILE_HDR_STRINGS) && (hs->hdrs[hs->hdr_index] == NULL)) { hs->hdr_index++; } hs->hdr_pos = 0; } } if ((hs->hdr_index >= NUM_FILE_HDR_STRINGS) && (hs->file == NULL)) { /* When we are at the end of the headers, check for data to send * instead of waiting for ACK from remote side to continue * (which would happen when sending files from async read). */ if(http_check_eof(pcb, hs)) { data_to_send = HTTP_DATA_TO_SEND_CONTINUE; } } /* If we get here and there are still header bytes to send, we send * the header information we just wrote immediately. If there are no * more headers to send, but we do have file data to send, drop through * to try to send some file data too. */ if((hs->hdr_index < NUM_FILE_HDR_STRINGS) || !hs->file) { LWIP_DEBUGF(HTTPD_DEBUG, ("tcp_output\n")); return HTTP_DATA_TO_SEND_BREAK; } return data_to_send; } #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ /** Sub-function of http_send(): end-of-file (or block) is reached, * either close the file or read the next block (if supported). * * @returns: 0 if the file is finished or no data has been read * 1 if the file is not finished and data has been read */ static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs) { int bytes_left; #if LWIP_HTTPD_DYNAMIC_FILE_READ int count; #ifdef HTTPD_MAX_WRITE_LEN int max_write_len; #endif /* HTTPD_MAX_WRITE_LEN */ #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ /* Do we have a valid file handle? */ if (hs->handle == NULL) { /* No - close the connection. */ http_eof(pcb, hs); return 0; } bytes_left = fs_bytes_left(hs->handle); if (bytes_left <= 0) { /* We reached the end of the file so this request is done. */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } #if LWIP_HTTPD_DYNAMIC_FILE_READ /* Do we already have a send buffer allocated? */ if(hs->buf) { /* Yes - get the length of the buffer */ count = LWIP_MIN(hs->buf_len, bytes_left); } else { /* We don't have a send buffer so allocate one now */ count = tcp_sndbuf(pcb); if(bytes_left < count) { count = bytes_left; } #ifdef HTTPD_MAX_WRITE_LEN /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ max_write_len = HTTPD_MAX_WRITE_LEN(pcb); if (count > max_write_len) { count = max_write_len; } #endif /* HTTPD_MAX_WRITE_LEN */ do { hs->buf = (char*)mem_malloc((mem_size_t)count); if (hs->buf != NULL) { hs->buf_len = count; break; } count = count / 2; } while (count > 100); /* Did we get a send buffer? If not, return immediately. */ if (hs->buf == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("No buff\n")); return 0; } } /* Read a block of data from the file. */ LWIP_DEBUGF(HTTPD_DEBUG, ("Trying to read %d bytes.\n", count)); #if LWIP_HTTPD_FS_ASYNC_READ count = fs_read_async(hs->handle, hs->buf, count, http_continue, hs); #else /* LWIP_HTTPD_FS_ASYNC_READ */ count = fs_read(hs->handle, hs->buf, count); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ if (count < 0) { if (count == FS_READ_DELAYED) { /* Delayed read, wait for FS to unblock us */ return 0; } /* We reached the end of the file so this request is done. * @todo: close here for HTTP/1.1 when reading file fails */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } /* Set up to send the block of data we just read */ LWIP_DEBUGF(HTTPD_DEBUG, ("Read %d bytes.\n", count)); hs->left = count; hs->file = hs->buf; #if LWIP_HTTPD_SSI if (hs->ssi) { hs->ssi->parse_left = count; hs->ssi->parsed = hs->buf; } #endif /* LWIP_HTTPD_SSI */ #else /* LWIP_HTTPD_DYNAMIC_FILE_READ */ LWIP_ASSERT("SSI and DYNAMIC_HEADERS turned off but eof not reached", 0); #endif /* LWIP_HTTPD_SSI || LWIP_HTTPD_DYNAMIC_HEADERS */ return 1; } /** Sub-function of http_send(): This is the normal send-routine for non-ssi files * * @returns: - 1: data has been written (so call tcp_ouput) * - 0: no data has been written (no need to call tcp_output) */ static u8_t http_send_data_nonssi(struct tcp_pcb *pcb, struct http_state *hs) { err_t err; u16_t len; u8_t data_to_send = 0; /* We are not processing an SHTML file so no tag checking is necessary. * Just send the data as we received it from the file. */ len = (u16_t)LWIP_MIN(hs->left, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } return data_to_send; } #if LWIP_HTTPD_SSI /** Sub-function of http_send(): This is the send-routine for ssi files * * @returns: - 1: data has been written (so call tcp_ouput) * - 0: no data has been written (no need to call tcp_output) */ static u8_t http_send_data_ssi(struct tcp_pcb *pcb, struct http_state *hs) { err_t err = ERR_OK; u16_t len; u8_t data_to_send = 0; struct http_ssi_state *ssi = hs->ssi; LWIP_ASSERT("ssi != NULL", ssi != NULL); /* We are processing an SHTML file so need to scan for tags and replace * them with insert strings. We need to be careful here since a tag may * straddle the boundary of two blocks read from the file and we may also * have to split the insert string between two tcp_write operations. */ /* How much data could we send? */ len = tcp_sndbuf(pcb); /* Do we have remaining data to send before parsing more? */ if(ssi->parsed > hs->file) { len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } /* If the send buffer is full, return now. */ if(tcp_sndbuf(pcb) == 0) { return data_to_send; } } LWIP_DEBUGF(HTTPD_DEBUG, ("State %d, %d left\n", ssi->tag_state, (int)ssi->parse_left)); /* We have sent all the data that was already parsed so continue parsing * the buffer contents looking for SSI tags. */ while((ssi->parse_left) && (err == ERR_OK)) { if (len == 0) { return data_to_send; } switch(ssi->tag_state) { case TAG_NONE: /* We are not currently processing an SSI tag so scan for the * start of the lead-in marker. */ if(*ssi->parsed == g_pcTagLeadIn[0]) { /* We found what could be the lead-in for a new tag so change * state appropriately. */ ssi->tag_state = TAG_LEADIN; ssi->tag_index = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->tag_started = ssi->parsed; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; case TAG_LEADIN: /* We are processing the lead-in marker, looking for the start of * the tag name. */ /* Have we reached the end of the leadin? */ if(ssi->tag_index == LEN_TAG_LEAD_IN) { ssi->tag_index = 0; ssi->tag_state = TAG_FOUND; } else { /* Have we found the next character we expect for the tag leadin? */ if(*ssi->parsed == g_pcTagLeadIn[ssi->tag_index]) { /* Yes - move to the next one unless we have found the complete * leadin, in which case we start looking for the tag itself */ ssi->tag_index++; } else { /* We found an unexpected character so this is not a tag. Move * back to idle state. */ ssi->tag_state = TAG_NONE; } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; } break; case TAG_FOUND: /* We are reading the tag name, looking for the start of the * lead-out marker and removing any whitespace found. */ /* Remove leading whitespace between the tag leading and the first * tag name character. */ if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r'))) { /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; } /* Have we found the end of the tag name? This is signalled by * us finding the first leadout character or whitespace */ if((*ssi->parsed == g_pcTagLeadOut[0]) || (*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r')) { if(ssi->tag_index == 0) { /* We read a zero length tag so ignore it. */ ssi->tag_state = TAG_NONE; } else { /* We read a non-empty tag so go ahead and look for the * leadout string. */ ssi->tag_state = TAG_LEADOUT; LWIP_ASSERT("ssi->tag_index <= 0xff", ssi->tag_index <= 0xff); ssi->tag_name_len = (u8_t)ssi->tag_index; ssi->tag_name[ssi->tag_index] = '\0'; if(*ssi->parsed == g_pcTagLeadOut[0]) { ssi->tag_index = 1; } else { ssi->tag_index = 0; } } } else { /* This character is part of the tag name so save it */ if(ssi->tag_index < LWIP_HTTPD_MAX_TAG_NAME_LEN) { ssi->tag_name[ssi->tag_index++] = *ssi->parsed; } else { /* The tag was too long so ignore it. */ ssi->tag_state = TAG_NONE; } } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; /* We are looking for the end of the lead-out marker. */ case TAG_LEADOUT: /* Remove leading whitespace between the tag leading and the first * tag leadout character. */ if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r'))) { /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; } /* Have we found the next character we expect for the tag leadout? */ if(*ssi->parsed == g_pcTagLeadOut[ssi->tag_index]) { /* Yes - move to the next one unless we have found the complete * leadout, in which case we need to call the client to process * the tag. */ /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; if(ssi->tag_index == (LEN_TAG_LEAD_OUT - 1)) { /* Call the client to ask for the insert string for the * tag we just found. */ #if LWIP_HTTPD_SSI_MULTIPART ssi->tag_part = 0; /* start with tag part 0 */ #endif /* LWIP_HTTPD_SSI_MULTIPART */ get_tag_insert(hs); /* Next time through, we are going to be sending data * immediately, either the end of the block we start * sending here or the insert string. */ ssi->tag_index = 0; ssi->tag_state = TAG_SENDING; ssi->tag_end = ssi->parsed; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->parsed = ssi->tag_started; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ /* If there is any unsent data in the buffer prior to the * tag, we need to send it now. */ if (ssi->tag_end > hs->file) { /* How much of the data can we send? */ #if LWIP_HTTPD_SSI_INCLUDE_TAG len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ /* we would include the tag in sending */ len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG if(ssi->tag_started <= hs->file) { /* pretend to have sent the tag, too */ len += ssi->tag_end - ssi->tag_started; } #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ hs->file += len; hs->left -= len; } } } else { ssi->tag_index++; } } else { /* We found an unexpected character so this is not a tag. Move * back to idle state. */ ssi->parse_left--; ssi->parsed++; ssi->tag_state = TAG_NONE; } break; /* * We have found a valid tag and are in the process of sending * data as a result of that discovery. We send either remaining data * from the file prior to the insert point or the insert string itself. */ case TAG_SENDING: /* Do we have any remaining file data to send from the buffer prior * to the tag? */ if(ssi->tag_end > hs->file) { /* How much of the data can we send? */ #if LWIP_HTTPD_SSI_INCLUDE_TAG len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ LWIP_ASSERT("hs->started >= hs->file", ssi->tag_started >= hs->file); /* we would include the tag in sending */ len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ if (len != 0) { err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); } else { err = ERR_OK; } if (err == ERR_OK) { data_to_send = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG if(ssi->tag_started <= hs->file) { /* pretend to have sent the tag, too */ len += ssi->tag_end - ssi->tag_started; } #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ hs->file += len; hs->left -= len; } } else { #if LWIP_HTTPD_SSI_MULTIPART if(ssi->tag_index >= ssi->tag_insert_len) { /* Did the last SSIHandler have more to send? */ if (ssi->tag_part != HTTPD_LAST_TAG_PART) { /* If so, call it again */ ssi->tag_index = 0; get_tag_insert(hs); } } #endif /* LWIP_HTTPD_SSI_MULTIPART */ /* Do we still have insert data left to send? */ if(ssi->tag_index < ssi->tag_insert_len) { /* We are sending the insert string itself. How much of the * insert can we send? */ len = (ssi->tag_insert_len - ssi->tag_index); /* Note that we set the copy flag here since we only have a * single tag insert buffer per connection. If we don't do * this, insert corruption can occur if more than one insert * is processed before we call tcp_output. */ err = http_write(pcb, &(ssi->tag_insert[ssi->tag_index]), &len, HTTP_IS_TAG_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; ssi->tag_index += len; /* Don't return here: keep on sending data */ } } else { #if LWIP_HTTPD_SSI_MULTIPART if (ssi->tag_part == HTTPD_LAST_TAG_PART) #endif /* LWIP_HTTPD_SSI_MULTIPART */ { /* We have sent all the insert data so go back to looking for * a new tag. */ LWIP_DEBUGF(HTTPD_DEBUG, ("Everything sent.\n")); ssi->tag_index = 0; ssi->tag_state = TAG_NONE; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->parsed = ssi->tag_end; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ } } break; default: break; } } } /* If we drop out of the end of the for loop, this implies we must have * file data to send so send it now. In TAG_SENDING state, we've already * handled this so skip the send if that's the case. */ if((ssi->tag_state != TAG_SENDING) && (ssi->parsed > hs->file)) { len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } } return data_to_send; } #endif /* LWIP_HTTPD_SSI */ /** * Try to send more data on this pcb. * * @param pcb the pcb to send data * @param hs connection state */ static u8_t http_send(struct tcp_pcb *pcb, struct http_state *hs) { u8_t data_to_send = HTTP_NO_DATA_TO_SEND; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_send: pcb=%p hs=%p left=%d\n", (void*)pcb, (void*)hs, hs != NULL ? (int)hs->left : 0)); #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND if (hs->unrecved_bytes != 0) { return 0; } #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ /* If we were passed a NULL state structure pointer, ignore the call. */ if (hs == NULL) { return 0; } #if LWIP_HTTPD_FS_ASYNC_READ /* Check if we are allowed to read from this file. (e.g. SSI might want to delay sending until data is available) */ if (!fs_is_file_ready(hs->handle, http_continue, hs)) { return 0; } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #if LWIP_HTTPD_DYNAMIC_HEADERS /* Do we have any more header data to send for this file? */ if (hs->hdr_index < NUM_FILE_HDR_STRINGS) { data_to_send = http_send_headers(pcb, hs); if ((data_to_send != HTTP_DATA_TO_SEND_CONTINUE) && (hs->hdr_index < NUM_FILE_HDR_STRINGS)) { return data_to_send; } } #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ /* Have we run out of file data to send? If so, we need to read the next * block from the file. */ if (hs->left == 0) { if (!http_check_eof(pcb, hs)) { return 0; } } #if LWIP_HTTPD_SSI if(hs->ssi) { data_to_send = http_send_data_ssi(pcb, hs); } else #endif /* LWIP_HTTPD_SSI */ { data_to_send = http_send_data_nonssi(pcb, hs); } if((hs->left == 0) && (fs_bytes_left(hs->handle) <= 0)) { /* We reached the end of the file so this request is done. * This adds the FIN flag right into the last data segment. */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("send_data end.\n")); return data_to_send; } #if LWIP_HTTPD_SUPPORT_EXTSTATUS /** Initialize a http connection with a file to send for an error message * * @param hs http connection state * @param error_nr HTTP error number * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_find_error_file(struct http_state *hs, u16_t error_nr) { const char *uri1, *uri2, *uri3; err_t err; if (error_nr == 501) { uri1 = "/501.html"; uri2 = "/501.htm"; uri3 = "/501.shtml"; } else { /* 400 (bad request is the default) */ uri1 = "/400.html"; uri2 = "/400.htm"; uri3 = "/400.shtml"; } err = fs_open(&hs->file_handle, uri1); if (err != ERR_OK) { err = fs_open(&hs->file_handle, uri2); if (err != ERR_OK) { err = fs_open(&hs->file_handle, uri3); if (err != ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG, ("Error page for error %"U16_F" not found\n", error_nr)); return ERR_ARG; } } } return http_init_file(hs, &hs->file_handle, 0, NULL, 0, NULL); } #else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ #define http_find_error_file(hs, error_nr) ERR_ARG #endif /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ /** * Get the file struct for a 404 error page. * Tries some file names and returns NULL if none found. * * @param uri pointer that receives the actual file name URI * @return file struct for the error page or NULL no matching file was found */ static struct fs_file * http_get_404_file(struct http_state *hs, const char **uri) { err_t err; *uri = "/404.html"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.html doesn't exist. Try 404.htm instead. */ *uri = "/404.htm"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.htm doesn't exist either. Try 404.shtml instead. */ *uri = "/404.shtml"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.htm doesn't exist either. Indicate to the caller that it should * send back a default 404 page. */ *uri = NULL; return NULL; } } } return &hs->file_handle; } #if LWIP_HTTPD_SUPPORT_POST static err_t http_handle_post_finished(struct http_state *hs) { #if LWIP_HTTPD_POST_MANUAL_WND /* Prevent multiple calls to httpd_post_finished, since it might have already been called before from httpd_post_data_recved(). */ if (hs->post_finished) { return ERR_OK; } hs->post_finished = 1; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ /* application error or POST finished */ /* NULL-terminate the buffer */ http_uri_buf[0] = 0; httpd_post_finished(hs, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN); return http_find_file(hs, http_uri_buf, 0); } /** Pass received POST body data to the application and correctly handle * returning a response document or closing the connection. * ATTENTION: The application is responsible for the pbuf now, so don't free it! * * @param hs http connection state * @param p pbuf to pass to the application * @return ERR_OK if passed successfully, another err_t if the response file * hasn't been found (after POST finished) */ static err_t http_post_rxpbuf(struct http_state *hs, struct pbuf *p) { err_t err; if (p != NULL) { /* adjust remaining Content-Length */ if (hs->post_content_len_left < p->tot_len) { hs->post_content_len_left = 0; } else { hs->post_content_len_left -= p->tot_len; } } #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND /* prevent connection being closed if httpd_post_data_recved() is called nested */ hs->unrecved_bytes++; #endif err = httpd_post_receive_data(hs, p); #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND hs->unrecved_bytes--; #endif if (err != ERR_OK) { /* Ignore remaining content in case of application error */ hs->post_content_len_left = 0; } if (hs->post_content_len_left == 0) { #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND if (hs->unrecved_bytes != 0) { return ERR_OK; } #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ /* application error or POST finished */ return http_handle_post_finished(hs); } return ERR_OK; } /** Handle a post request. Called from http_parse_request when method 'POST' * is found. * * @param p The input pbuf (containing the POST header and body). * @param hs The http connection state. * @param data HTTP request (header and part of body) from input pbuf(s). * @param data_len Size of 'data'. * @param uri The HTTP URI parsed from input pbuf(s). * @param uri_end Pointer to the end of 'uri' (here, the rest of the HTTP * header starts). * @return ERR_OK: POST correctly parsed and accepted by the application. * ERR_INPROGRESS: POST not completely parsed (no error yet) * another err_t: Error parsing POST or denied by the application */ static err_t http_post_request(struct pbuf *inp, struct http_state *hs, char *data, u16_t data_len, char *uri, char *uri_end) { err_t err; /* search for end-of-header (first double-CRLF) */ char* crlfcrlf = lwip_strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data)); if (crlfcrlf != NULL) { /* search for "Content-Length: " */ #define HTTP_HDR_CONTENT_LEN "Content-Length: " #define HTTP_HDR_CONTENT_LEN_LEN 16 #define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN 10 char *scontent_len = lwip_strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1)); if (scontent_len != NULL) { char *scontent_len_end = lwip_strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN); if (scontent_len_end != NULL) { int content_len; char *content_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN; content_len = atoi(content_len_num); if (content_len == 0) { /* if atoi returns 0 on error, fix this */ if ((content_len_num[0] != '0') || (content_len_num[1] != '\r')) { content_len = -1; } } if (content_len >= 0) { /* adjust length of HTTP header passed to application */ const char *hdr_start_after_uri = uri_end + 1; u16_t hdr_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - data); u16_t hdr_data_len = (u16_t)LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri); u8_t post_auto_wnd = 1; http_uri_buf[0] = 0; /* trim http header */ *crlfcrlf = 0; err = httpd_post_begin(hs, uri, hdr_start_after_uri, hdr_data_len, content_len, http_uri_buf, LWIP_HTTPD_URI_BUF_LEN, &post_auto_wnd); if (err == ERR_OK) { /* try to pass in data of the first pbuf(s) */ struct pbuf *q = inp; u16_t start_offset = hdr_len; #if LWIP_HTTPD_POST_MANUAL_WND hs->no_auto_wnd = !post_auto_wnd; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ /* set the Content-Length to be received for this POST */ hs->post_content_len_left = (u32_t)content_len; /* get to the pbuf where the body starts */ while((q != NULL) && (q->len <= start_offset)) { start_offset -= q->len; q = q->next; } if (q != NULL) { /* hide the remaining HTTP header */ pbuf_header(q, -(s16_t)start_offset); #if LWIP_HTTPD_POST_MANUAL_WND if (!post_auto_wnd) { /* already tcp_recved() this data... */ hs->unrecved_bytes = q->tot_len; } #endif /* LWIP_HTTPD_POST_MANUAL_WND */ pbuf_ref(q); return http_post_rxpbuf(hs, q); } else if (hs->post_content_len_left == 0) { q = pbuf_alloc(PBUF_RAW, 0, PBUF_REF); return http_post_rxpbuf(hs, q); } else { return ERR_OK; } } else { /* return file passed from application */ return http_find_file(hs, http_uri_buf, 0); } } else { LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n", content_len_num)); return ERR_ARG; } } } /* If we come here, headers are fully received (double-crlf), but Content-Length was not included. Since this is currently the only supported method, we have to fail in this case! */ LWIP_DEBUGF(HTTPD_DEBUG, ("Error when parsing Content-Length\n")); return ERR_ARG; } /* if we come here, the POST is incomplete */ #if LWIP_HTTPD_SUPPORT_REQUESTLIST return ERR_INPROGRESS; #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ return ERR_ARG; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ } #if LWIP_HTTPD_POST_MANUAL_WND /** A POST implementation can call this function to update the TCP window. * This can be used to throttle data reception (e.g. when received data is * programmed to flash and data is received faster than programmed). * * @param connection A connection handle passed to httpd_post_begin for which * httpd_post_finished has *NOT* been called yet! * @param recved_len Length of data received (for window update) */ void httpd_post_data_recved(void *connection, u16_t recved_len) { struct http_state *hs = (struct http_state*)connection; if (hs != NULL) { if (hs->no_auto_wnd) { u16_t len = recved_len; if (hs->unrecved_bytes >= recved_len) { hs->unrecved_bytes -= recved_len; } else { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("httpd_post_data_recved: recved_len too big\n")); len = (u16_t)hs->unrecved_bytes; hs->unrecved_bytes = 0; } if (hs->pcb != NULL) { if (len != 0) { tcp_recved(hs->pcb, len); } if ((hs->post_content_len_left == 0) && (hs->unrecved_bytes == 0)) { /* finished handling POST */ http_handle_post_finished(hs); http_send(hs->pcb, hs); } } } } } #endif /* LWIP_HTTPD_POST_MANUAL_WND */ #endif /* LWIP_HTTPD_SUPPORT_POST */ #if LWIP_HTTPD_FS_ASYNC_READ /** Try to send more data if file has been blocked before * This is a callback function passed to fs_read_async(). */ static void http_continue(void *connection) { struct http_state *hs = (struct http_state*)connection; if (hs && (hs->pcb) && (hs->handle)) { LWIP_ASSERT("hs->pcb != NULL", hs->pcb != NULL); LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("httpd_continue: try to send more data\n")); if (http_send(hs->pcb, hs)) { /* If we wrote anything to be sent, go ahead and send it now. */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); tcp_output(hs->pcb); } } } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ /** * When data has been received in the correct state, try to parse it * as a HTTP request. * * @param inp the received pbuf * @param hs the connection state * @param pcb the tcp_pcb which received this packet * @return ERR_OK if request was OK and hs has been initialized correctly * ERR_INPROGRESS if request was OK so far but not fully received * another err_t otherwise */ static err_t http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) { char *data; char *crlf; u16_t data_len; struct pbuf *p = inp; #if LWIP_HTTPD_SUPPORT_REQUESTLIST u16_t clen; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_SUPPORT_POST err_t err; #endif /* LWIP_HTTPD_SUPPORT_POST */ LWIP_UNUSED_ARG(pcb); /* only used for post */ LWIP_ASSERT("p != NULL", p != NULL); LWIP_ASSERT("hs != NULL", hs != NULL); if ((hs->handle != NULL) || (hs->file != NULL)) { LWIP_DEBUGF(HTTPD_DEBUG, ("Received data while sending a file\n")); /* already sending a file */ /* @todo: abort? */ return ERR_USE; } #if LWIP_HTTPD_SUPPORT_REQUESTLIST LWIP_DEBUGF(HTTPD_DEBUG, ("Received %"U16_F" bytes\n", p->tot_len)); /* first check allowed characters in this pbuf? */ /* enqueue the pbuf */ if (hs->req == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("First pbuf\n")); hs->req = p; } else { LWIP_DEBUGF(HTTPD_DEBUG, ("pbuf enqueued\n")); pbuf_cat(hs->req, p); } /* increase pbuf ref counter as it is freed when we return but we want to keep it on the req list */ pbuf_ref(p); if (hs->req->next != NULL) { data_len = LWIP_MIN(hs->req->tot_len, LWIP_HTTPD_MAX_REQ_LENGTH); pbuf_copy_partial(hs->req, httpd_req_buf, data_len, 0); data = httpd_req_buf; } else #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ { data = (char *)p->payload; data_len = p->len; if (p->len != p->tot_len) { LWIP_DEBUGF(HTTPD_DEBUG, ("Warning: incomplete header due to chained pbufs\n")); } } /* received enough data for minimal request? */ if (data_len >= MIN_REQ_LEN) { /* wait for CRLF before parsing anything */ crlf = lwip_strnstr(data, CRLF, data_len); if (crlf != NULL) { #if LWIP_HTTPD_SUPPORT_POST int is_post = 0; #endif /* LWIP_HTTPD_SUPPORT_POST */ int is_09 = 0; char *sp1, *sp2; u16_t left_len, uri_len; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n")); /* parse method */ if (!strncmp(data, "GET ", 4)) { sp1 = data + 3; /* received GET request */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n")); #if LWIP_HTTPD_SUPPORT_POST } else if (!strncmp(data, "POST ", 5)) { /* store request type */ is_post = 1; sp1 = data + 4; /* received GET request */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n")); #endif /* LWIP_HTTPD_SUPPORT_POST */ } else { /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ data[4] = 0; /* unsupported method! */ LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n", data)); return http_find_error_file(hs, 501); } /* if we come here, method is OK, parse URI */ left_len = (u16_t)(data_len - ((sp1 +1) - data)); sp2 = lwip_strnstr(sp1 + 1, " ", left_len); #if LWIP_HTTPD_SUPPORT_V09 if (sp2 == NULL) { /* HTTP 0.9: respond with correct protocol version */ sp2 = lwip_strnstr(sp1 + 1, CRLF, left_len); is_09 = 1; #if LWIP_HTTPD_SUPPORT_POST if (is_post) { /* HTTP/0.9 does not support POST */ goto badrequest; } #endif /* LWIP_HTTPD_SUPPORT_POST */ } #endif /* LWIP_HTTPD_SUPPORT_V09 */ uri_len = (u16_t)(sp2 - (sp1 + 1)); if ((sp2 != 0) && (sp2 > sp1)) { /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */ if (lwip_strnstr(data, CRLF CRLF, data_len) != NULL) { char *uri = sp1 + 1; #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE /* This is HTTP/1.0 compatible: for strict 1.1, a connection would always be persistent unless "close" was specified. */ if (!is_09 && (lwip_strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len) || lwip_strnstr(data, HTTP11_CONNECTIONKEEPALIVE2, data_len))) { hs->keepalive = 1; } else { hs->keepalive = 0; } #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ *sp1 = 0; uri[uri_len] = 0; LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n", data, uri)); #if LWIP_HTTPD_SUPPORT_POST if (is_post) { #if LWIP_HTTPD_SUPPORT_REQUESTLIST struct pbuf *q = hs->req; #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ struct pbuf *q = inp; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ err = http_post_request(q, hs, data, data_len, uri, sp2); if (err != ERR_OK) { /* restore header for next try */ *sp1 = ' '; *sp2 = ' '; uri[uri_len] = ' '; } if (err == ERR_ARG) { goto badrequest; } return err; } else #endif /* LWIP_HTTPD_SUPPORT_POST */ { return http_find_file(hs, uri, is_09); } } } else { LWIP_DEBUGF(HTTPD_DEBUG, ("invalid URI\n")); } } } #if LWIP_HTTPD_SUPPORT_REQUESTLIST clen = pbuf_clen(hs->req); if ((hs->req->tot_len <= LWIP_HTTPD_REQ_BUFSIZE) && (clen <= LWIP_HTTPD_REQ_QUEUELEN)) { /* request not fully received (too short or CRLF is missing) */ return ERR_INPROGRESS; } else #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ { #if LWIP_HTTPD_SUPPORT_POST badrequest: #endif /* LWIP_HTTPD_SUPPORT_POST */ LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n")); /* could not parse request */ return http_find_error_file(hs, 400); } } /** Try to find the file specified by uri and, if found, initialize hs * accordingly. * * @param hs the connection state * @param uri the HTTP header URI * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_find_file(struct http_state *hs, const char *uri, int is_09) { size_t loop; struct fs_file *file = NULL; char *params = NULL; err_t err; #if LWIP_HTTPD_CGI int i; #endif /* LWIP_HTTPD_CGI */ #if !LWIP_HTTPD_SSI const #endif /* !LWIP_HTTPD_SSI */ /* By default, assume we will not be processing server-side-includes tags */ u8_t tag_check = 0; /* Have we been asked for the default file (in root or a directory) ? */ #if LWIP_HTTPD_MAX_REQUEST_URI_LEN size_t uri_len = strlen(uri); if ((uri_len > 0) && (uri[uri_len-1] == '/') && ((uri != http_uri_buf) || (uri_len == 1))) { size_t copy_len = LWIP_MIN(sizeof(http_uri_buf) - 1, uri_len - 1); if (copy_len > 0) { MEMCPY(http_uri_buf, uri, copy_len); http_uri_buf[copy_len] = 0; } #else /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */ if ((uri[0] == '/') && (uri[1] == 0)) { #endif /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */ /* Try each of the configured default filenames until we find one that exists. */ for (loop = 0; loop < NUM_DEFAULT_FILENAMES; loop++) { const char* file_name; #if LWIP_HTTPD_MAX_REQUEST_URI_LEN if (copy_len > 0) { size_t len_left = sizeof(http_uri_buf) - copy_len - 1; if (len_left > 0) { size_t name_len = strlen(g_psDefaultFilenames[loop].name); size_t name_copy_len = LWIP_MIN(len_left, name_len); MEMCPY(&http_uri_buf[copy_len], g_psDefaultFilenames[loop].name, name_copy_len); } file_name = http_uri_buf; } else #endif /* LWIP_HTTPD_MAX_REQUEST_URI_LEN */ { file_name = g_psDefaultFilenames[loop].name; } LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Looking for %s...\n", file_name)); err = fs_open(&hs->file_handle, file_name); if(err == ERR_OK) { uri = file_name; file = &hs->file_handle; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opened.\n")); #if LWIP_HTTPD_SSI tag_check = g_psDefaultFilenames[loop].shtml; #endif /* LWIP_HTTPD_SSI */ break; } } } if (file == NULL) { /* No - we've been asked for a specific file. */ /* First, isolate the base URI (without any parameters) */ params = (char *)strchr(uri, '?'); if (params != NULL) { /* URI contains parameters. NULL-terminate the base URI */ *params = '\0'; params++; } #if LWIP_HTTPD_CGI http_cgi_paramcount = -1; /* Does the base URI we have isolated correspond to a CGI handler? */ if (g_iNumCGIs && g_pCGIs) { for (i = 0; i < g_iNumCGIs; i++) { if (strcmp(uri, g_pCGIs[i].pcCGIName) == 0) { /* * We found a CGI that handles this URI so extract the * parameters and call the handler. */ http_cgi_paramcount = extract_uri_parameters(hs, params); uri = g_pCGIs[i].pfnCGIHandler(i, http_cgi_paramcount, hs->params, hs->param_vals); break; } } } #endif /* LWIP_HTTPD_CGI */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opening %s\n", uri)); err = fs_open(&hs->file_handle, uri); if (err == ERR_OK) { file = &hs->file_handle; } else { file = http_get_404_file(hs, &uri); } #if LWIP_HTTPD_SSI if (file != NULL) { /* See if we have been asked for an shtml file and, if so, enable tag checking. */ const char* ext = NULL, *sub; char* param = (char*)strstr(uri, "?"); if (param != NULL) { /* separate uri from parameters for now, set back later */ *param = 0; } sub = uri; ext = uri; for (sub = strstr(sub, "."); sub != NULL; sub = strstr(sub, ".")) { ext = sub; sub++; } tag_check = 0; for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) { if (!lwip_stricmp(ext, g_pcSSIExtensions[loop])) { tag_check = 1; break; } } if (param != NULL) { *param = '?'; } } #endif /* LWIP_HTTPD_SSI */ } if (file == NULL) { /* None of the default filenames exist so send back a 404 page */ file = http_get_404_file(hs, &uri); } return http_init_file(hs, file, is_09, uri, tag_check, params); } /** Initialize a http connection with a file to send (if found). * Called by http_find_file and http_find_error_file. * * @param hs http connection state * @param file file structure to send (or NULL if not found) * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) * @param uri the HTTP header URI * @param tag_check enable SSI tag checking * @param params != NULL if URI has parameters (separated by '?') * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check, char* params) { if (file != NULL) { /* file opened, initialise struct http_state */ #if LWIP_HTTPD_SSI if (tag_check) { struct http_ssi_state *ssi = http_ssi_state_alloc(); if (ssi != NULL) { ssi->tag_index = 0; ssi->tag_state = TAG_NONE; ssi->parsed = file->data; ssi->parse_left = file->len; ssi->tag_end = file->data; hs->ssi = ssi; } } #else /* LWIP_HTTPD_SSI */ LWIP_UNUSED_ARG(tag_check); #endif /* LWIP_HTTPD_SSI */ hs->handle = file; hs->file = file->data; LWIP_ASSERT("File length must be positive!", (file->len >= 0)); #if LWIP_HTTPD_CUSTOM_FILES if (file->is_custom_file && (file->data == NULL)) { /* custom file, need to read data first (via fs_read_custom) */ hs->left = 0; } else #endif /* LWIP_HTTPD_CUSTOM_FILES */ { hs->left = file->len; } hs->retries = 0; #if LWIP_HTTPD_TIMING hs->time_started = sys_now(); #endif /* LWIP_HTTPD_TIMING */ #if !LWIP_HTTPD_DYNAMIC_HEADERS LWIP_ASSERT("HTTP headers not included in file system", (hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) != 0); #endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SUPPORT_V09 if (is_09 && ((hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) != 0)) { /* HTTP/0.9 responses are sent without HTTP header, search for the end of the header. */ char *file_start = lwip_strnstr(hs->file, CRLF CRLF, hs->left); if (file_start != NULL) { size_t diff = file_start + 4 - hs->file; hs->file += diff; hs->left -= (u32_t)diff; } } #endif /* LWIP_HTTPD_SUPPORT_V09*/ #if LWIP_HTTPD_CGI_SSI if (params != NULL) { /* URI contains parameters, call generic CGI handler */ int count; #if LWIP_HTTPD_CGI if (http_cgi_paramcount >= 0) { count = http_cgi_paramcount; } else #endif { count = extract_uri_parameters(hs, params); } httpd_cgi_handler(uri, count, http_cgi_params, http_cgi_param_vals #if defined(LWIP_HTTPD_FILE_STATE) && LWIP_HTTPD_FILE_STATE , hs->handle->state #endif /* LWIP_HTTPD_FILE_STATE */ ); } #else /* LWIP_HTTPD_CGI_SSI */ LWIP_UNUSED_ARG(params); #endif /* LWIP_HTTPD_CGI_SSI */ } else { hs->handle = NULL; hs->file = NULL; hs->left = 0; hs->retries = 0; } #if LWIP_HTTPD_DYNAMIC_HEADERS /* Determine the HTTP headers to send based on the file extension of * the requested URI. */ if ((hs->handle == NULL) || ((hs->handle->flags & FS_FILE_FLAGS_HEADER_INCLUDED) == 0)) { get_http_headers(hs, uri); } #else /* LWIP_HTTPD_DYNAMIC_HEADERS */ LWIP_UNUSED_ARG(uri); #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if (hs->keepalive) { #if LWIP_HTTPD_SSI if (hs->ssi != NULL) { hs->keepalive = 0; } else #endif /* LWIP_HTTPD_SSI */ { if ((hs->handle != NULL) && ((hs->handle->flags & (FS_FILE_FLAGS_HEADER_INCLUDED|FS_FILE_FLAGS_HEADER_PERSISTENT)) == FS_FILE_FLAGS_HEADER_INCLUDED)) { hs->keepalive = 0; } } } #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ return ERR_OK; } /** * The pcb had an error and is already deallocated. * The argument might still be valid (if != NULL). */ static void http_err(void *arg, err_t err) { struct http_state *hs = (struct http_state *)arg; LWIP_UNUSED_ARG(err); LWIP_DEBUGF(HTTPD_DEBUG, ("http_err: %s", lwip_strerr(err))); if (hs != NULL) { http_state_free(hs); } } /** * Data has been sent and acknowledged by the remote host. * This means that more data can be sent. */ static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len) { struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_sent %p\n", (void*)pcb)); LWIP_UNUSED_ARG(len); if (hs == NULL) { return ERR_OK; } hs->retries = 0; http_send(pcb, hs); return ERR_OK; } /** * The poll function is called every 2nd second. * If there has been no data sent (which resets the retries) in 8 seconds, close. * If the last portion of a file has not been sent in 2 seconds, close. * * This could be increased, but we don't want to waste resources for bad connections. */ static err_t http_poll(void *arg, struct tcp_pcb *pcb) { struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: pcb=%p hs=%p pcb_state=%s\n", (void*)pcb, (void*)hs, tcp_debug_state_str(pcb->state))); if (hs == NULL) { err_t closed; /* arg is null, close. */ LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: arg is NULL, close\n")); closed = http_close_conn(pcb, NULL); LWIP_UNUSED_ARG(closed); #if LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR if (closed == ERR_MEM) { tcp_abort(pcb); return ERR_ABRT; } #endif /* LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR */ return ERR_OK; } else { hs->retries++; if (hs->retries == HTTPD_MAX_RETRIES) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: too many retries, close\n")); http_close_conn(pcb, hs); return ERR_OK; } /* If this connection has a file open, try to send some more data. If * it has not yet received a GET request, don't do this since it will * cause the connection to close immediately. */ if(hs && (hs->handle)) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: try to send more data\n")); if(http_send(pcb, hs)) { /* If we wrote anything to be sent, go ahead and send it now. */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); tcp_output(pcb); } } } return ERR_OK; } /** * Data has been received on this pcb. * For HTTP 1.0, this should normally only happen once (if the request fits in one packet). */ static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: pcb=%p pbuf=%p err=%s\n", (void*)pcb, (void*)p, lwip_strerr(err))); if ((err != ERR_OK) || (p == NULL) || (hs == NULL)) { /* error or closed by other side? */ if (p != NULL) { /* Inform TCP that we have taken the data. */ tcp_recved(pcb, p->tot_len); pbuf_free(p); } if (hs == NULL) { /* this should not happen, only to be robust */ LWIP_DEBUGF(HTTPD_DEBUG, ("Error, http_recv: hs is NULL, close\n")); } http_close_conn(pcb, hs); return ERR_OK; } #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND if (hs->no_auto_wnd) { hs->unrecved_bytes += p->tot_len; } else #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ { /* Inform TCP that we have taken the data. */ tcp_recved(pcb, p->tot_len); } #if LWIP_HTTPD_SUPPORT_POST if (hs->post_content_len_left > 0) { /* reset idle counter when POST data is received */ hs->retries = 0; /* this is data for a POST, pass the complete pbuf to the application */ http_post_rxpbuf(hs, p); /* pbuf is passed to the application, don't free it! */ if (hs->post_content_len_left == 0) { /* all data received, send response or close connection */ http_send(pcb, hs); } return ERR_OK; } else #endif /* LWIP_HTTPD_SUPPORT_POST */ { if (hs->handle == NULL) { err_t parsed = http_parse_request(p, hs, pcb); LWIP_ASSERT("http_parse_request: unexpected return value", parsed == ERR_OK || parsed == ERR_INPROGRESS ||parsed == ERR_ARG || parsed == ERR_USE); #if LWIP_HTTPD_SUPPORT_REQUESTLIST if (parsed != ERR_INPROGRESS) { /* request fully parsed or error */ if (hs->req != NULL) { pbuf_free(hs->req); hs->req = NULL; } } #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ pbuf_free(p); if (parsed == ERR_OK) { #if LWIP_HTTPD_SUPPORT_POST if (hs->post_content_len_left == 0) #endif /* LWIP_HTTPD_SUPPORT_POST */ { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: data %p len %"S32_F"\n", (const void*)hs->file, hs->left)); http_send(pcb, hs); } } else if (parsed == ERR_ARG) { /* @todo: close on ERR_USE? */ http_close_conn(pcb, hs); } } else { LWIP_DEBUGF(HTTPD_DEBUG, ("http_recv: already sending data\n")); /* already sending but still receiving data, we might want to RST here? */ pbuf_free(p); } } return ERR_OK; } /** * A new incoming connection has been accepted. */ static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err) { struct http_state *hs; LWIP_UNUSED_ARG(err); LWIP_UNUSED_ARG(arg); LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept %p / %p\n", (void*)pcb, arg)); if ((err != ERR_OK) || (pcb == NULL)) { return ERR_VAL; } /* Set priority */ tcp_setprio(pcb, HTTPD_TCP_PRIO); /* Allocate memory for the structure that holds the state of the connection - initialized by that function. */ hs = http_state_alloc(); if (hs == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept: Out of memory, RST\n")); return ERR_MEM; } hs->pcb = pcb; /* Tell TCP that this is the structure we wish to be passed for our callbacks. */ tcp_arg(pcb, hs); /* Set up the various callback functions */ tcp_recv(pcb, http_recv); tcp_err(pcb, http_err); tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); tcp_sent(pcb, http_sent); return ERR_OK; } /** * @ingroup httpd * Initialize the httpd: set up a listening PCB and bind it to the defined port */ void httpd_init(void) { struct tcp_pcb *pcb; err_t err; #if HTTPD_USE_MEM_POOL LWIP_MEMPOOL_INIT(HTTPD_STATE); #if LWIP_HTTPD_SSI LWIP_MEMPOOL_INIT(HTTPD_SSI_STATE); #endif #endif LWIP_DEBUGF(HTTPD_DEBUG, ("httpd_init\n")); pcb = tcp_new_ip_type(IPADDR_TYPE_ANY); LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL); tcp_setprio(pcb, HTTPD_TCP_PRIO); /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */ err = tcp_bind(pcb, IP_ANY_TYPE, HTTPD_SERVER_PORT); LWIP_UNUSED_ARG(err); /* in case of LWIP_NOASSERT */ LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK); pcb = tcp_listen(pcb); LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL); tcp_accept(pcb, http_accept); } #if LWIP_HTTPD_SSI /** * Set the SSI handler function. * * @param ssi_handler the SSI handler function * @param tags an array of SSI tag strings to search for in SSI-enabled files * @param num_tags number of tags in the 'tags' array */ void http_set_ssi_handler(tSSIHandler ssi_handler, const char **tags, int num_tags) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_set_ssi_handler\n")); LWIP_ASSERT("no ssi_handler given", ssi_handler != NULL); g_pfnSSIHandler = ssi_handler; #if LWIP_HTTPD_SSI_RAW LWIP_UNUSED_ARG(tags); LWIP_UNUSED_ARG(num_tags); #else /* LWIP_HTTPD_SSI_RAW */ LWIP_ASSERT("no tags given", tags != NULL); LWIP_ASSERT("invalid number of tags", num_tags > 0); g_ppcTags = tags; g_iNumTags = num_tags; #endif /* !LWIP_HTTPD_SSI_RAW */ } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI /** * Set an array of CGI filenames/handler functions * * @param cgis an array of CGI filenames/handler functions * @param num_handlers number of elements in the 'cgis' array */ void http_set_cgi_handlers(const tCGI *cgis, int num_handlers) { LWIP_ASSERT("no cgis given", cgis != NULL); LWIP_ASSERT("invalid number of handlers", num_handlers > 0); g_pCGIs = cgis; g_iNumCGIs = num_handlers; } #endif /* LWIP_HTTPD_CGI */ #endif /* LWIP_TCP && LWIP_CALLBACK_API */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/httpd.c
C
unknown
89,660
#ifndef LWIP_HTTPD_STRUCTS_H #define LWIP_HTTPD_STRUCTS_H #include "lwip/apps/httpd.h" #if LWIP_HTTPD_DYNAMIC_HEADERS /** This struct is used for a list of HTTP header strings for various * filename extensions. */ typedef struct { const char *extension; const char *content_type; } tHTTPHeader; /** A list of strings used in HTTP headers (see RFC 1945 HTTP/1.0 and * RFC 2616 HTTP/1.1 for header field definitions) */ static const char * const g_psHTTPHeaderStrings[] = { "HTTP/1.0 200 OK\r\n", "HTTP/1.0 404 File not found\r\n", "HTTP/1.0 400 Bad Request\r\n", "HTTP/1.0 501 Not Implemented\r\n", "HTTP/1.1 200 OK\r\n", "HTTP/1.1 404 File not found\r\n", "HTTP/1.1 400 Bad Request\r\n", "HTTP/1.1 501 Not Implemented\r\n", "Content-Length: ", "Connection: Close\r\n", "Connection: keep-alive\r\n", "Connection: keep-alive\r\nContent-Length: ", "Server: "HTTPD_SERVER_AGENT"\r\n", "\r\n<html><body><h2>404: The requested file cannot be found.</h2></body></html>\r\n" #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE ,"Connection: keep-alive\r\nContent-Length: 77\r\n\r\n<html><body><h2>404: The requested file cannot be found.</h2></body></html>\r\n" #endif }; /* Indexes into the g_psHTTPHeaderStrings array */ #define HTTP_HDR_OK 0 /* 200 OK */ #define HTTP_HDR_NOT_FOUND 1 /* 404 File not found */ #define HTTP_HDR_BAD_REQUEST 2 /* 400 Bad request */ #define HTTP_HDR_NOT_IMPL 3 /* 501 Not Implemented */ #define HTTP_HDR_OK_11 4 /* 200 OK */ #define HTTP_HDR_NOT_FOUND_11 5 /* 404 File not found */ #define HTTP_HDR_BAD_REQUEST_11 6 /* 400 Bad request */ #define HTTP_HDR_NOT_IMPL_11 7 /* 501 Not Implemented */ #define HTTP_HDR_CONTENT_LENGTH 8 /* Content-Length: (HTTP 1.0)*/ #define HTTP_HDR_CONN_CLOSE 9 /* Connection: Close (HTTP 1.1) */ #define HTTP_HDR_CONN_KEEPALIVE 10 /* Connection: keep-alive (HTTP 1.1) */ #define HTTP_HDR_KEEPALIVE_LEN 11 /* Connection: keep-alive + Content-Length: (HTTP 1.1)*/ #define HTTP_HDR_SERVER 12 /* Server: HTTPD_SERVER_AGENT */ #define DEFAULT_404_HTML 13 /* default 404 body */ #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE #define DEFAULT_404_HTML_PERSISTENT 14 /* default 404 body, but including Connection: keep-alive */ #endif #define HTTP_HDR_HTML "Content-type: text/html\r\n\r\n" #define HTTP_HDR_SSI "Content-type: text/html\r\nExpires: Fri, 10 Apr 2008 14:00:00 GMT\r\nPragma: no-cache\r\n\r\n" #define HTTP_HDR_GIF "Content-type: image/gif\r\n\r\n" #define HTTP_HDR_PNG "Content-type: image/png\r\n\r\n" #define HTTP_HDR_JPG "Content-type: image/jpeg\r\n\r\n" #define HTTP_HDR_BMP "Content-type: image/bmp\r\n\r\n" #define HTTP_HDR_ICO "Content-type: image/x-icon\r\n\r\n" #define HTTP_HDR_APP "Content-type: application/octet-stream\r\n\r\n" #define HTTP_HDR_JS "Content-type: application/javascript\r\n\r\n" #define HTTP_HDR_RA "Content-type: application/javascript\r\n\r\n" #define HTTP_HDR_CSS "Content-type: text/css\r\n\r\n" #define HTTP_HDR_SWF "Content-type: application/x-shockwave-flash\r\n\r\n" #define HTTP_HDR_XML "Content-type: text/xml\r\n\r\n" #define HTTP_HDR_PDF "Content-type: application/pdf\r\n\r\n" #define HTTP_HDR_JSON "Content-type: application/json\r\n\r\n" #define HTTP_HDR_DEFAULT_TYPE "Content-type: text/plain\r\n\r\n" /** A list of extension-to-HTTP header strings (see outdated RFC 1700 MEDIA TYPES * and http://www.iana.org/assignments/media-types for registered content types * and subtypes) */ static const tHTTPHeader g_psHTTPHeaders[] = { { "html", HTTP_HDR_HTML}, { "htm", HTTP_HDR_HTML}, { "shtml",HTTP_HDR_SSI}, { "shtm", HTTP_HDR_SSI}, { "ssi", HTTP_HDR_SSI}, { "gif", HTTP_HDR_GIF}, { "png", HTTP_HDR_PNG}, { "jpg", HTTP_HDR_JPG}, { "bmp", HTTP_HDR_BMP}, { "ico", HTTP_HDR_ICO}, { "class",HTTP_HDR_APP}, { "cls", HTTP_HDR_APP}, { "js", HTTP_HDR_JS}, { "ram", HTTP_HDR_RA}, { "css", HTTP_HDR_CSS}, { "swf", HTTP_HDR_SWF}, { "xml", HTTP_HDR_XML}, { "xsl", HTTP_HDR_XML}, { "pdf", HTTP_HDR_PDF}, { "json", HTTP_HDR_JSON} }; #define NUM_HTTP_HEADERS (sizeof(g_psHTTPHeaders) / sizeof(tHTTPHeader)) #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SSI static const char * const g_pcSSIExtensions[] = { ".shtml", ".shtm", ".ssi", ".xml" }; #define NUM_SHTML_EXTENSIONS (sizeof(g_pcSSIExtensions) / sizeof(const char *)) #endif /* LWIP_HTTPD_SSI */ #endif /* LWIP_HTTPD_STRUCTS_H */
2301_81045437/classic-platform
communication/lwip-2.0.3/src/apps/httpd/httpd_structs.h
C
unknown
4,671