NDS: WIP on combined dswifi support

This commit is contained in:
UnknownShadow200 2025-10-08 18:37:54 +11:00
parent 8459f9ed74
commit 72b29fee19
337 changed files with 36 additions and 127291 deletions

View File

@ -8,25 +8,22 @@ ARM_NONE_EABI_PATH ?= $(WONDERFUL_TOOLCHAIN)/toolchain/gcc-arm-none-eabi/bin/
SOURCEDIRS := misc/nds
INCLUDEDIRS :=
DSIWIFI := third_party/dsiwifi
ifdef BUILD_DSI
SOURCEDIRS += $(DSIWIFI)/arm_iop/source $(DSIWIFI)/common/source $(DSIWIFI)/arm_iop/source/ath $(DSIWIFI)/arm_iop/source/crypto $(DSIWIFI)/arm_iop/source/ieee
INCLUDEDIRS += $(DSIWIFI)/arm_iop/source $(DSIWIFI)/arm_iop/include $(DSIWIFI)/common/source $(DSIWIFI)/include $(DSIWIFI)/include/lwip
BUILDDIR := build/dsi
LIBS := -lc -lnds7
LIBDIRS := $(BLOCKSDS)/libs/libnds
ifdef BUILD_NONET
BUILDDIR := build/nds_nonet
else
BUILDDIR := build/nds
LIBS := -lc -lnds7 -ldswifi7
LIBDIRS := $(BLOCKSDS)/libs/libnds $(BLOCKSDS)/libs/dswifi
LIBS += -ldswifi7
LIBDIRS += $(BLOCKSDS)/libs/dswifi
endif
NAME := cc-arm7
NAME := cc-arm7
ELF := $(BUILDDIR)/$(NAME).elf
MAP := $(BUILDDIR)/$(NAME).map
PREFIX := $(ARM_NONE_EABI_PATH)arm-none-eabi-
PREFIX := $(ARM_NONE_EABI_PATH)arm-none-eabi-
CC := $(PREFIX)gcc
CXX := $(PREFIX)g++
LD := $(CC)

View File

@ -7,30 +7,26 @@ export WONDERFUL_TOOLCHAIN ?= /opt/wonderful
ARM_NONE_EABI_PATH ?= $(WONDERFUL_TOOLCHAIN)/toolchain/gcc-arm-none-eabi/bin/
SOURCEDIRS := src src/nds
INCLUDEDIRS :=
DSIWIFI := third_party/dsiwifi
ifdef BUILD_DSI
SOURCEDIRS += $(DSIWIFI)/arm_host/source $(DSIWIFI)/common/source $(DSIWIFI)/arm_host/source/nds $(DSIWIFI)/arm_host/source/lwip $(DSIWIFI)/arm_host/source/lwip/ipv4 $(DSIWIFI)/arm_host/source/lwip/ipv6 $(DSIWIFI)/arm_host/source/lwip/netif $(DSIWIFI)/arm_host/source/lwip/netif/ppp $(DSIWIFI)/arm_host/source/lwip/api
INCLUDEDIRS += $(DSIWIFI)/arm_host/include $(DSIWIFI)/common/source $(DSIWIFI)/include $(DSIWIFI)/include/lwip
BUILDDIR := build/dsi
DEFINES := -DPLAT_NDS -DBUILD_DSI
INCLUDEDIRS :=
DEFINES := -DPLAT_NDS
LIBS := -lnds9 -lc
LIBDIRS := $(BLOCKSDS)/libs/libnds
ifdef BUILD_NONET
BUILDDIR := build/nds_nonet
else
BUILDDIR := build/nds
DEFINES := -DPLAT_NDS
LIBS := -ldswifi9 -lnds9 -lc
LIBDIRS := $(BLOCKSDS)/libs/dswifi $(BLOCKSDS)/libs/libnds
LIBS += -ldswifi9
LIBDIRS += $(BLOCKSDS)/libs/dswifi
endif
NAME := cc-arm9
NAME := cc-arm9
ELF := $(BUILDDIR)/$(NAME).elf
MAP := $(BUILDDIR)/$(NAME).map
# Tools
# -----
PREFIX := $(ARM_NONE_EABI_PATH)arm-none-eabi-
PREFIX := $(ARM_NONE_EABI_PATH)arm-none-eabi-
CC := $(PREFIX)gcc
CXX := $(PREFIX)g++
LD := $(PREFIX)gcc

View File

@ -556,9 +556,7 @@ typedef cc_uint8 cc_bool;
#define CC_BUILD_MAXSTACK (16 * 1024) /* Only < 16 kb stack as it's in DTCM region */
#define CC_BUILD_NOFPU
#define CC_DISABLE_ANIMATIONS /* Very costly in FPU less system */
#ifndef BUILD_DSI
#undef CC_BUILD_ADVLIGHTING
#endif
#undef CC_BUILD_ADVLIGHTING
#define DEFAULT_NET_BACKEND CC_NET_BACKEND_BUILTIN
#define DEFAULT_AUD_BACKEND CC_AUD_BACKEND_NULL
#elif defined PLAT_WIIU

View File

@ -29,9 +29,9 @@ static void WaitForGPUDone(void) {
if (!GFX_BUSY) return;
// Geometry engine still busy from before, give it some time
swiWaitForVBlank();
swiWaitForVBlank();
swiWaitForVBlank();
cothread_yield_irq(IRQ_VBLANK);
cothread_yield_irq(IRQ_VBLANK);
cothread_yield_irq(IRQ_VBLANK);
if (!GFX_BUSY) return;
// The geometry engine may still have some leftover state, try to recover
@ -159,7 +159,7 @@ void Gfx_EndFrame(void) {
GFX_FLUSH = 0;
// TODO not needed?
swiWaitForVBlank();
cothread_yield_irq(IRQ_VBLANK);
}

View File

@ -30,11 +30,7 @@
#include <nds/arm9/sdmmc.h>
#include <nds/arm9/exceptions.h>
#include <fat.h>
#ifdef BUILD_DSI
#include <dsiwifi9.h>
#else
#include <dswifi9.h>
#endif
#include <netdb.h>
#include <netinet/in.h>
#include <sys/stat.h>
@ -510,11 +506,7 @@ cc_result Socket_Write(cc_socket s, const cc_uint8* data, cc_uint32 count, cc_ui
void Socket_Close(cc_socket s) {
shutdown(s, 2); // SHUT_RDWR = 2
#ifdef BUILD_DSI
lwip_close(s);
#else
closesocket(s);
#endif
}
static cc_result Socket_Poll(cc_socket s, int mode, cc_bool* success) {
@ -568,37 +560,30 @@ static void LogWifiStatus(int status) {
}
}
#define VSYNCS_PER_SEC 60
static void InitNetworking(void) {
#ifdef BUILD_DSI
if (!DSiWifi_InitDefault(INIT_ONLY)) {
#else
if (!Wifi_InitDefault(INIT_ONLY)) {
#endif
if (!Wifi_InitDefault(INIT_ONLY | WIFI_ATTEMPT_DSI_MODE)) {
Platform_LogConst("Initing WIFI failed");
net_supported = false; return;
}
#ifdef BUILD_DSI
DSiWifi_AutoConnect();
#else
Wifi_AutoConnect();
#endif
int last_status = -1;
for (int i = 0; i < 300; i++)
for (int i = 0; i < VSYNCS_PER_SEC * 10; i++)
{
#ifdef BUILD_DSI
int status = DSiWifi_AssocStatus();
#else
int status = Wifi_AssocStatus();
#endif
LogWifiStatus(status);
if (status == ASSOCSTATUS_ASSOCIATED) return;
int status = Wifi_AssocStatus();
int do_log = status != last_status || ((i % VSYNCS_PER_SEC) == 0);
if (do_log) LogWifiStatus(status);
last_status = status;
if (status == ASSOCSTATUS_ASSOCIATED) return;
if (status == ASSOCSTATUS_CANNOTCONNECT) {
net_supported = false; return;
}
swiWaitForVBlank();
cothread_yield_irq(IRQ_VBLANK);
}
Platform_LogConst("Gave up after 300 tries");
Platform_LogConst("Gave up after ~10 seconds");
net_supported = false;
}
@ -608,11 +593,7 @@ static void InitNetworking(void) {
*#########################################################################################################################*/
void Platform_Init(void) {
cc_bool dsiMode = isDSiMode();
#ifdef BUILD_DSI
Platform_Log1("Running in %c mode with DSi wifi", dsiMode ? "DSi" : "DS");
#else
Platform_Log1("Running in %c mode with NDS wifi", dsiMode ? "DSi" : "DS");
#endif
Platform_Log1("Running in %c mode", dsiMode ? "DSi" : "DS");
InitFilesystem();
InitNetworking();

View File

@ -9,11 +9,7 @@
#include "../Errors.h"
#include "../ExtMath.h"
#include "../Camera.h"
#include <nds/arm9/background.h>
#include <nds/arm9/input.h>
#include <nds/arm9/keyboard.h>
#include <nds/interrupts.h>
#include <nds/system.h>
#include <nds.h>
#include <fat.h>
#define LAYER_CON 0
@ -312,7 +308,7 @@ void Window_AllocFramebuffer(struct Bitmap* bmp, int width, int height) {
}
void Window_DrawFramebuffer(Rect2D r, struct Bitmap* bmp) {
swiWaitForVBlank();
cothread_yield_irq(IRQ_VBLANK);
for (int y = r.y; y < r.y + r.height; y++)
{

View File

@ -1,6 +0,0 @@
arm_iop/debug
arm_iop/release
arm_host/debug
arm_host/release
lib
*.bz2

View File

@ -1,76 +0,0 @@
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>devkitPro")
endif
export TOPDIR := $(CURDIR)
export DSIWIFI_MAJOR := 0
export DSIWIFI_MINOR := 1
export DSIWIFI_REVISION := 0
VERSION := $(DSIWIFI_MAJOR).$(DSIWIFI_MINOR).$(DSIWIFI_REVISION)
.PHONY: release debug clean all test_app
all: include/dswifi_version.h release debug test_app
include/dswifi_version.h : Makefile
@echo "#ifndef _dswifi_version_h_" > $@
@echo "#define _dswifi_version_h_" >> $@
@echo >> $@
@echo "#define DSIWIFI_MAJOR $(DSIWIFI_MAJOR)" >> $@
@echo "#define DSIWIFI_MINOR $(DSIWIFI_MINOR)" >> $@
@echo "#define DSIWIFI_REVISION $(DSIWIFI_REVISION)" >> $@
@echo >> $@
@echo '#define DSIWIFI_VERSION "'$(DSIWIFI_MAJOR).$(DSIWIFI_MINOR).$(DSIWIFI_REVISION)'"' >> $@
@echo >> $@
@echo "#endif // _dsiwifi_version_h_" >> $@
#-------------------------------------------------------------------------------
test_app: debug
#-------------------------------------------------------------------------------
$(MAKE) -C test_app
#-------------------------------------------------------------------------------
release: lib
#-------------------------------------------------------------------------------
$(MAKE) -C arm_host BUILD=release
$(MAKE) -C arm_iop BUILD=release
#-------------------------------------------------------------------------------
debug: lib
#-------------------------------------------------------------------------------
$(MAKE) -C arm_host BUILD=debug
$(MAKE) -C arm_iop BUILD=debug
#-------------------------------------------------------------------------------
lib:
#-------------------------------------------------------------------------------
mkdir lib
#-------------------------------------------------------------------------------
clean:
#-------------------------------------------------------------------------------
@$(MAKE) -C arm_host clean
@$(MAKE) -C arm_iop clean
@$(MAKE) -C test_app clean
@$(RM) -r dsiwifi-src-*.tar.bz2 dsiwifi-*.tar.bz2 include/dsiwifi_version.h lib
#-------------------------------------------------------------------------------
dist-src:
#-------------------------------------------------------------------------------
@tar --exclude=*CVS* --exclude=.svn -cjf dsiwifi-src-$(VERSION).tar.bz2 arm_iop/source arm_iop/Makefile arm_host/source arm_host/Makefile common include Makefile dsiwifi_license.txt dswifi_license.txt
#-------------------------------------------------------------------------------
dist-bin: all
#-------------------------------------------------------------------------------
@tar --exclude=*CVS* --exclude=.svn -cjf dsiwifi-$(VERSION).tar.bz2 include lib dsiwifi_license.txt dswifi_license.txt
dist: dist-bin dist-src
#-------------------------------------------------------------------------------
install: dist-bin
#-------------------------------------------------------------------------------
mkdir -p $(DESTDIR)$(DEVKITPRO)/libnds
bzip2 -cd dsiwifi-$(VERSION).tar.bz2 | tar -x -C $(DESTDIR)$(DEVKITPRO)/libnds

View File

@ -1,149 +0,0 @@
#---------------------------------------------------------------------------------
.SUFFIXES:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITARM)),)
$(error "Please set DEVKITARM in your environment. export DEVKITARM=<path to>devkitARM")
endif
include $(DEVKITARM)/ds_rules
TOPDIR ?= $(CURDIR)/..
#---------------------------------------------------------------------------------
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
# DATA is a list of directories containing binary files
# all directories are relative to this makefile
#---------------------------------------------------------------------------------
BUILD ?= release
SOURCES := source ../common/source source/nds source/lwip source/lwip/ipv4 source/lwip/ipv6 source/lwip/netif source/lwip/netif/ppp source/lwip/api
INCLUDES := include ../common/source ../include ../include/lwip source/nds
DATA := data
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
ARCH := -mthumb -mthumb-interwork
CFLAGS := -g -Wall -Os\
-ffunction-sections -fdata-sections \
-march=armv5te -mtune=arm946e-s -fomit-frame-pointer -mno-unaligned-access\
-ffast-math \
$(ARCH)
CFLAGS += $(INCLUDE) -DARM9 -DARM_HOST
CXXFLAGS := $(CFLAGS)
ASFLAGS := -g $(ARCH) $(INCLUDE) -DARM9 -DARM_HOST
LDFLAGS = -specs=ds_arm9.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map)
ifneq ($(BUILD),debug)
export ARM9BIN := $(TOPDIR)/lib/libdsiwifi9.a
else
export ARM9BIN := $(TOPDIR)/lib/libdsiwifi9d.a
CFLAGS += -DSGIP_DEBUG
endif
#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project
#---------------------------------------------------------------------------------
LIBS :=
#-lnds9
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS := $(LIBNDS)
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export DEPSDIR := $(CURDIR)/$(BUILD)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export CC := $(PREFIX)gcc
export CXX := $(PREFIX)g++
export AR := $(PREFIX)ar
export OBJCOPY := $(PREFIX)objcopy
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#---------------------------------------------------------------------------------
export LD := $(CC)
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
export LD := $(CXX)
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
export OFILES := $(addsuffix .o,$(BINFILES)) \
$(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o)
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
.PHONY: $(BUILD) clean
#---------------------------------------------------------------------------------
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr debug release
@rm -f $(TOPDIR)/lib/libdsiwifi9*
all: $(ARM9BIN)
#---------------------------------------------------------------------------------
else
DEPENDS := $(OFILES:.o=.d)
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(ARM9BIN) : $(OFILES)
@rm -f "$(ARM9BIN)"
@$(AR) rcs "$(ARM9BIN)" $(OFILES)
@echo built ... $(notdir $@)
#---------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#---------------------------------------------------------------------------------
%.bin.o : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#---------------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------------

View File

@ -1,248 +0,0 @@
// DS Wifi interface code
// Copyright (C) 2005-2006 Stephen Stair - sgstair@akkit.org - http://www.akkit.org
// wifi_arm9.c - arm9 wifi support code
/******************************************************************************
DSWifi Lib and test materials are licenced under the MIT open source licence:
Copyright (c) 2005-2006 Stephen Stair
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "dsiwifi9.h"
#include <nds.h>
#include "dsregs.h"
#include "dswifi9.h"
#include <stdarg.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <nds/arm9/sassert.h>
#include "wifi_host.h"
#ifdef WIFI_USE_TCP_SGIP
#include "nds/sgIP.h"
//////////////////////////////////////////////////////////////////////////
#endif
WifiLogHandler DSiWifi_pfnLogHandler = NULL;
WifiConnectHandler DSiWifi_pfnConnectHandler = NULL;
WifiReconnectHandler DSiWifi_pfnReconnectHandler = NULL;
u32 DSiWifi_TxBufferWordsAvailable() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
void DSiWifi_TxBufferWrite(s32 start, s32 len, u16 * data) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
int DSiWifi_RxRawReadPacket(s32 packetID, s32 readlength, u16 * data) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
u16 DSiWifi_RxReadOffset(s32 base, s32 offset) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_RawTxFrame(u16 datalen, u16 rate, u16 * data) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
void DSiWifi_RawSetPacketHandler(WifiPacketHandler wphfunc) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_SetSyncHandler(WifiSyncHandler wshfunc) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_DisableWifi() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_EnableWifi() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_SetPromiscuousMode(int enable) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_ScanMode() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_SetChannel(int channel) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
int DSiWifi_GetNumAP() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_GetAPData(int apnum, Wifi_AccessPoint * apdata) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_FindMatchingAP(int numaps, Wifi_AccessPoint * apdata, Wifi_AccessPoint * match_dest) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_ConnectAP(Wifi_AccessPoint * apdata, int wepmode, int wepkeyid, u8 * wepkey) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
void DSiWifi_AutoConnect() {
//sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
int DSiWifi_AssocStatus() {
//sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return wifi_host_get_status();
}
int DSiWifi_DisconnectAP() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
#ifdef WIFI_USE_TCP_SGIP
int DSiWifi_TransmitFunction(sgIP_Hub_HWInterface * hw, sgIP_memblock * mb) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_Interface_Init(sgIP_Hub_HWInterface * hw) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
void DSiWifi_Timer(int num_ms) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
#endif
unsigned long DSiWifi_Init(int initflags) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
int DSiWifi_CheckInit() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
void DSiWifi_Update() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
u32 DSiWifi_GetIP() {
return wifi_host_get_ipaddr();
}
struct in_addr DSiWifi_GetIPInfo(struct in_addr * pGateway,struct in_addr * pSnmask,struct in_addr * pDns1,struct in_addr * pDns2) {
//sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
struct in_addr ip = { wifi_host_get_ipaddr() };
return ip;
}
//////////////////////////////////////////////////////////////////////////
// Ip addr get/set functions
#ifdef WIFI_USE_TCP_SGIP
void DSiWifi_SetIP(u32 IPaddr, u32 gateway, u32 subnetmask, u32 dns1, u32 dns2) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
void DSiWifi_SetDHCP() {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
#endif
int DSiWifi_GetData(int datatype, int bufferlen, unsigned char * buffer) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return -1;
}
u32 DSiWifi_GetStats(int statnum) {
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
return 0;
}
//---------------------------------------------------------------------------------
// sync functions
//---------------------------------------------------------------------------------
void DSiWifi_Sync() {
//---------------------------------------------------------------------------------
sassert(false, "%s\nis currently unimplemented", __FUNCTION__);
}
//---------------------------------------------------------------------------------
bool DSiWifi_InitDefault(bool useFirmwareSettings) {
//---------------------------------------------------------------------------------
// TODO Wifi_InitDefault
wifi_host_init();
return true;
}
void DSiWifi_SetLogHandler(WifiLogHandler handler)
{
DSiWifi_pfnLogHandler = handler;
}
void DSiWifi_SetConnectHandler(WifiConnectHandler handler)
{
DSiWifi_pfnConnectHandler = handler;
}
void DSiWifi_SetReconnectHandler(WifiReconnectHandler handler)
{
DSiWifi_pfnReconnectHandler = handler;
}
void DSiWifi_Shutdown(void)
{
}

View File

@ -1,717 +0,0 @@
/**
* @file
* @defgroup altcp Application layered TCP Functions
* @ingroup altcp_api
*
* This file contains the common functions for altcp to work.
* For more details see @ref altcp_api.
*/
/**
* @defgroup altcp_api Application layered TCP Introduction
* @ingroup callbackstyle_api
*
* Overview
* --------
* altcp (application layered TCP connection API; to be used from TCPIP thread)
* is an abstraction layer that prevents applications linking hard against the
* @ref tcp.h functions while providing the same functionality. It is used to
* e.g. add SSL/TLS (see LWIP_ALTCP_TLS) or proxy-connect support to an application
* written for the tcp callback API without that application knowing the
* protocol details.
*
* * This interface mimics the tcp callback API to the application while preventing
* direct linking (much like virtual functions).
* * This way, an application can make use of other application layer protocols
* on top of TCP without knowing the details (e.g. TLS, proxy connection).
* * This is achieved by simply including "lwip/altcp.h" instead of "lwip/tcp.h",
* replacing "struct tcp_pcb" with "struct altcp_pcb" and prefixing all functions
* with "altcp_" instead of "tcp_".
*
* With altcp support disabled (LWIP_ALTCP==0), applications written against the
* altcp API can still be compiled but are directly linked against the tcp.h
* callback API and then cannot use layered protocols. To minimize code changes
* in this case, the use of altcp_allocators is strongly suggested.
*
* Usage
* -----
* To make use of this API from an existing tcp raw API application:
* * Include "lwip/altcp.h" instead of "lwip/tcp.h"
* * Replace "struct tcp_pcb" with "struct altcp_pcb"
* * Prefix all called tcp API functions with "altcp_" instead of "tcp_" to link
* against the altcp functions
* * @ref altcp_new (and @ref altcp_new_ip_type / @ref altcp_new_ip6) take
* an @ref altcp_allocator_t as an argument, whereas the original tcp API
* functions take no arguments.
* * An @ref altcp_allocator_t allocator is an object that holds a pointer to an
* allocator object and a corresponding state (e.g. for TLS, the corresponding
* state may hold certificates or keys). This way, the application does not
* even need to know if it uses TLS or pure TCP, this is handled at runtime
* by passing a specific allocator.
* * An application can alternatively bind hard to the altcp_tls API by calling
* @ref altcp_tls_new or @ref altcp_tls_wrap.
* * The TLS layer is not directly implemented by lwIP, but a port to mbedTLS is
* provided.
* * Another altcp layer is proxy-connect to use TLS behind a HTTP proxy (see
* @ref altcp_proxyconnect.h)
*
* altcp_allocator_t
* -----------------
* An altcp allocator is created by the application by combining an allocator
* callback function and a corresponding state, e.g.:\code{.c}
* static const unsigned char cert[] = {0x2D, ... (see mbedTLS doc for how to create this)};
* struct altcp_tls_config * conf = altcp_tls_create_config_client(cert, sizeof(cert));
* altcp_allocator_t tls_allocator = {
* altcp_tls_alloc, conf
* };
* \endcode
*
*
* struct altcp_tls_config
* -----------------------
* The struct altcp_tls_config holds state that is needed to create new TLS client
* or server connections (e.g. certificates and private keys).
*
* It is not defined by lwIP itself but by the TLS port (e.g. altcp_tls to mbedTLS
* adaption). However, the parameters used to create it are defined in @ref
* altcp_tls.h (see @ref altcp_tls_create_config_server_privkey_cert for servers
* and @ref altcp_tls_create_config_client / @ref altcp_tls_create_config_client_2wayauth
* for clients).
*
* For mbedTLS, ensure that certificates can be parsed by 'mbedtls_x509_crt_parse()' and
* private keys can be parsed by 'mbedtls_pk_parse_key()'.
*/
/*
* Copyright (c) 2017 Simon Goldschmidt
* 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 <goldsimon@gmx.de>
*
*/
#include "lwip/opt.h"
#if LWIP_ALTCP /* don't build if not configured for use in lwipopts.h */
#include "lwip/altcp.h"
#include "lwip/priv/altcp_priv.h"
#include "lwip/altcp_tcp.h"
#include "lwip/tcp.h"
#include "lwip/mem.h"
#include <string.h>
extern const struct altcp_functions altcp_tcp_functions;
/**
* For altcp layer implementations only: allocate a new struct altcp_pcb from the pool
* and zero the memory
*/
struct altcp_pcb *
altcp_alloc(void)
{
struct altcp_pcb *ret = (struct altcp_pcb *)memp_malloc(MEMP_ALTCP_PCB);
if (ret != NULL) {
memset(ret, 0, sizeof(struct altcp_pcb));
}
return ret;
}
/**
* For altcp layer implementations only: return a struct altcp_pcb to the pool
*/
void
altcp_free(struct altcp_pcb *conn)
{
if (conn) {
if (conn->fns && conn->fns->dealloc) {
conn->fns->dealloc(conn);
}
memp_free(MEMP_ALTCP_PCB, conn);
}
}
/**
* @ingroup altcp
* altcp_new_ip6: @ref altcp_new for IPv6
*/
struct altcp_pcb *
altcp_new_ip6(altcp_allocator_t *allocator)
{
return altcp_new_ip_type(allocator, IPADDR_TYPE_V6);
}
/**
* @ingroup altcp
* altcp_new: @ref altcp_new for IPv4
*/
struct altcp_pcb *
altcp_new(altcp_allocator_t *allocator)
{
return altcp_new_ip_type(allocator, IPADDR_TYPE_V4);
}
/**
* @ingroup altcp
* altcp_new_ip_type: called by applications to allocate a new pcb with the help of an
* allocator function.
*
* @param allocator allocator function and argument
* @param ip_type IP version of the pcb (@ref lwip_ip_addr_type)
* @return a new altcp_pcb or NULL on error
*/
struct altcp_pcb *
altcp_new_ip_type(altcp_allocator_t *allocator, u8_t ip_type)
{
struct altcp_pcb *conn;
if (allocator == NULL) {
/* no allocator given, create a simple TCP connection */
return altcp_tcp_new_ip_type(ip_type);
}
if (allocator->alloc == NULL) {
/* illegal allocator */
return NULL;
}
conn = allocator->alloc(allocator->arg, ip_type);
if (conn == NULL) {
/* allocation failed */
return NULL;
}
return conn;
}
/**
* @ingroup altcp
* @see tcp_arg()
*/
void
altcp_arg(struct altcp_pcb *conn, void *arg)
{
if (conn) {
conn->arg = arg;
}
}
/**
* @ingroup altcp
* @see tcp_accept()
*/
void
altcp_accept(struct altcp_pcb *conn, altcp_accept_fn accept)
{
if (conn != NULL) {
conn->accept = accept;
}
}
/**
* @ingroup altcp
* @see tcp_recv()
*/
void
altcp_recv(struct altcp_pcb *conn, altcp_recv_fn recv)
{
if (conn) {
conn->recv = recv;
}
}
/**
* @ingroup altcp
* @see tcp_sent()
*/
void
altcp_sent(struct altcp_pcb *conn, altcp_sent_fn sent)
{
if (conn) {
conn->sent = sent;
}
}
/**
* @ingroup altcp
* @see tcp_poll()
*/
void
altcp_poll(struct altcp_pcb *conn, altcp_poll_fn poll, u8_t interval)
{
if (conn) {
conn->poll = poll;
conn->pollinterval = interval;
if (conn->fns && conn->fns->set_poll) {
conn->fns->set_poll(conn, interval);
}
}
}
/**
* @ingroup altcp
* @see tcp_err()
*/
void
altcp_err(struct altcp_pcb *conn, altcp_err_fn err)
{
if (conn) {
conn->err = err;
}
}
/* Generic functions calling the "virtual" ones */
/**
* @ingroup altcp
* @see tcp_recved()
*/
void
altcp_recved(struct altcp_pcb *conn, u16_t len)
{
if (conn && conn->fns && conn->fns->recved) {
conn->fns->recved(conn, len);
}
}
/**
* @ingroup altcp
* @see tcp_bind()
*/
err_t
altcp_bind(struct altcp_pcb *conn, const ip_addr_t *ipaddr, u16_t port)
{
if (conn && conn->fns && conn->fns->bind) {
return conn->fns->bind(conn, ipaddr, port);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_connect()
*/
err_t
altcp_connect(struct altcp_pcb *conn, const ip_addr_t *ipaddr, u16_t port, altcp_connected_fn connected)
{
if (conn && conn->fns && conn->fns->connect) {
return conn->fns->connect(conn, ipaddr, port, connected);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_listen_with_backlog_and_err()
*/
struct altcp_pcb *
altcp_listen_with_backlog_and_err(struct altcp_pcb *conn, u8_t backlog, err_t *err)
{
if (conn && conn->fns && conn->fns->listen) {
return conn->fns->listen(conn, backlog, err);
}
return NULL;
}
/**
* @ingroup altcp
* @see tcp_abort()
*/
void
altcp_abort(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->abort) {
conn->fns->abort(conn);
}
}
/**
* @ingroup altcp
* @see tcp_close()
*/
err_t
altcp_close(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->close) {
return conn->fns->close(conn);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_shutdown()
*/
err_t
altcp_shutdown(struct altcp_pcb *conn, int shut_rx, int shut_tx)
{
if (conn && conn->fns && conn->fns->shutdown) {
return conn->fns->shutdown(conn, shut_rx, shut_tx);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_write()
*/
err_t
altcp_write(struct altcp_pcb *conn, const void *dataptr, u16_t len, u8_t apiflags)
{
if (conn && conn->fns && conn->fns->write) {
return conn->fns->write(conn, dataptr, len, apiflags);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_output()
*/
err_t
altcp_output(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->output) {
return conn->fns->output(conn);
}
return ERR_VAL;
}
/**
* @ingroup altcp
* @see tcp_mss()
*/
u16_t
altcp_mss(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->mss) {
return conn->fns->mss(conn);
}
return 0;
}
/**
* @ingroup altcp
* @see tcp_sndbuf()
*/
u16_t
altcp_sndbuf(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->sndbuf) {
return conn->fns->sndbuf(conn);
}
return 0;
}
/**
* @ingroup altcp
* @see tcp_sndqueuelen()
*/
u16_t
altcp_sndqueuelen(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->sndqueuelen) {
return conn->fns->sndqueuelen(conn);
}
return 0;
}
void
altcp_nagle_disable(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->nagle_disable) {
conn->fns->nagle_disable(conn);
}
}
void
altcp_nagle_enable(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->nagle_enable) {
conn->fns->nagle_enable(conn);
}
}
int
altcp_nagle_disabled(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->nagle_disabled) {
return conn->fns->nagle_disabled(conn);
}
return 0;
}
/**
* @ingroup altcp
* @see tcp_setprio()
*/
void
altcp_setprio(struct altcp_pcb *conn, u8_t prio)
{
if (conn && conn->fns && conn->fns->setprio) {
conn->fns->setprio(conn, prio);
}
}
err_t
altcp_get_tcp_addrinfo(struct altcp_pcb *conn, int local, ip_addr_t *addr, u16_t *port)
{
if (conn && conn->fns && conn->fns->addrinfo) {
return conn->fns->addrinfo(conn, local, addr, port);
}
return ERR_VAL;
}
ip_addr_t *
altcp_get_ip(struct altcp_pcb *conn, int local)
{
if (conn && conn->fns && conn->fns->getip) {
return conn->fns->getip(conn, local);
}
return NULL;
}
u16_t
altcp_get_port(struct altcp_pcb *conn, int local)
{
if (conn && conn->fns && conn->fns->getport) {
return conn->fns->getport(conn, local);
}
return 0;
}
#if LWIP_TCP_KEEPALIVE
void
altcp_keepalive_disable(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->keepalive_disable) {
conn->fns->keepalive_disable(conn);
}
}
void
altcp_keepalive_enable(struct altcp_pcb *conn, u32_t idle, u32_t intvl, u32_t count)
{
if (conn && conn->fns && conn->fns->keepalive_enable) {
conn->fns->keepalive_enable(conn, idle, intvl, count);
}
}
#endif
#ifdef LWIP_DEBUG
enum tcp_state
altcp_dbg_get_tcp_state(struct altcp_pcb *conn)
{
if (conn && conn->fns && conn->fns->dbg_get_tcp_state) {
return conn->fns->dbg_get_tcp_state(conn);
}
return CLOSED;
}
#endif
/* Default implementations for the "virtual" functions */
void
altcp_default_set_poll(struct altcp_pcb *conn, u8_t interval)
{
if (conn && conn->inner_conn) {
altcp_poll(conn->inner_conn, conn->poll, interval);
}
}
void
altcp_default_recved(struct altcp_pcb *conn, u16_t len)
{
if (conn && conn->inner_conn) {
altcp_recved(conn->inner_conn, len);
}
}
err_t
altcp_default_bind(struct altcp_pcb *conn, const ip_addr_t *ipaddr, u16_t port)
{
if (conn && conn->inner_conn) {
return altcp_bind(conn->inner_conn, ipaddr, port);
}
return ERR_VAL;
}
err_t
altcp_default_shutdown(struct altcp_pcb *conn, int shut_rx, int shut_tx)
{
if (conn) {
if (shut_rx && shut_tx && conn->fns && conn->fns->close) {
/* default shutdown for both sides is close */
return conn->fns->close(conn);
}
if (conn->inner_conn) {
return altcp_shutdown(conn->inner_conn, shut_rx, shut_tx);
}
}
return ERR_VAL;
}
err_t
altcp_default_write(struct altcp_pcb *conn, const void *dataptr, u16_t len, u8_t apiflags)
{
if (conn && conn->inner_conn) {
return altcp_write(conn->inner_conn, dataptr, len, apiflags);
}
return ERR_VAL;
}
err_t
altcp_default_output(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_output(conn->inner_conn);
}
return ERR_VAL;
}
u16_t
altcp_default_mss(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_mss(conn->inner_conn);
}
return 0;
}
u16_t
altcp_default_sndbuf(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_sndbuf(conn->inner_conn);
}
return 0;
}
u16_t
altcp_default_sndqueuelen(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_sndqueuelen(conn->inner_conn);
}
return 0;
}
void
altcp_default_nagle_disable(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
altcp_nagle_disable(conn->inner_conn);
}
}
void
altcp_default_nagle_enable(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
altcp_nagle_enable(conn->inner_conn);
}
}
int
altcp_default_nagle_disabled(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_nagle_disabled(conn->inner_conn);
}
return 0;
}
void
altcp_default_setprio(struct altcp_pcb *conn, u8_t prio)
{
if (conn && conn->inner_conn) {
altcp_setprio(conn->inner_conn, prio);
}
}
void
altcp_default_dealloc(struct altcp_pcb *conn)
{
LWIP_UNUSED_ARG(conn);
/* nothing to do */
}
err_t
altcp_default_get_tcp_addrinfo(struct altcp_pcb *conn, int local, ip_addr_t *addr, u16_t *port)
{
if (conn && conn->inner_conn) {
return altcp_get_tcp_addrinfo(conn->inner_conn, local, addr, port);
}
return ERR_VAL;
}
ip_addr_t *
altcp_default_get_ip(struct altcp_pcb *conn, int local)
{
if (conn && conn->inner_conn) {
return altcp_get_ip(conn->inner_conn, local);
}
return NULL;
}
u16_t
altcp_default_get_port(struct altcp_pcb *conn, int local)
{
if (conn && conn->inner_conn) {
return altcp_get_port(conn->inner_conn, local);
}
return 0;
}
#if LWIP_TCP_KEEPALIVE
void
altcp_default_keepalive_disable(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
altcp_keepalive_disable(conn->inner_conn);
}
}
void
altcp_default_keepalive_enable(struct altcp_pcb *conn, u32_t idle, u32_t intvl, u32_t count)
{
if (conn && conn->inner_conn) {
altcp_keepalive_enable(conn->inner_conn, idle, intvl, count);
}
}
#endif
#ifdef LWIP_DEBUG
enum tcp_state
altcp_default_dbg_get_tcp_state(struct altcp_pcb *conn)
{
if (conn && conn->inner_conn) {
return altcp_dbg_get_tcp_state(conn->inner_conn);
}
return CLOSED;
}
#endif
#endif /* LWIP_ALTCP */

View File

@ -1,87 +0,0 @@
/**
* @file
* Application layered TCP connection API (to be used from TCPIP thread)<br>
* This interface mimics the tcp callback API to the application while preventing
* direct linking (much like virtual functions).
* This way, an application can make use of other application layer protocols
* on top of TCP without knowing the details (e.g. TLS, proxy connection).
*
* This file contains allocation implementation that combine several layers.
*/
/*
* Copyright (c) 2017 Simon Goldschmidt
* 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 <goldsimon@gmx.de>
*
*/
#include "lwip/opt.h"
#if LWIP_ALTCP /* don't build if not configured for use in lwipopts.h */
#include "lwip/altcp.h"
#include "lwip/altcp_tcp.h"
#include "lwip/altcp_tls.h"
#include "lwip/priv/altcp_priv.h"
#include "lwip/mem.h"
#include <string.h>
#if LWIP_ALTCP_TLS
/** This standard allocator function creates an altcp pcb for
* TLS over TCP */
struct altcp_pcb *
altcp_tls_new(struct altcp_tls_config *config, u8_t ip_type)
{
struct altcp_pcb *inner_conn, *ret;
LWIP_UNUSED_ARG(ip_type);
inner_conn = altcp_tcp_new_ip_type(ip_type);
if (inner_conn == NULL) {
return NULL;
}
ret = altcp_tls_wrap(config, inner_conn);
if (ret == NULL) {
altcp_close(inner_conn);
}
return ret;
}
/** This standard allocator function creates an altcp pcb for
* TLS over TCP */
struct altcp_pcb *
altcp_tls_alloc(void *arg, u8_t ip_type)
{
return altcp_tls_new((struct altcp_tls_config *)arg, ip_type);
}
#endif /* LWIP_ALTCP_TLS */
#endif /* LWIP_ALTCP */

View File

@ -1,578 +0,0 @@
/**
* @file
* Application layered TCP connection API (to be used from TCPIP thread)
*
* This interface mimics the tcp callback API to the application while preventing
* direct linking (much like virtual functions).
* This way, an application can make use of other application layer protocols
* on top of TCP without knowing the details (e.g. TLS, proxy connection).
*
* This file contains the base implementation calling into tcp.
*/
/*
* Copyright (c) 2017 Simon Goldschmidt
* 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 <goldsimon@gmx.de>
*
*/
#include "lwip/opt.h"
#if LWIP_ALTCP /* don't build if not configured for use in lwipopts.h */
#include "lwip/altcp.h"
#include "lwip/altcp_tcp.h"
#include "lwip/priv/altcp_priv.h"
#include "lwip/tcp.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/mem.h"
#include <string.h>
#define ALTCP_TCP_ASSERT_CONN(conn) do { \
LWIP_ASSERT("conn->inner_conn == NULL", (conn)->inner_conn == NULL); \
LWIP_UNUSED_ARG(conn); /* for LWIP_NOASSERT */ } while(0)
#define ALTCP_TCP_ASSERT_CONN_PCB(conn, tpcb) do { \
LWIP_ASSERT("pcb mismatch", (conn)->state == tpcb); \
LWIP_UNUSED_ARG(tpcb); /* for LWIP_NOASSERT */ \
ALTCP_TCP_ASSERT_CONN(conn); } while(0)
/* Variable prototype, the actual declaration is at the end of this file
since it contains pointers to static functions declared here */
extern const struct altcp_functions altcp_tcp_functions;
static void altcp_tcp_setup(struct altcp_pcb *conn, struct tcp_pcb *tpcb);
/* callback functions for TCP */
static err_t
altcp_tcp_accept(void *arg, struct tcp_pcb *new_tpcb, err_t err)
{
struct altcp_pcb *listen_conn = (struct altcp_pcb *)arg;
if (listen_conn && listen_conn->accept) {
/* create a new altcp_conn to pass to the next 'accept' callback */
struct altcp_pcb *new_conn = altcp_alloc();
if (new_conn == NULL) {
return ERR_MEM;
}
altcp_tcp_setup(new_conn, new_tpcb);
return listen_conn->accept(listen_conn->arg, new_conn, err);
}
return ERR_ARG;
}
static err_t
altcp_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err)
{
struct altcp_pcb *conn = (struct altcp_pcb *)arg;
if (conn) {
ALTCP_TCP_ASSERT_CONN_PCB(conn, tpcb);
if (conn->connected) {
return conn->connected(conn->arg, conn, err);
}
}
return ERR_OK;
}
static err_t
altcp_tcp_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
{
struct altcp_pcb *conn = (struct altcp_pcb *)arg;
if (conn) {
ALTCP_TCP_ASSERT_CONN_PCB(conn, tpcb);
if (conn->recv) {
return conn->recv(conn->arg, conn, p, err);
}
}
if (p != NULL) {
/* prevent memory leaks */
pbuf_free(p);
}
return ERR_OK;
}
static err_t
altcp_tcp_sent(void *arg, struct tcp_pcb *tpcb, u16_t len)
{
struct altcp_pcb *conn = (struct altcp_pcb *)arg;
if (conn) {
ALTCP_TCP_ASSERT_CONN_PCB(conn, tpcb);
if (conn->sent) {
return conn->sent(conn->arg, conn, len);
}
}
return ERR_OK;
}
static err_t
altcp_tcp_poll(void *arg, struct tcp_pcb *tpcb)
{
struct altcp_pcb *conn = (struct altcp_pcb *)arg;
if (conn) {
ALTCP_TCP_ASSERT_CONN_PCB(conn, tpcb);
if (conn->poll) {
return conn->poll(conn->arg, conn);
}
}
return ERR_OK;
}
static void
altcp_tcp_err(void *arg, err_t err)
{
struct altcp_pcb *conn = (struct altcp_pcb *)arg;
if (conn) {
conn->state = NULL; /* already freed */
if (conn->err) {
conn->err(conn->arg, err);
}
altcp_free(conn);
}
}
/* setup functions */
static void
altcp_tcp_remove_callbacks(struct tcp_pcb *tpcb)
{
tcp_arg(tpcb, NULL);
if (tpcb->state != LISTEN) {
tcp_recv(tpcb, NULL);
tcp_sent(tpcb, NULL);
tcp_err(tpcb, NULL);
tcp_poll(tpcb, NULL, tpcb->pollinterval);
}
}
static void
altcp_tcp_setup_callbacks(struct altcp_pcb *conn, struct tcp_pcb *tpcb)
{
tcp_arg(tpcb, conn);
/* this might be called for LISTN when close fails... */
if (tpcb->state != LISTEN) {
tcp_recv(tpcb, altcp_tcp_recv);
tcp_sent(tpcb, altcp_tcp_sent);
tcp_err(tpcb, altcp_tcp_err);
/* tcp_poll is set when interval is set by application */
}
}
static void
altcp_tcp_setup(struct altcp_pcb *conn, struct tcp_pcb *tpcb)
{
altcp_tcp_setup_callbacks(conn, tpcb);
conn->state = tpcb;
conn->fns = &altcp_tcp_functions;
}
struct altcp_pcb *
altcp_tcp_new_ip_type(u8_t ip_type)
{
/* Allocate the tcp pcb first to invoke the priority handling code
if we're out of pcbs */
struct tcp_pcb *tpcb = tcp_new_ip_type(ip_type);
if (tpcb != NULL) {
struct altcp_pcb *ret = altcp_alloc();
if (ret != NULL) {
altcp_tcp_setup(ret, tpcb);
return ret;
} else {
/* altcp_pcb allocation failed -> free the tcp_pcb too */
tcp_close(tpcb);
}
}
return NULL;
}
/** altcp_tcp allocator function fitting to @ref altcp_allocator_t / @ref altcp_new.
*
* arg pointer is not used for TCP.
*/
struct altcp_pcb *
altcp_tcp_alloc(void *arg, u8_t ip_type)
{
LWIP_UNUSED_ARG(arg);
return altcp_tcp_new_ip_type(ip_type);
}
struct altcp_pcb *
altcp_tcp_wrap(struct tcp_pcb *tpcb)
{
if (tpcb != NULL) {
struct altcp_pcb *ret = altcp_alloc();
if (ret != NULL) {
altcp_tcp_setup(ret, tpcb);
return ret;
}
}
return NULL;
}
/* "virtual" functions calling into tcp */
static void
altcp_tcp_set_poll(struct altcp_pcb *conn, u8_t interval)
{
if (conn != NULL) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
tcp_poll(pcb, altcp_tcp_poll, interval);
}
}
static void
altcp_tcp_recved(struct altcp_pcb *conn, u16_t len)
{
if (conn != NULL) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
tcp_recved(pcb, len);
}
}
static err_t
altcp_tcp_bind(struct altcp_pcb *conn, const ip_addr_t *ipaddr, u16_t port)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_bind(pcb, ipaddr, port);
}
static err_t
altcp_tcp_connect(struct altcp_pcb *conn, const ip_addr_t *ipaddr, u16_t port, altcp_connected_fn connected)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
conn->connected = connected;
pcb = (struct tcp_pcb *)conn->state;
return tcp_connect(pcb, ipaddr, port, altcp_tcp_connected);
}
static struct altcp_pcb *
altcp_tcp_listen(struct altcp_pcb *conn, u8_t backlog, err_t *err)
{
struct tcp_pcb *pcb;
struct tcp_pcb *lpcb;
if (conn == NULL) {
return NULL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
lpcb = tcp_listen_with_backlog_and_err(pcb, backlog, err);
if (lpcb != NULL) {
conn->state = lpcb;
tcp_accept(lpcb, altcp_tcp_accept);
return conn;
}
return NULL;
}
static void
altcp_tcp_abort(struct altcp_pcb *conn)
{
if (conn != NULL) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
if (pcb) {
tcp_abort(pcb);
}
}
}
static err_t
altcp_tcp_close(struct altcp_pcb *conn)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
if (pcb) {
err_t err;
tcp_poll_fn oldpoll = pcb->poll;
altcp_tcp_remove_callbacks(pcb);
err = tcp_close(pcb);
if (err != ERR_OK) {
/* not closed, set up all callbacks again */
altcp_tcp_setup_callbacks(conn, pcb);
/* poll callback is not included in the above */
tcp_poll(pcb, oldpoll, pcb->pollinterval);
return err;
}
conn->state = NULL; /* unsafe to reference pcb after tcp_close(). */
}
altcp_free(conn);
return ERR_OK;
}
static err_t
altcp_tcp_shutdown(struct altcp_pcb *conn, int shut_rx, int shut_tx)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_shutdown(pcb, shut_rx, shut_tx);
}
static err_t
altcp_tcp_write(struct altcp_pcb *conn, const void *dataptr, u16_t len, u8_t apiflags)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_write(pcb, dataptr, len, apiflags);
}
static err_t
altcp_tcp_output(struct altcp_pcb *conn)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return ERR_VAL;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_output(pcb);
}
static u16_t
altcp_tcp_mss(struct altcp_pcb *conn)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return 0;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_mss(pcb);
}
static u16_t
altcp_tcp_sndbuf(struct altcp_pcb *conn)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return 0;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_sndbuf(pcb);
}
static u16_t
altcp_tcp_sndqueuelen(struct altcp_pcb *conn)
{
struct tcp_pcb *pcb;
if (conn == NULL) {
return 0;
}
ALTCP_TCP_ASSERT_CONN(conn);
pcb = (struct tcp_pcb *)conn->state;
return tcp_sndqueuelen(pcb);
}
static void
altcp_tcp_nagle_disable(struct altcp_pcb *conn)
{
if (conn && conn->state) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
tcp_nagle_disable(pcb);
}
}
static void
altcp_tcp_nagle_enable(struct altcp_pcb *conn)
{
if (conn && conn->state) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
tcp_nagle_enable(pcb);
}
}
static int
altcp_tcp_nagle_disabled(struct altcp_pcb *conn)
{
if (conn && conn->state) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
return tcp_nagle_disabled(pcb);
}
return 0;
}
static void
altcp_tcp_setprio(struct altcp_pcb *conn, u8_t prio)
{
if (conn != NULL) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
tcp_setprio(pcb, prio);
}
}
#if LWIP_TCP_KEEPALIVE
static void
altcp_tcp_keepalive_disable(struct altcp_pcb *conn)
{
if (conn && conn->state) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
ip_reset_option(pcb, SOF_KEEPALIVE);
}
}
static void
altcp_tcp_keepalive_enable(struct altcp_pcb *conn, u32_t idle, u32_t intvl, u32_t cnt)
{
if (conn && conn->state) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
ip_set_option(pcb, SOF_KEEPALIVE);
pcb->keep_idle = idle ? idle : TCP_KEEPIDLE_DEFAULT;
pcb->keep_intvl = intvl ? intvl : TCP_KEEPINTVL_DEFAULT;
pcb->keep_cnt = cnt ? cnt : TCP_KEEPCNT_DEFAULT;
}
}
#endif
static void
altcp_tcp_dealloc(struct altcp_pcb *conn)
{
LWIP_UNUSED_ARG(conn);
ALTCP_TCP_ASSERT_CONN(conn);
/* no private state to clean up */
}
static err_t
altcp_tcp_get_tcp_addrinfo(struct altcp_pcb *conn, int local, ip_addr_t *addr, u16_t *port)
{
if (conn) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
return tcp_tcp_get_tcp_addrinfo(pcb, local, addr, port);
}
return ERR_VAL;
}
static ip_addr_t *
altcp_tcp_get_ip(struct altcp_pcb *conn, int local)
{
if (conn) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
if (pcb) {
if (local) {
return &pcb->local_ip;
} else {
return &pcb->remote_ip;
}
}
}
return NULL;
}
static u16_t
altcp_tcp_get_port(struct altcp_pcb *conn, int local)
{
if (conn) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
if (pcb) {
if (local) {
return pcb->local_port;
} else {
return pcb->remote_port;
}
}
}
return 0;
}
#ifdef LWIP_DEBUG
static enum tcp_state
altcp_tcp_dbg_get_tcp_state(struct altcp_pcb *conn)
{
if (conn) {
struct tcp_pcb *pcb = (struct tcp_pcb *)conn->state;
ALTCP_TCP_ASSERT_CONN(conn);
if (pcb) {
return pcb->state;
}
}
return CLOSED;
}
#endif
const struct altcp_functions altcp_tcp_functions = {
altcp_tcp_set_poll,
altcp_tcp_recved,
altcp_tcp_bind,
altcp_tcp_connect,
altcp_tcp_listen,
altcp_tcp_abort,
altcp_tcp_close,
altcp_tcp_shutdown,
altcp_tcp_write,
altcp_tcp_output,
altcp_tcp_mss,
altcp_tcp_sndbuf,
altcp_tcp_sndqueuelen,
altcp_tcp_nagle_disable,
altcp_tcp_nagle_enable,
altcp_tcp_nagle_disabled,
altcp_tcp_setprio,
altcp_tcp_dealloc,
altcp_tcp_get_tcp_addrinfo,
altcp_tcp_get_ip,
altcp_tcp_get_port
#if LWIP_TCP_KEEPALIVE
, altcp_tcp_keepalive_disable
, altcp_tcp_keepalive_enable
#endif
#ifdef LWIP_DEBUG
, altcp_tcp_dbg_get_tcp_state
#endif
};
#endif /* LWIP_ALTCP */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,115 +0,0 @@
/**
* @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 */

View File

@ -1,102 +0,0 @@
/**
* @file
* Interface Identification APIs from:
* RFC 3493: Basic Socket Interface Extensions for IPv6
* Section 4: Interface Identification
*
* @defgroup if_api Interface Identification API
* @ingroup socket
*/
/*
* Copyright (c) 2017 Joel Cunningham, Garmin International, Inc. <joel.cunningham@garmin.com>
* 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: Joel Cunningham <joel.cunningham@me.com>
*
*/
#include "lwip/opt.h"
#if LWIP_SOCKET
#include "lwip/errno.h"
#include "lwip/if_api.h"
#include "lwip/netifapi.h"
#include "lwip/priv/sockets_priv.h"
/**
* @ingroup if_api
* Maps an interface index to its corresponding name.
* @param ifindex interface index
* @param ifname shall point to a buffer of at least {IF_NAMESIZE} bytes
* @return If ifindex is an interface index, then the function shall return the
* value supplied in ifname, which points to a buffer now containing the interface name.
* Otherwise, the function shall return a NULL pointer.
*/
char *
lwip_if_indextoname(unsigned int ifindex, char *ifname)
{
#if LWIP_NETIF_API
if (ifindex <= 0xff) {
err_t err = netifapi_netif_index_to_name((u8_t)ifindex, ifname);
if (!err && ifname[0] != '\0') {
return ifname;
}
}
#else /* LWIP_NETIF_API */
LWIP_UNUSED_ARG(ifindex);
LWIP_UNUSED_ARG(ifname);
#endif /* LWIP_NETIF_API */
set_errno(ENXIO);
return NULL;
}
/**
* @ingroup if_api
* Returns the interface index corresponding to name ifname.
* @param ifname Interface name
* @return The corresponding index if ifname is the name of an interface;
* otherwise, zero.
*/
unsigned int
lwip_if_nametoindex(const char *ifname)
{
#if LWIP_NETIF_API
err_t err;
u8_t idx;
err = netifapi_netif_name_to_index(ifname, &idx);
if (!err) {
return idx;
}
#else /* LWIP_NETIF_API */
LWIP_UNUSED_ARG(ifname);
#endif /* LWIP_NETIF_API */
return 0; /* invalid index */
}
#endif /* LWIP_SOCKET */

View File

@ -1,250 +0,0 @@
/**
* @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.<br>
* Buffers must not be shared across 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;
#if LWIP_CHECKSUM_ON_COPY
buf->flags = 0;
buf->toport_chksum = 0;
#endif /* LWIP_CHECKSUM_ON_COPY */
}
/**
* @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 */

View File

@ -1,448 +0,0 @@
/**
* @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 */
/** LWIP_DNS_API_HOSTENT_STORAGE: if set to 0 (default), lwip_gethostbyname()
* returns the same global variabe for all calls (in all threads).
* When set to 1, your port should provide a function
* struct hostent* sys_thread_hostent( struct hostent* h);
* which have to do a copy of "h" and return a pointer ont the "per-thread"
* copy.
*/
#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]-> == %s\n", idx, ipaddr_ntoa(s_phostent_addr[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) + LWIP_MEM_ALIGN_BUFFER(namelen + 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 && (servname[0] != '0')) {
/* atoi failed - service was not numeric */
return EAI_SERVICE;
}
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_val(ai_family == AF_INET6, addr);
} else {
ip_addr_set_loopback_val(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);
sa6->sin6_scope_id = ip6_addr_zone(ip_2_ip6(&addr));
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;
}
#if LWIP_COMPAT_SOCKETS
struct hostent *gethostbyname(const char *name)
{
return lwip_gethostbyname(name);
}
int gethostbyname_r(const char *name, struct hostent *ret, char *buf,
size_t buflen, struct hostent **result, int *h_errnop)
{
return lwip_gethostbyname_r(name, ret, buf, buflen, result, h_errnop);
}
void freeaddrinfo(struct addrinfo *ai)
{
return lwip_freeaddrinfo(ai);
}
int getaddrinfo(const char *nodename,
const char *servname,
const struct addrinfo *hints,
struct addrinfo **res)
{
return lwip_getaddrinfo(nodename, servname, hints, res);
}
#endif
#endif /* LWIP_DNS && LWIP_SOCKET */

View File

@ -1,380 +0,0 @@
/**
* @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/etharp.h"
#include "lwip/netifapi.h"
#include "lwip/memp.h"
#include "lwip/priv/tcpip_priv.h"
#include <string.h> /* strncpy */
#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 netif_name_to_index() inside the tcpip_thread context.
*/
static err_t
netifapi_do_name_to_index(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;
msg->msg.ifs.index = netif_name_to_index(msg->msg.ifs.name);
return ERR_OK;
}
/**
* Call netif_index_to_name() inside the tcpip_thread context.
*/
static err_t
netifapi_do_index_to_name(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_index_to_name(msg->msg.ifs.index, msg->msg.ifs.name)) {
/* return failure via empty name */
msg->msg.ifs.name[0] = '\0';
}
return ERR_OK;
}
/**
* 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;
}
}
#if LWIP_ARP && LWIP_IPV4
/**
* @ingroup netifapi_arp
* Add or update an entry in the ARP cache.
* For an update, ipaddr is used to find the cache entry.
*
* @param ipaddr IPv4 address of cache entry
* @param ethaddr hardware address mapped to ipaddr
* @param type type of ARP cache entry
* @return ERR_OK: entry added/updated, else error from err_t
*/
err_t
netifapi_arp_add(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr, enum netifapi_arp_entry type)
{
err_t err;
/* We only support permanent entries currently */
LWIP_UNUSED_ARG(type);
#if ETHARP_SUPPORT_STATIC_ENTRIES && LWIP_TCPIP_CORE_LOCKING
LOCK_TCPIP_CORE();
err = etharp_add_static_entry(ipaddr, ethaddr);
UNLOCK_TCPIP_CORE();
#else
/* @todo add new vars to struct netifapi_msg and create a 'do' func */
LWIP_UNUSED_ARG(ipaddr);
LWIP_UNUSED_ARG(ethaddr);
err = ERR_VAL;
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES && LWIP_TCPIP_CORE_LOCKING */
return err;
}
/**
* @ingroup netifapi_arp
* Remove an entry in the ARP cache identified by ipaddr
*
* @param ipaddr IPv4 address of cache entry
* @param type type of ARP cache entry
* @return ERR_OK: entry removed, else error from err_t
*/
err_t
netifapi_arp_remove(const ip4_addr_t *ipaddr, enum netifapi_arp_entry type)
{
err_t err;
/* We only support permanent entries currently */
LWIP_UNUSED_ARG(type);
#if ETHARP_SUPPORT_STATIC_ENTRIES && LWIP_TCPIP_CORE_LOCKING
LOCK_TCPIP_CORE();
err = etharp_remove_static_entry(ipaddr);
UNLOCK_TCPIP_CORE();
#else
/* @todo add new vars to struct netifapi_msg and create a 'do' func */
LWIP_UNUSED_ARG(ipaddr);
err = ERR_VAL;
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES && LWIP_TCPIP_CORE_LOCKING */
return err;
}
#endif /* LWIP_ARP && LWIP_IPV4 */
/**
* @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;
}
/**
* @ingroup netifapi_netif
* Call netif_name_to_index() in a thread-safe way by running that function inside the
* tcpip_thread context.
*
* @param name the interface name of the netif
* @param idx output index of the found netif
*/
err_t
netifapi_netif_name_to_index(const char *name, u8_t *idx)
{
err_t err;
NETIFAPI_VAR_DECLARE(msg);
NETIFAPI_VAR_ALLOC(msg);
*idx = 0;
#if LWIP_MPU_COMPATIBLE
strncpy(NETIFAPI_VAR_REF(msg).msg.ifs.name, name, NETIF_NAMESIZE - 1);
NETIFAPI_VAR_REF(msg).msg.ifs.name[NETIF_NAMESIZE - 1] = '\0';
#else
NETIFAPI_VAR_REF(msg).msg.ifs.name = LWIP_CONST_CAST(char *, name);
#endif /* LWIP_MPU_COMPATIBLE */
err = tcpip_api_call(netifapi_do_name_to_index, &API_VAR_REF(msg).call);
if (!err) {
*idx = NETIFAPI_VAR_REF(msg).msg.ifs.index;
}
NETIFAPI_VAR_FREE(msg);
return err;
}
/**
* @ingroup netifapi_netif
* Call netif_index_to_name() in a thread-safe way by running that function inside the
* tcpip_thread context.
*
* @param idx the interface index of the netif
* @param name output name of the found netif, empty '\0' string if netif not found.
* name should be of at least NETIF_NAMESIZE bytes
*/
err_t
netifapi_netif_index_to_name(u8_t idx, char *name)
{
err_t err;
NETIFAPI_VAR_DECLARE(msg);
NETIFAPI_VAR_ALLOC(msg);
NETIFAPI_VAR_REF(msg).msg.ifs.index = idx;
#if !LWIP_MPU_COMPATIBLE
NETIFAPI_VAR_REF(msg).msg.ifs.name = name;
#endif /* LWIP_MPU_COMPATIBLE */
err = tcpip_api_call(netifapi_do_index_to_name, &API_VAR_REF(msg).call);
#if LWIP_MPU_COMPATIBLE
if (!err) {
strncpy(name, NETIFAPI_VAR_REF(msg).msg.ifs.name, NETIF_NAMESIZE - 1);
name[NETIF_NAMESIZE - 1] = '\0';
}
#endif /* LWIP_MPU_COMPATIBLE */
NETIFAPI_VAR_FREE(msg);
return err;
}
#endif /* LWIP_NETIF_API */

File diff suppressed because it is too large Load Diff

View File

@ -1,717 +0,0 @@
/**
* @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 tcpip_mbox;
#if LWIP_TCPIP_CORE_LOCKING
/** The global semaphore to lock the stack. */
sys_mutex_t lock_tcpip_core;
#endif /* LWIP_TCPIP_CORE_LOCKING */
static void tcpip_thread_handle_msg(struct tcpip_msg *msg);
#if !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)
#else /* !LWIP_TIMERS */
/* wait for a message, timeouts are processed while waiting */
#define TCPIP_MBOX_FETCH(mbox, msg) tcpip_timeouts_mbox_fetch(mbox, msg)
/**
* Wait (forever) for a message to arrive in an mbox.
* While waiting, timeouts are processed.
*
* @param mbox the mbox to fetch the message from
* @param msg the place to store the message
*/
static void
tcpip_timeouts_mbox_fetch(sys_mbox_t *mbox, void **msg)
{
u32_t sleeptime, res;
again:
LWIP_ASSERT_CORE_LOCKED();
sleeptime = sys_timeouts_sleeptime();
if (sleeptime == SYS_TIMEOUTS_SLEEPTIME_INFINITE) {
UNLOCK_TCPIP_CORE();
sys_arch_mbox_fetch(mbox, msg, 0);
LOCK_TCPIP_CORE();
return;
} else if (sleeptime == 0) {
sys_check_timeouts();
/* We try again to fetch a message from the mbox. */
goto again;
}
UNLOCK_TCPIP_CORE();
res = sys_arch_mbox_fetch(mbox, msg, sleeptime);
LOCK_TCPIP_CORE();
if (res == SYS_ARCH_TIMEOUT) {
/* If a SYS_ARCH_TIMEOUT value is returned, a timeout occurred
before a message could be fetched. */
sys_check_timeouts();
/* We try again to fetch a message from the mbox. */
goto again;
}
}
#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);
LWIP_MARK_TCPIP_THREAD();
LOCK_TCPIP_CORE();
if (tcpip_init_done != NULL) {
tcpip_init_done(tcpip_init_done_arg);
}
while (1) { /* MAIN Loop */
LWIP_TCPIP_THREAD_ALIVE();
/* wait for a message, timeouts are processed while waiting */
TCPIP_MBOX_FETCH(&tcpip_mbox, (void **)&msg);
if (msg == NULL) {
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: invalid message: NULL\n"));
LWIP_ASSERT("tcpip_thread: invalid message", 0);
continue;
}
tcpip_thread_handle_msg(msg);
}
}
/* Handle a single tcpip_msg
* This is in its own function for access by tests only.
*/
static void
tcpip_thread_handle_msg(struct tcpip_msg *msg)
{
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;
case TCPIP_MSG_CALLBACK_STATIC_WAIT:
LWIP_DEBUGF(TCPIP_DEBUG, ("tcpip_thread: CALLBACK WAIT message %p\n", (void *)msg));
msg->msg.cb_wait.function(msg->msg.cb_wait.ctx);
sys_sem_signal(msg->msg.cb_wait.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));
if (msg->msg.inp.input_fn(msg->msg.inp.p, msg->msg.inp.netif) != ERR_OK) {
pbuf_free(msg->msg.inp.p);
}
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;
}
}
#ifdef TCPIP_THREAD_TEST
/** Work on queued items in single-threaded test mode */
int
tcpip_thread_poll_one(void)
{
int ret = 0;
struct tcpip_msg *msg;
if (sys_arch_mbox_tryfetch(&tcpip_mbox, (void **)&msg) != SYS_MBOX_EMPTY) {
LOCK_TCPIP_CORE();
if (msg != NULL) {
tcpip_thread_handle_msg(msg);
ret = 1;
}
UNLOCK_TCPIP_CORE();
}
return ret;
}
#endif
/**
* 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(tcpip_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(&tcpip_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);
}
/**
* @ingroup lwip_os
* 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.
* Blocks until the request is posted.
* Must not be called from interrupt context!
*
* @param function the function to call
* @param ctx parameter passed to f
* @return ERR_OK if the function was called, another err_t if not
*
* @see tcpip_try_callback
*/
err_t
tcpip_callback(tcpip_callback_fn function, void *ctx)
{
struct tcpip_msg *msg;
LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(tcpip_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;
sys_mbox_post(&tcpip_mbox, msg);
return ERR_OK;
}
/**
* @ingroup lwip_os
* 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.
* Does NOT block when the request cannot be posted because the
* tcpip_mbox is full, but returns ERR_MEM instead.
* Can be called from interrupt context.
*
* @param function the function to call
* @param ctx parameter passed to f
* @return ERR_OK if the function was called, another err_t if not
*
* @see tcpip_callback
*/
err_t
tcpip_try_callback(tcpip_callback_fn function, void *ctx)
{
struct tcpip_msg *msg;
LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(tcpip_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 (sys_mbox_trypost(&tcpip_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(tcpip_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(&tcpip_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(tcpip_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(&tcpip_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(tcpip_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(&tcpip_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(tcpip_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(&tcpip_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 */
}
/**
* @ingroup lwip_os
* Allocate a structure for a static callback message and initialize it.
* The message has a special type such that lwIP never frees it.
* This is intended to be used to send "static" messages from interrupt context,
* e.g. the message is allocated once and posted several times from an IRQ
* using tcpip_callbackmsg_trycallback().
* Example usage: Trigger execution of an ethernet IRQ DPC routine in lwIP thread context.
*
* @param function the function to call
* @param ctx parameter passed to function
* @return a struct pointer to pass to tcpip_callbackmsg_trycallback().
*
* @see tcpip_callbackmsg_trycallback()
* @see tcpip_callbackmsg_delete()
*/
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;
}
/**
* @ingroup lwip_os
* Free a callback message allocated by tcpip_callbackmsg_new().
*
* @param msg the message to free
*
* @see tcpip_callbackmsg_new()
*/
void
tcpip_callbackmsg_delete(struct tcpip_callback_msg *msg)
{
memp_free(MEMP_TCPIP_MSG_API, msg);
}
/**
* @ingroup lwip_os
* Try to post a callback-message to the tcpip_thread tcpip_mbox.
*
* @param msg pointer to the message to post
* @return sys_mbox_trypost() return code
*
* @see tcpip_callbackmsg_new()
*/
err_t
tcpip_callbackmsg_trycallback(struct tcpip_callback_msg *msg)
{
LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(tcpip_mbox));
return sys_mbox_trypost(&tcpip_mbox, msg);
}
/**
* @ingroup lwip_os
* Try to post a callback-message to the tcpip_thread mbox.
* Same as @ref tcpip_callbackmsg_trycallback but calls sys_mbox_trypost_fromisr(),
* mainly to help FreeRTOS, where calls differ between task level and ISR level.
*
* @param msg pointer to the message to post
* @return sys_mbox_trypost_fromisr() return code (without change, so this
* knowledge can be used to e.g. propagate "bool needs_scheduling")
*
* @see tcpip_callbackmsg_new()
*/
err_t
tcpip_callbackmsg_trycallback_fromisr(struct tcpip_callback_msg *msg)
{
LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(tcpip_mbox));
return sys_mbox_trypost_fromisr(&tcpip_mbox, msg);
}
/**
* Sends a message to TCPIP thread to call a function. Caller thread blocks
* until the function returns.
* 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 function the function to call
* @param ctx parameter passed to f
* @return ERR_OK if the function was called, another err_t if not
*/
err_t
tcpip_callback_wait(tcpip_callback_fn function, void *ctx)
{
#if LWIP_TCPIP_CORE_LOCKING
LOCK_TCPIP_CORE();
function(ctx);
UNLOCK_TCPIP_CORE();
return ERR_OK;
#else /* LWIP_TCPIP_CORE_LOCKING */
err_t err;
sys_sem_t sem;
struct tcpip_msg msg;
LWIP_ASSERT("Invalid mbox", sys_mbox_valid_val(tcpip_mbox));
err = sys_sem_new(&sem, 0);
if (err != ERR_OK) {
return err;
}
msg.type = TCPIP_MSG_CALLBACK_STATIC_WAIT;
msg.msg.cb_wait.function = function;
msg.msg.cb_wait.ctx = ctx;
msg.msg.cb_wait.sem = &sem;
sys_mbox_post(&tcpip_mbox, &msg);
sys_arch_sem_wait(&sem, 0);
sys_sem_free(&sem);
return ERR_OK;
#endif /* LWIP_TCPIP_CORE_LOCKING */
}
/**
* @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(&tcpip_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);
// dsiwifi altered: no thread
struct tcpip_msg *msg;
LWIP_UNUSED_ARG(arg);
LWIP_MARK_TCPIP_THREAD();
LOCK_TCPIP_CORE();
if (tcpip_init_done != NULL) {
tcpip_init_done(tcpip_init_done_arg);
}
}
/**
* 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_try_callback(pbuf_free_int, p);
}
/**
* 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_try_callback(mem_free, m);
}
#endif /* !NO_SYS */

View File

@ -1,263 +0,0 @@
/**
* @file
* Common functions used throughout the stack.
*
* These are reference implementations of the byte swapping functions.
* Again with the aim of being simple, correct and fully portable.
* Byte swapping is the second thing you would want to optimize. You will
* need to port it to your architecture and in your cc.h:
*
* \#define lwip_htons(x) your_htons
* \#define lwip_htonl(x) your_htonl
*
* Note lwip_ntohs() and lwip_ntohl() are merely references to the htonx counterparts.
*
* If you \#define them to htons() and htonl(), you should
* \#define LWIP_DONT_PROVIDE_BYTEORDER_FUNCTIONS to prevent lwIP from
* defining htonx/ntohx compatibility macros.
* @defgroup sys_nonstandard Non-standard functions
* @ingroup sys_layer
* lwIP provides default implementations for non-standard functions.
* These can be mapped to OS functions to reduce code footprint if desired.
* All defines related to this section must not be placed in lwipopts.h,
* but in arch/cc.h!
* These options cannot be \#defined in lwipopts.h since they are not options
* of lwIP itself, but options of the lwIP port to your system.
*/
/*
* 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: Simon Goldschmidt
*
*/
#include "lwip/opt.h"
#include "lwip/def.h"
#include <string.h>
#if BYTE_ORDER == LITTLE_ENDIAN
#if !defined(lwip_htons)
/**
* Convert an u16_t from host- to network byte order.
*
* @param n u16_t in host byte order
* @return n in network byte order
*/
u16_t
lwip_htons(u16_t n)
{
return PP_HTONS(n);
}
#endif /* lwip_htons */
#if !defined(lwip_htonl)
/**
* Convert an u32_t from host- to network byte order.
*
* @param n u32_t in host byte order
* @return n in network byte order
*/
u32_t
lwip_htonl(u32_t n)
{
return PP_HTONL(n);
}
#endif /* lwip_htonl */
#endif /* BYTE_ORDER == LITTLE_ENDIAN */
#ifndef lwip_strnstr
/**
* @ingroup sys_nonstandard
* lwIP default implementation for strnstr() non-standard function.
* This can be \#defined to strnstr() depending on your platform port.
*/
char *
lwip_strnstr(const char *buffer, const char *token, size_t n)
{
const char *p;
size_t tokenlen = strlen(token);
if (tokenlen == 0) {
return LWIP_CONST_CAST(char *, buffer);
}
for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) {
if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) {
return LWIP_CONST_CAST(char *, p);
}
}
return NULL;
}
#endif
#ifndef lwip_strnistr
/**
* @ingroup sys_nonstandard
* lwIP default implementation for strnistr() non-standard function.
* This can be \#defined to strnistr() depending on your platform port.
*/
char *
lwip_strnistr(const char *buffer, const char *token, size_t n)
{
const char *p;
size_t tokenlen = strlen(token);
if (tokenlen == 0) {
return LWIP_CONST_CAST(char *, buffer);
}
for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) {
if (lwip_strnicmp(p, token, tokenlen) == 0) {
return LWIP_CONST_CAST(char *, p);
}
}
return NULL;
}
#endif
#ifndef lwip_stricmp
/**
* @ingroup sys_nonstandard
* lwIP default implementation for stricmp() non-standard function.
* This can be \#defined to stricmp() depending on your platform port.
*/
int
lwip_stricmp(const char *str1, const char *str2)
{
char c1, c2;
do {
c1 = *str1++;
c2 = *str2++;
if (c1 != c2) {
char c1_upc = c1 | 0x20;
if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
/* characters are not equal an one is in the alphabet range:
downcase both chars and check again */
char c2_upc = c2 | 0x20;
if (c1_upc != c2_upc) {
/* still not equal */
/* don't care for < or > */
return 1;
}
} else {
/* characters are not equal but none is in the alphabet range */
return 1;
}
}
} while (c1 != 0);
return 0;
}
#endif
#ifndef lwip_strnicmp
/**
* @ingroup sys_nonstandard
* lwIP default implementation for strnicmp() non-standard function.
* This can be \#defined to strnicmp() depending on your platform port.
*/
int
lwip_strnicmp(const char *str1, const char *str2, size_t len)
{
char c1, c2;
do {
c1 = *str1++;
c2 = *str2++;
if (c1 != c2) {
char c1_upc = c1 | 0x20;
if ((c1_upc >= 'a') && (c1_upc <= 'z')) {
/* characters are not equal an one is in the alphabet range:
downcase both chars and check again */
char c2_upc = c2 | 0x20;
if (c1_upc != c2_upc) {
/* still not equal */
/* don't care for < or > */
return 1;
}
} else {
/* characters are not equal but none is in the alphabet range */
return 1;
}
}
len--;
} while ((len != 0) && (c1 != 0));
return 0;
}
#endif
#ifndef lwip_itoa
/**
* @ingroup sys_nonstandard
* lwIP default implementation for itoa() non-standard function.
* This can be \#defined to itoa() or snprintf(result, bufsize, "%d", number) depending on your platform port.
*/
void
lwip_itoa(char *result, size_t bufsize, int number)
{
char *res = result;
char *tmp = result + bufsize - 1;
int n = (number >= 0) ? number : -number;
/* handle invalid bufsize */
if (bufsize < 2) {
if (bufsize == 1) {
*result = 0;
}
return;
}
/* First, add sign */
if (number < 0) {
*res++ = '-';
}
/* Then create the string from the end and stop if buffer full,
and ensure output string is zero terminated */
*tmp = 0;
while ((n != 0) && (tmp > res)) {
char val = (char)('0' + (n % 10));
tmp--;
*tmp = val;
n = n / 10;
}
if (n) {
/* buffer is too small */
*result = 0;
return;
}
if (*tmp == 0) {
/* Nothing added? */
*res++ = '0';
*res++ = 0;
return;
}
/* move from temporary buffer to output buffer (sign is not moved) */
memmove(res, tmp, (size_t)((result + bufsize) - tmp));
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,608 +0,0 @@
/**
* @file
* Internet checksum functions.
*
* These are some reference implementations of the checksum algorithm, with the
* aim of being simple, correct and fully portable. Checksumming is the
* first thing you would want to optimize for your platform. If you create
* your own version, link it in and in your cc.h put:
*
* \#define LWIP_CHKSUM your_checksum_routine
*
* Or you can select from the implementations below by defining
* LWIP_CHKSUM_ALGORITHM to 1, 2 or 3.
*/
/*
* 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"
#include "lwip/inet_chksum.h"
#include "lwip/def.h"
#include "lwip/ip_addr.h"
#include <string.h>
#ifndef LWIP_CHKSUM
# define LWIP_CHKSUM lwip_standard_chksum
# ifndef LWIP_CHKSUM_ALGORITHM
# define LWIP_CHKSUM_ALGORITHM 2
# endif
u16_t lwip_standard_chksum(const void *dataptr, int len);
#endif
/* If none set: */
#ifndef LWIP_CHKSUM_ALGORITHM
# define LWIP_CHKSUM_ALGORITHM 0
#endif
#if (LWIP_CHKSUM_ALGORITHM == 1) /* Version #1 */
/**
* lwip checksum
*
* @param dataptr points to start of data to be summed at any boundary
* @param len length of data to be summed
* @return host order (!) lwip checksum (non-inverted Internet sum)
*
* @note accumulator size limits summable length to 64k
* @note host endianness is irrelevant (p3 RFC1071)
*/
u16_t
lwip_standard_chksum(const void *dataptr, int len)
{
u32_t acc;
u16_t src;
const u8_t *octetptr;
acc = 0;
/* dataptr may be at odd or even addresses */
octetptr = (const u8_t *)dataptr;
while (len > 1) {
/* declare first octet as most significant
thus assume network order, ignoring host order */
src = (*octetptr) << 8;
octetptr++;
/* declare second octet as least significant */
src |= (*octetptr);
octetptr++;
acc += src;
len -= 2;
}
if (len > 0) {
/* accumulate remaining octet */
src = (*octetptr) << 8;
acc += src;
}
/* add deferred carry bits */
acc = (acc >> 16) + (acc & 0x0000ffffUL);
if ((acc & 0xffff0000UL) != 0) {
acc = (acc >> 16) + (acc & 0x0000ffffUL);
}
/* This maybe a little confusing: reorder sum using lwip_htons()
instead of lwip_ntohs() since it has a little less call overhead.
The caller must invert bits for Internet sum ! */
return lwip_htons((u16_t)acc);
}
#endif
#if (LWIP_CHKSUM_ALGORITHM == 2) /* Alternative version #2 */
/*
* Curt McDowell
* Broadcom Corp.
* csm@broadcom.com
*
* IP checksum two bytes at a time with support for
* unaligned buffer.
* Works for len up to and including 0x20000.
* by Curt McDowell, Broadcom Corp. 12/08/2005
*
* @param dataptr points to start of data to be summed at any boundary
* @param len length of data to be summed
* @return host order (!) lwip checksum (non-inverted Internet sum)
*/
u16_t
lwip_standard_chksum(const void *dataptr, int len)
{
const u8_t *pb = (const u8_t *)dataptr;
const u16_t *ps;
u16_t t = 0;
u32_t sum = 0;
int odd = ((mem_ptr_t)pb & 1);
/* Get aligned to u16_t */
if (odd && len > 0) {
((u8_t *)&t)[1] = *pb++;
len--;
}
/* Add the bulk of the data */
ps = (const u16_t *)(const void *)pb;
while (len > 1) {
sum += *ps++;
len -= 2;
}
/* Consume left-over byte, if any */
if (len > 0) {
((u8_t *)&t)[0] = *(const u8_t *)ps;
}
/* Add end bytes */
sum += t;
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
sum = FOLD_U32T(sum);
sum = FOLD_U32T(sum);
/* Swap if alignment was odd */
if (odd) {
sum = SWAP_BYTES_IN_WORD(sum);
}
return (u16_t)sum;
}
#endif
#if (LWIP_CHKSUM_ALGORITHM == 3) /* Alternative version #3 */
/**
* An optimized checksum routine. Basically, it uses loop-unrolling on
* the checksum loop, treating the head and tail bytes specially, whereas
* the inner loop acts on 8 bytes at a time.
*
* @arg start of buffer to be checksummed. May be an odd byte address.
* @len number of bytes in the buffer to be checksummed.
* @return host order (!) lwip checksum (non-inverted Internet sum)
*
* by Curt McDowell, Broadcom Corp. December 8th, 2005
*/
u16_t
lwip_standard_chksum(const void *dataptr, int len)
{
const u8_t *pb = (const u8_t *)dataptr;
const u16_t *ps;
u16_t t = 0;
const u32_t *pl;
u32_t sum = 0, tmp;
/* starts at odd byte address? */
int odd = ((mem_ptr_t)pb & 1);
if (odd && len > 0) {
((u8_t *)&t)[1] = *pb++;
len--;
}
ps = (const u16_t *)(const void *)pb;
if (((mem_ptr_t)ps & 3) && len > 1) {
sum += *ps++;
len -= 2;
}
pl = (const u32_t *)(const void *)ps;
while (len > 7) {
tmp = sum + *pl++; /* ping */
if (tmp < sum) {
tmp++; /* add back carry */
}
sum = tmp + *pl++; /* pong */
if (sum < tmp) {
sum++; /* add back carry */
}
len -= 8;
}
/* make room in upper bits */
sum = FOLD_U32T(sum);
ps = (const u16_t *)pl;
/* 16-bit aligned word remaining? */
while (len > 1) {
sum += *ps++;
len -= 2;
}
/* dangling tail byte remaining? */
if (len > 0) { /* include odd byte */
((u8_t *)&t)[0] = *(const u8_t *)ps;
}
sum += t; /* add end bytes */
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
sum = FOLD_U32T(sum);
sum = FOLD_U32T(sum);
if (odd) {
sum = SWAP_BYTES_IN_WORD(sum);
}
return (u16_t)sum;
}
#endif
/** Parts of the pseudo checksum which are common to IPv4 and IPv6 */
static u16_t
inet_cksum_pseudo_base(struct pbuf *p, u8_t proto, u16_t proto_len, u32_t acc)
{
struct pbuf *q;
int swapped = 0;
/* iterate through all pbuf in chain */
for (q = p; q != NULL; q = q->next) {
LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): checksumming pbuf %p (has next %p) \n",
(void *)q, (void *)q->next));
acc += LWIP_CHKSUM(q->payload, q->len);
/*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): unwrapped lwip_chksum()=%"X32_F" \n", acc));*/
/* just executing this next line is probably faster that the if statement needed
to check whether we really need to execute it, and does no harm */
acc = FOLD_U32T(acc);
if (q->len % 2 != 0) {
swapped = !swapped;
acc = SWAP_BYTES_IN_WORD(acc);
}
/*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): wrapped lwip_chksum()=%"X32_F" \n", acc));*/
}
if (swapped) {
acc = SWAP_BYTES_IN_WORD(acc);
}
acc += (u32_t)lwip_htons((u16_t)proto);
acc += (u32_t)lwip_htons(proto_len);
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): pbuf chain lwip_chksum()=%"X32_F"\n", acc));
return (u16_t)~(acc & 0xffffUL);
}
#if LWIP_IPV4
/* inet_chksum_pseudo:
*
* Calculates the IPv4 pseudo Internet checksum used by TCP and UDP for a pbuf chain.
* IP addresses are expected to be in network byte order.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param src source ip address (used for checksum of pseudo header)
* @param dst destination ip address (used for checksum of pseudo header)
* @param proto ip protocol (used for checksum of pseudo header)
* @param proto_len length of the ip data part (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
inet_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len,
const ip4_addr_t *src, const ip4_addr_t *dest)
{
u32_t acc;
u32_t addr;
addr = ip4_addr_get_u32(src);
acc = (addr & 0xffffUL);
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
addr = ip4_addr_get_u32(dest);
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
/* fold down to 16 bits */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
return inet_cksum_pseudo_base(p, proto, proto_len, acc);
}
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
/**
* Calculates the checksum with IPv6 pseudo header used by TCP and UDP for a pbuf chain.
* IPv6 addresses are expected to be in network byte order.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param proto ipv6 protocol/next header (used for checksum of pseudo header)
* @param proto_len length of the ipv6 payload (used for checksum of pseudo header)
* @param src source ipv6 address (used for checksum of pseudo header)
* @param dest destination ipv6 address (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
ip6_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len,
const ip6_addr_t *src, const ip6_addr_t *dest)
{
u32_t acc = 0;
u32_t addr;
u8_t addr_part;
for (addr_part = 0; addr_part < 4; addr_part++) {
addr = src->addr[addr_part];
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
addr = dest->addr[addr_part];
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
}
/* fold down to 16 bits */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
return inet_cksum_pseudo_base(p, proto, proto_len, acc);
}
#endif /* LWIP_IPV6 */
/* ip_chksum_pseudo:
*
* Calculates the IPv4 or IPv6 pseudo Internet checksum used by TCP and UDP for a pbuf chain.
* IP addresses are expected to be in network byte order.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param src source ip address (used for checksum of pseudo header)
* @param dst destination ip address (used for checksum of pseudo header)
* @param proto ip protocol (used for checksum of pseudo header)
* @param proto_len length of the ip data part (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
ip_chksum_pseudo(struct pbuf *p, u8_t proto, u16_t proto_len,
const ip_addr_t *src, const ip_addr_t *dest)
{
#if LWIP_IPV6
if (IP_IS_V6(dest)) {
return ip6_chksum_pseudo(p, proto, proto_len, ip_2_ip6(src), ip_2_ip6(dest));
}
#endif /* LWIP_IPV6 */
#if LWIP_IPV4 && LWIP_IPV6
else
#endif /* LWIP_IPV4 && LWIP_IPV6 */
#if LWIP_IPV4
{
return inet_chksum_pseudo(p, proto, proto_len, ip_2_ip4(src), ip_2_ip4(dest));
}
#endif /* LWIP_IPV4 */
}
/** Parts of the pseudo checksum which are common to IPv4 and IPv6 */
static u16_t
inet_cksum_pseudo_partial_base(struct pbuf *p, u8_t proto, u16_t proto_len,
u16_t chksum_len, u32_t acc)
{
struct pbuf *q;
int swapped = 0;
u16_t chklen;
/* iterate through all pbuf in chain */
for (q = p; (q != NULL) && (chksum_len > 0); q = q->next) {
LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): checksumming pbuf %p (has next %p) \n",
(void *)q, (void *)q->next));
chklen = q->len;
if (chklen > chksum_len) {
chklen = chksum_len;
}
acc += LWIP_CHKSUM(q->payload, chklen);
chksum_len = (u16_t)(chksum_len - chklen);
LWIP_ASSERT("delete me", chksum_len < 0x7fff);
/*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): unwrapped lwip_chksum()=%"X32_F" \n", acc));*/
/* fold the upper bit down */
acc = FOLD_U32T(acc);
if (q->len % 2 != 0) {
swapped = !swapped;
acc = SWAP_BYTES_IN_WORD(acc);
}
/*LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): wrapped lwip_chksum()=%"X32_F" \n", acc));*/
}
if (swapped) {
acc = SWAP_BYTES_IN_WORD(acc);
}
acc += (u32_t)lwip_htons((u16_t)proto);
acc += (u32_t)lwip_htons(proto_len);
/* Fold 32-bit sum to 16 bits
calling this twice is probably faster than if statements... */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
LWIP_DEBUGF(INET_DEBUG, ("inet_chksum_pseudo(): pbuf chain lwip_chksum()=%"X32_F"\n", acc));
return (u16_t)~(acc & 0xffffUL);
}
#if LWIP_IPV4
/* inet_chksum_pseudo_partial:
*
* Calculates the IPv4 pseudo Internet checksum used by TCP and UDP for a pbuf chain.
* IP addresses are expected to be in network byte order.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param src source ip address (used for checksum of pseudo header)
* @param dst destination ip address (used for checksum of pseudo header)
* @param proto ip protocol (used for checksum of pseudo header)
* @param proto_len length of the ip data part (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
inet_chksum_pseudo_partial(struct pbuf *p, u8_t proto, u16_t proto_len,
u16_t chksum_len, const ip4_addr_t *src, const ip4_addr_t *dest)
{
u32_t acc;
u32_t addr;
addr = ip4_addr_get_u32(src);
acc = (addr & 0xffffUL);
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
addr = ip4_addr_get_u32(dest);
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
/* fold down to 16 bits */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
return inet_cksum_pseudo_partial_base(p, proto, proto_len, chksum_len, acc);
}
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
/**
* Calculates the checksum with IPv6 pseudo header used by TCP and UDP for a pbuf chain.
* IPv6 addresses are expected to be in network byte order. Will only compute for a
* portion of the payload.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param proto ipv6 protocol/next header (used for checksum of pseudo header)
* @param proto_len length of the ipv6 payload (used for checksum of pseudo header)
* @param chksum_len number of payload bytes used to compute chksum
* @param src source ipv6 address (used for checksum of pseudo header)
* @param dest destination ipv6 address (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
ip6_chksum_pseudo_partial(struct pbuf *p, u8_t proto, u16_t proto_len,
u16_t chksum_len, const ip6_addr_t *src, const ip6_addr_t *dest)
{
u32_t acc = 0;
u32_t addr;
u8_t addr_part;
for (addr_part = 0; addr_part < 4; addr_part++) {
addr = src->addr[addr_part];
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
addr = dest->addr[addr_part];
acc = (u32_t)(acc + (addr & 0xffffUL));
acc = (u32_t)(acc + ((addr >> 16) & 0xffffUL));
}
/* fold down to 16 bits */
acc = FOLD_U32T(acc);
acc = FOLD_U32T(acc);
return inet_cksum_pseudo_partial_base(p, proto, proto_len, chksum_len, acc);
}
#endif /* LWIP_IPV6 */
/* ip_chksum_pseudo_partial:
*
* Calculates the IPv4 or IPv6 pseudo Internet checksum used by TCP and UDP for a pbuf chain.
*
* @param p chain of pbufs over that a checksum should be calculated (ip data part)
* @param src source ip address (used for checksum of pseudo header)
* @param dst destination ip address (used for checksum of pseudo header)
* @param proto ip protocol (used for checksum of pseudo header)
* @param proto_len length of the ip data part (used for checksum of pseudo header)
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
ip_chksum_pseudo_partial(struct pbuf *p, u8_t proto, u16_t proto_len,
u16_t chksum_len, const ip_addr_t *src, const ip_addr_t *dest)
{
#if LWIP_IPV6
if (IP_IS_V6(dest)) {
return ip6_chksum_pseudo_partial(p, proto, proto_len, chksum_len, ip_2_ip6(src), ip_2_ip6(dest));
}
#endif /* LWIP_IPV6 */
#if LWIP_IPV4 && LWIP_IPV6
else
#endif /* LWIP_IPV4 && LWIP_IPV6 */
#if LWIP_IPV4
{
return inet_chksum_pseudo_partial(p, proto, proto_len, chksum_len, ip_2_ip4(src), ip_2_ip4(dest));
}
#endif /* LWIP_IPV4 */
}
/* inet_chksum:
*
* Calculates the Internet checksum over a portion of memory. Used primarily for IP
* and ICMP.
*
* @param dataptr start of the buffer to calculate the checksum (no alignment needed)
* @param len length of the buffer to calculate the checksum
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
inet_chksum(const void *dataptr, u16_t len)
{
return (u16_t)~(unsigned int)LWIP_CHKSUM(dataptr, len);
}
/**
* Calculate a checksum over a chain of pbufs (without pseudo-header, much like
* inet_chksum only pbufs are used).
*
* @param p pbuf chain over that the checksum should be calculated
* @return checksum (as u16_t) to be saved directly in the protocol header
*/
u16_t
inet_chksum_pbuf(struct pbuf *p)
{
u32_t acc;
struct pbuf *q;
int swapped = 0;
acc = 0;
for (q = p; q != NULL; q = q->next) {
acc += LWIP_CHKSUM(q->payload, q->len);
acc = FOLD_U32T(acc);
if (q->len % 2 != 0) {
swapped = !swapped;
acc = SWAP_BYTES_IN_WORD(acc);
}
}
if (swapped) {
acc = SWAP_BYTES_IN_WORD(acc);
}
return (u16_t)~(acc & 0xffffUL);
}
/* These are some implementations for LWIP_CHKSUM_COPY, which copies data
* like MEMCPY but generates a checksum at the same time. Since this is a
* performance-sensitive function, you might want to create your own version
* in assembly targeted at your hardware by defining it in lwipopts.h:
* #define LWIP_CHKSUM_COPY(dst, src, len) your_chksum_copy(dst, src, len)
*/
#if (LWIP_CHKSUM_COPY_ALGORITHM == 1) /* Version #1 */
/** Safe but slow: first call MEMCPY, then call LWIP_CHKSUM.
* For architectures with big caches, data might still be in cache when
* generating the checksum after copying.
*/
u16_t
lwip_chksum_copy(void *dst, const void *src, u16_t len)
{
MEMCPY(dst, src, len);
return LWIP_CHKSUM(dst, len);
}
#endif /* (LWIP_CHKSUM_COPY_ALGORITHM == 1) */

View File

@ -1,100 +0,0 @@
/**
* @file
* lwIP initialization API
*/
/*
* 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_HDR_INIT_H
#define LWIP_HDR_INIT_H
#include "lwip/opt.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup lwip_version Version
* @ingroup lwip
* @{
*/
/** X.x.x: Major version of the stack */
#define LWIP_VERSION_MAJOR ${LWIP_VERSION_MAJOR}
/** x.X.x: Minor version of the stack */
#define LWIP_VERSION_MINOR ${LWIP_VERSION_MINOR}
/** x.x.X: Revision of the stack */
#define LWIP_VERSION_REVISION ${LWIP_VERSION_REVISION}
/** For release candidates, this is set to 1..254
* For official releases, this is set to 255 (LWIP_RC_RELEASE)
* For development versions (Git), this is set to 0 (LWIP_RC_DEVELOPMENT) */
#define LWIP_VERSION_RC ${LWIP_VERSION_RC}
/** LWIP_VERSION_RC is set to LWIP_RC_RELEASE for official releases */
#define LWIP_RC_RELEASE 255
/** LWIP_VERSION_RC is set to LWIP_RC_DEVELOPMENT for Git versions */
#define LWIP_RC_DEVELOPMENT 0
#define LWIP_VERSION_IS_RELEASE (LWIP_VERSION_RC == LWIP_RC_RELEASE)
#define LWIP_VERSION_IS_DEVELOPMENT (LWIP_VERSION_RC == LWIP_RC_DEVELOPMENT)
#define LWIP_VERSION_IS_RC ((LWIP_VERSION_RC != LWIP_RC_RELEASE) && (LWIP_VERSION_RC != LWIP_RC_DEVELOPMENT))
/* Some helper defines to get a version string */
#define LWIP_VERSTR2(x) #x
#define LWIP_VERSTR(x) LWIP_VERSTR2(x)
#if LWIP_VERSION_IS_RELEASE
#define LWIP_VERSION_STRING_SUFFIX ""
#elif LWIP_VERSION_IS_DEVELOPMENT
#define LWIP_VERSION_STRING_SUFFIX "d"
#else
#define LWIP_VERSION_STRING_SUFFIX "rc" LWIP_VERSTR(LWIP_VERSION_RC)
#endif
/** Provides the version of the stack */
#define LWIP_VERSION ((LWIP_VERSION_MAJOR) << 24 | (LWIP_VERSION_MINOR) << 16 | \
(LWIP_VERSION_REVISION) << 8 | (LWIP_VERSION_RC))
/** Provides the version of the stack as string */
#define LWIP_VERSION_STRING LWIP_VERSTR(LWIP_VERSION_MAJOR) "." LWIP_VERSTR(LWIP_VERSION_MINOR) "." LWIP_VERSTR(LWIP_VERSION_REVISION) LWIP_VERSION_STRING_SUFFIX
/**
* @}
*/
/* Modules initialization */
void lwip_init(void);
#ifdef __cplusplus
}
#endif
#endif /* LWIP_HDR_INIT_H */

View File

@ -1,167 +0,0 @@
/**
* @file
* Common IPv4 and IPv6 code
*
* @defgroup ip IP
* @ingroup callbackstyle_api
*
* @defgroup ip4 IPv4
* @ingroup ip
*
* @defgroup ip6 IPv6
* @ingroup ip
*
* @defgroup ipaddr IP address handling
* @ingroup infrastructure
*
* @defgroup ip4addr IPv4 only
* @ingroup ipaddr
*
* @defgroup ip6addr IPv6 only
* @ingroup ipaddr
*/
/*
* 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_IPV4 || LWIP_IPV6
#include "lwip/ip_addr.h"
#include "lwip/ip.h"
/** Global data for both IPv4 and IPv6 */
struct ip_globals ip_data;
#if LWIP_IPV4 && LWIP_IPV6
const ip_addr_t ip_addr_any_type = IPADDR_ANY_TYPE_INIT;
/**
* @ingroup ipaddr
* Convert numeric IP address (both versions) into ASCII representation.
* returns ptr to static buffer; not reentrant!
*
* @param addr ip address in network order to convert
* @return pointer to a global static (!) buffer that holds the ASCII
* representation of addr
*/
char *ipaddr_ntoa(const ip_addr_t *addr)
{
if (addr == NULL) {
return NULL;
}
if (IP_IS_V6(addr)) {
return ip6addr_ntoa(ip_2_ip6(addr));
} else {
return ip4addr_ntoa(ip_2_ip4(addr));
}
}
/**
* @ingroup ipaddr
* Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used.
*
* @param addr ip address in network order to convert
* @param buf target buffer where the string is stored
* @param buflen length of buf
* @return either pointer to buf which now holds the ASCII
* representation of addr or NULL if buf was too small
*/
char *ipaddr_ntoa_r(const ip_addr_t *addr, char *buf, int buflen)
{
if (addr == NULL) {
return NULL;
}
if (IP_IS_V6(addr)) {
return ip6addr_ntoa_r(ip_2_ip6(addr), buf, buflen);
} else {
return ip4addr_ntoa_r(ip_2_ip4(addr), buf, buflen);
}
}
/**
* @ingroup ipaddr
* Convert IP address string (both versions) to numeric.
* The version is auto-detected from the string.
*
* @param cp IP address string to convert
* @param addr conversion result is stored here
* @return 1 on success, 0 on error
*/
int
ipaddr_aton(const char *cp, ip_addr_t *addr)
{
if (cp != NULL) {
const char *c;
for (c = cp; *c != 0; c++) {
if (*c == ':') {
/* contains a colon: IPv6 address */
if (addr) {
IP_SET_TYPE_VAL(*addr, IPADDR_TYPE_V6);
}
return ip6addr_aton(cp, ip_2_ip6(addr));
} else if (*c == '.') {
/* contains a dot: IPv4 address */
break;
}
}
/* call ip4addr_aton as fallback or if IPv4 was found */
if (addr) {
IP_SET_TYPE_VAL(*addr, IPADDR_TYPE_V4);
}
return ip4addr_aton(cp, ip_2_ip4(addr));
}
return 0;
}
/**
* @ingroup lwip_nosys
* If both IP versions are enabled, this function can dispatch packets to the correct one.
* Don't call directly, pass to netif_add() and call netif->input().
*/
err_t
ip_input(struct pbuf *p, struct netif *inp)
{
if (p != NULL) {
if (IP_HDR_GET_VERSION(p->payload) == 6) {
return ip6_input(p, inp);
}
return ip4_input(p, inp);
}
return ERR_VAL;
}
#endif /* LWIP_IPV4 && LWIP_IPV6 */
#endif /* LWIP_IPV4 || LWIP_IPV6 */

View File

@ -1,557 +0,0 @@
/**
* @file
*
* ACD IPv4 Address Conflict Detection
*
* This is an IPv4 address conflict detection implementation for the lwIP TCP/IP
* stack. It aims to be conform to RFC5227.
*
* @defgroup acd ACD
* @ingroup ip4
* ACD related functions
* USAGE:
*
* define @ref LWIP_ACD 1 in your lwipopts.h
* Options:
* ACD_TMR_INTERVAL msecs,
* I recommend a value of 100. The value must divide 1000 with a remainder almost 0.
* Possible values are 1000, 500, 333, 250, 200, 166, 142, 125, 111, 100 ....
*
* For fixed IP:
* - call acd_start after selecting an IP address. The caller will be informed
* on conflict status via the callback function.
*
* With AUTOIP:
* - will be called from the autoip module. No extra's needed.
*
* With DHCP:
* - enable LWIP_DHCP_DOES_ACD_CHECK. Then it will be called from the dhcp module.
* No extra's needed.
*/
/*
*
* Copyright (c) 2007 Dominik Spies <kontakt@dspies.de>
* Copyright (c) 2018 Jasper Verschueren <jasper.verschueren@apart-audio.com>
* 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: Jasper Verschueren <jasper.verschueren@apart-audio.com>
* Author: Dominik Spies <kontakt@dspies.de>
*/
#include "lwip/opt.h"
/* don't build if not configured for use in lwipopts.h */
#if LWIP_IPV4 && LWIP_ACD
#include <string.h>
#include "lwip/acd.h"
#include "lwip/prot/acd.h"
#define ACD_FOREACH(acd, acd_list) for ((acd) = acd_list; (acd) != NULL; (acd) = (acd)->next)
#define ACD_TICKS_PER_SECOND (1000 / ACD_TMR_INTERVAL)
/* Define good random function (LWIP_RAND) in lwipopts.h */
#ifdef LWIP_RAND
#define LWIP_ACD_RAND(netif, acd) LWIP_RAND()
#else /* LWIP_RAND */
#ifdef LWIP_AUTOIP_RAND
#include "lwip/autoip.h"
#define LWIP_ACD_RAND(netif, acd) LWIP_AUTOIP_RAND(netif) /* for backwards compatibility */
#else
#define LWIP_ACD_RAND(netif, acd) ((((u32_t)((netif->hwaddr[5]) & 0xff) << 24) | \
((u32_t)((netif->hwaddr[3]) & 0xff) << 16) | \
((u32_t)((netif->hwaddr[2]) & 0xff) << 8) | \
((u32_t)((netif->hwaddr[4]) & 0xff))) + \
(acd->sent_num))
#endif /* LWIP_AUTOIP_RAND */
#endif /* LWIP_RAND */
#define ACD_RANDOM_PROBE_WAIT(netif, acd) (LWIP_ACD_RAND(netif, acd) % \
(PROBE_WAIT * ACD_TICKS_PER_SECOND))
#define ACD_RANDOM_PROBE_INTERVAL(netif, acd) ((LWIP_ACD_RAND(netif, acd) % \
((PROBE_MAX - PROBE_MIN) * ACD_TICKS_PER_SECOND)) + \
(PROBE_MIN * ACD_TICKS_PER_SECOND ))
/* Function definitions */
static void acd_restart(struct netif *netif, struct acd *acd);
static void acd_handle_arp_conflict(struct netif *netif, struct acd *acd);
static void acd_put_in_passive_mode(struct netif *netif, struct acd *acd);
/**
* @ingroup acd
* Add ACD client to the client list and initialize callback function
*
* @param netif network interface on which to start the acd
* client
* @param acd acd module to be added to the list
* @param acd_conflict_callback callback to be called when conflict information
* is available
*/
err_t
acd_add(struct netif *netif, struct acd *acd,
acd_conflict_callback_t acd_conflict_callback)
{
struct acd *acd2;
/* Set callback */
LWIP_ASSERT_CORE_LOCKED();
LWIP_ASSERT("acd_conflict_callback != NULL", acd_conflict_callback != NULL);
acd->acd_conflict_callback = acd_conflict_callback;
/* Check if the acd struct is already added */
for (acd2 = netif->acd_list; acd2 != NULL; acd2 = acd2->next) {
if (acd2 == acd) {
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_add(): acd already added to list\n"));
return ERR_OK;
}
}
/* add acd struct to the list */
acd->next = netif->acd_list;
netif->acd_list = acd;
return ERR_OK;
}
/**
* @ingroup acd
* Remvoe ACD client from the client list
*
* @param netif network interface from which to remove the acd client
* @param acd acd module to be removed from the list
*/
void
acd_remove(struct netif *netif, struct acd *acd)
{
struct acd *acd2, *prev = NULL;
LWIP_ASSERT_CORE_LOCKED();
for (acd2 = netif->acd_list; acd2 != NULL; acd2 = acd2->next) {
if (acd2 == acd) {
if (prev) {
prev->next = acd->next;
} else {
netif->acd_list = acd->next;
}
return;
}
prev = acd2;
}
LWIP_ASSERT(("acd_remove(): acd not on list\n"), 0);
}
/**
* @ingroup acd
* Start ACD client
*
* @param netif network interface on which to start the acd client
* @param acd acd module to start
* @param ipaddr ip address to perform acd on
*/
err_t
acd_start(struct netif *netif, struct acd *acd, ip4_addr_t ipaddr)
{
err_t result = ERR_OK;
LWIP_UNUSED_ARG(netif);
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_start(netif=%p) %c%c%"U16_F"\n",
(void *)netif, netif->name[0],
netif->name[1], (u16_t)netif->num));
/* init probing state */
acd->sent_num = 0;
acd->lastconflict = 0;
ip4_addr_copy(acd->ipaddr, ipaddr);
acd->state = ACD_STATE_PROBE_WAIT;
acd->ttw = (u16_t)(ACD_RANDOM_PROBE_WAIT(netif, acd));
return result;
}
/**
* @ingroup acd
* Stop ACD client
*
* @param acd acd module to stop
*/
err_t
acd_stop(struct acd *acd)
{
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("acd_stop\n"));
if (acd != NULL) {
acd->state = ACD_STATE_OFF;
}
return ERR_OK;
}
/**
* @ingroup acd
* Inform the ACD modules when the link goes down
*
* @param netif network interface on which to inform the ACD clients
*/
void
acd_network_changed_link_down(struct netif *netif)
{
struct acd *acd;
/* loop over the acd's*/
ACD_FOREACH(acd, netif->acd_list) {
acd_stop(acd);
}
}
/**
* Has to be called in loop every ACD_TMR_INTERVAL milliseconds
*/
void
acd_tmr(void)
{
struct netif *netif;
struct acd *acd;
/* loop through netif's */
NETIF_FOREACH(netif) {
ACD_FOREACH(acd, netif->acd_list) {
if (acd->lastconflict > 0) {
acd->lastconflict--;
}
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE,
("acd_tmr() ACD-State: %"U16_F", ttw=%"U16_F"\n",
(u16_t)(acd->state), acd->ttw));
if (acd->ttw > 0) {
acd->ttw--;
}
switch (acd->state) {
case ACD_STATE_PROBE_WAIT:
case ACD_STATE_PROBING:
if (acd->ttw == 0) {
acd->state = ACD_STATE_PROBING;
etharp_acd_probe(netif, &acd->ipaddr);
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE,
("acd_tmr() PROBING Sent Probe\n"));
acd->sent_num++;
if (acd->sent_num >= PROBE_NUM) {
/* Switch to ANNOUNCE_WAIT: last probe is sent*/
acd->state = ACD_STATE_ANNOUNCE_WAIT;
acd->sent_num = 0;
/* calculate time to wait before announcing */
acd->ttw = (u16_t)(ANNOUNCE_WAIT * ACD_TICKS_PER_SECOND);
} else {
/* calculate time to wait to next probe */
acd->ttw = (u16_t)(ACD_RANDOM_PROBE_INTERVAL(netif, acd));
}
}
break;
case ACD_STATE_ANNOUNCE_WAIT:
case ACD_STATE_ANNOUNCING:
if (acd->ttw == 0) {
if (acd->sent_num == 0) {
acd->state = ACD_STATE_ANNOUNCING;
/* reset conflict count to ensure fast re-probing after announcing */
acd->num_conflicts = 0;
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_tmr(): changing state to ANNOUNCING: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
ip4_addr1_16(&acd->ipaddr), ip4_addr2_16(&acd->ipaddr),
ip4_addr3_16(&acd->ipaddr), ip4_addr4_16(&acd->ipaddr)));
}
etharp_acd_announce(netif, &acd->ipaddr);
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE,
("acd_tmr() ANNOUNCING Sent Announce\n"));
acd->ttw = ANNOUNCE_INTERVAL * ACD_TICKS_PER_SECOND;
acd->sent_num++;
if (acd->sent_num >= ANNOUNCE_NUM) {
acd->state = ACD_STATE_ONGOING;
acd->sent_num = 0;
acd->ttw = 0;
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_tmr(): changing state to ONGOING: %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
ip4_addr1_16(&acd->ipaddr), ip4_addr2_16(&acd->ipaddr),
ip4_addr3_16(&acd->ipaddr), ip4_addr4_16(&acd->ipaddr)));
/* finally, let acd user know that the address is good and can be used */
acd->acd_conflict_callback(netif, ACD_IP_OK);
}
}
break;
case ACD_STATE_RATE_LIMIT:
if (acd->ttw == 0) {
/* acd should be stopped because ipaddr isn't valid any more */
acd_stop(acd);
/* let the acd user (after rate limit interval) know that their is
* a conflict detected. So it can restart the address acquiring
* process.*/
acd->acd_conflict_callback(netif, ACD_RESTART_CLIENT);
}
break;
default:
/* nothing to do in other states */
break;
}
}
}
}
/**
* Restarts the acd module
*
* The number of conflicts is increased and the upper layer is informed.
*/
static void
acd_restart(struct netif *netif, struct acd *acd)
{
/* increase conflict counter. */
acd->num_conflicts++;
/* Decline the address */
acd->acd_conflict_callback(netif, ACD_DECLINE);
/* if we tried more then MAX_CONFLICTS we must limit our rate for
* acquiring and probing addresses. compliant to RFC 5227 Section 2.1.1 */
if (acd->num_conflicts >= MAX_CONFLICTS) {
acd->state = ACD_STATE_RATE_LIMIT;
acd->ttw = (u16_t)(RATE_LIMIT_INTERVAL * ACD_TICKS_PER_SECOND);
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
("acd_restart(): rate limiting initiated. too many conflicts\n"));
}
else {
/* acd should be stopped because ipaddr isn't valid any more */
acd_stop(acd);
/* let the acd user know right away that their is a conflict detected.
* So it can restart the address acquiring process. */
acd->acd_conflict_callback(netif, ACD_RESTART_CLIENT);
}
}
/**
* Handles every incoming ARP Packet, called by etharp_input().
*
* @param netif network interface to use for acd processing
* @param hdr Incoming ARP packet
*/
void
acd_arp_reply(struct netif *netif, struct etharp_hdr *hdr)
{
struct acd *acd;
ip4_addr_t sipaddr, dipaddr;
struct eth_addr netifaddr;
SMEMCPY(netifaddr.addr, netif->hwaddr, ETH_HWADDR_LEN);
/* Copy struct ip4_addr_wordaligned to aligned ip4_addr, to support
* compilers without structure packing (not using structure copy which
* breaks strict-aliasing rules).
*/
IPADDR_WORDALIGNED_COPY_TO_IP4_ADDR_T(&sipaddr, &hdr->sipaddr);
IPADDR_WORDALIGNED_COPY_TO_IP4_ADDR_T(&dipaddr, &hdr->dipaddr);
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE, ("acd_arp_reply()\n"));
/* loop over the acd's*/
ACD_FOREACH(acd, netif->acd_list) {
switch(acd->state) {
case ACD_STATE_OFF:
case ACD_STATE_RATE_LIMIT:
default:
/* do nothing */
break;
case ACD_STATE_PROBE_WAIT:
case ACD_STATE_PROBING:
case ACD_STATE_ANNOUNCE_WAIT:
/* RFC 5227 Section 2.1.1:
* from beginning to after ANNOUNCE_WAIT seconds we have a conflict if
* ip.src == ipaddr (someone is already using the address)
* OR
* ip.dst == ipaddr && hw.src != own hwaddr (someone else is probing it)
*/
if ((ip4_addr_eq(&sipaddr, &acd->ipaddr)) ||
(ip4_addr_isany_val(sipaddr) &&
ip4_addr_eq(&dipaddr, &acd->ipaddr) &&
!eth_addr_eq(&netifaddr, &hdr->shwaddr))) {
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
("acd_arp_reply(): Probe Conflict detected\n"));
acd_restart(netif, acd);
}
break;
case ACD_STATE_ANNOUNCING:
case ACD_STATE_ONGOING:
case ACD_STATE_PASSIVE_ONGOING:
/* RFC 5227 Section 2.4:
* in any state we have a conflict if
* ip.src == ipaddr && hw.src != own hwaddr (someone is using our address)
*/
if (ip4_addr_eq(&sipaddr, &acd->ipaddr) &&
!eth_addr_eq(&netifaddr, &hdr->shwaddr)) {
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE | LWIP_DBG_LEVEL_WARNING,
("acd_arp_reply(): Conflicting ARP-Packet detected\n"));
acd_handle_arp_conflict(netif, acd);
}
break;
}
}
}
/**
* Handle a IP address conflict after an ARP conflict detection
*/
static void
acd_handle_arp_conflict(struct netif *netif, struct acd *acd)
{
/* RFC5227, 2.4 "Ongoing Address Conflict Detection and Address Defense"
allows three options where:
a) means retreat on the first conflict,
b) allows to keep an already configured address when having only one
conflict in DEFEND_INTERVAL seconds and
c) the host will not give up it's address and defend it indefinitely
We use option b) when the acd module represents the netif address, since it
helps to improve the chance that one of the two conflicting hosts may be
able to retain its address. while we are flexible enough to help network
performance
We use option a) when the acd module does not represent the netif address,
since we cannot have the acd module announcing or restarting. This
situation occurs for the LL acd module when a routable address is used on
the netif but the LL address is still open in the background. */
if (acd->state == ACD_STATE_PASSIVE_ONGOING) {
/* Immediately back off on a conflict. */
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_handle_arp_conflict(): conflict when we are in passive mode -> back off\n"));
acd_stop(acd);
acd->acd_conflict_callback(netif, ACD_DECLINE);
}
else {
if (acd->lastconflict > 0) {
/* retreat, there was a conflicting ARP in the last DEFEND_INTERVAL seconds */
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_handle_arp_conflict(): conflict within DEFEND_INTERVAL -> retreating\n"));
/* Active TCP sessions are aborted when removing the ip address but a bad
* connection was inevitable anyway with conflicting hosts */
acd_restart(netif, acd);
} else {
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_handle_arp_conflict(): we are defending, send ARP Announce\n"));
etharp_acd_announce(netif, &acd->ipaddr);
acd->lastconflict = DEFEND_INTERVAL * ACD_TICKS_PER_SECOND;
}
}
}
/**
* Put the acd module in passive ongoing conflict detection.
*/
static void
acd_put_in_passive_mode(struct netif *netif, struct acd *acd)
{
switch(acd->state) {
case ACD_STATE_OFF:
case ACD_STATE_PASSIVE_ONGOING:
default:
/* do nothing */
break;
case ACD_STATE_PROBE_WAIT:
case ACD_STATE_PROBING:
case ACD_STATE_ANNOUNCE_WAIT:
case ACD_STATE_RATE_LIMIT:
acd_stop(acd);
acd->acd_conflict_callback(netif, ACD_DECLINE);
break;
case ACD_STATE_ANNOUNCING:
case ACD_STATE_ONGOING:
acd->state = ACD_STATE_PASSIVE_ONGOING;
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_put_in_passive_mode()\n"));
break;
}
}
/**
* @ingroup acd
* Inform the ACD modules of address changes
*
* @param netif network interface on which the address is changing
* @param old_addr old ip address
* @param new_addr new ip address
*/
void
acd_netif_ip_addr_changed(struct netif *netif, const ip_addr_t *old_addr,
const ip_addr_t *new_addr)
{
struct acd *acd;
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_netif_ip_addr_changed(): Address changed\n"));
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_netif_ip_addr_changed(): old address = %s\n", ipaddr_ntoa(old_addr)));
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_netif_ip_addr_changed(): new address = %s\n", ipaddr_ntoa(new_addr)));
/* If we change from ANY to an IP or from an IP to ANY we do nothing */
if (ip_addr_isany(old_addr) || ip_addr_isany(new_addr)) {
return;
}
ACD_FOREACH(acd, netif->acd_list) {
/* Find ACD module of old address */
if(ip4_addr_eq(&acd->ipaddr, ip_2_ip4(old_addr))) {
/* Did we change from a LL address to a routable address? */
if (ip_addr_islinklocal(old_addr) && !ip_addr_islinklocal(new_addr)) {
LWIP_DEBUGF(ACD_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("acd_netif_ip_addr_changed(): changed from LL to routable address\n"));
/* Put the module in passive conflict detection mode */
acd_put_in_passive_mode(netif, acd);
}
}
}
}
#endif /* LWIP_IPV4 && LWIP_ACD */

View File

@ -1,379 +0,0 @@
/**
* @file
* AutoIP Automatic LinkLocal IP Configuration
*
* This is a AutoIP implementation for the lwIP TCP/IP stack. It aims to conform
* with RFC 3927. It uses IPv4 address conflict detection to evaluate the chosen
* address. The ACD module aims to be conform to RFC 5227.
* RFC 5227 is extracted out of RFC 3927 so the acd module fits nicely in autoip.
*
* @defgroup autoip AUTOIP
* @ingroup ip4
* AUTOIP related functions
* USAGE:
*
* define @ref LWIP_AUTOIP 1 in your lwipopts.h
*
* Without DHCP:
* - Call autoip_start() after netif_add().
*
* With DHCP:
* - define @ref LWIP_DHCP_AUTOIP_COOP 1 in your lwipopts.h.
* - Configure your DHCP Client.
*
* @see netifapi_autoip
*/
/*
*
* Copyright (c) 2007 Dominik Spies <kontakt@dspies.de>
* 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: Dominik Spies <kontakt@dspies.de>
*/
#include "lwip/opt.h"
#if LWIP_IPV4 && LWIP_AUTOIP /* don't build if not configured for use in lwipopts.h */
#include "lwip/mem.h"
/* #include "lwip/udp.h" */
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/autoip.h"
#include "lwip/acd.h"
#include "lwip/etharp.h"
#include "lwip/prot/autoip.h"
#include <string.h>
/**
* Macro that generates the initial IP address to be tried by AUTOIP.
* If you want to override this, define it to something else in lwipopts.h.
*/
#ifndef LWIP_AUTOIP_CREATE_SEED_ADDR
#define LWIP_AUTOIP_CREATE_SEED_ADDR(netif) \
lwip_htonl(AUTOIP_RANGE_START + ((u32_t)(((u8_t)(netif->hwaddr[4])) | \
((u32_t)((u8_t)(netif->hwaddr[5]))) << 8)))
#endif /* LWIP_AUTOIP_CREATE_SEED_ADDR */
/* Function definitions */
static void autoip_restart(struct netif *netif);
static void autoip_create_addr(struct netif *netif, ip4_addr_t *ipaddr);
static err_t autoip_bind(struct netif *netif);
static void autoip_conflict_callback(struct netif *netif,
acd_callback_enum_t state);
/**
* @ingroup autoip
* Set a statically allocated struct autoip to work with.
* Using this prevents autoip_start to allocate it using mem_malloc.
*
* @param netif the netif for which to set the struct autoip
* @param autoip (uninitialised) autoip struct allocated by the application
*/
void
autoip_set_struct(struct netif *netif, struct autoip *autoip)
{
LWIP_ASSERT_CORE_LOCKED();
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("autoip != NULL", autoip != NULL);
LWIP_ASSERT("netif already has a struct autoip set",
netif_autoip_data(netif) == NULL);
/* clear data structure */
memset(autoip, 0, sizeof(struct autoip));
/* autoip->state = AUTOIP_STATE_OFF; */
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, autoip);
}
/**
* @ingroup autoip
* Remove a struct autoip previously set to the netif using autoip_set_struct()
*
* @param netif the netif for which to set the struct autoip
*/
void
autoip_remove_struct(struct netif *netif)
{
LWIP_ASSERT_CORE_LOCKED();
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("netif has no struct autoip set",
netif_autoip_data(netif) != NULL);
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, NULL);
}
/** Restart AutoIP client and check the next address (conflict detected)
*
* @param netif The netif under AutoIP control
*/
static void
autoip_restart(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
autoip->tried_llipaddr++;
autoip_start(netif);
}
/**
* Create an IP-Address out of range 169.254.1.0 to 169.254.254.255
*
* @param netif network interface on which create the IP-Address
* @param ipaddr ip address to initialize
*/
static void
autoip_create_addr(struct netif *netif, ip4_addr_t *ipaddr)
{
struct autoip *autoip = netif_autoip_data(netif);
/* Here we create an IP-Address out of range 169.254.1.0 to 169.254.254.255
* compliant to RFC 3927 Section 2.1
* We have 254 * 256 possibilities */
u32_t addr = lwip_ntohl(LWIP_AUTOIP_CREATE_SEED_ADDR(netif));
addr += autoip->tried_llipaddr;
addr = AUTOIP_NET | (addr & 0xffff);
/* Now, 169.254.0.0 <= addr <= 169.254.255.255 */
if (addr < AUTOIP_RANGE_START) {
addr += AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1;
}
if (addr > AUTOIP_RANGE_END) {
addr -= AUTOIP_RANGE_END - AUTOIP_RANGE_START + 1;
}
LWIP_ASSERT("AUTOIP address not in range", (addr >= AUTOIP_RANGE_START) &&
(addr <= AUTOIP_RANGE_END));
ip4_addr_set_u32(ipaddr, lwip_htonl(addr));
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("autoip_create_addr(): tried_llipaddr=%"U16_F", %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
(u16_t)(autoip->tried_llipaddr), ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr),
ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr)));
}
/**
* Configure interface for use with current LL IP-Address
*
* @param netif network interface to configure with current LL IP-Address
*/
static err_t
autoip_bind(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
ip4_addr_t sn_mask, gw_addr;
autoip->state = AUTOIP_STATE_BOUND;
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
("autoip_bind(netif=%p) %c%c%"U16_F" %"U16_F".%"U16_F".%"U16_F".%"U16_F"\n",
(void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num,
ip4_addr1_16(&autoip->llipaddr), ip4_addr2_16(&autoip->llipaddr),
ip4_addr3_16(&autoip->llipaddr), ip4_addr4_16(&autoip->llipaddr)));
IP4_ADDR(&sn_mask, 255, 255, 0, 0);
IP4_ADDR(&gw_addr, 0, 0, 0, 0);
netif_set_addr(netif, &autoip->llipaddr, &sn_mask, &gw_addr);
/* interface is used by routing now that an address is set */
return ERR_OK;
}
/**
* Handle conflict information from ACD module
*
* @param netif network interface to handle conflict information on
* @param state acd_callback_enum_t
*/
static void
autoip_conflict_callback(struct netif *netif, acd_callback_enum_t state)
{
struct autoip *autoip = netif_autoip_data(netif);
switch (state) {
case ACD_IP_OK:
autoip_bind(netif);
break;
case ACD_RESTART_CLIENT:
autoip_restart(netif);
break;
case ACD_DECLINE:
/* "delete" conflicting address so a new one will be selected in
* autoip_start() */
ip4_addr_set_any(&autoip->llipaddr);
autoip_stop(netif);
break;
default:
break;
}
}
/**
* @ingroup autoip
* Start AutoIP client
*
* @param netif network interface on which start the AutoIP client
*/
err_t
autoip_start(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
err_t result = ERR_OK;
LWIP_ASSERT_CORE_LOCKED();
LWIP_ERROR("netif is not up, old style port?", netif_is_up(netif), return ERR_ARG;);
if (autoip == NULL) {
/* no AutoIP client attached yet? */
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
("autoip_start(): starting new AUTOIP client\n"));
autoip = (struct autoip *)mem_calloc(1, sizeof(struct autoip));
if (autoip == NULL) {
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
("autoip_start(): could not allocate autoip\n"));
return ERR_MEM;
}
/* store this AutoIP client in the netif */
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_AUTOIP, autoip);
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE, ("autoip_start(): allocated autoip"));
}
if (autoip->state == AUTOIP_STATE_OFF) {
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("autoip_start(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0],
netif->name[1], (u16_t)netif->num));
/* add acd struct to list*/
acd_add(netif, &autoip->acd, autoip_conflict_callback);
/* In accordance to RFC3927 section 2.1:
* Keep using the same link local address as much as possible.
* Only when there is none or when there was a conflict, select a new one.
*/
if (!ip4_addr_islinklocal(&autoip->llipaddr)) {
autoip_create_addr(netif, &(autoip->llipaddr));
}
autoip->state = AUTOIP_STATE_CHECKING;
acd_start(netif, &autoip->acd, autoip->llipaddr);
} else {
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE,
("autoip_start(): already started on netif=%p %c%c%"U16_F"\n",
(void *)netif, netif->name[0],
netif->name[1], (u16_t)netif->num));
}
return result;
}
/**
* Handle a possible change in the network configuration: link up
*
* If there is an AutoIP address configured and AutoIP is not in cooperation
* with DHCP, start probing for previous address.
*/
void
autoip_network_changed_link_up(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
if (autoip && (autoip->state != AUTOIP_STATE_OFF) && !LWIP_DHCP_AUTOIP_COOP) {
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
("autoip_network_changed_link_up(): start acd"));
autoip->state = AUTOIP_STATE_CHECKING;
/* Start acd check again for the last used address */
acd_start(netif, &autoip->acd, autoip->llipaddr);
}
}
/**
* Handle a possible change in the network configuration: link down
*
* If there is an AutoIP address configured and AutoIP is in cooperation
* with DHCP, then stop the autoip module. When the link goes up, we do not want
* the autoip module to start again. DHCP will initiate autoip when needed.
*/
void
autoip_network_changed_link_down(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
if (autoip && (autoip->state != AUTOIP_STATE_OFF) && LWIP_DHCP_AUTOIP_COOP) {
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,
("autoip_network_changed_link_down(): stop autoip"));
autoip_stop(netif);
}
}
/**
* @ingroup autoip
* Stop AutoIP client
*
* @param netif network interface on which stop the AutoIP client
*/
err_t
autoip_stop(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
LWIP_ASSERT_CORE_LOCKED();
if (autoip != NULL) {
autoip->state = AUTOIP_STATE_OFF;
if (ip4_addr_islinklocal(netif_ip4_addr(netif))) {
netif_set_addr(netif, IP4_ADDR_ANY4, IP4_ADDR_ANY4, IP4_ADDR_ANY4);
}
LWIP_DEBUGF(AUTOIP_DEBUG | LWIP_DBG_TRACE,("autoip_stop()"));
}
return ERR_OK;
}
/** check if AutoIP supplied netif->ip_addr
*
* @param netif the netif to check
* @return 1 if AutoIP supplied netif->ip_addr (state BOUND),
* 0 otherwise
*/
u8_t
autoip_supplied_address(struct netif *netif)
{
struct autoip *autoip = netif_autoip_data(netif);
return (autoip != NULL)
&& (ip4_addr_eq(netif_ip4_addr(netif), &(autoip->llipaddr)))
&& (autoip->state == AUTOIP_STATE_BOUND);
}
u8_t
autoip_accept_packet(struct netif *netif, const ip4_addr_t *addr)
{
struct autoip *autoip = netif_autoip_data(netif);
return (autoip != NULL)
&& (ip4_addr_eq(addr, &(autoip->llipaddr)))
&& (autoip->state == AUTOIP_STATE_BOUND);
}
#endif /* LWIP_IPV4 && LWIP_AUTOIP */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,405 +0,0 @@
/**
* @file
* ICMP - Internet Control Message Protocol
*
*/
/*
* 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>
*
*/
/* Some ICMP messages should be passed to the transport protocols. This
is not implemented. */
#include "lwip/opt.h"
#if LWIP_IPV4 && LWIP_ICMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/icmp.h"
#include "lwip/inet_chksum.h"
#include "lwip/ip.h"
#include "lwip/def.h"
#include "lwip/stats.h"
#include <string.h>
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
/** Small optimization: set to 0 if incoming PBUF_POOL pbuf always can be
* used to modify and send a response packet (and to 1 if this is not the case,
* e.g. when link header is stripped off when receiving) */
#ifndef LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN
#define LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN 1
#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */
/* The maximum amount of data from the original packet to return in a dest-unreachable */
#define ICMP_DEST_UNREACH_DATASIZE 8
static void icmp_send_response(struct pbuf *p, u8_t type, u8_t code);
/**
* Processes ICMP input packets, called from ip_input().
*
* Currently only processes icmp echo requests and sends
* out the echo response.
*
* @param p the icmp echo request packet, p->payload pointing to the icmp header
* @param inp the netif on which this packet was received
*/
void
icmp_input(struct pbuf *p, struct netif *inp)
{
u8_t type;
#ifdef LWIP_DEBUG
u8_t code;
#endif /* LWIP_DEBUG */
struct icmp_echo_hdr *iecho;
const struct ip_hdr *iphdr_in;
u16_t hlen;
const ip4_addr_t *src;
ICMP_STATS_INC(icmp.recv);
MIB2_STATS_INC(mib2.icmpinmsgs);
iphdr_in = ip4_current_header();
hlen = IPH_HL_BYTES(iphdr_in);
if (hlen < IP_HLEN) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: short IP header (%"S16_F" bytes) received\n", hlen));
goto lenerr;
}
if (p->len < sizeof(u16_t) * 2) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: short ICMP (%"U16_F" bytes) received\n", p->tot_len));
goto lenerr;
}
type = *((u8_t *)p->payload);
#ifdef LWIP_DEBUG
code = *(((u8_t *)p->payload) + 1);
/* if debug is enabled but debug statement below is somehow disabled: */
LWIP_UNUSED_ARG(code);
#endif /* LWIP_DEBUG */
switch (type) {
case ICMP_ER:
/* This is OK, echo reply might have been parsed by a raw PCB
(as obviously, an echo request has been sent, too). */
MIB2_STATS_INC(mib2.icmpinechoreps);
break;
case ICMP_ECHO:
MIB2_STATS_INC(mib2.icmpinechos);
src = ip4_current_dest_addr();
/* multicast destination address? */
if (ip4_addr_ismulticast(ip4_current_dest_addr())) {
#if LWIP_MULTICAST_PING
/* For multicast, use address of receiving interface as source address */
src = netif_ip4_addr(inp);
#else /* LWIP_MULTICAST_PING */
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: Not echoing to multicast pings\n"));
goto icmperr;
#endif /* LWIP_MULTICAST_PING */
}
/* broadcast destination address? */
if (ip4_addr_isbroadcast(ip4_current_dest_addr(), ip_current_netif())) {
#if LWIP_BROADCAST_PING
/* For broadcast, use address of receiving interface as source address */
src = netif_ip4_addr(inp);
#else /* LWIP_BROADCAST_PING */
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: Not echoing to broadcast pings\n"));
goto icmperr;
#endif /* LWIP_BROADCAST_PING */
}
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ping\n"));
if (p->tot_len < sizeof(struct icmp_echo_hdr)) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: bad ICMP echo received\n"));
goto lenerr;
}
#if CHECKSUM_CHECK_ICMP
IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_CHECK_ICMP) {
if (inet_chksum_pbuf(p) != 0) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: checksum failed for received ICMP echo\n"));
pbuf_free(p);
ICMP_STATS_INC(icmp.chkerr);
MIB2_STATS_INC(mib2.icmpinerrors);
return;
}
}
#endif
#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN
if (pbuf_add_header(p, hlen + PBUF_LINK_HLEN + PBUF_LINK_ENCAPSULATION_HLEN)) {
/* p is not big enough to contain link headers
* allocate a new one and copy p into it
*/
struct pbuf *r;
u16_t alloc_len = (u16_t)(p->tot_len + hlen);
if (alloc_len < p->tot_len) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: allocating new pbuf failed (tot_len overflow)\n"));
goto icmperr;
}
/* allocate new packet buffer with space for link headers */
r = pbuf_alloc(PBUF_LINK, alloc_len, PBUF_RAM);
if (r == NULL) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: allocating new pbuf failed\n"));
goto icmperr;
}
if (r->len < hlen + sizeof(struct icmp_echo_hdr)) {
LWIP_DEBUGF(ICMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("first pbuf cannot hold the ICMP header"));
pbuf_free(r);
goto icmperr;
}
/* copy the ip header */
MEMCPY(r->payload, iphdr_in, hlen);
/* switch r->payload back to icmp header (cannot fail) */
if (pbuf_remove_header(r, hlen)) {
LWIP_ASSERT("icmp_input: moving r->payload to icmp header failed", 0);
pbuf_free(r);
goto icmperr;
}
/* copy the rest of the packet without ip header */
if (pbuf_copy(r, p) != ERR_OK) {
LWIP_DEBUGF(ICMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("icmp_input: copying to new pbuf failed"));
pbuf_free(r);
goto icmperr;
}
/* free the original p */
pbuf_free(p);
/* we now have an identical copy of p that has room for link headers */
p = r;
} else {
/* restore p->payload to point to icmp header (cannot fail) */
if (pbuf_remove_header(p, hlen + PBUF_LINK_HLEN + PBUF_LINK_ENCAPSULATION_HLEN)) {
LWIP_ASSERT("icmp_input: restoring original p->payload failed", 0);
goto icmperr;
}
}
#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */
/* At this point, all checks are OK. */
/* We generate an answer by switching the dest and src ip addresses,
* setting the icmp type to ECHO_RESPONSE and updating the checksum. */
iecho = (struct icmp_echo_hdr *)p->payload;
if (pbuf_add_header(p, hlen)) {
LWIP_DEBUGF(ICMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("Can't move over header in packet"));
} else {
err_t ret;
struct ip_hdr *iphdr = (struct ip_hdr *)p->payload;
ip4_addr_copy(iphdr->src, *src);
ip4_addr_copy(iphdr->dest, *ip4_current_src_addr());
ICMPH_TYPE_SET(iecho, ICMP_ER);
#if CHECKSUM_GEN_ICMP
IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_GEN_ICMP) {
/* adjust the checksum */
if (iecho->chksum > PP_HTONS(0xffffU - (ICMP_ECHO << 8))) {
iecho->chksum = (u16_t)(iecho->chksum + PP_HTONS((u16_t)(ICMP_ECHO << 8)) + 1);
} else {
iecho->chksum = (u16_t)(iecho->chksum + PP_HTONS(ICMP_ECHO << 8));
}
}
#if LWIP_CHECKSUM_CTRL_PER_NETIF
else {
iecho->chksum = 0;
}
#endif /* LWIP_CHECKSUM_CTRL_PER_NETIF */
#else /* CHECKSUM_GEN_ICMP */
iecho->chksum = 0;
#endif /* CHECKSUM_GEN_ICMP */
/* Set the correct TTL and recalculate the header checksum. */
IPH_TTL_SET(iphdr, ICMP_TTL);
IPH_CHKSUM_SET(iphdr, 0);
#if CHECKSUM_GEN_IP
IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_GEN_IP) {
IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, hlen));
}
#endif /* CHECKSUM_GEN_IP */
ICMP_STATS_INC(icmp.xmit);
/* increase number of messages attempted to send */
MIB2_STATS_INC(mib2.icmpoutmsgs);
/* increase number of echo replies attempted to send */
MIB2_STATS_INC(mib2.icmpoutechoreps);
/* send an ICMP packet */
ret = ip4_output_if(p, src, LWIP_IP_HDRINCL,
ICMP_TTL, 0, IP_PROTO_ICMP, inp);
if (ret != ERR_OK) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ip_output_if returned an error: %s\n", lwip_strerr(ret)));
}
}
break;
default:
if (type == ICMP_DUR) {
MIB2_STATS_INC(mib2.icmpindestunreachs);
} else if (type == ICMP_TE) {
MIB2_STATS_INC(mib2.icmpintimeexcds);
} else if (type == ICMP_PP) {
MIB2_STATS_INC(mib2.icmpinparmprobs);
} else if (type == ICMP_SQ) {
MIB2_STATS_INC(mib2.icmpinsrcquenchs);
} else if (type == ICMP_RD) {
MIB2_STATS_INC(mib2.icmpinredirects);
} else if (type == ICMP_TS) {
MIB2_STATS_INC(mib2.icmpintimestamps);
} else if (type == ICMP_TSR) {
MIB2_STATS_INC(mib2.icmpintimestampreps);
} else if (type == ICMP_AM) {
MIB2_STATS_INC(mib2.icmpinaddrmasks);
} else if (type == ICMP_AMR) {
MIB2_STATS_INC(mib2.icmpinaddrmaskreps);
}
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ICMP type %"S16_F" code %"S16_F" not supported.\n",
(s16_t)type, (s16_t)code));
ICMP_STATS_INC(icmp.proterr);
ICMP_STATS_INC(icmp.drop);
}
pbuf_free(p);
return;
lenerr:
pbuf_free(p);
ICMP_STATS_INC(icmp.lenerr);
MIB2_STATS_INC(mib2.icmpinerrors);
return;
#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN || !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING
icmperr:
pbuf_free(p);
ICMP_STATS_INC(icmp.err);
MIB2_STATS_INC(mib2.icmpinerrors);
return;
#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN || !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING */
}
/**
* Send an icmp 'destination unreachable' packet, called from ip_input() if
* the transport layer protocol is unknown and from udp_input() if the local
* port is not bound.
*
* @param p the input packet for which the 'unreachable' should be sent,
* p->payload pointing to the IP header
* @param t type of the 'unreachable' packet
*/
void
icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t)
{
MIB2_STATS_INC(mib2.icmpoutdestunreachs);
icmp_send_response(p, ICMP_DUR, t);
}
#if IP_FORWARD || IP_REASSEMBLY
/**
* Send a 'time exceeded' packet, called from ip_forward() if TTL is 0.
*
* @param p the input packet for which the 'time exceeded' should be sent,
* p->payload pointing to the IP header
* @param t type of the 'time exceeded' packet
*/
void
icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t)
{
MIB2_STATS_INC(mib2.icmpouttimeexcds);
icmp_send_response(p, ICMP_TE, t);
}
#endif /* IP_FORWARD || IP_REASSEMBLY */
/**
* Send an icmp packet in response to an incoming packet.
*
* @param p the input packet for which the 'unreachable' should be sent,
* p->payload pointing to the IP header
* @param type Type of the ICMP header
* @param code Code of the ICMP header
*/
static void
icmp_send_response(struct pbuf *p, u8_t type, u8_t code)
{
struct pbuf *q;
struct ip_hdr *iphdr;
struct icmp_hdr *icmphdr;
ip4_addr_t iphdr_src;
struct netif *netif;
u16_t response_pkt_len;
/* increase number of messages attempted to send */
MIB2_STATS_INC(mib2.icmpoutmsgs);
/* Keep IP header + up to 8 bytes */
response_pkt_len = IP_HLEN + ICMP_DEST_UNREACH_DATASIZE;
if (p->tot_len < response_pkt_len) response_pkt_len = p->tot_len;
/* ICMP header + part of original packet */
q = pbuf_alloc(PBUF_IP, sizeof(struct icmp_hdr) + response_pkt_len, PBUF_RAM);
if (q == NULL) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_send_response: failed to allocate pbuf for ICMP packet.\n"));
MIB2_STATS_INC(mib2.icmpouterrors);
return;
}
LWIP_ASSERT("check that first pbuf can hold icmp message",
(q->len >= (sizeof(struct icmp_hdr) + response_pkt_len)));
iphdr = (struct ip_hdr *)p->payload;
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_send_response: Sending ICMP type %02X for packet from ", type));
ip4_addr_debug_print_val(ICMP_DEBUG, iphdr->src);
LWIP_DEBUGF(ICMP_DEBUG, (" to "));
ip4_addr_debug_print_val(ICMP_DEBUG, iphdr->dest);
LWIP_DEBUGF(ICMP_DEBUG, ("\n"));
icmphdr = (struct icmp_hdr *)q->payload;
icmphdr->type = type;
icmphdr->code = code;
icmphdr->data = 0;
/* copy fields from original packet */
pbuf_copy_partial_pbuf(q, p, response_pkt_len, sizeof(struct icmp_hdr));
ip4_addr_copy(iphdr_src, iphdr->src);
#ifdef LWIP_HOOK_IP4_ROUTE_SRC
{
ip4_addr_t iphdr_dst;
ip4_addr_copy(iphdr_dst, iphdr->dest);
netif = ip4_route_src(&iphdr_dst, &iphdr_src);
}
#else
netif = ip4_route(&iphdr_src);
#endif
if (netif != NULL) {
/* calculate checksum */
icmphdr->chksum = 0;
#if CHECKSUM_GEN_ICMP
IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP) {
icmphdr->chksum = inet_chksum(icmphdr, q->len);
}
#endif
ICMP_STATS_INC(icmp.xmit);
ip4_output_if(q, NULL, &iphdr_src, ICMP_TTL, 0, IP_PROTO_ICMP, netif);
}
pbuf_free(q);
}
#endif /* LWIP_IPV4 && LWIP_ICMP */

View File

@ -1,801 +0,0 @@
/**
* @file
* IGMP - Internet Group Management Protocol
*
* @defgroup igmp IGMP
* @ingroup ip4
* To be called from TCPIP thread
*/
/*
* Copyright (c) 2002 CITEL Technologies Ltd.
* 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 CITEL Technologies Ltd 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 CITEL TECHNOLOGIES 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 CITEL TECHNOLOGIES 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 a contribution to the lwIP TCP/IP stack.
* The Swedish Institute of Computer Science and Adam Dunkels
* are specifically granted permission to redistribute this
* source code.
*/
/*-------------------------------------------------------------
Note 1)
Although the rfc requires V1 AND V2 capability
we will only support v2 since now V1 is very old (August 1989)
V1 can be added if required
a debug print and statistic have been implemented to
show this up.
-------------------------------------------------------------
-------------------------------------------------------------
Note 2)
A query for a specific group address (as opposed to ALLHOSTS)
has now been implemented as I am unsure if it is required
a debug print and statistic have been implemented to
show this up.
-------------------------------------------------------------
-------------------------------------------------------------
Note 3)
The router alert rfc 2113 is implemented in outgoing packets
but not checked rigorously incoming
-------------------------------------------------------------
Steve Reynolds
------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* RFC 988 - Host extensions for IP multicasting - V0
* RFC 1054 - Host extensions for IP multicasting -
* RFC 1112 - Host extensions for IP multicasting - V1
* RFC 2236 - Internet Group Management Protocol, Version 2 - V2 <- this code is based on this RFC (it's the "de facto" standard)
* RFC 3376 - Internet Group Management Protocol, Version 3 - V3
* RFC 4604 - Using Internet Group Management Protocol Version 3... - V3+
* RFC 2113 - IP Router Alert Option -
*----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* Includes
*----------------------------------------------------------------------------*/
#include "lwip/opt.h"
#if LWIP_IPV4 && LWIP_IGMP /* don't build if not configured for use in lwipopts.h */
#include "lwip/igmp.h"
#include "lwip/debug.h"
#include "lwip/def.h"
#include "lwip/mem.h"
#include "lwip/ip.h"
#include "lwip/inet_chksum.h"
#include "lwip/netif.h"
#include "lwip/stats.h"
#include "lwip/prot/igmp.h"
#include <string.h>
static struct igmp_group *igmp_lookup_group(struct netif *ifp, const ip4_addr_t *addr);
static err_t igmp_remove_group(struct netif *netif, struct igmp_group *group);
static void igmp_timeout(struct netif *netif, struct igmp_group *group);
static void igmp_start_timer(struct igmp_group *group, u8_t max_time);
static void igmp_delaying_member(struct igmp_group *group, u8_t maxresp);
static err_t igmp_ip_output_if(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, struct netif *netif);
static void igmp_send(struct netif *netif, struct igmp_group *group, u8_t type);
static ip4_addr_t allsystems;
static ip4_addr_t allrouters;
/**
* Initialize the IGMP module
*/
void
igmp_init(void)
{
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_init: initializing\n"));
IP4_ADDR(&allsystems, 224, 0, 0, 1);
IP4_ADDR(&allrouters, 224, 0, 0, 2);
}
/**
* Start IGMP processing on interface
*
* @param netif network interface on which start IGMP processing
*/
err_t
igmp_start(struct netif *netif)
{
struct igmp_group *group;
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_start: starting IGMP processing on if %p\n", (void *)netif));
group = igmp_lookup_group(netif, &allsystems);
if (group != NULL) {
group->group_state = IGMP_GROUP_IDLE_MEMBER;
group->use++;
/* Allow the igmp messages at the MAC level */
if (netif->igmp_mac_filter != NULL) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_start: igmp_mac_filter(ADD "));
ip4_addr_debug_print_val(IGMP_DEBUG, allsystems);
LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", (void *)netif));
netif->igmp_mac_filter(netif, &allsystems, NETIF_ADD_MAC_FILTER);
}
return ERR_OK;
}
return ERR_MEM;
}
/**
* Stop IGMP processing on interface
*
* @param netif network interface on which stop IGMP processing
*/
err_t
igmp_stop(struct netif *netif)
{
struct igmp_group *group = netif_igmp_data(netif);
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, NULL);
while (group != NULL) {
struct igmp_group *next = group->next; /* avoid use-after-free below */
/* disable the group at the MAC level */
if (netif->igmp_mac_filter != NULL) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_stop: igmp_mac_filter(DEL "));
ip4_addr_debug_print_val(IGMP_DEBUG, group->group_address);
LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", (void *)netif));
netif->igmp_mac_filter(netif, &(group->group_address), NETIF_DEL_MAC_FILTER);
}
/* free group */
memp_free(MEMP_IGMP_GROUP, group);
/* move to "next" */
group = next;
}
return ERR_OK;
}
/**
* Report IGMP memberships for this interface
*
* @param netif network interface on which report IGMP memberships
*/
void
igmp_report_groups(struct netif *netif)
{
struct igmp_group *group = netif_igmp_data(netif);
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_report_groups: sending IGMP reports on if %p\n", (void *)netif));
/* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
if (group != NULL) {
group = group->next;
}
while (group != NULL) {
igmp_delaying_member(group, IGMP_JOIN_DELAYING_MEMBER_TMR);
group = group->next;
}
}
/**
* Search for a group in the netif's igmp group list
*
* @param ifp the network interface for which to look
* @param addr the group ip address to search for
* @return a struct igmp_group* if the group has been found,
* NULL if the group wasn't found.
*/
struct igmp_group *
igmp_lookfor_group(struct netif *ifp, const ip4_addr_t *addr)
{
struct igmp_group *group = netif_igmp_data(ifp);
while (group != NULL) {
if (ip4_addr_eq(&(group->group_address), addr)) {
return group;
}
group = group->next;
}
/* to be clearer, we return NULL here instead of
* 'group' (which is also NULL at this point).
*/
return NULL;
}
/**
* Search for a specific igmp group and create a new one if not found-
*
* @param ifp the network interface for which to look
* @param addr the group ip address to search
* @return a struct igmp_group*,
* NULL on memory error.
*/
static struct igmp_group *
igmp_lookup_group(struct netif *ifp, const ip4_addr_t *addr)
{
struct igmp_group *group;
struct igmp_group *list_head = netif_igmp_data(ifp);
/* Search if the group already exists */
group = igmp_lookfor_group(ifp, addr);
if (group != NULL) {
/* Group already exists. */
return group;
}
/* Group doesn't exist yet, create a new one */
group = (struct igmp_group *)memp_malloc(MEMP_IGMP_GROUP);
if (group != NULL) {
ip4_addr_set(&(group->group_address), addr);
group->timer = 0; /* Not running */
group->group_state = IGMP_GROUP_NON_MEMBER;
group->last_reporter_flag = 0;
group->use = 0;
/* Ensure allsystems group is always first in list */
if (list_head == NULL) {
/* this is the first entry in linked list */
LWIP_ASSERT("igmp_lookup_group: first group must be allsystems",
(ip4_addr_eq(addr, &allsystems) != 0));
group->next = NULL;
netif_set_client_data(ifp, LWIP_NETIF_CLIENT_DATA_INDEX_IGMP, group);
} else {
/* append _after_ first entry */
LWIP_ASSERT("igmp_lookup_group: all except first group must not be allsystems",
(ip4_addr_eq(addr, &allsystems) == 0));
group->next = list_head->next;
list_head->next = group;
}
}
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_lookup_group: %sallocated a new group with address ", (group ? "" : "impossible to ")));
ip4_addr_debug_print(IGMP_DEBUG, addr);
LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", (void *)ifp));
return group;
}
/**
* Remove a group from netif's igmp group list, but don't free it yet
*
* @param group the group to remove from the netif's igmp group list
* @return ERR_OK if group was removed from the list, an err_t otherwise
*/
static err_t
igmp_remove_group(struct netif *netif, struct igmp_group *group)
{
err_t err = ERR_OK;
struct igmp_group *tmp_group;
/* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
for (tmp_group = netif_igmp_data(netif); tmp_group != NULL; tmp_group = tmp_group->next) {
if (tmp_group->next == group) {
tmp_group->next = group->next;
break;
}
}
/* Group not found in netif's igmp group list */
if (tmp_group == NULL) {
err = ERR_ARG;
}
return err;
}
/**
* Called from ip_input() if a new IGMP packet is received.
*
* @param p received igmp packet, p->payload pointing to the igmp header
* @param inp network interface on which the packet was received
* @param dest destination ip address of the igmp packet
*/
void
igmp_input(struct pbuf *p, struct netif *inp, const ip4_addr_t *dest)
{
struct igmp_msg *igmp;
struct igmp_group *group;
struct igmp_group *groupref;
IGMP_STATS_INC(igmp.recv);
/* Note that the length CAN be greater than 8 but only 8 are used - All are included in the checksum */
if (p->len < IGMP_MINLEN) {
pbuf_free(p);
IGMP_STATS_INC(igmp.lenerr);
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: length error\n"));
return;
}
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: message from "));
ip4_addr_debug_print_val(IGMP_DEBUG, ip4_current_header()->src);
LWIP_DEBUGF(IGMP_DEBUG, (" to address "));
ip4_addr_debug_print_val(IGMP_DEBUG, ip4_current_header()->dest);
LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", (void *)inp));
/* Now calculate and check the checksum */
igmp = (struct igmp_msg *)p->payload;
if (inet_chksum(igmp, p->len)) {
pbuf_free(p);
IGMP_STATS_INC(igmp.chkerr);
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: checksum error\n"));
return;
}
/* Packet is ok so find an existing group */
group = igmp_lookfor_group(inp, dest); /* use the destination IP address of incoming packet */
/* If group can be found or create... */
if (!group) {
pbuf_free(p);
IGMP_STATS_INC(igmp.drop);
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP frame not for us\n"));
return;
}
/* NOW ACT ON THE INCOMING MESSAGE TYPE... */
switch (igmp->igmp_msgtype) {
case IGMP_MEMB_QUERY:
/* IGMP_MEMB_QUERY to the "all systems" address ? */
if ((ip4_addr_eq(dest, &allsystems)) && ip4_addr_isany(&igmp->igmp_group_address)) {
/* THIS IS THE GENERAL QUERY */
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: General IGMP_MEMB_QUERY on \"ALL SYSTEMS\" address (224.0.0.1) [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp)));
if (igmp->igmp_maxresp == 0) {
IGMP_STATS_INC(igmp.rx_v1);
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: got an all hosts query with time== 0 - this is V1 and not implemented - treat as v2\n"));
igmp->igmp_maxresp = IGMP_V1_DELAYING_MEMBER_TMR;
} else {
IGMP_STATS_INC(igmp.rx_general);
}
groupref = netif_igmp_data(inp);
/* Do not send messages on the all systems group address! */
/* Skip the first group in the list, it is always the allsystems group added in igmp_start() */
if (groupref != NULL) {
groupref = groupref->next;
}
while (groupref) {
igmp_delaying_member(groupref, igmp->igmp_maxresp);
groupref = groupref->next;
}
} else {
/* IGMP_MEMB_QUERY to a specific group ? */
if (!ip4_addr_isany(&igmp->igmp_group_address)) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP_MEMB_QUERY to a specific group "));
ip4_addr_debug_print_val(IGMP_DEBUG, igmp->igmp_group_address);
if (ip4_addr_eq(dest, &allsystems)) {
ip4_addr_t groupaddr;
LWIP_DEBUGF(IGMP_DEBUG, (" using \"ALL SYSTEMS\" address (224.0.0.1) [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp)));
/* we first need to re-look for the group since we used dest last time */
ip4_addr_copy(groupaddr, igmp->igmp_group_address);
group = igmp_lookfor_group(inp, &groupaddr);
} else {
LWIP_DEBUGF(IGMP_DEBUG, (" with the group address as destination [igmp_maxresp=%i]\n", (int)(igmp->igmp_maxresp)));
}
if (group != NULL) {
IGMP_STATS_INC(igmp.rx_group);
igmp_delaying_member(group, igmp->igmp_maxresp);
} else {
IGMP_STATS_INC(igmp.drop);
}
} else {
IGMP_STATS_INC(igmp.proterr);
}
}
break;
case IGMP_V2_MEMB_REPORT:
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: IGMP_V2_MEMB_REPORT\n"));
IGMP_STATS_INC(igmp.rx_report);
if (group->group_state == IGMP_GROUP_DELAYING_MEMBER) {
/* This is on a specific group we have already looked up */
group->timer = 0; /* stopped */
group->group_state = IGMP_GROUP_IDLE_MEMBER;
group->last_reporter_flag = 0;
}
break;
default:
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_input: unexpected msg %d in state %d on group %p on if %p\n",
igmp->igmp_msgtype, group->group_state, (void *)&group, (void *)inp));
IGMP_STATS_INC(igmp.proterr);
break;
}
pbuf_free(p);
return;
}
/**
* @ingroup igmp
* Join a group on one network interface.
*
* @param ifaddr ip address of the network interface which should join a new group
* @param groupaddr the ip address of the group which to join
* @return ERR_OK if group was joined on the netif(s), an err_t otherwise
*/
err_t
igmp_joingroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr)
{
err_t err = ERR_VAL; /* no matching interface */
struct netif *netif;
LWIP_ASSERT_CORE_LOCKED();
/* make sure it is multicast address */
LWIP_ERROR("igmp_joingroup: attempt to join non-multicast address", ip4_addr_ismulticast(groupaddr), return ERR_VAL;);
LWIP_ERROR("igmp_joingroup: attempt to join allsystems address", (!ip4_addr_eq(groupaddr, &allsystems)), return ERR_VAL;);
/* loop through netif's */
NETIF_FOREACH(netif) {
/* Should we join this interface ? */
if ((netif->flags & NETIF_FLAG_IGMP) && ((ip4_addr_isany(ifaddr) || ip4_addr_eq(netif_ip4_addr(netif), ifaddr)))) {
err = igmp_joingroup_netif(netif, groupaddr);
if (err != ERR_OK) {
/* Return an error even if some network interfaces are joined */
/** @todo undo any other netif already joined */
return err;
}
}
}
return err;
}
/**
* @ingroup igmp
* Join a group on one network interface.
*
* @param netif the network interface which should join a new group
* @param groupaddr the ip address of the group which to join
* @return ERR_OK if group was joined on the netif, an err_t otherwise
*/
err_t
igmp_joingroup_netif(struct netif *netif, const ip4_addr_t *groupaddr)
{
struct igmp_group *group;
LWIP_ASSERT_CORE_LOCKED();
/* make sure it is multicast address */
LWIP_ERROR("igmp_joingroup_netif: attempt to join non-multicast address", ip4_addr_ismulticast(groupaddr), return ERR_VAL;);
LWIP_ERROR("igmp_joingroup_netif: attempt to join allsystems address", (!ip4_addr_eq(groupaddr, &allsystems)), return ERR_VAL;);
/* make sure it is an igmp-enabled netif */
LWIP_ERROR("igmp_joingroup_netif: attempt to join on non-IGMP netif", netif->flags & NETIF_FLAG_IGMP, return ERR_VAL;);
/* find group or create a new one if not found */
group = igmp_lookup_group(netif, groupaddr);
if (group != NULL) {
/* This should create a new group, check the state to make sure */
if (group->group_state != IGMP_GROUP_NON_MEMBER) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup_netif: join to group not in state IGMP_GROUP_NON_MEMBER\n"));
} else {
/* OK - it was new group */
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup_netif: join to new group: "));
ip4_addr_debug_print(IGMP_DEBUG, groupaddr);
LWIP_DEBUGF(IGMP_DEBUG, ("\n"));
/* If first use of the group, allow the group at the MAC level */
if ((group->use == 0) && (netif->igmp_mac_filter != NULL)) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup_netif: igmp_mac_filter(ADD "));
ip4_addr_debug_print(IGMP_DEBUG, groupaddr);
LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", (void *)netif));
netif->igmp_mac_filter(netif, groupaddr, NETIF_ADD_MAC_FILTER);
}
IGMP_STATS_INC(igmp.tx_join);
igmp_send(netif, group, IGMP_V2_MEMB_REPORT);
igmp_start_timer(group, IGMP_JOIN_DELAYING_MEMBER_TMR);
/* Need to work out where this timer comes from */
group->group_state = IGMP_GROUP_DELAYING_MEMBER;
}
/* Increment group use */
group->use++;
/* Join on this interface */
return ERR_OK;
} else {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_joingroup_netif: Not enough memory to join to group\n"));
return ERR_MEM;
}
}
/**
* @ingroup igmp
* Leave a group on one network interface.
*
* @param ifaddr ip address of the network interface which should leave a group
* @param groupaddr the ip address of the group which to leave
* @return ERR_OK if group was left on the netif(s), an err_t otherwise
*/
err_t
igmp_leavegroup(const ip4_addr_t *ifaddr, const ip4_addr_t *groupaddr)
{
err_t err = ERR_VAL; /* no matching interface */
struct netif *netif;
LWIP_ASSERT_CORE_LOCKED();
/* make sure it is multicast address */
LWIP_ERROR("igmp_leavegroup: attempt to leave non-multicast address", ip4_addr_ismulticast(groupaddr), return ERR_VAL;);
LWIP_ERROR("igmp_leavegroup: attempt to leave allsystems address", (!ip4_addr_eq(groupaddr, &allsystems)), return ERR_VAL;);
/* loop through netif's */
NETIF_FOREACH(netif) {
/* Should we leave this interface ? */
if ((netif->flags & NETIF_FLAG_IGMP) && ((ip4_addr_isany(ifaddr) || ip4_addr_eq(netif_ip4_addr(netif), ifaddr)))) {
err_t res = igmp_leavegroup_netif(netif, groupaddr);
if (err != ERR_OK) {
/* Store this result if we have not yet gotten a success */
err = res;
}
}
}
return err;
}
/**
* @ingroup igmp
* Leave a group on one network interface.
*
* @param netif the network interface which should leave a group
* @param groupaddr the ip address of the group which to leave
* @return ERR_OK if group was left on the netif, an err_t otherwise
*/
err_t
igmp_leavegroup_netif(struct netif *netif, const ip4_addr_t *groupaddr)
{
struct igmp_group *group;
LWIP_ASSERT_CORE_LOCKED();
/* make sure it is multicast address */
LWIP_ERROR("igmp_leavegroup_netif: attempt to leave non-multicast address", ip4_addr_ismulticast(groupaddr), return ERR_VAL;);
LWIP_ERROR("igmp_leavegroup_netif: attempt to leave allsystems address", (!ip4_addr_eq(groupaddr, &allsystems)), return ERR_VAL;);
/* make sure it is an igmp-enabled netif */
LWIP_ERROR("igmp_leavegroup_netif: attempt to leave on non-IGMP netif", netif->flags & NETIF_FLAG_IGMP, return ERR_VAL;);
/* find group */
group = igmp_lookfor_group(netif, groupaddr);
if (group != NULL) {
/* Only send a leave if the flag is set according to the state diagram */
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup_netif: Leaving group: "));
ip4_addr_debug_print(IGMP_DEBUG, groupaddr);
LWIP_DEBUGF(IGMP_DEBUG, ("\n"));
/* If there is no other use of the group */
if (group->use <= 1) {
/* Remove the group from the list */
igmp_remove_group(netif, group);
/* If we are the last reporter for this group */
if (group->last_reporter_flag) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup_netif: sending leaving group\n"));
IGMP_STATS_INC(igmp.tx_leave);
igmp_send(netif, group, IGMP_LEAVE_GROUP);
}
/* Disable the group at the MAC level */
if (netif->igmp_mac_filter != NULL) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup_netif: igmp_mac_filter(DEL "));
ip4_addr_debug_print(IGMP_DEBUG, groupaddr);
LWIP_DEBUGF(IGMP_DEBUG, (") on if %p\n", (void *)netif));
netif->igmp_mac_filter(netif, groupaddr, NETIF_DEL_MAC_FILTER);
}
/* Free group struct */
memp_free(MEMP_IGMP_GROUP, group);
} else {
/* Decrement group use */
group->use--;
}
return ERR_OK;
} else {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_leavegroup_netif: not member of group\n"));
return ERR_VAL;
}
}
/**
* The igmp timer function (both for NO_SYS=1 and =0)
* Should be called every IGMP_TMR_INTERVAL milliseconds (100 ms is default).
*/
void
igmp_tmr(void)
{
struct netif *netif;
NETIF_FOREACH(netif) {
struct igmp_group *group = netif_igmp_data(netif);
while (group != NULL) {
if (group->timer > 0) {
group->timer--;
if (group->timer == 0) {
igmp_timeout(netif, group);
}
}
group = group->next;
}
}
}
/**
* Called if a timeout for one group is reached.
* Sends a report for this group.
*
* @param group an igmp_group for which a timeout is reached
*/
static void
igmp_timeout(struct netif *netif, struct igmp_group *group)
{
/* If the state is IGMP_GROUP_DELAYING_MEMBER then we send a report for this group
(unless it is the allsystems group) */
if ((group->group_state == IGMP_GROUP_DELAYING_MEMBER) &&
(!(ip4_addr_eq(&(group->group_address), &allsystems)))) {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_timeout: report membership for group with address "));
ip4_addr_debug_print_val(IGMP_DEBUG, group->group_address);
LWIP_DEBUGF(IGMP_DEBUG, (" on if %p\n", (void *)netif));
group->group_state = IGMP_GROUP_IDLE_MEMBER;
IGMP_STATS_INC(igmp.tx_report);
igmp_send(netif, group, IGMP_V2_MEMB_REPORT);
}
}
/**
* Start a timer for an igmp group
*
* @param group the igmp_group for which to start a timer
* @param max_time the time in multiples of IGMP_TMR_INTERVAL (decrease with
* every call to igmp_tmr())
*/
static void
igmp_start_timer(struct igmp_group *group, u8_t max_time)
{
#ifdef LWIP_RAND
group->timer = (u16_t)(max_time > 2 ? (LWIP_RAND() % max_time) : 1);
#else /* LWIP_RAND */
/* ATTENTION: use this only if absolutely necessary! */
group->timer = max_time / 2;
#endif /* LWIP_RAND */
if (group->timer == 0) {
group->timer = 1;
}
}
/**
* Delaying membership report for a group if necessary
*
* @param group the igmp_group for which "delaying" membership report
* @param maxresp query delay
*/
static void
igmp_delaying_member(struct igmp_group *group, u8_t maxresp)
{
if ((group->group_state == IGMP_GROUP_IDLE_MEMBER) ||
((group->group_state == IGMP_GROUP_DELAYING_MEMBER) &&
((group->timer == 0) || (maxresp < group->timer)))) {
igmp_start_timer(group, maxresp);
group->group_state = IGMP_GROUP_DELAYING_MEMBER;
}
}
/**
* Sends an IP packet on a network interface. This function constructs the IP header
* and calculates the IP header checksum. If the source IP address is NULL,
* the IP address of the outgoing network interface is filled in as source address.
*
* @param p the packet to send (p->payload points to the data, e.g. next
protocol header; if dest == LWIP_IP_HDRINCL, p already includes an
IP header and p->payload points to that IP header)
* @param src the source IP address to send from (if src == IP4_ADDR_ANY, the
* IP address of the netif used to send is used as source address)
* @param dest the destination IP address to send the packet to
* @param netif the netif on which to send this packet
* @return ERR_OK if the packet was sent OK
* ERR_BUF if p doesn't have enough space for IP/LINK headers
* returns errors returned by netif->output
*/
static err_t
igmp_ip_output_if(struct pbuf *p, const ip4_addr_t *src, const ip4_addr_t *dest, struct netif *netif)
{
/* This is the "router alert" option */
u16_t ra[2];
ra[0] = PP_HTONS(ROUTER_ALERT);
ra[1] = 0x0000; /* Router shall examine packet */
IGMP_STATS_INC(igmp.xmit);
return ip4_output_if_opt(p, src, dest, IGMP_TTL, 0, IP_PROTO_IGMP, netif, ra, ROUTER_ALERTLEN);
}
/**
* Send an igmp packet to a specific group.
*
* @param group the group to which to send the packet
* @param type the type of igmp packet to send
*/
static void
igmp_send(struct netif *netif, struct igmp_group *group, u8_t type)
{
struct pbuf *p = NULL;
struct igmp_msg *igmp = NULL;
ip4_addr_t src = *IP4_ADDR_ANY4;
ip4_addr_t *dest = NULL;
/* IP header + "router alert" option + IGMP header */
p = pbuf_alloc(PBUF_TRANSPORT, IGMP_MINLEN, PBUF_RAM);
if (p) {
igmp = (struct igmp_msg *)p->payload;
LWIP_ASSERT("igmp_send: check that first pbuf can hold struct igmp_msg",
(p->len >= sizeof(struct igmp_msg)));
ip4_addr_copy(src, *netif_ip4_addr(netif));
if (type == IGMP_V2_MEMB_REPORT) {
dest = &(group->group_address);
ip4_addr_copy(igmp->igmp_group_address, group->group_address);
group->last_reporter_flag = 1; /* Remember we were the last to report */
} else {
if (type == IGMP_LEAVE_GROUP) {
dest = &allrouters;
ip4_addr_copy(igmp->igmp_group_address, group->group_address);
}
}
if ((type == IGMP_V2_MEMB_REPORT) || (type == IGMP_LEAVE_GROUP)) {
igmp->igmp_msgtype = type;
igmp->igmp_maxresp = 0;
igmp->igmp_checksum = 0;
igmp->igmp_checksum = inet_chksum(igmp, IGMP_MINLEN);
igmp_ip_output_if(p, &src, dest, netif);
}
pbuf_free(p);
} else {
LWIP_DEBUGF(IGMP_DEBUG, ("igmp_send: not enough memory for igmp_send\n"));
IGMP_STATS_INC(igmp.memerr);
}
}
#endif /* LWIP_IPV4 && LWIP_IGMP */

File diff suppressed because it is too large Load Diff

View File

@ -1,323 +0,0 @@
/**
* @file
* This is the IPv4 address tools implementation.
*
*/
/*
* 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_IPV4
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
/* used by IP4_ADDR_ANY and IP_ADDR_BROADCAST in ip_addr.h */
const ip_addr_t ip_addr_any = IPADDR4_INIT(IPADDR_ANY);
const ip_addr_t ip_addr_broadcast = IPADDR4_INIT(IPADDR_BROADCAST);
/**
* Determine if an address is a broadcast address on a network interface
*
* @param addr address to be checked
* @param netif the network interface against which the address is checked
* @return returns non-zero if the address is a broadcast address
*/
u8_t
ip4_addr_isbroadcast_u32(u32_t addr, const struct netif *netif)
{
ip4_addr_t ipaddr;
ip4_addr_set_u32(&ipaddr, addr);
/* all ones (broadcast) or all zeroes (old skool broadcast) */
if ((~addr == IPADDR_ANY) ||
(addr == IPADDR_ANY)) {
return 1;
/* no broadcast support on this network interface? */
} else if ((netif->flags & NETIF_FLAG_BROADCAST) == 0) {
/* the given address cannot be a broadcast address
* nor can we check against any broadcast addresses */
return 0;
/* address matches network interface address exactly? => no broadcast */
} else if (addr == ip4_addr_get_u32(netif_ip4_addr(netif))) {
return 0;
/* on the same (sub) network... */
} else if (ip4_addr_net_eq(&ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif))
/* ...and host identifier bits are all ones? =>... */
&& ((addr & ~ip4_addr_get_u32(netif_ip4_netmask(netif))) ==
(IPADDR_BROADCAST & ~ip4_addr_get_u32(netif_ip4_netmask(netif))))) {
/* => network broadcast address */
return 1;
} else {
return 0;
}
}
/** Checks if a netmask is valid (starting with ones, then only zeros)
*
* @param netmask the IPv4 netmask to check (in network byte order!)
* @return 1 if the netmask is valid, 0 if it is not
*/
u8_t
ip4_addr_netmask_valid(u32_t netmask)
{
u32_t mask;
u32_t nm_hostorder = lwip_htonl(netmask);
/* first, check for the first zero */
for (mask = 1UL << 31 ; mask != 0; mask >>= 1) {
if ((nm_hostorder & mask) == 0) {
break;
}
}
/* then check that there is no one */
for (; mask != 0; mask >>= 1) {
if ((nm_hostorder & mask) != 0) {
/* there is a one after the first zero -> invalid */
return 0;
}
}
/* no one after the first zero -> valid */
return 1;
}
/**
* Ascii internet address interpretation routine.
* The value returned is in network order.
*
* @param cp IP address in ascii representation (e.g. "127.0.0.1")
* @return ip address in network order
*/
u32_t
ipaddr_addr(const char *cp)
{
ip4_addr_t val;
if (ip4addr_aton(cp, &val)) {
return ip4_addr_get_u32(&val);
}
return (IPADDR_NONE);
}
/**
* Check whether "cp" is a valid ascii representation
* of an Internet address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
* This replaces inet_addr, the return value from which
* cannot distinguish between failure and a local broadcast address.
*
* @param cp IP address in ascii representation (e.g. "127.0.0.1")
* @param addr pointer to which to save the ip address in network order
* @return 1 if cp could be converted to addr, 0 on failure
*/
int
ip4addr_aton(const char *cp, ip4_addr_t *addr)
{
u32_t val;
u8_t base;
char c;
u32_t parts[4];
u32_t *pp = parts;
c = *cp;
for (;;) {
/*
* Collect number up to ``.''.
* Values are specified as for C:
* 0x=hex, 0=octal, 1-9=decimal.
*/
if (!lwip_isdigit(c)) {
return 0;
}
val = 0;
base = 10;
if (c == '0') {
c = *++cp;
if (c == 'x' || c == 'X') {
base = 16;
c = *++cp;
} else {
base = 8;
}
}
for (;;) {
if (lwip_isdigit(c)) {
if((base == 8) && ((u32_t)(c - '0') >= 8))
break;
val = (val * base) + (u32_t)(c - '0');
c = *++cp;
} else if (base == 16 && lwip_isxdigit(c)) {
val = (val << 4) | (u32_t)(c + 10 - (lwip_islower(c) ? 'a' : 'A'));
c = *++cp;
} else {
break;
}
}
if (c == '.') {
/*
* Internet format:
* a.b.c.d
* a.b.c (with c treated as 16 bits)
* a.b (with b treated as 24 bits)
*/
if (pp >= parts + 3) {
return 0;
}
*pp++ = val;
c = *++cp;
} else {
break;
}
}
/*
* Check for trailing characters.
*/
if (c != '\0' && !lwip_isspace(c)) {
return 0;
}
/*
* Concoct the address according to
* the number of parts specified.
*/
switch (pp - parts + 1) {
case 0:
return 0; /* initial nondigit */
case 1: /* a -- 32 bits */
break;
case 2: /* a.b -- 8.24 bits */
if (val > 0xffffffUL) {
return 0;
}
if (parts[0] > 0xff) {
return 0;
}
val |= parts[0] << 24;
break;
case 3: /* a.b.c -- 8.8.16 bits */
if (val > 0xffff) {
return 0;
}
if ((parts[0] > 0xff) || (parts[1] > 0xff)) {
return 0;
}
val |= (parts[0] << 24) | (parts[1] << 16);
break;
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if (val > 0xff) {
return 0;
}
if ((parts[0] > 0xff) || (parts[1] > 0xff) || (parts[2] > 0xff)) {
return 0;
}
val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
break;
default:
LWIP_ASSERT("unhandled", 0);
break;
}
if (addr) {
ip4_addr_set_u32(addr, lwip_htonl(val));
}
return 1;
}
/**
* Convert numeric IP address into decimal dotted ASCII representation.
* returns ptr to static buffer; not reentrant!
*
* @param addr ip address in network order to convert
* @return pointer to a global static (!) buffer that holds the ASCII
* representation of addr
*/
char *
ip4addr_ntoa(const ip4_addr_t *addr)
{
static char str[IP4ADDR_STRLEN_MAX];
return ip4addr_ntoa_r(addr, str, IP4ADDR_STRLEN_MAX);
}
/**
* Same as ip4addr_ntoa, but reentrant since a user-supplied buffer is used.
*
* @param addr ip address in network order to convert
* @param buf target buffer where the string is stored
* @param buflen length of buf
* @return either pointer to buf which now holds the ASCII
* representation of addr or NULL if buf was too small
*/
char *
ip4addr_ntoa_r(const ip4_addr_t *addr, char *buf, int buflen)
{
u32_t s_addr;
char inv[3];
char *rp;
u8_t *ap;
u8_t rem;
u8_t n;
u8_t i;
int len = 0;
s_addr = ip4_addr_get_u32(addr);
rp = buf;
ap = (u8_t *)&s_addr;
for (n = 0; n < 4; n++) {
i = 0;
do {
rem = *ap % (u8_t)10;
*ap /= (u8_t)10;
inv[i++] = (char)('0' + rem);
} while (*ap);
while (i--) {
if (len++ >= buflen) {
return NULL;
}
*rp++ = inv[i];
}
if (len++ >= buflen) {
return NULL;
}
*rp++ = '.';
ap++;
}
*--rp = 0;
return buf;
}
#endif /* LWIP_IPV4 */

View File

@ -1,894 +0,0 @@
/**
* @file
* This is the IPv4 packet segmentation and reassembly implementation.
*
*/
/*
* 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: Jani Monoses <jani@iv.ro>
* Simon Goldschmidt
* original reassembly code by Adam Dunkels <adam@sics.se>
*
*/
#include "lwip/opt.h"
#if LWIP_IPV4
#include "lwip/ip4_frag.h"
#include "lwip/def.h"
#include "lwip/inet_chksum.h"
#include "lwip/netif.h"
#include "lwip/stats.h"
#include "lwip/icmp.h"
#include <string.h>
#if IP_REASSEMBLY
/**
* The IP reassembly code currently has the following limitations:
* - IP header options are not supported
* - fragments must not overlap (e.g. due to different routes),
* currently, overlapping or duplicate fragments are thrown away
* if IP_REASS_CHECK_OVERLAP=1 (the default)!
*
* @todo: work with IP header options
*/
/** Setting this to 0, you can turn off checking the fragments for overlapping
* regions. The code gets a little smaller. Only use this if you know that
* overlapping won't occur on your network! */
#ifndef IP_REASS_CHECK_OVERLAP
#define IP_REASS_CHECK_OVERLAP 1
#endif /* IP_REASS_CHECK_OVERLAP */
/** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
* full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
* Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
* is set to 1, so one datagram can be reassembled at a time, only. */
#ifndef IP_REASS_FREE_OLDEST
#define IP_REASS_FREE_OLDEST 1
#endif /* IP_REASS_FREE_OLDEST */
#define IP_REASS_FLAG_LASTFRAG 0x01
#define IP_REASS_VALIDATE_TELEGRAM_FINISHED 1
#define IP_REASS_VALIDATE_PBUF_QUEUED 0
#define IP_REASS_VALIDATE_PBUF_DROPPED -1
/** This is a helper struct which holds the starting
* offset and the ending offset of this fragment to
* easily chain the fragments.
* It has the same packing requirements as the IP header, since it replaces
* the IP header in memory in incoming fragments (after copying it) to keep
* track of the various fragments. (-> If the IP header doesn't need packing,
* this struct doesn't need packing, too.)
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct ip_reass_helper {
PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
PACK_STRUCT_FIELD(u16_t start);
PACK_STRUCT_FIELD(u16_t end);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define IP_ADDRESSES_AND_ID_MATCH(iphdrA, iphdrB) \
(ip4_addr_eq(&(iphdrA)->src, &(iphdrB)->src) && \
ip4_addr_eq(&(iphdrA)->dest, &(iphdrB)->dest) && \
IPH_ID(iphdrA) == IPH_ID(iphdrB)) ? 1 : 0
/* global variables */
static struct ip_reassdata *reassdatagrams;
static u16_t ip_reass_pbufcount;
/* function prototypes */
static void ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
static int ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev);
/**
* Reassembly timer base function
* for both NO_SYS == 0 and 1 (!).
*
* Should be called every 1000 msec (defined by IP_TMR_INTERVAL).
*/
void
ip_reass_tmr(void)
{
struct ip_reassdata *r, *prev = NULL;
r = reassdatagrams;
while (r != NULL) {
/* Decrement the timer. Once it reaches 0,
* clean up the incomplete fragment assembly */
if (r->timer > 0) {
r->timer--;
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer dec %"U16_F"\n", (u16_t)r->timer));
prev = r;
r = r->next;
} else {
/* reassembly timed out */
struct ip_reassdata *tmp;
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_tmr: timer timed out\n"));
tmp = r;
/* get the next pointer before freeing */
r = r->next;
/* free the helper struct and all enqueued pbufs */
ip_reass_free_complete_datagram(tmp, prev);
}
}
}
/**
* Free a datagram (struct ip_reassdata) and all its pbufs.
* Updates the total count of enqueued pbufs (ip_reass_pbufcount),
* SNMP counters and sends an ICMP time exceeded packet.
*
* @param ipr datagram to free
* @param prev the previous datagram in the linked list
* @return the number of pbufs freed
*/
static int
ip_reass_free_complete_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
{
u16_t pbufs_freed = 0;
u16_t clen;
struct pbuf *p;
struct ip_reass_helper *iprh;
LWIP_ASSERT("prev != ipr", prev != ipr);
if (prev != NULL) {
LWIP_ASSERT("prev->next == ipr", prev->next == ipr);
}
MIB2_STATS_INC(mib2.ipreasmfails);
#if LWIP_ICMP
iprh = (struct ip_reass_helper *)ipr->p->payload;
if (iprh->start == 0) {
/* The first fragment was received, send ICMP time exceeded. */
/* First, de-queue the first pbuf from r->p. */
p = ipr->p;
ipr->p = iprh->next_pbuf;
/* Then, copy the original header into it. */
SMEMCPY(p->payload, &ipr->iphdr, IP_HLEN);
icmp_time_exceeded(p, ICMP_TE_FRAG);
clen = pbuf_clen(p);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed = (u16_t)(pbufs_freed + clen);
pbuf_free(p);
}
#endif /* LWIP_ICMP */
/* First, free all received pbufs. The individual pbufs need to be released
separately as they have not yet been chained */
p = ipr->p;
while (p != NULL) {
struct pbuf *pcur;
iprh = (struct ip_reass_helper *)p->payload;
pcur = p;
/* get the next pointer before freeing */
p = iprh->next_pbuf;
clen = pbuf_clen(pcur);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed = (u16_t)(pbufs_freed + clen);
pbuf_free(pcur);
}
/* Then, unchain the struct ip_reassdata from the list and free it. */
ip_reass_dequeue_datagram(ipr, prev);
LWIP_ASSERT("ip_reass_pbufcount >= pbufs_freed", ip_reass_pbufcount >= pbufs_freed);
ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount - pbufs_freed);
return pbufs_freed;
}
#if IP_REASS_FREE_OLDEST
/**
* Free the oldest datagram to make room for enqueueing new fragments.
* The datagram 'fraghdr' belongs to is not freed!
*
* @param fraghdr IP header of the current fragment
* @param pbufs_needed number of pbufs needed to enqueue
* (used for freeing other datagrams if not enough space)
* @return the number of pbufs freed
*/
static int
ip_reass_remove_oldest_datagram(struct ip_hdr *fraghdr, int pbufs_needed)
{
/* @todo Can't we simply remove the last datagram in the
* linked list behind reassdatagrams?
*/
struct ip_reassdata *r, *oldest, *prev, *oldest_prev;
int pbufs_freed = 0, pbufs_freed_current;
int other_datagrams;
/* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
* but don't free the datagram that 'fraghdr' belongs to! */
do {
oldest = NULL;
prev = NULL;
oldest_prev = NULL;
other_datagrams = 0;
r = reassdatagrams;
while (r != NULL) {
if (!IP_ADDRESSES_AND_ID_MATCH(&r->iphdr, fraghdr)) {
/* Not the same datagram as fraghdr */
other_datagrams++;
if (oldest == NULL) {
oldest = r;
oldest_prev = prev;
} else if (r->timer <= oldest->timer) {
/* older than the previous oldest */
oldest = r;
oldest_prev = prev;
}
}
if (r->next != NULL) {
prev = r;
}
r = r->next;
}
if (oldest != NULL) {
pbufs_freed_current = ip_reass_free_complete_datagram(oldest, oldest_prev);
pbufs_freed += pbufs_freed_current;
}
} while ((pbufs_freed < pbufs_needed) && (other_datagrams > 1));
return pbufs_freed;
}
#endif /* IP_REASS_FREE_OLDEST */
/**
* Enqueues a new fragment into the fragment queue
* @param fraghdr points to the new fragments IP hdr
* @param clen number of pbufs needed to enqueue (used for freeing other datagrams if not enough space)
* @return A pointer to the queue location into which the fragment was enqueued
*/
static struct ip_reassdata *
ip_reass_enqueue_new_datagram(struct ip_hdr *fraghdr, int clen)
{
struct ip_reassdata *ipr;
#if ! IP_REASS_FREE_OLDEST
LWIP_UNUSED_ARG(clen);
#endif
/* No matching previous fragment found, allocate a new reassdata struct */
ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
if (ipr == NULL) {
#if IP_REASS_FREE_OLDEST
if (ip_reass_remove_oldest_datagram(fraghdr, clen) >= clen) {
ipr = (struct ip_reassdata *)memp_malloc(MEMP_REASSDATA);
}
if (ipr == NULL)
#endif /* IP_REASS_FREE_OLDEST */
{
IPFRAG_STATS_INC(ip_frag.memerr);
LWIP_DEBUGF(IP_REASS_DEBUG, ("Failed to alloc reassdata struct\n"));
return NULL;
}
}
memset(ipr, 0, sizeof(struct ip_reassdata));
ipr->timer = IP_REASS_MAXAGE;
/* enqueue the new structure to the front of the list */
ipr->next = reassdatagrams;
reassdatagrams = ipr;
/* copy the ip header for later tests and input */
/* @todo: no ip options supported? */
SMEMCPY(&(ipr->iphdr), fraghdr, IP_HLEN);
return ipr;
}
/**
* Dequeues a datagram from the datagram queue. Doesn't deallocate the pbufs.
* @param ipr points to the queue entry to dequeue
*/
static void
ip_reass_dequeue_datagram(struct ip_reassdata *ipr, struct ip_reassdata *prev)
{
/* dequeue the reass struct */
if (reassdatagrams == ipr) {
/* it was the first in the list */
reassdatagrams = ipr->next;
} else {
/* it wasn't the first, so it must have a valid 'prev' */
LWIP_ASSERT("sanity check linked list", prev != NULL);
prev->next = ipr->next;
}
/* now we can free the ip_reassdata struct */
memp_free(MEMP_REASSDATA, ipr);
}
/**
* Chain a new pbuf into the pbuf list that composes the datagram. The pbuf list
* will grow over time as new pbufs are rx.
* Also checks that the datagram passes basic continuity checks (if the last
* fragment was received at least once).
* @param ipr points to the reassembly state
* @param new_p points to the pbuf for the current fragment
* @param is_last is 1 if this pbuf has MF==0 (ipr->flags not updated yet)
* @return see IP_REASS_VALIDATE_* defines
*/
static int
ip_reass_chain_frag_into_datagram_and_validate(struct ip_reassdata *ipr, struct pbuf *new_p, int is_last)
{
struct ip_reass_helper *iprh, *iprh_tmp, *iprh_prev = NULL;
struct pbuf *q;
u16_t offset, len;
u8_t hlen;
struct ip_hdr *fraghdr;
int valid = 1;
/* Extract length and fragment offset from current fragment */
fraghdr = (struct ip_hdr *)new_p->payload;
len = lwip_ntohs(IPH_LEN(fraghdr));
hlen = IPH_HL_BYTES(fraghdr);
if (hlen > len) {
/* invalid datagram */
return IP_REASS_VALIDATE_PBUF_DROPPED;
}
len = (u16_t)(len - hlen);
offset = IPH_OFFSET_BYTES(fraghdr);
/* overwrite the fragment's ip header from the pbuf with our helper struct,
* and setup the embedded helper structure. */
/* make sure the struct ip_reass_helper fits into the IP header */
LWIP_ASSERT("sizeof(struct ip_reass_helper) <= IP_HLEN",
sizeof(struct ip_reass_helper) <= IP_HLEN);
iprh = (struct ip_reass_helper *)new_p->payload;
iprh->next_pbuf = NULL;
iprh->start = offset;
iprh->end = (u16_t)(offset + len);
if (iprh->end < offset) {
/* u16_t overflow, cannot handle this */
return IP_REASS_VALIDATE_PBUF_DROPPED;
}
/* Iterate through until we either get to the end of the list (append),
* or we find one with a larger offset (insert). */
for (q = ipr->p; q != NULL;) {
iprh_tmp = (struct ip_reass_helper *)q->payload;
if (iprh->start < iprh_tmp->start) {
/* the new pbuf should be inserted before this */
iprh->next_pbuf = q;
if (iprh_prev != NULL) {
/* not the fragment with the lowest offset */
#if IP_REASS_CHECK_OVERLAP
if ((iprh->start < iprh_prev->end) || (iprh->end > iprh_tmp->start)) {
/* fragment overlaps with previous or following, throw away */
return IP_REASS_VALIDATE_PBUF_DROPPED;
}
#endif /* IP_REASS_CHECK_OVERLAP */
iprh_prev->next_pbuf = new_p;
if (iprh_prev->end != iprh->start) {
/* There is a fragment missing between the current
* and the previous fragment */
valid = 0;
}
} else {
#if IP_REASS_CHECK_OVERLAP
if (iprh->end > iprh_tmp->start) {
/* fragment overlaps with following, throw away */
return IP_REASS_VALIDATE_PBUF_DROPPED;
}
#endif /* IP_REASS_CHECK_OVERLAP */
/* fragment with the lowest offset */
ipr->p = new_p;
}
break;
} else if (iprh->start == iprh_tmp->start) {
/* received the same datagram twice: no need to keep the datagram */
return IP_REASS_VALIDATE_PBUF_DROPPED;
#if IP_REASS_CHECK_OVERLAP
} else if (iprh->start < iprh_tmp->end) {
/* overlap: no need to keep the new datagram */
return IP_REASS_VALIDATE_PBUF_DROPPED;
#endif /* IP_REASS_CHECK_OVERLAP */
} else {
/* Check if the fragments received so far have no holes. */
if (iprh_prev != NULL) {
if (iprh_prev->end != iprh_tmp->start) {
/* There is a fragment missing between the current
* and the previous fragment */
valid = 0;
}
}
}
q = iprh_tmp->next_pbuf;
iprh_prev = iprh_tmp;
}
/* If q is NULL, then we made it to the end of the list. Determine what to do now */
if (q == NULL) {
if (iprh_prev != NULL) {
/* this is (for now), the fragment with the highest offset:
* chain it to the last fragment */
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= iprh->start);
#endif /* IP_REASS_CHECK_OVERLAP */
iprh_prev->next_pbuf = new_p;
if (iprh_prev->end != iprh->start) {
valid = 0;
}
} else {
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("no previous fragment, this must be the first fragment!",
ipr->p == NULL);
#endif /* IP_REASS_CHECK_OVERLAP */
/* this is the first fragment we ever received for this ip datagram */
ipr->p = new_p;
}
}
/* At this point, the validation part begins: */
/* If we already received the last fragment */
if (is_last || ((ipr->flags & IP_REASS_FLAG_LASTFRAG) != 0)) {
/* and had no holes so far */
if (valid) {
/* then check if the rest of the fragments is here */
/* Check if the queue starts with the first datagram */
if ((ipr->p == NULL) || (((struct ip_reass_helper *)ipr->p->payload)->start != 0)) {
valid = 0;
} else {
/* and check that there are no holes after this datagram */
iprh_prev = iprh;
q = iprh->next_pbuf;
while (q != NULL) {
iprh = (struct ip_reass_helper *)q->payload;
if (iprh_prev->end != iprh->start) {
valid = 0;
break;
}
iprh_prev = iprh;
q = iprh->next_pbuf;
}
/* if still valid, all fragments are received
* (because to the MF==0 already arrived */
if (valid) {
LWIP_ASSERT("sanity check", ipr->p != NULL);
LWIP_ASSERT("sanity check",
((struct ip_reass_helper *)ipr->p->payload) != iprh);
LWIP_ASSERT("validate_datagram:next_pbuf!=NULL",
iprh->next_pbuf == NULL);
}
}
}
/* If valid is 0 here, there are some fragments missing in the middle
* (since MF == 0 has already arrived). Such datagrams simply time out if
* no more fragments are received... */
return valid ? IP_REASS_VALIDATE_TELEGRAM_FINISHED : IP_REASS_VALIDATE_PBUF_QUEUED;
}
/* If we come here, not all fragments were received, yet! */
return IP_REASS_VALIDATE_PBUF_QUEUED; /* not yet valid! */
}
/**
* Reassembles incoming IP fragments into an IP datagram.
*
* @param p points to a pbuf chain of the fragment
* @return NULL if reassembly is incomplete, ? otherwise
*/
struct pbuf *
ip4_reass(struct pbuf *p)
{
struct pbuf *r;
struct ip_hdr *fraghdr;
struct ip_reassdata *ipr;
struct ip_reass_helper *iprh;
u16_t offset, len, clen;
u8_t hlen;
int valid;
int is_last;
IPFRAG_STATS_INC(ip_frag.recv);
MIB2_STATS_INC(mib2.ipreasmreqds);
fraghdr = (struct ip_hdr *)p->payload;
if (IPH_HL_BYTES(fraghdr) != IP_HLEN) {
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: IP options currently not supported!\n"));
IPFRAG_STATS_INC(ip_frag.err);
goto nullreturn;
}
offset = IPH_OFFSET_BYTES(fraghdr);
len = lwip_ntohs(IPH_LEN(fraghdr));
hlen = IPH_HL_BYTES(fraghdr);
if (hlen > len) {
/* invalid datagram */
goto nullreturn;
}
len = (u16_t)(len - hlen);
/* Check if we are allowed to enqueue more datagrams. */
clen = pbuf_clen(p);
if ((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
#if IP_REASS_FREE_OLDEST
if (!ip_reass_remove_oldest_datagram(fraghdr, clen) ||
((ip_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS))
#endif /* IP_REASS_FREE_OLDEST */
{
/* No datagram could be freed and still too many pbufs enqueued */
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: Overflow condition: pbufct=%d, clen=%d, MAX=%d\n",
ip_reass_pbufcount, clen, IP_REASS_MAX_PBUFS));
IPFRAG_STATS_INC(ip_frag.memerr);
/* @todo: send ICMP time exceeded here? */
/* drop this pbuf */
goto nullreturn;
}
}
/* Look for the datagram the fragment belongs to in the current datagram queue,
* remembering the previous in the queue for later dequeueing. */
for (ipr = reassdatagrams; ipr != NULL; ipr = ipr->next) {
/* Check if the incoming fragment matches the one currently present
in the reassembly buffer. If so, we proceed with copying the
fragment into the buffer. */
if (IP_ADDRESSES_AND_ID_MATCH(&ipr->iphdr, fraghdr)) {
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: matching previous fragment ID=%"X16_F"\n",
lwip_ntohs(IPH_ID(fraghdr))));
IPFRAG_STATS_INC(ip_frag.cachehit);
break;
}
}
if (ipr == NULL) {
/* Enqueue a new datagram into the datagram queue */
ipr = ip_reass_enqueue_new_datagram(fraghdr, clen);
/* Bail if unable to enqueue */
if (ipr == NULL) {
goto nullreturn;
}
} else {
if (((lwip_ntohs(IPH_OFFSET(fraghdr)) & IP_OFFMASK) == 0) &&
((lwip_ntohs(IPH_OFFSET(&ipr->iphdr)) & IP_OFFMASK) != 0)) {
/* ipr->iphdr is not the header from the first fragment, but fraghdr is
* -> copy fraghdr into ipr->iphdr since we want to have the header
* of the first fragment (for ICMP time exceeded and later, for copying
* all options, if supported)*/
SMEMCPY(&ipr->iphdr, fraghdr, IP_HLEN);
}
}
/* At this point, we have either created a new entry or pointing
* to an existing one */
/* check for 'no more fragments', and update queue entry*/
is_last = (IPH_OFFSET(fraghdr) & PP_NTOHS(IP_MF)) == 0;
if (is_last) {
u16_t datagram_len = (u16_t)(offset + len);
if ((datagram_len < offset) || (datagram_len > (0xFFFF - IP_HLEN))) {
/* u16_t overflow, cannot handle this */
goto nullreturn_ipr;
}
}
/* find the right place to insert this pbuf */
/* @todo: trim pbufs if fragments are overlapping */
valid = ip_reass_chain_frag_into_datagram_and_validate(ipr, p, is_last);
if (valid == IP_REASS_VALIDATE_PBUF_DROPPED) {
goto nullreturn_ipr;
}
/* if we come here, the pbuf has been enqueued */
/* Track the current number of pbufs current 'in-flight', in order to limit
the number of fragments that may be enqueued at any one time
(overflow checked by testing against IP_REASS_MAX_PBUFS) */
ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount + clen);
if (is_last) {
u16_t datagram_len = (u16_t)(offset + len);
ipr->datagram_len = datagram_len;
ipr->flags |= IP_REASS_FLAG_LASTFRAG;
LWIP_DEBUGF(IP_REASS_DEBUG,
("ip4_reass: last fragment seen, total len %"S16_F"\n",
ipr->datagram_len));
}
if (valid == IP_REASS_VALIDATE_TELEGRAM_FINISHED) {
struct ip_reassdata *ipr_prev;
/* the totally last fragment (flag more fragments = 0) was received at least
* once AND all fragments are received */
u16_t datagram_len = (u16_t)(ipr->datagram_len + IP_HLEN);
/* save the second pbuf before copying the header over the pointer */
r = ((struct ip_reass_helper *)ipr->p->payload)->next_pbuf;
/* copy the original ip header back to the first pbuf */
fraghdr = (struct ip_hdr *)(ipr->p->payload);
SMEMCPY(fraghdr, &ipr->iphdr, IP_HLEN);
IPH_LEN_SET(fraghdr, lwip_htons(datagram_len));
IPH_OFFSET_SET(fraghdr, 0);
IPH_CHKSUM_SET(fraghdr, 0);
/* @todo: do we need to set/calculate the correct checksum? */
#if CHECKSUM_GEN_IP
IF__NETIF_CHECKSUM_ENABLED(ip_current_input_netif(), NETIF_CHECKSUM_GEN_IP) {
IPH_CHKSUM_SET(fraghdr, inet_chksum(fraghdr, IP_HLEN));
}
#endif /* CHECKSUM_GEN_IP */
p = ipr->p;
/* chain together the pbufs contained within the reass_data list. */
while (r != NULL) {
iprh = (struct ip_reass_helper *)r->payload;
/* hide the ip header for every succeeding fragment */
pbuf_remove_header(r, IP_HLEN);
pbuf_cat(p, r);
r = iprh->next_pbuf;
}
/* find the previous entry in the linked list */
if (ipr == reassdatagrams) {
ipr_prev = NULL;
} else {
for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
if (ipr_prev->next == ipr) {
break;
}
}
}
/* release the sources allocate for the fragment queue entry */
ip_reass_dequeue_datagram(ipr, ipr_prev);
/* and adjust the number of pbufs currently queued for reassembly. */
clen = pbuf_clen(p);
LWIP_ASSERT("ip_reass_pbufcount >= clen", ip_reass_pbufcount >= clen);
ip_reass_pbufcount = (u16_t)(ip_reass_pbufcount - clen);
MIB2_STATS_INC(mib2.ipreasmoks);
/* Return the pbuf chain */
return p;
}
/* the datagram is not (yet?) reassembled completely */
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip_reass_pbufcount: %d out\n", ip_reass_pbufcount));
return NULL;
nullreturn_ipr:
LWIP_ASSERT("ipr != NULL", ipr != NULL);
if (ipr->p == NULL) {
/* dropped pbuf after creating a new datagram entry: remove the entry, too */
LWIP_ASSERT("not firstalthough just enqueued", ipr == reassdatagrams);
ip_reass_dequeue_datagram(ipr, NULL);
}
nullreturn:
LWIP_DEBUGF(IP_REASS_DEBUG, ("ip4_reass: nullreturn\n"));
IPFRAG_STATS_INC(ip_frag.drop);
pbuf_free(p);
return NULL;
}
#endif /* IP_REASSEMBLY */
#if IP_FRAG
#if !LWIP_NETIF_TX_SINGLE_PBUF
/** Allocate a new struct pbuf_custom_ref */
static struct pbuf_custom_ref *
ip_frag_alloc_pbuf_custom_ref(void)
{
return (struct pbuf_custom_ref *)memp_malloc(MEMP_FRAG_PBUF);
}
/** Free a struct pbuf_custom_ref */
static void
ip_frag_free_pbuf_custom_ref(struct pbuf_custom_ref *p)
{
LWIP_ASSERT("p != NULL", p != NULL);
memp_free(MEMP_FRAG_PBUF, p);
}
/** Free-callback function to free a 'struct pbuf_custom_ref', called by
* pbuf_free. */
static void
ipfrag_free_pbuf_custom(struct pbuf *p)
{
struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref *)p;
LWIP_ASSERT("pcr != NULL", pcr != NULL);
LWIP_ASSERT("pcr == p", (void *)pcr == (void *)p);
if (pcr->original != NULL) {
pbuf_free(pcr->original);
}
ip_frag_free_pbuf_custom_ref(pcr);
}
#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
/**
* Fragment an IP datagram if too large for the netif.
*
* Chop the datagram in MTU sized chunks and send them in order
* by pointing PBUF_REFs into p.
*
* @param p ip packet to send
* @param netif the netif on which to send
* @param dest destination ip address to which to send
*
* @return ERR_OK if sent successfully, err_t otherwise
*/
err_t
ip4_frag(struct pbuf *p, struct netif *netif, const ip4_addr_t *dest)
{
struct pbuf *rambuf;
#if !LWIP_NETIF_TX_SINGLE_PBUF
struct pbuf *newpbuf;
u16_t newpbuflen = 0;
u16_t left_to_copy;
#endif
struct ip_hdr *original_iphdr;
struct ip_hdr *iphdr;
const u16_t nfb = (u16_t)((netif->mtu - IP_HLEN) / 8);
u16_t left, fragsize;
u16_t ofo;
int last;
u16_t poff = IP_HLEN;
u16_t tmp;
int mf_set;
original_iphdr = (struct ip_hdr *)p->payload;
iphdr = original_iphdr;
if (IPH_HL_BYTES(iphdr) != IP_HLEN) {
/* ip4_frag() does not support IP options */
return ERR_VAL;
}
LWIP_ERROR("ip4_frag(): pbuf too short", p->len >= IP_HLEN, return ERR_VAL);
/* Save original offset */
tmp = lwip_ntohs(IPH_OFFSET(iphdr));
ofo = tmp & IP_OFFMASK;
/* already fragmented? if so, the last fragment we create must have MF, too */
mf_set = tmp & IP_MF;
left = (u16_t)(p->tot_len - IP_HLEN);
while (left) {
/* Fill this fragment */
fragsize = LWIP_MIN(left, (u16_t)(nfb * 8));
#if LWIP_NETIF_TX_SINGLE_PBUF
rambuf = pbuf_alloc(PBUF_IP, fragsize, PBUF_RAM);
if (rambuf == NULL) {
goto memerr;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
poff += pbuf_copy_partial(p, rambuf->payload, fragsize, poff);
/* make room for the IP header */
if (pbuf_add_header(rambuf, IP_HLEN)) {
pbuf_free(rambuf);
goto memerr;
}
/* fill in the IP header */
SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
iphdr = (struct ip_hdr *)rambuf->payload;
#else /* LWIP_NETIF_TX_SINGLE_PBUF */
/* When not using a static buffer, create a chain of pbufs.
* The first will be a PBUF_RAM holding the link and IP header.
* The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
* but limited to the size of an mtu.
*/
rambuf = pbuf_alloc(PBUF_LINK, IP_HLEN, PBUF_RAM);
if (rambuf == NULL) {
goto memerr;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(rambuf->len >= (IP_HLEN)));
SMEMCPY(rambuf->payload, original_iphdr, IP_HLEN);
iphdr = (struct ip_hdr *)rambuf->payload;
left_to_copy = fragsize;
while (left_to_copy) {
struct pbuf_custom_ref *pcr;
u16_t plen = (u16_t)(p->len - poff);
LWIP_ASSERT("p->len >= poff", p->len >= poff);
newpbuflen = LWIP_MIN(left_to_copy, plen);
/* Is this pbuf already empty? */
if (!newpbuflen) {
poff = 0;
p = p->next;
continue;
}
pcr = ip_frag_alloc_pbuf_custom_ref();
if (pcr == NULL) {
pbuf_free(rambuf);
goto memerr;
}
/* Mirror this pbuf, although we might not need all of it. */
newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc,
(u8_t *)p->payload + poff, newpbuflen);
if (newpbuf == NULL) {
ip_frag_free_pbuf_custom_ref(pcr);
pbuf_free(rambuf);
goto memerr;
}
pbuf_ref(p);
pcr->original = p;
pcr->pc.custom_free_function = ipfrag_free_pbuf_custom;
/* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
* so that it is removed when pbuf_dechain is later called on rambuf.
*/
pbuf_cat(rambuf, newpbuf);
left_to_copy = (u16_t)(left_to_copy - newpbuflen);
if (left_to_copy) {
poff = 0;
p = p->next;
}
}
poff = (u16_t)(poff + newpbuflen);
#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
/* Correct header */
last = (left <= netif->mtu - IP_HLEN);
/* Set new offset and MF flag */
tmp = (IP_OFFMASK & (ofo));
if (!last || mf_set) {
/* the last fragment has MF set if the input frame had it */
tmp = tmp | IP_MF;
}
IPH_OFFSET_SET(iphdr, lwip_htons(tmp));
IPH_LEN_SET(iphdr, lwip_htons((u16_t)(fragsize + IP_HLEN)));
IPH_CHKSUM_SET(iphdr, 0);
#if CHECKSUM_GEN_IP
IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_IP) {
IPH_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP_HLEN));
}
#endif /* CHECKSUM_GEN_IP */
/* No need for separate header pbuf - we allowed room for it in rambuf
* when allocated.
*/
netif->output(netif, rambuf, dest);
IPFRAG_STATS_INC(ip_frag.xmit);
/* Unfortunately we can't reuse rambuf - the hardware may still be
* using the buffer. Instead we free it (and the ensuing chain) and
* recreate it next time round the loop. If we're lucky the hardware
* will have already sent the packet, the free will really free, and
* there will be zero memory penalty.
*/
pbuf_free(rambuf);
left = (u16_t)(left - fragsize);
ofo = (u16_t)(ofo + nfb);
}
MIB2_STATS_INC(mib2.ipfragoks);
return ERR_OK;
memerr:
MIB2_STATS_INC(mib2.ipfragfails);
return ERR_MEM;
}
#endif /* IP_FRAG */
#endif /* LWIP_IPV4 */

View File

@ -1,821 +0,0 @@
/**
* @file
*
* @defgroup dhcp6 DHCPv6
* @ingroup ip6
* DHCPv6 client: IPv6 address autoconfiguration as per
* RFC 3315 (stateful DHCPv6) and
* RFC 3736 (stateless DHCPv6).
*
* For now, only stateless DHCPv6 is implemented!
*
* TODO:
* - enable/disable API to not always start when RA is received
* - stateful DHCPv6 (for now, only stateless DHCPv6 for DNS and NTP servers works)
* - create Client Identifier?
* - only start requests if a valid local address is available on the netif
* - only start information requests if required (not for every RA)
*
* dhcp6_enable_stateful() enables stateful DHCPv6 for a netif (stateless disabled)<br>
* dhcp6_enable_stateless() enables stateless DHCPv6 for a netif (stateful disabled)<br>
* dhcp6_disable() disable DHCPv6 for a netif
*
* When enabled, requests are only issued after receipt of RA with the
* corresponding bits set.
*/
/*
* Copyright (c) 2018 Simon Goldschmidt
* 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 <goldsimon@gmx.de>
*/
#include "lwip/opt.h"
#if LWIP_IPV6 && LWIP_IPV6_DHCP6 /* don't build if not configured for use in lwipopts.h */
#include "lwip/dhcp6.h"
#include "lwip/prot/dhcp6.h"
#include "lwip/def.h"
#include "lwip/udp.h"
#include "lwip/dns.h"
#include <string.h>
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
#ifndef LWIP_HOOK_DHCP6_APPEND_OPTIONS
#define LWIP_HOOK_DHCP6_APPEND_OPTIONS(netif, dhcp6, state, msg, msg_type, options_len_ptr, max_len)
#endif
#ifndef LWIP_HOOK_DHCP6_PARSE_OPTION
#define LWIP_HOOK_DHCP6_PARSE_OPTION(netif, dhcp6, state, msg, msg_type, option, len, pbuf, offset) do { LWIP_UNUSED_ARG(msg); } while(0)
#endif
#if LWIP_DNS && LWIP_DHCP6_MAX_DNS_SERVERS
#if DNS_MAX_SERVERS > LWIP_DHCP6_MAX_DNS_SERVERS
#define LWIP_DHCP6_PROVIDE_DNS_SERVERS LWIP_DHCP6_MAX_DNS_SERVERS
#else
#define LWIP_DHCP6_PROVIDE_DNS_SERVERS DNS_MAX_SERVERS
#endif
#else
#define LWIP_DHCP6_PROVIDE_DNS_SERVERS 0
#endif
/** Option handling: options are parsed in dhcp6_parse_reply
* and saved in an array where other functions can load them from.
* This might be moved into the struct dhcp6 (not necessarily since
* lwIP is single-threaded and the array is only used while in recv
* callback). */
enum dhcp6_option_idx {
DHCP6_OPTION_IDX_CLI_ID = 0,
DHCP6_OPTION_IDX_SERVER_ID,
#if LWIP_DHCP6_PROVIDE_DNS_SERVERS
DHCP6_OPTION_IDX_DNS_SERVER,
DHCP6_OPTION_IDX_DOMAIN_LIST,
#endif /* LWIP_DHCP_PROVIDE_DNS_SERVERS */
#if LWIP_DHCP6_GET_NTP_SRV
DHCP6_OPTION_IDX_NTP_SERVER,
#endif /* LWIP_DHCP_GET_NTP_SRV */
DHCP6_OPTION_IDX_MAX
};
struct dhcp6_option_info {
u8_t option_given;
u16_t val_start;
u16_t val_length;
};
/** Holds the decoded option info, only valid while in dhcp6_recv. */
struct dhcp6_option_info dhcp6_rx_options[DHCP6_OPTION_IDX_MAX];
#define dhcp6_option_given(dhcp6, idx) (dhcp6_rx_options[idx].option_given != 0)
#define dhcp6_got_option(dhcp6, idx) (dhcp6_rx_options[idx].option_given = 1)
#define dhcp6_clear_option(dhcp6, idx) (dhcp6_rx_options[idx].option_given = 0)
#define dhcp6_clear_all_options(dhcp6) (memset(dhcp6_rx_options, 0, sizeof(dhcp6_rx_options)))
#define dhcp6_get_option_start(dhcp6, idx) (dhcp6_rx_options[idx].val_start)
#define dhcp6_get_option_length(dhcp6, idx) (dhcp6_rx_options[idx].val_length)
#define dhcp6_set_option(dhcp6, idx, start, len) do { dhcp6_rx_options[idx].val_start = (start); dhcp6_rx_options[idx].val_length = (len); }while(0)
const ip_addr_t dhcp6_All_DHCP6_Relay_Agents_and_Servers = IPADDR6_INIT_HOST(0xFF020000, 0, 0, 0x00010002);
const ip_addr_t dhcp6_All_DHCP6_Servers = IPADDR6_INIT_HOST(0xFF020000, 0, 0, 0x00010003);
static struct udp_pcb *dhcp6_pcb;
static u8_t dhcp6_pcb_refcount;
/* receive, unfold, parse and free incoming messages */
static void dhcp6_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port);
/** Ensure DHCP PCB is allocated and bound */
static err_t
dhcp6_inc_pcb_refcount(void)
{
if (dhcp6_pcb_refcount == 0) {
LWIP_ASSERT("dhcp6_inc_pcb_refcount(): memory leak", dhcp6_pcb == NULL);
/* allocate UDP PCB */
dhcp6_pcb = udp_new_ip6();
if (dhcp6_pcb == NULL) {
return ERR_MEM;
}
ip_set_option(dhcp6_pcb, SOF_BROADCAST);
/* set up local and remote port for the pcb -> listen on all interfaces on all src/dest IPs */
udp_bind(dhcp6_pcb, IP6_ADDR_ANY, DHCP6_CLIENT_PORT);
udp_recv(dhcp6_pcb, dhcp6_recv, NULL);
}
dhcp6_pcb_refcount++;
return ERR_OK;
}
/** Free DHCP PCB if the last netif stops using it */
static void
dhcp6_dec_pcb_refcount(void)
{
LWIP_ASSERT("dhcp6_pcb_refcount(): refcount error", (dhcp6_pcb_refcount > 0));
dhcp6_pcb_refcount--;
if (dhcp6_pcb_refcount == 0) {
udp_remove(dhcp6_pcb);
dhcp6_pcb = NULL;
}
}
/**
* @ingroup dhcp6
* Set a statically allocated struct dhcp6 to work with.
* Using this prevents dhcp6_start to allocate it using mem_malloc.
*
* @param netif the netif for which to set the struct dhcp
* @param dhcp6 (uninitialised) dhcp6 struct allocated by the application
*/
void
dhcp6_set_struct(struct netif *netif, struct dhcp6 *dhcp6)
{
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("dhcp6 != NULL", dhcp6 != NULL);
LWIP_ASSERT("netif already has a struct dhcp6 set", netif_dhcp6_data(netif) == NULL);
/* clear data structure */
memset(dhcp6, 0, sizeof(struct dhcp6));
/* dhcp6_set_state(&dhcp, DHCP6_STATE_OFF); */
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, dhcp6);
}
/**
* @ingroup dhcp6
* Removes a struct dhcp6 from a netif.
*
* ATTENTION: Only use this when not using dhcp6_set_struct() to allocate the
* struct dhcp6 since the memory is passed back to the heap.
*
* @param netif the netif from which to remove the struct dhcp
*/
void dhcp6_cleanup(struct netif *netif)
{
LWIP_ASSERT("netif != NULL", netif != NULL);
if (netif_dhcp6_data(netif) != NULL) {
mem_free(netif_dhcp6_data(netif));
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, NULL);
}
}
static struct dhcp6*
dhcp6_get_struct(struct netif *netif, const char *dbg_requester)
{
struct dhcp6 *dhcp6 = netif_dhcp6_data(netif);
if (dhcp6 == NULL) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("%s: mallocing new DHCPv6 client\n", dbg_requester));
dhcp6 = (struct dhcp6 *)mem_malloc(sizeof(struct dhcp6));
if (dhcp6 == NULL) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("%s: could not allocate dhcp6\n", dbg_requester));
return NULL;
}
/* clear data structure, this implies DHCP6_STATE_OFF */
memset(dhcp6, 0, sizeof(struct dhcp6));
/* store this dhcp6 client in the netif */
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, dhcp6);
} else {
/* already has DHCP6 client attached */
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("%s: using existing DHCPv6 client\n", dbg_requester));
}
if (!dhcp6->pcb_allocated) {
if (dhcp6_inc_pcb_refcount() != ERR_OK) { /* ensure DHCP6 PCB is allocated */
mem_free(dhcp6);
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_DHCP6, NULL);
return NULL;
}
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("%s: allocated dhcp6", dbg_requester));
dhcp6->pcb_allocated = 1;
}
return dhcp6;
}
/*
* Set the DHCPv6 state
* If the state changed, reset the number of tries.
*/
static void
dhcp6_set_state(struct dhcp6 *dhcp6, u8_t new_state, const char *dbg_caller)
{
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("DHCPv6 state: %d -> %d (%s)\n",
dhcp6->state, new_state, dbg_caller));
if (new_state != dhcp6->state) {
dhcp6->state = new_state;
dhcp6->tries = 0;
dhcp6->request_timeout = 0;
}
}
static int
dhcp6_stateless_enabled(struct dhcp6 *dhcp6)
{
if ((dhcp6->state == DHCP6_STATE_STATELESS_IDLE) ||
(dhcp6->state == DHCP6_STATE_REQUESTING_CONFIG)) {
return 1;
}
return 0;
}
/*static int
dhcp6_stateful_enabled(struct dhcp6 *dhcp6)
{
if (dhcp6->state == DHCP6_STATE_OFF) {
return 0;
}
if (dhcp6_stateless_enabled(dhcp6)) {
return 0;
}
return 1;
}*/
/**
* @ingroup dhcp6
* Enable stateful DHCPv6 on this netif
* Requests are sent on receipt of an RA message with the
* ND6_RA_FLAG_MANAGED_ADDR_CONFIG flag set.
*
* A struct dhcp6 will be allocated for this netif if not
* set via @ref dhcp6_set_struct before.
*
* @todo: stateful DHCPv6 not supported, yet
*/
err_t
dhcp6_enable_stateful(struct netif *netif)
{
LWIP_UNUSED_ARG(netif);
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("stateful dhcp6 not implemented yet"));
return ERR_VAL;
}
/**
* @ingroup dhcp6
* Enable stateless DHCPv6 on this netif
* Requests are sent on receipt of an RA message with the
* ND6_RA_FLAG_OTHER_CONFIG flag set.
*
* A struct dhcp6 will be allocated for this netif if not
* set via @ref dhcp6_set_struct before.
*/
err_t
dhcp6_enable_stateless(struct netif *netif)
{
struct dhcp6 *dhcp6;
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp6_enable_stateless(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
dhcp6 = dhcp6_get_struct(netif, "dhcp6_enable_stateless()");
if (dhcp6 == NULL) {
return ERR_MEM;
}
if (dhcp6_stateless_enabled(dhcp6)) {
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp6_enable_stateless(): stateless DHCPv6 already enabled"));
return ERR_OK;
} else if (dhcp6->state != DHCP6_STATE_OFF) {
/* stateful running */
/* @todo: stop stateful once it is implemented */
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp6_enable_stateless(): switching from stateful to stateless DHCPv6"));
}
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp6_enable_stateless(): stateless DHCPv6 enabled\n"));
dhcp6_set_state(dhcp6, DHCP6_STATE_STATELESS_IDLE, "dhcp6_enable_stateless");
return ERR_OK;
}
/**
* @ingroup dhcp6
* Disable stateful or stateless DHCPv6 on this netif
* Requests are sent on receipt of an RA message with the
* ND6_RA_FLAG_OTHER_CONFIG flag set.
*/
void
dhcp6_disable(struct netif *netif)
{
struct dhcp6 *dhcp6;
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp6_disable(netif=%p) %c%c%"U16_F"\n", (void *)netif, netif->name[0], netif->name[1], (u16_t)netif->num));
dhcp6 = netif_dhcp6_data(netif);
if (dhcp6 != NULL) {
if (dhcp6->state != DHCP6_STATE_OFF) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("dhcp6_disable(): DHCPv6 disabled (old state: %s)\n",
(dhcp6_stateless_enabled(dhcp6) ? "stateless" : "stateful")));
dhcp6_set_state(dhcp6, DHCP6_STATE_OFF, "dhcp6_disable");
if (dhcp6->pcb_allocated != 0) {
dhcp6_dec_pcb_refcount(); /* free DHCPv6 PCB if not needed any more */
dhcp6->pcb_allocated = 0;
}
}
}
}
/**
* Create a DHCPv6 request, fill in common headers
*
* @param netif the netif under DHCPv6 control
* @param dhcp6 dhcp6 control struct
* @param message_type message type of the request
* @param opt_len_alloc option length to allocate
* @param options_out_len option length on exit
* @return a pbuf for the message
*/
static struct pbuf *
dhcp6_create_msg(struct netif *netif, struct dhcp6 *dhcp6, u8_t message_type,
u16_t opt_len_alloc, u16_t *options_out_len)
{
struct pbuf *p_out;
struct dhcp6_msg *msg_out;
LWIP_ERROR("dhcp6_create_msg: netif != NULL", (netif != NULL), return NULL;);
LWIP_ERROR("dhcp6_create_msg: dhcp6 != NULL", (dhcp6 != NULL), return NULL;);
p_out = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct dhcp6_msg) + opt_len_alloc, PBUF_RAM);
if (p_out == NULL) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
("dhcp6_create_msg(): could not allocate pbuf\n"));
return NULL;
}
LWIP_ASSERT("dhcp6_create_msg: check that first pbuf can hold struct dhcp6_msg",
(p_out->len >= sizeof(struct dhcp6_msg) + opt_len_alloc));
/* @todo: limit new xid for certain message types? */
/* reuse transaction identifier in retransmissions */
if (dhcp6->tries == 0) {
dhcp6->xid = LWIP_RAND() & 0xFFFFFF;
}
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE,
("transaction id xid(%"X32_F")\n", dhcp6->xid));
msg_out = (struct dhcp6_msg *)p_out->payload;
memset(msg_out, 0, sizeof(struct dhcp6_msg) + opt_len_alloc);
msg_out->msgtype = message_type;
msg_out->transaction_id[0] = (u8_t)(dhcp6->xid >> 16);
msg_out->transaction_id[1] = (u8_t)(dhcp6->xid >> 8);
msg_out->transaction_id[2] = (u8_t)dhcp6->xid;
*options_out_len = 0;
return p_out;
}
static u16_t
dhcp6_option_short(u16_t options_out_len, u8_t *options, u16_t value)
{
options[options_out_len++] = (u8_t)((value & 0xff00U) >> 8);
options[options_out_len++] = (u8_t) (value & 0x00ffU);
return options_out_len;
}
static u16_t
dhcp6_option_optionrequest(u16_t options_out_len, u8_t *options, const u16_t *req_options,
u16_t num_req_options, u16_t max_len)
{
size_t i;
u16_t ret;
LWIP_ASSERT("dhcp6_option_optionrequest: options_out_len + sizeof(struct dhcp6_msg) + addlen <= max_len",
sizeof(struct dhcp6_msg) + options_out_len + 4U + (2U * num_req_options) <= max_len);
LWIP_UNUSED_ARG(max_len);
ret = dhcp6_option_short(options_out_len, options, DHCP6_OPTION_ORO);
ret = dhcp6_option_short(ret, options, 2 * num_req_options);
for (i = 0; i < num_req_options; i++) {
ret = dhcp6_option_short(ret, options, req_options[i]);
}
return ret;
}
/* All options are added, shrink the pbuf to the required size */
static void
dhcp6_msg_finalize(u16_t options_out_len, struct pbuf *p_out)
{
/* shrink the pbuf to the actual content length */
pbuf_realloc(p_out, (u16_t)(sizeof(struct dhcp6_msg) + options_out_len));
}
#if LWIP_IPV6_DHCP6_STATELESS
static void
dhcp6_information_request(struct netif *netif, struct dhcp6 *dhcp6)
{
const u16_t requested_options[] = {
#if LWIP_DHCP6_PROVIDE_DNS_SERVERS
DHCP6_OPTION_DNS_SERVERS,
DHCP6_OPTION_DOMAIN_LIST
#endif
#if LWIP_DHCP6_GET_NTP_SRV
, DHCP6_OPTION_SNTP_SERVERS
#endif
};
u16_t msecs;
struct pbuf *p_out;
u16_t options_out_len;
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("dhcp6_information_request()\n"));
/* create and initialize the DHCP message header */
p_out = dhcp6_create_msg(netif, dhcp6, DHCP6_INFOREQUEST, 4 + sizeof(requested_options), &options_out_len);
if (p_out != NULL) {
err_t err;
struct dhcp6_msg *msg_out = (struct dhcp6_msg *)p_out->payload;
u8_t *options = (u8_t *)(msg_out + 1);
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("dhcp6_information_request: making request\n"));
options_out_len = dhcp6_option_optionrequest(options_out_len, options, requested_options,
LWIP_ARRAYSIZE(requested_options), p_out->len);
LWIP_HOOK_DHCP6_APPEND_OPTIONS(netif, dhcp6, DHCP6_STATE_REQUESTING_CONFIG, msg_out,
DHCP6_INFOREQUEST, options_out_len, p_out->len);
dhcp6_msg_finalize(options_out_len, p_out);
err = udp_sendto_if(dhcp6_pcb, p_out, &dhcp6_All_DHCP6_Relay_Agents_and_Servers, DHCP6_SERVER_PORT, netif);
pbuf_free(p_out);
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp6_information_request: INFOREQUESTING -> %d\n", (int)err));
LWIP_UNUSED_ARG(err);
} else {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("dhcp6_information_request: could not allocate DHCP6 request\n"));
}
dhcp6_set_state(dhcp6, DHCP6_STATE_REQUESTING_CONFIG, "dhcp6_information_request");
if (dhcp6->tries < 255) {
dhcp6->tries++;
}
msecs = (u16_t)((dhcp6->tries < 6 ? 1 << dhcp6->tries : 60) * 1000);
dhcp6->request_timeout = (u16_t)((msecs + DHCP6_TIMER_MSECS - 1) / DHCP6_TIMER_MSECS);
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp6_information_request(): set request timeout %"U16_F" msecs\n", msecs));
}
static err_t
dhcp6_request_config(struct netif *netif, struct dhcp6 *dhcp6)
{
/* stateless mode enabled and no request running? */
if (dhcp6->state == DHCP6_STATE_STATELESS_IDLE) {
/* send Information-request and wait for answer; setup receive timeout */
dhcp6_information_request(netif, dhcp6);
}
return ERR_OK;
}
static void
dhcp6_abort_config_request(struct dhcp6 *dhcp6)
{
if (dhcp6->state == DHCP6_STATE_REQUESTING_CONFIG) {
/* abort running request */
dhcp6_set_state(dhcp6, DHCP6_STATE_STATELESS_IDLE, "dhcp6_abort_config_request");
}
}
/* Handle a REPLY to INFOREQUEST
* This parses DNS and NTP server addresses from the reply.
*/
static void
dhcp6_handle_config_reply(struct netif *netif, struct pbuf *p_msg_in)
{
struct dhcp6 *dhcp6 = netif_dhcp6_data(netif);
LWIP_UNUSED_ARG(dhcp6);
LWIP_UNUSED_ARG(p_msg_in);
#if LWIP_DHCP6_PROVIDE_DNS_SERVERS
if (dhcp6_option_given(dhcp6, DHCP6_OPTION_IDX_DNS_SERVER)) {
ip_addr_t dns_addr;
ip6_addr_t *dns_addr6;
u16_t op_start = dhcp6_get_option_start(dhcp6, DHCP6_OPTION_IDX_DNS_SERVER);
u16_t op_len = dhcp6_get_option_length(dhcp6, DHCP6_OPTION_IDX_DNS_SERVER);
u16_t idx;
u8_t n;
ip_addr_set_zero_ip6(&dns_addr);
dns_addr6 = ip_2_ip6(&dns_addr);
for (n = 0, idx = op_start; (idx < op_start + op_len) && (n < LWIP_DHCP6_PROVIDE_DNS_SERVERS);
n++, idx += sizeof(struct ip6_addr_packed)) {
u16_t copied = pbuf_copy_partial(p_msg_in, dns_addr6, sizeof(struct ip6_addr_packed), idx);
if (copied != sizeof(struct ip6_addr_packed)) {
/* pbuf length mismatch */
return;
}
ip6_addr_assign_zone(dns_addr6, IP6_UNKNOWN, netif);
/* @todo: do we need a different offset than DHCP(v4)? */
dns_setserver(n, &dns_addr);
}
}
/* @ todo: parse and set Domain Search List */
#endif /* LWIP_DHCP6_PROVIDE_DNS_SERVERS */
#if LWIP_DHCP6_GET_NTP_SRV
if (dhcp6_option_given(dhcp6, DHCP6_OPTION_IDX_NTP_SERVER)) {
ip_addr_t ntp_server_addrs[LWIP_DHCP6_MAX_NTP_SERVERS];
u16_t op_start = dhcp6_get_option_start(dhcp6, DHCP6_OPTION_IDX_NTP_SERVER);
u16_t op_len = dhcp6_get_option_length(dhcp6, DHCP6_OPTION_IDX_NTP_SERVER);
u16_t idx;
u8_t n;
for (n = 0, idx = op_start; (idx < op_start + op_len) && (n < LWIP_DHCP6_MAX_NTP_SERVERS);
n++, idx += sizeof(struct ip6_addr_packed)) {
u16_t copied;
ip6_addr_t *ntp_addr6 = ip_2_ip6(&ntp_server_addrs[n]);
ip_addr_set_zero_ip6(&ntp_server_addrs[n]);
copied = pbuf_copy_partial(p_msg_in, ntp_addr6, sizeof(struct ip6_addr_packed), idx);
if (copied != sizeof(struct ip6_addr_packed)) {
/* pbuf length mismatch */
return;
}
ip6_addr_assign_zone(ntp_addr6, IP6_UNKNOWN, netif);
}
dhcp6_set_ntp_servers(n, ntp_server_addrs);
}
#endif /* LWIP_DHCP6_GET_NTP_SRV */
}
#endif /* LWIP_IPV6_DHCP6_STATELESS */
/** This function is called from nd6 module when an RA message is received
* It triggers DHCPv6 requests (if enabled).
*/
void
dhcp6_nd6_ra_trigger(struct netif *netif, u8_t managed_addr_config, u8_t other_config)
{
struct dhcp6 *dhcp6;
LWIP_ASSERT("netif != NULL", netif != NULL);
dhcp6 = netif_dhcp6_data(netif);
LWIP_UNUSED_ARG(managed_addr_config);
LWIP_UNUSED_ARG(other_config);
LWIP_UNUSED_ARG(dhcp6);
#if LWIP_IPV6_DHCP6_STATELESS
if (dhcp6 != NULL) {
if (dhcp6_stateless_enabled(dhcp6)) {
if (other_config) {
dhcp6_request_config(netif, dhcp6);
} else {
dhcp6_abort_config_request(dhcp6);
}
}
}
#endif /* LWIP_IPV6_DHCP6_STATELESS */
}
/**
* Parse the DHCPv6 message and extract the DHCPv6 options.
*
* Extract the DHCPv6 options (offset + length) so that we can later easily
* check for them or extract the contents.
*/
static err_t
dhcp6_parse_reply(struct pbuf *p, struct dhcp6 *dhcp6)
{
u16_t offset;
u16_t offset_max;
u16_t options_idx;
struct dhcp6_msg *msg_in;
LWIP_UNUSED_ARG(dhcp6);
/* clear received options */
dhcp6_clear_all_options(dhcp6);
msg_in = (struct dhcp6_msg *)p->payload;
/* parse options */
options_idx = sizeof(struct dhcp6_msg);
/* parse options to the end of the received packet */
offset_max = p->tot_len;
offset = options_idx;
/* at least 4 byte to read? */
while ((offset + 4 <= offset_max)) {
u8_t op_len_buf[4];
u8_t *op_len;
u16_t op;
u16_t len;
u16_t val_offset = (u16_t)(offset + 4);
if (val_offset < offset) {
/* overflow */
return ERR_BUF;
}
/* copy option + length, might be split across pbufs */
op_len = (u8_t *)pbuf_get_contiguous(p, op_len_buf, 4, 4, offset);
if (op_len == NULL) {
/* failed to get option and length */
return ERR_VAL;
}
op = (op_len[0] << 8) | op_len[1];
len = (op_len[2] << 8) | op_len[3];
offset = val_offset + len;
if (offset < val_offset) {
/* overflow */
return ERR_BUF;
}
switch (op) {
case (DHCP6_OPTION_CLIENTID):
dhcp6_got_option(dhcp6, DHCP6_OPTION_IDX_CLI_ID);
dhcp6_set_option(dhcp6, DHCP6_OPTION_IDX_CLI_ID, val_offset, len);
break;
case (DHCP6_OPTION_SERVERID):
dhcp6_got_option(dhcp6, DHCP6_OPTION_IDX_SERVER_ID);
dhcp6_set_option(dhcp6, DHCP6_OPTION_IDX_SERVER_ID, val_offset, len);
break;
#if LWIP_DHCP6_PROVIDE_DNS_SERVERS
case (DHCP6_OPTION_DNS_SERVERS):
dhcp6_got_option(dhcp6, DHCP6_OPTION_IDX_DNS_SERVER);
dhcp6_set_option(dhcp6, DHCP6_OPTION_IDX_DNS_SERVER, val_offset, len);
break;
case (DHCP6_OPTION_DOMAIN_LIST):
dhcp6_got_option(dhcp6, DHCP6_OPTION_IDX_DOMAIN_LIST);
dhcp6_set_option(dhcp6, DHCP6_OPTION_IDX_DOMAIN_LIST, val_offset, len);
break;
#endif /* LWIP_DHCP6_PROVIDE_DNS_SERVERS */
#if LWIP_DHCP6_GET_NTP_SRV
case (DHCP6_OPTION_SNTP_SERVERS):
dhcp6_got_option(dhcp6, DHCP6_OPTION_IDX_NTP_SERVER);
dhcp6_set_option(dhcp6, DHCP6_OPTION_IDX_NTP_SERVER, val_offset, len);
break;
#endif /* LWIP_DHCP6_GET_NTP_SRV*/
default:
LWIP_DEBUGF(DHCP6_DEBUG, ("skipping option %"U16_F" in options\n", op));
LWIP_HOOK_DHCP6_PARSE_OPTION(ip_current_netif(), dhcp6, dhcp6->state, msg_in,
msg_in->msgtype, op, len, q, val_offset);
break;
}
}
return ERR_OK;
}
static void
dhcp6_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p, const ip_addr_t *addr, u16_t port)
{
struct netif *netif = ip_current_input_netif();
struct dhcp6 *dhcp6 = netif_dhcp6_data(netif);
struct dhcp6_msg *reply_msg = (struct dhcp6_msg *)p->payload;
u8_t msg_type;
u32_t xid;
LWIP_UNUSED_ARG(arg);
/* Caught DHCPv6 message from netif that does not have DHCPv6 enabled? -> not interested */
if ((dhcp6 == NULL) || (dhcp6->pcb_allocated == 0)) {
goto free_pbuf_and_return;
}
LWIP_ERROR("invalid server address type", IP_IS_V6(addr), goto free_pbuf_and_return;);
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("dhcp6_recv(pbuf = %p) from DHCPv6 server %s port %"U16_F"\n", (void *)p,
ipaddr_ntoa(addr), port));
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("pbuf->len = %"U16_F"\n", p->len));
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("pbuf->tot_len = %"U16_F"\n", p->tot_len));
/* prevent warnings about unused arguments */
LWIP_UNUSED_ARG(pcb);
LWIP_UNUSED_ARG(addr);
LWIP_UNUSED_ARG(port);
if (p->len < sizeof(struct dhcp6_msg)) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("DHCPv6 reply message or pbuf too short\n"));
goto free_pbuf_and_return;
}
/* match transaction ID against what we expected */
xid = reply_msg->transaction_id[0] << 16;
xid |= reply_msg->transaction_id[1] << 8;
xid |= reply_msg->transaction_id[2];
if (xid != dhcp6->xid) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
("transaction id mismatch reply_msg->xid(%"X32_F")!= dhcp6->xid(%"X32_F")\n", xid, dhcp6->xid));
goto free_pbuf_and_return;
}
/* option fields could be unfold? */
if (dhcp6_parse_reply(p, dhcp6) != ERR_OK) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
("problem unfolding DHCPv6 message - too short on memory?\n"));
goto free_pbuf_and_return;
}
/* read DHCP message type */
msg_type = reply_msg->msgtype;
/* message type is DHCP6 REPLY? */
if (msg_type == DHCP6_REPLY) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("DHCP6_REPLY received\n"));
#if LWIP_IPV6_DHCP6_STATELESS
/* in info-requesting state? */
if (dhcp6->state == DHCP6_STATE_REQUESTING_CONFIG) {
dhcp6_set_state(dhcp6, DHCP6_STATE_STATELESS_IDLE, "dhcp6_recv");
dhcp6_handle_config_reply(netif, p);
} else
#endif /* LWIP_IPV6_DHCP6_STATELESS */
{
/* @todo: handle reply in other states? */
}
} else {
/* @todo: handle other message types */
}
free_pbuf_and_return:
pbuf_free(p);
}
/**
* A DHCPv6 request has timed out.
*
* The timer that was started with the DHCPv6 request has
* timed out, indicating no response was received in time.
*/
static void
dhcp6_timeout(struct netif *netif, struct dhcp6 *dhcp6)
{
LWIP_DEBUGF(DHCP_DEBUG | LWIP_DBG_TRACE, ("dhcp6_timeout()\n"));
LWIP_UNUSED_ARG(netif);
LWIP_UNUSED_ARG(dhcp6);
#if LWIP_IPV6_DHCP6_STATELESS
/* back-off period has passed, or server selection timed out */
if (dhcp6->state == DHCP6_STATE_REQUESTING_CONFIG) {
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE, ("dhcp6_timeout(): retrying information request\n"));
dhcp6_information_request(netif, dhcp6);
}
#endif /* LWIP_IPV6_DHCP6_STATELESS */
}
/**
* DHCPv6 timeout handling (this function must be called every 500ms,
* see @ref DHCP6_TIMER_MSECS).
*
* A DHCPv6 server is expected to respond within a short period of time.
* This timer checks whether an outstanding DHCPv6 request is timed out.
*/
void
dhcp6_tmr(void)
{
struct netif *netif;
/* loop through netif's */
NETIF_FOREACH(netif) {
struct dhcp6 *dhcp6 = netif_dhcp6_data(netif);
/* only act on DHCPv6 configured interfaces */
if (dhcp6 != NULL) {
/* timer is active (non zero), and is about to trigger now */
if (dhcp6->request_timeout > 1) {
dhcp6->request_timeout--;
} else if (dhcp6->request_timeout == 1) {
dhcp6->request_timeout--;
/* { dhcp6->request_timeout == 0 } */
LWIP_DEBUGF(DHCP6_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_STATE, ("dhcp6_tmr(): request timeout\n"));
/* this client's request timeout triggered */
dhcp6_timeout(netif, dhcp6);
}
}
}
}
#endif /* LWIP_IPV6 && LWIP_IPV6_DHCP6 */

View File

@ -1,123 +0,0 @@
/**
* @file
*
* Ethernet output for IPv6. Uses ND tables for link-layer addressing.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
#include "lwip/opt.h"
#if LWIP_IPV6 && LWIP_ETHERNET
#include "lwip/ethip6.h"
#include "lwip/nd6.h"
#include "lwip/pbuf.h"
#include "lwip/ip6.h"
#include "lwip/ip6_addr.h"
#include "lwip/inet_chksum.h"
#include "lwip/netif.h"
#include "lwip/icmp6.h"
#include "lwip/prot/ethernet.h"
#include "netif/ethernet.h"
#include <string.h>
/**
* Resolve and fill-in Ethernet address header for outgoing IPv6 packet.
*
* For IPv6 multicast, corresponding Ethernet addresses
* are selected and the packet is transmitted on the link.
*
* For unicast addresses, ask the ND6 module what to do. It will either let us
* send the the packet right away, or queue the packet for later itself, unless
* an error occurs.
*
* @todo anycast addresses
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The pbuf(s) containing the IP packet to be sent.
* @param ip6addr The IP address of the packet destination.
*
* @return
* - ERR_OK or the return value of @ref nd6_get_next_hop_addr_or_queue.
*/
err_t
ethip6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
{
struct eth_addr dest;
const u8_t *hwaddr;
err_t result;
LWIP_ASSERT_CORE_LOCKED();
/* The destination IP address must be properly zoned from here on down. */
IP6_ADDR_ZONECHECK_NETIF(ip6addr, netif);
/* multicast destination IP address? */
if (ip6_addr_ismulticast(ip6addr)) {
/* Hash IP multicast address to MAC address.*/
dest.addr[0] = 0x33;
dest.addr[1] = 0x33;
dest.addr[2] = ((const u8_t *)(&(ip6addr->addr[3])))[0];
dest.addr[3] = ((const u8_t *)(&(ip6addr->addr[3])))[1];
dest.addr[4] = ((const u8_t *)(&(ip6addr->addr[3])))[2];
dest.addr[5] = ((const u8_t *)(&(ip6addr->addr[3])))[3];
/* Send out. */
return ethernet_output(netif, q, (const struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
}
/* We have a unicast destination IP address */
/* @todo anycast? */
/* Ask ND6 what to do with the packet. */
result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
if (result != ERR_OK) {
return result;
}
/* If no hardware address is returned, nd6 has queued the packet for later. */
if (hwaddr == NULL) {
return ERR_OK;
}
/* Send out the packet using the returned hardware address. */
SMEMCPY(dest.addr, hwaddr, 6);
return ethernet_output(netif, q, (const struct eth_addr*)(netif->hwaddr), &dest, ETHTYPE_IPV6);
}
#endif /* LWIP_IPV6 && LWIP_ETHERNET */

View File

@ -1,425 +0,0 @@
/**
* @file
*
* IPv6 version of ICMP, as per RFC 4443.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
#include "lwip/opt.h"
#if LWIP_ICMP6 && LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */
#include "lwip/icmp6.h"
#include "lwip/prot/icmp6.h"
#include "lwip/ip6.h"
#include "lwip/ip6_addr.h"
#include "lwip/inet_chksum.h"
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#include "lwip/nd6.h"
#include "lwip/mld6.h"
#include "lwip/ip.h"
#include "lwip/stats.h"
#include <string.h>
#if !LWIP_ICMP6_DATASIZE || (LWIP_ICMP6_DATASIZE > (IP6_MIN_MTU_LENGTH - IP6_HLEN - ICMP6_HLEN))
#undef LWIP_ICMP6_DATASIZE
#define LWIP_ICMP6_DATASIZE (IP6_MIN_MTU_LENGTH - IP6_HLEN - ICMP6_HLEN)
#endif
/* Forward declarations */
static void icmp6_send_response(struct pbuf *p, u8_t code, u32_t data, u8_t type);
static void icmp6_send_response_with_addrs(struct pbuf *p, u8_t code, u32_t data,
u8_t type, const ip6_addr_t *src_addr, const ip6_addr_t *dest_addr);
static void icmp6_send_response_with_addrs_and_netif(struct pbuf *p, u8_t code, u32_t data,
u8_t type, const ip6_addr_t *src_addr, const ip6_addr_t *dest_addr, struct netif *netif);
/**
* Process an input ICMPv6 message. Called by ip6_input.
*
* Will generate a reply for echo requests. Other messages are forwarded
* to nd6_input, or mld6_input.
*
* @param p the mld packet, p->payload pointing to the icmpv6 header
* @param inp the netif on which this packet was received
*/
void
icmp6_input(struct pbuf *p, struct netif *inp)
{
struct icmp6_hdr *icmp6hdr;
struct pbuf *r;
const ip6_addr_t *reply_src;
ICMP6_STATS_INC(icmp6.recv);
/* Check that ICMPv6 header fits in payload */
if (p->len < sizeof(struct icmp6_hdr)) {
/* drop short packets */
pbuf_free(p);
ICMP6_STATS_INC(icmp6.lenerr);
ICMP6_STATS_INC(icmp6.drop);
return;
}
icmp6hdr = (struct icmp6_hdr *)p->payload;
#if CHECKSUM_CHECK_ICMP6
IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_CHECK_ICMP6) {
if (ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->tot_len, ip6_current_src_addr(),
ip6_current_dest_addr()) != 0) {
/* Checksum failed */
pbuf_free(p);
ICMP6_STATS_INC(icmp6.chkerr);
ICMP6_STATS_INC(icmp6.drop);
return;
}
}
#endif /* CHECKSUM_CHECK_ICMP6 */
switch (icmp6hdr->type) {
case ICMP6_TYPE_NA: /* Neighbor advertisement */
case ICMP6_TYPE_NS: /* Neighbor solicitation */
case ICMP6_TYPE_RA: /* Router advertisement */
case ICMP6_TYPE_RD: /* Redirect */
case ICMP6_TYPE_PTB: /* Packet too big */
nd6_input(p, inp);
return;
case ICMP6_TYPE_RS:
#if LWIP_IPV6_FORWARD
/* @todo implement router functionality */
#endif
break;
#if LWIP_IPV6_MLD
case ICMP6_TYPE_MLQ:
case ICMP6_TYPE_MLR:
case ICMP6_TYPE_MLD:
mld6_input(p, inp);
return;
#endif
case ICMP6_TYPE_EREQ:
#if !LWIP_MULTICAST_PING
/* multicast destination address? */
if (ip6_addr_ismulticast(ip6_current_dest_addr())) {
/* drop */
pbuf_free(p);
ICMP6_STATS_INC(icmp6.drop);
return;
}
#endif /* LWIP_MULTICAST_PING */
/* Allocate reply. */
r = pbuf_alloc(PBUF_IP, p->tot_len, PBUF_RAM);
if (r == NULL) {
/* drop */
pbuf_free(p);
ICMP6_STATS_INC(icmp6.memerr);
return;
}
/* Copy echo request. */
if (pbuf_copy(r, p) != ERR_OK) {
/* drop */
pbuf_free(p);
pbuf_free(r);
ICMP6_STATS_INC(icmp6.err);
return;
}
/* Determine reply source IPv6 address. */
#if LWIP_MULTICAST_PING
if (ip6_addr_ismulticast(ip6_current_dest_addr())) {
reply_src = ip_2_ip6(ip6_select_source_address(inp, ip6_current_src_addr()));
if (reply_src == NULL) {
/* drop */
pbuf_free(p);
pbuf_free(r);
ICMP6_STATS_INC(icmp6.rterr);
return;
}
}
else
#endif /* LWIP_MULTICAST_PING */
{
reply_src = ip6_current_dest_addr();
}
/* Set fields in reply. */
((struct icmp6_echo_hdr *)(r->payload))->type = ICMP6_TYPE_EREP;
((struct icmp6_echo_hdr *)(r->payload))->chksum = 0;
#if CHECKSUM_GEN_ICMP6
IF__NETIF_CHECKSUM_ENABLED(inp, NETIF_CHECKSUM_GEN_ICMP6) {
((struct icmp6_echo_hdr *)(r->payload))->chksum = ip6_chksum_pseudo(r,
IP6_NEXTH_ICMP6, r->tot_len, reply_src, ip6_current_src_addr());
}
#endif /* CHECKSUM_GEN_ICMP6 */
/* Send reply. */
ICMP6_STATS_INC(icmp6.xmit);
ip6_output_if(r, reply_src, ip6_current_src_addr(),
LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, inp);
pbuf_free(r);
break;
default:
ICMP6_STATS_INC(icmp6.proterr);
ICMP6_STATS_INC(icmp6.drop);
break;
}
pbuf_free(p);
}
/**
* Send an icmpv6 'destination unreachable' packet.
*
* This function must be used only in direct response to a packet that is being
* received right now. Otherwise, address zones would be lost.
*
* @param p the input packet for which the 'unreachable' should be sent,
* p->payload pointing to the IPv6 header
* @param c ICMPv6 code for the unreachable type
*/
void
icmp6_dest_unreach(struct pbuf *p, enum icmp6_dur_code c)
{
icmp6_send_response(p, c, 0, ICMP6_TYPE_DUR);
}
/**
* Send an icmpv6 'packet too big' packet.
*
* This function must be used only in direct response to a packet that is being
* received right now. Otherwise, address zones would be lost.
*
* @param p the input packet for which the 'packet too big' should be sent,
* p->payload pointing to the IPv6 header
* @param mtu the maximum mtu that we can accept
*/
void
icmp6_packet_too_big(struct pbuf *p, u32_t mtu)
{
icmp6_send_response(p, 0, mtu, ICMP6_TYPE_PTB);
}
/**
* Send an icmpv6 'time exceeded' packet.
*
* This function must be used only in direct response to a packet that is being
* received right now. Otherwise, address zones would be lost.
*
* @param p the input packet for which the 'time exceeded' should be sent,
* p->payload pointing to the IPv6 header
* @param c ICMPv6 code for the time exceeded type
*/
void
icmp6_time_exceeded(struct pbuf *p, enum icmp6_te_code c)
{
icmp6_send_response(p, c, 0, ICMP6_TYPE_TE);
}
/**
* Send an icmpv6 'time exceeded' packet, with explicit source and destination
* addresses.
*
* This function may be used to send a response sometime after receiving the
* packet for which this response is meant. The provided source and destination
* addresses are used primarily to retain their zone information.
*
* @param p the input packet for which the 'time exceeded' should be sent,
* p->payload pointing to the IPv6 header
* @param c ICMPv6 code for the time exceeded type
* @param src_addr source address of the original packet, with zone information
* @param dest_addr destination address of the original packet, with zone
* information
*/
void
icmp6_time_exceeded_with_addrs(struct pbuf *p, enum icmp6_te_code c,
const ip6_addr_t *src_addr, const ip6_addr_t *dest_addr)
{
icmp6_send_response_with_addrs(p, c, 0, ICMP6_TYPE_TE, src_addr, dest_addr);
}
/**
* Send an icmpv6 'parameter problem' packet.
*
* This function must be used only in direct response to a packet that is being
* received right now. Otherwise, address zones would be lost and the calculated
* offset would be wrong (calculated against ip6_current_header()).
*
* @param p the input packet for which the 'param problem' should be sent,
* p->payload pointing to the IP header
* @param c ICMPv6 code for the param problem type
* @param pointer the pointer to the byte where the parameter is found
*/
void
icmp6_param_problem(struct pbuf *p, enum icmp6_pp_code c, const void *pointer)
{
u32_t pointer_u32 = (u32_t)((const u8_t *)pointer - (const u8_t *)ip6_current_header());
icmp6_send_response(p, c, pointer_u32, ICMP6_TYPE_PP);
}
/**
* Send an ICMPv6 packet in response to an incoming packet.
* The packet is sent *to* ip_current_src_addr() on ip_current_netif().
*
* @param p the input packet for which the response should be sent,
* p->payload pointing to the IPv6 header
* @param code Code of the ICMPv6 header
* @param data Additional 32-bit parameter in the ICMPv6 header
* @param type Type of the ICMPv6 header
*/
static void
icmp6_send_response(struct pbuf *p, u8_t code, u32_t data, u8_t type)
{
const struct ip6_addr *reply_src, *reply_dest;
struct netif *netif = ip_current_netif();
LWIP_ASSERT("icmpv6 packet not a direct response", netif != NULL);
reply_dest = ip6_current_src_addr();
/* Select an address to use as source. */
reply_src = ip_2_ip6(ip6_select_source_address(netif, reply_dest));
if (reply_src == NULL) {
ICMP6_STATS_INC(icmp6.rterr);
return;
}
icmp6_send_response_with_addrs_and_netif(p, code, data, type, reply_src, reply_dest, netif);
}
/**
* Send an ICMPv6 packet in response to an incoming packet.
*
* Call this function if the packet is NOT sent as a direct response to an
* incoming packet, but rather sometime later (e.g. for a fragment reassembly
* timeout). The caller must provide the zoned source and destination addresses
* from the original packet with the src_addr and dest_addr parameters. The
* reason for this approach is that while the addresses themselves are part of
* the original packet, their zone information is not, thus possibly resulting
* in a link-local response being sent over the wrong link.
*
* @param p the input packet for which the response should be sent,
* p->payload pointing to the IPv6 header
* @param code Code of the ICMPv6 header
* @param data Additional 32-bit parameter in the ICMPv6 header
* @param type Type of the ICMPv6 header
* @param src_addr original source address
* @param dest_addr original destination address
*/
static void
icmp6_send_response_with_addrs(struct pbuf *p, u8_t code, u32_t data, u8_t type,
const ip6_addr_t *src_addr, const ip6_addr_t *dest_addr)
{
const struct ip6_addr *reply_src, *reply_dest;
struct netif *netif;
/* Get the destination address and netif for this ICMP message. */
LWIP_ASSERT("must provide both source and destination", src_addr != NULL);
LWIP_ASSERT("must provide both source and destination", dest_addr != NULL);
/* Special case, as ip6_current_xxx is either NULL, or points
to a different packet than the one that expired. */
IP6_ADDR_ZONECHECK(src_addr);
IP6_ADDR_ZONECHECK(dest_addr);
/* Swap source and destination for the reply. */
reply_dest = src_addr;
reply_src = dest_addr;
netif = ip6_route(reply_src, reply_dest);
if (netif == NULL) {
ICMP6_STATS_INC(icmp6.rterr);
return;
}
icmp6_send_response_with_addrs_and_netif(p, code, data, type, reply_src,
reply_dest, netif);
}
/**
* Send an ICMPv6 packet (with srd/dst address and netif given).
*
* @param p the input packet for which the response should be sent,
* p->payload pointing to the IPv6 header
* @param code Code of the ICMPv6 header
* @param data Additional 32-bit parameter in the ICMPv6 header
* @param type Type of the ICMPv6 header
* @param reply_src source address of the packet to send
* @param reply_dest destination address of the packet to send
* @param netif netif to send the packet
*/
static void
icmp6_send_response_with_addrs_and_netif(struct pbuf *p, u8_t code, u32_t data, u8_t type,
const ip6_addr_t *reply_src, const ip6_addr_t *reply_dest, struct netif *netif)
{
struct pbuf *q;
struct icmp6_hdr *icmp6hdr;
u16_t datalen = LWIP_MIN(p->tot_len, LWIP_ICMP6_DATASIZE);
/* ICMPv6 header + datalen (as much of the offending packet as possible) */
q = pbuf_alloc(PBUF_IP, sizeof(struct icmp6_hdr) + datalen,
PBUF_RAM);
if (q == NULL) {
LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded: failed to allocate pbuf for ICMPv6 packet.\n"));
ICMP6_STATS_INC(icmp6.memerr);
return;
}
LWIP_ASSERT("check that first pbuf can hold icmp6 header",
(q->len >= (sizeof(struct icmp6_hdr))));
icmp6hdr = (struct icmp6_hdr *)q->payload;
icmp6hdr->type = type;
icmp6hdr->code = code;
icmp6hdr->data = lwip_htonl(data);
/* copy fields from original packet */
pbuf_copy_partial_pbuf(q, p, datalen, sizeof(struct icmp6_hdr));
/* calculate checksum */
icmp6hdr->chksum = 0;
#if CHECKSUM_GEN_ICMP6
IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
icmp6hdr->chksum = ip6_chksum_pseudo(q, IP6_NEXTH_ICMP6, q->tot_len,
reply_src, reply_dest);
}
#endif /* CHECKSUM_GEN_ICMP6 */
ICMP6_STATS_INC(icmp6.xmit);
ip6_output_if(q, reply_src, reply_dest, LWIP_ICMP6_HL, 0, IP6_NEXTH_ICMP6, netif);
pbuf_free(q);
}
#endif /* LWIP_ICMP6 && LWIP_IPV6 */

View File

@ -1,53 +0,0 @@
/**
* @file
*
* INET v6 addresses.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
#include "lwip/opt.h"
#if LWIP_IPV6 && LWIP_SOCKET /* don't build if not configured for use in lwipopts.h */
#include "lwip/def.h"
#include "lwip/inet.h"
/** This variable is initialized by the system to contain the wildcard IPv6 address.
*/
const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
#endif /* LWIP_IPV6 */

File diff suppressed because it is too large Load Diff

View File

@ -1,355 +0,0 @@
/**
* @file
*
* IPv6 addresses.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
* Functions for handling IPv6 addresses.
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
#include "lwip/opt.h"
#if LWIP_IPV6 /* don't build if not configured for use in lwipopts.h */
#include "lwip/ip_addr.h"
#include "lwip/def.h"
#include "lwip/netif.h"
#include <string.h>
#if LWIP_IPV4
#include "lwip/ip4_addr.h" /* for ip6addr_aton to handle IPv4-mapped addresses */
#endif /* LWIP_IPV4 */
/* used by IP6_ADDR_ANY(6) in ip6_addr.h */
const ip_addr_t ip6_addr_any = IPADDR6_INIT(0ul, 0ul, 0ul, 0ul);
#define lwip_xchar(i) ((char)((i) < 10 ? '0' + (i) : 'A' + (i) - 10))
/**
* Check whether "cp" is a valid ascii representation
* of an IPv6 address and convert to a binary address.
* Returns 1 if the address is valid, 0 if not.
*
* @param cp IPv6 address in ascii representation (e.g. "FF01::1")
* @param addr pointer to which to save the ip address in network order
* @return 1 if cp could be converted to addr, 0 on failure
*/
int
ip6addr_aton(const char *cp, ip6_addr_t *addr)
{
u32_t addr_index, zero_blocks, current_block_index, current_block_value;
const char *s;
#if LWIP_IPV4
int check_ipv4_mapped = 0;
#endif /* LWIP_IPV4 */
/* Count the number of colons, to count the number of blocks in a "::" sequence
zero_blocks may be 1 even if there are no :: sequences */
zero_blocks = 8;
for (s = cp; *s != 0; s++) {
if (*s == ':') {
zero_blocks--;
#if LWIP_IPV4
} else if (*s == '.') {
if ((zero_blocks == 5) ||(zero_blocks == 2)) {
check_ipv4_mapped = 1;
/* last block could be the start of an IPv4 address */
zero_blocks--;
} else {
/* invalid format */
return 0;
}
break;
#endif /* LWIP_IPV4 */
} else if (!lwip_isxdigit(*s)) {
break;
}
}
/* parse each block */
addr_index = 0;
current_block_index = 0;
current_block_value = 0;
for (s = cp; *s != 0; s++) {
if (*s == ':') {
if (addr) {
if (current_block_index & 0x1) {
addr->addr[addr_index++] |= current_block_value;
}
else {
addr->addr[addr_index] = current_block_value << 16;
}
}
current_block_index++;
#if LWIP_IPV4
if (check_ipv4_mapped) {
if (current_block_index == 6) {
ip4_addr_t ip4;
int ret = ip4addr_aton(s + 1, &ip4);
if (ret) {
if (addr) {
addr->addr[3] = lwip_htonl(ip4.addr);
current_block_index++;
goto fix_byte_order_and_return;
}
return 1;
}
}
}
#endif /* LWIP_IPV4 */
current_block_value = 0;
if (current_block_index > 7) {
/* address too long! */
return 0;
}
if (s[1] == ':') {
if (s[2] == ':') {
/* invalid format: three successive colons */
return 0;
}
s++;
/* "::" found, set zeros */
while (zero_blocks > 0) {
zero_blocks--;
if (current_block_index & 0x1) {
addr_index++;
} else {
if (addr) {
addr->addr[addr_index] = 0;
}
}
current_block_index++;
if (current_block_index > 7) {
/* address too long! */
return 0;
}
}
}
} else if (lwip_isxdigit(*s)) {
/* add current digit */
current_block_value = (current_block_value << 4) +
(lwip_isdigit(*s) ? (u32_t)(*s - '0') :
(u32_t)(10 + (lwip_islower(*s) ? *s - 'a' : *s - 'A')));
} else {
/* unexpected digit, space? CRLF? */
break;
}
}
if (addr) {
if (current_block_index & 0x1) {
addr->addr[addr_index++] |= current_block_value;
}
else {
addr->addr[addr_index] = current_block_value << 16;
}
#if LWIP_IPV4
fix_byte_order_and_return:
#endif
/* convert to network byte order. */
for (addr_index = 0; addr_index < 4; addr_index++) {
addr->addr[addr_index] = lwip_htonl(addr->addr[addr_index]);
}
ip6_addr_clear_zone(addr);
#if LWIP_IPV6_SCOPES
if (*s == '%') {
const char *scopestr = s + 1;
if (*scopestr) {
struct netif *netif = netif_find(scopestr);
if (netif) {
ip6_addr_assign_zone(addr, IP6_UNKNOWN, netif);
}
}
}
#endif
}
if (current_block_index != 7) {
return 0;
}
return 1;
}
/**
* Convert numeric IPv6 address into ASCII representation.
* returns ptr to static buffer; not reentrant!
*
* @param addr ip6 address in network order to convert
* @return pointer to a global static (!) buffer that holds the ASCII
* representation of addr
*/
char *
ip6addr_ntoa(const ip6_addr_t *addr)
{
static char str[40];
return ip6addr_ntoa_r(addr, str, 40);
}
/**
* Same as ipaddr_ntoa, but reentrant since a user-supplied buffer is used.
*
* @param addr ip6 address in network order to convert
* @param buf target buffer where the string is stored
* @param buflen length of buf
* @return either pointer to buf which now holds the ASCII
* representation of addr or NULL if buf was too small
*/
char *
ip6addr_ntoa_r(const ip6_addr_t *addr, char *buf, int buflen)
{
u32_t current_block_index, current_block_value, next_block_value;
s32_t i;
u8_t zero_flag, empty_block_flag;
#if LWIP_IPV4
if (ip6_addr_isipv4mappedipv6(addr)) {
/* This is an IPv4 mapped address */
ip4_addr_t addr4;
char *ret;
#define IP4MAPPED_HEADER "::FFFF:"
char *buf_ip4 = buf + sizeof(IP4MAPPED_HEADER) - 1;
int buflen_ip4 = buflen - sizeof(IP4MAPPED_HEADER) + 1;
if (buflen < (int)sizeof(IP4MAPPED_HEADER)) {
return NULL;
}
memcpy(buf, IP4MAPPED_HEADER, sizeof(IP4MAPPED_HEADER));
addr4.addr = addr->addr[3];
ret = ip4addr_ntoa_r(&addr4, buf_ip4, buflen_ip4);
if (ret != buf_ip4) {
return NULL;
}
return buf;
}
#endif /* LWIP_IPV4 */
i = 0;
empty_block_flag = 0; /* used to indicate a zero chain for "::' */
for (current_block_index = 0; current_block_index < 8; current_block_index++) {
/* get the current 16-bit block */
current_block_value = lwip_htonl(addr->addr[current_block_index >> 1]);
if ((current_block_index & 0x1) == 0) {
current_block_value = current_block_value >> 16;
}
current_block_value &= 0xffff;
/* Check for empty block. */
if (current_block_value == 0) {
if (current_block_index == 7 && empty_block_flag == 1) {
/* special case, we must render a ':' for the last block. */
buf[i++] = ':';
if (i >= buflen) {
return NULL;
}
break;
}
if (empty_block_flag == 0) {
/* generate empty block "::", but only if more than one contiguous zero block,
* according to current formatting suggestions RFC 5952. */
next_block_value = lwip_htonl(addr->addr[(current_block_index + 1) >> 1]);
if ((current_block_index & 0x1) == 0x01) {
next_block_value = next_block_value >> 16;
}
next_block_value &= 0xffff;
if (next_block_value == 0) {
empty_block_flag = 1;
buf[i++] = ':';
if (i >= buflen) {
return NULL;
}
continue; /* move on to next block. */
}
} else if (empty_block_flag == 1) {
/* move on to next block. */
continue;
}
} else if (empty_block_flag == 1) {
/* Set this flag value so we don't produce multiple empty blocks. */
empty_block_flag = 2;
}
if (current_block_index > 0) {
buf[i++] = ':';
if (i >= buflen) {
return NULL;
}
}
if ((current_block_value & 0xf000) == 0) {
zero_flag = 1;
} else {
buf[i++] = lwip_xchar(((current_block_value & 0xf000) >> 12));
zero_flag = 0;
if (i >= buflen) {
return NULL;
}
}
if (((current_block_value & 0xf00) == 0) && (zero_flag)) {
/* do nothing */
} else {
buf[i++] = lwip_xchar(((current_block_value & 0xf00) >> 8));
zero_flag = 0;
if (i >= buflen) {
return NULL;
}
}
if (((current_block_value & 0xf0) == 0) && (zero_flag)) {
/* do nothing */
}
else {
buf[i++] = lwip_xchar(((current_block_value & 0xf0) >> 4));
zero_flag = 0;
if (i >= buflen) {
return NULL;
}
}
buf[i++] = lwip_xchar((current_block_value & 0xf));
if (i >= buflen) {
return NULL;
}
}
buf[i] = 0;
return buf;
}
#endif /* LWIP_IPV6 */

View File

@ -1,862 +0,0 @@
/**
* @file
*
* IPv6 fragmentation and reassembly.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
#include "lwip/opt.h"
#include "lwip/ip6_frag.h"
#include "lwip/ip6.h"
#include "lwip/icmp6.h"
#include "lwip/nd6.h"
#include "lwip/ip.h"
#include "lwip/pbuf.h"
#include "lwip/memp.h"
#include "lwip/stats.h"
#include <string.h>
#if LWIP_IPV6 && LWIP_IPV6_REASS /* don't build if not configured for use in lwipopts.h */
/** Setting this to 0, you can turn off checking the fragments for overlapping
* regions. The code gets a little smaller. Only use this if you know that
* overlapping won't occur on your network! */
#ifndef IP_REASS_CHECK_OVERLAP
#define IP_REASS_CHECK_OVERLAP 1
#endif /* IP_REASS_CHECK_OVERLAP */
/** Set to 0 to prevent freeing the oldest datagram when the reassembly buffer is
* full (IP_REASS_MAX_PBUFS pbufs are enqueued). The code gets a little smaller.
* Datagrams will be freed by timeout only. Especially useful when MEMP_NUM_REASSDATA
* is set to 1, so one datagram can be reassembled at a time, only. */
#ifndef IP_REASS_FREE_OLDEST
#define IP_REASS_FREE_OLDEST 1
#endif /* IP_REASS_FREE_OLDEST */
#if IPV6_FRAG_COPYHEADER
/* The number of bytes we need to "borrow" from (i.e., overwrite in) the header
* that precedes the fragment header for reassembly pruposes. */
#define IPV6_FRAG_REQROOM ((s16_t)(sizeof(struct ip6_reass_helper) - IP6_FRAG_HLEN))
#endif
#define IP_REASS_FLAG_LASTFRAG 0x01
/** This is a helper struct which holds the starting
* offset and the ending offset of this fragment to
* easily chain the fragments.
* It has the same packing requirements as the IPv6 header, since it replaces
* the Fragment Header in memory in incoming fragments to keep
* track of the various fragments.
*/
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct ip6_reass_helper {
PACK_STRUCT_FIELD(struct pbuf *next_pbuf);
PACK_STRUCT_FIELD(u16_t start);
PACK_STRUCT_FIELD(u16_t end);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/* static variables */
static struct ip6_reassdata *reassdatagrams;
static u16_t ip6_reass_pbufcount;
/* Forward declarations. */
static void ip6_reass_free_complete_datagram(struct ip6_reassdata *ipr);
#if IP_REASS_FREE_OLDEST
static void ip6_reass_remove_oldest_datagram(struct ip6_reassdata *ipr, int pbufs_needed);
#endif /* IP_REASS_FREE_OLDEST */
void
ip6_reass_tmr(void)
{
struct ip6_reassdata *r, *tmp;
#if !IPV6_FRAG_COPYHEADER
LWIP_ASSERT("sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN, set IPV6_FRAG_COPYHEADER to 1",
sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN);
#endif /* !IPV6_FRAG_COPYHEADER */
r = reassdatagrams;
while (r != NULL) {
/* Decrement the timer. Once it reaches 0,
* clean up the incomplete fragment assembly */
if (r->timer > 0) {
r->timer--;
r = r->next;
} else {
/* reassembly timed out */
tmp = r;
/* get the next pointer before freeing */
r = r->next;
/* free the helper struct and all enqueued pbufs */
ip6_reass_free_complete_datagram(tmp);
}
}
}
/**
* Free a datagram (struct ip6_reassdata) and all its pbufs.
* Updates the total count of enqueued pbufs (ip6_reass_pbufcount),
* sends an ICMP time exceeded packet.
*
* @param ipr datagram to free
*/
static void
ip6_reass_free_complete_datagram(struct ip6_reassdata *ipr)
{
struct ip6_reassdata *prev;
u16_t pbufs_freed = 0;
u16_t clen;
struct pbuf *p;
struct ip6_reass_helper *iprh;
#if LWIP_ICMP6
iprh = (struct ip6_reass_helper *)ipr->p->payload;
if (iprh->start == 0) {
/* The first fragment was received, send ICMP time exceeded. */
/* First, de-queue the first pbuf from r->p. */
p = ipr->p;
ipr->p = iprh->next_pbuf;
/* Restore the part that we've overwritten with our helper structure, or we
* might send garbage (and disclose a pointer) in the ICMPv6 reply. */
MEMCPY(p->payload, ipr->orig_hdr, sizeof(iprh));
/* Then, move back to the original ipv6 header (we are now pointing to Fragment header).
This cannot fail since we already checked when receiving this fragment. */
if (pbuf_header_force(p, (s16_t)((u8_t*)p->payload - (u8_t*)ipr->iphdr))) {
LWIP_ASSERT("ip6_reass_free: moving p->payload to ip6 header failed", 0);
}
else {
/* Reconstruct the zoned source and destination addresses, so that we do
* not end up sending the ICMP response over the wrong link. */
ip6_addr_t src_addr, dest_addr;
ip6_addr_copy_from_packed(src_addr, IPV6_FRAG_SRC(ipr));
ip6_addr_set_zone(&src_addr, ipr->src_zone);
ip6_addr_copy_from_packed(dest_addr, IPV6_FRAG_DEST(ipr));
ip6_addr_set_zone(&dest_addr, ipr->dest_zone);
/* Send the actual ICMP response. */
icmp6_time_exceeded_with_addrs(p, ICMP6_TE_FRAG, &src_addr, &dest_addr);
}
clen = pbuf_clen(p);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed = (u16_t)(pbufs_freed + clen);
pbuf_free(p);
}
#endif /* LWIP_ICMP6 */
/* First, free all received pbufs. The individual pbufs need to be released
separately as they have not yet been chained */
p = ipr->p;
while (p != NULL) {
struct pbuf *pcur;
iprh = (struct ip6_reass_helper *)p->payload;
pcur = p;
/* get the next pointer before freeing */
p = iprh->next_pbuf;
clen = pbuf_clen(pcur);
LWIP_ASSERT("pbufs_freed + clen <= 0xffff", pbufs_freed + clen <= 0xffff);
pbufs_freed = (u16_t)(pbufs_freed + clen);
pbuf_free(pcur);
}
/* Then, unchain the struct ip6_reassdata from the list and free it. */
if (ipr == reassdatagrams) {
reassdatagrams = ipr->next;
} else {
prev = reassdatagrams;
while (prev != NULL) {
if (prev->next == ipr) {
break;
}
prev = prev->next;
}
if (prev != NULL) {
prev->next = ipr->next;
}
}
memp_free(MEMP_IP6_REASSDATA, ipr);
/* Finally, update number of pbufs in reassembly queue */
LWIP_ASSERT("ip_reass_pbufcount >= clen", ip6_reass_pbufcount >= pbufs_freed);
ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount - pbufs_freed);
}
#if IP_REASS_FREE_OLDEST
/**
* Free the oldest datagram to make room for enqueueing new fragments.
* The datagram ipr is not freed!
*
* @param ipr ip6_reassdata for the current fragment
* @param pbufs_needed number of pbufs needed to enqueue
* (used for freeing other datagrams if not enough space)
*/
static void
ip6_reass_remove_oldest_datagram(struct ip6_reassdata *ipr, int pbufs_needed)
{
struct ip6_reassdata *r, *oldest;
/* Free datagrams until being allowed to enqueue 'pbufs_needed' pbufs,
* but don't free the current datagram! */
do {
r = oldest = reassdatagrams;
while (r != NULL) {
if (r != ipr) {
if (r->timer <= oldest->timer) {
/* older than the previous oldest */
oldest = r;
}
}
r = r->next;
}
if (oldest == ipr) {
/* nothing to free, ipr is the only element on the list */
return;
}
if (oldest != NULL) {
ip6_reass_free_complete_datagram(oldest);
}
} while (((ip6_reass_pbufcount + pbufs_needed) > IP_REASS_MAX_PBUFS) && (reassdatagrams != NULL));
}
#endif /* IP_REASS_FREE_OLDEST */
/**
* Reassembles incoming IPv6 fragments into an IPv6 datagram.
*
* @param p points to the IPv6 Fragment Header
* @return NULL if reassembly is incomplete, pbuf pointing to
* IPv6 Header if reassembly is complete
*/
struct pbuf *
ip6_reass(struct pbuf *p)
{
struct ip6_reassdata *ipr, *ipr_prev;
struct ip6_reass_helper *iprh, *iprh_tmp, *iprh_prev=NULL;
struct ip6_frag_hdr *frag_hdr;
u16_t offset, len, start, end;
ptrdiff_t hdrdiff;
u16_t clen;
u8_t valid = 1;
struct pbuf *q, *next_pbuf;
IP6_FRAG_STATS_INC(ip6_frag.recv);
/* ip6_frag_hdr must be in the first pbuf, not chained. Checked by caller. */
LWIP_ASSERT("IPv6 fragment header does not fit in first pbuf",
p->len >= sizeof(struct ip6_frag_hdr));
frag_hdr = (struct ip6_frag_hdr *) p->payload;
clen = pbuf_clen(p);
offset = lwip_ntohs(frag_hdr->_fragment_offset);
/* Calculate fragment length from IPv6 payload length.
* Adjust for headers before Fragment Header.
* And finally adjust by Fragment Header length. */
len = lwip_ntohs(ip6_current_header()->_plen);
hdrdiff = (u8_t*)p->payload - (const u8_t*)ip6_current_header();
LWIP_ASSERT("not a valid pbuf (ip6_input check missing?)", hdrdiff <= 0xFFFF);
LWIP_ASSERT("not a valid pbuf (ip6_input check missing?)", hdrdiff >= IP6_HLEN);
hdrdiff -= IP6_HLEN;
hdrdiff += IP6_FRAG_HLEN;
if (hdrdiff > len) {
IP6_FRAG_STATS_INC(ip6_frag.proterr);
goto nullreturn;
}
len = (u16_t)(len - hdrdiff);
start = (offset & IP6_FRAG_OFFSET_MASK);
if (start > (0xFFFF - len)) {
/* u16_t overflow, cannot handle this */
IP6_FRAG_STATS_INC(ip6_frag.proterr);
goto nullreturn;
}
/* Look for the datagram the fragment belongs to in the current datagram queue,
* remembering the previous in the queue for later dequeueing. */
for (ipr = reassdatagrams, ipr_prev = NULL; ipr != NULL; ipr = ipr->next) {
/* Check if the incoming fragment matches the one currently present
in the reassembly buffer. If so, we proceed with copying the
fragment into the buffer. */
if ((frag_hdr->_identification == ipr->identification) &&
ip6_addr_packed_eq(ip6_current_src_addr(), &(IPV6_FRAG_SRC(ipr)), ipr->src_zone) &&
ip6_addr_packed_eq(ip6_current_dest_addr(), &(IPV6_FRAG_DEST(ipr)), ipr->dest_zone)) {
IP6_FRAG_STATS_INC(ip6_frag.cachehit);
break;
}
ipr_prev = ipr;
}
if (ipr == NULL) {
/* Enqueue a new datagram into the datagram queue */
ipr = (struct ip6_reassdata *)memp_malloc(MEMP_IP6_REASSDATA);
if (ipr == NULL) {
#if IP_REASS_FREE_OLDEST
/* Make room and try again. */
ip6_reass_remove_oldest_datagram(ipr, clen);
ipr = (struct ip6_reassdata *)memp_malloc(MEMP_IP6_REASSDATA);
if (ipr != NULL) {
/* re-search ipr_prev since it might have been removed */
for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
if (ipr_prev->next == ipr) {
break;
}
}
} else
#endif /* IP_REASS_FREE_OLDEST */
{
IP6_FRAG_STATS_INC(ip6_frag.memerr);
goto nullreturn;
}
}
memset(ipr, 0, sizeof(struct ip6_reassdata));
ipr->timer = IPV6_REASS_MAXAGE;
/* enqueue the new structure to the front of the list */
ipr->next = reassdatagrams;
reassdatagrams = ipr;
/* Use the current IPv6 header for src/dest address reference.
* Eventually, we will replace it when we get the first fragment
* (it might be this one, in any case, it is done later). */
/* need to use the none-const pointer here: */
ipr->iphdr = ip_data.current_ip6_header;
#if IPV6_FRAG_COPYHEADER
MEMCPY(&ipr->src, &ip6_current_header()->src, sizeof(ipr->src));
MEMCPY(&ipr->dest, &ip6_current_header()->dest, sizeof(ipr->dest));
#endif /* IPV6_FRAG_COPYHEADER */
#if LWIP_IPV6_SCOPES
/* Also store the address zone information.
* @todo It is possible that due to netif destruction and recreation, the
* stored zones end up resolving to a different interface. In that case, we
* risk sending a "time exceeded" ICMP response over the wrong link.
* Ideally, netif destruction would clean up matching pending reassembly
* structures, but custom zone mappings would make that non-trivial. */
ipr->src_zone = ip6_addr_zone(ip6_current_src_addr());
ipr->dest_zone = ip6_addr_zone(ip6_current_dest_addr());
#endif /* LWIP_IPV6_SCOPES */
/* copy the fragmented packet id. */
ipr->identification = frag_hdr->_identification;
/* copy the nexth field */
ipr->nexth = frag_hdr->_nexth;
}
/* Check if we are allowed to enqueue more datagrams. */
if ((ip6_reass_pbufcount + clen) > IP_REASS_MAX_PBUFS) {
#if IP_REASS_FREE_OLDEST
ip6_reass_remove_oldest_datagram(ipr, clen);
if ((ip6_reass_pbufcount + clen) <= IP_REASS_MAX_PBUFS) {
/* re-search ipr_prev since it might have been removed */
for (ipr_prev = reassdatagrams; ipr_prev != NULL; ipr_prev = ipr_prev->next) {
if (ipr_prev->next == ipr) {
break;
}
}
} else
#endif /* IP_REASS_FREE_OLDEST */
{
/* @todo: send ICMPv6 time exceeded here? */
/* drop this pbuf */
IP6_FRAG_STATS_INC(ip6_frag.memerr);
goto nullreturn;
}
}
/* Overwrite Fragment Header with our own helper struct. */
#if IPV6_FRAG_COPYHEADER
if (IPV6_FRAG_REQROOM > 0) {
/* Make room for struct ip6_reass_helper (only required if sizeof(void*) > 4).
This cannot fail since we already checked when receiving this fragment. */
u8_t hdrerr = pbuf_header_force(p, IPV6_FRAG_REQROOM);
LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
}
#else /* IPV6_FRAG_COPYHEADER */
LWIP_ASSERT("sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN, set IPV6_FRAG_COPYHEADER to 1",
sizeof(struct ip6_reass_helper) <= IP6_FRAG_HLEN);
#endif /* IPV6_FRAG_COPYHEADER */
/* Prepare the pointer to the helper structure, and its initial values.
* Do not yet write to the structure itself, as we still have to make a
* backup of the original data, and we should not do that until we know for
* sure that we are going to add this packet to the list. */
iprh = (struct ip6_reass_helper *)p->payload;
next_pbuf = NULL;
end = (u16_t)(start + len);
/* find the right place to insert this pbuf */
/* Iterate through until we either get to the end of the list (append),
* or we find on with a larger offset (insert). */
for (q = ipr->p; q != NULL;) {
iprh_tmp = (struct ip6_reass_helper*)q->payload;
if (start < iprh_tmp->start) {
#if IP_REASS_CHECK_OVERLAP
if (end > iprh_tmp->start) {
/* fragment overlaps with following, throw away */
IP6_FRAG_STATS_INC(ip6_frag.proterr);
goto nullreturn;
}
if (iprh_prev != NULL) {
if (start < iprh_prev->end) {
/* fragment overlaps with previous, throw away */
IP6_FRAG_STATS_INC(ip6_frag.proterr);
goto nullreturn;
}
}
#endif /* IP_REASS_CHECK_OVERLAP */
/* the new pbuf should be inserted before this */
next_pbuf = q;
if (iprh_prev != NULL) {
/* not the fragment with the lowest offset */
iprh_prev->next_pbuf = p;
} else {
/* fragment with the lowest offset */
ipr->p = p;
}
break;
} else if (start == iprh_tmp->start) {
/* received the same datagram twice: no need to keep the datagram */
goto nullreturn;
#if IP_REASS_CHECK_OVERLAP
} else if (start < iprh_tmp->end) {
/* overlap: no need to keep the new datagram */
IP6_FRAG_STATS_INC(ip6_frag.proterr);
goto nullreturn;
#endif /* IP_REASS_CHECK_OVERLAP */
} else {
/* Check if the fragments received so far have no gaps. */
if (iprh_prev != NULL) {
if (iprh_prev->end != iprh_tmp->start) {
/* There is a fragment missing between the current
* and the previous fragment */
valid = 0;
}
}
}
q = iprh_tmp->next_pbuf;
iprh_prev = iprh_tmp;
}
/* If q is NULL, then we made it to the end of the list. Determine what to do now */
if (q == NULL) {
if (iprh_prev != NULL) {
/* this is (for now), the fragment with the highest offset:
* chain it to the last fragment */
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("check fragments don't overlap", iprh_prev->end <= start);
#endif /* IP_REASS_CHECK_OVERLAP */
iprh_prev->next_pbuf = p;
if (iprh_prev->end != start) {
valid = 0;
}
} else {
#if IP_REASS_CHECK_OVERLAP
LWIP_ASSERT("no previous fragment, this must be the first fragment!",
ipr->p == NULL);
#endif /* IP_REASS_CHECK_OVERLAP */
/* this is the first fragment we ever received for this ip datagram */
ipr->p = p;
}
}
/* Track the current number of pbufs current 'in-flight', in order to limit
the number of fragments that may be enqueued at any one time */
ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount + clen);
/* Remember IPv6 header if this is the first fragment. */
if (start == 0) {
/* need to use the none-const pointer here: */
ipr->iphdr = ip_data.current_ip6_header;
/* Make a backup of the part of the packet data that we are about to
* overwrite, so that we can restore the original later. */
MEMCPY(ipr->orig_hdr, p->payload, sizeof(*iprh));
/* For IPV6_FRAG_COPYHEADER there is no need to copy src/dst again, as they
* will be the same as they were. With LWIP_IPV6_SCOPES, the same applies
* to the source/destination zones. */
}
/* Only after the backup do we get to fill in the actual helper structure. */
iprh->next_pbuf = next_pbuf;
iprh->start = start;
iprh->end = end;
/* If this is the last fragment, calculate total packet length. */
if ((offset & IP6_FRAG_MORE_FLAG) == 0) {
ipr->datagram_len = iprh->end;
}
/* Additional validity tests: we have received first and last fragment. */
iprh_tmp = (struct ip6_reass_helper*)ipr->p->payload;
if (iprh_tmp->start != 0) {
valid = 0;
}
if (ipr->datagram_len == 0) {
valid = 0;
}
/* Final validity test: no gaps between current and last fragment. */
iprh_prev = iprh;
q = iprh->next_pbuf;
while ((q != NULL) && valid) {
iprh = (struct ip6_reass_helper*)q->payload;
if (iprh_prev->end != iprh->start) {
valid = 0;
break;
}
iprh_prev = iprh;
q = iprh->next_pbuf;
}
if (valid) {
/* All fragments have been received */
struct ip6_hdr* iphdr_ptr;
/* chain together the pbufs contained within the ip6_reassdata list. */
iprh = (struct ip6_reass_helper*) ipr->p->payload;
while (iprh != NULL) {
next_pbuf = iprh->next_pbuf;
if (next_pbuf != NULL) {
/* Save next helper struct (will be hidden in next step). */
iprh_tmp = (struct ip6_reass_helper*)next_pbuf->payload;
/* hide the fragment header for every succeeding fragment */
pbuf_remove_header(next_pbuf, IP6_FRAG_HLEN);
#if IPV6_FRAG_COPYHEADER
if (IPV6_FRAG_REQROOM > 0) {
/* hide the extra bytes borrowed from ip6_hdr for struct ip6_reass_helper */
u8_t hdrerr = pbuf_remove_header(next_pbuf, IPV6_FRAG_REQROOM);
LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
}
#endif
pbuf_cat(ipr->p, next_pbuf);
}
else {
iprh_tmp = NULL;
}
iprh = iprh_tmp;
}
/* Get the first pbuf. */
p = ipr->p;
#if IPV6_FRAG_COPYHEADER
if (IPV6_FRAG_REQROOM > 0) {
u8_t hdrerr;
/* Restore (only) the bytes that we overwrote beyond the fragment header.
* Those bytes may belong to either the IPv6 header or an extension
* header placed before the fragment header. */
MEMCPY(p->payload, ipr->orig_hdr, IPV6_FRAG_REQROOM);
/* get back room for struct ip6_reass_helper (only required if sizeof(void*) > 4) */
hdrerr = pbuf_remove_header(p, IPV6_FRAG_REQROOM);
LWIP_UNUSED_ARG(hdrerr); /* in case of LWIP_NOASSERT */
LWIP_ASSERT("no room for struct ip6_reass_helper", hdrerr == 0);
}
#endif
/* We need to get rid of the fragment header itself, which is somewhere in
* the middle of the packet (but still in the first pbuf of the chain).
* Getting rid of the header is required by RFC 2460 Sec. 4.5 and necessary
* in order to be able to reassemble packets that are close to full size
* (i.e., around 65535 bytes). We simply move up all the headers before the
* fragment header, including the IPv6 header, and adjust the payload start
* accordingly. This works because all these headers are in the first pbuf
* of the chain, and because the caller adjusts all its pointers on
* successful reassembly. */
MEMMOVE((u8_t*)ipr->iphdr + sizeof(struct ip6_frag_hdr), ipr->iphdr,
(size_t)((u8_t*)p->payload - (u8_t*)ipr->iphdr));
/* This is where the IPv6 header is now. */
iphdr_ptr = (struct ip6_hdr*)((u8_t*)ipr->iphdr +
sizeof(struct ip6_frag_hdr));
/* Adjust datagram length by adding header lengths. */
ipr->datagram_len = (u16_t)(ipr->datagram_len + ((u8_t*)p->payload - (u8_t*)iphdr_ptr)
- IP6_HLEN);
/* Set payload length in ip header. */
iphdr_ptr->_plen = lwip_htons(ipr->datagram_len);
/* With the fragment header gone, we now need to adjust the next-header
* field of whatever header was originally before it. Since the packet made
* it through the original header processing routines at least up to the
* fragment header, we do not need any further sanity checks here. */
if (IP6H_NEXTH(iphdr_ptr) == IP6_NEXTH_FRAGMENT) {
iphdr_ptr->_nexth = ipr->nexth;
} else {
u8_t *ptr = (u8_t *)iphdr_ptr + IP6_HLEN;
while (*ptr != IP6_NEXTH_FRAGMENT) {
ptr += 8 * (1 + ptr[1]);
}
*ptr = ipr->nexth;
}
/* release the resources allocated for the fragment queue entry */
if (reassdatagrams == ipr) {
/* it was the first in the list */
reassdatagrams = ipr->next;
} else {
/* it wasn't the first, so it must have a valid 'prev' */
LWIP_ASSERT("sanity check linked list", ipr_prev != NULL);
ipr_prev->next = ipr->next;
}
memp_free(MEMP_IP6_REASSDATA, ipr);
/* adjust the number of pbufs currently queued for reassembly. */
clen = pbuf_clen(p);
LWIP_ASSERT("ip6_reass_pbufcount >= clen", ip6_reass_pbufcount >= clen);
ip6_reass_pbufcount = (u16_t)(ip6_reass_pbufcount - clen);
/* Move pbuf back to IPv6 header. This should never fail. */
if (pbuf_header_force(p, (s16_t)((u8_t*)p->payload - (u8_t*)iphdr_ptr))) {
LWIP_ASSERT("ip6_reass: moving p->payload to ip6 header failed", 0);
pbuf_free(p);
return NULL;
}
/* Return the pbuf chain */
return p;
}
/* the datagram is not (yet?) reassembled completely */
return NULL;
nullreturn:
IP6_FRAG_STATS_INC(ip6_frag.drop);
pbuf_free(p);
return NULL;
}
#endif /* LWIP_IPV6 && LWIP_IPV6_REASS */
#if LWIP_IPV6 && LWIP_IPV6_FRAG
#if !LWIP_NETIF_TX_SINGLE_PBUF
/** Allocate a new struct pbuf_custom_ref */
static struct pbuf_custom_ref*
ip6_frag_alloc_pbuf_custom_ref(void)
{
return (struct pbuf_custom_ref*)memp_malloc(MEMP_FRAG_PBUF);
}
/** Free a struct pbuf_custom_ref */
static void
ip6_frag_free_pbuf_custom_ref(struct pbuf_custom_ref* p)
{
LWIP_ASSERT("p != NULL", p != NULL);
memp_free(MEMP_FRAG_PBUF, p);
}
/** Free-callback function to free a 'struct pbuf_custom_ref', called by
* pbuf_free. */
static void
ip6_frag_free_pbuf_custom(struct pbuf *p)
{
struct pbuf_custom_ref *pcr = (struct pbuf_custom_ref*)p;
LWIP_ASSERT("pcr != NULL", pcr != NULL);
LWIP_ASSERT("pcr == p", (void*)pcr == (void*)p);
if (pcr->original != NULL) {
pbuf_free(pcr->original);
}
ip6_frag_free_pbuf_custom_ref(pcr);
}
#endif /* !LWIP_NETIF_TX_SINGLE_PBUF */
/**
* Fragment an IPv6 datagram if too large for the netif or path MTU.
*
* Chop the datagram in MTU sized chunks and send them in order
* by pointing PBUF_REFs into p
*
* @param p ipv6 packet to send
* @param netif the netif on which to send
* @param dest destination ipv6 address to which to send
*
* @return ERR_OK if sent successfully, err_t otherwise
*/
err_t
ip6_frag(struct pbuf *p, struct netif *netif, const ip6_addr_t *dest)
{
struct ip6_hdr *original_ip6hdr;
struct ip6_hdr *ip6hdr;
struct ip6_frag_hdr *frag_hdr;
struct pbuf *rambuf;
#if !LWIP_NETIF_TX_SINGLE_PBUF
struct pbuf *newpbuf;
u16_t newpbuflen = 0;
u16_t left_to_copy;
#endif
static u32_t identification;
u16_t left, cop;
const u16_t mtu = nd6_get_destination_mtu(dest, netif);
const u16_t nfb = (u16_t)((mtu - (IP6_HLEN + IP6_FRAG_HLEN)) & IP6_FRAG_OFFSET_MASK);
u16_t fragment_offset = 0;
u16_t last;
u16_t poff = IP6_HLEN;
identification++;
original_ip6hdr = (struct ip6_hdr *)p->payload;
/* @todo we assume there are no options in the unfragmentable part (IPv6 header). */
LWIP_ASSERT("p->tot_len >= IP6_HLEN", p->tot_len >= IP6_HLEN);
left = (u16_t)(p->tot_len - IP6_HLEN);
while (left) {
last = (left <= nfb);
/* Fill this fragment */
cop = last ? left : nfb;
#if LWIP_NETIF_TX_SINGLE_PBUF
rambuf = pbuf_alloc(PBUF_IP, cop + IP6_FRAG_HLEN, PBUF_RAM);
if (rambuf == NULL) {
IP6_FRAG_STATS_INC(ip6_frag.memerr);
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(rambuf->len == rambuf->tot_len) && (rambuf->next == NULL));
poff += pbuf_copy_partial(p, (u8_t*)rambuf->payload + IP6_FRAG_HLEN, cop, poff);
/* make room for the IP header */
if (pbuf_add_header(rambuf, IP6_HLEN)) {
pbuf_free(rambuf);
IP6_FRAG_STATS_INC(ip6_frag.memerr);
return ERR_MEM;
}
/* fill in the IP header */
SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
ip6hdr = (struct ip6_hdr *)rambuf->payload;
frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
#else
/* When not using a static buffer, create a chain of pbufs.
* The first will be a PBUF_RAM holding the link, IPv6, and Fragment header.
* The rest will be PBUF_REFs mirroring the pbuf chain to be fragged,
* but limited to the size of an mtu.
*/
rambuf = pbuf_alloc(PBUF_LINK, IP6_HLEN + IP6_FRAG_HLEN, PBUF_RAM);
if (rambuf == NULL) {
IP6_FRAG_STATS_INC(ip6_frag.memerr);
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece!",
(rambuf->len >= (IP6_HLEN)));
SMEMCPY(rambuf->payload, original_ip6hdr, IP6_HLEN);
ip6hdr = (struct ip6_hdr *)rambuf->payload;
frag_hdr = (struct ip6_frag_hdr *)((u8_t*)rambuf->payload + IP6_HLEN);
/* Can just adjust p directly for needed offset. */
p->payload = (u8_t *)p->payload + poff;
p->len = (u16_t)(p->len - poff);
p->tot_len = (u16_t)(p->tot_len - poff);
left_to_copy = cop;
while (left_to_copy) {
struct pbuf_custom_ref *pcr;
newpbuflen = (left_to_copy < p->len) ? left_to_copy : p->len;
/* Is this pbuf already empty? */
if (!newpbuflen) {
p = p->next;
continue;
}
pcr = ip6_frag_alloc_pbuf_custom_ref();
if (pcr == NULL) {
pbuf_free(rambuf);
IP6_FRAG_STATS_INC(ip6_frag.memerr);
return ERR_MEM;
}
/* Mirror this pbuf, although we might not need all of it. */
newpbuf = pbuf_alloced_custom(PBUF_RAW, newpbuflen, PBUF_REF, &pcr->pc, p->payload, newpbuflen);
if (newpbuf == NULL) {
ip6_frag_free_pbuf_custom_ref(pcr);
pbuf_free(rambuf);
IP6_FRAG_STATS_INC(ip6_frag.memerr);
return ERR_MEM;
}
pbuf_ref(p);
pcr->original = p;
pcr->pc.custom_free_function = ip6_frag_free_pbuf_custom;
/* Add it to end of rambuf's chain, but using pbuf_cat, not pbuf_chain
* so that it is removed when pbuf_dechain is later called on rambuf.
*/
pbuf_cat(rambuf, newpbuf);
left_to_copy = (u16_t)(left_to_copy - newpbuflen);
if (left_to_copy) {
p = p->next;
}
}
poff = newpbuflen;
#endif /* LWIP_NETIF_TX_SINGLE_PBUF */
/* Set headers */
frag_hdr->_nexth = original_ip6hdr->_nexth;
frag_hdr->reserved = 0;
frag_hdr->_fragment_offset = lwip_htons((u16_t)((fragment_offset & IP6_FRAG_OFFSET_MASK) | (last ? 0 : IP6_FRAG_MORE_FLAG)));
frag_hdr->_identification = lwip_htonl(identification);
IP6H_NEXTH_SET(ip6hdr, IP6_NEXTH_FRAGMENT);
IP6H_PLEN_SET(ip6hdr, (u16_t)(cop + IP6_FRAG_HLEN));
/* No need for separate header pbuf - we allowed room for it in rambuf
* when allocated.
*/
IP6_FRAG_STATS_INC(ip6_frag.xmit);
netif->output_ip6(netif, rambuf, dest);
/* Unfortunately we can't reuse rambuf - the hardware may still be
* using the buffer. Instead we free it (and the ensuing chain) and
* recreate it next time round the loop. If we're lucky the hardware
* will have already sent the packet, the free will really free, and
* there will be zero memory penalty.
*/
pbuf_free(rambuf);
left = (u16_t)(left - cop);
fragment_offset = (u16_t)(fragment_offset + cop);
}
return ERR_OK;
}
#endif /* LWIP_IPV6 && LWIP_IPV6_FRAG */

View File

@ -1,626 +0,0 @@
/**
* @file
* Multicast listener discovery
*
* @defgroup mld6 MLD6
* @ingroup ip6
* Multicast listener discovery for IPv6. Aims to be compliant with RFC 2710.
* No support for MLDv2.<br>
* Note: The allnodes (ff01::1, ff02::1) group is assumed be received by your
* netif since it must always be received for correct IPv6 operation (e.g. SLAAC).
* Ensure the netif filters are configured accordingly!<br>
* The netif flags also need NETIF_FLAG_MLD6 flag set to enable MLD6 on a
* netif ("netif->flags |= NETIF_FLAG_MLD6;").<br>
* To be called from TCPIP thread.
*/
/*
* Copyright (c) 2010 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
/* Based on igmp.c implementation of igmp v2 protocol */
#include "lwip/opt.h"
#if LWIP_IPV6 && LWIP_IPV6_MLD /* don't build if not configured for use in lwipopts.h */
#include "lwip/mld6.h"
#include "lwip/prot/mld6.h"
#include "lwip/icmp6.h"
#include "lwip/ip6.h"
#include "lwip/ip6_addr.h"
#include "lwip/ip.h"
#include "lwip/inet_chksum.h"
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#include "lwip/memp.h"
#include "lwip/stats.h"
#include <string.h>
/*
* MLD constants
*/
#define MLD6_HL 1
#define MLD6_JOIN_DELAYING_MEMBER_TMR_MS (500)
#define MLD6_GROUP_NON_MEMBER 0
#define MLD6_GROUP_DELAYING_MEMBER 1
#define MLD6_GROUP_IDLE_MEMBER 2
/* Forward declarations. */
static struct mld_group *mld6_new_group(struct netif *ifp, const ip6_addr_t *addr);
static err_t mld6_remove_group(struct netif *netif, struct mld_group *group);
static void mld6_delayed_report(struct mld_group *group, u16_t maxresp);
static void mld6_send(struct netif *netif, struct mld_group *group, u8_t type);
/**
* Stop MLD processing on interface
*
* @param netif network interface on which stop MLD processing
*/
err_t
mld6_stop(struct netif *netif)
{
struct mld_group *group = netif_mld6_data(netif);
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, NULL);
while (group != NULL) {
struct mld_group *next = group->next; /* avoid use-after-free below */
/* disable the group at the MAC level */
if (netif->mld_mac_filter != NULL) {
netif->mld_mac_filter(netif, &(group->group_address), NETIF_DEL_MAC_FILTER);
}
/* free group */
memp_free(MEMP_MLD6_GROUP, group);
/* move to "next" */
group = next;
}
return ERR_OK;
}
/**
* Report MLD memberships for this interface
*
* @param netif network interface on which report MLD memberships
*/
void
mld6_report_groups(struct netif *netif)
{
struct mld_group *group = netif_mld6_data(netif);
while (group != NULL) {
mld6_delayed_report(group, MLD6_JOIN_DELAYING_MEMBER_TMR_MS);
group = group->next;
}
}
/**
* Search for a group that is joined on a netif
*
* @param ifp the network interface for which to look
* @param addr the group ipv6 address to search for
* @return a struct mld_group* if the group has been found,
* NULL if the group wasn't found.
*/
struct mld_group *
mld6_lookfor_group(struct netif *ifp, const ip6_addr_t *addr)
{
struct mld_group *group = netif_mld6_data(ifp);
while (group != NULL) {
if (ip6_addr_eq(&(group->group_address), addr)) {
return group;
}
group = group->next;
}
return NULL;
}
/**
* create a new group
*
* @param ifp the network interface for which to create
* @param addr the new group ipv6
* @return a struct mld_group*,
* NULL on memory error.
*/
static struct mld_group *
mld6_new_group(struct netif *ifp, const ip6_addr_t *addr)
{
struct mld_group *group;
group = (struct mld_group *)memp_malloc(MEMP_MLD6_GROUP);
if (group != NULL) {
ip6_addr_set(&(group->group_address), addr);
group->timer = 0; /* Not running */
group->group_state = MLD6_GROUP_IDLE_MEMBER;
group->last_reporter_flag = 0;
group->use = 0;
group->next = netif_mld6_data(ifp);
netif_set_client_data(ifp, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, group);
}
return group;
}
/**
* Remove a group from the mld_group_list, but do not free it yet
*
* @param group the group to remove
* @return ERR_OK if group was removed from the list, an err_t otherwise
*/
static err_t
mld6_remove_group(struct netif *netif, struct mld_group *group)
{
err_t err = ERR_OK;
/* Is it the first group? */
if (netif_mld6_data(netif) == group) {
netif_set_client_data(netif, LWIP_NETIF_CLIENT_DATA_INDEX_MLD6, group->next);
} else {
/* look for group further down the list */
struct mld_group *tmpGroup;
for (tmpGroup = netif_mld6_data(netif); tmpGroup != NULL; tmpGroup = tmpGroup->next) {
if (tmpGroup->next == group) {
tmpGroup->next = group->next;
break;
}
}
/* Group not find group */
if (tmpGroup == NULL) {
err = ERR_ARG;
}
}
return err;
}
/**
* Process an input MLD message. Called by icmp6_input.
*
* @param p the mld packet, p->payload pointing to the icmpv6 header
* @param inp the netif on which this packet was received
*/
void
mld6_input(struct pbuf *p, struct netif *inp)
{
struct mld_header *mld_hdr;
struct mld_group *group;
MLD6_STATS_INC(mld6.recv);
/* Check that mld header fits in packet. */
if (p->len < sizeof(struct mld_header)) {
/* @todo debug message */
pbuf_free(p);
MLD6_STATS_INC(mld6.lenerr);
MLD6_STATS_INC(mld6.drop);
return;
}
mld_hdr = (struct mld_header *)p->payload;
switch (mld_hdr->type) {
case ICMP6_TYPE_MLQ: /* Multicast listener query. */
/* Is it a general query? */
if (ip6_addr_isallnodes_linklocal(ip6_current_dest_addr()) &&
ip6_addr_isany(&(mld_hdr->multicast_address))) {
MLD6_STATS_INC(mld6.rx_general);
/* Report all groups, except all nodes group, and if-local groups. */
group = netif_mld6_data(inp);
while (group != NULL) {
if ((!(ip6_addr_ismulticast_iflocal(&(group->group_address)))) &&
(!(ip6_addr_isallnodes_linklocal(&(group->group_address))))) {
mld6_delayed_report(group, lwip_ntohs(mld_hdr->max_resp_delay));
}
group = group->next;
}
} else {
/* Have we joined this group?
* We use IP6 destination address to have a memory aligned copy.
* mld_hdr->multicast_address should be the same. */
MLD6_STATS_INC(mld6.rx_group);
group = mld6_lookfor_group(inp, ip6_current_dest_addr());
if (group != NULL) {
/* Schedule a report. */
mld6_delayed_report(group, lwip_ntohs(mld_hdr->max_resp_delay));
}
}
break; /* ICMP6_TYPE_MLQ */
case ICMP6_TYPE_MLR: /* Multicast listener report. */
/* Have we joined this group?
* We use IP6 destination address to have a memory aligned copy.
* mld_hdr->multicast_address should be the same. */
MLD6_STATS_INC(mld6.rx_report);
group = mld6_lookfor_group(inp, ip6_current_dest_addr());
if (group != NULL) {
/* If we are waiting to report, cancel it. */
if (group->group_state == MLD6_GROUP_DELAYING_MEMBER) {
group->timer = 0; /* stopped */
group->group_state = MLD6_GROUP_IDLE_MEMBER;
group->last_reporter_flag = 0;
}
}
break; /* ICMP6_TYPE_MLR */
case ICMP6_TYPE_MLD: /* Multicast listener done. */
/* Do nothing, router will query us. */
break; /* ICMP6_TYPE_MLD */
default:
MLD6_STATS_INC(mld6.proterr);
MLD6_STATS_INC(mld6.drop);
break;
}
pbuf_free(p);
}
/**
* @ingroup mld6
* Join a group on one or all network interfaces.
*
* If the group is to be joined on all interfaces, the given group address must
* not have a zone set (i.e., it must have its zone index set to IP6_NO_ZONE).
* If the group is to be joined on one particular interface, the given group
* address may or may not have a zone set.
*
* @param srcaddr ipv6 address (zoned) of the network interface which should
* join a new group. If IP6_ADDR_ANY6, join on all netifs
* @param groupaddr the ipv6 address of the group to join (possibly but not
* necessarily zoned)
* @return ERR_OK if group was joined on the netif(s), an err_t otherwise
*/
err_t
mld6_joingroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr)
{
err_t err = ERR_VAL; /* no matching interface */
struct netif *netif;
LWIP_ASSERT_CORE_LOCKED();
/* loop through netif's */
NETIF_FOREACH(netif) {
/* Should we join this interface ? */
if (ip6_addr_isany(srcaddr) ||
netif_get_ip6_addr_match(netif, srcaddr) >= 0) {
err = mld6_joingroup_netif(netif, groupaddr);
if (err != ERR_OK) {
return err;
}
}
}
return err;
}
/**
* @ingroup mld6
* Join a group on a network interface.
*
* @param netif the network interface which should join a new group.
* @param groupaddr the ipv6 address of the group to join (possibly but not
* necessarily zoned)
* @return ERR_OK if group was joined on the netif, an err_t otherwise
*/
err_t
mld6_joingroup_netif(struct netif *netif, const ip6_addr_t *groupaddr)
{
struct mld_group *group;
#if LWIP_IPV6_SCOPES
ip6_addr_t ip6addr;
/* If the address has a particular scope but no zone set, use the netif to
* set one now. Within the mld6 module, all addresses are properly zoned. */
if (ip6_addr_lacks_zone(groupaddr, IP6_MULTICAST)) {
ip6_addr_set(&ip6addr, groupaddr);
ip6_addr_assign_zone(&ip6addr, IP6_MULTICAST, netif);
groupaddr = &ip6addr;
}
IP6_ADDR_ZONECHECK_NETIF(groupaddr, netif);
#endif /* LWIP_IPV6_SCOPES */
LWIP_ASSERT_CORE_LOCKED();
/* find group or create a new one if not found */
group = mld6_lookfor_group(netif, groupaddr);
if (group == NULL) {
/* Joining a new group. Create a new group entry. */
group = mld6_new_group(netif, groupaddr);
if (group == NULL) {
return ERR_MEM;
}
/* Activate this address on the MAC layer. */
if (netif->mld_mac_filter != NULL) {
netif->mld_mac_filter(netif, groupaddr, NETIF_ADD_MAC_FILTER);
}
/* Report our membership. */
MLD6_STATS_INC(mld6.tx_report);
mld6_send(netif, group, ICMP6_TYPE_MLR);
mld6_delayed_report(group, MLD6_JOIN_DELAYING_MEMBER_TMR_MS);
}
/* Increment group use */
group->use++;
return ERR_OK;
}
/**
* @ingroup mld6
* Leave a group on a network interface.
*
* Zoning of address follows the same rules as @ref mld6_joingroup.
*
* @param srcaddr ipv6 address (zoned) of the network interface which should
* leave the group. If IP6_ADDR_ANY6, leave on all netifs
* @param groupaddr the ipv6 address of the group to leave (possibly, but not
* necessarily zoned)
* @return ERR_OK if group was left on the netif(s), an err_t otherwise
*/
err_t
mld6_leavegroup(const ip6_addr_t *srcaddr, const ip6_addr_t *groupaddr)
{
err_t err = ERR_VAL; /* no matching interface */
struct netif *netif;
LWIP_ASSERT_CORE_LOCKED();
/* loop through netif's */
NETIF_FOREACH(netif) {
/* Should we leave this interface ? */
if (ip6_addr_isany(srcaddr) ||
netif_get_ip6_addr_match(netif, srcaddr) >= 0) {
err_t res = mld6_leavegroup_netif(netif, groupaddr);
if (err != ERR_OK) {
/* Store this result if we have not yet gotten a success */
err = res;
}
}
}
return err;
}
/**
* @ingroup mld6
* Leave a group on a network interface.
*
* @param netif the network interface which should leave the group.
* @param groupaddr the ipv6 address of the group to leave (possibly, but not
* necessarily zoned)
* @return ERR_OK if group was left on the netif, an err_t otherwise
*/
err_t
mld6_leavegroup_netif(struct netif *netif, const ip6_addr_t *groupaddr)
{
struct mld_group *group;
#if LWIP_IPV6_SCOPES
ip6_addr_t ip6addr;
if (ip6_addr_lacks_zone(groupaddr, IP6_MULTICAST)) {
ip6_addr_set(&ip6addr, groupaddr);
ip6_addr_assign_zone(&ip6addr, IP6_MULTICAST, netif);
groupaddr = &ip6addr;
}
IP6_ADDR_ZONECHECK_NETIF(groupaddr, netif);
#endif /* LWIP_IPV6_SCOPES */
LWIP_ASSERT_CORE_LOCKED();
/* find group */
group = mld6_lookfor_group(netif, groupaddr);
if (group != NULL) {
/* Leave if there is no other use of the group */
if (group->use <= 1) {
/* Remove the group from the list */
mld6_remove_group(netif, group);
/* If we are the last reporter for this group */
if (group->last_reporter_flag) {
MLD6_STATS_INC(mld6.tx_leave);
mld6_send(netif, group, ICMP6_TYPE_MLD);
}
/* Disable the group at the MAC level */
if (netif->mld_mac_filter != NULL) {
netif->mld_mac_filter(netif, groupaddr, NETIF_DEL_MAC_FILTER);
}
/* free group struct */
memp_free(MEMP_MLD6_GROUP, group);
} else {
/* Decrement group use */
group->use--;
}
/* Left group */
return ERR_OK;
}
/* Group not found */
return ERR_VAL;
}
/**
* Periodic timer for mld processing. Must be called every
* MLD6_TMR_INTERVAL milliseconds (100).
*
* When a delaying member expires, a membership report is sent.
*/
void
mld6_tmr(void)
{
struct netif *netif;
NETIF_FOREACH(netif) {
struct mld_group *group = netif_mld6_data(netif);
while (group != NULL) {
if (group->timer > 0) {
group->timer--;
if (group->timer == 0) {
/* If the state is MLD6_GROUP_DELAYING_MEMBER then we send a report for this group */
if (group->group_state == MLD6_GROUP_DELAYING_MEMBER) {
MLD6_STATS_INC(mld6.tx_report);
mld6_send(netif, group, ICMP6_TYPE_MLR);
group->group_state = MLD6_GROUP_IDLE_MEMBER;
}
}
}
group = group->next;
}
}
}
/**
* Schedule a delayed membership report for a group
*
* @param group the mld_group for which "delaying" membership report
* should be sent
* @param maxresp_in the max resp delay provided in the query
*/
static void
mld6_delayed_report(struct mld_group *group, u16_t maxresp_in)
{
/* Convert maxresp from milliseconds to tmr ticks */
u16_t maxresp = maxresp_in / MLD6_TMR_INTERVAL;
if (maxresp == 0) {
maxresp = 1;
}
#ifdef LWIP_RAND
/* Randomize maxresp. (if LWIP_RAND is supported) */
maxresp = (u16_t)(LWIP_RAND() % maxresp);
if (maxresp == 0) {
maxresp = 1;
}
#endif /* LWIP_RAND */
/* Apply timer value if no report has been scheduled already. */
if ((group->group_state == MLD6_GROUP_IDLE_MEMBER) ||
((group->group_state == MLD6_GROUP_DELAYING_MEMBER) &&
((group->timer == 0) || (maxresp < group->timer)))) {
group->timer = maxresp;
group->group_state = MLD6_GROUP_DELAYING_MEMBER;
}
}
/**
* Send a MLD message (report or done).
*
* An IPv6 hop-by-hop options header with a router alert option
* is prepended.
*
* @param group the group to report or quit
* @param type ICMP6_TYPE_MLR (report) or ICMP6_TYPE_MLD (done)
*/
static void
mld6_send(struct netif *netif, struct mld_group *group, u8_t type)
{
struct mld_header *mld_hdr;
struct pbuf *p;
const ip6_addr_t *src_addr;
/* Allocate a packet. Size is MLD header + IPv6 Hop-by-hop options header. */
p = pbuf_alloc(PBUF_IP, sizeof(struct mld_header) + MLD6_HBH_HLEN, PBUF_RAM);
if (p == NULL) {
MLD6_STATS_INC(mld6.memerr);
return;
}
/* Move to make room for Hop-by-hop options header. */
if (pbuf_remove_header(p, MLD6_HBH_HLEN)) {
pbuf_free(p);
MLD6_STATS_INC(mld6.lenerr);
return;
}
/* Select our source address. */
if (!ip6_addr_isvalid(netif_ip6_addr_state(netif, 0))) {
/* This is a special case, when we are performing duplicate address detection.
* We must join the multicast group, but we don't have a valid address yet. */
src_addr = IP6_ADDR_ANY6;
} else {
/* Use link-local address as source address. */
src_addr = netif_ip6_addr(netif, 0);
}
/* MLD message header pointer. */
mld_hdr = (struct mld_header *)p->payload;
/* Set fields. */
mld_hdr->type = type;
mld_hdr->code = 0;
mld_hdr->chksum = 0;
mld_hdr->max_resp_delay = 0;
mld_hdr->reserved = 0;
ip6_addr_copy_to_packed(mld_hdr->multicast_address, group->group_address);
#if CHECKSUM_GEN_ICMP6
IF__NETIF_CHECKSUM_ENABLED(netif, NETIF_CHECKSUM_GEN_ICMP6) {
mld_hdr->chksum = ip6_chksum_pseudo(p, IP6_NEXTH_ICMP6, p->len,
src_addr, &(group->group_address));
}
#endif /* CHECKSUM_GEN_ICMP6 */
/* Add hop-by-hop headers options: router alert with MLD value. */
ip6_options_add_hbh_ra(p, IP6_NEXTH_ICMP6, IP6_ROUTER_ALERT_VALUE_MLD);
if (type == ICMP6_TYPE_MLR) {
/* Remember we were the last to report */
group->last_reporter_flag = 1;
}
/* Send the packet out. */
MLD6_STATS_INC(mld6.xmit);
ip6_output_if(p, (ip6_addr_isany(src_addr)) ? NULL : src_addr, &(group->group_address),
MLD6_HL, 0, IP6_NEXTH_HOPBYHOP, netif);
pbuf_free(p);
}
#endif /* LWIP_IPV6 */

File diff suppressed because it is too large Load Diff

View File

@ -1,387 +0,0 @@
/**
* @file
* Modules initialization
*
*/
/*
* 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"
#include "lwip/lwip_init.h"
#include "lwip/stats.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/memp.h"
#include "lwip/pbuf.h"
#include "lwip/netif.h"
#include "lwip/sockets.h"
#include "lwip/ip.h"
#include "lwip/raw.h"
#include "lwip/udp.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/igmp.h"
#include "lwip/dns.h"
#include "lwip/timeouts.h"
#include "lwip/etharp.h"
#include "lwip/ip6.h"
#include "lwip/nd6.h"
#include "lwip/mld6.h"
#include "lwip/api.h"
#include "netif/ppp/ppp_opts.h"
#include "netif/ppp/ppp_impl.h"
#ifndef LWIP_SKIP_PACKING_CHECK
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct packed_struct_test {
PACK_STRUCT_FLD_8(u8_t dummy1);
PACK_STRUCT_FIELD(u32_t dummy2);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#define PACKED_STRUCT_TEST_EXPECTED_SIZE 5
#endif
/* Compile-time sanity checks for configuration errors.
* These can be done independently of LWIP_DEBUG, without penalty.
*/
#ifndef BYTE_ORDER
#error "BYTE_ORDER is not defined, you have to define it in your cc.h"
#endif
#if (!IP_SOF_BROADCAST && IP_SOF_BROADCAST_RECV)
#error "If you want to use broadcast filter per pcb on recv operations, you have to define IP_SOF_BROADCAST=1 in your lwipopts.h"
#endif
#if (!LWIP_UDP && LWIP_UDPLITE)
#error "If you want to use UDP Lite, you have to define LWIP_UDP=1 in your lwipopts.h"
#endif
#if (!LWIP_UDP && LWIP_DHCP)
#error "If you want to use DHCP, you have to define LWIP_UDP=1 in your lwipopts.h"
#endif
#if (!LWIP_UDP && !LWIP_RAW && LWIP_MULTICAST_TX_OPTIONS)
#error "If you want to use LWIP_MULTICAST_TX_OPTIONS, you have to define LWIP_UDP=1 and/or LWIP_RAW=1 in your lwipopts.h"
#endif
#if (!LWIP_UDP && LWIP_DNS)
#error "If you want to use DNS, you have to define LWIP_UDP=1 in your lwipopts.h"
#endif
#if !MEMP_MEM_MALLOC /* MEMP_NUM_* checks are disabled when not using the pool allocator */
#if (LWIP_ARP && ARP_QUEUEING && (MEMP_NUM_ARP_QUEUE<=0))
#error "If you want to use ARP Queueing, you have to define MEMP_NUM_ARP_QUEUE>=1 in your lwipopts.h"
#endif
#if (LWIP_RAW && (MEMP_NUM_RAW_PCB<=0))
#error "If you want to use RAW, you have to define MEMP_NUM_RAW_PCB>=1 in your lwipopts.h"
#endif
#if (LWIP_UDP && (MEMP_NUM_UDP_PCB<=0))
#error "If you want to use UDP, you have to define MEMP_NUM_UDP_PCB>=1 in your lwipopts.h"
#endif
#if (LWIP_TCP && (MEMP_NUM_TCP_PCB<=0))
#error "If you want to use TCP, you have to define MEMP_NUM_TCP_PCB>=1 in your lwipopts.h"
#endif
#if (LWIP_IGMP && (MEMP_NUM_IGMP_GROUP<=1))
#error "If you want to use IGMP, you have to define MEMP_NUM_IGMP_GROUP>1 in your lwipopts.h"
#endif
#if (LWIP_IGMP && !LWIP_MULTICAST_TX_OPTIONS)
#error "If you want to use IGMP, you have to define LWIP_MULTICAST_TX_OPTIONS==1 in your lwipopts.h"
#endif
#if (LWIP_IGMP && !LWIP_IPV4)
#error "IGMP needs LWIP_IPV4 enabled in your lwipopts.h"
#endif
#if ((LWIP_NETCONN || LWIP_SOCKET) && (MEMP_NUM_TCPIP_MSG_API<=0))
#error "If you want to use Sequential API, you have to define MEMP_NUM_TCPIP_MSG_API>=1 in your lwipopts.h"
#endif
/* There must be sufficient timeouts, taking into account requirements of the subsystems. */
#if LWIP_TIMERS && (MEMP_NUM_SYS_TIMEOUT < LWIP_NUM_SYS_TIMEOUT_INTERNAL)
#error "MEMP_NUM_SYS_TIMEOUT is too low to accommodate all required timeouts"
#endif
#if (IP_REASSEMBLY && (MEMP_NUM_REASSDATA > IP_REASS_MAX_PBUFS))
#error "MEMP_NUM_REASSDATA > IP_REASS_MAX_PBUFS doesn't make sense since each struct ip_reassdata must hold 2 pbufs at least!"
#endif
#endif /* !MEMP_MEM_MALLOC */
#if LWIP_WND_SCALE
#if (LWIP_TCP && (TCP_WND > 0xffffffff))
#error "If you want to use TCP, TCP_WND must fit in an u32_t, so, you have to reduce it in your lwipopts.h"
#endif
#if (LWIP_TCP && (TCP_RCV_SCALE > 14))
#error "The maximum valid window scale value is 14!"
#endif
#if (LWIP_TCP && (TCP_WND > (0xFFFFU << TCP_RCV_SCALE)))
#error "TCP_WND is bigger than the configured LWIP_WND_SCALE allows!"
#endif
#if (LWIP_TCP && ((TCP_WND >> TCP_RCV_SCALE) == 0))
#error "TCP_WND is too small for the configured LWIP_WND_SCALE (results in zero window)!"
#endif
#else /* LWIP_WND_SCALE */
#if (LWIP_TCP && (TCP_WND > 0xffff))
#error "If you want to use TCP, TCP_WND must fit in an u16_t, so, you have to reduce it in your lwipopts.h (or enable window scaling)"
#endif
#endif /* LWIP_WND_SCALE */
#if (LWIP_TCP && (TCP_SND_QUEUELEN > 0xffff))
#error "If you want to use TCP, TCP_SND_QUEUELEN must fit in an u16_t, so, you have to reduce it in your lwipopts.h"
#endif
#if (LWIP_TCP && (TCP_SND_QUEUELEN < 2))
#error "TCP_SND_QUEUELEN must be at least 2 for no-copy TCP writes to work"
#endif
#if (LWIP_TCP && ((TCP_MAXRTX > 12) || (TCP_SYNMAXRTX > 12)))
#error "If you want to use TCP, TCP_MAXRTX and TCP_SYNMAXRTX must less or equal to 12 (due to tcp_backoff table), so, you have to reduce them in your lwipopts.h"
#endif
#if (LWIP_TCP && TCP_LISTEN_BACKLOG && ((TCP_DEFAULT_LISTEN_BACKLOG < 0) || (TCP_DEFAULT_LISTEN_BACKLOG > 0xff)))
#error "If you want to use TCP backlog, TCP_DEFAULT_LISTEN_BACKLOG must fit into an u8_t"
#endif
#if (LWIP_TCP && LWIP_TCP_SACK_OUT && !TCP_QUEUE_OOSEQ)
#error "To use LWIP_TCP_SACK_OUT, TCP_QUEUE_OOSEQ needs to be enabled"
#endif
#if (LWIP_TCP && LWIP_TCP_SACK_OUT && (LWIP_TCP_MAX_SACK_NUM < 1))
#error "LWIP_TCP_MAX_SACK_NUM must be greater than 0"
#endif
#if (LWIP_NETIF_API && (NO_SYS==1))
#error "If you want to use NETIF API, you have to define NO_SYS=0 in your lwipopts.h"
#endif
#if ((LWIP_SOCKET || LWIP_NETCONN) && (NO_SYS==1))
#error "If you want to use Sequential API, you have to define NO_SYS=0 in your lwipopts.h"
#endif
#if (LWIP_PPP_API && (NO_SYS==1))
#error "If you want to use PPP API, you have to define NO_SYS=0 in your lwipopts.h"
#endif
#if (LWIP_PPP_API && (PPP_SUPPORT==0))
#error "If you want to use PPP API, you have to enable PPP_SUPPORT in your lwipopts.h"
#endif
#if (((!LWIP_DHCP) || (!LWIP_AUTOIP)) && LWIP_DHCP_AUTOIP_COOP)
#error "If you want to use DHCP/AUTOIP cooperation mode, you have to define LWIP_DHCP=1 and LWIP_AUTOIP=1 in your lwipopts.h"
#endif
#if (((!LWIP_DHCP) || (!LWIP_ARP) || (!LWIP_ACD)) && LWIP_DHCP_DOES_ACD_CHECK)
#error "If you want to use DHCP ACD checking, you have to define LWIP_DHCP=1, LWIP_ARP=1 and LWIP_ACD=1 in your lwipopts.h"
#endif
#if (!LWIP_ARP && LWIP_AUTOIP)
#error "If you want to use AUTOIP, you have to define LWIP_ARP=1 in your lwipopts.h"
#endif
#if (LWIP_TCP && ((LWIP_EVENT_API && LWIP_CALLBACK_API) || (!LWIP_EVENT_API && !LWIP_CALLBACK_API)))
#error "One and exactly one of LWIP_EVENT_API and LWIP_CALLBACK_API has to be enabled in your lwipopts.h"
#endif
#if (LWIP_ALTCP && LWIP_EVENT_API)
#error "The application layered tcp API does not work with LWIP_EVENT_API"
#endif
#if (MEM_LIBC_MALLOC && MEM_USE_POOLS)
#error "MEM_LIBC_MALLOC and MEM_USE_POOLS may not both be simultaneously enabled in your lwipopts.h"
#endif
#if (MEM_USE_POOLS && !MEMP_USE_CUSTOM_POOLS)
#error "MEM_USE_POOLS requires custom pools (MEMP_USE_CUSTOM_POOLS) to be enabled in your lwipopts.h"
#endif
#if (PBUF_POOL_BUFSIZE <= MEM_ALIGNMENT)
#error "PBUF_POOL_BUFSIZE must be greater than MEM_ALIGNMENT or the offset may take the full first pbuf"
#endif
#if (DNS_LOCAL_HOSTLIST && !DNS_LOCAL_HOSTLIST_IS_DYNAMIC && !(defined(DNS_LOCAL_HOSTLIST_INIT)))
#error "you have to define define DNS_LOCAL_HOSTLIST_INIT {{'host1', 0x123}, {'host2', 0x234}} to initialize DNS_LOCAL_HOSTLIST"
#endif
#if PPP_SUPPORT && !PPPOS_SUPPORT && !PPPOE_SUPPORT && !PPPOL2TP_SUPPORT
#error "PPP_SUPPORT needs at least one of PPPOS_SUPPORT, PPPOE_SUPPORT or PPPOL2TP_SUPPORT turned on"
#endif
#if PPP_SUPPORT && !PPP_IPV4_SUPPORT && !PPP_IPV6_SUPPORT
#error "PPP_SUPPORT needs PPP_IPV4_SUPPORT and/or PPP_IPV6_SUPPORT turned on"
#endif
#if PPP_SUPPORT && PPP_IPV4_SUPPORT && !LWIP_IPV4
#error "PPP_IPV4_SUPPORT needs LWIP_IPV4 turned on"
#endif
#if PPP_SUPPORT && PPP_IPV6_SUPPORT && !LWIP_IPV6
#error "PPP_IPV6_SUPPORT needs LWIP_IPV6 turned on"
#endif
#if PPP_SUPPORT && CCP_SUPPORT && !MPPE_SUPPORT
#error "CCP_SUPPORT needs MPPE_SUPPORT turned on"
#endif
#if !LWIP_ETHERNET && (LWIP_ARP || PPPOE_SUPPORT)
#error "LWIP_ETHERNET needs to be turned on for LWIP_ARP or PPPOE_SUPPORT"
#endif
#if LWIP_TCPIP_CORE_LOCKING_INPUT && !LWIP_TCPIP_CORE_LOCKING
#error "When using LWIP_TCPIP_CORE_LOCKING_INPUT, LWIP_TCPIP_CORE_LOCKING must be enabled, too"
#endif
#if LWIP_TCP && LWIP_NETIF_TX_SINGLE_PBUF && !TCP_OVERSIZE
#error "LWIP_NETIF_TX_SINGLE_PBUF needs TCP_OVERSIZE enabled to create single-pbuf TCP packets"
#endif
#if LWIP_NETCONN && LWIP_TCP
#if NETCONN_COPY != TCP_WRITE_FLAG_COPY
#error "NETCONN_COPY != TCP_WRITE_FLAG_COPY"
#endif
#if NETCONN_MORE != TCP_WRITE_FLAG_MORE
#error "NETCONN_MORE != TCP_WRITE_FLAG_MORE"
#endif
#endif /* LWIP_NETCONN && LWIP_TCP */
#if LWIP_NETCONN_FULLDUPLEX && !LWIP_NETCONN_SEM_PER_THREAD
#error "For LWIP_NETCONN_FULLDUPLEX to work, LWIP_NETCONN_SEM_PER_THREAD is required"
#endif
/* Compile-time checks for deprecated options.
*/
#ifdef MEMP_NUM_TCPIP_MSG
#error "MEMP_NUM_TCPIP_MSG option is deprecated. Remove it from your lwipopts.h."
#endif
#ifdef TCP_REXMIT_DEBUG
#error "TCP_REXMIT_DEBUG option is deprecated. Remove it from your lwipopts.h."
#endif
#ifdef RAW_STATS
#error "RAW_STATS option is deprecated. Remove it from your lwipopts.h."
#endif
#ifdef ETHARP_QUEUE_FIRST
#error "ETHARP_QUEUE_FIRST option is deprecated. Remove it from your lwipopts.h."
#endif
#ifdef ETHARP_ALWAYS_INSERT
#error "ETHARP_ALWAYS_INSERT option is deprecated. Remove it from your lwipopts.h."
#endif
#if !NO_SYS && LWIP_TCPIP_CORE_LOCKING && LWIP_COMPAT_MUTEX && !defined(LWIP_COMPAT_MUTEX_ALLOWED)
#error "LWIP_COMPAT_MUTEX cannot prevent priority inversion. It is recommended to implement priority-aware mutexes. (Define LWIP_COMPAT_MUTEX_ALLOWED to disable this error.)"
#endif
#ifndef LWIP_DISABLE_TCP_SANITY_CHECKS
#define LWIP_DISABLE_TCP_SANITY_CHECKS 0
#endif
#ifndef LWIP_DISABLE_MEMP_SANITY_CHECKS
#define LWIP_DISABLE_MEMP_SANITY_CHECKS 0
#endif
/* MEMP sanity checks */
#if MEMP_MEM_MALLOC
#if !LWIP_DISABLE_MEMP_SANITY_CHECKS
#if LWIP_NETCONN || LWIP_SOCKET
#if !MEMP_NUM_NETCONN && LWIP_SOCKET
#error "lwip_sanity_check: WARNING: MEMP_NUM_NETCONN cannot be 0 when using sockets!"
#endif
#else /* MEMP_MEM_MALLOC */
#if MEMP_NUM_NETCONN > (MEMP_NUM_TCP_PCB+MEMP_NUM_TCP_PCB_LISTEN+MEMP_NUM_UDP_PCB+MEMP_NUM_RAW_PCB)
#error "lwip_sanity_check: WARNING: MEMP_NUM_NETCONN should be less than the sum of MEMP_NUM_{TCP,RAW,UDP}_PCB+MEMP_NUM_TCP_PCB_LISTEN. If you know what you are doing, define LWIP_DISABLE_MEMP_SANITY_CHECKS to 1 to disable this error."
#endif
#endif /* LWIP_NETCONN || LWIP_SOCKET */
#endif /* !LWIP_DISABLE_MEMP_SANITY_CHECKS */
#if MEM_USE_POOLS
#error "MEMP_MEM_MALLOC and MEM_USE_POOLS cannot be enabled at the same time"
#endif
#ifdef LWIP_HOOK_MEMP_AVAILABLE
#error "LWIP_HOOK_MEMP_AVAILABLE doesn't make sense with MEMP_MEM_MALLOC"
#endif
#endif /* MEMP_MEM_MALLOC */
/* TCP sanity checks */
#if !LWIP_DISABLE_TCP_SANITY_CHECKS
#if LWIP_TCP
#if !MEMP_MEM_MALLOC && (MEMP_NUM_TCP_SEG < TCP_SND_QUEUELEN)
#error "lwip_sanity_check: WARNING: MEMP_NUM_TCP_SEG should be at least as big as TCP_SND_QUEUELEN. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if TCP_SND_BUF < (2 * TCP_MSS)
#error "lwip_sanity_check: WARNING: TCP_SND_BUF must be at least as much as (2 * TCP_MSS) for things to work smoothly. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if TCP_SND_QUEUELEN < (2 * (TCP_SND_BUF / TCP_MSS))
#error "lwip_sanity_check: WARNING: TCP_SND_QUEUELEN must be at least as much as (2 * TCP_SND_BUF/TCP_MSS) for things to work. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if TCP_SNDLOWAT >= TCP_SND_BUF
#error "lwip_sanity_check: WARNING: TCP_SNDLOWAT must be less than TCP_SND_BUF. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if TCP_MSS >= ((16 * 1024) - 1)
#error "lwip_sanity_check: WARNING: TCP_MSS must be <= 16382 to prevent u16_t underflow in TCP_SNDLOWAT calculation!"
#endif
#if TCP_SNDLOWAT >= (0xFFFF - (4 * TCP_MSS))
#error "lwip_sanity_check: WARNING: TCP_SNDLOWAT must at least be 4*MSS below u16_t overflow!"
#endif
#if TCP_SNDQUEUELOWAT >= TCP_SND_QUEUELEN
#error "lwip_sanity_check: WARNING: TCP_SNDQUEUELOWAT must be less than TCP_SND_QUEUELEN. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if !MEMP_MEM_MALLOC && PBUF_POOL_SIZE && (PBUF_POOL_BUFSIZE <= (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN))
#error "lwip_sanity_check: WARNING: PBUF_POOL_BUFSIZE does not provide enough space for protocol headers. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if !MEMP_MEM_MALLOC && PBUF_POOL_SIZE && (TCP_WND > (PBUF_POOL_SIZE * (PBUF_POOL_BUFSIZE - (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + PBUF_IP_HLEN + PBUF_TRANSPORT_HLEN))))
#error "lwip_sanity_check: WARNING: TCP_WND is larger than space provided by PBUF_POOL_SIZE * (PBUF_POOL_BUFSIZE - protocol headers). If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#if TCP_WND < TCP_MSS
#error "lwip_sanity_check: WARNING: TCP_WND is smaller than MSS. If you know what you are doing, define LWIP_DISABLE_TCP_SANITY_CHECKS to 1 to disable this error."
#endif
#endif /* LWIP_TCP */
#endif /* !LWIP_DISABLE_TCP_SANITY_CHECKS */
/**
* @ingroup lwip_nosys
* Initialize all modules.
* Use this in NO_SYS mode. Use tcpip_init() otherwise.
*/
void
lwip_init(void)
{
#ifndef LWIP_SKIP_CONST_CHECK
int a = 0;
LWIP_UNUSED_ARG(a);
LWIP_ASSERT("LWIP_CONST_CAST not implemented correctly. Check your lwIP port.", LWIP_CONST_CAST(void *, &a) == &a);
#endif
#ifndef LWIP_SKIP_PACKING_CHECK
LWIP_ASSERT("Struct packing not implemented correctly. Check your lwIP port.", sizeof(struct packed_struct_test) == PACKED_STRUCT_TEST_EXPECTED_SIZE);
#endif
/* Modules initialization */
stats_init();
#if !NO_SYS
sys_init();
#endif /* !NO_SYS */
mem_init();
memp_init();
pbuf_init();
netif_init();
#if LWIP_IPV4
ip_init();
#if LWIP_ARP
etharp_init();
#endif /* LWIP_ARP */
#endif /* LWIP_IPV4 */
#if LWIP_RAW
raw_init();
#endif /* LWIP_RAW */
#if LWIP_UDP
udp_init();
#endif /* LWIP_UDP */
#if LWIP_TCP
tcp_init();
#endif /* LWIP_TCP */
#if LWIP_IGMP
igmp_init();
#endif /* LWIP_IGMP */
#if LWIP_DNS
dns_init();
#endif /* LWIP_DNS */
#if PPP_SUPPORT
ppp_init();
#endif
#if LWIP_TIMERS
sys_timeouts_init();
#endif /* LWIP_TIMERS */
}

File diff suppressed because it is too large Load Diff

View File

@ -1,447 +0,0 @@
/**
* @file
* Dynamic pool memory manager
*
* lwIP has dedicated pools for many structures (netconn, protocol control blocks,
* packet buffers, ...). All these pools are managed here.
*
* @defgroup mempool Memory pools
* @ingroup infrastructure
* Custom memory pools
*/
/*
* 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"
#include "lwip/memp.h"
#include "lwip/sys.h"
#include "lwip/stats.h"
#include <string.h>
/* Make sure we include everything we need for size calculation required by memp_std.h */
#include "lwip/pbuf.h"
#include "lwip/raw.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/altcp.h"
#include "lwip/ip4_frag.h"
#include "lwip/netbuf.h"
#include "lwip/api.h"
#include "lwip/priv/tcpip_priv.h"
#include "lwip/priv/api_msg.h"
#include "lwip/priv/sockets_priv.h"
#include "lwip/etharp.h"
#include "lwip/igmp.h"
#include "lwip/timeouts.h"
/* needed by default MEMP_NUM_SYS_TIMEOUT */
#include "netif/ppp/ppp_opts.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"
#include "lwip/priv/nd6_priv.h"
#include "lwip/ip6_frag.h"
#include "lwip/mld6.h"
#define LWIP_MEMPOOL(name,num,size,desc) LWIP_MEMPOOL_DECLARE(name,num,size,desc)
#include "lwip/priv/memp_std.h"
const struct memp_desc *const memp_pools[MEMP_MAX] = {
#define LWIP_MEMPOOL(name,num,size,desc) &memp_ ## name,
#include "lwip/priv/memp_std.h"
};
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
#if MEMP_MEM_MALLOC && MEMP_OVERFLOW_CHECK >= 2
#undef MEMP_OVERFLOW_CHECK
/* MEMP_OVERFLOW_CHECK >= 2 does not work with MEMP_MEM_MALLOC, use 1 instead */
#define MEMP_OVERFLOW_CHECK 1
#endif
#if MEMP_SANITY_CHECK && !MEMP_MEM_MALLOC
/**
* Check that memp-lists don't form a circle, using "Floyd's cycle-finding algorithm".
*/
static int
memp_sanity(const struct memp_desc *desc)
{
struct memp *t, *h;
t = *desc->tab;
if (t != NULL) {
for (h = t->next; (t != NULL) && (h != NULL); t = t->next,
h = ((h->next != NULL) ? h->next->next : NULL)) {
if (t == h) {
return 0;
}
}
}
return 1;
}
#endif /* MEMP_SANITY_CHECK && !MEMP_MEM_MALLOC */
#if MEMP_OVERFLOW_CHECK
/**
* Check if a memp element was victim of an overflow or underflow
* (e.g. the restricted area after/before it has been altered)
*
* @param p the memp element to check
* @param desc the pool p comes from
*/
static void
memp_overflow_check_element(struct memp *p, const struct memp_desc *desc)
{
mem_overflow_check_raw((u8_t *)p + MEMP_SIZE, desc->size, "pool ", desc->desc);
}
/**
* Initialize the restricted area of on memp element.
*/
static void
memp_overflow_init_element(struct memp *p, const struct memp_desc *desc)
{
mem_overflow_init_raw((u8_t *)p + MEMP_SIZE, desc->size);
}
#if MEMP_OVERFLOW_CHECK >= 2
/**
* Do an overflow check for all elements in every pool.
*
* @see memp_overflow_check_element for a description of the check
*/
static void
memp_overflow_check_all(void)
{
u16_t i, j;
struct memp *p;
SYS_ARCH_DECL_PROTECT(old_level);
SYS_ARCH_PROTECT(old_level);
for (i = 0; i < MEMP_MAX; ++i) {
p = (struct memp *)LWIP_MEM_ALIGN(memp_pools[i]->base);
for (j = 0; j < memp_pools[i]->num; ++j) {
memp_overflow_check_element(p, memp_pools[i]);
p = LWIP_ALIGNMENT_CAST(struct memp *, ((u8_t *)p + MEMP_SIZE + memp_pools[i]->size + MEM_SANITY_REGION_AFTER_ALIGNED));
}
}
SYS_ARCH_UNPROTECT(old_level);
}
#endif /* MEMP_OVERFLOW_CHECK >= 2 */
#endif /* MEMP_OVERFLOW_CHECK */
/**
* Initialize custom memory pool.
* Related functions: memp_malloc_pool, memp_free_pool
*
* @param desc pool to initialize
*/
void
memp_init_pool(const struct memp_desc *desc)
{
#if MEMP_MEM_MALLOC
LWIP_UNUSED_ARG(desc);
#else
int i;
struct memp *memp;
*desc->tab = NULL;
memp = (struct memp *)LWIP_MEM_ALIGN(desc->base);
#if MEMP_MEM_INIT
/* force memset on pool memory */
memset(memp, 0, (size_t)desc->num * (MEMP_SIZE + desc->size
#if MEMP_OVERFLOW_CHECK
+ MEM_SANITY_REGION_AFTER_ALIGNED
#endif
));
#endif
/* create a linked list of memp elements */
for (i = 0; i < desc->num; ++i) {
memp->next = *desc->tab;
*desc->tab = memp;
#if MEMP_OVERFLOW_CHECK
memp_overflow_init_element(memp, desc);
#endif /* MEMP_OVERFLOW_CHECK */
/* cast through void* to get rid of alignment warnings */
memp = (struct memp *)(void *)((u8_t *)memp + MEMP_SIZE + desc->size
#if MEMP_OVERFLOW_CHECK
+ MEM_SANITY_REGION_AFTER_ALIGNED
#endif
);
}
#if MEMP_STATS
desc->stats->avail = desc->num;
#endif /* MEMP_STATS */
#endif /* !MEMP_MEM_MALLOC */
#if MEMP_STATS && (defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY)
desc->stats->name = desc->desc;
#endif /* MEMP_STATS && (defined(LWIP_DEBUG) || LWIP_STATS_DISPLAY) */
}
/**
* Initializes lwIP built-in pools.
* Related functions: memp_malloc, memp_free
*
* Carves out memp_memory into linked lists for each pool-type.
*/
void
memp_init(void)
{
u16_t i;
/* for every pool: */
for (i = 0; i < LWIP_ARRAYSIZE(memp_pools); i++) {
memp_init_pool(memp_pools[i]);
#if LWIP_STATS && MEMP_STATS
lwip_stats.memp[i] = memp_pools[i]->stats;
#endif
}
#if MEMP_OVERFLOW_CHECK >= 2
/* check everything a first time to see if it worked */
memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK >= 2 */
}
static void *
#if !MEMP_OVERFLOW_CHECK
do_memp_malloc_pool(const struct memp_desc *desc)
#else
do_memp_malloc_pool_fn(const struct memp_desc *desc, const char *file, const int line)
#endif
{
struct memp *memp;
SYS_ARCH_DECL_PROTECT(old_level);
#if MEMP_MEM_MALLOC
memp = (struct memp *)mem_malloc(MEMP_SIZE + MEMP_ALIGN_SIZE(desc->size));
SYS_ARCH_PROTECT(old_level);
#else /* MEMP_MEM_MALLOC */
SYS_ARCH_PROTECT(old_level);
memp = *desc->tab;
#endif /* MEMP_MEM_MALLOC */
if (memp != NULL) {
#if !MEMP_MEM_MALLOC
#if MEMP_OVERFLOW_CHECK == 1
memp_overflow_check_element(memp, desc);
#endif /* MEMP_OVERFLOW_CHECK */
*desc->tab = memp->next;
#if MEMP_OVERFLOW_CHECK
memp->next = NULL;
#endif /* MEMP_OVERFLOW_CHECK */
#endif /* !MEMP_MEM_MALLOC */
#if MEMP_OVERFLOW_CHECK
memp->file = file;
memp->line = line;
#if MEMP_MEM_MALLOC
memp_overflow_init_element(memp, desc);
#endif /* MEMP_MEM_MALLOC */
#endif /* MEMP_OVERFLOW_CHECK */
LWIP_ASSERT("memp_malloc: memp properly aligned",
((mem_ptr_t)memp % MEM_ALIGNMENT) == 0);
#if MEMP_STATS
desc->stats->used++;
if (desc->stats->used > desc->stats->max) {
desc->stats->max = desc->stats->used;
}
#endif
SYS_ARCH_UNPROTECT(old_level);
/* cast through u8_t* to get rid of alignment warnings */
return ((u8_t *)memp + MEMP_SIZE);
} else {
#if MEMP_STATS
desc->stats->err++;
#endif
SYS_ARCH_UNPROTECT(old_level);
LWIP_DEBUGF(MEMP_DEBUG | LWIP_DBG_LEVEL_SERIOUS, ("memp_malloc: out of memory in pool %s\n", desc->desc));
}
return NULL;
}
/**
* Get an element from a custom pool.
*
* @param desc the pool to get an element from
*
* @return a pointer to the allocated memory or a NULL pointer on error
*/
void *
#if !MEMP_OVERFLOW_CHECK
memp_malloc_pool(const struct memp_desc *desc)
#else
memp_malloc_pool_fn(const struct memp_desc *desc, const char *file, const int line)
#endif
{
LWIP_ASSERT("invalid pool desc", desc != NULL);
if (desc == NULL) {
return NULL;
}
#if !MEMP_OVERFLOW_CHECK
return do_memp_malloc_pool(desc);
#else
return do_memp_malloc_pool_fn(desc, file, line);
#endif
}
/**
* Get an element from a specific pool.
*
* @param type the pool to get an element from
*
* @return a pointer to the allocated memory or a NULL pointer on error
*/
void *
#if !MEMP_OVERFLOW_CHECK
memp_malloc(memp_t type)
#else
memp_malloc_fn(memp_t type, const char *file, const int line)
#endif
{
void *memp;
LWIP_ERROR("memp_malloc: type < MEMP_MAX", (type < MEMP_MAX), return NULL;);
#if MEMP_OVERFLOW_CHECK >= 2
memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK >= 2 */
#if !MEMP_OVERFLOW_CHECK
memp = do_memp_malloc_pool(memp_pools[type]);
#else
memp = do_memp_malloc_pool_fn(memp_pools[type], file, line);
#endif
return memp;
}
static void
do_memp_free_pool(const struct memp_desc *desc, void *mem)
{
struct memp *memp;
SYS_ARCH_DECL_PROTECT(old_level);
LWIP_ASSERT("memp_free: mem properly aligned",
((mem_ptr_t)mem % MEM_ALIGNMENT) == 0);
/* cast through void* to get rid of alignment warnings */
memp = (struct memp *)(void *)((u8_t *)mem - MEMP_SIZE);
SYS_ARCH_PROTECT(old_level);
#if MEMP_OVERFLOW_CHECK == 1
memp_overflow_check_element(memp, desc);
#endif /* MEMP_OVERFLOW_CHECK */
#if MEMP_STATS
desc->stats->used--;
#endif
#if MEMP_MEM_MALLOC
LWIP_UNUSED_ARG(desc);
SYS_ARCH_UNPROTECT(old_level);
mem_free(memp);
#else /* MEMP_MEM_MALLOC */
memp->next = *desc->tab;
*desc->tab = memp;
#if MEMP_SANITY_CHECK
LWIP_ASSERT("memp sanity", memp_sanity(desc));
#endif /* MEMP_SANITY_CHECK */
SYS_ARCH_UNPROTECT(old_level);
#endif /* !MEMP_MEM_MALLOC */
}
/**
* Put a custom pool element back into its pool.
*
* @param desc the pool where to put mem
* @param mem the memp element to free
*/
void
memp_free_pool(const struct memp_desc *desc, void *mem)
{
LWIP_ASSERT("invalid pool desc", desc != NULL);
if ((desc == NULL) || (mem == NULL)) {
return;
}
do_memp_free_pool(desc, mem);
}
/**
* Put an element back into its pool.
*
* @param type the pool where to put mem
* @param mem the memp element to free
*/
void
memp_free(memp_t type, void *mem)
{
#ifdef LWIP_HOOK_MEMP_AVAILABLE
struct memp *old_first;
#endif
LWIP_ERROR("memp_free: type < MEMP_MAX", (type < MEMP_MAX), return;);
if (mem == NULL) {
return;
}
#if MEMP_OVERFLOW_CHECK >= 2
memp_overflow_check_all();
#endif /* MEMP_OVERFLOW_CHECK >= 2 */
#ifdef LWIP_HOOK_MEMP_AVAILABLE
old_first = *memp_pools[type]->tab;
#endif
do_memp_free_pool(memp_pools[type], mem);
#ifdef LWIP_HOOK_MEMP_AVAILABLE
if (old_first == NULL) {
LWIP_HOOK_MEMP_AVAILABLE(type);
}
#endif
}

View File

@ -1,533 +0,0 @@
/**
* @file
* NetBIOS name service responder
*/
/**
* @defgroup netbiosns NETBIOS responder
* @ingroup apps
*
* 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!
*/
/*
* 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.
*
* Modifications by Ray Abram to respond to NetBIOS name requests when Incoming name = *
* - based on code from "https://github.com/esp8266/Arduino/commit/1f7989b31d26d7df9776a08f36d685eae7ac8f99"
* - with permission to relicense to BSD from original author:
* http://www.xpablo.cz/?p=751#more-751
*/
#include "lwip/netbiosns.h"
#if LWIP_IPV4 && LWIP_UDP /* don't build if not configured for use in lwipopts.h */
#include "lwip/def.h"
#include "lwip/udp.h"
#include "lwip/ip.h"
#include "lwip/netif.h"
#include "lwip/prot/iana.h"
#include <string.h>
/** 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 300000u
/** NetBIOS header flags */
#define NETB_HFLAG_RESPONSE 0x8000U
#define NETB_HFLAG_OPCODE 0x7800U
#define NETB_HFLAG_OPCODE_NAME_QUERY 0x0000U
#define NETB_HFLAG_AUTHORATIVE 0x0400U
#define NETB_HFLAG_TRUNCATED 0x0200U
#define NETB_HFLAG_RECURS_DESIRED 0x0100U
#define NETB_HFLAG_RECURS_AVAILABLE 0x0080U
#define NETB_HFLAG_BROADCAST 0x0010U
#define NETB_HFLAG_REPLYCODE 0x0008U
#define NETB_HFLAG_REPLYCODE_NOERROR 0x0000U
/* NetBIOS question types */
#define NETB_QTYPE_NB 0x0020U
#define NETB_QTYPE_NBSTAT 0x0021U
/** NetBIOS name flags */
#define NETB_NFLAG_UNIQUE 0x8000U
#define NETB_NFLAG_NODETYPE 0x6000U
#define NETB_NFLAG_NODETYPE_HNODE 0x6000U
#define NETB_NFLAG_NODETYPE_MNODE 0x4000U
#define NETB_NFLAG_NODETYPE_PNODE 0x2000U
#define NETB_NFLAG_NODETYPE_BNODE 0x0000U
#define NETB_NFLAG_NAME_IN_CONFLICT 0x0800U /* 1=Yes, 0=No */
#define NETB_NFLAG_NAME_IS_ACTIVE 0x0400U /* 1=Yes, 0=No */
#define NETB_NFLAG_NAME_IS_PERMANENT 0x0200U /* 1=Yes (Name is Permanent Node Name), 0=No */
/** 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 question part */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct netbios_question_hdr {
PACK_STRUCT_FLD_8(u8_t nametype);
PACK_STRUCT_FLD_8(u8_t encname[(NETBIOS_NAME_LEN * 2) + 1]);
PACK_STRUCT_FIELD(u16_t type);
PACK_STRUCT_FIELD(u16_t cls);
} 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_FLD_8(u8_t nametype);
PACK_STRUCT_FLD_8(u8_t encname[(NETBIOS_NAME_LEN * 2) + 1]);
PACK_STRUCT_FIELD(u16_t type);
PACK_STRUCT_FIELD(u16_t cls);
PACK_STRUCT_FIELD(u32_t ttl);
PACK_STRUCT_FIELD(u16_t datalen);
PACK_STRUCT_FIELD(u16_t flags);
PACK_STRUCT_FLD_S(ip4_addr_p_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
/** The NBNS Structure Responds to a Name Query */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct netbios_answer {
struct netbios_hdr answer_hdr;
/** the length of the next string */
PACK_STRUCT_FIELD(u8_t name_size);
/** WARNING!!! this item may be of a different length (we use this struct for transmission) */
PACK_STRUCT_FLD_8(u8_t query_name[(NETBIOS_NAME_LEN * 2) + 1]);
PACK_STRUCT_FIELD(u16_t packet_type);
PACK_STRUCT_FIELD(u16_t cls);
PACK_STRUCT_FIELD(u32_t ttl);
PACK_STRUCT_FIELD(u16_t data_length);
#define OFFSETOF_STRUCT_NETBIOS_ANSWER_NUMBER_OF_NAMES 56
/** number of names */
PACK_STRUCT_FLD_8(u8_t number_of_names);
/** node name */
PACK_STRUCT_FLD_8(u8_t answer_name[NETBIOS_NAME_LEN]);
/** node flags */
PACK_STRUCT_FIELD(u16_t answer_name_flags);
/** Unit ID */
PACK_STRUCT_FLD_8(u8_t unit_id[6]);
/** Jumpers */
PACK_STRUCT_FLD_8(u8_t jumpers);
/** Test result */
PACK_STRUCT_FLD_8(u8_t test_result);
/** Version number */
PACK_STRUCT_FIELD(u16_t version_number);
/** Period of statistics */
PACK_STRUCT_FIELD(u16_t period_of_statistics);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_crcs);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_alignment_errors);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_collisions);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_send_aborts);
/** Statistics */
PACK_STRUCT_FIELD(u32_t number_of_good_sends);
/** Statistics */
PACK_STRUCT_FIELD(u32_t number_of_good_receives);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_retransmits);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_no_resource_condition);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_free_command_blocks);
/** Statistics */
PACK_STRUCT_FIELD(u16_t total_number_of_command_blocks);
/** Statistics */
PACK_STRUCT_FIELD(u16_t max_total_number_of_command_blocks);
/** Statistics */
PACK_STRUCT_FIELD(u16_t number_of_pending_sessions);
/** Statistics */
PACK_STRUCT_FIELD(u16_t max_number_of_pending_sessions);
/** Statistics */
PACK_STRUCT_FIELD(u16_t max_total_sessions_possible);
/** Statistics */
PACK_STRUCT_FIELD(u16_t session_data_packet_size);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef NETBIOS_LWIP_NAME
#define NETBIOS_LOCAL_NAME NETBIOS_LWIP_NAME
#else
static char netbiosns_local_name[NETBIOS_NAME_LEN];
#define NETBIOS_LOCAL_NAME netbiosns_local_name
#endif
static struct udp_pcb *netbiosns_pcb;
/** Decode a NetBIOS name (from packet to string) */
static int
netbiosns_name_decode(const char *name_enc, char *name_dec, int name_dec_len)
{
const char *pname;
char cname;
char cnbname;
int idx = 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 (!lwip_isupper(cname)) {
/* Not legal. */
return -1;
}
cname -= 'A';
cnbname = cname << 4;
pname++;
cname = *pname;
if (!lwip_isupper(cname)) {
/* Not legal. */
return -1;
}
cname -= 'A';
cnbname |= cname;
pname++;
/* Do we have room to store the character? */
if (idx < NETBIOS_NAME_LEN) {
/* Yes - store the character. */
name_dec[idx++] = (cnbname != ' ' ? cnbname : '\0');
}
}
return 0;
}
#if 0 /* function currently unused */
/** Encode a NetBIOS name (from string to packet) - currently unused because
we don't ask for names. */
static int
netbiosns_name_encode(char *name_enc, char *name_dec, int name_dec_len)
{
char *pname;
char cname;
unsigned char ucname;
int idx = 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 (idx >= name_dec_len) {
return -1;
}
/* Yes - store the character. */
ucname = cname;
name_dec[idx++] = ('A' + ((ucname >> 4) & 0x0F));
name_dec[idx++] = ('A' + ( ucname & 0x0F));
pname++;
}
/* Fill with "space" coding */
for (; idx < name_dec_len - 1;) {
name_dec[idx++] = 'C';
name_dec[idx++] = 'A';
}
/* Terminate string */
name_dec[idx] = '\0';
return 0;
}
#endif /* 0 */
/** NetBIOS Name service recv callback */
static void
netbiosns_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 = (struct netbios_hdr *)p->payload;
struct netbios_question_hdr *netbios_question_hdr = (struct netbios_question_hdr *)(netbios_hdr + 1);
/* is the packet long enough (we need the header in one piece) */
if (p->len < (sizeof(struct netbios_hdr) + sizeof(struct netbios_question_hdr))) {
/* packet too short */
pbuf_free(p);
return;
}
/* 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 (((netbios_hdr->flags & PP_NTOHS(NETB_HFLAG_OPCODE)) == PP_NTOHS(NETB_HFLAG_OPCODE_NAME_QUERY)) &&
((netbios_hdr->flags & PP_NTOHS(NETB_HFLAG_RESPONSE)) == 0) &&
(netbios_hdr->questions == PP_NTOHS(1))) {
/* decode the NetBIOS name */
netbiosns_name_decode((char *)(netbios_question_hdr->encname), netbios_name, sizeof(netbios_name));
/* check the request type */
if (netbios_question_hdr->type == PP_HTONS(NETB_QTYPE_NB)) {
/* if the packet is for us */
if (lwip_strnicmp(netbios_name, NETBIOS_LOCAL_NAME, sizeof(NETBIOS_LOCAL_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 = PP_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 = PP_HTONS(1);
resp->resp_hdr.authorityRRs = 0;
resp->resp_hdr.additionalRRs = 0;
/* prepare NetBIOS header datas */
MEMCPY( resp->resp_name.encname, netbios_question_hdr->encname, sizeof(netbios_question_hdr->encname));
resp->resp_name.nametype = netbios_question_hdr->nametype;
resp->resp_name.type = netbios_question_hdr->type;
resp->resp_name.cls = netbios_question_hdr->cls;
resp->resp_name.ttl = PP_HTONL(NETBIOS_NAME_TTL);
resp->resp_name.datalen = PP_HTONS(sizeof(resp->resp_name.flags) + sizeof(resp->resp_name.addr));
resp->resp_name.flags = PP_HTONS(NETB_NFLAG_NODETYPE_BNODE);
ip4_addr_copy(resp->resp_name.addr, *netif_ip4_addr(netif_default));
/* send the NetBIOS response */
udp_sendto(upcb, q, addr, port);
/* free the "reference" pbuf */
pbuf_free(q);
}
}
#if LWIP_NETBIOS_RESPOND_NAME_QUERY
} else if (netbios_question_hdr->type == PP_HTONS(NETB_QTYPE_NBSTAT)) {
/* if the packet is for us or general query */
if (!lwip_strnicmp(netbios_name, NETBIOS_LOCAL_NAME, sizeof(NETBIOS_LOCAL_NAME)) ||
!lwip_strnicmp(netbios_name, "*", sizeof(NETBIOS_LOCAL_NAME))) {
/* general query - ask for our IP address */
struct pbuf *q;
struct netbios_answer *resp;
q = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct netbios_answer), PBUF_RAM);
if (q != NULL) {
/* buffer to which a response is compiled */
resp = (struct netbios_answer *) q->payload;
/* Init response to zero, especially the statistics fields */
memset(resp, 0, sizeof(*resp));
/* copy the query to the response ID */
resp->answer_hdr.trans_id = netbios_hdr->trans_id;
/* acknowledgment of termination */
resp->answer_hdr.flags = PP_HTONS(NETB_HFLAG_RESPONSE | NETB_HFLAG_OPCODE_NAME_QUERY | NETB_HFLAG_AUTHORATIVE);
/* resp->answer_hdr.questions = PP_HTONS(0); done by memset() */
/* serial number of the answer */
resp->answer_hdr.answerRRs = PP_HTONS(1);
/* resp->answer_hdr.authorityRRs = PP_HTONS(0); done by memset() */
/* resp->answer_hdr.additionalRRs = PP_HTONS(0); done by memset() */
/* we will copy the length of the station name */
resp->name_size = netbios_question_hdr->nametype;
/* we will copy the queried name */
MEMCPY(resp->query_name, netbios_question_hdr->encname, (NETBIOS_NAME_LEN * 2) + 1);
/* NBSTAT */
resp->packet_type = PP_HTONS(0x21);
/* Internet name */
resp->cls = PP_HTONS(1);
/* resp->ttl = PP_HTONL(0); done by memset() */
resp->data_length = PP_HTONS(sizeof(struct netbios_answer) - offsetof(struct netbios_answer, number_of_names));
resp->number_of_names = 1;
/* make windows see us as workstation, not as a server */
memset(resp->answer_name, 0x20, NETBIOS_NAME_LEN - 1);
/* strlen is checked to be < NETBIOS_NAME_LEN during initialization */
MEMCPY(resp->answer_name, NETBIOS_LOCAL_NAME, strlen(NETBIOS_LOCAL_NAME));
/* b-node, unique, active */
resp->answer_name_flags = PP_HTONS(NETB_NFLAG_NAME_IS_ACTIVE);
/* Set responder netif MAC address */
SMEMCPY(resp->unit_id, ip_current_input_netif()->hwaddr, sizeof(resp->unit_id));
udp_sendto(upcb, q, addr, port);
pbuf_free(q);
}
}
#endif /* LWIP_NETBIOS_RESPOND_NAME_QUERY */
}
}
}
/* free the pbuf */
pbuf_free(p);
}
}
/**
* @ingroup netbiosns
* Init netbios responder
*/
void
netbiosns_init(void)
{
/* LWIP_ASSERT_CORE_LOCKED(); is checked by udp_new() */
#ifdef NETBIOS_LWIP_NAME
LWIP_ASSERT("NetBIOS name is too long!", strlen(NETBIOS_LWIP_NAME) < NETBIOS_NAME_LEN);
#endif
netbiosns_pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
if (netbiosns_pcb != NULL) {
/* we have to be allowed to send broadcast packets! */
ip_set_option(netbiosns_pcb, SOF_BROADCAST);
udp_bind(netbiosns_pcb, IP_ANY_TYPE, LWIP_IANA_PORT_NETBIOS);
udp_recv(netbiosns_pcb, netbiosns_recv, netbiosns_pcb);
}
}
#ifndef NETBIOS_LWIP_NAME
/**
* @ingroup netbiosns
* Set netbios name. ATTENTION: the hostname must be less than 15 characters!
* the NetBIOS name spec says the name MUST be upper case, so incoming name is forced into uppercase :-)
*/
void
netbiosns_set_name(const char *hostname)
{
size_t i;
size_t copy_len = strlen(hostname);
LWIP_ASSERT_CORE_LOCKED();
LWIP_ASSERT("NetBIOS name is too long!", copy_len < NETBIOS_NAME_LEN);
if (copy_len >= NETBIOS_NAME_LEN) {
copy_len = NETBIOS_NAME_LEN - 1;
}
/* make name into upper case */
for (i = 0; i < copy_len; i++ ) {
netbiosns_local_name[i] = (char)lwip_toupper(hostname[i]);
}
netbiosns_local_name[copy_len] = '\0';
}
#endif /* NETBIOS_LWIP_NAME */
/**
* @ingroup netbiosns
* Stop netbios responder
*/
void
netbiosns_stop(void)
{
LWIP_ASSERT_CORE_LOCKED();
if (netbiosns_pcb != NULL) {
udp_remove(netbiosns_pcb);
netbiosns_pcb = NULL;
}
}
#endif /* LWIP_IPV4 && LWIP_UDP */

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +0,0 @@
This directory contains generic network interface device drivers that
do not contain any hardware or architecture specific code. The files
are:
ethernet.c
Shared code for Ethernet based interfaces.
lowpan6.c
A 6LoWPAN implementation as a netif.
lowpan6_ble.c
A 6LoWPAN over Bluetooth Low Energy (BLE) implementation as netif,
according to RFC-7668.
slipif.c
A generic implementation of the SLIP (Serial Line IP)
protocol. It requires a sio (serial I/O) module to work.
ppp/ Point-to-Point Protocol stack
The lwIP PPP support is based from pppd (http://ppp.samba.org) with
huge changes to match code size and memory requirements for embedded
devices. Please read /doc/ppp.txt and ppp/PPPD_FOLLOWUP for a detailed
explanation.

View File

@ -1,563 +0,0 @@
/**
* @file
* lwIP netif implementing an IEEE 802.1D MAC Bridge
*/
/*
* Copyright (c) 2017 Simon Goldschmidt.
* 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 <goldsimon@gmx.de>
*
*/
/**
* @defgroup bridgeif IEEE 802.1D bridge
* @ingroup netifs
* This file implements an IEEE 802.1D bridge by using a multilayer netif approach
* (one hardware-independent netif for the bridge that uses hardware netifs for its ports).
* On transmit, the bridge selects the outgoing port(s).
* On receive, the port netif calls into the bridge (via its netif->input function) and
* the bridge selects the port(s) (and/or its netif->input function) to pass the received pbuf to.
*
* Usage:
* - add the port netifs just like you would when using them as dedicated netif without a bridge
* - only NETIF_FLAG_ETHARP/NETIF_FLAG_ETHERNET netifs are supported as bridge ports
* - add the bridge port netifs without IPv4 addresses (i.e. pass 'NULL, NULL, NULL')
* - don't add IPv6 addresses to the port netifs!
* - set up the bridge configuration in a global variable of type 'bridgeif_initdata_t' that contains
* - the MAC address of the bridge
* - some configuration options controlling the memory consumption (maximum number of ports
* and FDB entries)
* - e.g. for a bridge MAC address 00-01-02-03-04-05, 2 bridge ports, 1024 FDB entries + 16 static MAC entries:
* bridgeif_initdata_t mybridge_initdata = BRIDGEIF_INITDATA1(2, 1024, 16, ETH_ADDR(0, 1, 2, 3, 4, 5));
* - add the bridge netif (with IPv4 config):
* struct netif bridge_netif;
* netif_add(&bridge_netif, &my_ip, &my_netmask, &my_gw, &mybridge_initdata, bridgeif_init, tcpip_input);
* NOTE: the passed 'input' function depends on BRIDGEIF_PORT_NETIFS_OUTPUT_DIRECT setting,
* which controls where the forwarding is done (netif low level input context vs. tcpip_thread)
* - set up all ports netifs and the bridge netif
*
* - When adding a port netif, NETIF_FLAG_ETHARP flag will be removed from a port
* to prevent ETHARP working on that port netif (we only want one IP per bridge not per port).
* - When adding a port netif, its input function is changed to call into the bridge.
*
*
* @todo:
* - compact static FDB entries (instead of walking the whole array)
* - add FDB query/read access
* - add FDB change callback (when learning or dropping auto-learned entries)
* - prefill FDB with MAC classes that should never be forwarded
* - multicast snooping? (and only forward group addresses to interested ports)
* - support removing ports
* - check SNMP integration
* - VLAN handling / trunk ports
* - priority handling? (although that largely depends on TX queue limitations and lwIP doesn't provide tx-done handling)
*/
#include "netif/bridgeif.h"
#include "lwip/netif.h"
#include "lwip/sys.h"
#include "lwip/etharp.h"
#include "lwip/ethip6.h"
#include "lwip/snmp.h"
#include "lwip/timeouts.h"
#include <string.h>
#if LWIP_NUM_NETIF_CLIENT_DATA
/* Define those to better describe your network interface. */
#define IFNAME0 'b'
#define IFNAME1 'r'
struct bridgeif_private_s;
typedef struct bridgeif_port_private_s {
struct bridgeif_private_s *bridge;
struct netif *port_netif;
u8_t port_num;
} bridgeif_port_t;
typedef struct bridgeif_fdb_static_entry_s {
u8_t used;
bridgeif_portmask_t dst_ports;
struct eth_addr addr;
} bridgeif_fdb_static_entry_t;
typedef struct bridgeif_private_s {
struct netif *netif;
struct eth_addr ethaddr;
u8_t max_ports;
u8_t num_ports;
bridgeif_port_t *ports;
u16_t max_fdbs_entries;
bridgeif_fdb_static_entry_t *fdbs;
u16_t max_fdbd_entries;
void *fdbd;
} bridgeif_private_t;
/* netif data index to get the bridge on input */
u8_t bridgeif_netif_client_id = 0xff;
/**
* @ingroup bridgeif
* Add a static entry to the forwarding database.
* A static entry marks where frames to a specific eth address (unicast or group address) are
* forwarded.
* bits [0..(BRIDGEIF_MAX_PORTS-1)]: hw ports
* bit [BRIDGEIF_MAX_PORTS]: cpu port
* 0: drop
*/
err_t
bridgeif_fdb_add(struct netif *bridgeif, const struct eth_addr *addr, bridgeif_portmask_t ports)
{
int i;
bridgeif_private_t *br;
BRIDGEIF_DECL_PROTECT(lev);
LWIP_ASSERT("invalid netif", bridgeif != NULL);
br = (bridgeif_private_t *)bridgeif->state;
LWIP_ASSERT("invalid state", br != NULL);
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < br->max_fdbs_entries; i++) {
if (!br->fdbs[i].used) {
BRIDGEIF_WRITE_PROTECT(lev);
if (!br->fdbs[i].used) {
br->fdbs[i].used = 1;
br->fdbs[i].dst_ports = ports;
memcpy(&br->fdbs[i].addr, addr, sizeof(struct eth_addr));
BRIDGEIF_WRITE_UNPROTECT(lev);
BRIDGEIF_READ_UNPROTECT(lev);
return ERR_OK;
}
BRIDGEIF_WRITE_UNPROTECT(lev);
}
}
BRIDGEIF_READ_UNPROTECT(lev);
return ERR_MEM;
}
/**
* @ingroup bridgeif
* Remove a static entry from the forwarding database
*/
err_t
bridgeif_fdb_remove(struct netif *bridgeif, const struct eth_addr *addr)
{
int i;
bridgeif_private_t *br;
BRIDGEIF_DECL_PROTECT(lev);
LWIP_ASSERT("invalid netif", bridgeif != NULL);
br = (bridgeif_private_t *)bridgeif->state;
LWIP_ASSERT("invalid state", br != NULL);
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < br->max_fdbs_entries; i++) {
if (br->fdbs[i].used && !memcmp(&br->fdbs[i].addr, addr, sizeof(struct eth_addr))) {
BRIDGEIF_WRITE_PROTECT(lev);
if (br->fdbs[i].used && !memcmp(&br->fdbs[i].addr, addr, sizeof(struct eth_addr))) {
memset(&br->fdbs[i], 0, sizeof(bridgeif_fdb_static_entry_t));
BRIDGEIF_WRITE_UNPROTECT(lev);
BRIDGEIF_READ_UNPROTECT(lev);
return ERR_OK;
}
BRIDGEIF_WRITE_UNPROTECT(lev);
}
}
BRIDGEIF_READ_UNPROTECT(lev);
return ERR_VAL;
}
/** Get the forwarding port(s) (as bit mask) for the specified destination mac address */
static bridgeif_portmask_t
bridgeif_find_dst_ports(bridgeif_private_t *br, struct eth_addr *dst_addr)
{
int i;
BRIDGEIF_DECL_PROTECT(lev);
BRIDGEIF_READ_PROTECT(lev);
/* first check for static entries */
for (i = 0; i < br->max_fdbs_entries; i++) {
if (br->fdbs[i].used) {
if (!memcmp(&br->fdbs[i].addr, dst_addr, sizeof(struct eth_addr))) {
bridgeif_portmask_t ret = br->fdbs[i].dst_ports;
BRIDGEIF_READ_UNPROTECT(lev);
return ret;
}
}
}
if (dst_addr->addr[0] & 1) {
/* no match found: flood remaining group address */
BRIDGEIF_READ_UNPROTECT(lev);
return BR_FLOOD;
}
BRIDGEIF_READ_UNPROTECT(lev);
/* no match found: check dynamic fdb for port or fall back to flooding */
return bridgeif_fdb_get_dst_ports(br->fdbd, dst_addr);
}
/** Helper function to see if a destination mac belongs to the bridge
* (bridge netif or one of the port netifs), in which case the frame
* is sent to the cpu only.
*/
static int
bridgeif_is_local_mac(bridgeif_private_t *br, struct eth_addr *addr)
{
int i;
BRIDGEIF_DECL_PROTECT(lev);
if (!memcmp(br->netif->hwaddr, addr, sizeof(struct eth_addr))) {
return 1;
}
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < br->num_ports; i++) {
struct netif *portif = br->ports[i].port_netif;
if (portif != NULL) {
if (!memcmp(portif->hwaddr, addr, sizeof(struct eth_addr))) {
BRIDGEIF_READ_UNPROTECT(lev);
return 1;
}
}
}
BRIDGEIF_READ_UNPROTECT(lev);
return 0;
}
/* Output helper function */
static err_t
bridgeif_send_to_port(bridgeif_private_t *br, struct pbuf *p, u8_t dstport_idx)
{
if (dstport_idx < BRIDGEIF_MAX_PORTS) {
/* possibly an external port */
if (dstport_idx < br->max_ports) {
struct netif *portif = br->ports[dstport_idx].port_netif;
if ((portif != NULL) && (portif->linkoutput != NULL)) {
/* prevent sending out to rx port */
if (netif_get_index(portif) != p->if_idx) {
if (netif_is_link_up(portif)) {
LWIP_DEBUGF(BRIDGEIF_FW_DEBUG, ("br -> flood(%p:%d) -> %d\n", (void *)p, p->if_idx, netif_get_index(portif)));
return portif->linkoutput(portif, p);
}
}
}
}
} else {
LWIP_ASSERT("invalid port index", dstport_idx == BRIDGEIF_MAX_PORTS);
}
return ERR_OK;
}
/** Helper function to pass a pbuf to all ports marked in 'dstports'
*/
static err_t
bridgeif_send_to_ports(bridgeif_private_t *br, struct pbuf *p, bridgeif_portmask_t dstports)
{
err_t err, ret_err = ERR_OK;
u8_t i;
bridgeif_portmask_t mask = 1;
BRIDGEIF_DECL_PROTECT(lev);
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < BRIDGEIF_MAX_PORTS; i++, mask = (bridgeif_portmask_t)(mask << 1)) {
if (dstports & mask) {
err = bridgeif_send_to_port(br, p, i);
if (err != ERR_OK) {
ret_err = err;
}
}
}
BRIDGEIF_READ_UNPROTECT(lev);
return ret_err;
}
/** Output function of the application port of the bridge (the one with an ip address).
* The forwarding port(s) where this pbuf is sent on is/are automatically selected
* from the FDB.
*/
static err_t
bridgeif_output(struct netif *netif, struct pbuf *p)
{
err_t err;
bridgeif_private_t *br = (bridgeif_private_t *)netif->state;
struct eth_addr *dst = (struct eth_addr *)(p->payload);
bridgeif_portmask_t dstports = bridgeif_find_dst_ports(br, dst);
err = bridgeif_send_to_ports(br, p, dstports);
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p->tot_len);
if (((u8_t *)p->payload)[0] & 1) {
/* broadcast or multicast packet*/
MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts);
} else {
/* unicast packet */
MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
}
/* increase ifoutdiscards or ifouterrors on error */
LINK_STATS_INC(link.xmit);
return err;
}
/** The actual bridge input function. Port netif's input is changed to call
* here. This function decides where the frame is forwarded.
*/
static err_t
bridgeif_input(struct pbuf *p, struct netif *netif)
{
u8_t rx_idx;
bridgeif_portmask_t dstports;
struct eth_addr *src, *dst;
bridgeif_private_t *br;
bridgeif_port_t *port;
if (p == NULL || netif == NULL) {
return ERR_VAL;
}
port = (bridgeif_port_t *)netif_get_client_data(netif, bridgeif_netif_client_id);
LWIP_ASSERT("port data not set", port != NULL);
if (port == NULL || port->bridge == NULL) {
return ERR_VAL;
}
br = (bridgeif_private_t *)port->bridge;
rx_idx = netif_get_index(netif);
/* store receive index in pbuf */
p->if_idx = rx_idx;
dst = (struct eth_addr *)p->payload;
src = (struct eth_addr *)(((u8_t *)p->payload) + sizeof(struct eth_addr));
if ((src->addr[0] & 1) == 0) {
/* update src for all non-group addresses */
bridgeif_fdb_update_src(br->fdbd, src, port->port_num);
}
if (dst->addr[0] & 1) {
/* group address -> flood + cpu? */
dstports = bridgeif_find_dst_ports(br, dst);
bridgeif_send_to_ports(br, p, dstports);
if (dstports & (1 << BRIDGEIF_MAX_PORTS)) {
/* we pass the reference to ->input or have to free it */
LWIP_DEBUGF(BRIDGEIF_FW_DEBUG, ("br -> input(%p)\n", (void *)p));
if (br->netif->input(p, br->netif) != ERR_OK) {
pbuf_free(p);
}
} else {
/* all references done */
pbuf_free(p);
}
/* always return ERR_OK here to prevent the caller freeing the pbuf */
return ERR_OK;
} else {
/* is this for one of the local ports? */
if (bridgeif_is_local_mac(br, dst)) {
/* yes, send to cpu port only */
LWIP_DEBUGF(BRIDGEIF_FW_DEBUG, ("br -> input(%p)\n", (void *)p));
return br->netif->input(p, br->netif);
}
/* get dst port */
dstports = bridgeif_find_dst_ports(br, dst);
bridgeif_send_to_ports(br, p, dstports);
/* no need to send to cpu, flooding is for external ports only */
/* by this, we consumed the pbuf */
pbuf_free(p);
/* always return ERR_OK here to prevent the caller freeing the pbuf */
return ERR_OK;
}
}
#if !BRIDGEIF_PORT_NETIFS_OUTPUT_DIRECT
/** Input function for port netifs used to synchronize into tcpip_thread.
*/
static err_t
bridgeif_tcpip_input(struct pbuf *p, struct netif *netif)
{
return tcpip_inpkt(p, netif, bridgeif_input);
}
#endif /* BRIDGEIF_PORT_NETIFS_OUTPUT_DIRECT */
/**
* @ingroup bridgeif
* Initialization function passed to netif_add().
*
* ATTENTION: A pointer to a @ref bridgeif_initdata_t must be passed as 'state'
* to @ref netif_add when adding the bridge. I supplies MAC address
* and controls memory allocation (number of ports, FDB size).
*
* @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
bridgeif_init(struct netif *netif)
{
bridgeif_initdata_t *init_data;
bridgeif_private_t *br;
size_t alloc_len_sizet;
mem_size_t alloc_len;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("bridgeif needs an input callback", (netif->input != NULL));
#if !BRIDGEIF_PORT_NETIFS_OUTPUT_DIRECT
if (netif->input == tcpip_input) {
LWIP_DEBUGF(BRIDGEIF_DEBUG | LWIP_DBG_ON, ("bridgeif does not need tcpip_input, use netif_input/ethernet_input instead"));
}
#endif
if (bridgeif_netif_client_id == 0xFF) {
bridgeif_netif_client_id = netif_alloc_client_data_id();
}
init_data = (bridgeif_initdata_t *)netif->state;
LWIP_ASSERT("init_data != NULL", (init_data != NULL));
LWIP_ASSERT("init_data->max_ports <= BRIDGEIF_MAX_PORTS",
init_data->max_ports <= BRIDGEIF_MAX_PORTS);
alloc_len_sizet = sizeof(bridgeif_private_t) + (init_data->max_ports * sizeof(bridgeif_port_t) + (init_data->max_fdb_static_entries * sizeof(bridgeif_fdb_static_entry_t)));
alloc_len = (mem_size_t)alloc_len_sizet;
LWIP_ASSERT("alloc_len == alloc_len_sizet", alloc_len == alloc_len_sizet);
LWIP_DEBUGF(BRIDGEIF_DEBUG, ("bridgeif_init: allocating %d bytes for private data\n", (int)alloc_len));
br = (bridgeif_private_t *)mem_calloc(1, alloc_len);
if (br == NULL) {
LWIP_DEBUGF(NETIF_DEBUG, ("bridgeif_init: out of memory\n"));
return ERR_MEM;
}
memcpy(&br->ethaddr, &init_data->ethaddr, sizeof(br->ethaddr));
br->netif = netif;
br->max_ports = init_data->max_ports;
br->ports = (bridgeif_port_t *)(br + 1);
br->max_fdbs_entries = init_data->max_fdb_static_entries;
br->fdbs = (bridgeif_fdb_static_entry_t *)(((u8_t *)(br + 1)) + (init_data->max_ports * sizeof(bridgeif_port_t)));
br->max_fdbd_entries = init_data->max_fdb_dynamic_entries;
br->fdbd = bridgeif_fdb_init(init_data->max_fdb_dynamic_entries);
if (br->fdbd == NULL) {
LWIP_DEBUGF(NETIF_DEBUG, ("bridgeif_init: out of memory in fdb_init\n"));
mem_free(br);
return ERR_MEM;
}
#if LWIP_NETIF_HOSTNAME
/* Initialize interface hostname */
netif->hostname = "lwip";
#endif /* LWIP_NETIF_HOSTNAME */
/*
* 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.
*/
MIB2_INIT_NETIF(netif, snmp_ifType_ethernet_csmacd, 0);
netif->state = br;
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...) */
#if LWIP_IPV4
netif->output = etharp_output;
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
netif->output_ip6 = ethip6_output;
#endif /* LWIP_IPV6 */
netif->linkoutput = bridgeif_output;
/* set MAC hardware address length */
netif->hwaddr_len = ETH_HWADDR_LEN;
/* set MAC hardware address */
memcpy(netif->hwaddr, &br->ethaddr, ETH_HWADDR_LEN);
/* 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_ETHERNET | NETIF_FLAG_IGMP | NETIF_FLAG_MLD6 | NETIF_FLAG_LINK_UP;
#if LWIP_IPV6 && LWIP_IPV6_MLD
/*
* For hardware/netifs that implement MAC filtering.
* All-nodes link-local is handled by default, so we must let the hardware know
* to allow multicast packets in.
* Should set mld_mac_filter previously. */
if (netif->mld_mac_filter != NULL) {
ip6_addr_t ip6_allnodes_ll;
ip6_addr_set_allnodes_linklocal(&ip6_allnodes_ll);
netif->mld_mac_filter(netif, &ip6_allnodes_ll, NETIF_ADD_MAC_FILTER);
}
#endif /* LWIP_IPV6 && LWIP_IPV6_MLD */
return ERR_OK;
}
/**
* @ingroup bridgeif
* Add a port to the bridge
*/
err_t
bridgeif_add_port(struct netif *bridgeif, struct netif *portif)
{
bridgeif_private_t *br;
bridgeif_port_t *port;
LWIP_ASSERT("bridgeif != NULL", bridgeif != NULL);
LWIP_ASSERT("bridgeif->state != NULL", bridgeif->state != NULL);
LWIP_ASSERT("portif != NULL", portif != NULL);
if (!(portif->flags & NETIF_FLAG_ETHARP) || !(portif->flags & NETIF_FLAG_ETHERNET)) {
/* can only add ETHERNET/ETHARP interfaces */
return ERR_VAL;
}
br = (bridgeif_private_t *)bridgeif->state;
if (br->num_ports >= br->max_ports) {
return ERR_VAL;
}
port = &br->ports[br->num_ports];
port->port_netif = portif;
port->port_num = br->num_ports;
port->bridge = br;
br->num_ports++;
/* let the port call us on input */
#if BRIDGEIF_PORT_NETIFS_OUTPUT_DIRECT
portif->input = bridgeif_input;
#else
portif->input = bridgeif_tcpip_input;
#endif
/* store pointer to bridge in netif */
netif_set_client_data(portif, bridgeif_netif_client_id, port);
/* remove ETHARP flag to prevent sending report events on netif-up */
netif_clear_flags(portif, NETIF_FLAG_ETHARP);
return ERR_OK;
}
#endif /* LWIP_NUM_NETIF_CLIENT_DATA */

View File

@ -1,212 +0,0 @@
/**
* @file
* lwIP netif implementing an FDB for IEEE 802.1D MAC Bridge
*/
/*
* Copyright (c) 2017 Simon Goldschmidt.
* 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 <goldsimon@gmx.de>
*
*/
/**
* @defgroup bridgeif_fdb FDB example code
* @ingroup bridgeif
* This file implements an example for an FDB (Forwarding DataBase)
*/
#include "netif/bridgeif.h"
#include "lwip/sys.h"
#include "lwip/mem.h"
#include "lwip/timeouts.h"
#include <string.h>
#define BRIDGEIF_AGE_TIMER_MS 1000
#define BR_FDB_TIMEOUT_SEC (60*5) /* 5 minutes FDB timeout */
typedef struct bridgeif_dfdb_entry_s {
u8_t used;
u8_t port;
u32_t ts;
struct eth_addr addr;
} bridgeif_dfdb_entry_t;
typedef struct bridgeif_dfdb_s {
u16_t max_fdb_entries;
bridgeif_dfdb_entry_t *fdb;
} bridgeif_dfdb_t;
/**
* @ingroup bridgeif_fdb
* A real simple and slow implementation of an auto-learning forwarding database that
* remembers known src mac addresses to know which port to send frames destined for that
* mac address.
*
* ATTENTION: This is meant as an example only, in real-world use, you should
* provide a better implementation :-)
*/
void
bridgeif_fdb_update_src(void *fdb_ptr, struct eth_addr *src_addr, u8_t port_idx)
{
int i;
bridgeif_dfdb_t *fdb = (bridgeif_dfdb_t *)fdb_ptr;
BRIDGEIF_DECL_PROTECT(lev);
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < fdb->max_fdb_entries; i++) {
bridgeif_dfdb_entry_t *e = &fdb->fdb[i];
if (e->used && e->ts) {
if (!memcmp(&e->addr, src_addr, sizeof(struct eth_addr))) {
LWIP_DEBUGF(BRIDGEIF_FDB_DEBUG, ("br: update src %02x:%02x:%02x:%02x:%02x:%02x (from %d) @ idx %d\n",
src_addr->addr[0], src_addr->addr[1], src_addr->addr[2], src_addr->addr[3], src_addr->addr[4], src_addr->addr[5],
port_idx, i));
BRIDGEIF_WRITE_PROTECT(lev);
e->ts = BR_FDB_TIMEOUT_SEC;
e->port = port_idx;
BRIDGEIF_WRITE_UNPROTECT(lev);
BRIDGEIF_READ_UNPROTECT(lev);
return;
}
}
}
/* not found, allocate new entry from free */
for (i = 0; i < fdb->max_fdb_entries; i++) {
bridgeif_dfdb_entry_t *e = &fdb->fdb[i];
if (!e->used || !e->ts) {
BRIDGEIF_WRITE_PROTECT(lev);
/* check again when protected */
if (!e->used || !e->ts) {
LWIP_DEBUGF(BRIDGEIF_FDB_DEBUG, ("br: create src %02x:%02x:%02x:%02x:%02x:%02x (from %d) @ idx %d\n",
src_addr->addr[0], src_addr->addr[1], src_addr->addr[2], src_addr->addr[3], src_addr->addr[4], src_addr->addr[5],
port_idx, i));
memcpy(&e->addr, src_addr, sizeof(struct eth_addr));
e->ts = BR_FDB_TIMEOUT_SEC;
e->port = port_idx;
e->used = 1;
BRIDGEIF_WRITE_UNPROTECT(lev);
BRIDGEIF_READ_UNPROTECT(lev);
return;
}
BRIDGEIF_WRITE_UNPROTECT(lev);
}
}
BRIDGEIF_READ_UNPROTECT(lev);
/* not found, no free entry -> flood */
}
/**
* @ingroup bridgeif_fdb
* Walk our list of auto-learnt fdb entries and return a port to forward or BR_FLOOD if unknown
*/
bridgeif_portmask_t
bridgeif_fdb_get_dst_ports(void *fdb_ptr, struct eth_addr *dst_addr)
{
int i;
bridgeif_dfdb_t *fdb = (bridgeif_dfdb_t *)fdb_ptr;
BRIDGEIF_DECL_PROTECT(lev);
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < fdb->max_fdb_entries; i++) {
bridgeif_dfdb_entry_t *e = &fdb->fdb[i];
if (e->used && e->ts) {
if (!memcmp(&e->addr, dst_addr, sizeof(struct eth_addr))) {
bridgeif_portmask_t ret = (bridgeif_portmask_t)(1 << e->port);
BRIDGEIF_READ_UNPROTECT(lev);
return ret;
}
}
}
BRIDGEIF_READ_UNPROTECT(lev);
return BR_FLOOD;
}
/**
* @ingroup bridgeif_fdb
* Aging implementation of our simple fdb
*/
static void
bridgeif_fdb_age_one_second(void *fdb_ptr)
{
int i;
bridgeif_dfdb_t *fdb;
BRIDGEIF_DECL_PROTECT(lev);
fdb = (bridgeif_dfdb_t *)fdb_ptr;
BRIDGEIF_READ_PROTECT(lev);
for (i = 0; i < fdb->max_fdb_entries; i++) {
bridgeif_dfdb_entry_t *e = &fdb->fdb[i];
if (e->used && e->ts) {
BRIDGEIF_WRITE_PROTECT(lev);
/* check again when protected */
if (e->used && e->ts) {
if (--e->ts == 0) {
e->used = 0;
}
}
BRIDGEIF_WRITE_UNPROTECT(lev);
}
}
BRIDGEIF_READ_UNPROTECT(lev);
}
/** Timer callback for fdb aging, called once per second */
static void
bridgeif_age_tmr(void *arg)
{
bridgeif_dfdb_t *fdb = (bridgeif_dfdb_t *)arg;
LWIP_ASSERT("invalid arg", arg != NULL);
bridgeif_fdb_age_one_second(fdb);
sys_timeout(BRIDGEIF_AGE_TIMER_MS, bridgeif_age_tmr, arg);
}
/**
* @ingroup bridgeif_fdb
* Init our simple fdb list
*/
void *
bridgeif_fdb_init(u16_t max_fdb_entries)
{
bridgeif_dfdb_t *fdb;
size_t alloc_len_sizet = sizeof(bridgeif_dfdb_t) + (max_fdb_entries * sizeof(bridgeif_dfdb_entry_t));
mem_size_t alloc_len = (mem_size_t)alloc_len_sizet;
LWIP_ASSERT("alloc_len == alloc_len_sizet", alloc_len == alloc_len_sizet);
LWIP_DEBUGF(BRIDGEIF_DEBUG, ("bridgeif_fdb_init: allocating %d bytes for private FDB data\n", (int)alloc_len));
fdb = (bridgeif_dfdb_t *)mem_calloc(1, alloc_len);
if (fdb == NULL) {
return NULL;
}
fdb->max_fdb_entries = max_fdb_entries;
fdb->fdb = (bridgeif_dfdb_entry_t *)(fdb + 1);
sys_timeout(BRIDGEIF_AGE_TIMER_MS, bridgeif_age_tmr, fdb);
return fdb;
}

View File

@ -1,340 +0,0 @@
/**
* @file
* Ethernet common functions
*
* @defgroup ethernet Ethernet
* @ingroup callbackstyle_api
*/
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* Copyright (c) 2003-2004 Leon Woestenberg <leon.woestenberg@axon.tv>
* Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands.
* 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"
#if LWIP_ARP || LWIP_ETHERNET
#include "netif/ethernet.h"
#include "lwip/def.h"
#include "lwip/stats.h"
#include "lwip/etharp.h"
#include "lwip/ip.h"
#include "lwip/snmp.h"
#include <string.h>
#include "netif/ppp/ppp_opts.h"
#if PPPOE_SUPPORT
#include "netif/ppp/pppoe.h"
#endif /* PPPOE_SUPPORT */
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
const struct eth_addr ethbroadcast = {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
const struct eth_addr ethzero = {{0, 0, 0, 0, 0, 0}};
/**
* @ingroup lwip_nosys
* Process received ethernet frames. Using this function instead of directly
* calling ip_input and passing ARP frames through etharp in ethernetif_input,
* the ARP cache is protected from concurrent access.<br>
* Don't call directly, pass to netif_add() and call netif->input().
*
* @param p the received packet, p->payload pointing to the ethernet header
* @param netif the network interface on which the packet was received
*
* @see LWIP_HOOK_UNKNOWN_ETH_PROTOCOL
* @see ETHARP_SUPPORT_VLAN
* @see LWIP_HOOK_VLAN_CHECK
*/
err_t
ethernet_input(struct pbuf *p, struct netif *netif)
{
struct eth_hdr *ethhdr;
u16_t type;
#if LWIP_ARP || ETHARP_SUPPORT_VLAN || LWIP_IPV6
u16_t next_hdr_offset = SIZEOF_ETH_HDR;
#endif /* LWIP_ARP || ETHARP_SUPPORT_VLAN */
LWIP_ASSERT_CORE_LOCKED();
if (p->len <= SIZEOF_ETH_HDR) {
/* a packet with only an ethernet header (or less) is not valid for us */
ETHARP_STATS_INC(etharp.proterr);
ETHARP_STATS_INC(etharp.drop);
MIB2_STATS_NETIF_INC(netif, ifinerrors);
goto free_and_return;
}
if (p->if_idx == NETIF_NO_INDEX) {
p->if_idx = netif_get_index(netif);
}
/* points to packet payload, which starts with an Ethernet header */
ethhdr = (struct eth_hdr *)p->payload;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE,
("ethernet_input: dest:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", src:%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F":%"X8_F", type:%"X16_F"\n",
(unsigned char)ethhdr->dest.addr[0], (unsigned char)ethhdr->dest.addr[1], (unsigned char)ethhdr->dest.addr[2],
(unsigned char)ethhdr->dest.addr[3], (unsigned char)ethhdr->dest.addr[4], (unsigned char)ethhdr->dest.addr[5],
(unsigned char)ethhdr->src.addr[0], (unsigned char)ethhdr->src.addr[1], (unsigned char)ethhdr->src.addr[2],
(unsigned char)ethhdr->src.addr[3], (unsigned char)ethhdr->src.addr[4], (unsigned char)ethhdr->src.addr[5],
lwip_htons(ethhdr->type)));
type = ethhdr->type;
#if ETHARP_SUPPORT_VLAN
if (type == PP_HTONS(ETHTYPE_VLAN)) {
struct eth_vlan_hdr *vlan = (struct eth_vlan_hdr *)(((char *)ethhdr) + SIZEOF_ETH_HDR);
next_hdr_offset = SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR;
if (p->len <= SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR) {
/* a packet with only an ethernet/vlan header (or less) is not valid for us */
ETHARP_STATS_INC(etharp.proterr);
ETHARP_STATS_INC(etharp.drop);
MIB2_STATS_NETIF_INC(netif, ifinerrors);
goto free_and_return;
}
#if defined(LWIP_HOOK_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK_FN) /* if not, allow all VLANs */
#ifdef LWIP_HOOK_VLAN_CHECK
if (!LWIP_HOOK_VLAN_CHECK(netif, ethhdr, vlan)) {
#elif defined(ETHARP_VLAN_CHECK_FN)
if (!ETHARP_VLAN_CHECK_FN(ethhdr, vlan)) {
#elif defined(ETHARP_VLAN_CHECK)
if (VLAN_ID(vlan) != ETHARP_VLAN_CHECK) {
#endif
/* silently ignore this packet: not for our VLAN */
pbuf_free(p);
return ERR_OK;
}
#endif /* defined(LWIP_HOOK_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK) || defined(ETHARP_VLAN_CHECK_FN) */
type = vlan->tpid;
}
#endif /* ETHARP_SUPPORT_VLAN */
#if LWIP_ARP_FILTER_NETIF
netif = LWIP_ARP_FILTER_NETIF_FN(p, netif, lwip_htons(type));
#endif /* LWIP_ARP_FILTER_NETIF*/
if (ethhdr->dest.addr[0] & 1) {
/* this might be a multicast or broadcast packet */
if (ethhdr->dest.addr[0] == LL_IP4_MULTICAST_ADDR_0) {
#if LWIP_IPV4
if ((ethhdr->dest.addr[1] == LL_IP4_MULTICAST_ADDR_1) &&
(ethhdr->dest.addr[2] == LL_IP4_MULTICAST_ADDR_2)) {
/* mark the pbuf as link-layer multicast */
p->flags |= PBUF_FLAG_LLMCAST;
}
#endif /* LWIP_IPV4 */
}
#if LWIP_IPV6
else if ((ethhdr->dest.addr[0] == LL_IP6_MULTICAST_ADDR_0) &&
(ethhdr->dest.addr[1] == LL_IP6_MULTICAST_ADDR_1)) {
/* mark the pbuf as link-layer multicast */
p->flags |= PBUF_FLAG_LLMCAST;
}
#endif /* LWIP_IPV6 */
else if (eth_addr_cmp(&ethhdr->dest, &ethbroadcast)) {
/* mark the pbuf as link-layer broadcast */
p->flags |= PBUF_FLAG_LLBCAST;
}
}
switch (type) {
#if LWIP_IPV4 && LWIP_ARP
/* IP packet? */
case PP_HTONS(ETHTYPE_IP):
if (!(netif->flags & NETIF_FLAG_ETHARP)) {
goto free_and_return;
}
/* skip Ethernet header (min. size checked above) */
if (pbuf_remove_header(p, next_hdr_offset)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
("ethernet_input: IPv4 packet dropped, too short (%"U16_F"/%"U16_F")\n",
p->tot_len, next_hdr_offset));
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("Can't move over header in packet"));
goto free_and_return;
} else {
/* pass to IP layer */
ip4_input(p, netif);
}
break;
case PP_HTONS(ETHTYPE_ARP):
if (!(netif->flags & NETIF_FLAG_ETHARP)) {
goto free_and_return;
}
/* skip Ethernet header (min. size checked above) */
if (pbuf_remove_header(p, next_hdr_offset)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
("ethernet_input: ARP response packet dropped, too short (%"U16_F"/%"U16_F")\n",
p->tot_len, next_hdr_offset));
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("Can't move over header in packet"));
ETHARP_STATS_INC(etharp.lenerr);
ETHARP_STATS_INC(etharp.drop);
goto free_and_return;
} else {
/* pass p to ARP module */
etharp_input(p, netif);
}
break;
#endif /* LWIP_IPV4 && LWIP_ARP */
#if PPPOE_SUPPORT
case PP_HTONS(ETHTYPE_PPPOEDISC): /* PPP Over Ethernet Discovery Stage */
pppoe_disc_input(netif, p);
break;
case PP_HTONS(ETHTYPE_PPPOE): /* PPP Over Ethernet Session Stage */
pppoe_data_input(netif, p);
break;
#endif /* PPPOE_SUPPORT */
#if LWIP_IPV6
case PP_HTONS(ETHTYPE_IPV6): /* IPv6 */
/* skip Ethernet header */
if ((p->len < next_hdr_offset) || pbuf_remove_header(p, next_hdr_offset)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING,
("ethernet_input: IPv6 packet dropped, too short (%"U16_F"/%"U16_F")\n",
p->tot_len, next_hdr_offset));
goto free_and_return;
} else {
/* pass to IPv6 layer */
ip6_input(p, netif);
}
break;
#endif /* LWIP_IPV6 */
default:
#ifdef LWIP_HOOK_UNKNOWN_ETH_PROTOCOL
if (LWIP_HOOK_UNKNOWN_ETH_PROTOCOL(p, netif) == ERR_OK) {
break;
}
#endif
ETHARP_STATS_INC(etharp.proterr);
ETHARP_STATS_INC(etharp.drop);
MIB2_STATS_NETIF_INC(netif, ifinunknownprotos);
goto free_and_return;
}
/* This means the pbuf is freed or consumed,
so the caller doesn't have to free it again */
return ERR_OK;
free_and_return:
pbuf_free(p);
return ERR_OK;
}
/**
* @ingroup ethernet
* Send an ethernet packet on the network using netif->linkoutput().
* The ethernet header is filled in before sending.
*
* @see LWIP_HOOK_VLAN_SET
*
* @param netif the lwIP network interface on which to send the packet
* @param p the packet to send. pbuf layer must be @ref PBUF_LINK.
* @param src the source MAC address to be copied into the ethernet header
* @param dst the destination MAC address to be copied into the ethernet header
* @param eth_type ethernet type (@ref lwip_ieee_eth_type)
* @return ERR_OK if the packet was sent, any other err_t on failure
*/
err_t
ethernet_output(struct netif * netif, struct pbuf * p,
const struct eth_addr * src, const struct eth_addr * dst,
u16_t eth_type) {
struct eth_hdr *ethhdr;
u16_t eth_type_be = lwip_htons(eth_type);
#if ETHARP_SUPPORT_VLAN && (defined(LWIP_HOOK_VLAN_SET) || LWIP_VLAN_PCP)
s32_t vlan_prio_vid;
#ifdef LWIP_HOOK_VLAN_SET
vlan_prio_vid = LWIP_HOOK_VLAN_SET(netif, p, src, dst, eth_type);
#elif LWIP_VLAN_PCP
vlan_prio_vid = -1;
if (netif->hints && (netif->hints->tci >= 0)) {
vlan_prio_vid = (u16_t)netif->hints->tci;
}
#endif
if (vlan_prio_vid >= 0) {
struct eth_vlan_hdr *vlanhdr;
LWIP_ASSERT("prio_vid must be <= 0xFFFF", vlan_prio_vid <= 0xFFFF);
if (pbuf_add_header(p, SIZEOF_ETH_HDR + SIZEOF_VLAN_HDR) != 0) {
goto pbuf_header_failed;
}
vlanhdr = (struct eth_vlan_hdr *)(((u8_t *)p->payload) + SIZEOF_ETH_HDR);
vlanhdr->tpid = eth_type_be;
vlanhdr->prio_vid = lwip_htons((u16_t)vlan_prio_vid);
eth_type_be = PP_HTONS(ETHTYPE_VLAN);
} else
#endif /* ETHARP_SUPPORT_VLAN && (defined(LWIP_HOOK_VLAN_SET) || LWIP_VLAN_PCP) */
{
if (pbuf_add_header(p, SIZEOF_ETH_HDR) != 0) {
goto pbuf_header_failed;
}
}
LWIP_ASSERT_CORE_LOCKED();
ethhdr = (struct eth_hdr *)p->payload;
ethhdr->type = eth_type_be;
SMEMCPY(&ethhdr->dest, dst, ETH_HWADDR_LEN);
SMEMCPY(&ethhdr->src, src, ETH_HWADDR_LEN);
ethhdr->snap.hdr[0] = 0xAA;
ethhdr->snap.hdr[1] = 0xAA;
ethhdr->snap.hdr[2] = 0x03;
ethhdr->snap.hdr[3] = 0x00;
ethhdr->snap.hdr[4] = 0x00;
ethhdr->snap.hdr[5] = 0x00;
ethhdr->padding[0] = 0x00;
ethhdr->padding[1] = 0x1C;
u16_t eth_len = lwip_htons(p->len - 14);
ethhdr->len = eth_len;
LWIP_ASSERT("netif->hwaddr_len must be 6 for ethernet_output!",
(netif->hwaddr_len == ETH_HWADDR_LEN));
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE,
("ethernet_output: sending packet %p\n", (void *)p));
/* send the packet */
return netif->linkoutput(netif, p);
pbuf_header_failed:
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS,
("ethernet_output: could not allocate room for header.\n"));
LINK_STATS_INC(link.lenerr);
return ERR_BUF;
}
#endif /* LWIP_ARP || LWIP_ETHERNET */

View File

@ -1,921 +0,0 @@
/**
* @file
*
* 6LowPAN output for IPv6. Uses ND tables for link-layer addressing. Fragments packets to 6LowPAN units.
*
* This implementation aims to conform to IEEE 802.15.4(-2015), RFC 4944 and RFC 6282.
* @todo: RFC 6775.
*/
/*
* Copyright (c) 2015 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
/**
* @defgroup sixlowpan 6LoWPAN (RFC4944)
* @ingroup netifs
* 6LowPAN netif implementation
*/
#include "netif/lowpan6.h"
#if LWIP_IPV6
#include "lwip/ip.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/nd6.h"
#include "lwip/mem.h"
#include "lwip/udp.h"
#include "lwip/tcpip.h"
#include "lwip/snmp.h"
#include "netif/ieee802154.h"
#include <string.h>
#if LWIP_6LOWPAN_802154_HW_CRC
#define LWIP_6LOWPAN_DO_CALC_CRC(buf, len) 0
#else
#define LWIP_6LOWPAN_DO_CALC_CRC(buf, len) LWIP_6LOWPAN_CALC_CRC(buf, len)
#endif
/** This is a helper struct for reassembly of fragments
* (IEEE 802.15.4 limits to 127 bytes)
*/
struct lowpan6_reass_helper {
struct lowpan6_reass_helper *next_packet;
struct pbuf *reass;
struct pbuf *frags;
u8_t timer;
struct lowpan6_link_addr sender_addr;
u16_t datagram_size;
u16_t datagram_tag;
};
/** This struct keeps track of per-netif state */
struct lowpan6_ieee802154_data {
/** fragment reassembly list */
struct lowpan6_reass_helper *reass_list;
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
/** address context for compression */
ip6_addr_t lowpan6_context[LWIP_6LOWPAN_NUM_CONTEXTS];
#endif
/** Datagram Tag for fragmentation */
u16_t tx_datagram_tag;
/** local PAN ID for IEEE 802.15.4 header */
u16_t ieee_802154_pan_id;
/** Sequence Number for IEEE 802.15.4 transmission */
u8_t tx_frame_seq_num;
};
/* Maximum frame size is 127 bytes minus CRC size */
#define LOWPAN6_MAX_PAYLOAD (127 - 2)
/** Currently, this state is global, since there's only one 6LoWPAN netif */
static struct lowpan6_ieee802154_data lowpan6_data;
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
#define LWIP_6LOWPAN_CONTEXTS(netif) lowpan6_data.lowpan6_context
#else
#define LWIP_6LOWPAN_CONTEXTS(netif) NULL
#endif
static const struct lowpan6_link_addr ieee_802154_broadcast = {2, {0xff, 0xff}};
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
static struct lowpan6_link_addr short_mac_addr = {2, {0, 0}};
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
/* IEEE 802.15.4 specific functions: */
/** Write the IEEE 802.15.4 header that encapsulates the 6LoWPAN frame.
* Src and dst PAN IDs are filled with the ID set by @ref lowpan6_set_pan_id.
*
* Since the length is variable:
* @returns the header length
*/
static u8_t
lowpan6_write_iee802154_header(struct ieee_802154_hdr *hdr, const struct lowpan6_link_addr *src,
const struct lowpan6_link_addr *dst)
{
u8_t ieee_header_len;
u8_t *buffer;
u8_t i;
u16_t fc;
fc = IEEE_802154_FC_FT_DATA; /* send data packet (2003 frame version) */
fc |= IEEE_802154_FC_PANID_COMPR; /* set PAN ID compression, for now src and dst PANs are equal */
if (dst != &ieee_802154_broadcast) {
fc |= IEEE_802154_FC_ACK_REQ; /* data packet, no broadcast: ack required. */
}
if (dst->addr_len == 2) {
fc |= IEEE_802154_FC_DST_ADDR_MODE_SHORT;
} else {
LWIP_ASSERT("invalid dst address length", dst->addr_len == 8);
fc |= IEEE_802154_FC_DST_ADDR_MODE_EXT;
}
if (src->addr_len == 2) {
fc |= IEEE_802154_FC_SRC_ADDR_MODE_SHORT;
} else {
LWIP_ASSERT("invalid src address length", src->addr_len == 8);
fc |= IEEE_802154_FC_SRC_ADDR_MODE_EXT;
}
hdr->frame_control = fc;
hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;
hdr->destination_pan_id = lowpan6_data.ieee_802154_pan_id; /* pan id */
buffer = (u8_t *)hdr;
ieee_header_len = 5;
i = dst->addr_len;
/* reverse memcpy of dst addr */
while (i-- > 0) {
buffer[ieee_header_len++] = dst->addr[i];
}
/* Source PAN ID skipped due to PAN ID Compression */
i = src->addr_len;
/* reverse memcpy of src addr */
while (i-- > 0) {
buffer[ieee_header_len++] = src->addr[i];
}
return ieee_header_len;
}
/** Parse the IEEE 802.15.4 header from a pbuf.
* If successful, the header is hidden from the pbuf.
*
* PAN IDs and seuqence number are not checked
*
* @param p input pbuf, p->payload pointing at the IEEE 802.15.4 header
* @param src pointer to source address filled from the header
* @param dest pointer to destination address filled from the header
* @returns ERR_OK if successful
*/
static err_t
lowpan6_parse_iee802154_header(struct pbuf *p, struct lowpan6_link_addr *src,
struct lowpan6_link_addr *dest)
{
u8_t *puc;
s8_t i;
u16_t frame_control, addr_mode;
u16_t datagram_offset;
/* Parse IEEE 802.15.4 header */
puc = (u8_t *)p->payload;
frame_control = puc[0] | (puc[1] << 8);
datagram_offset = 2;
if (frame_control & IEEE_802154_FC_SEQNO_SUPPR) {
if (IEEE_802154_FC_FRAME_VERSION_GET(frame_control) <= 1) {
/* sequence number suppressed, this is not valid for versions 0/1 */
return ERR_VAL;
}
} else {
datagram_offset++;
}
datagram_offset += 2; /* Skip destination PAN ID */
addr_mode = frame_control & IEEE_802154_FC_DST_ADDR_MODE_MASK;
if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_EXT) {
/* extended address (64 bit) */
dest->addr_len = 8;
/* reverse memcpy: */
for (i = 0; i < 8; i++) {
dest->addr[i] = puc[datagram_offset + 7 - i];
}
datagram_offset += 8;
} else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
/* short address (16 bit) */
dest->addr_len = 2;
/* reverse memcpy: */
dest->addr[0] = puc[datagram_offset + 1];
dest->addr[1] = puc[datagram_offset];
datagram_offset += 2;
} else {
/* unsupported address mode (do we need "no address"?) */
return ERR_VAL;
}
if (!(frame_control & IEEE_802154_FC_PANID_COMPR)) {
/* No PAN ID compression, skip source PAN ID */
datagram_offset += 2;
}
addr_mode = frame_control & IEEE_802154_FC_SRC_ADDR_MODE_MASK;
if (addr_mode == IEEE_802154_FC_SRC_ADDR_MODE_EXT) {
/* extended address (64 bit) */
src->addr_len = 8;
/* reverse memcpy: */
for (i = 0; i < 8; i++) {
src->addr[i] = puc[datagram_offset + 7 - i];
}
datagram_offset += 8;
} else if (addr_mode == IEEE_802154_FC_DST_ADDR_MODE_SHORT) {
/* short address (16 bit) */
src->addr_len = 2;
src->addr[0] = puc[datagram_offset + 1];
src->addr[1] = puc[datagram_offset];
datagram_offset += 2;
} else {
/* unsupported address mode (do we need "no address"?) */
return ERR_VAL;
}
/* hide IEEE802.15.4 header. */
if (pbuf_remove_header(p, datagram_offset)) {
return ERR_VAL;
}
return ERR_OK;
}
/** Calculate the 16-bit CRC as required by IEEE 802.15.4 */
u16_t
lowpan6_calc_crc(const void* buf, u16_t len)
{
#define CCITT_POLY_16 0x8408U
u16_t i;
u8_t b;
u16_t crc = 0;
const u8_t* p = (const u8_t*)buf;
for (i = 0; i < len; i++) {
u8_t data = *p;
for (b = 0U; b < 8U; b++) {
if (((data ^ crc) & 1) != 0) {
crc = (u16_t)((crc >> 1) ^ CCITT_POLY_16);
} else {
crc = (u16_t)(crc >> 1);
}
data = (u8_t)(data >> 1);
}
p++;
}
return crc;
}
/* Fragmentation specific functions: */
static void
free_reass_datagram(struct lowpan6_reass_helper *lrh)
{
if (lrh->reass) {
pbuf_free(lrh->reass);
}
if (lrh->frags) {
pbuf_free(lrh->frags);
}
mem_free(lrh);
}
/**
* Removes a datagram from the reassembly queue.
**/
static void
dequeue_datagram(struct lowpan6_reass_helper *lrh, struct lowpan6_reass_helper *prev)
{
if (lowpan6_data.reass_list == lrh) {
lowpan6_data.reass_list = lowpan6_data.reass_list->next_packet;
} else {
/* it wasn't the first, so it must have a valid 'prev' */
LWIP_ASSERT("sanity check linked list", prev != NULL);
prev->next_packet = lrh->next_packet;
}
}
/**
* Periodic timer for 6LowPAN functions:
*
* - Remove incomplete/old packets
*/
void
lowpan6_tmr(void)
{
struct lowpan6_reass_helper *lrh, *lrh_next, *lrh_prev = NULL;
lrh = lowpan6_data.reass_list;
while (lrh != NULL) {
lrh_next = lrh->next_packet;
if ((--lrh->timer) == 0) {
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
} else {
lrh_prev = lrh;
}
lrh = lrh_next;
}
}
/*
* Encapsulates data into IEEE 802.15.4 frames.
* Fragments an IPv6 datagram into 6LowPAN units, which fit into IEEE 802.15.4 frames.
* If configured, will compress IPv6 and or UDP headers.
* */
static err_t
lowpan6_frag(struct netif *netif, struct pbuf *p, const struct lowpan6_link_addr *src, const struct lowpan6_link_addr *dst)
{
struct pbuf *p_frag;
u16_t frag_len, remaining_len, max_data_len;
u8_t *buffer;
u8_t ieee_header_len;
u8_t lowpan6_header_len;
u8_t hidden_header_len;
u16_t crc;
u16_t datagram_offset;
err_t err = ERR_IF;
LWIP_ASSERT("lowpan6_frag: netif->linkoutput not set", netif->linkoutput != NULL);
/* We'll use a dedicated pbuf for building 6LowPAN fragments. */
p_frag = pbuf_alloc(PBUF_RAW, 127, PBUF_RAM);
if (p_frag == NULL) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece", p_frag->len == p_frag->tot_len);
/* Write IEEE 802.15.4 header. */
buffer = (u8_t *)p_frag->payload;
ieee_header_len = lowpan6_write_iee802154_header((struct ieee_802154_hdr *)buffer, src, dst);
LWIP_ASSERT("ieee_header_len < p_frag->len", ieee_header_len < p_frag->len);
#if LWIP_6LOWPAN_IPHC
/* Perform 6LowPAN IPv6 header compression according to RFC 6282 */
/* do the header compression (this does NOT copy any non-compressed data) */
err = lowpan6_compress_headers(netif, (u8_t *)p->payload, p->len,
&buffer[ieee_header_len], p_frag->len - ieee_header_len, &lowpan6_header_len,
&hidden_header_len, LWIP_6LOWPAN_CONTEXTS(netif), src, dst);
if (err != ERR_OK) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
pbuf_free(p_frag);
return err;
}
pbuf_remove_header(p, hidden_header_len);
#else /* LWIP_6LOWPAN_IPHC */
/* Send uncompressed IPv6 header with appropriate dispatch byte. */
lowpan6_header_len = 1;
hidden_header_len = 0;
buffer[ieee_header_len] = 0x41; /* IPv6 dispatch */
#endif /* LWIP_6LOWPAN_IPHC */
/* Calculate remaining packet length */
remaining_len = p->tot_len;
if (remaining_len > 0x7FF) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
/* datagram_size must fit into 11 bit */
pbuf_free(p_frag);
return ERR_VAL;
}
/* Fragment, or 1 packet? */
max_data_len = LOWPAN6_MAX_PAYLOAD - ieee_header_len - lowpan6_header_len;
if (remaining_len > max_data_len) {
u16_t data_len;
/* We must move the 6LowPAN header to make room for the FRAG header. */
memmove(&buffer[ieee_header_len + 4], &buffer[ieee_header_len], lowpan6_header_len);
/* Now we need to fragment the packet. FRAG1 header first */
buffer[ieee_header_len] = 0xc0 | (((p->tot_len + hidden_header_len) >> 8) & 0x7);
buffer[ieee_header_len + 1] = (p->tot_len + hidden_header_len) & 0xff;
lowpan6_data.tx_datagram_tag++;
buffer[ieee_header_len + 2] = (lowpan6_data.tx_datagram_tag >> 8) & 0xff;
buffer[ieee_header_len + 3] = lowpan6_data.tx_datagram_tag & 0xff;
/* Fragment follows. */
data_len = (max_data_len - 4) & 0xf8;
frag_len = data_len + lowpan6_header_len;
pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len + 4, frag_len - lowpan6_header_len, 0);
remaining_len -= frag_len - lowpan6_header_len;
/* datagram offset holds the offset before compression */
datagram_offset = frag_len - lowpan6_header_len + hidden_header_len;
LWIP_ASSERT("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);
/* Calculate frame length */
p_frag->len = p_frag->tot_len = ieee_header_len + 4 + frag_len + 2; /* add 2 bytes for crc*/
/* 2 bytes CRC */
crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);
/* send the packet */
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
err = netif->linkoutput(netif, p_frag);
while ((remaining_len > 0) && (err == ERR_OK)) {
struct ieee_802154_hdr *hdr = (struct ieee_802154_hdr *)buffer;
/* new frame, new seq num for ACK */
hdr->sequence_number = lowpan6_data.tx_frame_seq_num++;
buffer[ieee_header_len] |= 0x20; /* Change FRAG1 to FRAGN */
LWIP_ASSERT("datagram offset must be a multiple of 8", (datagram_offset & 7) == 0);
buffer[ieee_header_len + 4] = (u8_t)(datagram_offset >> 3); /* datagram offset in FRAGN header (datagram_offset is max. 11 bit) */
frag_len = (127 - ieee_header_len - 5 - 2) & 0xf8;
if (frag_len > remaining_len) {
frag_len = remaining_len;
}
pbuf_copy_partial(p, buffer + ieee_header_len + 5, frag_len, p->tot_len - remaining_len);
remaining_len -= frag_len;
datagram_offset += frag_len;
/* Calculate frame length */
p_frag->len = p_frag->tot_len = frag_len + 5 + ieee_header_len + 2;
/* 2 bytes CRC */
crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);
/* send the packet */
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
err = netif->linkoutput(netif, p_frag);
}
} else {
/* It fits in one frame. */
frag_len = remaining_len;
/* Copy IPv6 packet */
pbuf_copy_partial(p, buffer + ieee_header_len + lowpan6_header_len, frag_len, 0);
remaining_len = 0;
/* Calculate frame length */
p_frag->len = p_frag->tot_len = frag_len + lowpan6_header_len + ieee_header_len + 2;
LWIP_ASSERT("", p_frag->len <= 127);
/* 2 bytes CRC */
crc = LWIP_6LOWPAN_DO_CALC_CRC(p_frag->payload, p_frag->len - 2);
pbuf_take_at(p_frag, &crc, 2, p_frag->len - 2);
/* send the packet */
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG | LWIP_DBG_TRACE, ("lowpan6_send: sending packet %p\n", (void *)p));
err = netif->linkoutput(netif, p_frag);
}
pbuf_free(p_frag);
return err;
}
/**
* @ingroup sixlowpan
* Set context
*/
err_t
lowpan6_set_context(u8_t idx, const ip6_addr_t *context)
{
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
if (idx >= LWIP_6LOWPAN_NUM_CONTEXTS) {
return ERR_ARG;
}
IP6_ADDR_ZONECHECK(context);
ip6_addr_set(&lowpan6_data.lowpan6_context[idx], context);
return ERR_OK;
#else
LWIP_UNUSED_ARG(idx);
LWIP_UNUSED_ARG(context);
return ERR_ARG;
#endif
}
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
/**
* @ingroup sixlowpan
* Set short address
*/
err_t
lowpan6_set_short_addr(u8_t addr_high, u8_t addr_low)
{
short_mac_addr.addr[0] = addr_high;
short_mac_addr.addr[1] = addr_low;
return ERR_OK;
}
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
/* Create IEEE 802.15.4 address from netif address */
static err_t
lowpan6_hwaddr_to_addr(struct netif *netif, struct lowpan6_link_addr *addr)
{
addr->addr_len = 8;
if (netif->hwaddr_len == 8) {
LWIP_ERROR("NETIF_MAX_HWADDR_LEN >= 8 required", sizeof(netif->hwaddr) >= 8, return ERR_VAL;);
SMEMCPY(addr->addr, netif->hwaddr, 8);
} else if (netif->hwaddr_len == 6) {
/* Copy from MAC-48 */
SMEMCPY(addr->addr, netif->hwaddr, 3);
addr->addr[3] = addr->addr[4] = 0xff;
SMEMCPY(&addr->addr[5], &netif->hwaddr[3], 3);
} else {
/* Invalid address length, don't know how to convert this */
return ERR_VAL;
}
return ERR_OK;
}
/**
* @ingroup sixlowpan
* Resolve and fill-in IEEE 802.15.4 address header for outgoing IPv6 packet.
*
* Perform Header Compression and fragment if necessary.
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The pbuf(s) containing the IP packet to be sent.
* @param ip6addr The IP address of the packet destination.
*
* @return err_t
*/
err_t
lowpan6_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
{
err_t result;
const u8_t *hwaddr;
struct lowpan6_link_addr src, dest;
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
ip6_addr_t ip6_src;
struct ip6_hdr *ip6_hdr;
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
/* Check if we can compress source address (use aligned copy) */
ip6_hdr = (struct ip6_hdr *)q->payload;
ip6_addr_copy_from_packed(ip6_src, ip6_hdr->src);
ip6_addr_assign_zone(&ip6_src, IP6_UNICAST, netif);
if (lowpan6_get_address_mode(&ip6_src, &short_mac_addr) == 3) {
src.addr_len = 2;
src.addr[0] = short_mac_addr.addr[0];
src.addr[1] = short_mac_addr.addr[1];
} else
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
{
result = lowpan6_hwaddr_to_addr(netif, &src);
if (result != ERR_OK) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
return result;
}
}
/* multicast destination IP address? */
if (ip6_addr_ismulticast(ip6addr)) {
MIB2_STATS_NETIF_INC(netif, ifoutnucastpkts);
/* We need to send to the broadcast address.*/
return lowpan6_frag(netif, q, &src, &ieee_802154_broadcast);
}
/* We have a unicast destination IP address */
/* @todo anycast? */
#if LWIP_6LOWPAN_INFER_SHORT_ADDRESS
if (src.addr_len == 2) {
/* If source address was compressible to short_mac_addr, and dest has same subnet and
* is also compressible to 2-bytes, assume we can infer dest as a short address too. */
dest.addr_len = 2;
dest.addr[0] = ((u8_t *)q->payload)[38];
dest.addr[1] = ((u8_t *)q->payload)[39];
if ((src.addr_len == 2) && (ip6_addr_net_zoneless_eq(&ip6_hdr->src, &ip6_hdr->dest)) &&
(lowpan6_get_address_mode(ip6addr, &dest) == 3)) {
MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
return lowpan6_frag(netif, q, &src, &dest);
}
}
#endif /* LWIP_6LOWPAN_INFER_SHORT_ADDRESS */
/* Ask ND6 what to do with the packet. */
result = nd6_get_next_hop_addr_or_queue(netif, q, ip6addr, &hwaddr);
if (result != ERR_OK) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
return result;
}
/* If no hardware address is returned, nd6 has queued the packet for later. */
if (hwaddr == NULL) {
return ERR_OK;
}
/* Send out the packet using the returned hardware address. */
dest.addr_len = netif->hwaddr_len;
/* XXX: Inferring the length of the source address from the destination address
* is not correct for IEEE 802.15.4, but currently we don't get this information
* from the neighbor cache */
SMEMCPY(dest.addr, hwaddr, netif->hwaddr_len);
MIB2_STATS_NETIF_INC(netif, ifoutucastpkts);
return lowpan6_frag(netif, q, &src, &dest);
}
/**
* @ingroup sixlowpan
* NETIF input function: don't free the input pbuf when returning != ERR_OK!
*/
err_t
lowpan6_input(struct pbuf *p, struct netif *netif)
{
u8_t *puc, b;
s8_t i;
struct lowpan6_link_addr src, dest;
u16_t datagram_size = 0;
u16_t datagram_offset, datagram_tag;
struct lowpan6_reass_helper *lrh, *lrh_next, *lrh_prev = NULL;
if (p == NULL) {
return ERR_OK;
}
MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);
if (p->len != p->tot_len) {
/* for now, this needs a pbuf in one piece */
goto lowpan6_input_discard;
}
if (lowpan6_parse_iee802154_header(p, &src, &dest) != ERR_OK) {
goto lowpan6_input_discard;
}
/* Check dispatch. */
puc = (u8_t *)p->payload;
b = *puc;
if ((b & 0xf8) == 0xc0) {
/* FRAG1 dispatch. add this packet to reassembly list. */
datagram_size = ((u16_t)(puc[0] & 0x07) << 8) | (u16_t)puc[1];
datagram_tag = ((u16_t)puc[2] << 8) | (u16_t)puc[3];
/* check for duplicate */
lrh = lowpan6_data.reass_list;
while (lrh != NULL) {
u8_t discard = 0;
lrh_next = lrh->next_packet;
if ((lrh->sender_addr.addr_len == src.addr_len) &&
(memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0)) {
/* address match with packet in reassembly. */
if ((datagram_tag == lrh->datagram_tag) && (datagram_size == lrh->datagram_size)) {
/* duplicate fragment. */
goto lowpan6_input_discard;
} else {
/* We are receiving the start of a new datagram. Discard old one (incomplete). */
discard = 1;
}
}
if (discard) {
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
} else {
lrh_prev = lrh;
}
/* Check next datagram in queue. */
lrh = lrh_next;
}
pbuf_remove_header(p, 4); /* hide frag1 dispatch */
lrh = (struct lowpan6_reass_helper *) mem_malloc(sizeof(struct lowpan6_reass_helper));
if (lrh == NULL) {
goto lowpan6_input_discard;
}
lrh->sender_addr.addr_len = src.addr_len;
for (i = 0; i < src.addr_len; i++) {
lrh->sender_addr.addr[i] = src.addr[i];
}
lrh->datagram_size = datagram_size;
lrh->datagram_tag = datagram_tag;
lrh->frags = NULL;
if (*(u8_t *)p->payload == 0x41) {
/* This is a complete IPv6 packet, just skip dispatch byte. */
pbuf_remove_header(p, 1); /* hide dispatch byte. */
lrh->reass = p;
} else if ((*(u8_t *)p->payload & 0xe0 ) == 0x60) {
lrh->reass = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
if (lrh->reass == NULL) {
/* decompression failed */
mem_free(lrh);
goto lowpan6_input_discard;
}
}
/* TODO: handle the case where we already have FRAGN received */
lrh->next_packet = lowpan6_data.reass_list;
lrh->timer = 2;
lowpan6_data.reass_list = lrh;
return ERR_OK;
} else if ((b & 0xf8) == 0xe0) {
/* FRAGN dispatch, find packet being reassembled. */
datagram_size = ((u16_t)(puc[0] & 0x07) << 8) | (u16_t)puc[1];
datagram_tag = ((u16_t)puc[2] << 8) | (u16_t)puc[3];
datagram_offset = (u16_t)puc[4] << 3;
pbuf_remove_header(p, 4); /* hide frag1 dispatch but keep datagram offset for reassembly */
for (lrh = lowpan6_data.reass_list; lrh != NULL; lrh_prev = lrh, lrh = lrh->next_packet) {
if ((lrh->sender_addr.addr_len == src.addr_len) &&
(memcmp(lrh->sender_addr.addr, src.addr, src.addr_len) == 0) &&
(datagram_tag == lrh->datagram_tag) &&
(datagram_size == lrh->datagram_size)) {
break;
}
}
if (lrh == NULL) {
/* rogue fragment */
goto lowpan6_input_discard;
}
/* Insert new pbuf into list of fragments. Each fragment is a pbuf,
this only works for unchained pbufs. */
LWIP_ASSERT("p->next == NULL", p->next == NULL);
if (lrh->reass != NULL) {
/* FRAG1 already received, check this offset against first len */
if (datagram_offset < lrh->reass->len) {
/* fragment overlap, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
}
if (lrh->frags == NULL) {
/* first FRAGN */
lrh->frags = p;
} else {
/* find the correct place to insert */
struct pbuf *q, *last;
u16_t new_frag_len = p->len - 1; /* p->len includes datagram_offset byte */
for (q = lrh->frags, last = NULL; q != NULL; last = q, q = q->next) {
u16_t q_datagram_offset = ((u8_t *)q->payload)[0] << 3;
u16_t q_frag_len = q->len - 1;
if (datagram_offset < q_datagram_offset) {
if (datagram_offset + new_frag_len > q_datagram_offset) {
/* overlap, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
/* insert here */
break;
} else if (datagram_offset == q_datagram_offset) {
if (q_frag_len != new_frag_len) {
/* fragment mismatch, discard old fragments */
dequeue_datagram(lrh, lrh_prev);
free_reass_datagram(lrh);
goto lowpan6_input_discard;
}
/* duplicate, ignore */
pbuf_free(p);
return ERR_OK;
}
}
/* insert fragment */
if (last == NULL) {
lrh->frags = p;
} else {
last->next = p;
p->next = q;
}
}
/* check if all fragments were received */
if (lrh->reass) {
u16_t offset = lrh->reass->len;
struct pbuf *q;
for (q = lrh->frags; q != NULL; q = q->next) {
u16_t q_datagram_offset = ((u8_t *)q->payload)[0] << 3;
if (q_datagram_offset != offset) {
/* not complete, wait for more fragments */
return ERR_OK;
}
offset += q->len - 1;
}
if (offset == datagram_size) {
/* all fragments received, combine pbufs */
u16_t datagram_left = datagram_size - lrh->reass->len;
for (q = lrh->frags; q != NULL; q = q->next) {
/* hide datagram_offset byte now */
pbuf_remove_header(q, 1);
q->tot_len = datagram_left;
datagram_left -= q->len;
}
LWIP_ASSERT("datagram_left == 0", datagram_left == 0);
q = lrh->reass;
q->tot_len = datagram_size;
q->next = lrh->frags;
lrh->frags = NULL;
lrh->reass = NULL;
dequeue_datagram(lrh, lrh_prev);
mem_free(lrh);
/* @todo: distinguish unicast/multicast */
MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
return ip6_input(q, netif);
}
}
/* pbuf enqueued, waiting for more fragments */
return ERR_OK;
} else {
if (b == 0x41) {
/* This is a complete IPv6 packet, just skip dispatch byte. */
pbuf_remove_header(p, 1); /* hide dispatch byte. */
} else if ((b & 0xe0 ) == 0x60) {
/* IPv6 headers are compressed using IPHC. */
p = lowpan6_decompress(p, datagram_size, LWIP_6LOWPAN_CONTEXTS(netif), &src, &dest);
if (p == NULL) {
MIB2_STATS_NETIF_INC(netif, ifindiscards);
return ERR_OK;
}
} else {
goto lowpan6_input_discard;
}
/* @todo: distinguish unicast/multicast */
MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
return ip6_input(p, netif);
}
lowpan6_input_discard:
MIB2_STATS_NETIF_INC(netif, ifindiscards);
pbuf_free(p);
/* always return ERR_OK here to prevent the caller freeing the pbuf */
return ERR_OK;
}
/**
* @ingroup sixlowpan
*/
err_t
lowpan6_if_init(struct netif *netif)
{
netif->name[0] = 'L';
netif->name[1] = '6';
netif->output_ip6 = lowpan6_output;
MIB2_INIT_NETIF(netif, snmp_ifType_other, 0);
/* maximum transfer unit */
netif->mtu = IP6_MIN_MTU_LENGTH;
/* broadcast capability */
netif->flags = NETIF_FLAG_BROADCAST /* | NETIF_FLAG_LOWPAN6 */;
return ERR_OK;
}
/**
* @ingroup sixlowpan
* Set PAN ID
*/
err_t
lowpan6_set_pan_id(u16_t pan_id)
{
lowpan6_data.ieee_802154_pan_id = pan_id;
return ERR_OK;
}
#if !NO_SYS
/**
* @ingroup sixlowpan
* Pass a received packet to tcpip_thread for input processing
*
* @param p the received packet, p->payload pointing to the
* IEEE 802.15.4 header.
* @param inp the network interface on which the packet was received
*/
err_t
tcpip_6lowpan_input(struct pbuf *p, struct netif *inp)
{
return tcpip_inpkt(p, inp, lowpan6_input);
}
#endif /* !NO_SYS */
#endif /* LWIP_IPV6 */

View File

@ -1,447 +0,0 @@
/**
* @file
* 6LowPAN over BLE output for IPv6 (RFC7668).
*/
/*
* Copyright (c) 2017 Benjamin Aigner
* Copyright (c) 2015 Inico Technologies Ltd. , Author: Ivan Delamer <delamer@inicotech.com>
*
* 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: Benjamin Aigner <aignerb@technikum-wien.at>
*
* Based on the original 6lowpan implementation of lwIP ( @see 6lowpan.c)
*/
/**
* @defgroup rfc7668if 6LoWPAN over BLE (RFC7668)
* @ingroup netifs
* This file implements a RFC7668 implementation for 6LoWPAN over
* Bluetooth Low Energy. The specification is very similar to 6LoWPAN,
* so most of the code is re-used.
* Compared to 6LoWPAN, much functionality is already implemented in
* lower BLE layers (fragmenting, session management,...).
*
* Usage:
* - add this netif
* - don't add IPv4 addresses (no IPv4 support in RFC7668), pass 'NULL','NULL','NULL'
* - use the BLE to EUI64 conversation util to create an IPv6 link-local address from the BLE MAC (@ref ble_addr_to_eui64)
* - input function: @ref rfc7668_input
* - set the link output function, which transmits output data to an established L2CAP channel
* - If data arrives (HCI event "L2CAP_DATA_PACKET"):
* - allocate a @ref PBUF_RAW buffer
* - let the pbuf struct point to the incoming data or copy it to the buffer
* - call netif->input
*
* @todo:
* - further testing
* - support compression contexts
* - support multiple addresses
* - support multicast
* - support neighbor discovery
*/
#include "netif/lowpan6_ble.h"
#if LWIP_IPV6
#include "lwip/ip.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/nd6.h"
#include "lwip/mem.h"
#include "lwip/udp.h"
#include "lwip/tcpip.h"
#include "lwip/snmp.h"
#include <string.h>
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
/** context memory, containing IPv6 addresses */
static ip6_addr_t rfc7668_context[LWIP_6LOWPAN_NUM_CONTEXTS];
#else
#define rfc7668_context NULL
#endif
static struct lowpan6_link_addr rfc7668_local_addr;
static struct lowpan6_link_addr rfc7668_peer_addr;
/**
* @ingroup rfc7668if
* convert BT address to EUI64 addr
*
* This method converts a Bluetooth MAC address to an EUI64 address,
* which is used within IPv6 communication
*
* @param dst IPv6 destination space
* @param src BLE MAC address source
* @param public_addr If the LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS
* option is set, bit 0x02 will be set if param=0 (no public addr); cleared otherwise
*
* @see LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS
*/
void
ble_addr_to_eui64(u8_t *dst, const u8_t *src, int public_addr)
{
/* according to RFC7668 ch 3.2.2. */
memcpy(dst, src, 3);
dst[3] = 0xFF;
dst[4] = 0xFE;
memcpy(&dst[5], &src[3], 3);
#if LWIP_RFC7668_LINUX_WORKAROUND_PUBLIC_ADDRESS
if(public_addr) {
dst[0] &= ~0x02;
} else {
dst[0] |= 0x02;
}
#else
LWIP_UNUSED_ARG(public_addr);
#endif
}
/**
* @ingroup rfc7668if
* convert EUI64 address to Bluetooth MAC addr
*
* This method converts an EUI64 address to a Bluetooth MAC address,
*
* @param dst BLE MAC address destination
* @param src IPv6 source
*
*/
void
eui64_to_ble_addr(u8_t *dst, const u8_t *src)
{
/* according to RFC7668 ch 3.2.2. */
memcpy(dst,src,3);
memcpy(&dst[3],&src[5],3);
}
/** Set an address used for stateful compression.
* This expects an address of 6 or 8 bytes.
*/
static err_t
rfc7668_set_addr(struct lowpan6_link_addr *addr, const u8_t *in_addr, size_t in_addr_len, int is_mac_48, int is_public_addr)
{
if ((in_addr == NULL) || (addr == NULL)) {
return ERR_VAL;
}
if (is_mac_48) {
if (in_addr_len != 6) {
return ERR_VAL;
}
addr->addr_len = 8;
ble_addr_to_eui64(addr->addr, in_addr, is_public_addr);
} else {
if (in_addr_len != 8) {
return ERR_VAL;
}
addr->addr_len = 8;
memcpy(addr->addr, in_addr, 8);
}
return ERR_OK;
}
/** Set the local address used for stateful compression.
* This expects an address of 8 bytes.
*/
err_t
rfc7668_set_local_addr_eui64(struct netif *netif, const u8_t *local_addr, size_t local_addr_len)
{
/* netif not used for now, the address is stored globally... */
LWIP_UNUSED_ARG(netif);
return rfc7668_set_addr(&rfc7668_local_addr, local_addr, local_addr_len, 0, 0);
}
/** Set the local address used for stateful compression.
* This expects an address of 6 bytes.
*/
err_t
rfc7668_set_local_addr_mac48(struct netif *netif, const u8_t *local_addr, size_t local_addr_len, int is_public_addr)
{
/* netif not used for now, the address is stored globally... */
LWIP_UNUSED_ARG(netif);
return rfc7668_set_addr(&rfc7668_local_addr, local_addr, local_addr_len, 1, is_public_addr);
}
/** Set the peer address used for stateful compression.
* This expects an address of 8 bytes.
*/
err_t
rfc7668_set_peer_addr_eui64(struct netif *netif, const u8_t *peer_addr, size_t peer_addr_len)
{
/* netif not used for now, the address is stored globally... */
LWIP_UNUSED_ARG(netif);
return rfc7668_set_addr(&rfc7668_peer_addr, peer_addr, peer_addr_len, 0, 0);
}
/** Set the peer address used for stateful compression.
* This expects an address of 6 bytes.
*/
err_t
rfc7668_set_peer_addr_mac48(struct netif *netif, const u8_t *peer_addr, size_t peer_addr_len, int is_public_addr)
{
/* netif not used for now, the address is stored globally... */
LWIP_UNUSED_ARG(netif);
return rfc7668_set_addr(&rfc7668_peer_addr, peer_addr, peer_addr_len, 1, is_public_addr);
}
/** Encapsulate IPv6 frames for BLE transmission
*
* This method implements the IPv6 header compression:
* *) According to RFC6282
* *) See Figure 2, contains base format of bit positions
* *) Fragmentation not necessary (done at L2CAP layer of BLE)
* @note Currently the pbuf allocation uses 256 bytes. If longer packets are used (possible due to MTU=1480Bytes), increase it here!
*
* @param p Pbuf struct, containing the payload data
* @param netif Output network interface. Should be of RFC7668 type
*
* @return Same as netif->output.
*/
static err_t
rfc7668_compress(struct netif *netif, struct pbuf *p)
{
struct pbuf *p_frag;
u16_t remaining_len;
u8_t *buffer;
u8_t lowpan6_header_len;
u8_t hidden_header_len;
err_t err;
LWIP_ASSERT("lowpan6_frag: netif->linkoutput not set", netif->linkoutput != NULL);
#if LWIP_6LOWPAN_IPHC
/* We'll use a dedicated pbuf for building BLE fragments.
* We'll over-allocate it by the bytes saved for header compression.
*/
p_frag = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if (p_frag == NULL) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
return ERR_MEM;
}
LWIP_ASSERT("this needs a pbuf in one piece", p_frag->len == p_frag->tot_len);
/* Write IP6 header (with IPHC). */
buffer = (u8_t*)p_frag->payload;
err = lowpan6_compress_headers(netif, (u8_t *)p->payload, p->len, buffer, p_frag->len,
&lowpan6_header_len, &hidden_header_len, rfc7668_context, &rfc7668_local_addr, &rfc7668_peer_addr);
if (err != ERR_OK) {
MIB2_STATS_NETIF_INC(netif, ifoutdiscards);
pbuf_free(p_frag);
return err;
}
pbuf_remove_header(p, hidden_header_len);
/* Calculate remaining packet length */
remaining_len = p->tot_len;
/* Copy IPv6 packet */
pbuf_copy_partial(p, buffer + lowpan6_header_len, remaining_len, 0);
/* Calculate frame length */
p_frag->len = p_frag->tot_len = remaining_len + lowpan6_header_len;
/* send the packet */
MIB2_STATS_NETIF_ADD(netif, ifoutoctets, p_frag->tot_len);
LWIP_DEBUGF(LWIP_LOWPAN6_DEBUG|LWIP_DBG_TRACE, ("rfc7668_output: sending packet %p\n", (void *)p));
err = netif->linkoutput(netif, p_frag);
pbuf_free(p_frag);
return err;
#else /* LWIP_6LOWPAN_IPHC */
/* 6LoWPAN over BLE requires IPHC! */
return ERR_IF;
#endif/* LWIP_6LOWPAN_IPHC */
}
/**
* @ingroup rfc7668if
* Set context id IPv6 address
*
* Store one IPv6 address to a given context id.
*
* @param idx Context id
* @param context IPv6 addr for this context
*
* @return ERR_OK (if everything is fine), ERR_ARG (if the context id is out of range), ERR_VAL (if contexts disabled)
*/
err_t
rfc7668_set_context(u8_t idx, const ip6_addr_t *context)
{
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
/* check if the ID is possible */
if (idx >= LWIP_6LOWPAN_NUM_CONTEXTS) {
return ERR_ARG;
}
/* copy IPv6 address to context storage */
ip6_addr_set(&rfc7668_context[idx], context);
return ERR_OK;
#else
LWIP_UNUSED_ARG(idx);
LWIP_UNUSED_ARG(context);
return ERR_VAL;
#endif
}
/**
* @ingroup rfc7668if
* Compress outgoing IPv6 packet and pass it on to netif->linkoutput
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The pbuf(s) containing the IP packet to be sent.
* @param ip6addr The IP address of the packet destination.
*
* @return See rfc7668_compress
*/
err_t
rfc7668_output(struct netif *netif, struct pbuf *q, const ip6_addr_t *ip6addr)
{
/* dst ip6addr is not used here, we only have one peer */
LWIP_UNUSED_ARG(ip6addr);
return rfc7668_compress(netif, q);
}
/**
* @ingroup rfc7668if
* Process a received raw payload from an L2CAP channel
*
* @param p the received packet, p->payload pointing to the
* IPv6 header (maybe compressed)
* @param netif the network interface on which the packet was received
*
* @return ERR_OK if everything was fine
*/
err_t
rfc7668_input(struct pbuf * p, struct netif *netif)
{
u8_t * puc;
MIB2_STATS_NETIF_ADD(netif, ifinoctets, p->tot_len);
/* Load first header byte */
puc = (u8_t*)p->payload;
/* no IP header compression */
if (*puc == 0x41) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Completed packet, removing dispatch: 0x%2x \n", *puc));
/* This is a complete IPv6 packet, just skip header byte. */
pbuf_remove_header(p, 1);
/* IPHC header compression */
} else if ((*puc & 0xe0 )== 0x60) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Completed packet, decompress dispatch: 0x%2x \n", *puc));
/* IPv6 headers are compressed using IPHC. */
p = lowpan6_decompress(p, 0, rfc7668_context, &rfc7668_peer_addr, &rfc7668_local_addr);
/* if no pbuf is returned, handle as discarded packet */
if (p == NULL) {
MIB2_STATS_NETIF_INC(netif, ifindiscards);
return ERR_OK;
}
/* invalid header byte, discard */
} else {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Completed packet, discarding: 0x%2x \n", *puc));
MIB2_STATS_NETIF_INC(netif, ifindiscards);
pbuf_free(p);
return ERR_OK;
}
/* @todo: distinguish unicast/multicast */
MIB2_STATS_NETIF_INC(netif, ifinucastpkts);
#if LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG
{
u16_t i;
LWIP_DEBUGF(LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG, ("IPv6 payload:\n"));
for (i = 0; i < p->len; i++) {
if ((i%4)==0) {
LWIP_DEBUGF(LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG, ("\n"));
}
LWIP_DEBUGF(LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG, ("%2X ", *((u8_t *)p->payload+i)));
}
LWIP_DEBUGF(LWIP_RFC7668_IP_UNCOMPRESSED_DEBUG, ("\np->len: %d\n", p->len));
}
#endif
/* pass data to ip6_input */
return ip6_input(p, netif);
}
/**
* @ingroup rfc7668if
* Initialize the netif
*
* No flags are used (broadcast not possible, not ethernet, ...)
* The shortname for this netif is "BT"
*
* @param netif the network interface to be initialized as RFC7668 netif
*
* @return ERR_OK if everything went fine
*/
err_t
rfc7668_if_init(struct netif *netif)
{
netif->name[0] = 'b';
netif->name[1] = 't';
/* local function as IPv6 output */
netif->output_ip6 = rfc7668_output;
MIB2_INIT_NETIF(netif, snmp_ifType_other, 0);
/* maximum transfer unit, set according to RFC7668 ch2.4 */
netif->mtu = IP6_MIN_MTU_LENGTH;
/* no flags set (no broadcast, ethernet,...)*/
netif->flags = 0;
/* everything fine */
return ERR_OK;
}
#if !NO_SYS
/**
* Pass a received packet to tcpip_thread for input processing
*
* @param p the received packet, p->payload pointing to the
* IEEE 802.15.4 header.
* @param inp the network interface on which the packet was received
*
* @return see @ref tcpip_inpkt, same return values
*/
err_t
tcpip_rfc7668_input(struct pbuf *p, struct netif *inp)
{
/* send data to upper layer, return the result */
return tcpip_inpkt(p, inp, rfc7668_input);
}
#endif /* !NO_SYS */
#endif /* LWIP_IPV6 */

View File

@ -1,841 +0,0 @@
/**
* @file
*
* Common 6LowPAN routines for IPv6. Uses ND tables for link-layer addressing. Fragments packets to 6LowPAN units.
*
* This implementation aims to conform to IEEE 802.15.4(-2015), RFC 4944 and RFC 6282.
* @todo: RFC 6775.
*/
/*
* Copyright (c) 2015 Inico Technologies Ltd.
* 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: Ivan Delamer <delamer@inicotech.com>
*
*
* Please coordinate changes and requests with Ivan Delamer
* <delamer@inicotech.com>
*/
/**
* @defgroup sixlowpan 6LoWPAN (RFC4944)
* @ingroup netifs
* 6LowPAN netif implementation
*/
#include "netif/lowpan6_common.h"
#if LWIP_IPV6
#include "lwip/ip.h"
#include "lwip/pbuf.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/udp.h"
#include <string.h>
/* Determine compression mode for unicast address. */
s8_t
lowpan6_get_address_mode(const ip6_addr_t *ip6addr, const struct lowpan6_link_addr *mac_addr)
{
if (mac_addr->addr_len == 2) {
if ((ip6addr->addr[2] == (u32_t)PP_HTONL(0x000000ff)) &&
((ip6addr->addr[3] & PP_HTONL(0xffff0000)) == PP_NTOHL(0xfe000000))) {
if ((ip6addr->addr[3] & PP_HTONL(0x0000ffff)) == lwip_ntohl((mac_addr->addr[0] << 8) | mac_addr->addr[1])) {
return 3;
}
}
} else if (mac_addr->addr_len == 8) {
if ((ip6addr->addr[2] == lwip_ntohl(((mac_addr->addr[0] ^ 2) << 24) | (mac_addr->addr[1] << 16) | mac_addr->addr[2] << 8 | mac_addr->addr[3])) &&
(ip6addr->addr[3] == lwip_ntohl((mac_addr->addr[4] << 24) | (mac_addr->addr[5] << 16) | mac_addr->addr[6] << 8 | mac_addr->addr[7]))) {
return 3;
}
}
if ((ip6addr->addr[2] == PP_HTONL(0x000000ffUL)) &&
((ip6addr->addr[3] & PP_HTONL(0xffff0000)) == PP_NTOHL(0xfe000000UL))) {
return 2;
}
return 1;
}
#if LWIP_6LOWPAN_IPHC
/* Determine compression mode for multicast address. */
static s8_t
lowpan6_get_address_mode_mc(const ip6_addr_t *ip6addr)
{
if ((ip6addr->addr[0] == PP_HTONL(0xff020000)) &&
(ip6addr->addr[1] == 0) &&
(ip6addr->addr[2] == 0) &&
((ip6addr->addr[3] & PP_HTONL(0xffffff00)) == 0)) {
return 3;
} else if (((ip6addr->addr[0] & PP_HTONL(0xff00ffff)) == PP_HTONL(0xff000000)) &&
(ip6addr->addr[1] == 0)) {
if ((ip6addr->addr[2] == 0) &&
((ip6addr->addr[3] & PP_HTONL(0xff000000)) == 0)) {
return 2;
} else if ((ip6addr->addr[2] & PP_HTONL(0xffffff00)) == 0) {
return 1;
}
}
return 0;
}
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
static s8_t
lowpan6_context_lookup(const ip6_addr_t *lowpan6_contexts, const ip6_addr_t *ip6addr)
{
s8_t i;
for (i = 0; i < LWIP_6LOWPAN_NUM_CONTEXTS; i++) {
if (ip6_addr_net_eq(&lowpan6_contexts[i], ip6addr)) {
return i;
}
}
return -1;
}
#endif /* LWIP_6LOWPAN_NUM_CONTEXTS > 0 */
/*
* Compress IPv6 and/or UDP headers.
* */
err_t
lowpan6_compress_headers(struct netif *netif, u8_t *inbuf, size_t inbuf_size, u8_t *outbuf, size_t outbuf_size,
u8_t *lowpan6_header_len_out, u8_t *hidden_header_len_out, ip6_addr_t *lowpan6_contexts,
const struct lowpan6_link_addr *src, const struct lowpan6_link_addr *dst)
{
u8_t *buffer, *inptr;
u8_t lowpan6_header_len;
u8_t hidden_header_len = 0;
s8_t i;
struct ip6_hdr *ip6hdr;
ip_addr_t ip6src, ip6dst;
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("inbuf != NULL", inbuf != NULL);
LWIP_ASSERT("outbuf != NULL", outbuf != NULL);
LWIP_ASSERT("lowpan6_header_len_out != NULL", lowpan6_header_len_out != NULL);
LWIP_ASSERT("hidden_header_len_out != NULL", hidden_header_len_out != NULL);
/* Perform 6LowPAN IPv6 header compression according to RFC 6282 */
buffer = outbuf;
inptr = inbuf;
if (inbuf_size < IP6_HLEN) {
/* input buffer too short */
return ERR_VAL;
}
if (outbuf_size < IP6_HLEN) {
/* output buffer too short for worst case */
return ERR_MEM;
}
/* Point to ip6 header and align copies of src/dest addresses. */
ip6hdr = (struct ip6_hdr *)inptr;
ip_addr_copy_from_ip6_packed(ip6dst, ip6hdr->dest);
ip6_addr_assign_zone(ip_2_ip6(&ip6dst), IP6_UNKNOWN, netif);
ip_addr_copy_from_ip6_packed(ip6src, ip6hdr->src);
ip6_addr_assign_zone(ip_2_ip6(&ip6src), IP6_UNKNOWN, netif);
/* Basic length of 6LowPAN header, set dispatch and clear fields. */
lowpan6_header_len = 2;
buffer[0] = 0x60;
buffer[1] = 0;
/* Determine whether there will be a Context Identifier Extension byte or not.
* If so, set it already. */
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
buffer[2] = 0;
i = lowpan6_context_lookup(lowpan6_contexts, ip_2_ip6(&ip6src));
if (i >= 0) {
/* Stateful source address compression. */
buffer[1] |= 0x40;
buffer[2] |= (i & 0x0f) << 4;
}
i = lowpan6_context_lookup(lowpan6_contexts, ip_2_ip6(&ip6dst));
if (i >= 0) {
/* Stateful destination address compression. */
buffer[1] |= 0x04;
buffer[2] |= i & 0x0f;
}
if (buffer[2] != 0x00) {
/* Context identifier extension byte is appended. */
buffer[1] |= 0x80;
lowpan6_header_len++;
}
#else /* LWIP_6LOWPAN_NUM_CONTEXTS > 0 */
LWIP_UNUSED_ARG(lowpan6_contexts);
#endif /* LWIP_6LOWPAN_NUM_CONTEXTS > 0 */
/* Determine TF field: Traffic Class, Flow Label */
if (IP6H_FL(ip6hdr) == 0) {
/* Flow label is elided. */
buffer[0] |= 0x10;
if (IP6H_TC(ip6hdr) == 0) {
/* Traffic class (ECN+DSCP) elided too. */
buffer[0] |= 0x08;
} else {
/* Traffic class (ECN+DSCP) appended. */
buffer[lowpan6_header_len++] = IP6H_TC(ip6hdr);
}
} else {
if (((IP6H_TC(ip6hdr) & 0x3f) == 0)) {
/* DSCP portion of Traffic Class is elided, ECN and FL are appended (3 bytes) */
buffer[0] |= 0x08;
buffer[lowpan6_header_len] = IP6H_TC(ip6hdr) & 0xc0;
buffer[lowpan6_header_len++] |= (IP6H_FL(ip6hdr) >> 16) & 0x0f;
buffer[lowpan6_header_len++] = (IP6H_FL(ip6hdr) >> 8) & 0xff;
buffer[lowpan6_header_len++] = IP6H_FL(ip6hdr) & 0xff;
} else {
/* Traffic class and flow label are appended (4 bytes) */
buffer[lowpan6_header_len++] = IP6H_TC(ip6hdr);
buffer[lowpan6_header_len++] = (IP6H_FL(ip6hdr) >> 16) & 0x0f;
buffer[lowpan6_header_len++] = (IP6H_FL(ip6hdr) >> 8) & 0xff;
buffer[lowpan6_header_len++] = IP6H_FL(ip6hdr) & 0xff;
}
}
/* Compress NH?
* Only if UDP for now. @todo support other NH compression. */
if (IP6H_NEXTH(ip6hdr) == IP6_NEXTH_UDP) {
buffer[0] |= 0x04;
} else {
/* append nexth. */
buffer[lowpan6_header_len++] = IP6H_NEXTH(ip6hdr);
}
/* Compress hop limit? */
if (IP6H_HOPLIM(ip6hdr) == 255) {
buffer[0] |= 0x03;
} else if (IP6H_HOPLIM(ip6hdr) == 64) {
buffer[0] |= 0x02;
} else if (IP6H_HOPLIM(ip6hdr) == 1) {
buffer[0] |= 0x01;
} else {
/* append hop limit */
buffer[lowpan6_header_len++] = IP6H_HOPLIM(ip6hdr);
}
/* Compress source address */
if (((buffer[1] & 0x40) != 0) ||
(ip6_addr_islinklocal(ip_2_ip6(&ip6src)))) {
/* Context-based or link-local source address compression. */
i = lowpan6_get_address_mode(ip_2_ip6(&ip6src), src);
buffer[1] |= (i & 0x03) << 4;
if (i == 1) {
MEMCPY(buffer + lowpan6_header_len, inptr + 16, 8);
lowpan6_header_len += 8;
} else if (i == 2) {
MEMCPY(buffer + lowpan6_header_len, inptr + 22, 2);
lowpan6_header_len += 2;
}
} else if (ip6_addr_isany(ip_2_ip6(&ip6src))) {
/* Special case: mark SAC and leave SAM=0 */
buffer[1] |= 0x40;
} else {
/* Append full address. */
MEMCPY(buffer + lowpan6_header_len, inptr + 8, 16);
lowpan6_header_len += 16;
}
/* Compress destination address */
if (ip6_addr_ismulticast(ip_2_ip6(&ip6dst))) {
/* @todo support stateful multicast address compression */
buffer[1] |= 0x08;
i = lowpan6_get_address_mode_mc(ip_2_ip6(&ip6dst));
buffer[1] |= i & 0x03;
if (i == 0) {
MEMCPY(buffer + lowpan6_header_len, inptr + 24, 16);
lowpan6_header_len += 16;
} else if (i == 1) {
buffer[lowpan6_header_len++] = inptr[25];
MEMCPY(buffer + lowpan6_header_len, inptr + 35, 5);
lowpan6_header_len += 5;
} else if (i == 2) {
buffer[lowpan6_header_len++] = inptr[25];
MEMCPY(buffer + lowpan6_header_len, inptr + 37, 3);
lowpan6_header_len += 3;
} else if (i == 3) {
buffer[lowpan6_header_len++] = (inptr)[39];
}
} else if (((buffer[1] & 0x04) != 0) ||
(ip6_addr_islinklocal(ip_2_ip6(&ip6dst)))) {
/* Context-based or link-local destination address compression. */
i = lowpan6_get_address_mode(ip_2_ip6(&ip6dst), dst);
buffer[1] |= i & 0x03;
if (i == 1) {
MEMCPY(buffer + lowpan6_header_len, inptr + 32, 8);
lowpan6_header_len += 8;
} else if (i == 2) {
MEMCPY(buffer + lowpan6_header_len, inptr + 38, 2);
lowpan6_header_len += 2;
}
} else {
/* Append full address. */
MEMCPY(buffer + lowpan6_header_len, inptr + 24, 16);
lowpan6_header_len += 16;
}
/* Move to payload. */
inptr += IP6_HLEN;
hidden_header_len += IP6_HLEN;
#if LWIP_UDP
/* Compress UDP header? */
if (IP6H_NEXTH(ip6hdr) == IP6_NEXTH_UDP) {
/* @todo support optional checksum compression */
if (inbuf_size < IP6_HLEN + UDP_HLEN) {
/* input buffer too short */
return ERR_VAL;
}
if (outbuf_size < (size_t)(hidden_header_len + 7)) {
/* output buffer too short for worst case */
return ERR_MEM;
}
buffer[lowpan6_header_len] = 0xf0;
/* determine port compression mode. */
if ((inptr[0] == 0xf0) && ((inptr[1] & 0xf0) == 0xb0) &&
(inptr[2] == 0xf0) && ((inptr[3] & 0xf0) == 0xb0)) {
/* Compress source and dest ports. */
buffer[lowpan6_header_len++] |= 0x03;
buffer[lowpan6_header_len++] = ((inptr[1] & 0x0f) << 4) | (inptr[3] & 0x0f);
} else if (inptr[0] == 0xf0) {
/* Compress source port. */
buffer[lowpan6_header_len++] |= 0x02;
buffer[lowpan6_header_len++] = inptr[1];
buffer[lowpan6_header_len++] = inptr[2];
buffer[lowpan6_header_len++] = inptr[3];
} else if (inptr[2] == 0xf0) {
/* Compress dest port. */
buffer[lowpan6_header_len++] |= 0x01;
buffer[lowpan6_header_len++] = inptr[0];
buffer[lowpan6_header_len++] = inptr[1];
buffer[lowpan6_header_len++] = inptr[3];
} else {
/* append full ports. */
lowpan6_header_len++;
buffer[lowpan6_header_len++] = inptr[0];
buffer[lowpan6_header_len++] = inptr[1];
buffer[lowpan6_header_len++] = inptr[2];
buffer[lowpan6_header_len++] = inptr[3];
}
/* elide length and copy checksum */
buffer[lowpan6_header_len++] = inptr[6];
buffer[lowpan6_header_len++] = inptr[7];
hidden_header_len += UDP_HLEN;
}
#endif /* LWIP_UDP */
*lowpan6_header_len_out = lowpan6_header_len;
*hidden_header_len_out = hidden_header_len;
return ERR_OK;
}
/** Decompress IPv6 and UDP headers compressed according to RFC 6282
*
* @param lowpan6_buffer compressed headers, first byte is the dispatch byte
* @param lowpan6_bufsize size of lowpan6_buffer (may include data after headers)
* @param decomp_buffer buffer where the decompressed headers are stored
* @param decomp_bufsize size of decomp_buffer
* @param hdr_size_comp returns the size of the compressed headers (skip to get to data)
* @param hdr_size_decomp returns the size of the decompressed headers (IPv6 + UDP)
* @param datagram_size datagram size from fragments or 0 if unfragmented
* @param compressed_size compressed datagram size (for unfragmented rx)
* @param lowpan6_contexts context addresses
* @param src source address of the outer layer, used for address compression
* @param dest destination address of the outer layer, used for address compression
* @return ERR_OK if decompression succeeded, an error otherwise
*/
static err_t
lowpan6_decompress_hdr(u8_t *lowpan6_buffer, size_t lowpan6_bufsize,
u8_t *decomp_buffer, size_t decomp_bufsize,
u16_t *hdr_size_comp, u16_t *hdr_size_decomp,
u16_t datagram_size, u16_t compressed_size,
ip6_addr_t *lowpan6_contexts,
struct lowpan6_link_addr *src, struct lowpan6_link_addr *dest)
{
u16_t lowpan6_offset;
struct ip6_hdr *ip6hdr;
s8_t i;
u32_t header_temp;
u16_t ip6_offset = IP6_HLEN;
LWIP_ASSERT("lowpan6_buffer != NULL", lowpan6_buffer != NULL);
LWIP_ASSERT("decomp_buffer != NULL", decomp_buffer != NULL);
LWIP_ASSERT("src != NULL", src != NULL);
LWIP_ASSERT("dest != NULL", dest != NULL);
LWIP_ASSERT("hdr_size_comp != NULL", hdr_size_comp != NULL);
LWIP_ASSERT("dehdr_size_decompst != NULL", hdr_size_decomp != NULL);
ip6hdr = (struct ip6_hdr *)decomp_buffer;
if (decomp_bufsize < IP6_HLEN) {
return ERR_MEM;
}
/* output the full compressed packet, if set in @see lowpan6_opts.h */
#if LWIP_LOWPAN6_IP_COMPRESSED_DEBUG
{
u16_t j;
LWIP_DEBUGF(LWIP_LOWPAN6_IP_COMPRESSED_DEBUG, ("lowpan6_decompress_hdr: IP6 payload (compressed): \n"));
for (j = 0; j < lowpan6_bufsize; j++) {
if ((j % 4) == 0) {
LWIP_DEBUGF(LWIP_LOWPAN6_IP_COMPRESSED_DEBUG, ("\n"));
}
LWIP_DEBUGF(LWIP_LOWPAN6_IP_COMPRESSED_DEBUG, ("%2X ", lowpan6_buffer[j]));
}
LWIP_DEBUGF(LWIP_LOWPAN6_IP_COMPRESSED_DEBUG, ("\np->len: %d", lowpan6_bufsize));
}
#endif
/* offset for inline IP headers (RFC 6282 ch3)*/
lowpan6_offset = 2;
/* if CID is set (context identifier), the context byte
* follows immediately after the header, so other IPHC fields are @+3 */
if (lowpan6_buffer[1] & 0x80) {
lowpan6_offset++;
}
/* Set IPv6 version, traffic class and flow label. (RFC6282, ch 3.1.1.)*/
if ((lowpan6_buffer[0] & 0x18) == 0x00) {
header_temp = ((lowpan6_buffer[lowpan6_offset+1] & 0x0f) << 16) | \
(lowpan6_buffer[lowpan6_offset + 2] << 8) | lowpan6_buffer[lowpan6_offset+3];
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("TF: 00, ECN: 0x%"X8_F", Flowlabel+DSCP: 0x%8"X32_F"\n", \
lowpan6_buffer[lowpan6_offset],header_temp));
IP6H_VTCFL_SET(ip6hdr, 6, lowpan6_buffer[lowpan6_offset], header_temp);
/* increase offset, processed 4 bytes here:
* TF=00: ECN + DSCP + 4-bit Pad + Flow Label (4 bytes)*/
lowpan6_offset += 4;
} else if ((lowpan6_buffer[0] & 0x18) == 0x08) {
header_temp = ((lowpan6_buffer[lowpan6_offset] & 0x0f) << 16) | (lowpan6_buffer[lowpan6_offset + 1] << 8) | lowpan6_buffer[lowpan6_offset+2];
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("TF: 01, ECN: 0x%"X8_F", Flowlabel: 0x%2"X32_F", DSCP ignored\n", \
lowpan6_buffer[lowpan6_offset] & 0xc0,header_temp));
IP6H_VTCFL_SET(ip6hdr, 6, lowpan6_buffer[lowpan6_offset] & 0xc0, header_temp);
/* increase offset, processed 3 bytes here:
* TF=01: ECN + 2-bit Pad + Flow Label (3 bytes), DSCP is elided.*/
lowpan6_offset += 3;
} else if ((lowpan6_buffer[0] & 0x18) == 0x10) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("TF: 10, DCSP+ECN: 0x%"X8_F", Flowlabel ignored\n", lowpan6_buffer[lowpan6_offset]));
IP6H_VTCFL_SET(ip6hdr, 6, lowpan6_buffer[lowpan6_offset],0);
/* increase offset, processed 1 byte here:
* ECN + DSCP (1 byte), Flow Label is elided.*/
lowpan6_offset += 1;
} else if ((lowpan6_buffer[0] & 0x18) == 0x18) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("TF: 11, DCSP/ECN & Flowlabel ignored\n"));
/* don't increase offset, no bytes processed here */
IP6H_VTCFL_SET(ip6hdr, 6, 0, 0);
}
/* Set Next Header (NH) */
if ((lowpan6_buffer[0] & 0x04) == 0x00) {
/* 0: full next header byte carried inline (increase offset)*/
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("NH: 0x%2X\n", lowpan6_buffer[lowpan6_offset+1]));
IP6H_NEXTH_SET(ip6hdr, lowpan6_buffer[lowpan6_offset++]);
} else {
/* 1: NH compression, LOWPAN_NHC (RFC6282, ch 4.1) */
/* We should fill this later with NHC decoding */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("NH: skipped, later done with NHC\n"));
IP6H_NEXTH_SET(ip6hdr, 0);
}
/* Set Hop Limit, either carried inline or 3 different hops (1,64,255) */
if ((lowpan6_buffer[0] & 0x03) == 0x00) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Hops: full value: %d\n", lowpan6_buffer[lowpan6_offset+1]));
IP6H_HOPLIM_SET(ip6hdr, lowpan6_buffer[lowpan6_offset++]);
} else if ((lowpan6_buffer[0] & 0x03) == 0x01) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Hops: compressed: 1\n"));
IP6H_HOPLIM_SET(ip6hdr, 1);
} else if ((lowpan6_buffer[0] & 0x03) == 0x02) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Hops: compressed: 64\n"));
IP6H_HOPLIM_SET(ip6hdr, 64);
} else if ((lowpan6_buffer[0] & 0x03) == 0x03) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Hops: compressed: 255\n"));
IP6H_HOPLIM_SET(ip6hdr, 255);
}
/* Source address decoding. */
if ((lowpan6_buffer[1] & 0x40) == 0x00) {
/* Source address compression (SAC) = 0 -> stateless compression */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAC == 0, no context byte\n"));
/* Stateless compression */
if ((lowpan6_buffer[1] & 0x30) == 0x00) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 00, no src compression, fetching 128bits inline\n"));
/* copy full address, increase offset by 16 Bytes */
MEMCPY(&ip6hdr->src.addr[0], lowpan6_buffer + lowpan6_offset, 16);
lowpan6_offset += 16;
} else if ((lowpan6_buffer[1] & 0x30) == 0x10) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 01, src compression, 64bits inline\n"));
/* set 64 bits to link local */
ip6hdr->src.addr[0] = PP_HTONL(0xfe800000UL);
ip6hdr->src.addr[1] = 0;
/* copy 8 Bytes, increase offset */
MEMCPY(&ip6hdr->src.addr[2], lowpan6_buffer + lowpan6_offset, 8);
lowpan6_offset += 8;
} else if ((lowpan6_buffer[1] & 0x30) == 0x20) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 10, src compression, 16bits inline\n"));
/* set 96 bits to link local */
ip6hdr->src.addr[0] = PP_HTONL(0xfe800000UL);
ip6hdr->src.addr[1] = 0;
ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
/* extract remaining 16bits from inline bytes, increase offset */
ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) |
lowpan6_buffer[lowpan6_offset + 1]);
lowpan6_offset += 2;
} else if ((lowpan6_buffer[1] & 0x30) == 0x30) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 11, src compression, 0bits inline, using other headers\n"));
/* no information available, using other layers, see RFC6282 ch 3.2.2 */
ip6hdr->src.addr[0] = PP_HTONL(0xfe800000UL);
ip6hdr->src.addr[1] = 0;
if (src->addr_len == 2) {
ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
} else if (src->addr_len == 8) {
ip6hdr->src.addr[2] = lwip_htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) |
(src->addr[2] << 8) | src->addr[3]);
ip6hdr->src.addr[3] = lwip_htonl((src->addr[4] << 24) | (src->addr[5] << 16) |
(src->addr[6] << 8) | src->addr[7]);
} else {
/* invalid source address length */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Invalid source address length\n"));
return ERR_VAL;
}
}
} else {
/* Source address compression (SAC) = 1 -> stateful/context-based compression */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAC == 1, additional context byte\n"));
if ((lowpan6_buffer[1] & 0x30) == 0x00) {
/* SAM=00, address=> :: (ANY) */
ip6hdr->src.addr[0] = 0;
ip6hdr->src.addr[1] = 0;
ip6hdr->src.addr[2] = 0;
ip6hdr->src.addr[3] = 0;
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 00, context compression, ANY (::)\n"));
} else {
/* Set prefix from context info */
if (lowpan6_buffer[1] & 0x80) {
i = (lowpan6_buffer[2] >> 4) & 0x0f;
} else {
i = 0;
}
if (i >= LWIP_6LOWPAN_NUM_CONTEXTS) {
/* Error */
return ERR_VAL;
}
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
ip6hdr->src.addr[0] = lowpan6_contexts[i].addr[0];
ip6hdr->src.addr[1] = lowpan6_contexts[i].addr[1];
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == xx, context compression found @%d: %8"X32_F", %8"X32_F"\n", (int)i, ip6hdr->src.addr[0], ip6hdr->src.addr[1]));
#else
LWIP_UNUSED_ARG(lowpan6_contexts);
#endif
}
/* determine further address bits */
if ((lowpan6_buffer[1] & 0x30) == 0x10) {
/* SAM=01, load additional 64bits */
MEMCPY(&ip6hdr->src.addr[2], lowpan6_buffer + lowpan6_offset, 8);
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 01, context compression, 64bits inline\n"));
lowpan6_offset += 8;
} else if ((lowpan6_buffer[1] & 0x30) == 0x20) {
/* SAM=01, load additional 16bits */
ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset + 1]);
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 10, context compression, 16bits inline\n"));
lowpan6_offset += 2;
} else if ((lowpan6_buffer[1] & 0x30) == 0x30) {
/* SAM=11, address is fully elided, load from other layers */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("SAM == 11, context compression, 0bits inline, using other headers\n"));
if (src->addr_len == 2) {
ip6hdr->src.addr[2] = PP_HTONL(0x000000ffUL);
ip6hdr->src.addr[3] = lwip_htonl(0xfe000000UL | (src->addr[0] << 8) | src->addr[1]);
} else if (src->addr_len == 8) {
ip6hdr->src.addr[2] = lwip_htonl(((src->addr[0] ^ 2) << 24) | (src->addr[1] << 16) | (src->addr[2] << 8) | src->addr[3]);
ip6hdr->src.addr[3] = lwip_htonl((src->addr[4] << 24) | (src->addr[5] << 16) | (src->addr[6] << 8) | src->addr[7]);
} else {
/* invalid source address length */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Invalid source address length\n"));
return ERR_VAL;
}
}
}
/* Destination address decoding. */
if (lowpan6_buffer[1] & 0x08) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("M=1: multicast\n"));
/* Multicast destination */
if (lowpan6_buffer[1] & 0x04) {
LWIP_DEBUGF(LWIP_DBG_ON,("DAC == 1, context multicast: unsupported!!!\n"));
/* @todo support stateful multicast addressing */
return ERR_VAL;
}
if ((lowpan6_buffer[1] & 0x03) == 0x00) {
/* DAM = 00, copy full address (128bits) */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 00, no dst compression, fetching 128bits inline\n"));
MEMCPY(&ip6hdr->dest.addr[0], lowpan6_buffer + lowpan6_offset, 16);
lowpan6_offset += 16;
} else if ((lowpan6_buffer[1] & 0x03) == 0x01) {
/* DAM = 01, copy 4 bytes (32bits) */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 01, dst address form (48bits): ffXX::00XX:XXXX:XXXX\n"));
ip6hdr->dest.addr[0] = lwip_htonl(0xff000000UL | (lowpan6_buffer[lowpan6_offset++] << 16));
ip6hdr->dest.addr[1] = 0;
ip6hdr->dest.addr[2] = lwip_htonl(lowpan6_buffer[lowpan6_offset++]);
ip6hdr->dest.addr[3] = lwip_htonl((lowpan6_buffer[lowpan6_offset] << 24) | (lowpan6_buffer[lowpan6_offset + 1] << 16) | (lowpan6_buffer[lowpan6_offset + 2] << 8) | lowpan6_buffer[lowpan6_offset + 3]);
lowpan6_offset += 4;
} else if ((lowpan6_buffer[1] & 0x03) == 0x02) {
/* DAM = 10, copy 3 bytes (24bits) */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 10, dst address form (32bits): ffXX::00XX:XXXX\n"));
ip6hdr->dest.addr[0] = lwip_htonl(0xff000000UL | (lowpan6_buffer[lowpan6_offset++] << 16));
ip6hdr->dest.addr[1] = 0;
ip6hdr->dest.addr[2] = 0;
ip6hdr->dest.addr[3] = lwip_htonl((lowpan6_buffer[lowpan6_offset] << 16) | (lowpan6_buffer[lowpan6_offset + 1] << 8) | lowpan6_buffer[lowpan6_offset + 2]);
lowpan6_offset += 3;
} else if ((lowpan6_buffer[1] & 0x03) == 0x03) {
/* DAM = 11, copy 1 byte (8bits) */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 11, dst address form (8bits): ff02::00XX\n"));
ip6hdr->dest.addr[0] = PP_HTONL(0xff020000UL);
ip6hdr->dest.addr[1] = 0;
ip6hdr->dest.addr[2] = 0;
ip6hdr->dest.addr[3] = lwip_htonl(lowpan6_buffer[lowpan6_offset++]);
}
} else {
/* no Multicast (M=0) */
if (lowpan6_buffer[1] & 0x04) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAC == 1, stateful compression\n"));
/* Stateful destination compression */
/* Set prefix from context info */
if (lowpan6_buffer[1] & 0x80) {
i = lowpan6_buffer[2] & 0x0f;
} else {
i = 0;
}
if (i >= LWIP_6LOWPAN_NUM_CONTEXTS) {
/* Error */
return ERR_VAL;
}
#if LWIP_6LOWPAN_NUM_CONTEXTS > 0
ip6hdr->dest.addr[0] = lowpan6_contexts[i].addr[0];
ip6hdr->dest.addr[1] = lowpan6_contexts[i].addr[1];
#endif
} else {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAC == 0, stateless compression, setting link local prefix\n"));
/* Link local address compression */
ip6hdr->dest.addr[0] = PP_HTONL(0xfe800000UL);
ip6hdr->dest.addr[1] = 0;
}
/* M=0, DAC=0, determining destination address length via DAM=xx */
if ((lowpan6_buffer[1] & 0x03) == 0x00) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 00, no dst compression, fetching 128bits inline"));
/* DAM=00, copy full address */
MEMCPY(&ip6hdr->dest.addr[0], lowpan6_buffer + lowpan6_offset, 16);
lowpan6_offset += 16;
} else if ((lowpan6_buffer[1] & 0x03) == 0x01) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 01, dst compression, 64bits inline\n"));
/* DAM=01, copy 64 inline bits, increase offset */
MEMCPY(&ip6hdr->dest.addr[2], lowpan6_buffer + lowpan6_offset, 8);
lowpan6_offset += 8;
} else if ((lowpan6_buffer[1] & 0x03) == 0x02) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("DAM == 01, dst compression, 16bits inline\n"));
/* DAM=10, copy 16 inline bits, increase offset */
ip6hdr->dest.addr[2] = PP_HTONL(0x000000ffUL);
ip6hdr->dest.addr[3] = lwip_htonl(0xfe000000UL | (lowpan6_buffer[lowpan6_offset] << 8) | lowpan6_buffer[lowpan6_offset + 1]);
lowpan6_offset += 2;
} else if ((lowpan6_buffer[1] & 0x03) == 0x03) {
/* DAM=11, no bits available, use other headers (not done here) */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG,("DAM == 01, dst compression, 0bits inline, using other headers\n"));
if (dest->addr_len == 2) {
ip6hdr->dest.addr[2] = PP_HTONL(0x000000ffUL);
ip6hdr->dest.addr[3] = lwip_htonl(0xfe000000UL | (dest->addr[0] << 8) | dest->addr[1]);
} else if (dest->addr_len == 8) {
ip6hdr->dest.addr[2] = lwip_htonl(((dest->addr[0] ^ 2) << 24) | (dest->addr[1] << 16) | dest->addr[2] << 8 | dest->addr[3]);
ip6hdr->dest.addr[3] = lwip_htonl((dest->addr[4] << 24) | (dest->addr[5] << 16) | dest->addr[6] << 8 | dest->addr[7]);
} else {
/* invalid destination address length */
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("Invalid destination address length\n"));
return ERR_VAL;
}
}
}
/* Next Header Compression (NHC) decoding? */
if (lowpan6_buffer[0] & 0x04) {
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("NHC decoding\n"));
#if LWIP_UDP
if ((lowpan6_buffer[lowpan6_offset] & 0xf8) == 0xf0) {
/* NHC: UDP */
struct udp_hdr *udphdr;
LWIP_DEBUGF(LWIP_LOWPAN6_DECOMPRESSION_DEBUG, ("NHC: UDP\n"));
/* UDP compression */
IP6H_NEXTH_SET(ip6hdr, IP6_NEXTH_UDP);
udphdr = (struct udp_hdr *)((u8_t *)decomp_buffer + ip6_offset);
if (decomp_bufsize < IP6_HLEN + UDP_HLEN) {
return ERR_MEM;
}
/* Checksum decompression */
if (lowpan6_buffer[lowpan6_offset] & 0x04) {
/* @todo support checksum decompress */
LWIP_DEBUGF(LWIP_DBG_ON, ("NHC: UDP chechsum decompression UNSUPPORTED\n"));
return ERR_VAL;
}
/* Decompress ports, according to RFC4944 */
i = lowpan6_buffer[lowpan6_offset++] & 0x03;
if (i == 0) {
udphdr->src = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
udphdr->dest = lwip_htons(lowpan6_buffer[lowpan6_offset + 2] << 8 | lowpan6_buffer[lowpan6_offset + 3]);
lowpan6_offset += 4;
} else if (i == 0x01) {
udphdr->src = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
udphdr->dest = lwip_htons(0xf000 | lowpan6_buffer[lowpan6_offset + 2]);
lowpan6_offset += 3;
} else if (i == 0x02) {
udphdr->src = lwip_htons(0xf000 | lowpan6_buffer[lowpan6_offset]);
udphdr->dest = lwip_htons(lowpan6_buffer[lowpan6_offset + 1] << 8 | lowpan6_buffer[lowpan6_offset + 2]);
lowpan6_offset += 3;
} else if (i == 0x03) {
udphdr->src = lwip_htons(0xf0b0 | ((lowpan6_buffer[lowpan6_offset] >> 4) & 0x0f));
udphdr->dest = lwip_htons(0xf0b0 | (lowpan6_buffer[lowpan6_offset] & 0x0f));
lowpan6_offset += 1;
}
udphdr->chksum = lwip_htons(lowpan6_buffer[lowpan6_offset] << 8 | lowpan6_buffer[lowpan6_offset + 1]);
lowpan6_offset += 2;
ip6_offset += UDP_HLEN;
if (datagram_size == 0) {
datagram_size = compressed_size - lowpan6_offset + ip6_offset;
}
udphdr->len = lwip_htons(datagram_size - IP6_HLEN);
} else
#endif /* LWIP_UDP */
{
LWIP_DEBUGF(LWIP_DBG_ON,("NHC: unsupported protocol!\n"));
/* @todo support NHC other than UDP */
return ERR_VAL;
}
}
if (datagram_size == 0) {
datagram_size = compressed_size - lowpan6_offset + ip6_offset;
}
/* Infer IPv6 payload length for header */
IP6H_PLEN_SET(ip6hdr, datagram_size - IP6_HLEN);
if (lowpan6_offset > lowpan6_bufsize) {
/* input buffer overflow */
return ERR_VAL;
}
*hdr_size_comp = lowpan6_offset;
*hdr_size_decomp = ip6_offset;
return ERR_OK;
}
struct pbuf *
lowpan6_decompress(struct pbuf *p, u16_t datagram_size, ip6_addr_t *lowpan6_contexts,
struct lowpan6_link_addr *src, struct lowpan6_link_addr *dest)
{
struct pbuf *q;
u16_t lowpan6_offset, ip6_offset;
err_t err;
#if LWIP_UDP
#define UDP_HLEN_ALLOC UDP_HLEN
#else
#define UDP_HLEN_ALLOC 0
#endif
/* Allocate a buffer for decompression. This buffer will be too big and will be
trimmed once the final size is known. */
q = pbuf_alloc(PBUF_IP, p->len + IP6_HLEN + UDP_HLEN_ALLOC, PBUF_POOL);
if (q == NULL) {
pbuf_free(p);
return NULL;
}
if (q->len < IP6_HLEN + UDP_HLEN_ALLOC) {
/* The headers need to fit into the first pbuf */
pbuf_free(p);
pbuf_free(q);
return NULL;
}
/* Decompress the IPv6 (and possibly UDP) header(s) into the new pbuf */
err = lowpan6_decompress_hdr((u8_t *)p->payload, p->len, (u8_t *)q->payload, q->len,
&lowpan6_offset, &ip6_offset, datagram_size, p->tot_len, lowpan6_contexts, src, dest);
if (err != ERR_OK) {
pbuf_free(p);
pbuf_free(q);
return NULL;
}
/* Now we copy leftover contents from p to q, so we have all L2 and L3 headers
(and L4?) in a single pbuf: */
/* Hide the compressed headers in p */
pbuf_remove_header(p, lowpan6_offset);
/* Temporarily hide the headers in q... */
pbuf_remove_header(q, ip6_offset);
/* ... copy the rest of p into q... */
pbuf_copy(q, p);
/* ... and reveal the headers again... */
pbuf_add_header_force(q, ip6_offset);
/* ... trim the pbuf to its correct size... */
pbuf_realloc(q, ip6_offset + p->len);
/* ... and cat possibly remaining (data-only) pbufs */
if (p->next != NULL) {
pbuf_cat(q, p->next);
}
/* the original (first) pbuf can now be freed */
p->next = NULL;
pbuf_free(p);
/* all done */
return q;
}
#endif /* LWIP_6LOWPAN_IPHC */
#endif /* LWIP_IPV6 */

View File

@ -1,473 +0,0 @@
The lwIP PPP support is based from pppd 2.4.5 (http://ppp.samba.org) with
huge changes to match code size and memory requirements for embedded devices.
Anyway, pppd has a mature codebase for years and the average commit count
is getting low on their Git repository, meaning that we can follow what
is happening on their side and merge what is relevant for lwIP.
So, here is the pppd follow up, so that we don't get away too far from pppd.
== Patch fetched from from pppd Debian packages ==
This has nothing to do with pppd, but we merged some good patch from
Debian and this is a good place to be.
- LCP adaptive echo, so that we don't send LCP echo request if we
are receiving data from peer, can be enabled by setting PPP_LCP_ADAPTIVE
to true.
- IPCP no/replace default route option, were added in the early stage of
the ppp port, but it wasn't really helpful and was disabled when adding
the new API ppp_set_default() call, which gives the lwIP user control over
which one is the default interface, it was actually a requirement if you
are doing PPP over PPP (i.e. PPPoL2TP, VPN link, over PPPoE, ADSL link).
- using rp-pppoe pppd exits with EXIT_OK after receiving a timeout waiting
for PADO due to no modem attached, bug reported to pppd bug tracker, fixed
in Debian but not in the latest (at the time when the port were started)
pppd release.
== Commits on pppd ==
2010-03-06 - Document +ipv6 and ipv6cp-accept-local
e7537958aee79b3f653c601e903cb31d78fb7dcc
Don't care.
2010-03-06 - Install pppol2tp plugins with sane permissions
406215672cfadc03017341fe03802d1c7294b903
Don't care.
2010-03-07 - pppd: Terminate correctly if lcp_lowerup delayed calling
fsm_lowerup
3eb9e810cfa515543655659b72dde30c54fea0a5
Merged 2012-05-17.
2010-03-07 - rp_pppoe: Copy acName and pppd_pppoe_service after option parsing
cab58617fd9d328029fffabc788020264b4fa91f
Don't care, is a patch for pppd/plugins/rp-pppoe/plugin.c which is not part
of the port.
2010-08-23 - set and reset options to control environment variables
for scripts.
2b6310fd24dba8e0fca8999916a162f0a1842a84
We can't fork processes in embedded, therefore all the pppd process run
feature is disabled in the port, so we don't care about the new
"environment variables" pppd feature.
2010-08-23 - Nit: use _exit when exec fails and restrict values to 0-255
per POSIX.
2b4ea140432eeba5a007c0d4e6236bd0e0c12ba4
Again, we are not running as a heavy process, so all exit() or _exit() calls
were removed.
2010-08-23 - Fix quote handling in configuration files to be more like shell
quoting.
3089132cdf5b58dbdfc2daf08ec5c08eb47f8aca
We are not parsing config file, all the filesystem I/O stuff were disabled
in our port.
2010-08-24 - rp-pppoe: allow MTU to be increased up to 1500
fd1dcdf758418f040da3ed801ab001b5e46854e7
Only concern changes on RP-PPPoE plugin, which we don't use.
2010-09-11 - chat: Allow TIMEOUT value to come from environment variable
ae80bf833e48a6202f44a935a68083ae52ad3824
See 2b6310fd24dba8e0fca8999916a162f0a1842a84.
2011-03-05 - pppdump: Fix printfs with insufficient arguments
7b8db569642c83ba3283745034f2e2c95e459423
pppdump is a ppp tool outside pppd source tree.
2012-05-06 - pppd: Don't unconditionally disable VJ compression under Linux
d8a66adf98a0e525cf38031b42098d539da6eeb6
Patch for sys-linux.c, which we don't use.
2012-05-20 - Remove old version of Linux if_pppol2tp.h
c41092dd4c49267f232f6cba3d31c6c68bfdf68d
Not in the port.
2012-05-20 - pppd: Make MSCHAP-v2 cope better with packet loss
08ef47ca532294eb428238c831616748940e24a2
This is an interesting patch. However it consumes much more memory for
MSCHAP and I am not sure if the benefit worth it. The PPP client can
always start the authentication again if it failed for whatever reason.
2012-05-20 - scripts: Make poff ignore extra arguments to pppd
18f515f32c9f5723a9c2c912601e04335106534b
Again, we are not running scripts.
2012-05-20 - rp-pppoe plugin: Print leading zeros in MAC address
f5dda0cfc220c4b52e26144096d729e27b30f0f7
Again, we are not using the RP-PPPoE plugin.
2012-05-20 - pppd: Notify IPv6 up/down as we do for IPv4
845cda8fa18939cf56e60b073f63a7efa65336fc
This is just a patch that adds plugins hooks for IPv6, the plugin interface
was disabled because we don't have .so plugins in embedded.
2012-05-20 - pppd: Enable IPV6 by default and fix some warnings
0b6118239615e98959f7e0b4e746bdd197533248
Change on Makefile for IPv6, warnings were already cleared during port.
2012-05-20 - contrib: Fix pppgetpass.gtk compilation
80a8e2ce257ca12cce723519a0f20ea1d663b14a
Change on Makefile, don't care.
2012-05-20 - pppd: Don't crash if crypt() returns NULL
04c4348108d847e034dd91066cc6843f60d71731
We are using the PolarSSL DES implementation that does not return NULL.
2012-05-20 - pppd: Eliminate some warnings
c44ae5e6a7338c96eb463881fe709b2dfaffe568
Again, we are handling compilation warnings on our own.
2012-05-20 - rp-pppoe plugin: Import some fixes from rp-pppoe-3.10
1817d83e51a411044e730ba89ebdb0480e1c8cd4
Once more, we are not using the RP-PPPoE plugin.
2013-01-23 - pppd: Clarify circumstances where DNS1/DNS2 environment variables are set
cf2f5c9538b9400ade23446a194729b0a4113b3a
Documentation only.
2013-02-03 - ppp: ignore unrecognised radiusclient configuration directives
7f736dde0da3c19855997d9e67370e351e15e923
Radius plugin, not in the port.
2013-02-03 - pppd: Take out unused %r conversion completely
356d8d558d844412119aa18c8e5a113bc6459c7b
Merged 2014-04-15.
2013-02-03 - pppd: Arrange to use logwtmp from libutil on Linux
9617a7eb137f4fee62799a677a9ecf8d834db3f5
Patch for sys-linux.c, which we don't use.
2013-02-03 - pppdump: Eliminate some compiler warnings
3e3acf1ba2b3046c072a42c19164788a9e419bd1
pppdump is a ppp tool outside pppd source tree.
2013-02-03 - chat: Correct spelling errors in the man page
8dea1b969d266ccbf6f3a8c5474eb6dcd8838e3b
Documentation only.
2013-02-03 - pppd: Fix spelling errors in man page
9e05a25d76b3f83096c661678010320df673df6b
Documentation only.
2013-02-03 - plugins/passprompt: Fix potential out-of-bounds array reference
8edb889b753056a691a3e4b217a110a35f9fdedb
Plugin patch, we do not have plugins.
2013-02-03 - chat: Fix *roff errors in the man page
a7c3489eeaf44e83ce592143c7c8a5b5c29f4c48
Documentation only.
2013-03-02 - pppd: Fix man page description of case when remote IP address isn't known
224841f4799f4f1e2e71bc490c54448d66740f4f
Documentation only.
2013-03-02 - pppd: Add master_detach option
398ed2585640d198c53e736ee5bbd67f7ce8168e
Option for multilink support, we do not support multilink and this option
is about detaching from the terminal, which is out of the embedded scope.
2013-03-11 - pppd: Default exit status to EXIT_CONNECT_FAILED during connection phase
225361d64ae737afdc8cb57579a2f33525461bc9
Commented out in our port, and already fixed by a previously applied Debian patch.
2013-03-11 - pppstats: Fix undefined macro in man page
d16a3985eade5280b8e171f5dd0670a91cba0d39
Documentation only.
2013-05-11 - plugins/radius: Handle bindaddr keyword in radiusclient.conf
d883b2dbafeed3ebd9d7a56ab1469373bd001a3b
Radius plugin, not in the port.
2013-06-09 - pppoatm: Remove explicit loading of pppoatm kernel module
52cd43a84bea524033b918b603698104f221bbb7
PPPoATM plugin, not in the port.
2013-06-09 - pppd: Fix segfault in update_db_entry()
37476164f15a45015310b9d4b197c2d7db1f7f8f
We do not use the samba db.
2013-06-09 - chat: Fix some text that was intended to be literal
cd9683676618adcee8add2c3cfa3382341b5a1f6
Documentation only.
2013-06-09 - README.pppoe: Minor semantic fix
b5b8898af6fd3d44e873cfc66810ace5f1f47e17
Documentation only.
2013-06-10 - radius: Handle additional attributes
2f581cd986a56f2ec4a95abad4f8297a1b10d7e2
Radius plugin, not in the port.
2013-06-10 - chat, pppd: Use \e instead of \\ in man pages
8d6942415d22f6ca4377340ca26e345c3f5fa5db
Documentation only.
2014-01-02 - pppd: Don't crash if NULL pointer passed to vslprintf for %q or %v
906814431bddeb2061825fa1ebad1a967b6d87a9
Merged 2014-04-15.
2014-01-02 - pppd: Accept IPCP ConfAck packets containing MS-WINS options
a243f217f1c6ac1aa7793806bc88590d077f490a
Merged 2014-04-15.
2014-01-02 - config: Update Solaris compiler options and enable CHAPMS and IPV6
99c46caaed01b7edba87962aa52b77fad61bfd7b
Solaris port, don't care.
2014-01-02 - Update README and patchlevel for 2.4.6 release
4043750fca36e7e0eb90d702e048ad1da4929418
Just release stuff.
2014-02-18 - pppd: Add option "stop-bits" to set number of serial port stop bits.
ad993a20ee485f0d0e2ac4105221641b200da6e2
Low level serial port, not in the port.
2014-03-09 - pppd: Separate IPv6 handling for sifup/sifdown
b04d2dc6df5c6b5650fea44250d58757ee3dac4a
Reimplemented.
2014-03-09 - pppol2tp: Connect up/down events to notifiers and add IPv6 ones
fafbe50251efc7d6b4a8be652d085316e112b34f
Not in the port.
2014-03-09 - pppd: Add declarations to eliminate compile warnings
50967962addebe15c7a7e63116ff46a0441dc464
We are handling compilation warnings on our own
2014-03-09 - pppd: Eliminate some unnecessary ifdefs
de8da14d845ee6db9236ccfddabf1d8ebf045ddb
We mostly did that previously. Anyway, merged 2014-12-24.
2014-08-01 - radius: Fix realms-config-file option
880a81be7c8e0fe8567227bc17a1bff3ea035943
Radius plugin, not in the port.
2014-08-01 - pppd: Eliminate potential integer overflow in option parsing
7658e8257183f062dc01f87969c140707c7e52cb
pppd config file parser, not in the port.
2014-08-01 - pppd: Eliminate memory leak with multiple instances of a string option
b94b7fbbaa0589aa6ec5fdc733aeb9ff294d2656
pppd config file parser, not in the port.
2014-08-01 - pppd: Fix a stack variable overflow in MSCHAP-v2
36733a891fb56594fcee580f667b33a64b990981
This fixes a bug introduced in 08ef47ca ("pppd: Make MSCHAP-v2 cope better with packet loss").
We didn't merge 08ef47ca ;-)
2014-08-01 - winbind plugin: Add -DMPPE=1 to eliminate compiler warnings
2b05e22c62095e97dd0a97e4b5588402c2185071
Linux plugin, not in the port.
2014-08-09 - Update README and patchlevel for 2.4.7 release
6e8eaa7a78b31cdab2edf140a9c8afdb02ffaca5
Just release stuff.
2014-08-10 - abort on errors in subdir builds
5e90783d11a59268e05f4cfb29ce2343b13e8ab2
Linux Makefile, not in the port.
2014-06-03 - pppd: add support for defaultroute-metric option
35e5a569c988b1ff865b02a24d9a727a00db4da9
Only necessary for Linux, lwIP does not support route metrics.
2014-12-13 - scripts: Avoid killing wrong pppd
67811a647d399db5d188a242827760615a0f86b5
pppd helper script, not in the port.
2014-12-20 - pppd: Fix sign-extension when displaying bytes in octal
5e8c3cb256a7e86e3572a82a75d51c6850efdbdc
Merged 2016-07-02.
2015-03-01 - Suppress false error message on PPPoE disconnect
219aac3b53d0827549377f1bfe22853ee52d4405
PPPoE plugin, not in the port.
2015-03-01 - Send PADT on PPPoE disconnect
cd2c14f998c57bbe6a01dc5854f2763c0d7f31fb
PPPoE plugin, not in the port. And our PPPoE implementation already does
that: pppoe_disconnect() calls pppoe_send_padt().
2015-08-14 - pppd: ipxcp: Prevent buffer overrun on remote router name
fe149de624f96629a7f46732055d8f718c74b856
We never ported IPX support. lwIP does not support IPX.
2015-03-25 - pppd: Fix ccp_options.mppe type
234edab99a6bb250cc9ecd384cca27b0c8b475ce
We found that while working on MPPE support in lwIP, that's our patch ;-)
2015-03-24 - pppd: Fix ccp_cilen calculated size if both deflate_correct and deflate_draft are enabled
094cb8ae4c61db225e67fedadb4964f846dd0c27
We found that while working on MPPE support in lwIP, that's our patch ;-)
2015-08-14 - Merge branch 'master' of https://github.com/ncopa/ppp
3a5c9a8fbc8970375cd881151d44e4b6fe249c6a
Merge commit, we don't care.
2015-08-14 - Merge branch 'master' of git://github.com/vapier/ppp
912e4fc6665aca188dced7ea7fdc663ce5a2dd24
Merge commit, we don't care.
2015-08-14 - Merge branch 'bug_fix' of git://github.com/radaiming/ppp
dfd33d7f526ecd7b39dd1bba8101260d02af5ebb
Merge commit, we don't care.
2015-08-14 - Merge branch 'master' of git://github.com/pprindeville/ppp
aa4a985f6114d08cf4e47634fb6325da71016473
Merge commit, we don't care.
2015-08-14 - Merge branch 'no-error-on-already-closed' of git://github.com/farnz/ppp
6edf252483b30dbcdcc5059f01831455365d5b6e
Merge commit, we don't care.
2015-08-14 - Merge branch 'send-padt-on-disconnect' of git://github.com/farnz/ppp
84684243d651f55f6df69d2a6707b52fbbe62bb9
Merge commit, we don't care.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,126 +0,0 @@
/*
* chap-md5.c - New CHAP/MD5 implementation.
*
* Copyright (c) 2003 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if 0 /* UNUSED */
#include <stdlib.h>
#include <string.h>
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/chap-new.h"
#include "netif/ppp/chap-md5.h"
#include "netif/ppp/magic.h"
#include "netif/ppp/pppcrypt.h"
#define MD5_HASH_SIZE 16
#define MD5_MIN_CHALLENGE 17
#define MD5_MAX_CHALLENGE 24
#define MD5_MIN_MAX_POWER_OF_TWO_CHALLENGE 3 /* 2^3-1 = 7, 17+7 = 24 */
#if PPP_SERVER
static void chap_md5_generate_challenge(ppp_pcb *pcb, unsigned char *cp) {
int clen;
LWIP_UNUSED_ARG(pcb);
clen = MD5_MIN_CHALLENGE + magic_pow(MD5_MIN_MAX_POWER_OF_TWO_CHALLENGE);
*cp++ = clen;
magic_random_bytes(cp, clen);
}
static int chap_md5_verify_response(ppp_pcb *pcb, int id, const char *name,
const unsigned char *secret, int secret_len,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space) {
lwip_md5_context ctx;
unsigned char idbyte = id;
unsigned char hash[MD5_HASH_SIZE];
int challenge_len, response_len;
LWIP_UNUSED_ARG(name);
LWIP_UNUSED_ARG(pcb);
challenge_len = *challenge++;
response_len = *response++;
if (response_len == MD5_HASH_SIZE) {
/* Generate hash of ID, secret, challenge */
lwip_md5_init(&ctx);
lwip_md5_starts(&ctx);
lwip_md5_update(&ctx, &idbyte, 1);
lwip_md5_update(&ctx, secret, secret_len);
lwip_md5_update(&ctx, challenge, challenge_len);
lwip_md5_finish(&ctx, hash);
lwip_md5_free(&ctx);
/* Test if our hash matches the peer's response */
if (memcmp(hash, response, MD5_HASH_SIZE) == 0) {
ppp_slprintf(message, message_space, "Access granted");
return 1;
}
}
ppp_slprintf(message, message_space, "Access denied");
return 0;
}
#endif /* PPP_SERVER */
static void chap_md5_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name,
const unsigned char *challenge, const char *secret, int secret_len,
unsigned char *private_) {
lwip_md5_context ctx;
unsigned char idbyte = id;
int challenge_len = *challenge++;
LWIP_UNUSED_ARG(our_name);
LWIP_UNUSED_ARG(private_);
LWIP_UNUSED_ARG(pcb);
lwip_md5_init(&ctx);
lwip_md5_starts(&ctx);
lwip_md5_update(&ctx, &idbyte, 1);
lwip_md5_update(&ctx, (const u_char *)secret, secret_len);
lwip_md5_update(&ctx, challenge, challenge_len);
lwip_md5_finish(&ctx, &response[1]);
lwip_md5_free(&ctx);
response[0] = MD5_HASH_SIZE;
}
const struct chap_digest_type md5_digest = {
CHAP_MD5, /* code */
#if PPP_SERVER
chap_md5_generate_challenge,
chap_md5_verify_response,
#endif /* PPP_SERVER */
chap_md5_make_response,
NULL, /* check_success */
NULL, /* handle_failure */
};
#endif /* PPP_SUPPORT && CHAP_SUPPORT */

View File

@ -1,677 +0,0 @@
/*
* chap-new.c - New CHAP implementation.
*
* Copyright (c) 2003 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && CHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if 0 /* UNUSED */
#include <stdlib.h>
#include <string.h>
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#if 0 /* UNUSED */
#include "session.h"
#endif /* UNUSED */
#include "netif/ppp/chap-new.h"
#include "netif/ppp/chap-md5.h"
#if MSCHAP_SUPPORT
#include "netif/ppp/chap_ms.h"
#endif
#include "netif/ppp/magic.h"
#if 0 /* UNUSED */
/* Hook for a plugin to validate CHAP challenge */
int (*chap_verify_hook)(const char *name, const char *ourname, int id,
const struct chap_digest_type *digest,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space) = NULL;
#endif /* UNUSED */
#if PPP_OPTIONS
/*
* Command-line options.
*/
static option_t chap_option_list[] = {
{ "chap-restart", o_int, &chap_timeout_time,
"Set timeout for CHAP", OPT_PRIO },
{ "chap-max-challenge", o_int, &pcb->settings.chap_max_transmits,
"Set max #xmits for challenge", OPT_PRIO },
{ "chap-interval", o_int, &pcb->settings.chap_rechallenge_time,
"Set interval for rechallenge", OPT_PRIO },
{ NULL }
};
#endif /* PPP_OPTIONS */
/* Values for flags in chap_client_state and chap_server_state */
#define LOWERUP 1
#define AUTH_STARTED 2
#define AUTH_DONE 4
#define AUTH_FAILED 8
#define TIMEOUT_PENDING 0x10
#define CHALLENGE_VALID 0x20
/*
* Prototypes.
*/
static void chap_init(ppp_pcb *pcb);
static void chap_lowerup(ppp_pcb *pcb);
static void chap_lowerdown(ppp_pcb *pcb);
#if PPP_SERVER
static void chap_timeout(void *arg);
static void chap_generate_challenge(ppp_pcb *pcb);
static void chap_handle_response(ppp_pcb *pcb, int code,
unsigned char *pkt, int len);
static int chap_verify_response(ppp_pcb *pcb, const char *name, const char *ourname, int id,
const struct chap_digest_type *digest,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space);
#endif /* PPP_SERVER */
static void chap_respond(ppp_pcb *pcb, int id,
unsigned char *pkt, int len);
static void chap_handle_status(ppp_pcb *pcb, int code, int id,
unsigned char *pkt, int len);
static void chap_protrej(ppp_pcb *pcb);
static void chap_input(ppp_pcb *pcb, unsigned char *pkt, int pktlen);
#if PRINTPKT_SUPPORT
static int chap_print_pkt(const unsigned char *p, int plen,
void (*printer) (void *, const char *, ...), void *arg);
#endif /* PRINTPKT_SUPPORT */
/* List of digest types that we know about */
static const struct chap_digest_type* const chap_digests[] = {
&md5_digest,
#if MSCHAP_SUPPORT
&chapms_digest,
&chapms2_digest,
#endif /* MSCHAP_SUPPORT */
NULL
};
/*
* chap_init - reset to initial state.
*/
static void chap_init(ppp_pcb *pcb) {
LWIP_UNUSED_ARG(pcb);
#if 0 /* Not necessary, everything is cleared in ppp_new() */
memset(&pcb->chap_client, 0, sizeof(chap_client_state));
#if PPP_SERVER
memset(&pcb->chap_server, 0, sizeof(chap_server_state));
#endif /* PPP_SERVER */
#endif /* 0 */
}
/*
* chap_lowerup - we can start doing stuff now.
*/
static void chap_lowerup(ppp_pcb *pcb) {
pcb->chap_client.flags |= LOWERUP;
#if PPP_SERVER
pcb->chap_server.flags |= LOWERUP;
if (pcb->chap_server.flags & AUTH_STARTED)
chap_timeout(pcb);
#endif /* PPP_SERVER */
}
static void chap_lowerdown(ppp_pcb *pcb) {
pcb->chap_client.flags = 0;
#if PPP_SERVER
if (pcb->chap_server.flags & TIMEOUT_PENDING)
UNTIMEOUT(chap_timeout, pcb);
pcb->chap_server.flags = 0;
#endif /* PPP_SERVER */
}
#if PPP_SERVER
/*
* chap_auth_peer - Start authenticating the peer.
* If the lower layer is already up, we start sending challenges,
* otherwise we wait for the lower layer to come up.
*/
void chap_auth_peer(ppp_pcb *pcb, const char *our_name, int digest_code) {
const struct chap_digest_type *dp;
int i;
if (pcb->chap_server.flags & AUTH_STARTED) {
ppp_error(("CHAP: peer authentication already started!"));
return;
}
for (i = 0; (dp = chap_digests[i]) != NULL; ++i)
if (dp->code == digest_code)
break;
if (dp == NULL)
ppp_fatal(("CHAP digest 0x%x requested but not available",
digest_code));
pcb->chap_server.digest = dp;
pcb->chap_server.name = our_name;
/* Start with a random ID value */
pcb->chap_server.id = magic();
pcb->chap_server.flags |= AUTH_STARTED;
if (pcb->chap_server.flags & LOWERUP)
chap_timeout(pcb);
}
#endif /* PPP_SERVER */
/*
* chap_auth_with_peer - Prepare to authenticate ourselves to the peer.
* There isn't much to do until we receive a challenge.
*/
void chap_auth_with_peer(ppp_pcb *pcb, const char *our_name, int digest_code) {
const struct chap_digest_type *dp;
int i;
if(NULL == our_name)
return;
if (pcb->chap_client.flags & AUTH_STARTED) {
ppp_error(("CHAP: authentication with peer already started!"));
return;
}
for (i = 0; (dp = chap_digests[i]) != NULL; ++i)
if (dp->code == digest_code)
break;
if (dp == NULL)
ppp_fatal(("CHAP digest 0x%x requested but not available",
digest_code));
pcb->chap_client.digest = dp;
pcb->chap_client.name = our_name;
pcb->chap_client.flags |= AUTH_STARTED;
}
#if PPP_SERVER
/*
* chap_timeout - It's time to send another challenge to the peer.
* This could be either a retransmission of a previous challenge,
* or a new challenge to start re-authentication.
*/
static void chap_timeout(void *arg) {
ppp_pcb *pcb = (ppp_pcb*)arg;
struct pbuf *p;
pcb->chap_server.flags &= ~TIMEOUT_PENDING;
if ((pcb->chap_server.flags & CHALLENGE_VALID) == 0) {
pcb->chap_server.challenge_xmits = 0;
chap_generate_challenge(pcb);
pcb->chap_server.flags |= CHALLENGE_VALID;
} else if (pcb->chap_server.challenge_xmits >= pcb->settings.chap_max_transmits) {
pcb->chap_server.flags &= ~CHALLENGE_VALID;
pcb->chap_server.flags |= AUTH_DONE | AUTH_FAILED;
auth_peer_fail(pcb, PPP_CHAP);
return;
}
p = pbuf_alloc(PBUF_RAW, (u16_t)(pcb->chap_server.challenge_pktlen), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
MEMCPY(p->payload, pcb->chap_server.challenge, pcb->chap_server.challenge_pktlen);
ppp_write(pcb, p);
++pcb->chap_server.challenge_xmits;
pcb->chap_server.flags |= TIMEOUT_PENDING;
TIMEOUT(chap_timeout, arg, pcb->settings.chap_timeout_time);
}
/*
* chap_generate_challenge - generate a challenge string and format
* the challenge packet in pcb->chap_server.challenge_pkt.
*/
static void chap_generate_challenge(ppp_pcb *pcb) {
int clen = 1, nlen, len;
unsigned char *p;
p = pcb->chap_server.challenge;
MAKEHEADER(p, PPP_CHAP);
p += CHAP_HDRLEN;
pcb->chap_server.digest->generate_challenge(pcb, p);
clen = *p;
nlen = strlen(pcb->chap_server.name);
memcpy(p + 1 + clen, pcb->chap_server.name, nlen);
len = CHAP_HDRLEN + 1 + clen + nlen;
pcb->chap_server.challenge_pktlen = PPP_HDRLEN + len;
p = pcb->chap_server.challenge + PPP_HDRLEN;
p[0] = CHAP_CHALLENGE;
p[1] = ++pcb->chap_server.id;
p[2] = len >> 8;
p[3] = len;
}
/*
* chap_handle_response - check the response to our challenge.
*/
static void chap_handle_response(ppp_pcb *pcb, int id,
unsigned char *pkt, int len) {
int response_len, ok, mlen;
const unsigned char *response;
unsigned char *outp;
struct pbuf *p;
const char *name = NULL; /* initialized to shut gcc up */
#if 0 /* UNUSED */
int (*verifier)(const char *, const char *, int, const struct chap_digest_type *,
const unsigned char *, const unsigned char *, char *, int);
#endif /* UNUSED */
char rname[MAXNAMELEN+1];
char message[256];
if ((pcb->chap_server.flags & LOWERUP) == 0)
return;
if (id != pcb->chap_server.challenge[PPP_HDRLEN+1] || len < 2)
return;
if (pcb->chap_server.flags & CHALLENGE_VALID) {
response = pkt;
GETCHAR(response_len, pkt);
len -= response_len + 1; /* length of name */
name = (char *)pkt + response_len;
if (len < 0)
return;
if (pcb->chap_server.flags & TIMEOUT_PENDING) {
pcb->chap_server.flags &= ~TIMEOUT_PENDING;
UNTIMEOUT(chap_timeout, pcb);
}
#if PPP_REMOTENAME
if (pcb->settings.explicit_remote) {
name = pcb->remote_name;
} else
#endif /* PPP_REMOTENAME */
{
/* Null terminate and clean remote name. */
ppp_slprintf(rname, sizeof(rname), "%.*v", len, name);
name = rname;
}
#if 0 /* UNUSED */
if (chap_verify_hook)
verifier = chap_verify_hook;
else
verifier = chap_verify_response;
ok = (*verifier)(name, pcb->chap_server.name, id, pcb->chap_server.digest,
pcb->chap_server.challenge + PPP_HDRLEN + CHAP_HDRLEN,
response, pcb->chap_server.message, sizeof(pcb->chap_server.message));
#endif /* UNUSED */
ok = chap_verify_response(pcb, name, pcb->chap_server.name, id, pcb->chap_server.digest,
pcb->chap_server.challenge + PPP_HDRLEN + CHAP_HDRLEN,
response, message, sizeof(message));
#if 0 /* UNUSED */
if (!ok || !auth_number()) {
#endif /* UNUSED */
if (!ok) {
pcb->chap_server.flags |= AUTH_FAILED;
ppp_warn(("Peer %q failed CHAP authentication", name));
}
} else if ((pcb->chap_server.flags & AUTH_DONE) == 0)
return;
/* send the response */
mlen = strlen(message);
len = CHAP_HDRLEN + mlen;
p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +len), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
outp = (unsigned char *)p->payload;
MAKEHEADER(outp, PPP_CHAP);
outp[0] = (pcb->chap_server.flags & AUTH_FAILED)? CHAP_FAILURE: CHAP_SUCCESS;
outp[1] = id;
outp[2] = len >> 8;
outp[3] = len;
if (mlen > 0)
memcpy(outp + CHAP_HDRLEN, message, mlen);
ppp_write(pcb, p);
if (pcb->chap_server.flags & CHALLENGE_VALID) {
pcb->chap_server.flags &= ~CHALLENGE_VALID;
if (!(pcb->chap_server.flags & AUTH_DONE) && !(pcb->chap_server.flags & AUTH_FAILED)) {
#if 0 /* UNUSED */
/*
* Auth is OK, so now we need to check session restrictions
* to ensure everything is OK, but only if we used a
* plugin, and only if we're configured to check. This
* allows us to do PAM checks on PPP servers that
* authenticate against ActiveDirectory, and use AD for
* account info (like when using Winbind integrated with
* PAM).
*/
if (session_mgmt &&
session_check(name, NULL, devnam, NULL) == 0) {
pcb->chap_server.flags |= AUTH_FAILED;
ppp_warn(("Peer %q failed CHAP Session verification", name));
}
#endif /* UNUSED */
}
if (pcb->chap_server.flags & AUTH_FAILED) {
auth_peer_fail(pcb, PPP_CHAP);
} else {
if ((pcb->chap_server.flags & AUTH_DONE) == 0)
auth_peer_success(pcb, PPP_CHAP,
pcb->chap_server.digest->code,
name, strlen(name));
if (pcb->settings.chap_rechallenge_time) {
pcb->chap_server.flags |= TIMEOUT_PENDING;
TIMEOUT(chap_timeout, pcb,
pcb->settings.chap_rechallenge_time);
}
}
pcb->chap_server.flags |= AUTH_DONE;
}
}
/*
* chap_verify_response - check whether the peer's response matches
* what we think it should be. Returns 1 if it does (authentication
* succeeded), or 0 if it doesn't.
*/
static int chap_verify_response(ppp_pcb *pcb, const char *name, const char *ourname, int id,
const struct chap_digest_type *digest,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space) {
int ok;
unsigned char secret[MAXSECRETLEN];
int secret_len;
/* Get the secret that the peer is supposed to know */
if (!get_secret(pcb, name, ourname, (char *)secret, &secret_len, 1)) {
ppp_error(("No CHAP secret found for authenticating %q", name));
return 0;
}
ok = digest->verify_response(pcb, id, name, secret, secret_len, challenge,
response, message, message_space);
memset(secret, 0, sizeof(secret));
return ok;
}
#endif /* PPP_SERVER */
/*
* chap_respond - Generate and send a response to a challenge.
*/
static void chap_respond(ppp_pcb *pcb, int id,
unsigned char *pkt, int len) {
int clen, nlen;
int secret_len;
struct pbuf *p;
u_char *outp;
char rname[MAXNAMELEN+1];
char secret[MAXSECRETLEN+1];
p = pbuf_alloc(PBUF_RAW, (u16_t)(RESP_MAX_PKTLEN), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
if ((pcb->chap_client.flags & (LOWERUP | AUTH_STARTED)) != (LOWERUP | AUTH_STARTED))
return; /* not ready */
if (len < 2 || len < pkt[0] + 1)
return; /* too short */
clen = pkt[0];
nlen = len - (clen + 1);
/* Null terminate and clean remote name. */
ppp_slprintf(rname, sizeof(rname), "%.*v", nlen, pkt + clen + 1);
#if PPP_REMOTENAME
/* Microsoft doesn't send their name back in the PPP packet */
if (pcb->settings.explicit_remote || (pcb->settings.remote_name[0] != 0 && rname[0] == 0))
strlcpy(rname, pcb->settings.remote_name, sizeof(rname));
#endif /* PPP_REMOTENAME */
/* get secret for authenticating ourselves with the specified host */
if (!get_secret(pcb, pcb->chap_client.name, rname, secret, &secret_len, 0)) {
secret_len = 0; /* assume null secret if can't find one */
ppp_warn(("No CHAP secret found for authenticating us to %q", rname));
}
outp = (u_char*)p->payload;
MAKEHEADER(outp, PPP_CHAP);
outp += CHAP_HDRLEN;
pcb->chap_client.digest->make_response(pcb, outp, id, pcb->chap_client.name, pkt,
secret, secret_len, pcb->chap_client.priv);
memset(secret, 0, secret_len);
clen = *outp;
nlen = strlen(pcb->chap_client.name);
memcpy(outp + clen + 1, pcb->chap_client.name, nlen);
outp = (u_char*)p->payload + PPP_HDRLEN;
len = CHAP_HDRLEN + clen + 1 + nlen;
outp[0] = CHAP_RESPONSE;
outp[1] = id;
outp[2] = len >> 8;
outp[3] = len;
pbuf_realloc(p, PPP_HDRLEN + len);
ppp_write(pcb, p);
}
static void chap_handle_status(ppp_pcb *pcb, int code, int id,
unsigned char *pkt, int len) {
const char *msg = NULL;
LWIP_UNUSED_ARG(id);
if ((pcb->chap_client.flags & (AUTH_DONE|AUTH_STARTED|LOWERUP))
!= (AUTH_STARTED|LOWERUP))
return;
pcb->chap_client.flags |= AUTH_DONE;
if (code == CHAP_SUCCESS) {
/* used for MS-CHAP v2 mutual auth, yuck */
if (pcb->chap_client.digest->check_success != NULL) {
if (!(*pcb->chap_client.digest->check_success)(pcb, pkt, len, pcb->chap_client.priv))
code = CHAP_FAILURE;
} else
msg = "CHAP authentication succeeded";
} else {
if (pcb->chap_client.digest->handle_failure != NULL)
(*pcb->chap_client.digest->handle_failure)(pcb, pkt, len);
else
msg = "CHAP authentication failed";
}
if (msg) {
if (len > 0)
ppp_info(("%s: %.*v", msg, len, pkt));
else
ppp_info(("%s", msg));
}
if (code == CHAP_SUCCESS)
auth_withpeer_success(pcb, PPP_CHAP, pcb->chap_client.digest->code);
else {
pcb->chap_client.flags |= AUTH_FAILED;
ppp_error(("CHAP authentication failed"));
auth_withpeer_fail(pcb, PPP_CHAP);
}
}
static void chap_input(ppp_pcb *pcb, unsigned char *pkt, int pktlen) {
unsigned char code, id;
int len;
if (pktlen < CHAP_HDRLEN)
return;
GETCHAR(code, pkt);
GETCHAR(id, pkt);
GETSHORT(len, pkt);
if (len < CHAP_HDRLEN || len > pktlen)
return;
len -= CHAP_HDRLEN;
switch (code) {
case CHAP_CHALLENGE:
chap_respond(pcb, id, pkt, len);
break;
#if PPP_SERVER
case CHAP_RESPONSE:
chap_handle_response(pcb, id, pkt, len);
break;
#endif /* PPP_SERVER */
case CHAP_FAILURE:
case CHAP_SUCCESS:
chap_handle_status(pcb, code, id, pkt, len);
break;
default:
break;
}
}
static void chap_protrej(ppp_pcb *pcb) {
#if PPP_SERVER
if (pcb->chap_server.flags & TIMEOUT_PENDING) {
pcb->chap_server.flags &= ~TIMEOUT_PENDING;
UNTIMEOUT(chap_timeout, pcb);
}
if (pcb->chap_server.flags & AUTH_STARTED) {
pcb->chap_server.flags = 0;
auth_peer_fail(pcb, PPP_CHAP);
}
#endif /* PPP_SERVER */
if ((pcb->chap_client.flags & (AUTH_STARTED|AUTH_DONE)) == AUTH_STARTED) {
pcb->chap_client.flags &= ~AUTH_STARTED;
ppp_error(("CHAP authentication failed due to protocol-reject"));
auth_withpeer_fail(pcb, PPP_CHAP);
}
}
#if PRINTPKT_SUPPORT
/*
* chap_print_pkt - print the contents of a CHAP packet.
*/
static const char* const chap_code_names[] = {
"Challenge", "Response", "Success", "Failure"
};
static int chap_print_pkt(const unsigned char *p, int plen,
void (*printer) (void *, const char *, ...), void *arg) {
int code, id, len;
int clen, nlen;
unsigned char x;
if (plen < CHAP_HDRLEN)
return 0;
GETCHAR(code, p);
GETCHAR(id, p);
GETSHORT(len, p);
if (len < CHAP_HDRLEN || len > plen)
return 0;
if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(chap_code_names))
printer(arg, " %s", chap_code_names[code-1]);
else
printer(arg, " code=0x%x", code);
printer(arg, " id=0x%x", id);
len -= CHAP_HDRLEN;
switch (code) {
case CHAP_CHALLENGE:
case CHAP_RESPONSE:
if (len < 1)
break;
clen = p[0];
if (len < clen + 1)
break;
++p;
nlen = len - clen - 1;
printer(arg, " <");
for (; clen > 0; --clen) {
GETCHAR(x, p);
printer(arg, "%.2x", x);
}
printer(arg, ">, name = ");
ppp_print_string(p, nlen, printer, arg);
break;
case CHAP_FAILURE:
case CHAP_SUCCESS:
printer(arg, " ");
ppp_print_string(p, len, printer, arg);
break;
default:
for (clen = len; clen > 0; --clen) {
GETCHAR(x, p);
printer(arg, " %.2x", x);
}
/* no break */
}
return len + CHAP_HDRLEN;
}
#endif /* PRINTPKT_SUPPORT */
const struct protent chap_protent = {
PPP_CHAP,
chap_init,
chap_input,
chap_protrej,
chap_lowerup,
chap_lowerdown,
NULL, /* open */
NULL, /* close */
#if PRINTPKT_SUPPORT
chap_print_pkt,
#endif /* PRINTPKT_SUPPORT */
#if PPP_DATAINPUT
NULL, /* datainput */
#endif /* PPP_DATAINPUT */
#if PRINTPKT_SUPPORT
"CHAP", /* name */
NULL, /* data_name */
#endif /* PRINTPKT_SUPPORT */
#if PPP_OPTIONS
chap_option_list,
NULL, /* check_options */
#endif /* PPP_OPTIONS */
#if DEMAND_SUPPORT
NULL,
NULL
#endif /* DEMAND_SUPPORT */
};
#endif /* PPP_SUPPORT && CHAP_SUPPORT */

View File

@ -1,962 +0,0 @@
/*
* chap_ms.c - Microsoft MS-CHAP compatible implementation.
*
* Copyright (c) 1995 Eric Rosenquist. 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(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Modifications by Lauri Pesonen / lpesonen@clinet.fi, april 1997
*
* Implemented LANManager type password response to MS-CHAP challenges.
* Now pppd provides both NT style and LANMan style blocks, and the
* preferred is set by option "ms-lanman". Default is to use NT.
* The hash text (StdText) was taken from Win95 RASAPI32.DLL.
*
* You should also use DOMAIN\\USERNAME as described in README.MSCHAP80
*/
/*
* Modifications by Frank Cusack, frank@google.com, March 2002.
*
* Implemented MS-CHAPv2 functionality, heavily based on sample
* implementation in RFC 2759. Implemented MPPE functionality,
* heavily based on sample implementation in RFC 3079.
*
* Copyright (c) 2002 Google, Inc. 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(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if 0 /* UNUSED */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/chap-new.h"
#include "netif/ppp/chap_ms.h"
#include "netif/ppp/pppcrypt.h"
#include "netif/ppp/magic.h"
#if MPPE_SUPPORT
#include "netif/ppp/mppe.h" /* For mppe_sha1_pad*, mppe_set_key() */
#endif /* MPPE_SUPPORT */
#define SHA1_SIGNATURE_SIZE 20
#define MD4_SIGNATURE_SIZE 16 /* 16 bytes in a MD4 message digest */
#define MAX_NT_PASSWORD 256 /* Max (Unicode) chars in an NT pass */
#define MS_CHAP_RESPONSE_LEN 49 /* Response length for MS-CHAP */
#define MS_CHAP2_RESPONSE_LEN 49 /* Response length for MS-CHAPv2 */
#define MS_AUTH_RESPONSE_LENGTH 40 /* MS-CHAPv2 authenticator response, */
/* as ASCII */
/* Error codes for MS-CHAP failure messages. */
#define MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS 646
#define MS_CHAP_ERROR_ACCT_DISABLED 647
#define MS_CHAP_ERROR_PASSWD_EXPIRED 648
#define MS_CHAP_ERROR_NO_DIALIN_PERMISSION 649
#define MS_CHAP_ERROR_AUTHENTICATION_FAILURE 691
#define MS_CHAP_ERROR_CHANGING_PASSWORD 709
/*
* Offsets within the response field for MS-CHAP
*/
#define MS_CHAP_LANMANRESP 0
#define MS_CHAP_LANMANRESP_LEN 24
#define MS_CHAP_NTRESP 24
#define MS_CHAP_NTRESP_LEN 24
#define MS_CHAP_USENT 48
/*
* Offsets within the response field for MS-CHAP2
*/
#define MS_CHAP2_PEER_CHALLENGE 0
#define MS_CHAP2_PEER_CHAL_LEN 16
#define MS_CHAP2_RESERVED_LEN 8
#define MS_CHAP2_NTRESP 24
#define MS_CHAP2_NTRESP_LEN 24
#define MS_CHAP2_FLAGS 48
#if MPPE_SUPPORT
#if 0 /* UNUSED */
/* These values are the RADIUS attribute values--see RFC 2548. */
#define MPPE_ENC_POL_ENC_ALLOWED 1
#define MPPE_ENC_POL_ENC_REQUIRED 2
#define MPPE_ENC_TYPES_RC4_40 2
#define MPPE_ENC_TYPES_RC4_128 4
/* used by plugins (using above values) */
extern void set_mppe_enc_types(int, int);
#endif /* UNUSED */
#endif /* MPPE_SUPPORT */
/* Are we the authenticator or authenticatee? For MS-CHAPv2 key derivation. */
#define MS_CHAP2_AUTHENTICATEE 0
#define MS_CHAP2_AUTHENTICATOR 1
static void ascii2unicode (const char[], int, u_char[]);
static void NTPasswordHash (u_char *, int, u_char[MD4_SIGNATURE_SIZE]);
static void ChallengeResponse (const u_char *, const u_char *, u_char[24]);
static void ChallengeHash (const u_char[16], const u_char *, const char *, u_char[8]);
static void ChapMS_NT (const u_char *, const char *, int, u_char[24]);
static void ChapMS2_NT (const u_char *, const u_char[16], const char *, const char *, int,
u_char[24]);
static void GenerateAuthenticatorResponsePlain
(const char*, int, u_char[24], const u_char[16], const u_char *,
const char *, u_char[41]);
#ifdef MSLANMAN
static void ChapMS_LANMan (u_char *, char *, int, u_char *);
#endif
static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE],
u_char NTResponse[24], const u_char PeerChallenge[16],
const u_char *rchallenge, const char *username,
u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]);
#if MPPE_SUPPORT
static void Set_Start_Key (ppp_pcb *pcb, const u_char *, const char *, int);
static void SetMasterKeys (ppp_pcb *pcb, const char *, int, u_char[24], int);
#endif /* MPPE_SUPPORT */
static void ChapMS (ppp_pcb *pcb, const u_char *, const char *, int, u_char *);
static void ChapMS2 (ppp_pcb *pcb, const u_char *, const u_char *, const char *, const char *, int,
u_char *, u_char[MS_AUTH_RESPONSE_LENGTH+1], int);
#ifdef MSLANMAN
bool ms_lanman = 0; /* Use LanMan password instead of NT */
/* Has meaning only with MS-CHAP challenges */
#endif
#if MPPE_SUPPORT
#ifdef DEBUGMPPEKEY
/* For MPPE debug */
/* Use "[]|}{?/><,`!2&&(" (sans quotes) for RFC 3079 MS-CHAPv2 test value */
static char *mschap_challenge = NULL;
/* Use "!@\#$%^&*()_+:3|~" (sans quotes, backslash is to escape #) for ... */
static char *mschap2_peer_challenge = NULL;
#endif
#include "netif/ppp/fsm.h" /* Need to poke MPPE options */
#include "netif/ppp/ccp.h"
#endif /* MPPE_SUPPORT */
#if PPP_OPTIONS
/*
* Command-line options.
*/
static option_t chapms_option_list[] = {
#ifdef MSLANMAN
{ "ms-lanman", o_bool, &ms_lanman,
"Use LanMan passwd when using MS-CHAP", 1 },
#endif
#ifdef DEBUGMPPEKEY
{ "mschap-challenge", o_string, &mschap_challenge,
"specify CHAP challenge" },
{ "mschap2-peer-challenge", o_string, &mschap2_peer_challenge,
"specify CHAP peer challenge" },
#endif
{ NULL }
};
#endif /* PPP_OPTIONS */
#if PPP_SERVER
/*
* chapms_generate_challenge - generate a challenge for MS-CHAP.
* For MS-CHAP the challenge length is fixed at 8 bytes.
* The length goes in challenge[0] and the actual challenge starts
* at challenge[1].
*/
static void chapms_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) {
LWIP_UNUSED_ARG(pcb);
*challenge++ = 8;
#ifdef DEBUGMPPEKEY
if (mschap_challenge && strlen(mschap_challenge) == 8)
memcpy(challenge, mschap_challenge, 8);
else
#endif
magic_random_bytes(challenge, 8);
}
static void chapms2_generate_challenge(ppp_pcb *pcb, unsigned char *challenge) {
LWIP_UNUSED_ARG(pcb);
*challenge++ = 16;
#ifdef DEBUGMPPEKEY
if (mschap_challenge && strlen(mschap_challenge) == 16)
memcpy(challenge, mschap_challenge, 16);
else
#endif
magic_random_bytes(challenge, 16);
}
static int chapms_verify_response(ppp_pcb *pcb, int id, const char *name,
const unsigned char *secret, int secret_len,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space) {
unsigned char md[MS_CHAP_RESPONSE_LEN];
int diff;
int challenge_len, response_len;
LWIP_UNUSED_ARG(id);
LWIP_UNUSED_ARG(name);
challenge_len = *challenge++; /* skip length, is 8 */
response_len = *response++;
if (response_len != MS_CHAP_RESPONSE_LEN)
goto bad;
#ifndef MSLANMAN
if (!response[MS_CHAP_USENT]) {
/* Should really propagate this into the error packet. */
ppp_notice(("Peer request for LANMAN auth not supported"));
goto bad;
}
#endif
/* Generate the expected response. */
ChapMS(pcb, (const u_char *)challenge, (const char *)secret, secret_len, md);
#ifdef MSLANMAN
/* Determine which part of response to verify against */
if (!response[MS_CHAP_USENT])
diff = memcmp(&response[MS_CHAP_LANMANRESP],
&md[MS_CHAP_LANMANRESP], MS_CHAP_LANMANRESP_LEN);
else
#endif
diff = memcmp(&response[MS_CHAP_NTRESP], &md[MS_CHAP_NTRESP],
MS_CHAP_NTRESP_LEN);
if (diff == 0) {
ppp_slprintf(message, message_space, "Access granted");
return 1;
}
bad:
/* See comments below for MS-CHAP V2 */
ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0",
challenge_len, challenge);
return 0;
}
static int chapms2_verify_response(ppp_pcb *pcb, int id, const char *name,
const unsigned char *secret, int secret_len,
const unsigned char *challenge, const unsigned char *response,
char *message, int message_space) {
unsigned char md[MS_CHAP2_RESPONSE_LEN];
char saresponse[MS_AUTH_RESPONSE_LENGTH+1];
int challenge_len, response_len;
LWIP_UNUSED_ARG(id);
challenge_len = *challenge++; /* skip length, is 16 */
response_len = *response++;
if (response_len != MS_CHAP2_RESPONSE_LEN)
goto bad; /* not even the right length */
/* Generate the expected response and our mutual auth. */
ChapMS2(pcb, (const u_char*)challenge, (const u_char*)&response[MS_CHAP2_PEER_CHALLENGE], name,
(const char *)secret, secret_len, md,
(unsigned char *)saresponse, MS_CHAP2_AUTHENTICATOR);
/* compare MDs and send the appropriate status */
/*
* Per RFC 2759, success message must be formatted as
* "S=<auth_string> M=<message>"
* where
* <auth_string> is the Authenticator Response (mutual auth)
* <message> is a text message
*
* However, some versions of Windows (win98 tested) do not know
* about the M=<message> part (required per RFC 2759) and flag
* it as an error (reported incorrectly as an encryption error
* to the user). Since the RFC requires it, and it can be
* useful information, we supply it if the peer is a conforming
* system. Luckily (?), win98 sets the Flags field to 0x04
* (contrary to RFC requirements) so we can use that to
* distinguish between conforming and non-conforming systems.
*
* Special thanks to Alex Swiridov <say@real.kharkov.ua> for
* help debugging this.
*/
if (memcmp(&md[MS_CHAP2_NTRESP], &response[MS_CHAP2_NTRESP],
MS_CHAP2_NTRESP_LEN) == 0) {
if (response[MS_CHAP2_FLAGS])
ppp_slprintf(message, message_space, "S=%s", saresponse);
else
ppp_slprintf(message, message_space, "S=%s M=%s",
saresponse, "Access granted");
return 1;
}
bad:
/*
* Failure message must be formatted as
* "E=e R=r C=c V=v M=m"
* where
* e = error code (we use 691, ERROR_AUTHENTICATION_FAILURE)
* r = retry (we use 1, ok to retry)
* c = challenge to use for next response, we reuse previous
* v = Change Password version supported, we use 0
* m = text message
*
* The M=m part is only for MS-CHAPv2. Neither win2k nor
* win98 (others untested) display the message to the user anyway.
* They also both ignore the E=e code.
*
* Note that it's safe to reuse the same challenge as we don't
* actually accept another response based on the error message
* (and no clients try to resend a response anyway).
*
* Basically, this whole bit is useless code, even the small
* implementation here is only because of overspecification.
*/
ppp_slprintf(message, message_space, "E=691 R=1 C=%0.*B V=0 M=%s",
challenge_len, challenge, "Access denied");
return 0;
}
#endif /* PPP_SERVER */
static void chapms_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name,
const unsigned char *challenge, const char *secret, int secret_len,
unsigned char *private_) {
LWIP_UNUSED_ARG(id);
LWIP_UNUSED_ARG(our_name);
LWIP_UNUSED_ARG(private_);
challenge++; /* skip length, should be 8 */
*response++ = MS_CHAP_RESPONSE_LEN;
ChapMS(pcb, challenge, secret, secret_len, response);
}
static void chapms2_make_response(ppp_pcb *pcb, unsigned char *response, int id, const char *our_name,
const unsigned char *challenge, const char *secret, int secret_len,
unsigned char *private_) {
LWIP_UNUSED_ARG(id);
challenge++; /* skip length, should be 16 */
*response++ = MS_CHAP2_RESPONSE_LEN;
ChapMS2(pcb, challenge,
#ifdef DEBUGMPPEKEY
mschap2_peer_challenge,
#else
NULL,
#endif
our_name, secret, secret_len, response, private_,
MS_CHAP2_AUTHENTICATEE);
}
static int chapms2_check_success(ppp_pcb *pcb, unsigned char *msg, int len, unsigned char *private_) {
LWIP_UNUSED_ARG(pcb);
if ((len < MS_AUTH_RESPONSE_LENGTH + 2) ||
strncmp((char *)msg, "S=", 2) != 0) {
/* Packet does not start with "S=" */
ppp_error(("MS-CHAPv2 Success packet is badly formed."));
return 0;
}
msg += 2;
len -= 2;
if (len < MS_AUTH_RESPONSE_LENGTH
|| memcmp(msg, private_, MS_AUTH_RESPONSE_LENGTH)) {
/* Authenticator Response did not match expected. */
ppp_error(("MS-CHAPv2 mutual authentication failed."));
return 0;
}
/* Authenticator Response matches. */
msg += MS_AUTH_RESPONSE_LENGTH; /* Eat it */
len -= MS_AUTH_RESPONSE_LENGTH;
if ((len >= 3) && !strncmp((char *)msg, " M=", 3)) {
msg += 3; /* Eat the delimiter */
} else if (len) {
/* Packet has extra text which does not begin " M=" */
ppp_error(("MS-CHAPv2 Success packet is badly formed."));
return 0;
}
return 1;
}
static void chapms_handle_failure(ppp_pcb *pcb, unsigned char *inp, int len) {
int err;
const char *p;
char msg[64];
LWIP_UNUSED_ARG(pcb);
/* We want a null-terminated string for strxxx(). */
len = LWIP_MIN(len, 63);
MEMCPY(msg, inp, len);
msg[len] = 0;
p = msg;
/*
* Deal with MS-CHAP formatted failure messages; just print the
* M=<message> part (if any). For MS-CHAP we're not really supposed
* to use M=<message>, but it shouldn't hurt. See
* chapms[2]_verify_response.
*/
if (!strncmp(p, "E=", 2))
err = strtol(p+2, NULL, 10); /* Remember the error code. */
else
goto print_msg; /* Message is badly formatted. */
if (len && ((p = strstr(p, " M=")) != NULL)) {
/* M=<message> field found. */
p += 3;
} else {
/* No M=<message>; use the error code. */
switch (err) {
case MS_CHAP_ERROR_RESTRICTED_LOGON_HOURS:
p = "E=646 Restricted logon hours";
break;
case MS_CHAP_ERROR_ACCT_DISABLED:
p = "E=647 Account disabled";
break;
case MS_CHAP_ERROR_PASSWD_EXPIRED:
p = "E=648 Password expired";
break;
case MS_CHAP_ERROR_NO_DIALIN_PERMISSION:
p = "E=649 No dialin permission";
break;
case MS_CHAP_ERROR_AUTHENTICATION_FAILURE:
p = "E=691 Authentication failure";
break;
case MS_CHAP_ERROR_CHANGING_PASSWORD:
/* Should never see this, we don't support Change Password. */
p = "E=709 Error changing password";
break;
default:
ppp_error(("Unknown MS-CHAP authentication failure: %.*v",
len, inp));
return;
}
}
print_msg:
if (p != NULL)
ppp_error(("MS-CHAP authentication failed: %v", p));
}
static void ChallengeResponse(const u_char *challenge,
const u_char PasswordHash[MD4_SIGNATURE_SIZE],
u_char response[24]) {
u_char ZPasswordHash[21];
lwip_des_context des;
u_char des_key[8];
BZERO(ZPasswordHash, sizeof(ZPasswordHash));
MEMCPY(ZPasswordHash, PasswordHash, MD4_SIGNATURE_SIZE);
#if 0
dbglog("ChallengeResponse - ZPasswordHash %.*B",
sizeof(ZPasswordHash), ZPasswordHash);
#endif
pppcrypt_56_to_64_bit_key(ZPasswordHash + 0, des_key);
lwip_des_init(&des);
lwip_des_setkey_enc(&des, des_key);
lwip_des_crypt_ecb(&des, challenge, response +0);
lwip_des_free(&des);
pppcrypt_56_to_64_bit_key(ZPasswordHash + 7, des_key);
lwip_des_init(&des);
lwip_des_setkey_enc(&des, des_key);
lwip_des_crypt_ecb(&des, challenge, response +8);
lwip_des_free(&des);
pppcrypt_56_to_64_bit_key(ZPasswordHash + 14, des_key);
lwip_des_init(&des);
lwip_des_setkey_enc(&des, des_key);
lwip_des_crypt_ecb(&des, challenge, response +16);
lwip_des_free(&des);
#if 0
dbglog("ChallengeResponse - response %.24B", response);
#endif
}
static void ChallengeHash(const u_char PeerChallenge[16], const u_char *rchallenge,
const char *username, u_char Challenge[8]) {
lwip_sha1_context sha1Context;
u_char sha1Hash[SHA1_SIGNATURE_SIZE];
const char *user;
/* remove domain from "domain\username" */
if ((user = strrchr(username, '\\')) != NULL)
++user;
else
user = username;
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, PeerChallenge, 16);
lwip_sha1_update(&sha1Context, rchallenge, 16);
lwip_sha1_update(&sha1Context, (const unsigned char*)user, strlen(user));
lwip_sha1_finish(&sha1Context, sha1Hash);
lwip_sha1_free(&sha1Context);
MEMCPY(Challenge, sha1Hash, 8);
}
/*
* Convert the ASCII version of the password to Unicode.
* This implicitly supports 8-bit ISO8859/1 characters.
* This gives us the little-endian representation, which
* is assumed by all M$ CHAP RFCs. (Unicode byte ordering
* is machine-dependent.)
*/
static void ascii2unicode(const char ascii[], int ascii_len, u_char unicode[]) {
int i;
BZERO(unicode, ascii_len * 2);
for (i = 0; i < ascii_len; i++)
unicode[i * 2] = (u_char) ascii[i];
}
static void NTPasswordHash(u_char *secret, int secret_len, u_char hash[MD4_SIGNATURE_SIZE]) {
lwip_md4_context md4Context;
lwip_md4_init(&md4Context);
lwip_md4_starts(&md4Context);
lwip_md4_update(&md4Context, secret, secret_len);
lwip_md4_finish(&md4Context, hash);
lwip_md4_free(&md4Context);
}
static void ChapMS_NT(const u_char *rchallenge, const char *secret, int secret_len,
u_char NTResponse[24]) {
u_char unicodePassword[MAX_NT_PASSWORD * 2];
u_char PasswordHash[MD4_SIGNATURE_SIZE];
/* Hash the Unicode version of the secret (== password). */
ascii2unicode(secret, secret_len, unicodePassword);
NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash);
ChallengeResponse(rchallenge, PasswordHash, NTResponse);
}
static void ChapMS2_NT(const u_char *rchallenge, const u_char PeerChallenge[16], const char *username,
const char *secret, int secret_len, u_char NTResponse[24]) {
u_char unicodePassword[MAX_NT_PASSWORD * 2];
u_char PasswordHash[MD4_SIGNATURE_SIZE];
u_char Challenge[8];
ChallengeHash(PeerChallenge, rchallenge, username, Challenge);
/* Hash the Unicode version of the secret (== password). */
ascii2unicode(secret, secret_len, unicodePassword);
NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash);
ChallengeResponse(Challenge, PasswordHash, NTResponse);
}
#ifdef MSLANMAN
static u_char *StdText = (u_char *)"KGS!@#$%"; /* key from rasapi32.dll */
static void ChapMS_LANMan(u_char *rchallenge, char *secret, int secret_len,
unsigned char *response) {
int i;
u_char UcasePassword[MAX_NT_PASSWORD]; /* max is actually 14 */
u_char PasswordHash[MD4_SIGNATURE_SIZE];
lwip_des_context des;
u_char des_key[8];
/* LANMan password is case insensitive */
BZERO(UcasePassword, sizeof(UcasePassword));
for (i = 0; i < secret_len; i++)
UcasePassword[i] = (u_char)toupper(secret[i]);
pppcrypt_56_to_64_bit_key(UcasePassword +0, des_key);
lwip_des_init(&des);
lwip_des_setkey_enc(&des, des_key);
lwip_des_crypt_ecb(&des, StdText, PasswordHash +0);
lwip_des_free(&des);
pppcrypt_56_to_64_bit_key(UcasePassword +7, des_key);
lwip_des_init(&des);
lwip_des_setkey_enc(&des, des_key);
lwip_des_crypt_ecb(&des, StdText, PasswordHash +8);
lwip_des_free(&des);
ChallengeResponse(rchallenge, PasswordHash, &response[MS_CHAP_LANMANRESP]);
}
#endif
static void GenerateAuthenticatorResponse(const u_char PasswordHashHash[MD4_SIGNATURE_SIZE],
u_char NTResponse[24], const u_char PeerChallenge[16],
const u_char *rchallenge, const char *username,
u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) {
/*
* "Magic" constants used in response generation, from RFC 2759.
*/
static const u_char Magic1[39] = /* "Magic server to client signing constant" */
{ 0x4D, 0x61, 0x67, 0x69, 0x63, 0x20, 0x73, 0x65, 0x72, 0x76,
0x65, 0x72, 0x20, 0x74, 0x6F, 0x20, 0x63, 0x6C, 0x69, 0x65,
0x6E, 0x74, 0x20, 0x73, 0x69, 0x67, 0x6E, 0x69, 0x6E, 0x67,
0x20, 0x63, 0x6F, 0x6E, 0x73, 0x74, 0x61, 0x6E, 0x74 };
static const u_char Magic2[41] = /* "Pad to make it do more than one iteration" */
{ 0x50, 0x61, 0x64, 0x20, 0x74, 0x6F, 0x20, 0x6D, 0x61, 0x6B,
0x65, 0x20, 0x69, 0x74, 0x20, 0x64, 0x6F, 0x20, 0x6D, 0x6F,
0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6E, 0x20, 0x6F, 0x6E,
0x65, 0x20, 0x69, 0x74, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6F,
0x6E };
int i;
lwip_sha1_context sha1Context;
u_char Digest[SHA1_SIGNATURE_SIZE];
u_char Challenge[8];
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE);
lwip_sha1_update(&sha1Context, NTResponse, 24);
lwip_sha1_update(&sha1Context, Magic1, sizeof(Magic1));
lwip_sha1_finish(&sha1Context, Digest);
lwip_sha1_free(&sha1Context);
ChallengeHash(PeerChallenge, rchallenge, username, Challenge);
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, Digest, sizeof(Digest));
lwip_sha1_update(&sha1Context, Challenge, sizeof(Challenge));
lwip_sha1_update(&sha1Context, Magic2, sizeof(Magic2));
lwip_sha1_finish(&sha1Context, Digest);
lwip_sha1_free(&sha1Context);
/* Convert to ASCII hex string. */
for (i = 0; i < LWIP_MAX((MS_AUTH_RESPONSE_LENGTH / 2), (int)sizeof(Digest)); i++)
sprintf((char *)&authResponse[i * 2], "%02X", Digest[i]);
}
static void GenerateAuthenticatorResponsePlain(
const char *secret, int secret_len,
u_char NTResponse[24], const u_char PeerChallenge[16],
const u_char *rchallenge, const char *username,
u_char authResponse[MS_AUTH_RESPONSE_LENGTH+1]) {
u_char unicodePassword[MAX_NT_PASSWORD * 2];
u_char PasswordHash[MD4_SIGNATURE_SIZE];
u_char PasswordHashHash[MD4_SIGNATURE_SIZE];
/* Hash (x2) the Unicode version of the secret (== password). */
ascii2unicode(secret, secret_len, unicodePassword);
NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash);
NTPasswordHash(PasswordHash, sizeof(PasswordHash),
PasswordHashHash);
GenerateAuthenticatorResponse(PasswordHashHash, NTResponse, PeerChallenge,
rchallenge, username, authResponse);
}
#if MPPE_SUPPORT
/*
* Set mppe_xxxx_key from MS-CHAP credentials. (see RFC 3079)
*/
static void Set_Start_Key(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, int secret_len) {
u_char unicodePassword[MAX_NT_PASSWORD * 2];
u_char PasswordHash[MD4_SIGNATURE_SIZE];
u_char PasswordHashHash[MD4_SIGNATURE_SIZE];
lwip_sha1_context sha1Context;
u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */
/* Hash (x2) the Unicode version of the secret (== password). */
ascii2unicode(secret, secret_len, unicodePassword);
NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash);
NTPasswordHash(PasswordHash, sizeof(PasswordHash), PasswordHashHash);
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE);
lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE);
lwip_sha1_update(&sha1Context, rchallenge, 8);
lwip_sha1_finish(&sha1Context, Digest);
lwip_sha1_free(&sha1Context);
/* Same key in both directions. */
mppe_set_key(pcb, &pcb->mppe_comp, Digest);
mppe_set_key(pcb, &pcb->mppe_decomp, Digest);
pcb->mppe_keys_set = 1;
}
/*
* Set mppe_xxxx_key from MS-CHAPv2 credentials. (see RFC 3079)
*/
static void SetMasterKeys(ppp_pcb *pcb, const char *secret, int secret_len, u_char NTResponse[24], int IsServer) {
u_char unicodePassword[MAX_NT_PASSWORD * 2];
u_char PasswordHash[MD4_SIGNATURE_SIZE];
u_char PasswordHashHash[MD4_SIGNATURE_SIZE];
lwip_sha1_context sha1Context;
u_char MasterKey[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */
u_char Digest[SHA1_SIGNATURE_SIZE]; /* >= MPPE_MAX_KEY_LEN */
const u_char *s;
/* "This is the MPPE Master Key" */
static const u_char Magic1[27] =
{ 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74,
0x68, 0x65, 0x20, 0x4d, 0x50, 0x50, 0x45, 0x20, 0x4d,
0x61, 0x73, 0x74, 0x65, 0x72, 0x20, 0x4b, 0x65, 0x79 };
/* "On the client side, this is the send key; "
"on the server side, it is the receive key." */
static const u_char Magic2[84] =
{ 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20,
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20, 0x6b, 0x65, 0x79,
0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73,
0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x69, 0x64, 0x65,
0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20,
0x6b, 0x65, 0x79, 0x2e };
/* "On the client side, this is the receive key; "
"on the server side, it is the send key." */
static const u_char Magic3[84] =
{ 0x4f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x69,
0x65, 0x6e, 0x74, 0x20, 0x73, 0x69, 0x64, 0x65, 0x2c, 0x20,
0x74, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
0x65, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x20,
0x6b, 0x65, 0x79, 0x3b, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68,
0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73,
0x69, 0x64, 0x65, 0x2c, 0x20, 0x69, 0x74, 0x20, 0x69, 0x73,
0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x20,
0x6b, 0x65, 0x79, 0x2e };
/* Hash (x2) the Unicode version of the secret (== password). */
ascii2unicode(secret, secret_len, unicodePassword);
NTPasswordHash(unicodePassword, secret_len * 2, PasswordHash);
NTPasswordHash(PasswordHash, sizeof(PasswordHash), PasswordHashHash);
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, PasswordHashHash, MD4_SIGNATURE_SIZE);
lwip_sha1_update(&sha1Context, NTResponse, 24);
lwip_sha1_update(&sha1Context, Magic1, sizeof(Magic1));
lwip_sha1_finish(&sha1Context, MasterKey);
lwip_sha1_free(&sha1Context);
/*
* generate send key
*/
if (IsServer)
s = Magic3;
else
s = Magic2;
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, MasterKey, 16);
lwip_sha1_update(&sha1Context, mppe_sha1_pad1, SHA1_PAD_SIZE);
lwip_sha1_update(&sha1Context, s, 84);
lwip_sha1_update(&sha1Context, mppe_sha1_pad2, SHA1_PAD_SIZE);
lwip_sha1_finish(&sha1Context, Digest);
lwip_sha1_free(&sha1Context);
mppe_set_key(pcb, &pcb->mppe_comp, Digest);
/*
* generate recv key
*/
if (IsServer)
s = Magic2;
else
s = Magic3;
lwip_sha1_init(&sha1Context);
lwip_sha1_starts(&sha1Context);
lwip_sha1_update(&sha1Context, MasterKey, 16);
lwip_sha1_update(&sha1Context, mppe_sha1_pad1, SHA1_PAD_SIZE);
lwip_sha1_update(&sha1Context, s, 84);
lwip_sha1_update(&sha1Context, mppe_sha1_pad2, SHA1_PAD_SIZE);
lwip_sha1_finish(&sha1Context, Digest);
lwip_sha1_free(&sha1Context);
mppe_set_key(pcb, &pcb->mppe_decomp, Digest);
pcb->mppe_keys_set = 1;
}
#endif /* MPPE_SUPPORT */
static void ChapMS(ppp_pcb *pcb, const u_char *rchallenge, const char *secret, int secret_len,
unsigned char *response) {
#if !MPPE_SUPPORT
LWIP_UNUSED_ARG(pcb);
#endif /* !MPPE_SUPPORT */
BZERO(response, MS_CHAP_RESPONSE_LEN);
ChapMS_NT(rchallenge, secret, secret_len, &response[MS_CHAP_NTRESP]);
#ifdef MSLANMAN
ChapMS_LANMan(rchallenge, secret, secret_len,
&response[MS_CHAP_LANMANRESP]);
/* preferred method is set by option */
response[MS_CHAP_USENT] = !ms_lanman;
#else
response[MS_CHAP_USENT] = 1;
#endif
#if MPPE_SUPPORT
Set_Start_Key(pcb, rchallenge, secret, secret_len);
#endif /* MPPE_SUPPORT */
}
/*
* If PeerChallenge is NULL, one is generated and the PeerChallenge
* field of response is filled in. Call this way when generating a response.
* If PeerChallenge is supplied, it is copied into the PeerChallenge field.
* Call this way when verifying a response (or debugging).
* Do not call with PeerChallenge = response.
*
* The PeerChallenge field of response is then used for calculation of the
* Authenticator Response.
*/
static void ChapMS2(ppp_pcb *pcb, const u_char *rchallenge, const u_char *PeerChallenge,
const char *user, const char *secret, int secret_len, unsigned char *response,
u_char authResponse[], int authenticator) {
/* ARGSUSED */
LWIP_UNUSED_ARG(authenticator);
#if !MPPE_SUPPORT
LWIP_UNUSED_ARG(pcb);
#endif /* !MPPE_SUPPORT */
BZERO(response, MS_CHAP2_RESPONSE_LEN);
/* Generate the Peer-Challenge if requested, or copy it if supplied. */
if (!PeerChallenge)
magic_random_bytes(&response[MS_CHAP2_PEER_CHALLENGE], MS_CHAP2_PEER_CHAL_LEN);
else
MEMCPY(&response[MS_CHAP2_PEER_CHALLENGE], PeerChallenge,
MS_CHAP2_PEER_CHAL_LEN);
/* Generate the NT-Response */
ChapMS2_NT(rchallenge, &response[MS_CHAP2_PEER_CHALLENGE], user,
secret, secret_len, &response[MS_CHAP2_NTRESP]);
/* Generate the Authenticator Response. */
GenerateAuthenticatorResponsePlain(secret, secret_len,
&response[MS_CHAP2_NTRESP],
&response[MS_CHAP2_PEER_CHALLENGE],
rchallenge, user, authResponse);
#if MPPE_SUPPORT
SetMasterKeys(pcb, secret, secret_len,
&response[MS_CHAP2_NTRESP], authenticator);
#endif /* MPPE_SUPPORT */
}
#if 0 /* UNUSED */
#if MPPE_SUPPORT
/*
* Set MPPE options from plugins.
*/
void set_mppe_enc_types(int policy, int types) {
/* Early exit for unknown policies. */
if (policy != MPPE_ENC_POL_ENC_ALLOWED ||
policy != MPPE_ENC_POL_ENC_REQUIRED)
return;
/* Don't modify MPPE if it's optional and wasn't already configured. */
if (policy == MPPE_ENC_POL_ENC_ALLOWED && !ccp_wantoptions[0].mppe)
return;
/*
* Disable undesirable encryption types. Note that we don't ENABLE
* any encryption types, to avoid overriding manual configuration.
*/
switch(types) {
case MPPE_ENC_TYPES_RC4_40:
ccp_wantoptions[0].mppe &= ~MPPE_OPT_128; /* disable 128-bit */
break;
case MPPE_ENC_TYPES_RC4_128:
ccp_wantoptions[0].mppe &= ~MPPE_OPT_40; /* disable 40-bit */
break;
default:
break;
}
}
#endif /* MPPE_SUPPORT */
#endif /* UNUSED */
const struct chap_digest_type chapms_digest = {
CHAP_MICROSOFT, /* code */
#if PPP_SERVER
chapms_generate_challenge,
chapms_verify_response,
#endif /* PPP_SERVER */
chapms_make_response,
NULL, /* check_success */
chapms_handle_failure,
};
const struct chap_digest_type chapms2_digest = {
CHAP_MICROSOFT_V2, /* code */
#if PPP_SERVER
chapms2_generate_challenge,
chapms2_verify_response,
#endif /* PPP_SERVER */
chapms2_make_response,
chapms2_check_success,
chapms_handle_failure,
};
#endif /* PPP_SUPPORT && MSCHAP_SUPPORT */

View File

@ -1,465 +0,0 @@
/*
* demand.c - Support routines for demand-dialling.
*
* Copyright (c) 1996-2002 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && DEMAND_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <unistd.h>
#include <syslog.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef PPP_FILTER
#include <pcap-bpf.h>
#endif
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/fsm.h"
#include "netif/ppp/ipcp.h"
#include "netif/ppp/lcp.h"
char *frame;
int framelen;
int framemax;
int escape_flag;
int flush_flag;
int fcs;
struct packet {
int length;
struct packet *next;
unsigned char data[1];
};
struct packet *pend_q;
struct packet *pend_qtail;
static int active_packet (unsigned char *, int);
/*
* demand_conf - configure the interface for doing dial-on-demand.
*/
void
demand_conf()
{
int i;
const struct protent *protp;
/* framemax = lcp_allowoptions[0].mru;
if (framemax < PPP_DEFMRU) */
framemax = PPP_DEFMRU;
framemax += PPP_HDRLEN + PPP_FCSLEN;
frame = malloc(framemax);
if (frame == NULL)
novm("demand frame");
framelen = 0;
pend_q = NULL;
escape_flag = 0;
flush_flag = 0;
fcs = PPP_INITFCS;
ppp_netif_set_mtu(pcb, LWIP_MIN(lcp_allowoptions[0].mru, PPP_DEFMRU));
if (ppp_send_config(pcb, PPP_DEFMRU, (u32_t) 0, 0, 0) < 0
|| ppp_recv_config(pcb, PPP_DEFMRU, (u32_t) 0, 0, 0) < 0)
fatal("Couldn't set up demand-dialled PPP interface: %m");
#ifdef PPP_FILTER
set_filters(&pass_filter, &active_filter);
#endif
/*
* Call the demand_conf procedure for each protocol that's got one.
*/
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (protp->demand_conf != NULL)
((*protp->demand_conf)(pcb));
/* FIXME: find a way to die() here */
#if 0
if (!((*protp->demand_conf)(pcb)))
die(1);
#endif
}
/*
* demand_block - set each network protocol to block further packets.
*/
void
demand_block()
{
int i;
const struct protent *protp;
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (protp->demand_conf != NULL)
sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_QUEUE);
get_loop_output();
}
/*
* demand_discard - set each network protocol to discard packets
* with an error.
*/
void
demand_discard()
{
struct packet *pkt, *nextpkt;
int i;
const struct protent *protp;
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (protp->demand_conf != NULL)
sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_ERROR);
get_loop_output();
/* discard all saved packets */
for (pkt = pend_q; pkt != NULL; pkt = nextpkt) {
nextpkt = pkt->next;
free(pkt);
}
pend_q = NULL;
framelen = 0;
flush_flag = 0;
escape_flag = 0;
fcs = PPP_INITFCS;
}
/*
* demand_unblock - set each enabled network protocol to pass packets.
*/
void
demand_unblock()
{
int i;
const struct protent *protp;
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (protp->demand_conf != NULL)
sifnpmode(pcb, protp->protocol & ~0x8000, NPMODE_PASS);
}
/*
* FCS lookup table as calculated by genfcstab.
*/
static u_short fcstab[256] = {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
/*
* loop_chars - process characters received from the loopback.
* Calls loop_frame when a complete frame has been accumulated.
* Return value is 1 if we need to bring up the link, 0 otherwise.
*/
int
loop_chars(p, n)
unsigned char *p;
int n;
{
int c, rv;
rv = 0;
/* check for synchronous connection... */
if ( (p[0] == 0xFF) && (p[1] == 0x03) ) {
rv = loop_frame(p,n);
return rv;
}
for (; n > 0; --n) {
c = *p++;
if (c == PPP_FLAG) {
if (!escape_flag && !flush_flag
&& framelen > 2 && fcs == PPP_GOODFCS) {
framelen -= 2;
if (loop_frame((unsigned char *)frame, framelen))
rv = 1;
}
framelen = 0;
flush_flag = 0;
escape_flag = 0;
fcs = PPP_INITFCS;
continue;
}
if (flush_flag)
continue;
if (escape_flag) {
c ^= PPP_TRANS;
escape_flag = 0;
} else if (c == PPP_ESCAPE) {
escape_flag = 1;
continue;
}
if (framelen >= framemax) {
flush_flag = 1;
continue;
}
frame[framelen++] = c;
fcs = PPP_FCS(fcs, c);
}
return rv;
}
/*
* loop_frame - given a frame obtained from the loopback,
* decide whether to bring up the link or not, and, if we want
* to transmit this frame later, put it on the pending queue.
* Return value is 1 if we need to bring up the link, 0 otherwise.
* We assume that the kernel driver has already applied the
* pass_filter, so we won't get packets it rejected.
* We apply the active_filter to see if we want this packet to
* bring up the link.
*/
int
loop_frame(frame, len)
unsigned char *frame;
int len;
{
struct packet *pkt;
/* dbglog("from loop: %P", frame, len); */
if (len < PPP_HDRLEN)
return 0;
if ((PPP_PROTOCOL(frame) & 0x8000) != 0)
return 0; /* shouldn't get any of these anyway */
if (!active_packet(frame, len))
return 0;
pkt = (struct packet *) malloc(sizeof(struct packet) + len);
if (pkt != NULL) {
pkt->length = len;
pkt->next = NULL;
memcpy(pkt->data, frame, len);
if (pend_q == NULL)
pend_q = pkt;
else
pend_qtail->next = pkt;
pend_qtail = pkt;
}
return 1;
}
/*
* demand_rexmit - Resend all those frames which we got via the
* loopback, now that the real serial link is up.
*/
void
demand_rexmit(proto, newip)
int proto;
u32_t newip;
{
struct packet *pkt, *prev, *nextpkt;
unsigned short checksum;
unsigned short pkt_checksum = 0;
unsigned iphdr;
struct timeval tv;
char cv = 0;
char ipstr[16];
prev = NULL;
pkt = pend_q;
pend_q = NULL;
tv.tv_sec = 1;
tv.tv_usec = 0;
select(0,NULL,NULL,NULL,&tv); /* Sleep for 1 Seconds */
for (; pkt != NULL; pkt = nextpkt) {
nextpkt = pkt->next;
if (PPP_PROTOCOL(pkt->data) == proto) {
if ( (proto == PPP_IP) && newip ) {
/* Get old checksum */
iphdr = (pkt->data[4] & 15) << 2;
checksum = *((unsigned short *) (pkt->data+14));
if (checksum == 0xFFFF) {
checksum = 0;
}
if (pkt->data[13] == 17) {
pkt_checksum = *((unsigned short *) (pkt->data+10+iphdr));
if (pkt_checksum) {
cv = 1;
if (pkt_checksum == 0xFFFF) {
pkt_checksum = 0;
}
}
else {
cv = 0;
}
}
if (pkt->data[13] == 6) {
pkt_checksum = *((unsigned short *) (pkt->data+20+iphdr));
cv = 1;
if (pkt_checksum == 0xFFFF) {
pkt_checksum = 0;
}
}
/* Delete old Source-IP-Address */
checksum -= *((unsigned short *) (pkt->data+16)) ^ 0xFFFF;
checksum -= *((unsigned short *) (pkt->data+18)) ^ 0xFFFF;
pkt_checksum -= *((unsigned short *) (pkt->data+16)) ^ 0xFFFF;
pkt_checksum -= *((unsigned short *) (pkt->data+18)) ^ 0xFFFF;
/* Change Source-IP-Address */
* ((u32_t *) (pkt->data + 16)) = newip;
/* Add new Source-IP-Address */
checksum += *((unsigned short *) (pkt->data+16)) ^ 0xFFFF;
checksum += *((unsigned short *) (pkt->data+18)) ^ 0xFFFF;
pkt_checksum += *((unsigned short *) (pkt->data+16)) ^ 0xFFFF;
pkt_checksum += *((unsigned short *) (pkt->data+18)) ^ 0xFFFF;
/* Write new checksum */
if (!checksum) {
checksum = 0xFFFF;
}
*((unsigned short *) (pkt->data+14)) = checksum;
if (pkt->data[13] == 6) {
*((unsigned short *) (pkt->data+20+iphdr)) = pkt_checksum;
}
if (cv && (pkt->data[13] == 17) ) {
*((unsigned short *) (pkt->data+10+iphdr)) = pkt_checksum;
}
/* Log Packet */
strcpy(ipstr,inet_ntoa(*( (struct in_addr *) (pkt->data+16))));
if (pkt->data[13] == 1) {
syslog(LOG_INFO,"Open ICMP %s -> %s\n",
ipstr,
inet_ntoa(*( (struct in_addr *) (pkt->data+20))));
} else {
syslog(LOG_INFO,"Open %s %s:%d -> %s:%d\n",
pkt->data[13] == 6 ? "TCP" : "UDP",
ipstr,
ntohs(*( (short *) (pkt->data+iphdr+4))),
inet_ntoa(*( (struct in_addr *) (pkt->data+20))),
ntohs(*( (short *) (pkt->data+iphdr+6))));
}
}
output(pcb, pkt->data, pkt->length);
free(pkt);
} else {
if (prev == NULL)
pend_q = pkt;
else
prev->next = pkt;
prev = pkt;
}
}
pend_qtail = prev;
if (prev != NULL)
prev->next = NULL;
}
/*
* Scan a packet to decide whether it is an "active" packet,
* that is, whether it is worth bringing up the link for.
*/
static int
active_packet(p, len)
unsigned char *p;
int len;
{
int proto, i;
const struct protent *protp;
if (len < PPP_HDRLEN)
return 0;
proto = PPP_PROTOCOL(p);
#ifdef PPP_FILTER
p[0] = 1; /* outbound packet indicator */
if ((pass_filter.bf_len != 0
&& bpf_filter(pass_filter.bf_insns, p, len, len) == 0)
|| (active_filter.bf_len != 0
&& bpf_filter(active_filter.bf_insns, p, len, len) == 0)) {
p[0] = 0xff;
return 0;
}
p[0] = 0xff;
#endif
for (i = 0; (protp = protocols[i]) != NULL; ++i) {
if (protp->protocol < 0xC000 && (protp->protocol & ~0x8000) == proto) {
if (protp->active_pkt == NULL)
return 1;
return (*protp->active_pkt)(p, len);
}
}
return 0; /* not a supported protocol !!?? */
}
#endif /* PPP_SUPPORT && DEMAND_SUPPORT */

File diff suppressed because it is too large Load Diff

View File

@ -1,191 +0,0 @@
/*
* ecp.c - PPP Encryption Control Protocol.
*
* Copyright (c) 2002 Google, Inc.
* 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(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Derived from ccp.c, which is:
*
* Copyright (c) 1994-2002 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && ECP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include <string.h>
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/fsm.h"
#include "netif/ppp/ecp.h"
#if PPP_OPTIONS
static option_t ecp_option_list[] = {
{ "noecp", o_bool, &ecp_protent.enabled_flag,
"Disable ECP negotiation" },
{ "-ecp", o_bool, &ecp_protent.enabled_flag,
"Disable ECP negotiation", OPT_ALIAS },
{ NULL }
};
#endif /* PPP_OPTIONS */
/*
* Protocol entry points from main code.
*/
static void ecp_init (int unit);
/*
static void ecp_open (int unit);
static void ecp_close (int unit, char *);
static void ecp_lowerup (int unit);
static void ecp_lowerdown (int);
static void ecp_input (int unit, u_char *pkt, int len);
static void ecp_protrej (int unit);
*/
#if PRINTPKT_SUPPORT
static int ecp_printpkt (const u_char *pkt, int len,
void (*printer) (void *, char *, ...),
void *arg);
#endif /* PRINTPKT_SUPPORT */
/*
static void ecp_datainput (int unit, u_char *pkt, int len);
*/
const struct protent ecp_protent = {
PPP_ECP,
ecp_init,
NULL, /* ecp_input, */
NULL, /* ecp_protrej, */
NULL, /* ecp_lowerup, */
NULL, /* ecp_lowerdown, */
NULL, /* ecp_open, */
NULL, /* ecp_close, */
#if PRINTPKT_SUPPORT
ecp_printpkt,
#endif /* PRINTPKT_SUPPORT */
#if PPP_DATAINPUT
NULL, /* ecp_datainput, */
#endif /* PPP_DATAINPUT */
#if PRINTPKT_SUPPORT
"ECP",
"Encrypted",
#endif /* PRINTPKT_SUPPORT */
#if PPP_OPTIONS
ecp_option_list,
NULL,
#endif /* PPP_OPTIONS */
#if DEMAND_SUPPORT
NULL,
NULL
#endif /* DEMAND_SUPPORT */
};
fsm ecp_fsm[NUM_PPP];
ecp_options ecp_wantoptions[NUM_PPP]; /* what to request the peer to use */
ecp_options ecp_gotoptions[NUM_PPP]; /* what the peer agreed to do */
ecp_options ecp_allowoptions[NUM_PPP]; /* what we'll agree to do */
ecp_options ecp_hisoptions[NUM_PPP]; /* what we agreed to do */
static const fsm_callbacks ecp_callbacks = {
NULL, /* ecp_resetci, */
NULL, /* ecp_cilen, */
NULL, /* ecp_addci, */
NULL, /* ecp_ackci, */
NULL, /* ecp_nakci, */
NULL, /* ecp_rejci, */
NULL, /* ecp_reqci, */
NULL, /* ecp_up, */
NULL, /* ecp_down, */
NULL,
NULL,
NULL,
NULL,
NULL, /* ecp_extcode, */
"ECP"
};
/*
* ecp_init - initialize ECP.
*/
static void
ecp_init(unit)
int unit;
{
fsm *f = &ecp_fsm[unit];
f->unit = unit;
f->protocol = PPP_ECP;
f->callbacks = &ecp_callbacks;
fsm_init(f);
#if 0 /* Not necessary, everything is cleared in ppp_new() */
memset(&ecp_wantoptions[unit], 0, sizeof(ecp_options));
memset(&ecp_gotoptions[unit], 0, sizeof(ecp_options));
memset(&ecp_allowoptions[unit], 0, sizeof(ecp_options));
memset(&ecp_hisoptions[unit], 0, sizeof(ecp_options));
#endif /* 0 */
}
#if PRINTPKT_SUPPORT
static int
ecp_printpkt(p, plen, printer, arg)
const u_char *p;
int plen;
void (*printer) (void *, char *, ...);
void *arg;
{
return 0;
}
#endif /* PRINTPKT_SUPPORT */
#endif /* PPP_SUPPORT && ECP_SUPPORT */

View File

@ -1,56 +0,0 @@
/*
* eui64.c - EUI64 routines for IPv6CP.
*
* Copyright (c) 1999 Tommi Komulainen. 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(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Tommi Komulainen
* <Tommi.Komulainen@iki.fi>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* $Id: eui64.c,v 1.6 2002/12/04 23:03:32 paulus Exp $
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && PPP_IPV6_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/eui64.h"
/*
* eui64_ntoa - Make an ascii representation of an interface identifier
*/
char *eui64_ntoa(eui64_t e) {
static char buf[20];
sprintf(buf, "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
e.e8[0], e.e8[1], e.e8[2], e.e8[3],
e.e8[4], e.e8[5], e.e8[6], e.e8[7]);
return buf;
}
#endif /* PPP_SUPPORT && PPP_IPV6_SUPPORT */

View File

@ -1,799 +0,0 @@
/*
* fsm.c - {Link, IP} Control Protocol Finite State Machine.
*
* Copyright (c) 1984-2000 Carnegie Mellon University. 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 "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* tech-transfer@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
/*
* @todo:
* Randomize fsm id on link/init.
* Deal with variable outgoing MTU.
*/
#if 0 /* UNUSED */
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/fsm.h"
static void fsm_timeout (void *);
static void fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len);
static void fsm_rconfack(fsm *f, int id, u_char *inp, int len);
static void fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len);
static void fsm_rtermreq(fsm *f, int id, u_char *p, int len);
static void fsm_rtermack(fsm *f);
static void fsm_rcoderej(fsm *f, u_char *inp, int len);
static void fsm_sconfreq(fsm *f, int retransmit);
#define PROTO_NAME(f) ((f)->callbacks->proto_name)
/*
* fsm_init - Initialize fsm.
*
* Initialize fsm state.
*/
void fsm_init(fsm *f) {
ppp_pcb *pcb = f->pcb;
f->state = PPP_FSM_INITIAL;
f->flags = 0;
f->id = 0; /* XXX Start with random id? */
f->maxnakloops = pcb->settings.fsm_max_nak_loops;
f->term_reason_len = 0;
}
/*
* fsm_lowerup - The lower layer is up.
*/
void fsm_lowerup(fsm *f) {
switch( f->state ){
case PPP_FSM_INITIAL:
f->state = PPP_FSM_CLOSED;
break;
case PPP_FSM_STARTING:
if( f->flags & OPT_SILENT )
f->state = PPP_FSM_STOPPED;
else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = PPP_FSM_REQSENT;
}
break;
default:
FSMDEBUG(("%s: Up event in state %d!", PROTO_NAME(f), f->state));
/* no break */
}
}
/*
* fsm_lowerdown - The lower layer is down.
*
* Cancel all timeouts and inform upper layers.
*/
void fsm_lowerdown(fsm *f) {
switch( f->state ){
case PPP_FSM_CLOSED:
f->state = PPP_FSM_INITIAL;
break;
case PPP_FSM_STOPPED:
f->state = PPP_FSM_STARTING;
if( f->callbacks->starting )
(*f->callbacks->starting)(f);
break;
case PPP_FSM_CLOSING:
f->state = PPP_FSM_INITIAL;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case PPP_FSM_STOPPING:
case PPP_FSM_REQSENT:
case PPP_FSM_ACKRCVD:
case PPP_FSM_ACKSENT:
f->state = PPP_FSM_STARTING;
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
break;
case PPP_FSM_OPENED:
if( f->callbacks->down )
(*f->callbacks->down)(f);
f->state = PPP_FSM_STARTING;
break;
default:
FSMDEBUG(("%s: Down event in state %d!", PROTO_NAME(f), f->state));
/* no break */
}
}
/*
* fsm_open - Link is allowed to come up.
*/
void fsm_open(fsm *f) {
switch( f->state ){
case PPP_FSM_INITIAL:
f->state = PPP_FSM_STARTING;
if( f->callbacks->starting )
(*f->callbacks->starting)(f);
break;
case PPP_FSM_CLOSED:
if( f->flags & OPT_SILENT )
f->state = PPP_FSM_STOPPED;
else {
/* Send an initial configure-request */
fsm_sconfreq(f, 0);
f->state = PPP_FSM_REQSENT;
}
break;
case PPP_FSM_CLOSING:
f->state = PPP_FSM_STOPPING;
/* fall through */
/* no break */
case PPP_FSM_STOPPED:
case PPP_FSM_OPENED:
if( f->flags & OPT_RESTART ){
fsm_lowerdown(f);
fsm_lowerup(f);
}
break;
default:
break;
}
}
/*
* terminate_layer - Start process of shutting down the FSM
*
* Cancel any timeout running, notify upper layers we're done, and
* send a terminate-request message as configured.
*/
static void terminate_layer(fsm *f, int nextstate) {
ppp_pcb *pcb = f->pcb;
if( f->state != PPP_FSM_OPENED )
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
else if( f->callbacks->down )
(*f->callbacks->down)(f); /* Inform upper layers we're down */
/* Init restart counter and send Terminate-Request */
f->retransmits = pcb->settings.fsm_max_term_transmits;
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(const u_char *) f->term_reason, f->term_reason_len);
if (f->retransmits == 0) {
/*
* User asked for no terminate requests at all; just close it.
* We've already fired off one Terminate-Request just to be nice
* to the peer, but we're not going to wait for a reply.
*/
f->state = nextstate == PPP_FSM_CLOSING ? PPP_FSM_CLOSED : PPP_FSM_STOPPED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
return;
}
TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time);
--f->retransmits;
f->state = nextstate;
}
/*
* fsm_close - Start closing connection.
*
* Cancel timeouts and either initiate close or possibly go directly to
* the PPP_FSM_CLOSED state.
*/
void fsm_close(fsm *f, const char *reason) {
f->term_reason = reason;
f->term_reason_len = (reason == NULL? 0: (u8_t)LWIP_MIN(strlen(reason), 0xFF) );
switch( f->state ){
case PPP_FSM_STARTING:
f->state = PPP_FSM_INITIAL;
break;
case PPP_FSM_STOPPED:
f->state = PPP_FSM_CLOSED;
break;
case PPP_FSM_STOPPING:
f->state = PPP_FSM_CLOSING;
break;
case PPP_FSM_REQSENT:
case PPP_FSM_ACKRCVD:
case PPP_FSM_ACKSENT:
case PPP_FSM_OPENED:
terminate_layer(f, PPP_FSM_CLOSING);
break;
default:
break;
}
}
/*
* fsm_timeout - Timeout expired.
*/
static void fsm_timeout(void *arg) {
fsm *f = (fsm *) arg;
ppp_pcb *pcb = f->pcb;
switch (f->state) {
case PPP_FSM_CLOSING:
case PPP_FSM_STOPPING:
if( f->retransmits <= 0 ){
/*
* We've waited for an ack long enough. Peer probably heard us.
*/
f->state = (f->state == PPP_FSM_CLOSING)? PPP_FSM_CLOSED: PPP_FSM_STOPPED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
} else {
/* Send Terminate-Request */
fsm_sdata(f, TERMREQ, f->reqid = ++f->id,
(const u_char *) f->term_reason, f->term_reason_len);
TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time);
--f->retransmits;
}
break;
case PPP_FSM_REQSENT:
case PPP_FSM_ACKRCVD:
case PPP_FSM_ACKSENT:
if (f->retransmits <= 0) {
ppp_warn(("%s: timeout sending Config-Requests", PROTO_NAME(f)));
f->state = PPP_FSM_STOPPED;
if( (f->flags & OPT_PASSIVE) == 0 && f->callbacks->finished )
(*f->callbacks->finished)(f);
} else {
/* Retransmit the configure-request */
if (f->callbacks->retransmit)
(*f->callbacks->retransmit)(f);
fsm_sconfreq(f, 1); /* Re-send Configure-Request */
if( f->state == PPP_FSM_ACKRCVD )
f->state = PPP_FSM_REQSENT;
}
break;
default:
FSMDEBUG(("%s: Timeout event in state %d!", PROTO_NAME(f), f->state));
/* no break */
}
}
/*
* fsm_input - Input packet.
*/
void fsm_input(fsm *f, u_char *inpacket, int l) {
u_char *inp;
u_char code, id;
int len;
/*
* Parse header (code, id and length).
* If packet too short, drop it.
*/
inp = inpacket;
if (l < HEADERLEN) {
FSMDEBUG(("fsm_input(%x): Rcvd short header.", f->protocol));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
GETSHORT(len, inp);
if (len < HEADERLEN) {
FSMDEBUG(("fsm_input(%x): Rcvd illegal length.", f->protocol));
return;
}
if (len > l) {
FSMDEBUG(("fsm_input(%x): Rcvd short packet.", f->protocol));
return;
}
len -= HEADERLEN; /* subtract header length */
if( f->state == PPP_FSM_INITIAL || f->state == PPP_FSM_STARTING ){
FSMDEBUG(("fsm_input(%x): Rcvd packet in state %d.",
f->protocol, f->state));
return;
}
/*
* Action depends on code.
*/
switch (code) {
case CONFREQ:
fsm_rconfreq(f, id, inp, len);
break;
case CONFACK:
fsm_rconfack(f, id, inp, len);
break;
case CONFNAK:
case CONFREJ:
fsm_rconfnakrej(f, code, id, inp, len);
break;
case TERMREQ:
fsm_rtermreq(f, id, inp, len);
break;
case TERMACK:
fsm_rtermack(f);
break;
case CODEREJ:
fsm_rcoderej(f, inp, len);
break;
default:
if( !f->callbacks->extcode
|| !(*f->callbacks->extcode)(f, code, id, inp, len) )
fsm_sdata(f, CODEREJ, ++f->id, inpacket, len + HEADERLEN);
break;
}
}
/*
* fsm_rconfreq - Receive Configure-Request.
*/
static void fsm_rconfreq(fsm *f, u_char id, u_char *inp, int len) {
int code, reject_if_disagree;
switch( f->state ){
case PPP_FSM_CLOSED:
/* Go away, we're closed */
fsm_sdata(f, TERMACK, id, NULL, 0);
return;
case PPP_FSM_CLOSING:
case PPP_FSM_STOPPING:
return;
case PPP_FSM_OPENED:
/* Go down and restart negotiation */
if( f->callbacks->down )
(*f->callbacks->down)(f); /* Inform upper layers */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = PPP_FSM_REQSENT;
break;
case PPP_FSM_STOPPED:
/* Negotiation started by our peer */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = PPP_FSM_REQSENT;
break;
default:
break;
}
/*
* Pass the requested configuration options
* to protocol-specific code for checking.
*/
if (f->callbacks->reqci){ /* Check CI */
reject_if_disagree = (f->nakloops >= f->maxnakloops);
code = (*f->callbacks->reqci)(f, inp, &len, reject_if_disagree);
} else if (len)
code = CONFREJ; /* Reject all CI */
else
code = CONFACK;
/* send the Ack, Nak or Rej to the peer */
fsm_sdata(f, code, id, inp, len);
if (code == CONFACK) {
if (f->state == PPP_FSM_ACKRCVD) {
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = PPP_FSM_OPENED;
if (f->callbacks->up)
(*f->callbacks->up)(f); /* Inform upper layers */
} else
f->state = PPP_FSM_ACKSENT;
f->nakloops = 0;
} else {
/* we sent CONFACK or CONFREJ */
if (f->state != PPP_FSM_ACKRCVD)
f->state = PPP_FSM_REQSENT;
if( code == CONFNAK )
++f->nakloops;
}
}
/*
* fsm_rconfack - Receive Configure-Ack.
*/
static void fsm_rconfack(fsm *f, int id, u_char *inp, int len) {
ppp_pcb *pcb = f->pcb;
if (id != f->reqid || f->seen_ack) /* Expected id? */
return; /* Nope, toss... */
if( !(f->callbacks->ackci? (*f->callbacks->ackci)(f, inp, len):
(len == 0)) ){
/* Ack is bad - ignore it */
ppp_error(("Received bad configure-ack: %P", inp, len));
return;
}
f->seen_ack = 1;
f->rnakloops = 0;
switch (f->state) {
case PPP_FSM_CLOSED:
case PPP_FSM_STOPPED:
fsm_sdata(f, TERMACK, id, NULL, 0);
break;
case PPP_FSM_REQSENT:
f->state = PPP_FSM_ACKRCVD;
f->retransmits = pcb->settings.fsm_max_conf_req_transmits;
break;
case PPP_FSM_ACKRCVD:
/* Huh? an extra valid Ack? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = PPP_FSM_REQSENT;
break;
case PPP_FSM_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
f->state = PPP_FSM_OPENED;
f->retransmits = pcb->settings.fsm_max_conf_req_transmits;
if (f->callbacks->up)
(*f->callbacks->up)(f); /* Inform upper layers */
break;
case PPP_FSM_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down)
(*f->callbacks->down)(f); /* Inform upper layers */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = PPP_FSM_REQSENT;
break;
default:
break;
}
}
/*
* fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject.
*/
static void fsm_rconfnakrej(fsm *f, int code, int id, u_char *inp, int len) {
int ret;
int treat_as_reject;
if (id != f->reqid || f->seen_ack) /* Expected id? */
return; /* Nope, toss... */
if (code == CONFNAK) {
++f->rnakloops;
treat_as_reject = (f->rnakloops >= f->maxnakloops);
if (f->callbacks->nakci == NULL
|| !(ret = f->callbacks->nakci(f, inp, len, treat_as_reject))) {
ppp_error(("Received bad configure-nak: %P", inp, len));
return;
}
} else {
f->rnakloops = 0;
if (f->callbacks->rejci == NULL
|| !(ret = f->callbacks->rejci(f, inp, len))) {
ppp_error(("Received bad configure-rej: %P", inp, len));
return;
}
}
f->seen_ack = 1;
switch (f->state) {
case PPP_FSM_CLOSED:
case PPP_FSM_STOPPED:
fsm_sdata(f, TERMACK, id, NULL, 0);
break;
case PPP_FSM_REQSENT:
case PPP_FSM_ACKSENT:
/* They didn't agree to what we wanted - try another request */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
if (ret < 0)
f->state = PPP_FSM_STOPPED; /* kludge for stopping CCP */
else
fsm_sconfreq(f, 0); /* Send Configure-Request */
break;
case PPP_FSM_ACKRCVD:
/* Got a Nak/reject when we had already had an Ack?? oh well... */
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
fsm_sconfreq(f, 0);
f->state = PPP_FSM_REQSENT;
break;
case PPP_FSM_OPENED:
/* Go down and restart negotiation */
if (f->callbacks->down)
(*f->callbacks->down)(f); /* Inform upper layers */
fsm_sconfreq(f, 0); /* Send initial Configure-Request */
f->state = PPP_FSM_REQSENT;
break;
default:
break;
}
}
/*
* fsm_rtermreq - Receive Terminate-Req.
*/
static void fsm_rtermreq(fsm *f, int id, u_char *p, int len) {
ppp_pcb *pcb = f->pcb;
switch (f->state) {
case PPP_FSM_ACKRCVD:
case PPP_FSM_ACKSENT:
f->state = PPP_FSM_REQSENT; /* Start over but keep trying */
break;
case PPP_FSM_OPENED:
if (len > 0) {
ppp_info(("%s terminated by peer (%0.*v)", PROTO_NAME(f), len, p));
} else
ppp_info(("%s terminated by peer", PROTO_NAME(f)));
f->retransmits = 0;
f->state = PPP_FSM_STOPPING;
if (f->callbacks->down)
(*f->callbacks->down)(f); /* Inform upper layers */
TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time);
break;
default:
break;
}
fsm_sdata(f, TERMACK, id, NULL, 0);
}
/*
* fsm_rtermack - Receive Terminate-Ack.
*/
static void fsm_rtermack(fsm *f) {
switch (f->state) {
case PPP_FSM_CLOSING:
UNTIMEOUT(fsm_timeout, f);
f->state = PPP_FSM_CLOSED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
break;
case PPP_FSM_STOPPING:
UNTIMEOUT(fsm_timeout, f);
f->state = PPP_FSM_STOPPED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
break;
case PPP_FSM_ACKRCVD:
f->state = PPP_FSM_REQSENT;
break;
case PPP_FSM_OPENED:
if (f->callbacks->down)
(*f->callbacks->down)(f); /* Inform upper layers */
fsm_sconfreq(f, 0);
f->state = PPP_FSM_REQSENT;
break;
default:
break;
}
}
/*
* fsm_rcoderej - Receive an Code-Reject.
*/
static void fsm_rcoderej(fsm *f, u_char *inp, int len) {
u_char code, id;
if (len < HEADERLEN) {
FSMDEBUG(("fsm_rcoderej: Rcvd short Code-Reject packet!"));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
ppp_warn(("%s: Rcvd Code-Reject for code %d, id %d", PROTO_NAME(f), code, id));
if( f->state == PPP_FSM_ACKRCVD )
f->state = PPP_FSM_REQSENT;
}
/*
* fsm_protreject - Peer doesn't speak this protocol.
*
* Treat this as a catastrophic error (RXJ-).
*/
void fsm_protreject(fsm *f) {
switch( f->state ){
case PPP_FSM_CLOSING:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
/* no break */
case PPP_FSM_CLOSED:
f->state = PPP_FSM_CLOSED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
break;
case PPP_FSM_STOPPING:
case PPP_FSM_REQSENT:
case PPP_FSM_ACKRCVD:
case PPP_FSM_ACKSENT:
UNTIMEOUT(fsm_timeout, f); /* Cancel timeout */
/* fall through */
/* no break */
case PPP_FSM_STOPPED:
f->state = PPP_FSM_STOPPED;
if( f->callbacks->finished )
(*f->callbacks->finished)(f);
break;
case PPP_FSM_OPENED:
terminate_layer(f, PPP_FSM_STOPPING);
break;
default:
FSMDEBUG(("%s: Protocol-reject event in state %d!",
PROTO_NAME(f), f->state));
/* no break */
}
}
/*
* fsm_sconfreq - Send a Configure-Request.
*/
static void fsm_sconfreq(fsm *f, int retransmit) {
ppp_pcb *pcb = f->pcb;
struct pbuf *p;
u_char *outp;
int cilen;
if( f->state != PPP_FSM_REQSENT && f->state != PPP_FSM_ACKRCVD && f->state != PPP_FSM_ACKSENT ){
/* Not currently negotiating - reset options */
if( f->callbacks->resetci )
(*f->callbacks->resetci)(f);
f->nakloops = 0;
f->rnakloops = 0;
}
if( !retransmit ){
/* New request - reset retransmission counter, use new ID */
f->retransmits = pcb->settings.fsm_max_conf_req_transmits;
f->reqid = ++f->id;
}
f->seen_ack = 0;
/*
* Make up the request packet
*/
if( f->callbacks->cilen && f->callbacks->addci ){
cilen = (*f->callbacks->cilen)(f);
if( cilen > pcb->peer_mru - HEADERLEN )
cilen = pcb->peer_mru - HEADERLEN;
} else
cilen = 0;
p = pbuf_alloc(PBUF_RAW, (u16_t)(cilen + HEADERLEN + PPP_HDRLEN), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
/* send the request to our peer */
outp = (u_char*)p->payload;
MAKEHEADER(outp, f->protocol);
PUTCHAR(CONFREQ, outp);
PUTCHAR(f->reqid, outp);
PUTSHORT(cilen + HEADERLEN, outp);
if (cilen != 0) {
(*f->callbacks->addci)(f, outp, &cilen);
LWIP_ASSERT("cilen == p->len - HEADERLEN - PPP_HDRLEN", cilen == p->len - HEADERLEN - PPP_HDRLEN);
}
ppp_write(pcb, p);
/* start the retransmit timer */
--f->retransmits;
TIMEOUT(fsm_timeout, f, pcb->settings.fsm_timeout_time);
}
/*
* fsm_sdata - Send some data.
*
* Used for all packets sent to our peer by this module.
*/
void fsm_sdata(fsm *f, u_char code, u_char id, const u_char *data, int datalen) {
ppp_pcb *pcb = f->pcb;
struct pbuf *p;
u_char *outp;
int outlen;
/* Adjust length to be smaller than MTU */
if (datalen > pcb->peer_mru - HEADERLEN)
datalen = pcb->peer_mru - HEADERLEN;
outlen = datalen + HEADERLEN;
p = pbuf_alloc(PBUF_RAW, (u16_t)(outlen + PPP_HDRLEN), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
outp = (u_char*)p->payload;
if (datalen) /* && data != outp + PPP_HDRLEN + HEADERLEN) -- was only for fsm_sconfreq() */
MEMCPY(outp + PPP_HDRLEN + HEADERLEN, data, datalen);
MAKEHEADER(outp, f->protocol);
PUTCHAR(code, outp);
PUTCHAR(id, outp);
PUTSHORT(outlen, outp);
ppp_write(pcb, p);
}
#endif /* PPP_SUPPORT */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,286 +0,0 @@
/*
* magic.c - PPP Magic Number routines.
*
* Copyright (c) 1984-2000 Carnegie Mellon University. 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 "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* tech-transfer@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*****************************************************************************
* randm.c - Random number generator program file.
*
* Copyright (c) 2003 by Marc Boucher, Services Informatiques (MBSI) inc.
* Copyright (c) 1998 by Global Election Systems Inc.
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice and the following disclaimer are included verbatim in any
* distributions. No written agreement, license, or royalty fee is required
* for any of the authorized uses.
*
* THIS SOFTWARE IS PROVIDED BY THE 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 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.
*
******************************************************************************
* REVISION HISTORY
*
* 03-01-01 Marc Boucher <marc@mbsi.ca>
* Ported to lwIP.
* 98-06-03 Guy Lancaster <lancasterg@acm.org>, Global Election Systems Inc.
* Extracted from avos.
*****************************************************************************/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/magic.h"
#if PPP_MD5_RANDM /* Using MD5 for better randomness if enabled */
#include "netif/ppp/pppcrypt.h"
#define MD5_HASH_SIZE 16
static char magic_randpool[MD5_HASH_SIZE]; /* Pool of randomness. */
static long magic_randcount; /* Pseudo-random incrementer */
static u32_t magic_randomseed; /* Seed used for random number generation. */
/*
* Churn the randomness pool on a random event. Call this early and often
* on random and semi-random system events to build randomness in time for
* usage. For randomly timed events, pass a null pointer and a zero length
* and this will use the system timer and other sources to add randomness.
* If new random data is available, pass a pointer to that and it will be
* included.
*
* Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427
*/
static void magic_churnrand(char *rand_data, u32_t rand_len) {
lwip_md5_context md5_ctx;
/* LWIP_DEBUGF(LOG_INFO, ("magic_churnrand: %u@%P\n", rand_len, rand_data)); */
lwip_md5_init(&md5_ctx);
lwip_md5_starts(&md5_ctx);
lwip_md5_update(&md5_ctx, (u_char *)magic_randpool, sizeof(magic_randpool));
if (rand_data) {
lwip_md5_update(&md5_ctx, (u_char *)rand_data, rand_len);
} else {
struct {
/* INCLUDE fields for any system sources of randomness */
u32_t jiffies;
#ifdef LWIP_RAND
u32_t rand;
#endif /* LWIP_RAND */
} sys_data;
/* Load sys_data fields here. */
magic_randomseed += sys_jiffies();
sys_data.jiffies = magic_randomseed;
#ifdef LWIP_RAND
sys_data.rand = LWIP_RAND();
#endif /* LWIP_RAND */
lwip_md5_update(&md5_ctx, (u_char *)&sys_data, sizeof(sys_data));
}
lwip_md5_finish(&md5_ctx, (u_char *)magic_randpool);
lwip_md5_free(&md5_ctx);
/* LWIP_DEBUGF(LOG_INFO, ("magic_churnrand: -> 0\n")); */
}
/*
* Initialize the random number generator.
*/
void magic_init(void) {
magic_churnrand(NULL, 0);
}
/*
* Randomize our random seed value.
*/
void magic_randomize(void) {
magic_churnrand(NULL, 0);
}
/*
* Fill a buffer with random bytes.
*
* Use the random pool to generate random data. This degrades to pseudo
* random when used faster than randomness is supplied using magic_churnrand().
* Note: It's important that there be sufficient randomness in magic_randpool
* before this is called for otherwise the range of the result may be
* narrow enough to make a search feasible.
*
* Ref: Applied Cryptography 2nd Ed. by Bruce Schneier p. 427
*
* XXX Why does he not just call magic_churnrand() for each block? Probably
* so that you don't ever publish the seed which could possibly help
* predict future values.
* XXX Why don't we preserve md5 between blocks and just update it with
* magic_randcount each time? Probably there is a weakness but I wish that
* it was documented.
*/
void magic_random_bytes(unsigned char *buf, u32_t buf_len) {
lwip_md5_context md5_ctx;
u_char tmp[MD5_HASH_SIZE];
u32_t n;
while (buf_len > 0) {
lwip_md5_init(&md5_ctx);
lwip_md5_starts(&md5_ctx);
lwip_md5_update(&md5_ctx, (u_char *)magic_randpool, sizeof(magic_randpool));
lwip_md5_update(&md5_ctx, (u_char *)&magic_randcount, sizeof(magic_randcount));
lwip_md5_finish(&md5_ctx, tmp);
lwip_md5_free(&md5_ctx);
magic_randcount++;
n = LWIP_MIN(buf_len, MD5_HASH_SIZE);
MEMCPY(buf, tmp, n);
buf += n;
buf_len -= n;
}
}
/*
* Return a new 32-bit random number.
*/
u32_t magic(void) {
u32_t new_rand;
magic_random_bytes((unsigned char *)&new_rand, sizeof(new_rand));
return new_rand;
}
#else /* PPP_MD5_RANDM */
#ifndef LWIP_RAND
static int magic_randomized; /* Set when truly randomized. */
#endif /* LWIP_RAND */
static u32_t magic_randomseed; /* Seed used for random number generation. */
/*
* Initialize the random number generator.
*
* Here we attempt to compute a random number seed but even if
* it isn't random, we'll randomize it later.
*
* The current method uses the jiffies counter. When this is
* invoked at startup the jiffies counter value may repeat
* after each boot. Thus we call it again on the first
* random event.
*
* If LWIP_RAND if available, we do not call srand() as we are
* not going to call rand().
*/
void magic_init(void) {
magic_randomseed += sys_jiffies();
#ifndef LWIP_RAND
/* Initialize the random number generator. */
srand((unsigned)magic_randomseed);
#endif /* LWIP_RAND */
}
/*
* Randomize our random seed value. Here we use the fact that
* this function is called at *truly random* times by the polling
* and network functions. Here we only get 16 bits of new random
* value but we use the previous value to randomize the other 16
* bits.
*/
void magic_randomize(void) {
#ifndef LWIP_RAND
if (!magic_randomized) {
magic_randomized = !0;
magic_init();
/* The initialization function also updates the seed. */
return;
}
#endif /* LWIP_RAND */
magic_randomseed += sys_jiffies();
}
/*
* Return a new 32-bit random number.
*
* Here we use the rand() function to supply a pseudo random
* number which we make truly random by combining it with our own
* seed which is randomized by truly random events.
* Thus the numbers will be truly random unless there have been no
* operator or network events in which case it will be pseudo random
* seeded by srand().
*
* Alternatively, use LWIP_RAND if available, but we do not assume
* it is returning 32 bits of random data because it is probably
* going to be defined to directly return the rand() value. For
* example, LCP magic numbers are 32-bit random values.
*/
u32_t magic(void) {
#ifdef LWIP_RAND
return (LWIP_RAND() << 16) + LWIP_RAND() + magic_randomseed;
#else /* LWIP_RAND */
return ((u32_t)rand() << 16) + (u32_t)rand() + magic_randomseed;
#endif /* LWIP_RAND */
}
/*
* Fill a buffer with random bytes.
*/
void magic_random_bytes(unsigned char *buf, u32_t buf_len) {
u32_t new_rand, n;
while (buf_len > 0) {
new_rand = magic();
n = LWIP_MIN(buf_len, sizeof(new_rand));
MEMCPY(buf, &new_rand, n);
buf += n;
buf_len -= n;
}
}
#endif /* PPP_MD5_RANDM */
/*
* Return a new random number between 0 and (2^pow)-1 included.
*/
u32_t magic_pow(u8_t pow) {
return magic() & ~(~0UL<<pow);
}
#endif /* PPP_SUPPORT */

View File

@ -1,412 +0,0 @@
/*
* mppe.c - interface MPPE to the PPP code.
*
* By Frank Cusack <fcusack@fcusack.com>.
* Copyright (c) 2002,2003,2004 Google, Inc.
* All rights reserved.
*
* License:
* Permission to use, copy, modify, and distribute this software and its
* documentation is hereby granted, provided that the above copyright
* notice appears in all copies. This software is provided without any
* warranty, express or implied.
*
* Changelog:
* 08/12/05 - Matt Domsch <Matt_Domsch@dell.com>
* Only need extra skb padding on transmit, not receive.
* 06/18/04 - Matt Domsch <Matt_Domsch@dell.com>, Oleg Makarenko <mole@quadra.ru>
* Use Linux kernel 2.6 arc4 and sha1 routines rather than
* providing our own.
* 2/15/04 - TS: added #include <version.h> and testing for Kernel
* version before using
* MOD_DEC_USAGE_COUNT/MOD_INC_USAGE_COUNT which are
* deprecated in 2.6
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && MPPE_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include <string.h>
#include "lwip/err.h"
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/ccp.h"
#include "netif/ppp/mppe.h"
#include "netif/ppp/pppdebug.h"
#include "netif/ppp/pppcrypt.h"
#define SHA1_SIGNATURE_SIZE 20
/* ppp_mppe_state.bits definitions */
#define MPPE_BIT_A 0x80 /* Encryption table were (re)inititalized */
#define MPPE_BIT_B 0x40 /* MPPC only (not implemented) */
#define MPPE_BIT_C 0x20 /* MPPC only (not implemented) */
#define MPPE_BIT_D 0x10 /* This is an encrypted frame */
#define MPPE_BIT_FLUSHED MPPE_BIT_A
#define MPPE_BIT_ENCRYPTED MPPE_BIT_D
#define MPPE_BITS(p) ((p)[0] & 0xf0)
#define MPPE_CCOUNT(p) ((((p)[0] & 0x0f) << 8) + (p)[1])
#define MPPE_CCOUNT_SPACE 0x1000 /* The size of the ccount space */
#define MPPE_OVHD 2 /* MPPE overhead/packet */
#define SANITY_MAX 1600 /* Max bogon factor we will tolerate */
/*
* Perform the MPPE rekey algorithm, from RFC 3078, sec. 7.3.
* Well, not what's written there, but rather what they meant.
*/
static void mppe_rekey(ppp_mppe_state * state, int initial_key)
{
lwip_sha1_context sha1_ctx;
u8_t sha1_digest[SHA1_SIGNATURE_SIZE];
/*
* Key Derivation, from RFC 3078, RFC 3079.
* Equivalent to Get_Key() for MS-CHAP as described in RFC 3079.
*/
lwip_sha1_init(&sha1_ctx);
lwip_sha1_starts(&sha1_ctx);
lwip_sha1_update(&sha1_ctx, state->master_key, state->keylen);
lwip_sha1_update(&sha1_ctx, mppe_sha1_pad1, SHA1_PAD_SIZE);
lwip_sha1_update(&sha1_ctx, state->session_key, state->keylen);
lwip_sha1_update(&sha1_ctx, mppe_sha1_pad2, SHA1_PAD_SIZE);
lwip_sha1_finish(&sha1_ctx, sha1_digest);
lwip_sha1_free(&sha1_ctx);
MEMCPY(state->session_key, sha1_digest, state->keylen);
if (!initial_key) {
lwip_arc4_init(&state->arc4);
lwip_arc4_setup(&state->arc4, sha1_digest, state->keylen);
lwip_arc4_crypt(&state->arc4, state->session_key, state->keylen);
lwip_arc4_free(&state->arc4);
}
if (state->keylen == 8) {
/* See RFC 3078 */
state->session_key[0] = 0xd1;
state->session_key[1] = 0x26;
state->session_key[2] = 0x9e;
}
lwip_arc4_init(&state->arc4);
lwip_arc4_setup(&state->arc4, state->session_key, state->keylen);
}
/*
* Set key, used by MSCHAP before mppe_init() is actually called by CCP so we
* don't have to keep multiple copies of keys.
*/
void mppe_set_key(ppp_pcb *pcb, ppp_mppe_state *state, u8_t *key) {
LWIP_UNUSED_ARG(pcb);
MEMCPY(state->master_key, key, MPPE_MAX_KEY_LEN);
}
/*
* Initialize (de)compressor state.
*/
void
mppe_init(ppp_pcb *pcb, ppp_mppe_state *state, u8_t options)
{
#if PPP_DEBUG
const u8_t *debugstr = (const u8_t*)"mppe_comp_init";
if (&pcb->mppe_decomp == state) {
debugstr = (const u8_t*)"mppe_decomp_init";
}
#endif /* PPP_DEBUG */
/* Save keys. */
MEMCPY(state->session_key, state->master_key, sizeof(state->master_key));
if (options & MPPE_OPT_128)
state->keylen = 16;
else if (options & MPPE_OPT_40)
state->keylen = 8;
else {
PPPDEBUG(LOG_DEBUG, ("%s[%d]: unknown key length\n", debugstr,
pcb->netif->num));
lcp_close(pcb, "MPPE required but peer negotiation failed");
return;
}
if (options & MPPE_OPT_STATEFUL)
state->stateful = 1;
/* Generate the initial session key. */
mppe_rekey(state, 1);
#if PPP_DEBUG
{
int i;
char mkey[sizeof(state->master_key) * 2 + 1];
char skey[sizeof(state->session_key) * 2 + 1];
PPPDEBUG(LOG_DEBUG, ("%s[%d]: initialized with %d-bit %s mode\n",
debugstr, pcb->netif->num, (state->keylen == 16) ? 128 : 40,
(state->stateful) ? "stateful" : "stateless"));
for (i = 0; i < (int)sizeof(state->master_key); i++)
sprintf(mkey + i * 2, "%02x", state->master_key[i]);
for (i = 0; i < (int)sizeof(state->session_key); i++)
sprintf(skey + i * 2, "%02x", state->session_key[i]);
PPPDEBUG(LOG_DEBUG,
("%s[%d]: keys: master: %s initial session: %s\n",
debugstr, pcb->netif->num, mkey, skey));
}
#endif /* PPP_DEBUG */
/*
* Initialize the coherency count. The initial value is not specified
* in RFC 3078, but we can make a reasonable assumption that it will
* start at 0. Setting it to the max here makes the comp/decomp code
* do the right thing (determined through experiment).
*/
state->ccount = MPPE_CCOUNT_SPACE - 1;
/*
* Note that even though we have initialized the key table, we don't
* set the FLUSHED bit. This is contrary to RFC 3078, sec. 3.1.
*/
state->bits = MPPE_BIT_ENCRYPTED;
}
/*
* We received a CCP Reset-Request (actually, we are sending a Reset-Ack),
* tell the compressor to rekey. Note that we MUST NOT rekey for
* every CCP Reset-Request; we only rekey on the next xmit packet.
* We might get multiple CCP Reset-Requests if our CCP Reset-Ack is lost.
* So, rekeying for every CCP Reset-Request is broken as the peer will not
* know how many times we've rekeyed. (If we rekey and THEN get another
* CCP Reset-Request, we must rekey again.)
*/
void mppe_comp_reset(ppp_pcb *pcb, ppp_mppe_state *state)
{
LWIP_UNUSED_ARG(pcb);
state->bits |= MPPE_BIT_FLUSHED;
}
/*
* Compress (encrypt) a packet.
* It's strange to call this a compressor, since the output is always
* MPPE_OVHD + 2 bytes larger than the input.
*/
err_t
mppe_compress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb, u16_t protocol)
{
struct pbuf *n, *np;
u8_t *pl;
err_t err;
LWIP_UNUSED_ARG(pcb);
/* TCP stack requires that we don't change the packet payload, therefore we copy
* the whole packet before encryption.
*/
np = pbuf_alloc(PBUF_RAW, MPPE_OVHD + sizeof(protocol) + (*pb)->tot_len, PBUF_RAM);
if (!np) {
return ERR_MEM;
}
/* Hide MPPE header + protocol */
pbuf_remove_header(np, MPPE_OVHD + sizeof(protocol));
if ((err = pbuf_copy(np, *pb)) != ERR_OK) {
pbuf_free(np);
return err;
}
/* Reveal MPPE header + protocol */
pbuf_add_header(np, MPPE_OVHD + sizeof(protocol));
*pb = np;
pl = (u8_t*)np->payload;
state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE;
PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: ccount %d\n", pcb->netif->num, state->ccount));
/* FIXME: use PUT* macros */
pl[0] = state->ccount>>8;
pl[1] = state->ccount;
if (!state->stateful || /* stateless mode */
((state->ccount & 0xff) == 0xff) || /* "flag" packet */
(state->bits & MPPE_BIT_FLUSHED)) { /* CCP Reset-Request */
/* We must rekey */
if (state->stateful) {
PPPDEBUG(LOG_DEBUG, ("mppe_compress[%d]: rekeying\n", pcb->netif->num));
}
mppe_rekey(state, 0);
state->bits |= MPPE_BIT_FLUSHED;
}
pl[0] |= state->bits;
state->bits &= ~MPPE_BIT_FLUSHED; /* reset for next xmit */
pl += MPPE_OVHD;
/* Add protocol */
/* FIXME: add PFC support */
pl[0] = protocol >> 8;
pl[1] = protocol;
/* Hide MPPE header */
pbuf_remove_header(np, MPPE_OVHD);
/* Encrypt packet */
for (n = np; n != NULL; n = n->next) {
lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len);
if (n->tot_len == n->len) {
break;
}
}
/* Reveal MPPE header */
pbuf_add_header(np, MPPE_OVHD);
return ERR_OK;
}
/*
* We received a CCP Reset-Ack. Just ignore it.
*/
void mppe_decomp_reset(ppp_pcb *pcb, ppp_mppe_state *state)
{
LWIP_UNUSED_ARG(pcb);
LWIP_UNUSED_ARG(state);
return;
}
/*
* Decompress (decrypt) an MPPE packet.
*/
err_t
mppe_decompress(ppp_pcb *pcb, ppp_mppe_state *state, struct pbuf **pb)
{
struct pbuf *n0 = *pb, *n;
u8_t *pl;
u16_t ccount;
u8_t flushed;
/* MPPE Header */
if (n0->len < MPPE_OVHD) {
PPPDEBUG(LOG_DEBUG,
("mppe_decompress[%d]: short pkt (%d)\n",
pcb->netif->num, n0->len));
state->sanity_errors += 100;
goto sanity_error;
}
pl = (u8_t*)n0->payload;
flushed = MPPE_BITS(pl) & MPPE_BIT_FLUSHED;
ccount = MPPE_CCOUNT(pl);
PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: ccount %d\n",
pcb->netif->num, ccount));
/* sanity checks -- terminate with extreme prejudice */
if (!(MPPE_BITS(pl) & MPPE_BIT_ENCRYPTED)) {
PPPDEBUG(LOG_DEBUG,
("mppe_decompress[%d]: ENCRYPTED bit not set!\n",
pcb->netif->num));
state->sanity_errors += 100;
goto sanity_error;
}
if (!state->stateful && !flushed) {
PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set in "
"stateless mode!\n", pcb->netif->num));
state->sanity_errors += 100;
goto sanity_error;
}
if (state->stateful && ((ccount & 0xff) == 0xff) && !flushed) {
PPPDEBUG(LOG_DEBUG, ("mppe_decompress[%d]: FLUSHED bit not set on "
"flag packet!\n", pcb->netif->num));
state->sanity_errors += 100;
goto sanity_error;
}
/*
* Check the coherency count.
*/
if (!state->stateful) {
/* Discard late packet */
if ((ccount - state->ccount) % MPPE_CCOUNT_SPACE > MPPE_CCOUNT_SPACE / 2) {
state->sanity_errors++;
goto sanity_error;
}
/* RFC 3078, sec 8.1. Rekey for every packet. */
while (state->ccount != ccount) {
mppe_rekey(state, 0);
state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE;
}
} else {
/* RFC 3078, sec 8.2. */
if (!state->discard) {
/* normal state */
state->ccount = (state->ccount + 1) % MPPE_CCOUNT_SPACE;
if (ccount != state->ccount) {
/*
* (ccount > state->ccount)
* Packet loss detected, enter the discard state.
* Signal the peer to rekey (by sending a CCP Reset-Request).
*/
state->discard = 1;
ccp_resetrequest(pcb);
return ERR_BUF;
}
} else {
/* discard state */
if (!flushed) {
/* ccp.c will be silent (no additional CCP Reset-Requests). */
return ERR_BUF;
} else {
/* Rekey for every missed "flag" packet. */
while ((ccount & ~0xff) !=
(state->ccount & ~0xff)) {
mppe_rekey(state, 0);
state->ccount =
(state->ccount +
256) % MPPE_CCOUNT_SPACE;
}
/* reset */
state->discard = 0;
state->ccount = ccount;
/*
* Another problem with RFC 3078 here. It implies that the
* peer need not send a Reset-Ack packet. But RFC 1962
* requires it. Hopefully, M$ does send a Reset-Ack; even
* though it isn't required for MPPE synchronization, it is
* required to reset CCP state.
*/
}
}
if (flushed)
mppe_rekey(state, 0);
}
/* Hide MPPE header */
pbuf_remove_header(n0, MPPE_OVHD);
/* Decrypt the packet. */
for (n = n0; n != NULL; n = n->next) {
lwip_arc4_crypt(&state->arc4, (u8_t*)n->payload, n->len);
if (n->tot_len == n->len) {
break;
}
}
/* good packet credit */
state->sanity_errors >>= 1;
return ERR_OK;
sanity_error:
if (state->sanity_errors >= SANITY_MAX) {
/*
* Take LCP down if the peer is sending too many bogons.
* We don't want to do this for a single or just a few
* instances since it could just be due to packet corruption.
*/
lcp_close(pcb, "Too many MPPE errors");
}
return ERR_BUF;
}
#endif /* PPP_SUPPORT && MPPE_SUPPORT */

View File

@ -1,609 +0,0 @@
/*
* multilink.c - support routines for multilink.
*
* Copyright (c) 2000-2002 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && defined(HAVE_MULTILINK) /* don't build if not configured for use in lwipopts.h */
/* Multilink support
*
* Multilink uses Samba TDB (Trivial Database Library), which
* we cannot port, because it needs a filesystem.
*
* We have to choose between doing a memory-shared TDB-clone,
* or dropping multilink support at all.
*/
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <netdb.h>
#include <errno.h>
#include <signal.h>
#include <netinet/in.h>
#include <unistd.h>
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/fsm.h"
#include "netif/ppp/lcp.h"
#include "netif/ppp/tdb.h"
bool endpoint_specified; /* user gave explicit endpoint discriminator */
char *bundle_id; /* identifier for our bundle */
char *blinks_id; /* key for the list of links */
bool doing_multilink; /* multilink was enabled and agreed to */
bool multilink_master; /* we own the multilink bundle */
extern TDB_CONTEXT *pppdb;
extern char db_key[];
static void make_bundle_links (int append);
static void remove_bundle_link (void);
static void iterate_bundle_links (void (*func) (char *));
static int get_default_epdisc (struct epdisc *);
static int parse_num (char *str, const char *key, int *valp);
static int owns_unit (TDB_DATA pid, int unit);
#define set_ip_epdisc(ep, addr) do { \
ep->length = 4; \
ep->value[0] = addr >> 24; \
ep->value[1] = addr >> 16; \
ep->value[2] = addr >> 8; \
ep->value[3] = addr; \
} while (0)
#define LOCAL_IP_ADDR(addr) \
(((addr) & 0xff000000) == 0x0a000000 /* 10.x.x.x */ \
|| ((addr) & 0xfff00000) == 0xac100000 /* 172.16.x.x */ \
|| ((addr) & 0xffff0000) == 0xc0a80000) /* 192.168.x.x */
#define process_exists(n) (kill((n), 0) == 0 || errno != ESRCH)
void
mp_check_options()
{
lcp_options *wo = &lcp_wantoptions[0];
lcp_options *ao = &lcp_allowoptions[0];
doing_multilink = 0;
if (!multilink)
return;
/* if we're doing multilink, we have to negotiate MRRU */
if (!wo->neg_mrru) {
/* mrru not specified, default to mru */
wo->mrru = wo->mru;
wo->neg_mrru = 1;
}
ao->mrru = ao->mru;
ao->neg_mrru = 1;
if (!wo->neg_endpoint && !noendpoint) {
/* get a default endpoint value */
wo->neg_endpoint = get_default_epdisc(&wo->endpoint);
}
}
/*
* Make a new bundle or join us to an existing bundle
* if we are doing multilink.
*/
int
mp_join_bundle()
{
lcp_options *go = &lcp_gotoptions[0];
lcp_options *ho = &lcp_hisoptions[0];
lcp_options *ao = &lcp_allowoptions[0];
int unit, pppd_pid;
int l, mtu;
char *p;
TDB_DATA key, pid, rec;
if (doing_multilink) {
/* have previously joined a bundle */
if (!go->neg_mrru || !ho->neg_mrru) {
notice("oops, didn't get multilink on renegotiation");
lcp_close(pcb, "multilink required");
return 0;
}
/* XXX should check the peer_authname and ho->endpoint
are the same as previously */
return 0;
}
if (!go->neg_mrru || !ho->neg_mrru) {
/* not doing multilink */
if (go->neg_mrru)
notice("oops, multilink negotiated only for receive");
mtu = ho->neg_mru? ho->mru: PPP_DEFMRU;
if (mtu > ao->mru)
mtu = ao->mru;
if (demand) {
/* already have a bundle */
cfg_bundle(0, 0, 0, 0);
ppp_netif_set_mtu(pcb, mtu);
return 0;
}
make_new_bundle(0, 0, 0, 0);
set_ifunit(1);
ppp_netif_set_mtu(pcb, mtu);
return 0;
}
doing_multilink = 1;
/*
* Find the appropriate bundle or join a new one.
* First we make up a name for the bundle.
* The length estimate is worst-case assuming every
* character has to be quoted.
*/
l = 4 * strlen(peer_authname) + 10;
if (ho->neg_endpoint)
l += 3 * ho->endpoint.length + 8;
if (bundle_name)
l += 3 * strlen(bundle_name) + 2;
bundle_id = malloc(l);
if (bundle_id == 0)
novm("bundle identifier");
p = bundle_id;
p += slprintf(p, l-1, "BUNDLE=\"%q\"", peer_authname);
if (ho->neg_endpoint || bundle_name)
*p++ = '/';
if (ho->neg_endpoint)
p += slprintf(p, bundle_id+l-p, "%s",
epdisc_to_str(&ho->endpoint));
if (bundle_name)
p += slprintf(p, bundle_id+l-p, "/%v", bundle_name);
/* Make the key for the list of links belonging to the bundle */
l = p - bundle_id;
blinks_id = malloc(l + 7);
if (blinks_id == NULL)
novm("bundle links key");
slprintf(blinks_id, l + 7, "BUNDLE_LINKS=%s", bundle_id + 7);
/*
* For demand mode, we only need to configure the bundle
* and attach the link.
*/
mtu = LWIP_MIN(ho->mrru, ao->mru);
if (demand) {
cfg_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf);
ppp_netif_set_mtu(pcb, mtu);
script_setenv("BUNDLE", bundle_id + 7, 1);
return 0;
}
/*
* Check if the bundle ID is already in the database.
*/
unit = -1;
lock_db();
key.dptr = bundle_id;
key.dsize = p - bundle_id;
pid = tdb_fetch(pppdb, key);
if (pid.dptr != NULL) {
/* bundle ID exists, see if the pppd record exists */
rec = tdb_fetch(pppdb, pid);
if (rec.dptr != NULL && rec.dsize > 0) {
/* make sure the string is null-terminated */
rec.dptr[rec.dsize-1] = 0;
/* parse the interface number */
parse_num(rec.dptr, "IFNAME=ppp", &unit);
/* check the pid value */
if (!parse_num(rec.dptr, "PPPD_PID=", &pppd_pid)
|| !process_exists(pppd_pid)
|| !owns_unit(pid, unit))
unit = -1;
free(rec.dptr);
}
free(pid.dptr);
}
if (unit >= 0) {
/* attach to existing unit */
if (bundle_attach(unit)) {
set_ifunit(0);
script_setenv("BUNDLE", bundle_id + 7, 0);
make_bundle_links(1);
unlock_db();
info("Link attached to %s", ifname);
return 1;
}
/* attach failed because bundle doesn't exist */
}
/* we have to make a new bundle */
make_new_bundle(go->mrru, ho->mrru, go->neg_ssnhf, ho->neg_ssnhf);
set_ifunit(1);
ppp_netif_set_mtu(pcb, mtu);
script_setenv("BUNDLE", bundle_id + 7, 1);
make_bundle_links(pcb);
unlock_db();
info("New bundle %s created", ifname);
multilink_master = 1;
return 0;
}
void mp_exit_bundle()
{
lock_db();
remove_bundle_link();
unlock_db();
}
static void sendhup(char *str)
{
int pid;
if (parse_num(str, "PPPD_PID=", &pid) && pid != getpid()) {
if (debug)
dbglog("sending SIGHUP to process %d", pid);
kill(pid, SIGHUP);
}
}
void mp_bundle_terminated()
{
TDB_DATA key;
bundle_terminating = 1;
upper_layers_down(pcb);
notice("Connection terminated.");
#if PPP_STATS_SUPPORT
print_link_stats();
#endif /* PPP_STATS_SUPPORT */
if (!demand) {
remove_pidfiles();
script_unsetenv("IFNAME");
}
lock_db();
destroy_bundle();
iterate_bundle_links(sendhup);
key.dptr = blinks_id;
key.dsize = strlen(blinks_id);
tdb_delete(pppdb, key);
unlock_db();
new_phase(PPP_PHASE_DEAD);
doing_multilink = 0;
multilink_master = 0;
}
static void make_bundle_links(int append)
{
TDB_DATA key, rec;
char *p;
char entry[32];
int l;
key.dptr = blinks_id;
key.dsize = strlen(blinks_id);
slprintf(entry, sizeof(entry), "%s;", db_key);
p = entry;
if (append) {
rec = tdb_fetch(pppdb, key);
if (rec.dptr != NULL && rec.dsize > 0) {
rec.dptr[rec.dsize-1] = 0;
if (strstr(rec.dptr, db_key) != NULL) {
/* already in there? strange */
warn("link entry already exists in tdb");
return;
}
l = rec.dsize + strlen(entry);
p = malloc(l);
if (p == NULL)
novm("bundle link list");
slprintf(p, l, "%s%s", rec.dptr, entry);
} else {
warn("bundle link list not found");
}
if (rec.dptr != NULL)
free(rec.dptr);
}
rec.dptr = p;
rec.dsize = strlen(p) + 1;
if (tdb_store(pppdb, key, rec, TDB_REPLACE))
error("couldn't %s bundle link list",
append? "update": "create");
if (p != entry)
free(p);
}
static void remove_bundle_link()
{
TDB_DATA key, rec;
char entry[32];
char *p, *q;
int l;
key.dptr = blinks_id;
key.dsize = strlen(blinks_id);
slprintf(entry, sizeof(entry), "%s;", db_key);
rec = tdb_fetch(pppdb, key);
if (rec.dptr == NULL || rec.dsize <= 0) {
if (rec.dptr != NULL)
free(rec.dptr);
return;
}
rec.dptr[rec.dsize-1] = 0;
p = strstr(rec.dptr, entry);
if (p != NULL) {
q = p + strlen(entry);
l = strlen(q) + 1;
memmove(p, q, l);
rec.dsize = p - rec.dptr + l;
if (tdb_store(pppdb, key, rec, TDB_REPLACE))
error("couldn't update bundle link list (removal)");
}
free(rec.dptr);
}
static void iterate_bundle_links(void (*func)(char *))
{
TDB_DATA key, rec, pp;
char *p, *q;
key.dptr = blinks_id;
key.dsize = strlen(blinks_id);
rec = tdb_fetch(pppdb, key);
if (rec.dptr == NULL || rec.dsize <= 0) {
error("bundle link list not found (iterating list)");
if (rec.dptr != NULL)
free(rec.dptr);
return;
}
p = rec.dptr;
p[rec.dsize-1] = 0;
while ((q = strchr(p, ';')) != NULL) {
*q = 0;
key.dptr = p;
key.dsize = q - p;
pp = tdb_fetch(pppdb, key);
if (pp.dptr != NULL && pp.dsize > 0) {
pp.dptr[pp.dsize-1] = 0;
func(pp.dptr);
}
if (pp.dptr != NULL)
free(pp.dptr);
p = q + 1;
}
free(rec.dptr);
}
static int
parse_num(str, key, valp)
char *str;
const char *key;
int *valp;
{
char *p, *endp;
int i;
p = strstr(str, key);
if (p != 0) {
p += strlen(key);
i = strtol(p, &endp, 10);
if (endp != p && (*endp == 0 || *endp == ';')) {
*valp = i;
return 1;
}
}
return 0;
}
/*
* Check whether the pppd identified by `key' still owns ppp unit `unit'.
*/
static int
owns_unit(key, unit)
TDB_DATA key;
int unit;
{
char ifkey[32];
TDB_DATA kd, vd;
int ret = 0;
slprintf(ifkey, sizeof(ifkey), "IFNAME=ppp%d", unit);
kd.dptr = ifkey;
kd.dsize = strlen(ifkey);
vd = tdb_fetch(pppdb, kd);
if (vd.dptr != NULL) {
ret = vd.dsize == key.dsize
&& memcmp(vd.dptr, key.dptr, vd.dsize) == 0;
free(vd.dptr);
}
return ret;
}
static int
get_default_epdisc(ep)
struct epdisc *ep;
{
char *p;
struct hostent *hp;
u32_t addr;
/* First try for an ethernet MAC address */
p = get_first_ethernet();
if (p != 0 && get_if_hwaddr(ep->value, p) >= 0) {
ep->class = EPD_MAC;
ep->length = 6;
return 1;
}
/* see if our hostname corresponds to a reasonable IP address */
hp = gethostbyname(hostname);
if (hp != NULL) {
addr = *(u32_t *)hp->h_addr;
if (!bad_ip_adrs(addr)) {
addr = lwip_ntohl(addr);
if (!LOCAL_IP_ADDR(addr)) {
ep->class = EPD_IP;
set_ip_epdisc(ep, addr);
return 1;
}
}
}
return 0;
}
/*
* epdisc_to_str - make a printable string from an endpoint discriminator.
*/
static char *endp_class_names[] = {
"null", "local", "IP", "MAC", "magic", "phone"
};
char *
epdisc_to_str(ep)
struct epdisc *ep;
{
static char str[MAX_ENDP_LEN*3+8];
u_char *p = ep->value;
int i, mask = 0;
char *q, c, c2;
if (ep->class == EPD_NULL && ep->length == 0)
return "null";
if (ep->class == EPD_IP && ep->length == 4) {
u32_t addr;
GETLONG(addr, p);
slprintf(str, sizeof(str), "IP:%I", lwip_htonl(addr));
return str;
}
c = ':';
c2 = '.';
if (ep->class == EPD_MAC && ep->length == 6)
c2 = ':';
else if (ep->class == EPD_MAGIC && (ep->length % 4) == 0)
mask = 3;
q = str;
if (ep->class <= EPD_PHONENUM)
q += slprintf(q, sizeof(str)-1, "%s",
endp_class_names[ep->class]);
else
q += slprintf(q, sizeof(str)-1, "%d", ep->class);
c = ':';
for (i = 0; i < ep->length && i < MAX_ENDP_LEN; ++i) {
if ((i & mask) == 0) {
*q++ = c;
c = c2;
}
q += slprintf(q, str + sizeof(str) - q, "%.2x", ep->value[i]);
}
return str;
}
static int hexc_val(int c)
{
if (c >= 'a')
return c - 'a' + 10;
if (c >= 'A')
return c - 'A' + 10;
return c - '0';
}
int
str_to_epdisc(ep, str)
struct epdisc *ep;
char *str;
{
int i, l;
char *p, *endp;
for (i = EPD_NULL; i <= EPD_PHONENUM; ++i) {
int sl = strlen(endp_class_names[i]);
if (strncasecmp(str, endp_class_names[i], sl) == 0) {
str += sl;
break;
}
}
if (i > EPD_PHONENUM) {
/* not a class name, try a decimal class number */
i = strtol(str, &endp, 10);
if (endp == str)
return 0; /* can't parse class number */
str = endp;
}
ep->class = i;
if (*str == 0) {
ep->length = 0;
return 1;
}
if (*str != ':' && *str != '.')
return 0;
++str;
if (i == EPD_IP) {
u32_t addr;
i = parse_dotted_ip(str, &addr);
if (i == 0 || str[i] != 0)
return 0;
set_ip_epdisc(ep, addr);
return 1;
}
if (i == EPD_MAC && get_if_hwaddr(ep->value, str) >= 0) {
ep->length = 6;
return 1;
}
p = str;
for (l = 0; l < MAX_ENDP_LEN; ++l) {
if (*str == 0)
break;
if (p <= str)
for (p = str; isxdigit(*p); ++p)
;
i = p - str;
if (i == 0)
return 0;
ep->value[l] = hexc_val(*str++);
if ((i & 1) == 0)
ep->value[l] = (ep->value[l] << 4) + hexc_val(*str++);
if (*str == ':' || *str == '.')
++str;
}
if (*str != 0 || (ep->class == EPD_MAC && l != 6))
return 0;
ep->length = l;
return 1;
}
#endif /* PPP_SUPPORT && HAVE_MULTILINK */

View File

@ -1,22 +0,0 @@
About PolarSSL files into lwIP PPP support
------------------------------------------
This folder contains some files fetched from the latest BSD release of
the PolarSSL project (PolarSSL 0.10.1-bsd) for ciphers and encryption
methods we need for lwIP PPP support.
The PolarSSL files were cleaned to contain only the necessary struct
fields and functions needed for lwIP.
The PolarSSL API was not changed at all, so if you are already using
PolarSSL you can choose to skip the compilation of the included PolarSSL
library into lwIP.
If you are not using the embedded copy you must include external
libraries into your arch/cc.h port file.
Beware of the stack requirements which can be a lot larger if you are not
using our cleaned PolarSSL library.
PolarSSL project website: http://polarssl.org/

View File

@ -1,101 +0,0 @@
/*
* An implementation of the ARCFOUR algorithm
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of PolarSSL or XySSL 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*/
/*
* The ARCFOUR algorithm was publicly disclosed on 94/09.
*
* http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_ARC4
#include "netif/ppp/polarssl/arc4.h"
/*
* ARC4 key schedule
*/
void arc4_setup( arc4_context *ctx, unsigned char *key, int keylen )
{
int i, j, k, a;
unsigned char *m;
ctx->x = 0;
ctx->y = 0;
m = ctx->m;
for( i = 0; i < 256; i++ )
m[i] = (unsigned char) i;
j = k = 0;
for( i = 0; i < 256; i++, k++ )
{
if( k >= keylen ) k = 0;
a = m[i];
j = ( j + a + key[k] ) & 0xFF;
m[i] = m[j];
m[j] = (unsigned char) a;
}
}
/*
* ARC4 cipher function
*/
void arc4_crypt( arc4_context *ctx, unsigned char *buf, int buflen )
{
int i, x, y, a, b;
unsigned char *m;
x = ctx->x;
y = ctx->y;
m = ctx->m;
for( i = 0; i < buflen; i++ )
{
x = ( x + 1 ) & 0xFF; a = m[x];
y = ( y + a ) & 0xFF; b = m[y];
m[x] = (unsigned char) b;
m[y] = (unsigned char) a;
buf[i] = (unsigned char)
( buf[i] ^ m[(unsigned char)( a + b )] );
}
ctx->x = x;
ctx->y = y;
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_DES */

View File

@ -1,422 +0,0 @@
/*
* FIPS-46-3 compliant Triple-DES implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of PolarSSL or XySSL 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*/
/*
* DES, on which TDES is based, was originally designed by Horst Feistel
* at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).
*
* http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_DES
#include "netif/ppp/polarssl/des.h"
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* Expanded DES S-boxes
*/
static const unsigned long SB1[64] =
{
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
static const unsigned long SB2[64] =
{
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
static const unsigned long SB3[64] =
{
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
static const unsigned long SB4[64] =
{
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
static const unsigned long SB5[64] =
{
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
static const unsigned long SB6[64] =
{
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
static const unsigned long SB7[64] =
{
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
static const unsigned long SB8[64] =
{
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/*
* PC1: left and right halves bit-swap
*/
static const unsigned long LHs[16] =
{
0x00000000, 0x00000001, 0x00000100, 0x00000101,
0x00010000, 0x00010001, 0x00010100, 0x00010101,
0x01000000, 0x01000001, 0x01000100, 0x01000101,
0x01010000, 0x01010001, 0x01010100, 0x01010101
};
static const unsigned long RHs[16] =
{
0x00000000, 0x01000000, 0x00010000, 0x01010000,
0x00000100, 0x01000100, 0x00010100, 0x01010100,
0x00000001, 0x01000001, 0x00010001, 0x01010001,
0x00000101, 0x01000101, 0x00010101, 0x01010101,
};
/*
* Initial Permutation macro
*/
#define DES_IP(X,Y) \
{ \
T = ((X >> 4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T << 4); \
T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16); \
T = ((Y >> 2) ^ X) & 0x33333333; X ^= T; Y ^= (T << 2); \
T = ((Y >> 8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T << 8); \
Y = ((Y << 1) | (Y >> 31)) & 0xFFFFFFFF; \
T = (X ^ Y) & 0xAAAAAAAA; Y ^= T; X ^= T; \
X = ((X << 1) | (X >> 31)) & 0xFFFFFFFF; \
}
/*
* Final Permutation macro
*/
#define DES_FP(X,Y) \
{ \
X = ((X << 31) | (X >> 1)) & 0xFFFFFFFF; \
T = (X ^ Y) & 0xAAAAAAAA; X ^= T; Y ^= T; \
Y = ((Y << 31) | (Y >> 1)) & 0xFFFFFFFF; \
T = ((Y >> 8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T << 8); \
T = ((Y >> 2) ^ X) & 0x33333333; X ^= T; Y ^= (T << 2); \
T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16); \
T = ((X >> 4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T << 4); \
}
/*
* DES round macro
*/
#define DES_ROUND(X,Y) \
{ \
T = *SK++ ^ X; \
Y ^= SB8[ (T ) & 0x3F ] ^ \
SB6[ (T >> 8) & 0x3F ] ^ \
SB4[ (T >> 16) & 0x3F ] ^ \
SB2[ (T >> 24) & 0x3F ]; \
\
T = *SK++ ^ ((X << 28) | (X >> 4)); \
Y ^= SB7[ (T ) & 0x3F ] ^ \
SB5[ (T >> 8) & 0x3F ] ^ \
SB3[ (T >> 16) & 0x3F ] ^ \
SB1[ (T >> 24) & 0x3F ]; \
}
#define SWAP(a,b) { unsigned long t = a; a = b; b = t; t = 0; }
static void des_setkey( unsigned long SK[32], unsigned char key[8] )
{
int i;
unsigned long X, Y, T;
GET_ULONG_BE( X, key, 0 );
GET_ULONG_BE( Y, key, 4 );
/*
* Permuted Choice 1
*/
T = ((Y >> 4) ^ X) & 0x0F0F0F0F; X ^= T; Y ^= (T << 4);
T = ((Y ) ^ X) & 0x10101010; X ^= T; Y ^= (T );
X = (LHs[ (X ) & 0xF] << 3) | (LHs[ (X >> 8) & 0xF ] << 2)
| (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ] )
| (LHs[ (X >> 5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6)
| (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4);
Y = (RHs[ (Y >> 1) & 0xF] << 3) | (RHs[ (Y >> 9) & 0xF ] << 2)
| (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ] )
| (RHs[ (Y >> 4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6)
| (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4);
X &= 0x0FFFFFFF;
Y &= 0x0FFFFFFF;
/*
* calculate subkeys
*/
for( i = 0; i < 16; i++ )
{
if( i < 2 || i == 8 || i == 15 )
{
X = ((X << 1) | (X >> 27)) & 0x0FFFFFFF;
Y = ((Y << 1) | (Y >> 27)) & 0x0FFFFFFF;
}
else
{
X = ((X << 2) | (X >> 26)) & 0x0FFFFFFF;
Y = ((Y << 2) | (Y >> 26)) & 0x0FFFFFFF;
}
*SK++ = ((X << 4) & 0x24000000) | ((X << 28) & 0x10000000)
| ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)
| ((X << 6) & 0x01000000) | ((X << 9) & 0x00200000)
| ((X >> 1) & 0x00100000) | ((X << 10) & 0x00040000)
| ((X << 2) & 0x00020000) | ((X >> 10) & 0x00010000)
| ((Y >> 13) & 0x00002000) | ((Y >> 4) & 0x00001000)
| ((Y << 6) & 0x00000800) | ((Y >> 1) & 0x00000400)
| ((Y >> 14) & 0x00000200) | ((Y ) & 0x00000100)
| ((Y >> 5) & 0x00000020) | ((Y >> 10) & 0x00000010)
| ((Y >> 3) & 0x00000008) | ((Y >> 18) & 0x00000004)
| ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);
*SK++ = ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)
| ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)
| ((X >> 2) & 0x02000000) | ((X << 1) & 0x01000000)
| ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)
| ((X << 3) & 0x00080000) | ((X >> 6) & 0x00040000)
| ((X << 15) & 0x00020000) | ((X >> 4) & 0x00010000)
| ((Y >> 2) & 0x00002000) | ((Y << 8) & 0x00001000)
| ((Y >> 14) & 0x00000808) | ((Y >> 9) & 0x00000400)
| ((Y ) & 0x00000200) | ((Y << 7) & 0x00000100)
| ((Y >> 7) & 0x00000020) | ((Y >> 3) & 0x00000011)
| ((Y << 2) & 0x00000004) | ((Y >> 21) & 0x00000002);
}
}
/*
* DES key schedule (56-bit, encryption)
*/
void des_setkey_enc( des_context *ctx, unsigned char key[8] )
{
des_setkey( ctx->sk, key );
}
/*
* DES key schedule (56-bit, decryption)
*/
void des_setkey_dec( des_context *ctx, unsigned char key[8] )
{
int i;
des_setkey( ctx->sk, key );
for( i = 0; i < 16; i += 2 )
{
SWAP( ctx->sk[i ], ctx->sk[30 - i] );
SWAP( ctx->sk[i + 1], ctx->sk[31 - i] );
}
}
/*
* DES-ECB block encryption/decryption
*/
void des_crypt_ecb( des_context *ctx,
const unsigned char input[8],
unsigned char output[8] )
{
int i;
unsigned long X, Y, T, *SK;
SK = ctx->sk;
GET_ULONG_BE( X, input, 0 );
GET_ULONG_BE( Y, input, 4 );
DES_IP( X, Y );
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
DES_FP( Y, X );
PUT_ULONG_BE( Y, output, 0 );
PUT_ULONG_BE( X, output, 4 );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_DES */

View File

@ -1,281 +0,0 @@
/*
* RFC 1186/1320 compliant MD4 implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of PolarSSL or XySSL 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*/
/*
* The MD4 algorithm was designed by Ron Rivest in 1990.
*
* http://www.ietf.org/rfc/rfc1186.txt
* http://www.ietf.org/rfc/rfc1320.txt
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4
#include "netif/ppp/polarssl/md4.h"
#include <string.h>
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_ULONG_LE
#define GET_ULONG_LE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] ) \
| ( (unsigned long) (b)[(i) + 1] << 8 ) \
| ( (unsigned long) (b)[(i) + 2] << 16 ) \
| ( (unsigned long) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_ULONG_LE
#define PUT_ULONG_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \
}
#endif
/*
* MD4 context setup
*/
void md4_starts( md4_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
}
static void md4_process( md4_context *ctx, const unsigned char data[64] )
{
unsigned long X[16], A, B, C, D;
GET_ULONG_LE( X[ 0], data, 0 );
GET_ULONG_LE( X[ 1], data, 4 );
GET_ULONG_LE( X[ 2], data, 8 );
GET_ULONG_LE( X[ 3], data, 12 );
GET_ULONG_LE( X[ 4], data, 16 );
GET_ULONG_LE( X[ 5], data, 20 );
GET_ULONG_LE( X[ 6], data, 24 );
GET_ULONG_LE( X[ 7], data, 28 );
GET_ULONG_LE( X[ 8], data, 32 );
GET_ULONG_LE( X[ 9], data, 36 );
GET_ULONG_LE( X[10], data, 40 );
GET_ULONG_LE( X[11], data, 44 );
GET_ULONG_LE( X[12], data, 48 );
GET_ULONG_LE( X[13], data, 52 );
GET_ULONG_LE( X[14], data, 56 );
GET_ULONG_LE( X[15], data, 60 );
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
#define F(x, y, z) ((x & y) | ((~x) & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 1], 7 );
P( C, D, A, B, X[ 2], 11 );
P( B, C, D, A, X[ 3], 19 );
P( A, B, C, D, X[ 4], 3 );
P( D, A, B, C, X[ 5], 7 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[ 7], 19 );
P( A, B, C, D, X[ 8], 3 );
P( D, A, B, C, X[ 9], 7 );
P( C, D, A, B, X[10], 11 );
P( B, C, D, A, X[11], 19 );
P( A, B, C, D, X[12], 3 );
P( D, A, B, C, X[13], 7 );
P( C, D, A, B, X[14], 11 );
P( B, C, D, A, X[15], 19 );
#undef P
#undef F
#define F(x,y,z) ((x & y) | (x & z) | (y & z))
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x5A827999; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 4], 5 );
P( C, D, A, B, X[ 8], 9 );
P( B, C, D, A, X[12], 13 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 5], 5 );
P( C, D, A, B, X[ 9], 9 );
P( B, C, D, A, X[13], 13 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[ 6], 5 );
P( C, D, A, B, X[10], 9 );
P( B, C, D, A, X[14], 13 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[ 7], 5 );
P( C, D, A, B, X[11], 9 );
P( B, C, D, A, X[15], 13 );
#undef P
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define P(a,b,c,d,x,s) { a += F(b,c,d) + x + 0x6ED9EBA1; a = S(a,s); }
P( A, B, C, D, X[ 0], 3 );
P( D, A, B, C, X[ 8], 9 );
P( C, D, A, B, X[ 4], 11 );
P( B, C, D, A, X[12], 15 );
P( A, B, C, D, X[ 2], 3 );
P( D, A, B, C, X[10], 9 );
P( C, D, A, B, X[ 6], 11 );
P( B, C, D, A, X[14], 15 );
P( A, B, C, D, X[ 1], 3 );
P( D, A, B, C, X[ 9], 9 );
P( C, D, A, B, X[ 5], 11 );
P( B, C, D, A, X[13], 15 );
P( A, B, C, D, X[ 3], 3 );
P( D, A, B, C, X[11], 9 );
P( C, D, A, B, X[ 7], 11 );
P( B, C, D, A, X[15], 15 );
#undef F
#undef P
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
}
/*
* MD4 process buffer
*/
void md4_update( md4_context *ctx, const unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
MEMCPY( (void *) (ctx->buffer + left),
input, fill );
md4_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
md4_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
MEMCPY( (void *) (ctx->buffer + left),
input, ilen );
}
}
static const unsigned char md4_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* MD4 final digest
*/
void md4_finish( md4_context *ctx, unsigned char output[16] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_LE( low, msglen, 0 );
PUT_ULONG_LE( high, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
md4_update( ctx, md4_padding, padn );
md4_update( ctx, msglen, 8 );
PUT_ULONG_LE( ctx->state[0], output, 0 );
PUT_ULONG_LE( ctx->state[1], output, 4 );
PUT_ULONG_LE( ctx->state[2], output, 8 );
PUT_ULONG_LE( ctx->state[3], output, 12 );
}
/*
* output = MD4( input buffer )
*/
void md4( unsigned char *input, int ilen, unsigned char output[16] )
{
md4_context ctx;
md4_starts( &ctx );
md4_update( &ctx, input, ilen );
md4_finish( &ctx, output );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD4 */

View File

@ -1,300 +0,0 @@
/*
* RFC 1321 compliant MD5 implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of PolarSSL or XySSL 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*/
/*
* The MD5 algorithm was designed by Ron Rivest in 1991.
*
* http://www.ietf.org/rfc/rfc1321.txt
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD5
#include "netif/ppp/polarssl/md5.h"
#include <string.h>
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_ULONG_LE
#define GET_ULONG_LE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] ) \
| ( (unsigned long) (b)[(i) + 1] << 8 ) \
| ( (unsigned long) (b)[(i) + 2] << 16 ) \
| ( (unsigned long) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_ULONG_LE
#define PUT_ULONG_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \
}
#endif
/*
* MD5 context setup
*/
void md5_starts( md5_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
}
static void md5_process( md5_context *ctx, const unsigned char data[64] )
{
unsigned long X[16], A, B, C, D;
GET_ULONG_LE( X[ 0], data, 0 );
GET_ULONG_LE( X[ 1], data, 4 );
GET_ULONG_LE( X[ 2], data, 8 );
GET_ULONG_LE( X[ 3], data, 12 );
GET_ULONG_LE( X[ 4], data, 16 );
GET_ULONG_LE( X[ 5], data, 20 );
GET_ULONG_LE( X[ 6], data, 24 );
GET_ULONG_LE( X[ 7], data, 28 );
GET_ULONG_LE( X[ 8], data, 32 );
GET_ULONG_LE( X[ 9], data, 36 );
GET_ULONG_LE( X[10], data, 40 );
GET_ULONG_LE( X[11], data, 44 );
GET_ULONG_LE( X[12], data, 48 );
GET_ULONG_LE( X[13], data, 52 );
GET_ULONG_LE( X[14], data, 56 );
GET_ULONG_LE( X[15], data, 60 );
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
#define P(a,b,c,d,k,s,t) \
{ \
a += F(b,c,d) + X[k] + t; a = S(a,s) + b; \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
#define F(x,y,z) (z ^ (x & (y ^ z)))
P( A, B, C, D, 0, 7, 0xD76AA478 );
P( D, A, B, C, 1, 12, 0xE8C7B756 );
P( C, D, A, B, 2, 17, 0x242070DB );
P( B, C, D, A, 3, 22, 0xC1BDCEEE );
P( A, B, C, D, 4, 7, 0xF57C0FAF );
P( D, A, B, C, 5, 12, 0x4787C62A );
P( C, D, A, B, 6, 17, 0xA8304613 );
P( B, C, D, A, 7, 22, 0xFD469501 );
P( A, B, C, D, 8, 7, 0x698098D8 );
P( D, A, B, C, 9, 12, 0x8B44F7AF );
P( C, D, A, B, 10, 17, 0xFFFF5BB1 );
P( B, C, D, A, 11, 22, 0x895CD7BE );
P( A, B, C, D, 12, 7, 0x6B901122 );
P( D, A, B, C, 13, 12, 0xFD987193 );
P( C, D, A, B, 14, 17, 0xA679438E );
P( B, C, D, A, 15, 22, 0x49B40821 );
#undef F
#define F(x,y,z) (y ^ (z & (x ^ y)))
P( A, B, C, D, 1, 5, 0xF61E2562 );
P( D, A, B, C, 6, 9, 0xC040B340 );
P( C, D, A, B, 11, 14, 0x265E5A51 );
P( B, C, D, A, 0, 20, 0xE9B6C7AA );
P( A, B, C, D, 5, 5, 0xD62F105D );
P( D, A, B, C, 10, 9, 0x02441453 );
P( C, D, A, B, 15, 14, 0xD8A1E681 );
P( B, C, D, A, 4, 20, 0xE7D3FBC8 );
P( A, B, C, D, 9, 5, 0x21E1CDE6 );
P( D, A, B, C, 14, 9, 0xC33707D6 );
P( C, D, A, B, 3, 14, 0xF4D50D87 );
P( B, C, D, A, 8, 20, 0x455A14ED );
P( A, B, C, D, 13, 5, 0xA9E3E905 );
P( D, A, B, C, 2, 9, 0xFCEFA3F8 );
P( C, D, A, B, 7, 14, 0x676F02D9 );
P( B, C, D, A, 12, 20, 0x8D2A4C8A );
#undef F
#define F(x,y,z) (x ^ y ^ z)
P( A, B, C, D, 5, 4, 0xFFFA3942 );
P( D, A, B, C, 8, 11, 0x8771F681 );
P( C, D, A, B, 11, 16, 0x6D9D6122 );
P( B, C, D, A, 14, 23, 0xFDE5380C );
P( A, B, C, D, 1, 4, 0xA4BEEA44 );
P( D, A, B, C, 4, 11, 0x4BDECFA9 );
P( C, D, A, B, 7, 16, 0xF6BB4B60 );
P( B, C, D, A, 10, 23, 0xBEBFBC70 );
P( A, B, C, D, 13, 4, 0x289B7EC6 );
P( D, A, B, C, 0, 11, 0xEAA127FA );
P( C, D, A, B, 3, 16, 0xD4EF3085 );
P( B, C, D, A, 6, 23, 0x04881D05 );
P( A, B, C, D, 9, 4, 0xD9D4D039 );
P( D, A, B, C, 12, 11, 0xE6DB99E5 );
P( C, D, A, B, 15, 16, 0x1FA27CF8 );
P( B, C, D, A, 2, 23, 0xC4AC5665 );
#undef F
#define F(x,y,z) (y ^ (x | ~z))
P( A, B, C, D, 0, 6, 0xF4292244 );
P( D, A, B, C, 7, 10, 0x432AFF97 );
P( C, D, A, B, 14, 15, 0xAB9423A7 );
P( B, C, D, A, 5, 21, 0xFC93A039 );
P( A, B, C, D, 12, 6, 0x655B59C3 );
P( D, A, B, C, 3, 10, 0x8F0CCC92 );
P( C, D, A, B, 10, 15, 0xFFEFF47D );
P( B, C, D, A, 1, 21, 0x85845DD1 );
P( A, B, C, D, 8, 6, 0x6FA87E4F );
P( D, A, B, C, 15, 10, 0xFE2CE6E0 );
P( C, D, A, B, 6, 15, 0xA3014314 );
P( B, C, D, A, 13, 21, 0x4E0811A1 );
P( A, B, C, D, 4, 6, 0xF7537E82 );
P( D, A, B, C, 11, 10, 0xBD3AF235 );
P( C, D, A, B, 2, 15, 0x2AD7D2BB );
P( B, C, D, A, 9, 21, 0xEB86D391 );
#undef F
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
}
/*
* MD5 process buffer
*/
void md5_update( md5_context *ctx, const unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
MEMCPY( (void *) (ctx->buffer + left),
input, fill );
md5_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
md5_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
MEMCPY( (void *) (ctx->buffer + left),
input, ilen );
}
}
static const unsigned char md5_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* MD5 final digest
*/
void md5_finish( md5_context *ctx, unsigned char output[16] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_LE( low, msglen, 0 );
PUT_ULONG_LE( high, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
md5_update( ctx, md5_padding, padn );
md5_update( ctx, msglen, 8 );
PUT_ULONG_LE( ctx->state[0], output, 0 );
PUT_ULONG_LE( ctx->state[1], output, 4 );
PUT_ULONG_LE( ctx->state[2], output, 8 );
PUT_ULONG_LE( ctx->state[3], output, 12 );
}
/*
* output = MD5( input buffer )
*/
void md5( unsigned char *input, int ilen, unsigned char output[16] )
{
md5_context ctx;
md5_starts( &ctx );
md5_update( &ctx, input, ilen );
md5_finish( &ctx, output );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_MD5 */

View File

@ -1,335 +0,0 @@
/*
* FIPS-180-1 compliant SHA-1 implementation
*
* Based on XySSL: Copyright (C) 2006-2008 Christophe Devine
*
* Copyright (C) 2009 Paul Bakker <polarssl_maintainer at polarssl dot org>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the names of PolarSSL or XySSL 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*/
/*
* The SHA-1 standard was published by NIST in 1993.
*
* http://www.itl.nist.gov/fipspubs/fip180-1.htm
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_SHA1
#include "netif/ppp/polarssl/sha1.h"
#include <string.h>
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_ULONG_BE
#define GET_ULONG_BE(n,b,i) \
{ \
(n) = ( (unsigned long) (b)[(i) ] << 24 ) \
| ( (unsigned long) (b)[(i) + 1] << 16 ) \
| ( (unsigned long) (b)[(i) + 2] << 8 ) \
| ( (unsigned long) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_ULONG_BE
#define PUT_ULONG_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* SHA-1 context setup
*/
void sha1_starts( sha1_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
}
static void sha1_process( sha1_context *ctx, const unsigned char data[64] )
{
unsigned long temp, W[16], A, B, C, D, E;
GET_ULONG_BE( W[ 0], data, 0 );
GET_ULONG_BE( W[ 1], data, 4 );
GET_ULONG_BE( W[ 2], data, 8 );
GET_ULONG_BE( W[ 3], data, 12 );
GET_ULONG_BE( W[ 4], data, 16 );
GET_ULONG_BE( W[ 5], data, 20 );
GET_ULONG_BE( W[ 6], data, 24 );
GET_ULONG_BE( W[ 7], data, 28 );
GET_ULONG_BE( W[ 8], data, 32 );
GET_ULONG_BE( W[ 9], data, 36 );
GET_ULONG_BE( W[10], data, 40 );
GET_ULONG_BE( W[11], data, 44 );
GET_ULONG_BE( W[12], data, 48 );
GET_ULONG_BE( W[13], data, 52 );
GET_ULONG_BE( W[14], data, 56 );
GET_ULONG_BE( W[15], data, 60 );
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
#define R(t) \
( \
temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \
W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \
( W[t & 0x0F] = S(temp,1) ) \
)
#define P(a,b,c,d,e,x) \
{ \
e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
E = ctx->state[4];
#define F(x,y,z) (z ^ (x & (y ^ z)))
#define K 0x5A827999
P( A, B, C, D, E, W[0] );
P( E, A, B, C, D, W[1] );
P( D, E, A, B, C, W[2] );
P( C, D, E, A, B, W[3] );
P( B, C, D, E, A, W[4] );
P( A, B, C, D, E, W[5] );
P( E, A, B, C, D, W[6] );
P( D, E, A, B, C, W[7] );
P( C, D, E, A, B, W[8] );
P( B, C, D, E, A, W[9] );
P( A, B, C, D, E, W[10] );
P( E, A, B, C, D, W[11] );
P( D, E, A, B, C, W[12] );
P( C, D, E, A, B, W[13] );
P( B, C, D, E, A, W[14] );
P( A, B, C, D, E, W[15] );
P( E, A, B, C, D, R(16) );
P( D, E, A, B, C, R(17) );
P( C, D, E, A, B, R(18) );
P( B, C, D, E, A, R(19) );
#undef K
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define K 0x6ED9EBA1
P( A, B, C, D, E, R(20) );
P( E, A, B, C, D, R(21) );
P( D, E, A, B, C, R(22) );
P( C, D, E, A, B, R(23) );
P( B, C, D, E, A, R(24) );
P( A, B, C, D, E, R(25) );
P( E, A, B, C, D, R(26) );
P( D, E, A, B, C, R(27) );
P( C, D, E, A, B, R(28) );
P( B, C, D, E, A, R(29) );
P( A, B, C, D, E, R(30) );
P( E, A, B, C, D, R(31) );
P( D, E, A, B, C, R(32) );
P( C, D, E, A, B, R(33) );
P( B, C, D, E, A, R(34) );
P( A, B, C, D, E, R(35) );
P( E, A, B, C, D, R(36) );
P( D, E, A, B, C, R(37) );
P( C, D, E, A, B, R(38) );
P( B, C, D, E, A, R(39) );
#undef K
#undef F
#define F(x,y,z) ((x & y) | (z & (x | y)))
#define K 0x8F1BBCDC
P( A, B, C, D, E, R(40) );
P( E, A, B, C, D, R(41) );
P( D, E, A, B, C, R(42) );
P( C, D, E, A, B, R(43) );
P( B, C, D, E, A, R(44) );
P( A, B, C, D, E, R(45) );
P( E, A, B, C, D, R(46) );
P( D, E, A, B, C, R(47) );
P( C, D, E, A, B, R(48) );
P( B, C, D, E, A, R(49) );
P( A, B, C, D, E, R(50) );
P( E, A, B, C, D, R(51) );
P( D, E, A, B, C, R(52) );
P( C, D, E, A, B, R(53) );
P( B, C, D, E, A, R(54) );
P( A, B, C, D, E, R(55) );
P( E, A, B, C, D, R(56) );
P( D, E, A, B, C, R(57) );
P( C, D, E, A, B, R(58) );
P( B, C, D, E, A, R(59) );
#undef K
#undef F
#define F(x,y,z) (x ^ y ^ z)
#define K 0xCA62C1D6
P( A, B, C, D, E, R(60) );
P( E, A, B, C, D, R(61) );
P( D, E, A, B, C, R(62) );
P( C, D, E, A, B, R(63) );
P( B, C, D, E, A, R(64) );
P( A, B, C, D, E, R(65) );
P( E, A, B, C, D, R(66) );
P( D, E, A, B, C, R(67) );
P( C, D, E, A, B, R(68) );
P( B, C, D, E, A, R(69) );
P( A, B, C, D, E, R(70) );
P( E, A, B, C, D, R(71) );
P( D, E, A, B, C, R(72) );
P( C, D, E, A, B, R(73) );
P( B, C, D, E, A, R(74) );
P( A, B, C, D, E, R(75) );
P( E, A, B, C, D, R(76) );
P( D, E, A, B, C, R(77) );
P( C, D, E, A, B, R(78) );
P( B, C, D, E, A, R(79) );
#undef K
#undef F
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
ctx->state[4] += E;
}
/*
* SHA-1 process buffer
*/
void sha1_update( sha1_context *ctx, const unsigned char *input, int ilen )
{
int fill;
unsigned long left;
if( ilen <= 0 )
return;
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (unsigned long) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
MEMCPY( (void *) (ctx->buffer + left),
input, fill );
sha1_process( ctx, ctx->buffer );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
sha1_process( ctx, input );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
MEMCPY( (void *) (ctx->buffer + left),
input, ilen );
}
}
static const unsigned char sha1_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* SHA-1 final digest
*/
void sha1_finish( sha1_context *ctx, unsigned char output[20] )
{
unsigned long last, padn;
unsigned long high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_ULONG_BE( high, msglen, 0 );
PUT_ULONG_BE( low, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
sha1_update( ctx, sha1_padding, padn );
sha1_update( ctx, msglen, 8 );
PUT_ULONG_BE( ctx->state[0], output, 0 );
PUT_ULONG_BE( ctx->state[1], output, 4 );
PUT_ULONG_BE( ctx->state[2], output, 8 );
PUT_ULONG_BE( ctx->state[3], output, 12 );
PUT_ULONG_BE( ctx->state[4], output, 16 );
}
/*
* output = SHA-1( input buffer )
*/
void sha1( unsigned char *input, int ilen, unsigned char output[20] )
{
sha1_context ctx;
sha1_starts( &ctx );
sha1_update( &ctx, input, ilen );
sha1_finish( &ctx, output );
}
#endif /* PPP_SUPPORT && LWIP_INCLUDED_POLARSSL_SHA1 */

File diff suppressed because it is too large Load Diff

View File

@ -1,427 +0,0 @@
/**
* @file
* Point To Point Protocol Sequential API module
*
*/
/*
* 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 "netif/ppp/ppp_opts.h"
#if LWIP_PPP_API /* don't build if not configured for use in lwipopts.h */
#include "netif/ppp/pppapi.h"
#include "lwip/priv/tcpip_priv.h"
#include "netif/ppp/pppoe.h"
#include "netif/ppp/pppol2tp.h"
#include "netif/ppp/pppos.h"
#if LWIP_MPU_COMPATIBLE
LWIP_MEMPOOL_DECLARE(PPPAPI_MSG, MEMP_NUM_PPP_API_MSG, sizeof(struct pppapi_msg), "PPPAPI_MSG")
#endif
#define PPPAPI_VAR_REF(name) API_VAR_REF(name)
#define PPPAPI_VAR_DECLARE(name) API_VAR_DECLARE(struct pppapi_msg, name)
#define PPPAPI_VAR_ALLOC(name) API_VAR_ALLOC_POOL(struct pppapi_msg, PPPAPI_MSG, name, ERR_MEM)
#define PPPAPI_VAR_ALLOC_RETURN_NULL(name) API_VAR_ALLOC_POOL(struct pppapi_msg, PPPAPI_MSG, name, NULL)
#define PPPAPI_VAR_FREE(name) API_VAR_FREE_POOL(PPPAPI_MSG, name)
/**
* Call ppp_set_default() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_set_default(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
ppp_set_default(msg->msg.ppp);
return ERR_OK;
}
/**
* Call ppp_set_default() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_set_default(ppp_pcb *pcb)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
err = tcpip_api_call(pppapi_do_ppp_set_default, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
#if PPP_NOTIFY_PHASE
/**
* Call ppp_set_notify_phase_callback() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_set_notify_phase_callback(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
ppp_set_notify_phase_callback(msg->msg.ppp, msg->msg.msg.setnotifyphasecb.notify_phase_cb);
return ERR_OK;
}
/**
* Call ppp_set_notify_phase_callback() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_set_notify_phase_callback(ppp_pcb *pcb, ppp_notify_phase_cb_fn notify_phase_cb)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
PPPAPI_VAR_REF(msg).msg.msg.setnotifyphasecb.notify_phase_cb = notify_phase_cb;
err = tcpip_api_call(pppapi_do_ppp_set_notify_phase_callback, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
#endif /* PPP_NOTIFY_PHASE */
#if PPPOS_SUPPORT
/**
* Call pppos_create() inside the tcpip_thread context.
*/
static err_t
pppapi_do_pppos_create(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
msg->msg.ppp = pppos_create(msg->msg.msg.serialcreate.pppif, msg->msg.msg.serialcreate.output_cb,
msg->msg.msg.serialcreate.link_status_cb, msg->msg.msg.serialcreate.ctx_cb);
return ERR_OK;
}
/**
* Call pppos_create() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
ppp_pcb*
pppapi_pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb,
ppp_link_status_cb_fn link_status_cb, void *ctx_cb)
{
ppp_pcb* result;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC_RETURN_NULL(msg);
PPPAPI_VAR_REF(msg).msg.ppp = NULL;
PPPAPI_VAR_REF(msg).msg.msg.serialcreate.pppif = pppif;
PPPAPI_VAR_REF(msg).msg.msg.serialcreate.output_cb = output_cb;
PPPAPI_VAR_REF(msg).msg.msg.serialcreate.link_status_cb = link_status_cb;
PPPAPI_VAR_REF(msg).msg.msg.serialcreate.ctx_cb = ctx_cb;
tcpip_api_call(pppapi_do_pppos_create, &PPPAPI_VAR_REF(msg).call);
result = PPPAPI_VAR_REF(msg).msg.ppp;
PPPAPI_VAR_FREE(msg);
return result;
}
#endif /* PPPOS_SUPPORT */
#if PPPOE_SUPPORT
/**
* Call pppoe_create() inside the tcpip_thread context.
*/
static err_t
pppapi_do_pppoe_create(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
msg->msg.ppp = pppoe_create(msg->msg.msg.ethernetcreate.pppif, msg->msg.msg.ethernetcreate.ethif,
msg->msg.msg.ethernetcreate.service_name, msg->msg.msg.ethernetcreate.concentrator_name,
msg->msg.msg.ethernetcreate.link_status_cb, msg->msg.msg.ethernetcreate.ctx_cb);
return ERR_OK;
}
/**
* Call pppoe_create() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
ppp_pcb*
pppapi_pppoe_create(struct netif *pppif, struct netif *ethif, const char *service_name,
const char *concentrator_name, ppp_link_status_cb_fn link_status_cb,
void *ctx_cb)
{
ppp_pcb* result;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC_RETURN_NULL(msg);
PPPAPI_VAR_REF(msg).msg.ppp = NULL;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.pppif = pppif;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.ethif = ethif;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.service_name = service_name;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.concentrator_name = concentrator_name;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.link_status_cb = link_status_cb;
PPPAPI_VAR_REF(msg).msg.msg.ethernetcreate.ctx_cb = ctx_cb;
tcpip_api_call(pppapi_do_pppoe_create, &PPPAPI_VAR_REF(msg).call);
result = PPPAPI_VAR_REF(msg).msg.ppp;
PPPAPI_VAR_FREE(msg);
return result;
}
#endif /* PPPOE_SUPPORT */
#if PPPOL2TP_SUPPORT
/**
* Call pppol2tp_create() inside the tcpip_thread context.
*/
static err_t
pppapi_do_pppol2tp_create(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
msg->msg.ppp = pppol2tp_create(msg->msg.msg.l2tpcreate.pppif,
msg->msg.msg.l2tpcreate.netif, API_EXPR_REF(msg->msg.msg.l2tpcreate.ipaddr), msg->msg.msg.l2tpcreate.port,
#if PPPOL2TP_AUTH_SUPPORT
msg->msg.msg.l2tpcreate.secret,
msg->msg.msg.l2tpcreate.secret_len,
#else /* PPPOL2TP_AUTH_SUPPORT */
NULL,
0,
#endif /* PPPOL2TP_AUTH_SUPPORT */
msg->msg.msg.l2tpcreate.link_status_cb, msg->msg.msg.l2tpcreate.ctx_cb);
return ERR_OK;
}
/**
* Call pppol2tp_create() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
ppp_pcb*
pppapi_pppol2tp_create(struct netif *pppif, struct netif *netif, ip_addr_t *ipaddr, u16_t port,
const u8_t *secret, u8_t secret_len,
ppp_link_status_cb_fn link_status_cb, void *ctx_cb)
{
ppp_pcb* result;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC_RETURN_NULL(msg);
#if !PPPOL2TP_AUTH_SUPPORT
LWIP_UNUSED_ARG(secret);
LWIP_UNUSED_ARG(secret_len);
#endif /* !PPPOL2TP_AUTH_SUPPORT */
PPPAPI_VAR_REF(msg).msg.ppp = NULL;
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.pppif = pppif;
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.netif = netif;
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.ipaddr = PPPAPI_VAR_REF(ipaddr);
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.port = port;
#if PPPOL2TP_AUTH_SUPPORT
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.secret = secret;
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.secret_len = secret_len;
#endif /* PPPOL2TP_AUTH_SUPPORT */
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.link_status_cb = link_status_cb;
PPPAPI_VAR_REF(msg).msg.msg.l2tpcreate.ctx_cb = ctx_cb;
tcpip_api_call(pppapi_do_pppol2tp_create, &PPPAPI_VAR_REF(msg).call);
result = PPPAPI_VAR_REF(msg).msg.ppp;
PPPAPI_VAR_FREE(msg);
return result;
}
#endif /* PPPOL2TP_SUPPORT */
/**
* Call ppp_connect() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_connect(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
return ppp_connect(msg->msg.ppp, msg->msg.msg.connect.holdoff);
}
/**
* Call ppp_connect() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_connect(ppp_pcb *pcb, u16_t holdoff)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
PPPAPI_VAR_REF(msg).msg.msg.connect.holdoff = holdoff;
err = tcpip_api_call(pppapi_do_ppp_connect, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
#if PPP_SERVER
/**
* Call ppp_listen() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_listen(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
return ppp_listen(msg->msg.ppp);
}
/**
* Call ppp_listen() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_listen(ppp_pcb *pcb)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
err = tcpip_api_call(pppapi_do_ppp_listen, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
#endif /* PPP_SERVER */
/**
* Call ppp_close() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_close(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
return ppp_close(msg->msg.ppp, msg->msg.msg.close.nocarrier);
}
/**
* Call ppp_close() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_close(ppp_pcb *pcb, u8_t nocarrier)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
PPPAPI_VAR_REF(msg).msg.msg.close.nocarrier = nocarrier;
err = tcpip_api_call(pppapi_do_ppp_close, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
/**
* Call ppp_free() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_free(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
return ppp_free(msg->msg.ppp);
}
/**
* Call ppp_free() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_free(ppp_pcb *pcb)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
err = tcpip_api_call(pppapi_do_ppp_free, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
/**
* Call ppp_ioctl() inside the tcpip_thread context.
*/
static err_t
pppapi_do_ppp_ioctl(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 pppapi_msg */
struct pppapi_msg *msg = (struct pppapi_msg *)(void*)m;
return ppp_ioctl(msg->msg.ppp, msg->msg.msg.ioctl.cmd, msg->msg.msg.ioctl.arg);
}
/**
* Call ppp_ioctl() in a thread-safe way by running that function inside the
* tcpip_thread context.
*/
err_t
pppapi_ioctl(ppp_pcb *pcb, u8_t cmd, void *arg)
{
err_t err;
PPPAPI_VAR_DECLARE(msg);
PPPAPI_VAR_ALLOC(msg);
PPPAPI_VAR_REF(msg).msg.ppp = pcb;
PPPAPI_VAR_REF(msg).msg.msg.ioctl.cmd = cmd;
PPPAPI_VAR_REF(msg).msg.msg.ioctl.arg = arg;
err = tcpip_api_call(pppapi_do_ppp_ioctl, &PPPAPI_VAR_REF(msg).call);
PPPAPI_VAR_FREE(msg);
return err;
}
#endif /* LWIP_PPP_API */

View File

@ -1,66 +0,0 @@
/*
* pppcrypt.c - PPP/DES linkage for MS-CHAP and EAP SRP-SHA1
*
* Extracted from chap_ms.c by James Carlson.
*
* Copyright (c) 1995 Eric Rosenquist. 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(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && MSCHAP_SUPPORT /* don't build if not necessary */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/pppcrypt.h"
static u_char pppcrypt_get_7bits(u_char *input, int startBit) {
unsigned int word;
word = (unsigned)input[startBit / 8] << 8;
word |= (unsigned)input[startBit / 8 + 1];
word >>= 15 - (startBit % 8 + 7);
return word & 0xFE;
}
/* IN 56 bit DES key missing parity bits
* OUT 64 bit DES key with parity bits added
*/
void pppcrypt_56_to_64_bit_key(u_char *key, u_char * des_key) {
des_key[0] = pppcrypt_get_7bits(key, 0);
des_key[1] = pppcrypt_get_7bits(key, 7);
des_key[2] = pppcrypt_get_7bits(key, 14);
des_key[3] = pppcrypt_get_7bits(key, 21);
des_key[4] = pppcrypt_get_7bits(key, 28);
des_key[5] = pppcrypt_get_7bits(key, 35);
des_key[6] = pppcrypt_get_7bits(key, 42);
des_key[7] = pppcrypt_get_7bits(key, 49);
}
#endif /* PPP_SUPPORT && MSCHAP_SUPPORT */

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,934 +0,0 @@
/**
* @file
* Network Point to Point Protocol over Serial file.
*
*/
/*
* 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 "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && PPPOS_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include <string.h>
#include "lwip/arch.h"
#include "lwip/err.h"
#include "lwip/pbuf.h"
#include "lwip/sys.h"
#include "lwip/memp.h"
#include "lwip/netif.h"
#include "lwip/snmp.h"
#include "lwip/priv/tcpip_priv.h"
#include "lwip/api.h"
#include "lwip/ip4.h" /* for ip4_input() */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/pppos.h"
#include "netif/ppp/vj.h"
/* Memory pool */
LWIP_MEMPOOL_DECLARE(PPPOS_PCB, MEMP_NUM_PPPOS_INTERFACES, sizeof(pppos_pcb), "PPPOS_PCB")
/* callbacks called from PPP core */
static err_t pppos_write(ppp_pcb *ppp, void *ctx, struct pbuf *p);
static err_t pppos_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *pb, u16_t protocol);
static void pppos_connect(ppp_pcb *ppp, void *ctx);
#if PPP_SERVER
static void pppos_listen(ppp_pcb *ppp, void *ctx);
#endif /* PPP_SERVER */
static void pppos_disconnect(ppp_pcb *ppp, void *ctx);
static err_t pppos_destroy(ppp_pcb *ppp, void *ctx);
static void pppos_send_config(ppp_pcb *ppp, void *ctx, u32_t accm, int pcomp, int accomp);
static void pppos_recv_config(ppp_pcb *ppp, void *ctx, u32_t accm, int pcomp, int accomp);
/* Prototypes for procedures local to this file. */
#if PPP_INPROC_IRQ_SAFE
static void pppos_input_callback(void *arg);
#endif /* PPP_INPROC_IRQ_SAFE */
static void pppos_input_free_current_packet(pppos_pcb *pppos);
static void pppos_input_drop(pppos_pcb *pppos);
static err_t pppos_output_append(pppos_pcb *pppos, err_t err, struct pbuf *nb, u8_t c, u8_t accm, u16_t *fcs);
static err_t pppos_output_last(pppos_pcb *pppos, err_t err, struct pbuf *nb, u16_t *fcs);
/* Callbacks structure for PPP core */
static const struct link_callbacks pppos_callbacks = {
pppos_connect,
#if PPP_SERVER
pppos_listen,
#endif /* PPP_SERVER */
pppos_disconnect,
pppos_destroy,
pppos_write,
pppos_netif_output,
pppos_send_config,
pppos_recv_config
};
/* PPP's Asynchronous-Control-Character-Map. The mask array is used
* to select the specific bit for a character. */
#define ESCAPE_P(accm, c) ((accm)[(c) >> 3] & 1 << (c & 0x07))
#if PPP_FCS_TABLE
/*
* FCS lookup table as calculated by genfcstab.
*/
static const u16_t fcstab[256] = {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
#define PPP_FCS(fcs, c) (((fcs) >> 8) ^ fcstab[((fcs) ^ (c)) & 0xff])
#else /* PPP_FCS_TABLE */
/* The HDLC polynomial: X**0 + X**5 + X**12 + X**16 (0x8408) */
#define PPP_FCS_POLYNOMIAL 0x8408
static u16_t
ppp_get_fcs(u8_t byte)
{
unsigned int octet;
int bit;
octet = byte;
for (bit = 8; bit-- > 0; ) {
octet = (octet & 0x01) ? ((octet >> 1) ^ PPP_FCS_POLYNOMIAL) : (octet >> 1);
}
return octet & 0xffff;
}
#define PPP_FCS(fcs, c) (((fcs) >> 8) ^ ppp_get_fcs(((fcs) ^ (c)) & 0xff))
#endif /* PPP_FCS_TABLE */
/*
* Values for FCS calculations.
*/
#define PPP_INITFCS 0xffff /* Initial FCS value */
#define PPP_GOODFCS 0xf0b8 /* Good final FCS value */
#if PPP_INPROC_IRQ_SAFE
#define PPPOS_DECL_PROTECT(lev) SYS_ARCH_DECL_PROTECT(lev)
#define PPPOS_PROTECT(lev) SYS_ARCH_PROTECT(lev)
#define PPPOS_UNPROTECT(lev) SYS_ARCH_UNPROTECT(lev)
#else
#define PPPOS_DECL_PROTECT(lev)
#define PPPOS_PROTECT(lev)
#define PPPOS_UNPROTECT(lev)
#endif /* PPP_INPROC_IRQ_SAFE */
/*
* Create a new PPP connection using the given serial I/O device.
*
* Return 0 on success, an error code on failure.
*/
ppp_pcb *pppos_create(struct netif *pppif, pppos_output_cb_fn output_cb,
ppp_link_status_cb_fn link_status_cb, void *ctx_cb)
{
pppos_pcb *pppos;
ppp_pcb *ppp;
LWIP_ASSERT_CORE_LOCKED();
pppos = (pppos_pcb *)LWIP_MEMPOOL_ALLOC(PPPOS_PCB);
if (pppos == NULL) {
return NULL;
}
ppp = ppp_new(pppif, &pppos_callbacks, pppos, link_status_cb, ctx_cb);
if (ppp == NULL) {
LWIP_MEMPOOL_FREE(PPPOS_PCB, pppos);
return NULL;
}
memset(pppos, 0, sizeof(pppos_pcb));
pppos->ppp = ppp;
pppos->output_cb = output_cb;
return ppp;
}
/* Called by PPP core */
static err_t
pppos_write(ppp_pcb *ppp, void *ctx, struct pbuf *p)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
u8_t *s;
struct pbuf *nb;
u16_t n;
u16_t fcs_out;
err_t err;
LWIP_UNUSED_ARG(ppp);
/* Grab an output buffer. Assume PBUF_POOL_BUFSIZE is an acceptable
* chunk size for Tx as well. */
nb = pbuf_alloc(PBUF_RAW, PBUF_POOL_BUFSIZE, PBUF_RAM);
if (nb == NULL) {
PPPDEBUG(LOG_WARNING, ("pppos_write[%d]: alloc fail\n", ppp->netif->num));
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(ppp->netif, ifoutdiscards);
pbuf_free(p);
return ERR_MEM;
}
/* Empty the buffer */
nb->len = 0;
/* Set nb->tot_len to actual payload length */
nb->tot_len = p->len;
/* If the link has been idle, we'll send a fresh flag character to
* flush any noise. */
err = ERR_OK;
if ((sys_now() - pppos->last_xmit) >= PPP_MAXIDLEFLAG) {
err = pppos_output_append(pppos, err, nb, PPP_FLAG, 0, NULL);
}
/* Load output buffer. */
fcs_out = PPP_INITFCS;
s = (u8_t*)p->payload;
n = p->len;
while (n-- > 0) {
err = pppos_output_append(pppos, err, nb, *s++, 1, &fcs_out);
}
err = pppos_output_last(pppos, err, nb, &fcs_out);
if (err == ERR_OK) {
PPPDEBUG(LOG_INFO, ("pppos_write[%d]: len=%d\n", ppp->netif->num, p->len));
} else {
PPPDEBUG(LOG_WARNING, ("pppos_write[%d]: output failed len=%d\n", ppp->netif->num, p->len));
}
pbuf_free(p);
return err;
}
/* Called by PPP core */
static err_t
pppos_netif_output(ppp_pcb *ppp, void *ctx, struct pbuf *pb, u16_t protocol)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
struct pbuf *nb, *p;
u16_t fcs_out;
err_t err;
LWIP_UNUSED_ARG(ppp);
/* Grab an output buffer. Assume PBUF_POOL_BUFSIZE is an acceptable
* chunk size for Tx as well. */
nb = pbuf_alloc(PBUF_RAW, PBUF_POOL_BUFSIZE, PBUF_RAM);
if (nb == NULL) {
PPPDEBUG(LOG_WARNING, ("pppos_netif_output[%d]: alloc fail\n", ppp->netif->num));
LINK_STATS_INC(link.memerr);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(ppp->netif, ifoutdiscards);
return ERR_MEM;
}
/* Empty the buffer */
nb->len = 0;
/* Set nb->tot_len to actual payload length */
nb->tot_len = pb->tot_len;
/* If the link has been idle, we'll send a fresh flag character to
* flush any noise. */
err = ERR_OK;
if ((sys_now() - pppos->last_xmit) >= PPP_MAXIDLEFLAG) {
err = pppos_output_append(pppos, err, nb, PPP_FLAG, 0, NULL);
}
fcs_out = PPP_INITFCS;
if (!pppos->accomp) {
err = pppos_output_append(pppos, err, nb, PPP_ALLSTATIONS, 1, &fcs_out);
err = pppos_output_append(pppos, err, nb, PPP_UI, 1, &fcs_out);
}
if (!pppos->pcomp || protocol > 0xFF) {
err = pppos_output_append(pppos, err, nb, (protocol >> 8) & 0xFF, 1, &fcs_out);
}
err = pppos_output_append(pppos, err, nb, protocol & 0xFF, 1, &fcs_out);
/* Load packet. */
for(p = pb; p; p = p->next) {
u16_t n = p->len;
u8_t *s = (u8_t*)p->payload;
while (n-- > 0) {
err = pppos_output_append(pppos, err, nb, *s++, 1, &fcs_out);
}
}
err = pppos_output_last(pppos, err, nb, &fcs_out);
if (err == ERR_OK) {
PPPDEBUG(LOG_INFO, ("pppos_netif_output[%d]: proto=0x%"X16_F", len = %d\n", ppp->netif->num, protocol, pb->tot_len));
} else {
PPPDEBUG(LOG_WARNING, ("pppos_netif_output[%d]: output failed proto=0x%"X16_F", len = %d\n", ppp->netif->num, protocol, pb->tot_len));
}
return err;
}
static void
pppos_connect(ppp_pcb *ppp, void *ctx)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
PPPOS_DECL_PROTECT(lev);
#if PPP_INPROC_IRQ_SAFE
/* input pbuf left over from last session? */
pppos_input_free_current_packet(pppos);
#endif /* PPP_INPROC_IRQ_SAFE */
/* reset PPPoS control block to its initial state */
memset(&pppos->last_xmit, 0, sizeof(pppos_pcb) - offsetof(pppos_pcb, last_xmit));
/*
* Default the in and out accm so that escape and flag characters
* are always escaped.
*/
pppos->in_accm[15] = 0x60; /* no need to protect since RX is not running */
pppos->out_accm[15] = 0x60;
PPPOS_PROTECT(lev);
pppos->open = 1;
PPPOS_UNPROTECT(lev);
/*
* Start the connection and handle incoming events (packet or timeout).
*/
PPPDEBUG(LOG_INFO, ("pppos_connect: unit %d: connecting\n", ppp->netif->num));
ppp_start(ppp); /* notify upper layers */
}
#if PPP_SERVER
static void
pppos_listen(ppp_pcb *ppp, void *ctx)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
PPPOS_DECL_PROTECT(lev);
#if PPP_INPROC_IRQ_SAFE
/* input pbuf left over from last session? */
pppos_input_free_current_packet(pppos);
#endif /* PPP_INPROC_IRQ_SAFE */
/* reset PPPoS control block to its initial state */
memset(&pppos->last_xmit, 0, sizeof(pppos_pcb) - offsetof(pppos_pcb, last_xmit));
/*
* Default the in and out accm so that escape and flag characters
* are always escaped.
*/
pppos->in_accm[15] = 0x60; /* no need to protect since RX is not running */
pppos->out_accm[15] = 0x60;
PPPOS_PROTECT(lev);
pppos->open = 1;
PPPOS_UNPROTECT(lev);
/*
* Wait for something to happen.
*/
PPPDEBUG(LOG_INFO, ("pppos_listen: unit %d: listening\n", ppp->netif->num));
ppp_start(ppp); /* notify upper layers */
}
#endif /* PPP_SERVER */
static void
pppos_disconnect(ppp_pcb *ppp, void *ctx)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
PPPOS_DECL_PROTECT(lev);
PPPOS_PROTECT(lev);
pppos->open = 0;
PPPOS_UNPROTECT(lev);
/* If PPP_INPROC_IRQ_SAFE is used we cannot call
* pppos_input_free_current_packet() here because
* rx IRQ might still call pppos_input().
*/
#if !PPP_INPROC_IRQ_SAFE
/* input pbuf left ? */
pppos_input_free_current_packet(pppos);
#endif /* !PPP_INPROC_IRQ_SAFE */
ppp_link_end(ppp); /* notify upper layers */
}
static err_t
pppos_destroy(ppp_pcb *ppp, void *ctx)
{
pppos_pcb *pppos = (pppos_pcb *)ctx;
LWIP_UNUSED_ARG(ppp);
#if PPP_INPROC_IRQ_SAFE
/* input pbuf left ? */
pppos_input_free_current_packet(pppos);
#endif /* PPP_INPROC_IRQ_SAFE */
LWIP_MEMPOOL_FREE(PPPOS_PCB, pppos);
return ERR_OK;
}
#if !NO_SYS && !PPP_INPROC_IRQ_SAFE
/** Pass received raw characters to PPPoS to be decoded through lwIP TCPIP thread.
*
* This is one of the only functions that may be called outside of the TCPIP thread!
*
* @param ppp PPP descriptor index, returned by pppos_create()
* @param s received data
* @param l length of received data
*/
err_t
pppos_input_tcpip(ppp_pcb *ppp, const void *s, int l)
{
struct pbuf *p;
err_t err;
p = pbuf_alloc(PBUF_RAW, l, PBUF_POOL);
if (!p) {
return ERR_MEM;
}
pbuf_take(p, s, l);
err = tcpip_inpkt(p, ppp_netif(ppp), pppos_input_sys);
if (err != ERR_OK) {
pbuf_free(p);
}
return err;
}
/* called from TCPIP thread */
err_t pppos_input_sys(struct pbuf *p, struct netif *inp) {
ppp_pcb *ppp = (ppp_pcb*)inp->state;
struct pbuf *n;
LWIP_ASSERT_CORE_LOCKED();
for (n = p; n; n = n->next) {
pppos_input(ppp, n->payload, n->len);
}
pbuf_free(p);
return ERR_OK;
}
#endif /* !NO_SYS && !PPP_INPROC_IRQ_SAFE */
/** PPPoS input helper struct, must be packed since it is stored
* to pbuf->payload, which might be unaligned. */
#if PPP_INPROC_IRQ_SAFE
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct pppos_input_header {
PACK_STRUCT_FIELD(ppp_pcb *ppp);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#endif /* PPP_INPROC_IRQ_SAFE */
/** Pass received raw characters to PPPoS to be decoded.
*
* @param ppp PPP descriptor index, returned by pppos_create()
* @param s received data
* @param l length of received data
*/
void
pppos_input(ppp_pcb *ppp, const void *s, int l)
{
pppos_pcb *pppos = (pppos_pcb *)ppp->link_ctx_cb;
struct pbuf *next_pbuf;
const u8_t *s_u8 = (const u8_t *)s;
u8_t cur_char;
u8_t escaped;
PPPOS_DECL_PROTECT(lev);
#if !PPP_INPROC_IRQ_SAFE
LWIP_ASSERT_CORE_LOCKED();
#endif
/* Don't even bother parsing data if we are disconnected.
* Added to that, ppp_input must never be called if the upper layer is down.
*/
PPPOS_PROTECT(lev);
if (!pppos->open) {
PPPOS_UNPROTECT(lev);
return;
}
PPPOS_UNPROTECT(lev);
PPPDEBUG(LOG_DEBUG, ("pppos_input[%d]: got %d bytes\n", ppp->netif->num, l));
while (l-- > 0) {
cur_char = *s_u8++;
PPPOS_PROTECT(lev);
escaped = ESCAPE_P(pppos->in_accm, cur_char);
PPPOS_UNPROTECT(lev);
/* Handle special characters. */
if (escaped) {
/* Check for escape sequences. */
/* XXX Note that this does not handle an escaped 0x5d character which
* would appear as an escape character. Since this is an ASCII ']'
* and there is no reason that I know of to escape it, I won't complicate
* the code to handle this case. GLL */
if (cur_char == PPP_ESCAPE) {
pppos->in_escaped = 1;
/* Check for the flag character. */
} else if (cur_char == PPP_FLAG) {
/* If this is just an extra flag character, ignore it. */
if (pppos->in_state <= PDADDRESS) {
/* ignore it */;
/* If we haven't received the packet header, drop what has come in. */
} else if (pppos->in_state < PDDATA) {
PPPDEBUG(LOG_WARNING,
("pppos_input[%d]: Dropping incomplete packet %d\n",
ppp->netif->num, pppos->in_state));
LINK_STATS_INC(link.lenerr);
pppos_input_drop(pppos);
/* If the fcs is invalid, drop the packet. */
} else if (pppos->in_fcs != PPP_GOODFCS) {
PPPDEBUG(LOG_INFO,
("pppos_input[%d]: Dropping bad fcs 0x%"X16_F" proto=0x%"X16_F"\n",
ppp->netif->num, pppos->in_fcs, pppos->in_protocol));
/* Note: If you get lots of these, check for UART frame errors or try different baud rate */
LINK_STATS_INC(link.chkerr);
pppos_input_drop(pppos);
/* Otherwise it's a good packet so pass it on. */
} else {
struct pbuf *inp;
/* Trim off the checksum. */
if(pppos->in_tail->len > 2) {
pppos->in_tail->len -= 2;
pppos->in_tail->tot_len = pppos->in_tail->len;
if (pppos->in_tail != pppos->in_head) {
pbuf_cat(pppos->in_head, pppos->in_tail);
}
} else {
pppos->in_tail->tot_len = pppos->in_tail->len;
if (pppos->in_tail != pppos->in_head) {
pbuf_cat(pppos->in_head, pppos->in_tail);
}
pbuf_realloc(pppos->in_head, pppos->in_head->tot_len - 2);
}
/* Dispatch the packet thereby consuming it. */
inp = pppos->in_head;
/* Packet consumed, release our references. */
pppos->in_head = NULL;
pppos->in_tail = NULL;
#if IP_FORWARD || LWIP_IPV6_FORWARD
/* hide the room for Ethernet forwarding header */
if (0
#if PPP_IPV4_SUPPORT
|| pppos->in_protocol == PPP_IP
#endif /* PPP_IPV4_SUPPORT */
#if PPP_IPV6_SUPPORT
|| pppos->in_protocol == PPP_IPV6
#endif /* PPP_IPV6_SUPPORT */
) {
pbuf_remove_header(inp, PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN);
}
#endif /* IP_FORWARD || LWIP_IPV6_FORWARD */
#if PPP_INPROC_IRQ_SAFE
if(tcpip_try_callback(pppos_input_callback, inp) != ERR_OK) {
PPPDEBUG(LOG_ERR, ("pppos_input[%d]: tcpip_callback() failed, dropping packet\n", ppp->netif->num));
pbuf_free(inp);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(ppp->netif, ifindiscards);
}
#else /* PPP_INPROC_IRQ_SAFE */
ppp_input(ppp, inp);
/* ppp_input can disconnect the interface, we need to abort to prevent a memory
* leak if there are remaining bytes because pppos_connect and pppos_listen
* functions expect input buffer to be free. Furthermore there are no real
* reason to continue reading bytes if we are disconnected.
*/
if (!pppos->open) {
break;
}
#endif /* PPP_INPROC_IRQ_SAFE */
}
/* Prepare for a new packet. */
pppos->in_fcs = PPP_INITFCS;
pppos->in_state = PDADDRESS;
pppos->in_escaped = 0;
/* Other characters are usually control characters that may have
* been inserted by the physical layer so here we just drop them. */
} else {
PPPDEBUG(LOG_WARNING,
("pppos_input[%d]: Dropping ACCM char <%d>\n", ppp->netif->num, cur_char));
}
/* Process other characters. */
} else {
/* Unencode escaped characters. */
if (pppos->in_escaped) {
pppos->in_escaped = 0;
cur_char ^= PPP_TRANS;
}
/* Process character relative to current state. */
switch (pppos->in_state) {
case PDIDLE: /* Idle state - wait for flag character. */
break;
case PDADDRESS: /* Process address field. */
if (cur_char == PPP_ALLSTATIONS) {
pppos->in_state = PDCONTROL;
break;
}
/* Else assume compressed address and control fields so
* fall through to get the protocol... */
/* Fall through */
case PDCONTROL: /* Process control field. */
if (cur_char == PPP_UI) {
pppos->in_state = PDPROTOCOL1;
break;
}
/* Fall through */
case PDPROTOCOL1: /* Process protocol field 1. */
/* If the lower bit is set, this is the end of the protocol
* field. */
if (cur_char & 1) {
pppos->in_protocol = cur_char;
pppos->in_state = PDDATA;
} else {
pppos->in_protocol = (u16_t)cur_char << 8;
pppos->in_state = PDPROTOCOL2;
}
break;
case PDPROTOCOL2: /* Process protocol field 2. */
pppos->in_protocol |= cur_char;
pppos->in_state = PDDATA;
break;
case PDDATA: /* Process data byte. */
/* Make space to receive processed data. */
if (pppos->in_tail == NULL || pppos->in_tail->len == PBUF_POOL_BUFSIZE) {
u16_t pbuf_alloc_len;
if (pppos->in_tail != NULL) {
u16_t mru;
pppos->in_tail->tot_len = pppos->in_tail->len;
if (pppos->in_tail != pppos->in_head) {
pbuf_cat(pppos->in_head, pppos->in_tail);
/* give up the in_tail reference now */
pppos->in_tail = NULL;
}
/* Compute MRU including headers length. If smaller packets are
* requested, we must still be able to receive packets of the
* default MRU for control packets. */
mru = LWIP_MAX(PPP_MRU, PPP_DEFMRU)
/* Add 10% more. We only want to avoid filling all PBUFs with garbage,
* we don't have to be pedantic. */
+ LWIP_MAX(PPP_MRU, PPP_DEFMRU)/10
#if IP_FORWARD || LWIP_IPV6_FORWARD
+ PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN
#endif /* IP_FORWARD || LWIP_IPV6_FORWARD */
#if PPP_INPROC_IRQ_SAFE
+ sizeof(struct pppos_input_header)
#endif /* PPP_INPROC_IRQ_SAFE */
+ sizeof(pppos->in_protocol);
if (pppos->in_head->tot_len > mru) {
/* Packet too big. Drop the input packet and let the
* higher layers deal with it. Continue processing
* received characters in case a new packet starts. */
PPPDEBUG(LOG_ERR, ("pppos_input[%d]: packet too big, max_len=%d, dropping packet\n", ppp->netif->num, mru));
LINK_STATS_INC(link.lenerr);
pppos_input_drop(pppos);
pppos->in_state = PDIDLE; /* Wait for flag character. */
break;
}
}
/* If we haven't started a packet, we need a packet header. */
pbuf_alloc_len = 0;
#if IP_FORWARD || LWIP_IPV6_FORWARD
/* If IP forwarding is enabled we are reserving PBUF_LINK_ENCAPSULATION_HLEN
* + PBUF_LINK_HLEN bytes so the packet is being allocated with enough header
* space to be forwarded (to Ethernet for example).
*/
if (pppos->in_head == NULL && (0
#if PPP_IPV4_SUPPORT
|| pppos->in_protocol == PPP_IP
#endif /* PPP_IPV4_SUPPORT */
#if PPP_IPV6_SUPPORT
|| pppos->in_protocol == PPP_IPV6
#endif /* PPP_IPV6_SUPPORT */
)) {
pbuf_alloc_len = PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN;
}
#endif /* IP_FORWARD || LWIP_IPV6_FORWARD */
next_pbuf = pbuf_alloc(PBUF_RAW, pbuf_alloc_len, PBUF_POOL);
if (next_pbuf == NULL) {
/* No free buffers. Drop the input packet and let the
* higher layers deal with it. Continue processing
* received characters in case a new packet starts. */
PPPDEBUG(LOG_ERR, ("pppos_input[%d]: NO FREE PBUFS!\n", ppp->netif->num));
LINK_STATS_INC(link.memerr);
pppos_input_drop(pppos);
pppos->in_state = PDIDLE; /* Wait for flag character. */
break;
}
if (pppos->in_head == NULL) {
u8_t *payload = ((u8_t*)next_pbuf->payload) + pbuf_alloc_len;
#if PPP_INPROC_IRQ_SAFE
((struct pppos_input_header*)payload)->ppp = ppp;
payload += sizeof(struct pppos_input_header);
next_pbuf->len += sizeof(struct pppos_input_header);
#endif /* PPP_INPROC_IRQ_SAFE */
next_pbuf->len += sizeof(pppos->in_protocol);
*(payload++) = pppos->in_protocol >> 8;
*(payload) = pppos->in_protocol & 0xFF;
pppos->in_head = next_pbuf;
}
pppos->in_tail = next_pbuf;
}
/* Load character into buffer. */
((u8_t*)pppos->in_tail->payload)[pppos->in_tail->len++] = cur_char;
break;
default:
break;
}
/* update the frame check sequence number. */
pppos->in_fcs = PPP_FCS(pppos->in_fcs, cur_char);
}
} /* while (l-- > 0), all bytes processed */
}
#if PPP_INPROC_IRQ_SAFE
/* PPPoS input callback using one input pointer
*/
static void pppos_input_callback(void *arg) {
struct pbuf *pb = (struct pbuf*)arg;
ppp_pcb *ppp;
pppos_pcb *pppos;
ppp = ((struct pppos_input_header*)pb->payload)->ppp;
if(pbuf_remove_header(pb, sizeof(struct pppos_input_header))) {
LWIP_ASSERT("pbuf_remove_header failed", 0);
goto drop;
}
/* A previous call to ppp_input might have disconnected the session
* while there were still packets in flight in the tcpip mailbox.
* Drop incoming packets because ppp_input must never be called if
* the upper layer is down.
*/
pppos = (pppos_pcb *)ppp->link_ctx_cb;
if (!pppos->open) {
goto drop;
}
/* Dispatch the packet thereby consuming it. */
ppp_input(ppp, pb);
return;
drop:
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(ppp->netif, ifindiscards);
pbuf_free(pb);
}
#endif /* PPP_INPROC_IRQ_SAFE */
static void
pppos_send_config(ppp_pcb *ppp, void *ctx, u32_t accm, int pcomp, int accomp)
{
int i;
pppos_pcb *pppos = (pppos_pcb *)ctx;
LWIP_UNUSED_ARG(ppp);
pppos->pcomp = pcomp;
pppos->accomp = accomp;
/* Load the ACCM bits for the 32 control codes. */
for (i = 0; i < 32/8; i++) {
pppos->out_accm[i] = (u8_t)((accm >> (8 * i)) & 0xFF);
}
PPPDEBUG(LOG_INFO, ("pppos_send_config[%d]: out_accm=%X %X %X %X\n",
pppos->ppp->netif->num,
pppos->out_accm[0], pppos->out_accm[1], pppos->out_accm[2], pppos->out_accm[3]));
}
static void
pppos_recv_config(ppp_pcb *ppp, void *ctx, u32_t accm, int pcomp, int accomp)
{
int i;
pppos_pcb *pppos = (pppos_pcb *)ctx;
PPPOS_DECL_PROTECT(lev);
LWIP_UNUSED_ARG(ppp);
LWIP_UNUSED_ARG(pcomp);
LWIP_UNUSED_ARG(accomp);
/* Load the ACCM bits for the 32 control codes. */
PPPOS_PROTECT(lev);
for (i = 0; i < 32 / 8; i++) {
pppos->in_accm[i] = (u8_t)(accm >> (i * 8));
}
PPPOS_UNPROTECT(lev);
PPPDEBUG(LOG_INFO, ("pppos_recv_config[%d]: in_accm=%X %X %X %X\n",
pppos->ppp->netif->num,
pppos->in_accm[0], pppos->in_accm[1], pppos->in_accm[2], pppos->in_accm[3]));
}
/*
* Drop the input packet.
*/
static void
pppos_input_free_current_packet(pppos_pcb *pppos)
{
if (pppos->in_head != NULL) {
if (pppos->in_tail && (pppos->in_tail != pppos->in_head)) {
pbuf_free(pppos->in_tail);
}
pbuf_free(pppos->in_head);
pppos->in_head = NULL;
}
pppos->in_tail = NULL;
}
/*
* Drop the input packet and increase error counters.
*/
static void
pppos_input_drop(pppos_pcb *pppos)
{
if (pppos->in_head != NULL) {
#if 0
PPPDEBUG(LOG_INFO, ("pppos_input_drop: %d:%.*H\n", pppos->in_head->len, min(60, pppos->in_head->len * 2), pppos->in_head->payload));
#endif
PPPDEBUG(LOG_INFO, ("pppos_input_drop: pbuf len=%d, addr %p\n", pppos->in_head->len, (void*)pppos->in_head));
}
pppos_input_free_current_packet(pppos);
#if VJ_SUPPORT
vj_uncompress_err(&pppos->ppp->vj_comp);
#endif /* VJ_SUPPORT */
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(pppos->ppp->netif, ifindiscards);
}
/*
* pppos_output_append - append given character to end of given pbuf.
* If out_accm is not 0 and the character needs to be escaped, do so.
* If pbuf is full, send the pbuf and reuse it.
* Return the current pbuf.
*/
static err_t
pppos_output_append(pppos_pcb *pppos, err_t err, struct pbuf *nb, u8_t c, u8_t accm, u16_t *fcs)
{
if (err != ERR_OK) {
return err;
}
/* Make sure there is room for the character and an escape code.
* Sure we don't quite fill the buffer if the character doesn't
* get escaped but is one character worth complicating this? */
if ((PBUF_POOL_BUFSIZE - nb->len) < 2) {
u32_t l = pppos->output_cb(pppos->ppp, nb->payload, nb->len, pppos->ppp->ctx_cb);
if (l != nb->len) {
return ERR_IF;
}
nb->len = 0;
}
/* Update FCS before checking for special characters. */
if (fcs) {
*fcs = PPP_FCS(*fcs, c);
}
/* Copy to output buffer escaping special characters. */
if (accm && ESCAPE_P(pppos->out_accm, c)) {
*((u8_t*)nb->payload + nb->len++) = PPP_ESCAPE;
*((u8_t*)nb->payload + nb->len++) = c ^ PPP_TRANS;
} else {
*((u8_t*)nb->payload + nb->len++) = c;
}
return ERR_OK;
}
static err_t
pppos_output_last(pppos_pcb *pppos, err_t err, struct pbuf *nb, u16_t *fcs)
{
ppp_pcb *ppp = pppos->ppp;
/* Add FCS and trailing flag. */
err = pppos_output_append(pppos, err, nb, ~(*fcs) & 0xFF, 1, NULL);
err = pppos_output_append(pppos, err, nb, (~(*fcs) >> 8) & 0xFF, 1, NULL);
err = pppos_output_append(pppos, err, nb, PPP_FLAG, 0, NULL);
if (err != ERR_OK) {
goto failed;
}
/* Send remaining buffer if not empty */
if (nb->len > 0) {
u32_t l = pppos->output_cb(ppp, nb->payload, nb->len, ppp->ctx_cb);
if (l != nb->len) {
err = ERR_IF;
goto failed;
}
}
pppos->last_xmit = sys_now();
MIB2_STATS_NETIF_ADD(ppp->netif, ifoutoctets, nb->tot_len);
MIB2_STATS_NETIF_INC(ppp->netif, ifoutucastpkts);
LINK_STATS_INC(link.xmit);
pbuf_free(nb);
return ERR_OK;
failed:
pppos->last_xmit = 0; /* prepend PPP_FLAG to next packet */
LINK_STATS_INC(link.err);
LINK_STATS_INC(link.drop);
MIB2_STATS_NETIF_INC(ppp->netif, ifoutdiscards);
pbuf_free(nb);
return err;
}
#endif /* PPP_SUPPORT && PPPOS_SUPPORT */

View File

@ -1,679 +0,0 @@
/*
* upap.c - User/Password Authentication Protocol.
*
* Copyright (c) 1984-2000 Carnegie Mellon University. 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 "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Office of Technology Transfer
* Carnegie Mellon University
* 5000 Forbes Avenue
* Pittsburgh, PA 15213-3890
* (412) 268-4387, fax: (412) 268-7395
* tech-transfer@andrew.cmu.edu
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && PAP_SUPPORT /* don't build if not configured for use in lwipopts.h */
/*
* @todo:
*/
#if 0 /* UNUSED */
#include <stdio.h>
#include <string.h>
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/upap.h"
#if PPP_OPTIONS
/*
* Command-line options.
*/
static option_t pap_option_list[] = {
{ "hide-password", o_bool, &hide_password,
"Don't output passwords to log", OPT_PRIO | 1 },
{ "show-password", o_bool, &hide_password,
"Show password string in debug log messages", OPT_PRIOSUB | 0 },
{ "pap-restart", o_int, &upap[0].us_timeouttime,
"Set retransmit timeout for PAP", OPT_PRIO },
{ "pap-max-authreq", o_int, &upap[0].us_maxtransmits,
"Set max number of transmissions for auth-reqs", OPT_PRIO },
{ "pap-timeout", o_int, &upap[0].us_reqtimeout,
"Set time limit for peer PAP authentication", OPT_PRIO },
{ NULL }
};
#endif /* PPP_OPTIONS */
/*
* Protocol entry points.
*/
static void upap_init(ppp_pcb *pcb);
static void upap_lowerup(ppp_pcb *pcb);
static void upap_lowerdown(ppp_pcb *pcb);
static void upap_input(ppp_pcb *pcb, u_char *inpacket, int l);
static void upap_protrej(ppp_pcb *pcb);
#if PRINTPKT_SUPPORT
static int upap_printpkt(const u_char *p, int plen, void (*printer) (void *, const char *, ...), void *arg);
#endif /* PRINTPKT_SUPPORT */
const struct protent pap_protent = {
PPP_PAP,
upap_init,
upap_input,
upap_protrej,
upap_lowerup,
upap_lowerdown,
NULL,
NULL,
#if PRINTPKT_SUPPORT
upap_printpkt,
#endif /* PRINTPKT_SUPPORT */
#if PPP_DATAINPUT
NULL,
#endif /* PPP_DATAINPUT */
#if PRINTPKT_SUPPORT
"PAP",
NULL,
#endif /* PRINTPKT_SUPPORT */
#if PPP_OPTIONS
pap_option_list,
NULL,
#endif /* PPP_OPTIONS */
#if DEMAND_SUPPORT
NULL,
NULL
#endif /* DEMAND_SUPPORT */
};
static void upap_timeout(void *arg);
#if PPP_SERVER
static void upap_reqtimeout(void *arg);
static void upap_rauthreq(ppp_pcb *pcb, u_char *inp, int id, int len);
#endif /* PPP_SERVER */
static void upap_rauthack(ppp_pcb *pcb, u_char *inp, int id, int len);
static void upap_rauthnak(ppp_pcb *pcb, u_char *inp, int id, int len);
static void upap_sauthreq(ppp_pcb *pcb);
#if PPP_SERVER
static void upap_sresp(ppp_pcb *pcb, u_char code, u_char id, const char *msg, int msglen);
#endif /* PPP_SERVER */
/*
* upap_init - Initialize a UPAP unit.
*/
static void upap_init(ppp_pcb *pcb) {
pcb->upap.us_user = NULL;
pcb->upap.us_userlen = 0;
pcb->upap.us_passwd = NULL;
pcb->upap.us_passwdlen = 0;
pcb->upap.us_clientstate = UPAPCS_INITIAL;
#if PPP_SERVER
pcb->upap.us_serverstate = UPAPSS_INITIAL;
#endif /* PPP_SERVER */
pcb->upap.us_id = 0;
}
/*
* upap_authwithpeer - Authenticate us with our peer (start client).
*
* Set new state and send authenticate's.
*/
void upap_authwithpeer(ppp_pcb *pcb, const char *user, const char *password) {
if(!user || !password)
return;
/* Save the username and password we're given */
pcb->upap.us_user = user;
pcb->upap.us_userlen = (u8_t)LWIP_MIN(strlen(user), 0xff);
pcb->upap.us_passwd = password;
pcb->upap.us_passwdlen = (u8_t)LWIP_MIN(strlen(password), 0xff);
pcb->upap.us_transmits = 0;
/* Lower layer up yet? */
if (pcb->upap.us_clientstate == UPAPCS_INITIAL ||
pcb->upap.us_clientstate == UPAPCS_PENDING) {
pcb->upap.us_clientstate = UPAPCS_PENDING;
return;
}
upap_sauthreq(pcb); /* Start protocol */
}
#if PPP_SERVER
/*
* upap_authpeer - Authenticate our peer (start server).
*
* Set new state.
*/
void upap_authpeer(ppp_pcb *pcb) {
/* Lower layer up yet? */
if (pcb->upap.us_serverstate == UPAPSS_INITIAL ||
pcb->upap.us_serverstate == UPAPSS_PENDING) {
pcb->upap.us_serverstate = UPAPSS_PENDING;
return;
}
pcb->upap.us_serverstate = UPAPSS_LISTEN;
if (pcb->settings.pap_req_timeout > 0)
TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout);
}
#endif /* PPP_SERVER */
/*
* upap_timeout - Retransmission timer for sending auth-reqs expired.
*/
static void upap_timeout(void *arg) {
ppp_pcb *pcb = (ppp_pcb*)arg;
if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ)
return;
if (pcb->upap.us_transmits >= pcb->settings.pap_max_transmits) {
/* give up in disgust */
ppp_error(("No response to PAP authenticate-requests"));
pcb->upap.us_clientstate = UPAPCS_BADAUTH;
auth_withpeer_fail(pcb, PPP_PAP);
return;
}
upap_sauthreq(pcb); /* Send Authenticate-Request */
}
#if PPP_SERVER
/*
* upap_reqtimeout - Give up waiting for the peer to send an auth-req.
*/
static void upap_reqtimeout(void *arg) {
ppp_pcb *pcb = (ppp_pcb*)arg;
if (pcb->upap.us_serverstate != UPAPSS_LISTEN)
return; /* huh?? */
auth_peer_fail(pcb, PPP_PAP);
pcb->upap.us_serverstate = UPAPSS_BADAUTH;
}
#endif /* PPP_SERVER */
/*
* upap_lowerup - The lower layer is up.
*
* Start authenticating if pending.
*/
static void upap_lowerup(ppp_pcb *pcb) {
if (pcb->upap.us_clientstate == UPAPCS_INITIAL)
pcb->upap.us_clientstate = UPAPCS_CLOSED;
else if (pcb->upap.us_clientstate == UPAPCS_PENDING) {
upap_sauthreq(pcb); /* send an auth-request */
}
#if PPP_SERVER
if (pcb->upap.us_serverstate == UPAPSS_INITIAL)
pcb->upap.us_serverstate = UPAPSS_CLOSED;
else if (pcb->upap.us_serverstate == UPAPSS_PENDING) {
pcb->upap.us_serverstate = UPAPSS_LISTEN;
if (pcb->settings.pap_req_timeout > 0)
TIMEOUT(upap_reqtimeout, pcb, pcb->settings.pap_req_timeout);
}
#endif /* PPP_SERVER */
}
/*
* upap_lowerdown - The lower layer is down.
*
* Cancel all timeouts.
*/
static void upap_lowerdown(ppp_pcb *pcb) {
if (pcb->upap.us_clientstate == UPAPCS_AUTHREQ) /* Timeout pending? */
UNTIMEOUT(upap_timeout, pcb); /* Cancel timeout */
#if PPP_SERVER
if (pcb->upap.us_serverstate == UPAPSS_LISTEN && pcb->settings.pap_req_timeout > 0)
UNTIMEOUT(upap_reqtimeout, pcb);
#endif /* PPP_SERVER */
pcb->upap.us_clientstate = UPAPCS_INITIAL;
#if PPP_SERVER
pcb->upap.us_serverstate = UPAPSS_INITIAL;
#endif /* PPP_SERVER */
}
/*
* upap_protrej - Peer doesn't speak this protocol.
*
* This shouldn't happen. In any case, pretend lower layer went down.
*/
static void upap_protrej(ppp_pcb *pcb) {
if (pcb->upap.us_clientstate == UPAPCS_AUTHREQ) {
ppp_error(("PAP authentication failed due to protocol-reject"));
auth_withpeer_fail(pcb, PPP_PAP);
}
#if PPP_SERVER
if (pcb->upap.us_serverstate == UPAPSS_LISTEN) {
ppp_error(("PAP authentication of peer failed (protocol-reject)"));
auth_peer_fail(pcb, PPP_PAP);
}
#endif /* PPP_SERVER */
upap_lowerdown(pcb);
}
/*
* upap_input - Input UPAP packet.
*/
static void upap_input(ppp_pcb *pcb, u_char *inpacket, int l) {
u_char *inp;
u_char code, id;
int len;
/*
* Parse header (code, id and length).
* If packet too short, drop it.
*/
inp = inpacket;
if (l < UPAP_HEADERLEN) {
UPAPDEBUG(("pap_input: rcvd short header."));
return;
}
GETCHAR(code, inp);
GETCHAR(id, inp);
GETSHORT(len, inp);
if (len < UPAP_HEADERLEN) {
UPAPDEBUG(("pap_input: rcvd illegal length."));
return;
}
if (len > l) {
UPAPDEBUG(("pap_input: rcvd short packet."));
return;
}
len -= UPAP_HEADERLEN;
/*
* Action depends on code.
*/
switch (code) {
case UPAP_AUTHREQ:
#if PPP_SERVER
upap_rauthreq(pcb, inp, id, len);
#endif /* PPP_SERVER */
break;
case UPAP_AUTHACK:
upap_rauthack(pcb, inp, id, len);
break;
case UPAP_AUTHNAK:
upap_rauthnak(pcb, inp, id, len);
break;
default: /* XXX Need code reject */
break;
}
}
#if PPP_SERVER
/*
* upap_rauth - Receive Authenticate.
*/
static void upap_rauthreq(ppp_pcb *pcb, u_char *inp, int id, int len) {
u_char ruserlen, rpasswdlen;
char *ruser;
char *rpasswd;
char rhostname[256];
int retcode;
const char *msg;
int msglen;
if (pcb->upap.us_serverstate < UPAPSS_LISTEN)
return;
/*
* If we receive a duplicate authenticate-request, we are
* supposed to return the same status as for the first request.
*/
if (pcb->upap.us_serverstate == UPAPSS_OPEN) {
upap_sresp(pcb, UPAP_AUTHACK, id, "", 0); /* return auth-ack */
return;
}
if (pcb->upap.us_serverstate == UPAPSS_BADAUTH) {
upap_sresp(pcb, UPAP_AUTHNAK, id, "", 0); /* return auth-nak */
return;
}
/*
* Parse user/passwd.
*/
if (len < 1) {
UPAPDEBUG(("pap_rauth: rcvd short packet."));
return;
}
GETCHAR(ruserlen, inp);
len -= sizeof (u_char) + ruserlen + sizeof (u_char);
if (len < 0) {
UPAPDEBUG(("pap_rauth: rcvd short packet."));
return;
}
ruser = (char *) inp;
INCPTR(ruserlen, inp);
GETCHAR(rpasswdlen, inp);
if (len < rpasswdlen) {
UPAPDEBUG(("pap_rauth: rcvd short packet."));
return;
}
rpasswd = (char *) inp;
/*
* Check the username and password given.
*/
retcode = UPAP_AUTHNAK;
if (auth_check_passwd(pcb, ruser, ruserlen, rpasswd, rpasswdlen, &msg, &msglen)) {
retcode = UPAP_AUTHACK;
}
BZERO(rpasswd, rpasswdlen);
#if 0 /* UNUSED */
/*
* Check remote number authorization. A plugin may have filled in
* the remote number or added an allowed number, and rather than
* return an authenticate failure, is leaving it for us to verify.
*/
if (retcode == UPAP_AUTHACK) {
if (!auth_number()) {
/* We do not want to leak info about the pap result. */
retcode = UPAP_AUTHNAK; /* XXX exit value will be "wrong" */
warn("calling number %q is not authorized", remote_number);
}
}
msglen = strlen(msg);
if (msglen > 255)
msglen = 255;
#endif /* UNUSED */
upap_sresp(pcb, retcode, id, msg, msglen);
/* Null terminate and clean remote name. */
ppp_slprintf(rhostname, sizeof(rhostname), "%.*v", ruserlen, ruser);
if (retcode == UPAP_AUTHACK) {
pcb->upap.us_serverstate = UPAPSS_OPEN;
ppp_notice(("PAP peer authentication succeeded for %q", rhostname));
auth_peer_success(pcb, PPP_PAP, 0, ruser, ruserlen);
} else {
pcb->upap.us_serverstate = UPAPSS_BADAUTH;
ppp_warn(("PAP peer authentication failed for %q", rhostname));
auth_peer_fail(pcb, PPP_PAP);
}
if (pcb->settings.pap_req_timeout > 0)
UNTIMEOUT(upap_reqtimeout, pcb);
}
#endif /* PPP_SERVER */
/*
* upap_rauthack - Receive Authenticate-Ack.
*/
static void upap_rauthack(ppp_pcb *pcb, u_char *inp, int id, int len) {
u_char msglen;
char *msg;
LWIP_UNUSED_ARG(id);
if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ) /* XXX */
return;
/*
* Parse message.
*/
if (len < 1) {
UPAPDEBUG(("pap_rauthack: ignoring missing msg-length."));
} else {
GETCHAR(msglen, inp);
if (msglen > 0) {
len -= sizeof (u_char);
if (len < msglen) {
UPAPDEBUG(("pap_rauthack: rcvd short packet."));
return;
}
msg = (char *) inp;
PRINTMSG(msg, msglen);
}
}
UNTIMEOUT(upap_timeout, pcb);
pcb->upap.us_clientstate = UPAPCS_OPEN;
auth_withpeer_success(pcb, PPP_PAP, 0);
}
/*
* upap_rauthnak - Receive Authenticate-Nak.
*/
static void upap_rauthnak(ppp_pcb *pcb, u_char *inp, int id, int len) {
u_char msglen;
char *msg;
LWIP_UNUSED_ARG(id);
if (pcb->upap.us_clientstate != UPAPCS_AUTHREQ) /* XXX */
return;
/*
* Parse message.
*/
if (len < 1) {
UPAPDEBUG(("pap_rauthnak: ignoring missing msg-length."));
} else {
GETCHAR(msglen, inp);
if (msglen > 0) {
len -= sizeof (u_char);
if (len < msglen) {
UPAPDEBUG(("pap_rauthnak: rcvd short packet."));
return;
}
msg = (char *) inp;
PRINTMSG(msg, msglen);
}
}
UNTIMEOUT(upap_timeout, pcb);
pcb->upap.us_clientstate = UPAPCS_BADAUTH;
ppp_error(("PAP authentication failed"));
auth_withpeer_fail(pcb, PPP_PAP);
}
/*
* upap_sauthreq - Send an Authenticate-Request.
*/
static void upap_sauthreq(ppp_pcb *pcb) {
struct pbuf *p;
u_char *outp;
int outlen;
outlen = UPAP_HEADERLEN + 2 * sizeof (u_char) +
pcb->upap.us_userlen + pcb->upap.us_passwdlen;
p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +outlen), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
outp = (u_char*)p->payload;
MAKEHEADER(outp, PPP_PAP);
PUTCHAR(UPAP_AUTHREQ, outp);
PUTCHAR(++pcb->upap.us_id, outp);
PUTSHORT(outlen, outp);
PUTCHAR(pcb->upap.us_userlen, outp);
MEMCPY(outp, pcb->upap.us_user, pcb->upap.us_userlen);
INCPTR(pcb->upap.us_userlen, outp);
PUTCHAR(pcb->upap.us_passwdlen, outp);
MEMCPY(outp, pcb->upap.us_passwd, pcb->upap.us_passwdlen);
ppp_write(pcb, p);
TIMEOUT(upap_timeout, pcb, pcb->settings.pap_timeout_time);
++pcb->upap.us_transmits;
pcb->upap.us_clientstate = UPAPCS_AUTHREQ;
}
#if PPP_SERVER
/*
* upap_sresp - Send a response (ack or nak).
*/
static void upap_sresp(ppp_pcb *pcb, u_char code, u_char id, const char *msg, int msglen) {
struct pbuf *p;
u_char *outp;
int outlen;
outlen = UPAP_HEADERLEN + sizeof (u_char) + msglen;
p = pbuf_alloc(PBUF_RAW, (u16_t)(PPP_HDRLEN +outlen), PBUF_RAM);
if(NULL == p)
return;
if(p->tot_len != p->len) {
pbuf_free(p);
return;
}
outp = (u_char*)p->payload;
MAKEHEADER(outp, PPP_PAP);
PUTCHAR(code, outp);
PUTCHAR(id, outp);
PUTSHORT(outlen, outp);
PUTCHAR(msglen, outp);
MEMCPY(outp, msg, msglen);
ppp_write(pcb, p);
}
#endif /* PPP_SERVER */
#if PRINTPKT_SUPPORT
/*
* upap_printpkt - print the contents of a PAP packet.
*/
static const char* const upap_codenames[] = {
"AuthReq", "AuthAck", "AuthNak"
};
static int upap_printpkt(const u_char *p, int plen, void (*printer) (void *, const char *, ...), void *arg) {
int code, id, len;
int mlen, ulen, wlen;
const u_char *user, *pwd, *msg;
const u_char *pstart;
if (plen < UPAP_HEADERLEN)
return 0;
pstart = p;
GETCHAR(code, p);
GETCHAR(id, p);
GETSHORT(len, p);
if (len < UPAP_HEADERLEN || len > plen)
return 0;
if (code >= 1 && code <= (int)LWIP_ARRAYSIZE(upap_codenames))
printer(arg, " %s", upap_codenames[code-1]);
else
printer(arg, " code=0x%x", code);
printer(arg, " id=0x%x", id);
len -= UPAP_HEADERLEN;
switch (code) {
case UPAP_AUTHREQ:
if (len < 1)
break;
ulen = p[0];
if (len < ulen + 2)
break;
wlen = p[ulen + 1];
if (len < ulen + wlen + 2)
break;
user = (const u_char *) (p + 1);
pwd = (const u_char *) (p + ulen + 2);
p += ulen + wlen + 2;
len -= ulen + wlen + 2;
printer(arg, " user=");
ppp_print_string(user, ulen, printer, arg);
printer(arg, " password=");
/* FIXME: require ppp_pcb struct as printpkt() argument */
#if 0
if (!pcb->settings.hide_password)
#endif
ppp_print_string(pwd, wlen, printer, arg);
#if 0
else
printer(arg, "<hidden>");
#endif
break;
case UPAP_AUTHACK:
case UPAP_AUTHNAK:
if (len < 1)
break;
mlen = p[0];
if (len < mlen + 1)
break;
msg = (const u_char *) (p + 1);
p += mlen + 1;
len -= mlen + 1;
printer(arg, " ");
ppp_print_string(msg, mlen, printer, arg);
break;
default:
break;
}
/* print the rest of the bytes in the packet */
for (; len > 0; --len) {
GETCHAR(code, p);
printer(arg, " %.2x", code);
}
return p - pstart;
}
#endif /* PRINTPKT_SUPPORT */
#endif /* PPP_SUPPORT && PAP_SUPPORT */

View File

@ -1,957 +0,0 @@
/*
* utils.c - various utility functions used in pppd.
*
* Copyright (c) 1999-2002 Paul Mackerras. 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. The name(s) of the authors of this software must not be used to
* endorse or promote products derived from this software without
* prior written permission.
*
* 3. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Paul Mackerras
* <paulus@samba.org>".
*
* THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT /* don't build if not configured for use in lwipopts.h */
#if 0 /* UNUSED */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <syslog.h>
#include <netdb.h>
#include <time.h>
#include <utmp.h>
#include <pwd.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#ifdef SVR4
#include <sys/mkdev.h>
#endif
#endif /* UNUSED */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/fsm.h"
#include "netif/ppp/lcp.h"
#if defined(SUNOS4)
extern char *strerror();
#endif
static void ppp_logit(int level, const char *fmt, va_list args);
static void ppp_log_write(int level, char *buf);
#if PRINTPKT_SUPPORT
static void ppp_vslp_printer(void *arg, const char *fmt, ...);
static void ppp_format_packet(const u_char *p, int len,
void (*printer) (void *, const char *, ...), void *arg);
struct buffer_info {
char *ptr;
int len;
};
#endif /* PRINTPKT_SUPPORT */
/*
* ppp_strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
* always leaves destination null-terminated (for len > 0).
*/
size_t ppp_strlcpy(char *dest, const char *src, size_t len) {
size_t ret = strlen(src);
if (len != 0) {
if (ret < len)
strcpy(dest, src);
else {
strncpy(dest, src, len - 1);
dest[len-1] = 0;
}
}
return ret;
}
/*
* ppp_strlcat - like strcat/strncat, doesn't overflow destination buffer,
* always leaves destination null-terminated (for len > 0).
*/
size_t ppp_strlcat(char *dest, const char *src, size_t len) {
size_t dlen = strlen(dest);
return dlen + ppp_strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
}
/*
* ppp_slprintf - format a message into a buffer. Like sprintf except we
* also specify the length of the output buffer, and we handle
* %m (error message), %v (visible string),
* %q (quoted string), %t (current time) and %I (IP address) formats.
* Doesn't do floating-point formats.
* Returns the number of chars put into buf.
*/
int ppp_slprintf(char *buf, int buflen, const char *fmt, ...) {
va_list args;
int n;
va_start(args, fmt);
n = ppp_vslprintf(buf, buflen, fmt, args);
va_end(args);
return n;
}
/*
* ppp_vslprintf - like ppp_slprintf, takes a va_list instead of a list of args.
*/
#define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
int ppp_vslprintf(char *buf, int buflen, const char *fmt, va_list args) {
int c, i, n;
int width, prec, fillch;
int base, len, neg, quoted;
unsigned long val = 0;
const char *f;
char *str, *buf0;
const unsigned char *p;
char num[32];
#if 0 /* need port */
time_t t;
#endif /* need port */
u32_t ip;
static char hexchars[] = "0123456789abcdef";
#if PRINTPKT_SUPPORT
struct buffer_info bufinfo;
#endif /* PRINTPKT_SUPPORT */
buf0 = buf;
--buflen;
while (buflen > 0) {
for (f = fmt; *f != '%' && *f != 0; ++f)
;
if (f > fmt) {
len = f - fmt;
if (len > buflen)
len = buflen;
memcpy(buf, fmt, len);
buf += len;
buflen -= len;
fmt = f;
}
if (*fmt == 0)
break;
c = *++fmt;
width = 0;
prec = -1;
fillch = ' ';
if (c == '0') {
fillch = '0';
c = *++fmt;
}
if (c == '*') {
width = va_arg(args, int);
c = *++fmt;
} else {
while (lwip_isdigit(c)) {
width = width * 10 + c - '0';
c = *++fmt;
}
}
if (c == '.') {
c = *++fmt;
if (c == '*') {
prec = va_arg(args, int);
c = *++fmt;
} else {
prec = 0;
while (lwip_isdigit(c)) {
prec = prec * 10 + c - '0';
c = *++fmt;
}
}
}
str = 0;
base = 0;
neg = 0;
++fmt;
switch (c) {
case 'l':
c = *fmt++;
switch (c) {
case 'd':
val = va_arg(args, long);
if ((long)val < 0) {
neg = 1;
val = (unsigned long)-(long)val;
}
base = 10;
break;
case 'u':
val = va_arg(args, unsigned long);
base = 10;
break;
default:
OUTCHAR('%');
OUTCHAR('l');
--fmt; /* so %lz outputs %lz etc. */
continue;
}
break;
case 'd':
i = va_arg(args, int);
if (i < 0) {
neg = 1;
val = -i;
} else
val = i;
base = 10;
break;
case 'u':
val = va_arg(args, unsigned int);
base = 10;
break;
case 'o':
val = va_arg(args, unsigned int);
base = 8;
break;
case 'x':
case 'X':
val = va_arg(args, unsigned int);
base = 16;
break;
#if 0 /* unused (and wrong on LLP64 systems) */
case 'p':
val = (unsigned long) va_arg(args, void *);
base = 16;
neg = 2;
break;
#endif /* unused (and wrong on LLP64 systems) */
case 's':
str = va_arg(args, char *);
break;
case 'c':
num[0] = va_arg(args, int);
num[1] = 0;
str = num;
break;
#if 0 /* do we always have strerror() in embedded ? */
case 'm':
str = strerror(errno);
break;
#endif /* do we always have strerror() in embedded ? */
case 'I':
ip = va_arg(args, u32_t);
ip = lwip_ntohl(ip);
ppp_slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
(ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
str = num;
break;
#if 0 /* need port */
case 't':
time(&t);
str = ctime(&t);
str += 4; /* chop off the day name */
str[15] = 0; /* chop off year and newline */
break;
#endif /* need port */
case 'v': /* "visible" string */
case 'q': /* quoted string */
quoted = c == 'q';
p = va_arg(args, unsigned char *);
if (p == NULL)
p = (const unsigned char *)"<NULL>";
if (fillch == '0' && prec >= 0) {
n = prec;
} else {
n = strlen((const char *)p);
if (prec >= 0 && n > prec)
n = prec;
}
while (n > 0 && buflen > 0) {
c = *p++;
--n;
if (!quoted && c >= 0x80) {
OUTCHAR('M');
OUTCHAR('-');
c -= 0x80;
}
if (quoted && (c == '"' || c == '\\'))
OUTCHAR('\\');
if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
if (quoted) {
OUTCHAR('\\');
switch (c) {
case '\t': OUTCHAR('t'); break;
case '\n': OUTCHAR('n'); break;
case '\b': OUTCHAR('b'); break;
case '\f': OUTCHAR('f'); break;
default:
OUTCHAR('x');
OUTCHAR(hexchars[c >> 4]);
OUTCHAR(hexchars[c & 0xf]);
}
} else {
if (c == '\t')
OUTCHAR(c);
else {
OUTCHAR('^');
OUTCHAR(c ^ 0x40);
}
}
} else
OUTCHAR(c);
}
continue;
#if PRINTPKT_SUPPORT
case 'P': /* print PPP packet */
bufinfo.ptr = buf;
bufinfo.len = buflen + 1;
p = va_arg(args, unsigned char *);
n = va_arg(args, int);
ppp_format_packet(p, n, ppp_vslp_printer, &bufinfo);
buf = bufinfo.ptr;
buflen = bufinfo.len - 1;
continue;
#endif /* PRINTPKT_SUPPORT */
case 'B':
p = va_arg(args, unsigned char *);
for (n = prec; n > 0; --n) {
c = *p++;
if (fillch == ' ')
OUTCHAR(' ');
OUTCHAR(hexchars[(c >> 4) & 0xf]);
OUTCHAR(hexchars[c & 0xf]);
}
continue;
default:
*buf++ = '%';
if (c != '%')
--fmt; /* so %z outputs %z etc. */
--buflen;
continue;
}
if (base != 0) {
str = num + sizeof(num);
*--str = 0;
while (str > num + neg) {
*--str = hexchars[val % base];
val = val / base;
if (--prec <= 0 && val == 0)
break;
}
switch (neg) {
case 1:
*--str = '-';
break;
case 2:
*--str = 'x';
*--str = '0';
break;
default:
break;
}
len = num + sizeof(num) - 1 - str;
} else {
len = strlen(str);
if (prec >= 0 && len > prec)
len = prec;
}
if (width > 0) {
if (width > buflen)
width = buflen;
if ((n = width - len) > 0) {
buflen -= n;
for (; n > 0; --n)
*buf++ = fillch;
}
}
if (len > buflen)
len = buflen;
memcpy(buf, str, len);
buf += len;
buflen -= len;
}
*buf = 0;
return buf - buf0;
}
#if PRINTPKT_SUPPORT
/*
* vslp_printer - used in processing a %P format
*/
static void ppp_vslp_printer(void *arg, const char *fmt, ...) {
int n;
va_list pvar;
struct buffer_info *bi;
va_start(pvar, fmt);
bi = (struct buffer_info *) arg;
n = ppp_vslprintf(bi->ptr, bi->len, fmt, pvar);
va_end(pvar);
bi->ptr += n;
bi->len -= n;
}
#endif /* PRINTPKT_SUPPORT */
#if 0 /* UNUSED */
/*
* log_packet - format a packet and log it.
*/
void
log_packet(p, len, prefix, level)
u_char *p;
int len;
char *prefix;
int level;
{
init_pr_log(prefix, level);
ppp_format_packet(p, len, pr_log, &level);
end_pr_log();
}
#endif /* UNUSED */
#if PRINTPKT_SUPPORT
/*
* ppp_format_packet - make a readable representation of a packet,
* calling `printer(arg, format, ...)' to output it.
*/
static void ppp_format_packet(const u_char *p, int len,
void (*printer) (void *, const char *, ...), void *arg) {
int i, n;
u_short proto;
const struct protent *protp;
if (len >= 2) {
GETSHORT(proto, p);
len -= 2;
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (proto == protp->protocol)
break;
if (protp != NULL) {
printer(arg, "[%s", protp->name);
n = (*protp->printpkt)(p, len, printer, arg);
printer(arg, "]");
p += n;
len -= n;
} else {
for (i = 0; (protp = protocols[i]) != NULL; ++i)
if (proto == (protp->protocol & ~0x8000))
break;
if (protp != 0 && protp->data_name != 0) {
printer(arg, "[%s data]", protp->data_name);
if (len > 8)
printer(arg, "%.8B ...", p);
else
printer(arg, "%.*B", len, p);
len = 0;
} else
printer(arg, "[proto=0x%x]", proto);
}
}
if (len > 32)
printer(arg, "%.32B ...", p);
else
printer(arg, "%.*B", len, p);
}
#endif /* PRINTPKT_SUPPORT */
#if 0 /* UNUSED */
/*
* init_pr_log, end_pr_log - initialize and finish use of pr_log.
*/
static char line[256]; /* line to be logged accumulated here */
static char *linep; /* current pointer within line */
static int llevel; /* level for logging */
void
init_pr_log(prefix, level)
const char *prefix;
int level;
{
linep = line;
if (prefix != NULL) {
ppp_strlcpy(line, prefix, sizeof(line));
linep = line + strlen(line);
}
llevel = level;
}
void
end_pr_log()
{
if (linep != line) {
*linep = 0;
ppp_log_write(llevel, line);
}
}
/*
* pr_log - printer routine for outputting to log
*/
void
pr_log (void *arg, const char *fmt, ...)
{
int l, n;
va_list pvar;
char *p, *eol;
char buf[256];
va_start(pvar, fmt);
n = ppp_vslprintf(buf, sizeof(buf), fmt, pvar);
va_end(pvar);
p = buf;
eol = strchr(buf, '\n');
if (linep != line) {
l = (eol == NULL)? n: eol - buf;
if (linep + l < line + sizeof(line)) {
if (l > 0) {
memcpy(linep, buf, l);
linep += l;
}
if (eol == NULL)
return;
p = eol + 1;
eol = strchr(p, '\n');
}
*linep = 0;
ppp_log_write(llevel, line);
linep = line;
}
while (eol != NULL) {
*eol = 0;
ppp_log_write(llevel, p);
p = eol + 1;
eol = strchr(p, '\n');
}
/* assumes sizeof(buf) <= sizeof(line) */
l = buf + n - p;
if (l > 0) {
memcpy(line, p, n);
linep = line + l;
}
}
#endif /* UNUSED */
/*
* ppp_print_string - print a readable representation of a string using
* printer.
*/
void ppp_print_string(const u_char *p, int len, void (*printer) (void *, const char *, ...), void *arg) {
int c;
printer(arg, "\"");
for (; len > 0; --len) {
c = *p++;
if (' ' <= c && c <= '~') {
if (c == '\\' || c == '"')
printer(arg, "\\");
printer(arg, "%c", c);
} else {
switch (c) {
case '\n':
printer(arg, "\\n");
break;
case '\r':
printer(arg, "\\r");
break;
case '\t':
printer(arg, "\\t");
break;
default:
printer(arg, "\\%.3o", (u8_t)c);
/* no break */
}
}
}
printer(arg, "\"");
}
/*
* ppp_logit - does the hard work for fatal et al.
*/
static void ppp_logit(int level, const char *fmt, va_list args) {
char buf[1024];
ppp_vslprintf(buf, sizeof(buf), fmt, args);
ppp_log_write(level, buf);
}
static void ppp_log_write(int level, char *buf) {
LWIP_UNUSED_ARG(level); /* necessary if PPPDEBUG is defined to an empty function */
LWIP_UNUSED_ARG(buf);
PPPDEBUG(level, ("%s\n", buf) );
#if 0
if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
int n = strlen(buf);
if (n > 0 && buf[n-1] == '\n')
--n;
if (write(log_to_fd, buf, n) != n
|| write(log_to_fd, "\n", 1) != 1)
log_to_fd = -1;
}
#endif
}
/*
* ppp_fatal - log an error message and die horribly.
*/
void ppp_fatal_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_ERR, fmt, pvar);
va_end(pvar);
LWIP_ASSERT("ppp_fatal", 0); /* as promised */
}
/*
* ppp_error - log an error message.
*/
void ppp_error_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_ERR, fmt, pvar);
va_end(pvar);
#if 0 /* UNUSED */
++error_count;
#endif /* UNUSED */
}
/*
* ppp_warn - log a warning message.
*/
void ppp_warn_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_WARNING, fmt, pvar);
va_end(pvar);
}
/*
* ppp_notice - log a notice-level message.
*/
void ppp_notice_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_NOTICE, fmt, pvar);
va_end(pvar);
}
/*
* ppp_info - log an informational message.
*/
void ppp_info_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_INFO, fmt, pvar);
va_end(pvar);
}
/*
* ppp_dbglog - log a debug message.
*/
void ppp_dbglog_impl(const char *fmt, ...) {
va_list pvar;
va_start(pvar, fmt);
ppp_logit(LOG_DEBUG, fmt, pvar);
va_end(pvar);
}
#if PRINTPKT_SUPPORT
/*
* ppp_dump_packet - print out a packet in readable form if it is interesting.
* Assumes len >= PPP_HDRLEN.
*/
void ppp_dump_packet(ppp_pcb *pcb, const char *tag, unsigned char *p, int len) {
int proto;
/*
* don't print data packets, i.e. IPv4, IPv6, VJ, and compressed packets.
*/
proto = (p[0] << 8) + p[1];
if (proto < 0xC000 && (proto & ~0x8000) == proto)
return;
/*
* don't print valid LCP echo request/reply packets if the link is up.
*/
if (proto == PPP_LCP && pcb->phase == PPP_PHASE_RUNNING && len >= 2 + HEADERLEN) {
unsigned char *lcp = p + 2;
int l = (lcp[2] << 8) + lcp[3];
if ((lcp[0] == ECHOREQ || lcp[0] == ECHOREP)
&& l >= HEADERLEN && l <= len - 2)
return;
}
ppp_dbglog(("%s %P", tag, p, len));
}
#endif /* PRINTPKT_SUPPORT */
#if 0 /* Unused */
/*
* complete_read - read a full `count' bytes from fd,
* unless end-of-file or an error other than EINTR is encountered.
*/
ssize_t
complete_read(int fd, void *buf, size_t count)
{
size_t done;
ssize_t nb;
char *ptr = buf;
for (done = 0; done < count; ) {
nb = read(fd, ptr, count - done);
if (nb < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (nb == 0)
break;
done += nb;
ptr += nb;
}
return done;
}
/* Procedures for locking the serial device using a lock file. */
#ifndef LOCK_DIR
#ifdef __linux__
#define LOCK_DIR "/var/lock"
#else
#ifdef SVR4
#define LOCK_DIR "/var/spool/locks"
#else
#define LOCK_DIR "/var/spool/lock"
#endif
#endif
#endif /* LOCK_DIR */
static char lock_file[MAXPATHLEN];
/*
* lock - create a lock file for the named device
*/
int
lock(dev)
char *dev;
{
#ifdef LOCKLIB
int result;
result = mklock (dev, (void *) 0);
if (result == 0) {
ppp_strlcpy(lock_file, dev, sizeof(lock_file));
return 0;
}
if (result > 0)
ppp_notice(("Device %s is locked by pid %d", dev, result));
else
ppp_error(("Can't create lock file %s", lock_file));
return -1;
#else /* LOCKLIB */
char lock_buffer[12];
int fd, pid, n;
#ifdef SVR4
struct stat sbuf;
if (stat(dev, &sbuf) < 0) {
ppp_error(("Can't get device number for %s: %m", dev));
return -1;
}
if ((sbuf.st_mode & S_IFMT) != S_IFCHR) {
ppp_error(("Can't lock %s: not a character device", dev));
return -1;
}
ppp_slprintf(lock_file, sizeof(lock_file), "%s/LK.%03d.%03d.%03d",
LOCK_DIR, major(sbuf.st_dev),
major(sbuf.st_rdev), minor(sbuf.st_rdev));
#else
char *p;
char lockdev[MAXPATHLEN];
if ((p = strstr(dev, "dev/")) != NULL) {
dev = p + 4;
strncpy(lockdev, dev, MAXPATHLEN-1);
lockdev[MAXPATHLEN-1] = 0;
while ((p = strrchr(lockdev, '/')) != NULL) {
*p = '_';
}
dev = lockdev;
} else
if ((p = strrchr(dev, '/')) != NULL)
dev = p + 1;
ppp_slprintf(lock_file, sizeof(lock_file), "%s/LCK..%s", LOCK_DIR, dev);
#endif
while ((fd = open(lock_file, O_EXCL | O_CREAT | O_RDWR, 0644)) < 0) {
if (errno != EEXIST) {
ppp_error(("Can't create lock file %s: %m", lock_file));
break;
}
/* Read the lock file to find out who has the device locked. */
fd = open(lock_file, O_RDONLY, 0);
if (fd < 0) {
if (errno == ENOENT) /* This is just a timing problem. */
continue;
ppp_error(("Can't open existing lock file %s: %m", lock_file));
break;
}
#ifndef LOCK_BINARY
n = read(fd, lock_buffer, 11);
#else
n = read(fd, &pid, sizeof(pid));
#endif /* LOCK_BINARY */
close(fd);
fd = -1;
if (n <= 0) {
ppp_error(("Can't read pid from lock file %s", lock_file));
break;
}
/* See if the process still exists. */
#ifndef LOCK_BINARY
lock_buffer[n] = 0;
pid = atoi(lock_buffer);
#endif /* LOCK_BINARY */
if (pid == getpid())
return 1; /* somebody else locked it for us */
if (pid == 0
|| (kill(pid, 0) == -1 && errno == ESRCH)) {
if (unlink (lock_file) == 0) {
ppp_notice(("Removed stale lock on %s (pid %d)", dev, pid));
continue;
}
ppp_warn(("Couldn't remove stale lock on %s", dev));
} else
ppp_notice(("Device %s is locked by pid %d", dev, pid));
break;
}
if (fd < 0) {
lock_file[0] = 0;
return -1;
}
pid = getpid();
#ifndef LOCK_BINARY
ppp_slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
write (fd, lock_buffer, 11);
#else
write(fd, &pid, sizeof (pid));
#endif
close(fd);
return 0;
#endif
}
/*
* relock - called to update our lockfile when we are about to detach,
* thus changing our pid (we fork, the child carries on, and the parent dies).
* Note that this is called by the parent, with pid equal to the pid
* of the child. This avoids a potential race which would exist if
* we had the child rewrite the lockfile (the parent might die first,
* and another process could think the lock was stale if it checked
* between when the parent died and the child rewrote the lockfile).
*/
int
relock(pid)
int pid;
{
#ifdef LOCKLIB
/* XXX is there a way to do this? */
return -1;
#else /* LOCKLIB */
int fd;
char lock_buffer[12];
if (lock_file[0] == 0)
return -1;
fd = open(lock_file, O_WRONLY, 0);
if (fd < 0) {
ppp_error(("Couldn't reopen lock file %s: %m", lock_file));
lock_file[0] = 0;
return -1;
}
#ifndef LOCK_BINARY
ppp_slprintf(lock_buffer, sizeof(lock_buffer), "%10d\n", pid);
write (fd, lock_buffer, 11);
#else
write(fd, &pid, sizeof(pid));
#endif /* LOCK_BINARY */
close(fd);
return 0;
#endif /* LOCKLIB */
}
/*
* unlock - remove our lockfile
*/
void
unlock()
{
if (lock_file[0]) {
#ifdef LOCKLIB
(void) rmlock(lock_file, (void *) 0);
#else
unlink(lock_file);
#endif
lock_file[0] = 0;
}
}
#endif /* Unused */
#endif /* PPP_SUPPORT */

View File

@ -1,685 +0,0 @@
/*
* Routines to compress and uncompess tcp packets (for transmission
* over low speed serial lines.
*
* Copyright (c) 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
* Initial distribution.
*
* Modified June 1993 by Paul Mackerras, paulus@cs.anu.edu.au,
* so that the entire packet being decompressed doesn't have
* to be in contiguous memory (just the compressed header).
*
* Modified March 1998 by Guy Lancaster, glanca@gesn.com,
* for a 16 bit processor.
*/
#include "netif/ppp/ppp_opts.h"
#if PPP_SUPPORT && VJ_SUPPORT /* don't build if not configured for use in lwipopts.h */
#include "netif/ppp/ppp_impl.h"
#include "netif/ppp/pppdebug.h"
#include "netif/ppp/vj.h"
#include <string.h>
#if LINK_STATS
#define INCR(counter) ++comp->stats.counter
#else
#define INCR(counter)
#endif
void
vj_compress_init(struct vjcompress *comp)
{
u8_t i;
struct cstate *tstate = comp->tstate;
#if MAX_SLOTS == 0
memset((char *)comp, 0, sizeof(*comp));
#endif
comp->maxSlotIndex = MAX_SLOTS - 1;
comp->compressSlot = 0; /* Disable slot ID compression by default. */
for (i = MAX_SLOTS - 1; i > 0; --i) {
tstate[i].cs_id = i;
tstate[i].cs_next = &tstate[i - 1];
}
tstate[0].cs_next = &tstate[MAX_SLOTS - 1];
tstate[0].cs_id = 0;
comp->last_cs = &tstate[0];
comp->last_recv = 255;
comp->last_xmit = 255;
comp->flags = VJF_TOSS;
}
/* ENCODE encodes a number that is known to be non-zero. ENCODEZ
* checks for zero (since zero has to be encoded in the long, 3 byte
* form).
*/
#define ENCODE(n) { \
if ((u16_t)(n) >= 256) { \
*cp++ = 0; \
cp[1] = (u8_t)(n); \
cp[0] = (u8_t)((n) >> 8); \
cp += 2; \
} else { \
*cp++ = (u8_t)(n); \
} \
}
#define ENCODEZ(n) { \
if ((u16_t)(n) >= 256 || (u16_t)(n) == 0) { \
*cp++ = 0; \
cp[1] = (u8_t)(n); \
cp[0] = (u8_t)((n) >> 8); \
cp += 2; \
} else { \
*cp++ = (u8_t)(n); \
} \
}
#define DECODEL(f) { \
if (*cp == 0) {\
u32_t tmp_ = lwip_ntohl(f) + ((cp[1] << 8) | cp[2]); \
(f) = lwip_htonl(tmp_); \
cp += 3; \
} else { \
u32_t tmp_ = lwip_ntohl(f) + (u32_t)*cp++; \
(f) = lwip_htonl(tmp_); \
} \
}
#define DECODES(f) { \
if (*cp == 0) {\
u16_t tmp_ = lwip_ntohs(f) + (((u16_t)cp[1] << 8) | cp[2]); \
(f) = lwip_htons(tmp_); \
cp += 3; \
} else { \
u16_t tmp_ = lwip_ntohs(f) + (u16_t)*cp++; \
(f) = lwip_htons(tmp_); \
} \
}
#define DECODEU(f) { \
if (*cp == 0) {\
(f) = lwip_htons(((u16_t)cp[1] << 8) | cp[2]); \
cp += 3; \
} else { \
(f) = lwip_htons((u16_t)*cp++); \
} \
}
/* Helper structures for unaligned *u32_t and *u16_t accesses */
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct vj_u32_t {
PACK_STRUCT_FIELD(u32_t v);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct vj_u16_t {
PACK_STRUCT_FIELD(u16_t v);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
/*
* vj_compress_tcp - Attempt to do Van Jacobson header compression on a
* packet. This assumes that nb and comp are not null and that the first
* buffer of the chain contains a valid IP header.
* Return the VJ type code indicating whether or not the packet was
* compressed.
*/
u8_t
vj_compress_tcp(struct vjcompress *comp, struct pbuf **pb)
{
struct pbuf *np = *pb;
struct ip_hdr *ip = (struct ip_hdr *)np->payload;
struct cstate *cs = comp->last_cs->cs_next;
u16_t ilen = IPH_HL(ip);
u16_t hlen;
struct tcp_hdr *oth;
struct tcp_hdr *th;
u16_t deltaS, deltaA = 0;
u32_t deltaL;
u32_t changes = 0;
u8_t new_seq[16];
u8_t *cp = new_seq;
/*
* Check that the packet is IP proto TCP.
*/
if (IPH_PROTO(ip) != IP_PROTO_TCP) {
return (TYPE_IP);
}
/*
* Bail if this is an IP fragment or if the TCP packet isn't
* `compressible' (i.e., ACK isn't set or some other control bit is
* set).
*/
if ((IPH_OFFSET(ip) & PP_HTONS(0x3fff)) || np->tot_len < 40) {
return (TYPE_IP);
}
th = (struct tcp_hdr *)&((struct vj_u32_t*)ip)[ilen];
if ((TCPH_FLAGS(th) & (TCP_SYN|TCP_FIN|TCP_RST|TCP_ACK)) != TCP_ACK) {
return (TYPE_IP);
}
/* Check that the TCP/IP headers are contained in the first buffer. */
hlen = ilen + TCPH_HDRLEN(th);
hlen <<= 2;
if (np->len < hlen) {
PPPDEBUG(LOG_INFO, ("vj_compress_tcp: header len %d spans buffers\n", hlen));
return (TYPE_IP);
}
/* TCP stack requires that we don't change the packet payload, therefore we copy
* the whole packet before compression. */
np = pbuf_clone(PBUF_RAW, PBUF_RAM, *pb);
if (!np) {
return (TYPE_IP);
}
*pb = np;
ip = (struct ip_hdr *)np->payload;
/*
* Packet is compressible -- we're going to send either a
* COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way we need
* to locate (or create) the connection state. Special case the
* most recently used connection since it's most likely to be used
* again & we don't have to do any reordering if it's used.
*/
INCR(vjs_packets);
if (!ip4_addr_eq(&ip->src, &cs->cs_ip.src)
|| !ip4_addr_eq(&ip->dest, &cs->cs_ip.dest)
|| (*(struct vj_u32_t*)th).v != (((struct vj_u32_t*)&cs->cs_ip)[IPH_HL(&cs->cs_ip)]).v) {
/*
* Wasn't the first -- search for it.
*
* States are kept in a circularly linked list with
* last_cs pointing to the end of the list. The
* list is kept in lru order by moving a state to the
* head of the list whenever it is referenced. Since
* the list is short and, empirically, the connection
* we want is almost always near the front, we locate
* states via linear search. If we don't find a state
* for the datagram, the oldest state is (re-)used.
*/
struct cstate *lcs;
struct cstate *lastcs = comp->last_cs;
do {
lcs = cs; cs = cs->cs_next;
INCR(vjs_searches);
if (ip4_addr_eq(&ip->src, &cs->cs_ip.src)
&& ip4_addr_eq(&ip->dest, &cs->cs_ip.dest)
&& (*(struct vj_u32_t*)th).v == (((struct vj_u32_t*)&cs->cs_ip)[IPH_HL(&cs->cs_ip)]).v) {
goto found;
}
} while (cs != lastcs);
/*
* Didn't find it -- re-use oldest cstate. Send an
* uncompressed packet that tells the other side what
* connection number we're using for this conversation.
* Note that since the state list is circular, the oldest
* state points to the newest and we only need to set
* last_cs to update the lru linkage.
*/
INCR(vjs_misses);
comp->last_cs = lcs;
goto uncompressed;
found:
/*
* Found it -- move to the front on the connection list.
*/
if (cs == lastcs) {
comp->last_cs = lcs;
} else {
lcs->cs_next = cs->cs_next;
cs->cs_next = lastcs->cs_next;
lastcs->cs_next = cs;
}
}
oth = (struct tcp_hdr *)&((struct vj_u32_t*)&cs->cs_ip)[ilen];
deltaS = ilen;
/*
* Make sure that only what we expect to change changed. The first
* line of the `if' checks the IP protocol version, header length &
* type of service. The 2nd line checks the "Don't fragment" bit.
* The 3rd line checks the time-to-live and protocol (the protocol
* check is unnecessary but costless). The 4th line checks the TCP
* header length. The 5th line checks IP options, if any. The 6th
* line checks TCP options, if any. If any of these things are
* different between the previous & current datagram, we send the
* current datagram `uncompressed'.
*/
if ((((struct vj_u16_t*)ip)[0]).v != (((struct vj_u16_t*)&cs->cs_ip)[0]).v
|| (((struct vj_u16_t*)ip)[3]).v != (((struct vj_u16_t*)&cs->cs_ip)[3]).v
|| (((struct vj_u16_t*)ip)[4]).v != (((struct vj_u16_t*)&cs->cs_ip)[4]).v
|| TCPH_HDRLEN(th) != TCPH_HDRLEN(oth)
|| (deltaS > 5 && BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2))
|| (TCPH_HDRLEN(th) > 5 && BCMP(th + 1, oth + 1, (TCPH_HDRLEN(th) - 5) << 2))) {
goto uncompressed;
}
/*
* Figure out which of the changing fields changed. The
* receiver expects changes in the order: urgent, window,
* ack, seq (the order minimizes the number of temporaries
* needed in this section of code).
*/
if (TCPH_FLAGS(th) & TCP_URG) {
deltaS = lwip_ntohs(th->urgp);
ENCODEZ(deltaS);
changes |= NEW_U;
} else if (th->urgp != oth->urgp) {
/* argh! URG not set but urp changed -- a sensible
* implementation should never do this but RFC793
* doesn't prohibit the change so we have to deal
* with it. */
goto uncompressed;
}
if ((deltaS = (u16_t)(lwip_ntohs(th->wnd) - lwip_ntohs(oth->wnd))) != 0) {
ENCODE(deltaS);
changes |= NEW_W;
}
if ((deltaL = lwip_ntohl(th->ackno) - lwip_ntohl(oth->ackno)) != 0) {
if (deltaL > 0xffff) {
goto uncompressed;
}
deltaA = (u16_t)deltaL;
ENCODE(deltaA);
changes |= NEW_A;
}
if ((deltaL = lwip_ntohl(th->seqno) - lwip_ntohl(oth->seqno)) != 0) {
if (deltaL > 0xffff) {
goto uncompressed;
}
deltaS = (u16_t)deltaL;
ENCODE(deltaS);
changes |= NEW_S;
}
switch(changes) {
case 0:
/*
* Nothing changed. If this packet contains data and the
* last one didn't, this is probably a data packet following
* an ack (normal on an interactive connection) and we send
* it compressed. Otherwise it's probably a retransmit,
* retransmitted ack or window probe. Send it uncompressed
* in case the other side missed the compressed version.
*/
if (IPH_LEN(ip) != IPH_LEN(&cs->cs_ip) &&
lwip_ntohs(IPH_LEN(&cs->cs_ip)) == hlen) {
break;
}
/* no break */
/* fall through */
case SPECIAL_I:
case SPECIAL_D:
/*
* actual changes match one of our special case encodings --
* send packet uncompressed.
*/
goto uncompressed;
case NEW_S|NEW_A:
if (deltaS == deltaA && deltaS == lwip_ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
/* special case for echoed terminal traffic */
changes = SPECIAL_I;
cp = new_seq;
}
break;
case NEW_S:
if (deltaS == lwip_ntohs(IPH_LEN(&cs->cs_ip)) - hlen) {
/* special case for data xfer */
changes = SPECIAL_D;
cp = new_seq;
}
break;
default:
break;
}
deltaS = (u16_t)(lwip_ntohs(IPH_ID(ip)) - lwip_ntohs(IPH_ID(&cs->cs_ip)));
if (deltaS != 1) {
ENCODEZ(deltaS);
changes |= NEW_I;
}
if (TCPH_FLAGS(th) & TCP_PSH) {
changes |= TCP_PUSH_BIT;
}
/*
* Grab the cksum before we overwrite it below. Then update our
* state with this packet's header.
*/
deltaA = lwip_ntohs(th->chksum);
MEMCPY(&cs->cs_ip, ip, hlen);
/*
* We want to use the original packet as our compressed packet.
* (cp - new_seq) is the number of bytes we need for compressed
* sequence numbers. In addition we need one byte for the change
* mask, one for the connection id and two for the tcp checksum.
* So, (cp - new_seq) + 4 bytes of header are needed. hlen is how
* many bytes of the original packet to toss so subtract the two to
* get the new packet size.
*/
deltaS = (u16_t)(cp - new_seq);
if (!comp->compressSlot || comp->last_xmit != cs->cs_id) {
comp->last_xmit = cs->cs_id;
hlen -= deltaS + 4;
if (pbuf_remove_header(np, hlen)){
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_remove_header failed", 0);
}
cp = (u8_t*)np->payload;
*cp++ = (u8_t)(changes | NEW_C);
*cp++ = cs->cs_id;
} else {
hlen -= deltaS + 3;
if (pbuf_remove_header(np, hlen)) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_remove_header failed", 0);
}
cp = (u8_t*)np->payload;
*cp++ = (u8_t)changes;
}
*cp++ = (u8_t)(deltaA >> 8);
*cp++ = (u8_t)deltaA;
MEMCPY(cp, new_seq, deltaS);
INCR(vjs_compressed);
return (TYPE_COMPRESSED_TCP);
/*
* Update connection state cs & send uncompressed packet (that is,
* a regular ip/tcp packet but with the 'conversation id' we hope
* to use on future compressed packets in the protocol field).
*/
uncompressed:
MEMCPY(&cs->cs_ip, ip, hlen);
IPH_PROTO_SET(ip, cs->cs_id);
comp->last_xmit = cs->cs_id;
return (TYPE_UNCOMPRESSED_TCP);
}
/*
* Called when we may have missed a packet.
*/
void
vj_uncompress_err(struct vjcompress *comp)
{
comp->flags |= VJF_TOSS;
INCR(vjs_errorin);
}
/*
* "Uncompress" a packet of type TYPE_UNCOMPRESSED_TCP.
* Return 0 on success, -1 on failure.
*/
int
vj_uncompress_uncomp(struct pbuf *nb, struct vjcompress *comp)
{
u32_t hlen;
struct cstate *cs;
struct ip_hdr *ip;
ip = (struct ip_hdr *)nb->payload;
hlen = IPH_HL(ip) << 2;
if (IPH_PROTO(ip) >= MAX_SLOTS
|| hlen + sizeof(struct tcp_hdr) > nb->len
|| (hlen += TCPH_HDRLEN_BYTES((struct tcp_hdr *)&((char *)ip)[hlen]))
> nb->len
|| hlen > MAX_HDR) {
PPPDEBUG(LOG_INFO, ("vj_uncompress_uncomp: bad cid=%d, hlen=%d buflen=%d\n",
IPH_PROTO(ip), hlen, nb->len));
vj_uncompress_err(comp);
return -1;
}
cs = &comp->rstate[comp->last_recv = IPH_PROTO(ip)];
comp->flags &=~ VJF_TOSS;
IPH_PROTO_SET(ip, IP_PROTO_TCP);
/* copy from/to bigger buffers checked above instead of cs->cs_ip and ip
just to help static code analysis to see this is correct ;-) */
MEMCPY(&cs->cs_hdr, nb->payload, hlen);
cs->cs_hlen = (u16_t)hlen;
INCR(vjs_uncompressedin);
return 0;
}
/*
* Uncompress a packet of type TYPE_COMPRESSED_TCP.
* The packet is composed of a buffer chain and the first buffer
* must contain an accurate chain length.
* The first buffer must include the entire compressed TCP/IP header.
* This procedure replaces the compressed header with the uncompressed
* header and returns the length of the VJ header.
*/
int
vj_uncompress_tcp(struct pbuf **nb, struct vjcompress *comp)
{
u8_t *cp;
struct tcp_hdr *th;
struct cstate *cs;
struct vj_u16_t *bp;
struct pbuf *n0 = *nb;
u32_t tmp;
u32_t vjlen, hlen, changes;
INCR(vjs_compressedin);
cp = (u8_t*)n0->payload;
changes = *cp++;
if (changes & NEW_C) {
/*
* Make sure the state index is in range, then grab the state.
* If we have a good state index, clear the 'discard' flag.
*/
if (*cp >= MAX_SLOTS) {
PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: bad cid=%d\n", *cp));
goto bad;
}
comp->flags &=~ VJF_TOSS;
comp->last_recv = *cp++;
} else {
/*
* this packet has an implicit state index. If we've
* had a line error since the last time we got an
* explicit state index, we have to toss the packet.
*/
if (comp->flags & VJF_TOSS) {
PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: tossing\n"));
INCR(vjs_tossed);
return (-1);
}
}
cs = &comp->rstate[comp->last_recv];
hlen = IPH_HL(&cs->cs_ip) << 2;
th = (struct tcp_hdr *)&((u8_t*)&cs->cs_ip)[hlen];
th->chksum = lwip_htons((*cp << 8) | cp[1]);
cp += 2;
if (changes & TCP_PUSH_BIT) {
TCPH_SET_FLAG(th, TCP_PSH);
} else {
TCPH_UNSET_FLAG(th, TCP_PSH);
}
switch (changes & SPECIALS_MASK) {
case SPECIAL_I:
{
u32_t i = lwip_ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
/* some compilers can't nest inline assembler.. */
tmp = lwip_ntohl(th->ackno) + i;
th->ackno = lwip_htonl(tmp);
tmp = lwip_ntohl(th->seqno) + i;
th->seqno = lwip_htonl(tmp);
}
break;
case SPECIAL_D:
/* some compilers can't nest inline assembler.. */
tmp = lwip_ntohl(th->seqno) + lwip_ntohs(IPH_LEN(&cs->cs_ip)) - cs->cs_hlen;
th->seqno = lwip_htonl(tmp);
break;
default:
if (changes & NEW_U) {
TCPH_SET_FLAG(th, TCP_URG);
DECODEU(th->urgp);
} else {
TCPH_UNSET_FLAG(th, TCP_URG);
}
if (changes & NEW_W) {
DECODES(th->wnd);
}
if (changes & NEW_A) {
DECODEL(th->ackno);
}
if (changes & NEW_S) {
DECODEL(th->seqno);
}
break;
}
if (changes & NEW_I) {
DECODES(cs->cs_ip._id);
} else {
IPH_ID_SET(&cs->cs_ip, lwip_ntohs(IPH_ID(&cs->cs_ip)) + 1);
IPH_ID_SET(&cs->cs_ip, lwip_htons(IPH_ID(&cs->cs_ip)));
}
/*
* At this point, cp points to the first byte of data in the
* packet. Fill in the IP total length and update the IP
* header checksum.
*/
vjlen = (u16_t)(cp - (u8_t*)n0->payload);
if (n0->len < vjlen) {
/*
* We must have dropped some characters (crc should detect
* this but the old slip framing won't)
*/
PPPDEBUG(LOG_INFO, ("vj_uncompress_tcp: head buffer %d too short %d\n",
n0->len, vjlen));
goto bad;
}
#if BYTE_ORDER == LITTLE_ENDIAN
tmp = n0->tot_len - vjlen + cs->cs_hlen;
IPH_LEN_SET(&cs->cs_ip, lwip_htons((u16_t)tmp));
#else
IPH_LEN_SET(&cs->cs_ip, lwip_htons(n0->tot_len - vjlen + cs->cs_hlen));
#endif
/* recompute the ip header checksum */
bp = (struct vj_u16_t*) &cs->cs_ip;
IPH_CHKSUM_SET(&cs->cs_ip, 0);
for (tmp = 0; hlen > 0; hlen -= 2) {
tmp += (*bp++).v;
}
tmp = (tmp & 0xffff) + (tmp >> 16);
tmp = (tmp & 0xffff) + (tmp >> 16);
IPH_CHKSUM_SET(&cs->cs_ip, (u16_t)(~tmp));
/* Remove the compressed header and prepend the uncompressed header. */
if (pbuf_remove_header(n0, vjlen)) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_remove_header failed", 0);
goto bad;
}
if(LWIP_MEM_ALIGN(n0->payload) != n0->payload) {
struct pbuf *np;
#if IP_FORWARD
/* If IP forwarding is enabled we are using a PBUF_LINK packet type so
* the packet is being allocated with enough header space to be
* forwarded (to Ethernet for example).
*/
np = pbuf_alloc(PBUF_LINK, n0->len + cs->cs_hlen, PBUF_POOL);
#else /* IP_FORWARD */
np = pbuf_alloc(PBUF_RAW, n0->len + cs->cs_hlen, PBUF_POOL);
#endif /* IP_FORWARD */
if(!np) {
PPPDEBUG(LOG_WARNING, ("vj_uncompress_tcp: realign failed\n"));
goto bad;
}
if (pbuf_remove_header(np, cs->cs_hlen)) {
/* Can we cope with this failing? Just assert for now */
LWIP_ASSERT("pbuf_remove_header failed", 0);
goto bad;
}
pbuf_take(np, n0->payload, n0->len);
if(n0->next) {
pbuf_chain(np, n0->next);
pbuf_dechain(n0);
}
pbuf_free(n0);
n0 = np;
}
if (pbuf_add_header(n0, cs->cs_hlen)) {
struct pbuf *np;
LWIP_ASSERT("vj_uncompress_tcp: cs->cs_hlen <= PBUF_POOL_BUFSIZE", cs->cs_hlen <= PBUF_POOL_BUFSIZE);
np = pbuf_alloc(PBUF_RAW, cs->cs_hlen, PBUF_POOL);
if(!np) {
PPPDEBUG(LOG_WARNING, ("vj_uncompress_tcp: prepend failed\n"));
goto bad;
}
pbuf_cat(np, n0);
n0 = np;
}
LWIP_ASSERT("n0->len >= cs->cs_hlen", n0->len >= cs->cs_hlen);
MEMCPY(n0->payload, &cs->cs_ip, cs->cs_hlen);
*nb = n0;
return vjlen;
bad:
vj_uncompress_err(comp);
return (-1);
}
#endif /* PPP_SUPPORT && VJ_SUPPORT */

View File

@ -1,558 +0,0 @@
/**
* @file
* SLIP Interface
*
*/
/*
* 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. 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 built upon the file: src/arch/rtxc/netif/sioslip.c
*
* Author: Magnus Ivarsson <magnus.ivarsson(at)volvo.com>
* Simon Goldschmidt
*/
/**
* @defgroup slipif SLIP
* @ingroup netifs
*
* This is an arch independent SLIP netif. The specific serial hooks must be
* provided by another file. They are sio_open, sio_read/sio_tryread and sio_send
*
* Usage: This netif can be used in three ways:
* 1. For NO_SYS==0, an RX thread can be used which blocks on sio_read()
* until data is received.
* 2. In your main loop, call slipif_poll() to check for new RX bytes,
* completed packets are fed into netif->input().
* 3. Call slipif_received_byte[s]() from your serial RX ISR and
* slipif_process_rxqueue() from your main loop. ISR level decodes
* packets and puts completed packets on a queue which is fed into
* the stack from the main loop (needs SYS_LIGHTWEIGHT_PROT for
* pbuf_alloc to work on ISR level!).
*
*/
#include "netif/slipif.h"
#include "lwip/opt.h"
#include "lwip/def.h"
#include "lwip/pbuf.h"
#include "lwip/stats.h"
#include "lwip/snmp.h"
#include "lwip/sys.h"
#include "lwip/sio.h"
#define SLIP_END 0xC0 /* 0300: start and end of every packet */
#define SLIP_ESC 0xDB /* 0333: escape start (one byte escaped data follows) */
#define SLIP_ESC_END 0xDC /* 0334: following escape: original byte is 0xC0 (END) */
#define SLIP_ESC_ESC 0xDD /* 0335: following escape: original byte is 0xDB (ESC) */
/** Maximum packet size that is received by this netif */
#ifndef SLIP_MAX_SIZE
#define SLIP_MAX_SIZE 1500
#endif
/** Define this to the interface speed for SNMP
* (sio_fd is the sio_fd_t returned by sio_open).
* The default value of zero means 'unknown'.
*/
#ifndef SLIP_SIO_SPEED
#define SLIP_SIO_SPEED(sio_fd) 0
#endif
enum slipif_recv_state {
SLIP_RECV_NORMAL,
SLIP_RECV_ESCAPE
};
struct slipif_priv {
sio_fd_t sd;
/* q is the whole pbuf chain for a packet, p is the current pbuf in the chain */
struct pbuf *p, *q;
u8_t state;
u16_t i, recved;
#if SLIP_RX_FROM_ISR
struct pbuf *rxpackets;
#endif
};
/**
* Send a pbuf doing the necessary SLIP encapsulation
*
* Uses the serial layer's sio_send()
*
* @param netif the lwip network interface structure for this slipif
* @param p the pbuf chain packet to send
* @return always returns ERR_OK since the serial layer does not provide return values
*/
static err_t
slipif_output(struct netif *netif, struct pbuf *p)
{
struct slipif_priv *priv;
struct pbuf *q;
u16_t i;
u8_t c;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
LWIP_ASSERT("p != NULL", (p != NULL));
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_output: sending %"U16_F" bytes\n", p->tot_len));
priv = (struct slipif_priv *)netif->state;
/* Send pbuf out on the serial I/O device. */
/* Start with packet delimiter. */
sio_send(SLIP_END, priv->sd);
for (q = p; q != NULL; q = q->next) {
for (i = 0; i < q->len; i++) {
c = ((u8_t *)q->payload)[i];
switch (c) {
case SLIP_END:
/* need to escape this byte (0xC0 -> 0xDB, 0xDC) */
sio_send(SLIP_ESC, priv->sd);
sio_send(SLIP_ESC_END, priv->sd);
break;
case SLIP_ESC:
/* need to escape this byte (0xDB -> 0xDB, 0xDD) */
sio_send(SLIP_ESC, priv->sd);
sio_send(SLIP_ESC_ESC, priv->sd);
break;
default:
/* normal byte - no need for escaping */
sio_send(c, priv->sd);
break;
}
}
}
/* End with packet delimiter. */
sio_send(SLIP_END, priv->sd);
return ERR_OK;
}
#if LWIP_IPV4
/**
* Send a pbuf doing the necessary SLIP encapsulation
*
* Uses the serial layer's sio_send()
*
* @param netif the lwip network interface structure for this slipif
* @param p the pbuf chain packet to send
* @param ipaddr the ip address to send the packet to (not used for slipif)
* @return always returns ERR_OK since the serial layer does not provide return values
*/
static err_t
slipif_output_v4(struct netif *netif, struct pbuf *p, const ip4_addr_t *ipaddr)
{
LWIP_UNUSED_ARG(ipaddr);
return slipif_output(netif, p);
}
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
/**
* Send a pbuf doing the necessary SLIP encapsulation
*
* Uses the serial layer's sio_send()
*
* @param netif the lwip network interface structure for this slipif
* @param p the pbuf chain packet to send
* @param ipaddr the ip address to send the packet to (not used for slipif)
* @return always returns ERR_OK since the serial layer does not provide return values
*/
static err_t
slipif_output_v6(struct netif *netif, struct pbuf *p, const ip6_addr_t *ipaddr)
{
LWIP_UNUSED_ARG(ipaddr);
return slipif_output(netif, p);
}
#endif /* LWIP_IPV6 */
/**
* Handle the incoming SLIP stream character by character
*
* @param netif the lwip network interface structure for this slipif
* @param c received character (multiple calls to this function will
* return a complete packet, NULL is returned before - used for polling)
* @return The IP packet when SLIP_END is received
*/
static struct pbuf *
slipif_rxbyte(struct netif *netif, u8_t c)
{
struct slipif_priv *priv;
struct pbuf *t;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
priv = (struct slipif_priv *)netif->state;
switch (priv->state) {
case SLIP_RECV_NORMAL:
switch (c) {
case SLIP_END:
if (priv->recved > 0) {
/* Received whole packet. */
/* Trim the pbuf to the size of the received packet. */
pbuf_realloc(priv->q, priv->recved);
LINK_STATS_INC(link.recv);
LWIP_DEBUGF(SLIP_DEBUG, ("slipif: Got packet (%"U16_F" bytes)\n", priv->recved));
t = priv->q;
priv->p = priv->q = NULL;
priv->i = priv->recved = 0;
return t;
}
return NULL;
case SLIP_ESC:
priv->state = SLIP_RECV_ESCAPE;
return NULL;
default:
break;
} /* end switch (c) */
break;
case SLIP_RECV_ESCAPE:
/* un-escape END or ESC bytes, leave other bytes
(although that would be a protocol error) */
switch (c) {
case SLIP_ESC_END:
c = SLIP_END;
break;
case SLIP_ESC_ESC:
c = SLIP_ESC;
break;
default:
break;
}
priv->state = SLIP_RECV_NORMAL;
break;
default:
break;
} /* end switch (priv->state) */
/* byte received, packet not yet completely received */
if (priv->p == NULL) {
/* allocate a new pbuf */
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: alloc\n"));
priv->p = pbuf_alloc(PBUF_LINK, (PBUF_POOL_BUFSIZE - PBUF_LINK_HLEN - PBUF_LINK_ENCAPSULATION_HLEN), PBUF_POOL);
if (priv->p == NULL) {
LINK_STATS_INC(link.drop);
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_input: no new pbuf! (DROP)\n"));
/* don't process any further since we got no pbuf to receive to */
return NULL;
}
if (priv->q != NULL) {
/* 'chain' the pbuf to the existing chain */
pbuf_cat(priv->q, priv->p);
} else {
/* p is the first pbuf in the chain */
priv->q = priv->p;
}
}
/* this automatically drops bytes if > SLIP_MAX_SIZE */
if ((priv->p != NULL) && (priv->recved <= SLIP_MAX_SIZE)) {
((u8_t *)priv->p->payload)[priv->i] = c;
priv->recved++;
priv->i++;
if (priv->i >= priv->p->len) {
/* on to the next pbuf */
priv->i = 0;
if (priv->p->next != NULL && priv->p->next->len > 0) {
/* p is a chain, on to the next in the chain */
priv->p = priv->p->next;
} else {
/* p is a single pbuf, set it to NULL so next time a new
* pbuf is allocated */
priv->p = NULL;
}
}
}
return NULL;
}
/** Like slipif_rxbyte, but passes completed packets to netif->input
*
* @param netif The lwip network interface structure for this slipif
* @param c received character
*/
static void
slipif_rxbyte_input(struct netif *netif, u8_t c)
{
struct pbuf *p;
p = slipif_rxbyte(netif, c);
if (p != NULL) {
if (netif->input(p, netif) != ERR_OK) {
pbuf_free(p);
}
}
}
#if SLIP_USE_RX_THREAD
/**
* The SLIP input thread.
*
* Feed the IP layer with incoming packets
*
* @param nf the lwip network interface structure for this slipif
*/
static void
slipif_loop_thread(void *nf)
{
u8_t c;
struct netif *netif = (struct netif *)nf;
struct slipif_priv *priv = (struct slipif_priv *)netif->state;
while (1) {
if (sio_read(priv->sd, &c, 1) > 0) {
slipif_rxbyte_input(netif, c);
}
}
}
#endif /* SLIP_USE_RX_THREAD */
/**
* @ingroup slipif
* SLIP netif initialization
*
* Call the arch specific sio_open and remember
* the opened device in the state field of the netif.
*
* @param netif the lwip network interface structure for this slipif
* @return ERR_OK if serial line could be opened,
* ERR_MEM if no memory could be allocated,
* ERR_IF is serial line couldn't be opened
*
* @note If netif->state is interpreted as an u8_t serial port number.
*
*/
err_t
slipif_init(struct netif *netif)
{
struct slipif_priv *priv;
u8_t sio_num;
LWIP_ASSERT("slipif needs an input callback", netif->input != NULL);
/* netif->state contains serial port number */
sio_num = LWIP_PTR_NUMERIC_CAST(u8_t, netif->state);
LWIP_DEBUGF(SLIP_DEBUG, ("slipif_init: netif->num=%"U16_F"\n", (u16_t)sio_num));
/* Allocate private data */
priv = (struct slipif_priv *)mem_malloc(sizeof(struct slipif_priv));
if (!priv) {
return ERR_MEM;
}
netif->name[0] = 's';
netif->name[1] = 'l';
#if LWIP_IPV4
netif->output = slipif_output_v4;
#endif /* LWIP_IPV4 */
#if LWIP_IPV6
netif->output_ip6 = slipif_output_v6;
#endif /* LWIP_IPV6 */
netif->mtu = SLIP_MAX_SIZE;
/* Try to open the serial port. */
priv->sd = sio_open(sio_num);
if (!priv->sd) {
/* Opening the serial port failed. */
mem_free(priv);
return ERR_IF;
}
/* Initialize private data */
priv->p = NULL;
priv->q = NULL;
priv->state = SLIP_RECV_NORMAL;
priv->i = 0;
priv->recved = 0;
#if SLIP_RX_FROM_ISR
priv->rxpackets = NULL;
#endif
netif->state = priv;
/* initialize the snmp variables and counters inside the struct netif */
MIB2_INIT_NETIF(netif, snmp_ifType_slip, SLIP_SIO_SPEED(priv->sd));
#if SLIP_USE_RX_THREAD
/* Create a thread to poll the serial line. */
sys_thread_new(SLIPIF_THREAD_NAME, slipif_loop_thread, netif,
SLIPIF_THREAD_STACKSIZE, SLIPIF_THREAD_PRIO);
#endif /* SLIP_USE_RX_THREAD */
return ERR_OK;
}
/**
* @ingroup slipif
* Polls the serial device and feeds the IP layer with incoming packets.
*
* @param netif The lwip network interface structure for this slipif
*/
void
slipif_poll(struct netif *netif)
{
u8_t c;
struct slipif_priv *priv;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
priv = (struct slipif_priv *)netif->state;
while (sio_tryread(priv->sd, &c, 1) > 0) {
slipif_rxbyte_input(netif, c);
}
}
#if SLIP_RX_FROM_ISR
/**
* @ingroup slipif
* Feeds the IP layer with incoming packets that were receive
*
* @param netif The lwip network interface structure for this slipif
*/
void
slipif_process_rxqueue(struct netif *netif)
{
struct slipif_priv *priv;
SYS_ARCH_DECL_PROTECT(old_level);
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
priv = (struct slipif_priv *)netif->state;
SYS_ARCH_PROTECT(old_level);
while (priv->rxpackets != NULL) {
struct pbuf *p = priv->rxpackets;
#if SLIP_RX_QUEUE
/* dequeue packet */
struct pbuf *q = p;
while ((q->len != q->tot_len) && (q->next != NULL)) {
q = q->next;
}
priv->rxpackets = q->next;
q->next = NULL;
#else /* SLIP_RX_QUEUE */
priv->rxpackets = NULL;
#endif /* SLIP_RX_QUEUE */
SYS_ARCH_UNPROTECT(old_level);
if (netif->input(p, netif) != ERR_OK) {
pbuf_free(p);
}
SYS_ARCH_PROTECT(old_level);
}
SYS_ARCH_UNPROTECT(old_level);
}
/** Like slipif_rxbyte, but queues completed packets.
*
* @param netif The lwip network interface structure for this slipif
* @param data Received serial byte
*/
static void
slipif_rxbyte_enqueue(struct netif *netif, u8_t data)
{
struct pbuf *p;
struct slipif_priv *priv = (struct slipif_priv *)netif->state;
SYS_ARCH_DECL_PROTECT(old_level);
p = slipif_rxbyte(netif, data);
if (p != NULL) {
SYS_ARCH_PROTECT(old_level);
if (priv->rxpackets != NULL) {
#if SLIP_RX_QUEUE
/* queue multiple pbufs */
struct pbuf *q = p;
while (q->next != NULL) {
q = q->next;
}
q->next = p;
} else {
#else /* SLIP_RX_QUEUE */
pbuf_free(priv->rxpackets);
}
{
#endif /* SLIP_RX_QUEUE */
priv->rxpackets = p;
}
SYS_ARCH_UNPROTECT(old_level);
}
}
/**
* @ingroup slipif
* Process a received byte, completed packets are put on a queue that is
* fed into IP through slipif_process_rxqueue().
*
* This function can be called from ISR if SYS_LIGHTWEIGHT_PROT is enabled.
*
* @param netif The lwip network interface structure for this slipif
* @param data received character
*/
void
slipif_received_byte(struct netif *netif, u8_t data)
{
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
slipif_rxbyte_enqueue(netif, data);
}
/**
* @ingroup slipif
* Process multiple received byte, completed packets are put on a queue that is
* fed into IP through slipif_process_rxqueue().
*
* This function can be called from ISR if SYS_LIGHTWEIGHT_PROT is enabled.
*
* @param netif The lwip network interface structure for this slipif
* @param data received character
* @param len Number of received characters
*/
void
slipif_received_bytes(struct netif *netif, u8_t *data, u8_t len)
{
u8_t i;
u8_t *rxdata = data;
LWIP_ASSERT("netif != NULL", (netif != NULL));
LWIP_ASSERT("netif->state != NULL", (netif->state != NULL));
for (i = 0; i < len; i++, rxdata++) {
slipif_rxbyte_enqueue(netif, *rxdata);
}
}
#endif /* SLIP_RX_FROM_ISR */

View File

@ -1,300 +0,0 @@
/**
* @file
*
* @defgroup zepif ZEP - ZigBee Encapsulation Protocol
* @ingroup netifs
* A netif implementing the ZigBee Encapsulation Protocol (ZEP).
* This is used to tunnel 6LowPAN over UDP.
*
* Usage (there must be a default netif before!):
* @code{.c}
* netif_add(&zep_netif, NULL, NULL, NULL, NULL, zepif_init, tcpip_6lowpan_input);
* netif_create_ip6_linklocal_address(&zep_netif, 1);
* netif_set_up(&zep_netif);
* netif_set_link_up(&zep_netif);
* @endcode
*/
/*
* Copyright (c) 2018 Simon Goldschmidt
* 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 <goldsimon@gmx.de>
*
*/
#include "netif/zepif.h"
#if LWIP_IPV6 && LWIP_UDP
#include "netif/lowpan6.h"
#include "lwip/udp.h"
#include "lwip/timeouts.h"
#include <string.h>
/** Define this to 1 to loop back TX packets for testing */
#ifndef ZEPIF_LOOPBACK
#define ZEPIF_LOOPBACK 0
#endif
#define ZEP_MAX_DATA_LEN 127
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/bpstruct.h"
#endif
PACK_STRUCT_BEGIN
struct zep_hdr {
PACK_STRUCT_FLD_8(u8_t prot_id[2]);
PACK_STRUCT_FLD_8(u8_t prot_version);
PACK_STRUCT_FLD_8(u8_t type);
PACK_STRUCT_FLD_8(u8_t channel_id);
PACK_STRUCT_FIELD(u16_t device_id);
PACK_STRUCT_FLD_8(u8_t crc_mode);
PACK_STRUCT_FLD_8(u8_t unknown_1);
PACK_STRUCT_FIELD(u32_t timestamp[2]);
PACK_STRUCT_FIELD(u32_t seq_num);
PACK_STRUCT_FLD_8(u8_t unknown_2[10]);
PACK_STRUCT_FLD_8(u8_t len);
} PACK_STRUCT_STRUCT;
PACK_STRUCT_END
#ifdef PACK_STRUCT_USE_INCLUDES
# include "arch/epstruct.h"
#endif
struct zepif_state {
struct zepif_init init;
struct udp_pcb *pcb;
u32_t seqno;
};
static u8_t zep_lowpan_timer_running;
/* Helper function that calls the 6LoWPAN timer and reschedules itself */
static void
zep_lowpan_timer(void *arg)
{
lowpan6_tmr();
if (zep_lowpan_timer_running) {
sys_timeout(LOWPAN6_TMR_INTERVAL, zep_lowpan_timer, arg);
}
}
/* Pass received pbufs into 6LowPAN netif */
static void
zepif_udp_recv(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
{
err_t err;
struct netif *netif_lowpan6 = (struct netif *)arg;
struct zep_hdr *zep;
LWIP_ASSERT("arg != NULL", arg != NULL);
LWIP_ASSERT("pcb != NULL", pcb != NULL);
LWIP_UNUSED_ARG(pcb); /* for LWIP_NOASSERT */
LWIP_UNUSED_ARG(addr);
LWIP_UNUSED_ARG(port);
if (p == NULL) {
return;
}
/* Parse and hide the ZEP header */
if (p->len < sizeof(struct zep_hdr)) {
/* need the zep_hdr in one piece */
goto err_return;
}
zep = (struct zep_hdr *)p->payload;
if (zep->prot_id[0] != 'E') {
goto err_return;
}
if (zep->prot_id[1] != 'X') {
goto err_return;
}
if (zep->prot_version != 2) {
/* we only support this version for now */
goto err_return;
}
if (zep->type != 1) {
goto err_return;
}
if (zep->crc_mode != 1) {
goto err_return;
}
if (zep->len != p->tot_len - sizeof(struct zep_hdr)) {
goto err_return;
}
/* everything seems to be OK, hide the ZEP header */
if (pbuf_remove_header(p, sizeof(struct zep_hdr))) {
goto err_return;
}
/* TODO Check CRC? */
/* remove CRC trailer */
pbuf_realloc(p, p->tot_len - 2);
/* Call into 6LoWPAN code. */
err = netif_lowpan6->input(p, netif_lowpan6);
if (err == ERR_OK) {
return;
}
err_return:
pbuf_free(p);
}
/* Send 6LoWPAN TX packets as UDP broadcast */
static err_t
zepif_linkoutput(struct netif *netif, struct pbuf *p)
{
err_t err;
struct pbuf *q;
struct zep_hdr *zep;
struct zepif_state *state;
LWIP_ASSERT("invalid netif", netif != NULL);
LWIP_ASSERT("invalid pbuf", p != NULL);
if (p->tot_len > ZEP_MAX_DATA_LEN) {
return ERR_VAL;
}
LWIP_ASSERT("TODO: support chained pbufs", p->next == NULL);
state = (struct zepif_state *)netif->state;
LWIP_ASSERT("state->pcb != NULL", state->pcb != NULL);
q = pbuf_alloc(PBUF_TRANSPORT, sizeof(struct zep_hdr) + p->tot_len, PBUF_RAM);
if (q == NULL) {
return ERR_MEM;
}
zep = (struct zep_hdr *)q->payload;
memset(zep, 0, sizeof(struct zep_hdr));
zep->prot_id[0] = 'E';
zep->prot_id[1] = 'X';
zep->prot_version = 2;
zep->type = 1; /* Data */
zep->channel_id = 0; /* whatever */
zep->device_id = lwip_htons(1); /* whatever */
zep->crc_mode = 1;
zep->unknown_1 = 0xff;
zep->seq_num = lwip_htonl(state->seqno);
state->seqno++;
zep->len = (u8_t)p->tot_len;
err = pbuf_copy_partial_pbuf(q, p, p->tot_len, sizeof(struct zep_hdr));
if (err == ERR_OK) {
#if ZEPIF_LOOPBACK
zepif_udp_recv(netif, state->pcb, pbuf_clone(PBUF_RAW, PBUF_RAM, q), NULL, 0);
#endif
err = udp_sendto(state->pcb, q, state->init.zep_dst_ip_addr, state->init.zep_dst_udp_port);
}
pbuf_free(q);
return err;
}
/**
* @ingroup zepif
* Set up a raw 6LowPAN netif and surround it with input- and output
* functions for ZEP
*/
err_t
zepif_init(struct netif *netif)
{
err_t err;
struct zepif_init *init_state = (struct zepif_init *)netif->state;
struct zepif_state *state = (struct zepif_state *)mem_malloc(sizeof(struct zepif_state));
LWIP_ASSERT("zepif needs an input callback", netif->input != NULL);
if (state == NULL) {
return ERR_MEM;
}
memset(state, 0, sizeof(struct zepif_state));
if (init_state != NULL) {
memcpy(&state->init, init_state, sizeof(struct zepif_init));
}
if (state->init.zep_src_udp_port == 0) {
state->init.zep_src_udp_port = ZEPIF_DEFAULT_UDP_PORT;
}
if (state->init.zep_dst_udp_port == 0) {
state->init.zep_dst_udp_port = ZEPIF_DEFAULT_UDP_PORT;
}
#if LWIP_IPV4
if (state->init.zep_dst_ip_addr == NULL) {
/* With IPv4 enabled, default to broadcasting packets if no address is set */
state->init.zep_dst_ip_addr = IP_ADDR_BROADCAST;
}
#endif /* LWIP_IPV4 */
netif->state = NULL;
state->pcb = udp_new_ip_type(IPADDR_TYPE_ANY);
if (state->pcb == NULL) {
err = ERR_MEM;
goto err_ret;
}
err = udp_bind(state->pcb, state->init.zep_src_ip_addr, state->init.zep_src_udp_port);
if (err != ERR_OK) {
goto err_ret;
}
if (state->init.zep_netif != NULL) {
udp_bind_netif(state->pcb, state->init.zep_netif);
}
LWIP_ASSERT("udp_bind(lowpan6_broadcast_pcb) failed", err == ERR_OK);
ip_set_option(state->pcb, SOF_BROADCAST);
udp_recv(state->pcb, zepif_udp_recv, netif);
err = lowpan6_if_init(netif);
LWIP_ASSERT("lowpan6_if_init set a state", netif->state == NULL);
if (err == ERR_OK) {
netif->state = state;
netif->hwaddr_len = 6;
if (init_state != NULL) {
memcpy(netif->hwaddr, init_state->addr, 6);
} else {
u8_t i;
for (i = 0; i < 6; i++) {
netif->hwaddr[i] = i;
}
netif->hwaddr[0] &= 0xfc;
}
netif->linkoutput = zepif_linkoutput;
if (!zep_lowpan_timer_running) {
sys_timeout(LOWPAN6_TMR_INTERVAL, zep_lowpan_timer, NULL);
zep_lowpan_timer_running = 1;
}
return ERR_OK;
}
err_ret:
if (state->pcb != NULL) {
udp_remove(state->pcb);
}
mem_free(state);
return err;
}
#endif /* LWIP_IPV6 && LWIP_UDP */

File diff suppressed because it is too large Load Diff

View File

@ -1,671 +0,0 @@
/**
* @file
* Implementation of raw protocol PCBs for low-level handling of
* different types of protocols besides (or overriding) those
* already available in lwIP.<br>
* See also @ref raw_raw
*
* @defgroup raw_raw RAW
* @ingroup callbackstyle_api
* Implementation of raw protocol PCBs for low-level handling of
* different types of protocols besides (or overriding) those
* already available in lwIP.<br>
* @see @ref api
*/
/*
* 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_RAW /* don't build if not configured for use in lwipopts.h */
#include "lwip/def.h"
#include "lwip/memp.h"
#include "lwip/ip_addr.h"
#include "lwip/netif.h"
#include "lwip/raw.h"
#include "lwip/priv/raw_priv.h"
#include "lwip/stats.h"
#include "lwip/ip6.h"
#include "lwip/ip6_addr.h"
#include "lwip/inet_chksum.h"
#include <string.h>
/** The list of RAW PCBs */
static struct raw_pcb *raw_pcbs;
static u8_t
raw_input_local_match(struct raw_pcb *pcb, u8_t broadcast)
{
LWIP_UNUSED_ARG(broadcast); /* in IPv6 only case */
/* check if PCB is bound to specific netif */
if ((pcb->netif_idx != NETIF_NO_INDEX) &&
(pcb->netif_idx != netif_get_index(ip_data.current_input_netif))) {
return 0;
}
#if LWIP_IPV4 && LWIP_IPV6
/* Dual-stack: PCBs listening to any IP type also listen to any IP address */
if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
#if IP_SOF_BROADCAST_RECV
if ((broadcast != 0) && !ip_get_option(pcb, SOF_BROADCAST)) {
return 0;
}
#endif /* IP_SOF_BROADCAST_RECV */
return 1;
}
#endif /* LWIP_IPV4 && LWIP_IPV6 */
/* Only need to check PCB if incoming IP version matches PCB IP version */
if (IP_ADDR_PCB_VERSION_MATCH_EXACT(pcb, ip_current_dest_addr())) {
#if LWIP_IPV4
/* Special case: IPv4 broadcast: receive all broadcasts
* Note: broadcast variable can only be 1 if it is an IPv4 broadcast */
if (broadcast != 0) {
#if IP_SOF_BROADCAST_RECV
if (ip_get_option(pcb, SOF_BROADCAST))
#endif /* IP_SOF_BROADCAST_RECV */
{
if (ip4_addr_isany(ip_2_ip4(&pcb->local_ip))) {
return 1;
}
}
} else
#endif /* LWIP_IPV4 */
/* Handle IPv4 and IPv6: catch all or exact match */
if (ip_addr_isany(&pcb->local_ip) ||
ip_addr_eq(&pcb->local_ip, ip_current_dest_addr())) {
return 1;
}
}
return 0;
}
/**
* Determine if in incoming IP packet is covered by a RAW PCB
* and if so, pass it to a user-provided receive callback function.
*
* Given an incoming IP datagram (as a chain of pbufs) this function
* finds a corresponding RAW PCB and calls the corresponding receive
* callback function.
*
* @param p pbuf to be demultiplexed to a RAW PCB.
* @param inp network interface on which the datagram was received.
* @return - 1 if the packet has been eaten by a RAW PCB receive
* callback function. The caller MAY NOT not reference the
* packet any longer, and MAY NOT call pbuf_free().
* @return - 0 if packet is not eaten (pbuf is still referenced by the
* caller).
*
*/
raw_input_state_t
raw_input(struct pbuf *p, struct netif *inp)
{
struct raw_pcb *pcb, *prev;
s16_t proto;
raw_input_state_t ret = RAW_INPUT_NONE;
u8_t broadcast = ip_addr_isbroadcast(ip_current_dest_addr(), ip_current_netif());
LWIP_UNUSED_ARG(inp);
#if LWIP_IPV6
#if LWIP_IPV4
if (IP_HDR_GET_VERSION(p->payload) == 6)
#endif /* LWIP_IPV4 */
{
struct ip6_hdr *ip6hdr = (struct ip6_hdr *)p->payload;
proto = IP6H_NEXTH(ip6hdr);
}
#if LWIP_IPV4
else
#endif /* LWIP_IPV4 */
#endif /* LWIP_IPV6 */
#if LWIP_IPV4
{
proto = IPH_PROTO((struct ip_hdr *)p->payload);
}
#endif /* LWIP_IPV4 */
prev = NULL;
pcb = raw_pcbs;
/* loop through all raw pcbs until the packet is eaten by one */
/* this allows multiple pcbs to match against the packet by design */
while (pcb != NULL) {
if ((pcb->protocol == proto) && raw_input_local_match(pcb, broadcast) &&
(((pcb->flags & RAW_FLAGS_CONNECTED) == 0) ||
ip_addr_eq(&pcb->remote_ip, ip_current_src_addr()))) {
/* receive callback function available? */
if (pcb->recv != NULL) {
u8_t eaten;
#ifndef LWIP_NOASSERT
void *old_payload = p->payload;
#endif
ret = RAW_INPUT_DELIVERED;
/* the receive callback function did not eat the packet? */
eaten = pcb->recv(pcb->recv_arg, pcb, p, ip_current_src_addr());
if (eaten != 0) {
/* receive function ate the packet */
p = NULL;
if (prev != NULL) {
/* move the pcb to the front of raw_pcbs so that is
found faster next time */
prev->next = pcb->next;
pcb->next = raw_pcbs;
raw_pcbs = pcb;
}
return RAW_INPUT_EATEN;
} else {
/* sanity-check that the receive callback did not alter the pbuf */
LWIP_ASSERT("raw pcb recv callback altered pbuf payload pointer without eating packet",
p->payload == old_payload);
}
}
/* no receive callback function was set for this raw PCB */
}
/* drop the packet */
prev = pcb;
pcb = pcb->next;
}
return ret;
}
/**
* @ingroup raw_raw
* Bind a RAW PCB.
*
* @param pcb RAW PCB to be bound with a local address ipaddr.
* @param ipaddr local IP address to bind with. Use IP4_ADDR_ANY to
* bind to all local interfaces.
*
* @return lwIP error code.
* - ERR_OK. Successful. No error occurred.
* - ERR_USE. The specified IP address is already bound to by
* another RAW PCB.
*
* @see raw_disconnect()
*/
err_t
raw_bind(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
{
LWIP_ASSERT_CORE_LOCKED();
if ((pcb == NULL) || (ipaddr == NULL)) {
return ERR_VAL;
}
ip_addr_set_ipaddr(&pcb->local_ip, ipaddr);
#if LWIP_IPV6 && LWIP_IPV6_SCOPES
/* If the given IP address should have a zone but doesn't, assign one now.
* This is legacy support: scope-aware callers should always provide properly
* zoned source addresses. */
if (IP_IS_V6(&pcb->local_ip) &&
ip6_addr_lacks_zone(ip_2_ip6(&pcb->local_ip), IP6_UNKNOWN)) {
ip6_addr_select_zone(ip_2_ip6(&pcb->local_ip), ip_2_ip6(&pcb->local_ip));
}
#endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
return ERR_OK;
}
/**
* @ingroup raw_raw
* Bind an RAW PCB to a specific netif.
* After calling this function, all packets received via this PCB
* are guaranteed to have come in via the specified netif, and all
* outgoing packets will go out via the specified netif.
*
* @param pcb RAW PCB to be bound with netif.
* @param netif netif to bind to. Can be NULL.
*
* @see raw_disconnect()
*/
void
raw_bind_netif(struct raw_pcb *pcb, const struct netif *netif)
{
LWIP_ASSERT_CORE_LOCKED();
if (netif != NULL) {
pcb->netif_idx = netif_get_index(netif);
} else {
pcb->netif_idx = NETIF_NO_INDEX;
}
}
/**
* @ingroup raw_raw
* Connect an RAW PCB. This function is required by upper layers
* of lwip. Using the raw api you could use raw_sendto() instead
*
* This will associate the RAW PCB with the remote address.
*
* @param pcb RAW PCB to be connected with remote address ipaddr and port.
* @param ipaddr remote IP address to connect with.
*
* @return lwIP error code
*
* @see raw_disconnect() and raw_sendto()
*/
err_t
raw_connect(struct raw_pcb *pcb, const ip_addr_t *ipaddr)
{
LWIP_ASSERT_CORE_LOCKED();
if ((pcb == NULL) || (ipaddr == NULL)) {
return ERR_VAL;
}
ip_addr_set_ipaddr(&pcb->remote_ip, ipaddr);
#if LWIP_IPV6 && LWIP_IPV6_SCOPES
/* If the given IP address should have a zone but doesn't, assign one now,
* using the bound address to make a more informed decision when possible. */
if (IP_IS_V6(&pcb->remote_ip) &&
ip6_addr_lacks_zone(ip_2_ip6(&pcb->remote_ip), IP6_UNKNOWN)) {
ip6_addr_select_zone(ip_2_ip6(&pcb->remote_ip), ip_2_ip6(&pcb->local_ip));
}
#endif /* LWIP_IPV6 && LWIP_IPV6_SCOPES */
raw_set_flags(pcb, RAW_FLAGS_CONNECTED);
return ERR_OK;
}
/**
* @ingroup raw_raw
* Disconnect a RAW PCB.
*
* @param pcb the raw pcb to disconnect.
*/
void
raw_disconnect(struct raw_pcb *pcb)
{
LWIP_ASSERT_CORE_LOCKED();
/* reset remote address association */
#if LWIP_IPV4 && LWIP_IPV6
if (IP_IS_ANY_TYPE_VAL(pcb->local_ip)) {
ip_addr_copy(pcb->remote_ip, *IP_ANY_TYPE);
} else {
#endif
ip_addr_set_any(IP_IS_V6_VAL(pcb->remote_ip), &pcb->remote_ip);
#if LWIP_IPV4 && LWIP_IPV6
}
#endif
pcb->netif_idx = NETIF_NO_INDEX;
/* mark PCB as unconnected */
raw_clear_flags(pcb, RAW_FLAGS_CONNECTED);
}
/**
* @ingroup raw_raw
* Set the callback function for received packets that match the
* raw PCB's protocol and binding.
*
* The callback function MUST either
* - eat the packet by calling pbuf_free() and returning non-zero. The
* packet will not be passed to other raw PCBs or other protocol layers.
* - not free the packet, and return zero. The packet will be matched
* against further PCBs and/or forwarded to another protocol layers.
*/
void
raw_recv(struct raw_pcb *pcb, raw_recv_fn recv, void *recv_arg)
{
LWIP_ASSERT_CORE_LOCKED();
/* remember recv() callback and user data */
pcb->recv = recv;
pcb->recv_arg = recv_arg;
}
/**
* @ingroup raw_raw
* Send the raw IP packet to the given address. An IP header will be prepended
* to the packet, unless the RAW_FLAGS_HDRINCL flag is set on the PCB. In that
* case, the packet must include an IP header, which will then be sent as is.
*
* @param pcb the raw pcb which to send
* @param p the IP payload to send
* @param ipaddr the destination address of the IP packet
*
*/
err_t
raw_sendto(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *ipaddr)
{
struct netif *netif;
const ip_addr_t *src_ip;
if ((pcb == NULL) || (ipaddr == NULL) || !IP_ADDR_PCB_VERSION_MATCH(pcb, ipaddr)) {
return ERR_VAL;
}
LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE, ("raw_sendto\n"));
if (pcb->netif_idx != NETIF_NO_INDEX) {
netif = netif_get_by_index(pcb->netif_idx);
} else {
#if LWIP_MULTICAST_TX_OPTIONS
netif = NULL;
if (ip_addr_ismulticast(ipaddr)) {
/* For multicast-destined packets, use the user-provided interface index to
* determine the outgoing interface, if an interface index is set and a
* matching netif can be found. Otherwise, fall back to regular routing. */
netif = netif_get_by_index(pcb->mcast_ifindex);
}
if (netif == NULL)
#endif /* LWIP_MULTICAST_TX_OPTIONS */
{
netif = ip_route(&pcb->local_ip, ipaddr);
}
}
if (netif == NULL) {
LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ("raw_sendto: No route to "));
ip_addr_debug_print(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ipaddr);
return ERR_RTE;
}
if (ip_addr_isany(&pcb->local_ip) || ip_addr_ismulticast(&pcb->local_ip)) {
/* use outgoing network interface IP address as source address */
src_ip = ip_netif_get_local_ip(netif, ipaddr);
#if LWIP_IPV6
if (src_ip == NULL) {
return ERR_RTE;
}
#endif /* LWIP_IPV6 */
} else {
/* use RAW PCB local IP address as source address */
src_ip = &pcb->local_ip;
}
return raw_sendto_if_src(pcb, p, ipaddr, netif, src_ip);
}
/**
* @ingroup raw_raw
* Send the raw IP packet to the given address, using a particular outgoing
* netif and source IP address. An IP header will be prepended to the packet,
* unless the RAW_FLAGS_HDRINCL flag is set on the PCB. In that case, the
* packet must include an IP header, which will then be sent as is.
*
* @param pcb RAW PCB used to send the data
* @param p chain of pbufs to be sent
* @param dst_ip destination IP address
* @param netif the netif used for sending
* @param src_ip source IP address
*/
err_t
raw_sendto_if_src(struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *dst_ip,
struct netif *netif, const ip_addr_t *src_ip)
{
err_t err;
struct pbuf *q; /* q will be sent down the stack */
u16_t header_size;
u8_t ttl;
LWIP_ASSERT_CORE_LOCKED();
if ((pcb == NULL) || (dst_ip == NULL) || (netif == NULL) || (src_ip == NULL) ||
!IP_ADDR_PCB_VERSION_MATCH(pcb, src_ip) || !IP_ADDR_PCB_VERSION_MATCH(pcb, dst_ip)) {
return ERR_VAL;
}
header_size = (
#if LWIP_IPV4 && LWIP_IPV6
IP_IS_V6(dst_ip) ? IP6_HLEN : IP_HLEN);
#elif LWIP_IPV4
IP_HLEN);
#else
IP6_HLEN);
#endif
/* Handle the HDRINCL option as an exception: none of the code below applies
* to this case, and sending the packet needs to be done differently too. */
if (pcb->flags & RAW_FLAGS_HDRINCL) {
/* A full header *must* be present in the first pbuf of the chain, as the
* output routines may access its fields directly. */
if (p->len < header_size) {
return ERR_VAL;
}
/* @todo multicast loop support, if at all desired for this scenario.. */
NETIF_SET_HINTS(netif, &pcb->netif_hints);
err = ip_output_if_hdrincl(p, src_ip, dst_ip, netif);
NETIF_RESET_HINTS(netif);
return err;
}
/* packet too large to add an IP header without causing an overflow? */
if ((u16_t)(p->tot_len + header_size) < p->tot_len) {
return ERR_MEM;
}
/* not enough space to add an IP header to first pbuf in given p chain? */
if (pbuf_add_header(p, header_size)) {
/* allocate header in new pbuf */
q = pbuf_alloc(PBUF_IP, 0, PBUF_RAM);
/* new header pbuf could not be allocated? */
if (q == NULL) {
LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("raw_sendto: could not allocate header\n"));
return ERR_MEM;
}
if (p->tot_len != 0) {
/* chain header q in front of given pbuf p */
pbuf_chain(q, p);
}
/* { first pbuf q points to header pbuf } */
LWIP_DEBUGF(RAW_DEBUG, ("raw_sendto: added header pbuf %p before given pbuf %p\n", (void *)q, (void *)p));
} else {
/* first pbuf q equals given pbuf */
q = p;
if (pbuf_remove_header(q, header_size)) {
LWIP_ASSERT("Can't restore header we just removed!", 0);
return ERR_MEM;
}
}
#if IP_SOF_BROADCAST
if (IP_IS_V4(dst_ip)) {
/* broadcast filter? */
if (!ip_get_option(pcb, SOF_BROADCAST) && ip_addr_isbroadcast(dst_ip, netif)) {
LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_LEVEL_WARNING, ("raw_sendto: SOF_BROADCAST not enabled on pcb %p\n", (void *)pcb));
/* free any temporary header pbuf allocated by pbuf_header() */
if (q != p) {
pbuf_free(q);
}
return ERR_VAL;
}
}
#endif /* IP_SOF_BROADCAST */
/* Multicast Loop? */
#if LWIP_MULTICAST_TX_OPTIONS
if (((pcb->flags & RAW_FLAGS_MULTICAST_LOOP) != 0) && ip_addr_ismulticast(dst_ip)) {
q->flags |= PBUF_FLAG_MCASTLOOP;
}
#endif /* LWIP_MULTICAST_TX_OPTIONS */
#if LWIP_IPV6
/* If requested, based on the IPV6_CHECKSUM socket option per RFC3542,
compute the checksum and update the checksum in the payload. */
if (IP_IS_V6(dst_ip) && pcb->chksum_reqd) {
u16_t chksum = ip6_chksum_pseudo(p, pcb->protocol, p->tot_len, ip_2_ip6(src_ip), ip_2_ip6(dst_ip));
LWIP_ASSERT("Checksum must fit into first pbuf", p->len >= (pcb->chksum_offset + 2));
SMEMCPY(((u8_t *)p->payload) + pcb->chksum_offset, &chksum, sizeof(u16_t));
}
#endif
/* Determine TTL to use */
#if LWIP_MULTICAST_TX_OPTIONS
ttl = (ip_addr_ismulticast(dst_ip) ? raw_get_multicast_ttl(pcb) : pcb->ttl);
#else /* LWIP_MULTICAST_TX_OPTIONS */
ttl = pcb->ttl;
#endif /* LWIP_MULTICAST_TX_OPTIONS */
NETIF_SET_HINTS(netif, &pcb->netif_hints);
err = ip_output_if(q, src_ip, dst_ip, ttl, pcb->tos, pcb->protocol, netif);
NETIF_RESET_HINTS(netif);
/* did we chain a header earlier? */
if (q != p) {
/* free the header */
pbuf_free(q);
}
return err;
}
/**
* @ingroup raw_raw
* Send the raw IP packet to the address given by raw_connect()
*
* @param pcb the raw pcb which to send
* @param p the IP payload to send
*
*/
err_t
raw_send(struct raw_pcb *pcb, struct pbuf *p)
{
return raw_sendto(pcb, p, &pcb->remote_ip);
}
/**
* @ingroup raw_raw
* Remove an RAW PCB.
*
* @param pcb RAW PCB to be removed. The PCB is removed from the list of
* RAW PCB's and the data structure is freed from memory.
*
* @see raw_new()
*/
void
raw_remove(struct raw_pcb *pcb)
{
struct raw_pcb *pcb2;
LWIP_ASSERT_CORE_LOCKED();
/* pcb to be removed is first in list? */
if (raw_pcbs == pcb) {
/* make list start at 2nd pcb */
raw_pcbs = raw_pcbs->next;
/* pcb not 1st in list */
} else {
for (pcb2 = raw_pcbs; pcb2 != NULL; pcb2 = pcb2->next) {
/* find pcb in raw_pcbs list */
if (pcb2->next != NULL && pcb2->next == pcb) {
/* remove pcb from list */
pcb2->next = pcb->next;
break;
}
}
}
memp_free(MEMP_RAW_PCB, pcb);
}
/**
* @ingroup raw_raw
* Create a RAW PCB.
*
* @return The RAW PCB which was created. NULL if the PCB data structure
* could not be allocated.
*
* @param proto the protocol number of the IPs payload (e.g. IP_PROTO_ICMP)
*
* @see raw_remove()
*/
struct raw_pcb *
raw_new(u8_t proto)
{
struct raw_pcb *pcb;
LWIP_DEBUGF(RAW_DEBUG | LWIP_DBG_TRACE, ("raw_new\n"));
LWIP_ASSERT_CORE_LOCKED();
pcb = (struct raw_pcb *)memp_malloc(MEMP_RAW_PCB);
/* could allocate RAW PCB? */
if (pcb != NULL) {
/* initialize PCB to all zeroes */
memset(pcb, 0, sizeof(struct raw_pcb));
pcb->protocol = proto;
pcb->ttl = RAW_TTL;
#if LWIP_MULTICAST_TX_OPTIONS
raw_set_multicast_ttl(pcb, RAW_TTL);
#endif /* LWIP_MULTICAST_TX_OPTIONS */
pcb->next = raw_pcbs;
raw_pcbs = pcb;
}
return pcb;
}
/**
* @ingroup raw_raw
* Create a RAW PCB for specific IP type.
*
* @return The RAW PCB which was created. NULL if the PCB data structure
* could not be allocated.
*
* @param type IP address type, see @ref lwip_ip_addr_type definitions.
* If you want to listen to IPv4 and IPv6 (dual-stack) packets,
* supply @ref IPADDR_TYPE_ANY as argument and bind to @ref IP_ANY_TYPE.
* @param proto the protocol number (next header) of the IPv6 packet payload
* (e.g. IP6_NEXTH_ICMP6)
*
* @see raw_remove()
*/
struct raw_pcb *
raw_new_ip_type(u8_t type, u8_t proto)
{
struct raw_pcb *pcb;
LWIP_ASSERT_CORE_LOCKED();
pcb = raw_new(proto);
#if LWIP_IPV4 && LWIP_IPV6
if (pcb != NULL) {
IP_SET_TYPE_VAL(pcb->local_ip, type);
IP_SET_TYPE_VAL(pcb->remote_ip, type);
}
#else /* LWIP_IPV4 && LWIP_IPV6 */
LWIP_UNUSED_ARG(type);
#endif /* LWIP_IPV4 && LWIP_IPV6 */
return pcb;
}
/** This function is called from netif.c when address is changed
*
* @param old_addr IP address of the netif before change
* @param new_addr IP address of the netif after change
*/
void raw_netif_ip_addr_changed(const ip_addr_t *old_addr, const ip_addr_t *new_addr)
{
struct raw_pcb *rpcb;
if (!ip_addr_isany(old_addr) && !ip_addr_isany(new_addr)) {
for (rpcb = raw_pcbs; rpcb != NULL; rpcb = rpcb->next) {
/* PCB bound to current local interface address? */
if (ip_addr_eq(&rpcb->local_ip, old_addr)) {
/* The PCB is bound to the old ipaddr and
* is set to bound to the new one instead */
ip_addr_copy(rpcb->local_ip, *new_addr);
}
}
}
}
#endif /* LWIP_RAW */

View File

@ -1,168 +0,0 @@
/**
* @file
* Statistics 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_STATS /* don't build if not configured for use in lwipopts.h */
#include "lwip/def.h"
#include "lwip/stats.h"
#include "lwip/mem.h"
#include "lwip/debug.h"
#include <string.h>
struct stats_ lwip_stats;
void
stats_init(void)
{
#ifdef LWIP_DEBUG
#if MEM_STATS
lwip_stats.mem.name = "MEM";
#endif /* MEM_STATS */
#endif /* LWIP_DEBUG */
}
#if LWIP_STATS_DISPLAY
void
stats_display_proto(struct stats_proto *proto, const char *name)
{
LWIP_PLATFORM_DIAG(("\n%s\n\t", name));
LWIP_PLATFORM_DIAG(("xmit: %"STAT_COUNTER_F"\n\t", proto->xmit));
LWIP_PLATFORM_DIAG(("recv: %"STAT_COUNTER_F"\n\t", proto->recv));
LWIP_PLATFORM_DIAG(("fw: %"STAT_COUNTER_F"\n\t", proto->fw));
LWIP_PLATFORM_DIAG(("drop: %"STAT_COUNTER_F"\n\t", proto->drop));
LWIP_PLATFORM_DIAG(("chkerr: %"STAT_COUNTER_F"\n\t", proto->chkerr));
LWIP_PLATFORM_DIAG(("lenerr: %"STAT_COUNTER_F"\n\t", proto->lenerr));
LWIP_PLATFORM_DIAG(("memerr: %"STAT_COUNTER_F"\n\t", proto->memerr));
LWIP_PLATFORM_DIAG(("rterr: %"STAT_COUNTER_F"\n\t", proto->rterr));
LWIP_PLATFORM_DIAG(("proterr: %"STAT_COUNTER_F"\n\t", proto->proterr));
LWIP_PLATFORM_DIAG(("opterr: %"STAT_COUNTER_F"\n\t", proto->opterr));
LWIP_PLATFORM_DIAG(("err: %"STAT_COUNTER_F"\n\t", proto->err));
LWIP_PLATFORM_DIAG(("cachehit: %"STAT_COUNTER_F"\n", proto->cachehit));
}
#if IGMP_STATS || MLD6_STATS
void
stats_display_igmp(struct stats_igmp *igmp, const char *name)
{
LWIP_PLATFORM_DIAG(("\n%s\n\t", name));
LWIP_PLATFORM_DIAG(("xmit: %"STAT_COUNTER_F"\n\t", igmp->xmit));
LWIP_PLATFORM_DIAG(("recv: %"STAT_COUNTER_F"\n\t", igmp->recv));
LWIP_PLATFORM_DIAG(("drop: %"STAT_COUNTER_F"\n\t", igmp->drop));
LWIP_PLATFORM_DIAG(("chkerr: %"STAT_COUNTER_F"\n\t", igmp->chkerr));
LWIP_PLATFORM_DIAG(("lenerr: %"STAT_COUNTER_F"\n\t", igmp->lenerr));
LWIP_PLATFORM_DIAG(("memerr: %"STAT_COUNTER_F"\n\t", igmp->memerr));
LWIP_PLATFORM_DIAG(("proterr: %"STAT_COUNTER_F"\n\t", igmp->proterr));
LWIP_PLATFORM_DIAG(("rx_v1: %"STAT_COUNTER_F"\n\t", igmp->rx_v1));
LWIP_PLATFORM_DIAG(("rx_group: %"STAT_COUNTER_F"\n\t", igmp->rx_group));
LWIP_PLATFORM_DIAG(("rx_general: %"STAT_COUNTER_F"\n\t", igmp->rx_general));
LWIP_PLATFORM_DIAG(("rx_report: %"STAT_COUNTER_F"\n\t", igmp->rx_report));
LWIP_PLATFORM_DIAG(("tx_join: %"STAT_COUNTER_F"\n\t", igmp->tx_join));
LWIP_PLATFORM_DIAG(("tx_leave: %"STAT_COUNTER_F"\n\t", igmp->tx_leave));
LWIP_PLATFORM_DIAG(("tx_report: %"STAT_COUNTER_F"\n", igmp->tx_report));
}
#endif /* IGMP_STATS || MLD6_STATS */
#if MEM_STATS || MEMP_STATS
void
stats_display_mem(struct stats_mem *mem, const char *name)
{
LWIP_PLATFORM_DIAG(("\nMEM %s\n\t", name));
LWIP_PLATFORM_DIAG(("avail: %"MEM_SIZE_F"\n\t", mem->avail));
LWIP_PLATFORM_DIAG(("used: %"MEM_SIZE_F"\n\t", mem->used));
LWIP_PLATFORM_DIAG(("max: %"MEM_SIZE_F"\n\t", mem->max));
LWIP_PLATFORM_DIAG(("err: %"STAT_COUNTER_F"\n", mem->err));
}
#if MEMP_STATS
void
stats_display_memp(struct stats_mem *mem, int idx)
{
if (idx < MEMP_MAX) {
stats_display_mem(mem, mem->name);
}
}
#endif /* MEMP_STATS */
#endif /* MEM_STATS || MEMP_STATS */
#if SYS_STATS
void
stats_display_sys(struct stats_sys *sys)
{
LWIP_PLATFORM_DIAG(("\nSYS\n\t"));
LWIP_PLATFORM_DIAG(("sem.used: %"STAT_COUNTER_F"\n\t", sys->sem.used));
LWIP_PLATFORM_DIAG(("sem.max: %"STAT_COUNTER_F"\n\t", sys->sem.max));
LWIP_PLATFORM_DIAG(("sem.err: %"STAT_COUNTER_F"\n\t", sys->sem.err));
LWIP_PLATFORM_DIAG(("mutex.used: %"STAT_COUNTER_F"\n\t", sys->mutex.used));
LWIP_PLATFORM_DIAG(("mutex.max: %"STAT_COUNTER_F"\n\t", sys->mutex.max));
LWIP_PLATFORM_DIAG(("mutex.err: %"STAT_COUNTER_F"\n\t", sys->mutex.err));
LWIP_PLATFORM_DIAG(("mbox.used: %"STAT_COUNTER_F"\n\t", sys->mbox.used));
LWIP_PLATFORM_DIAG(("mbox.max: %"STAT_COUNTER_F"\n\t", sys->mbox.max));
LWIP_PLATFORM_DIAG(("mbox.err: %"STAT_COUNTER_F"\n", sys->mbox.err));
}
#endif /* SYS_STATS */
void
stats_display(void)
{
s16_t i;
LINK_STATS_DISPLAY();
ETHARP_STATS_DISPLAY();
IPFRAG_STATS_DISPLAY();
IP6_FRAG_STATS_DISPLAY();
IP_STATS_DISPLAY();
ND6_STATS_DISPLAY();
IP6_STATS_DISPLAY();
IGMP_STATS_DISPLAY();
MLD6_STATS_DISPLAY();
ICMP_STATS_DISPLAY();
ICMP6_STATS_DISPLAY();
UDP_STATS_DISPLAY();
TCP_STATS_DISPLAY();
MEM_STATS_DISPLAY();
for (i = 0; i < MEMP_MAX; i++) {
MEMP_STATS_DISPLAY(i);
}
SYS_STATS_DISPLAY();
}
#endif /* LWIP_STATS_DISPLAY */
#endif /* LWIP_STATS */

View File

@ -1,148 +0,0 @@
/**
* @file
* lwIP Operating System abstraction
*
*/
/*
* 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>
*
*/
/**
* @defgroup sys_layer Porting (system abstraction layer)
* @ingroup lwip
*
* @defgroup sys_os OS abstraction layer
* @ingroup sys_layer
* No need to implement functions in this section in NO_SYS mode.
* The OS-specific code should be implemented in arch/sys_arch.h
* and sys_arch.c of your port.
*
* The operating system emulation layer provides a common interface
* between the lwIP code and the underlying operating system kernel. The
* general idea is that porting lwIP to new architectures requires only
* small changes to a few header files and a new sys_arch
* implementation. It is also possible to do a sys_arch implementation
* that does not rely on any underlying operating system.
*
* The sys_arch provides semaphores, mailboxes and mutexes to lwIP. For the full
* lwIP functionality, multiple threads support can be implemented in the
* sys_arch, but this is not required for the basic lwIP
* functionality. Timer scheduling is implemented in lwIP, but can be implemented
* by the sys_arch port (LWIP_TIMERS_CUSTOM==1).
*
* In addition to the source file providing the functionality of sys_arch,
* the OS emulation layer must provide several header files defining
* macros used throughout lwip. The files required and the macros they
* must define are listed below the sys_arch description.
*
* Since lwIP 1.4.0, semaphore, mutexes and mailbox functions are prototyped in a way that
* allows both using pointers or actual OS structures to be used. This way, memory
* required for such types can be either allocated in place (globally or on the
* stack) or on the heap (allocated internally in the "*_new()" functions).
*
* Note:
* -----
* Be careful with using mem_malloc() in sys_arch. When malloc() refers to
* mem_malloc() you can run into a circular function call problem. In mem.c
* mem_init() tries to allocate a semaphore using mem_malloc, which of course
* can't be performed when sys_arch uses mem_malloc.
*
* @defgroup sys_sem Semaphores
* @ingroup sys_os
* Semaphores can be either counting or binary - lwIP works with both
* kinds.
* Semaphores are represented by the type "sys_sem_t" which is typedef'd
* in the sys_arch.h file. Mailboxes are equivalently represented by the
* type "sys_mbox_t". Mutexes are represented by the type "sys_mutex_t".
* lwIP does not place any restrictions on how these types are represented
* internally.
*
* @defgroup sys_mutex Mutexes
* @ingroup sys_os
* Mutexes are recommended to correctly handle priority inversion,
* especially if you use LWIP_CORE_LOCKING .
*
* @defgroup sys_mbox Mailboxes
* @ingroup sys_os
* Mailboxes should be implemented as a queue which allows multiple messages
* to be posted (implementing as a rendez-vous point where only one message can be
* posted at a time can have a highly negative impact on performance). A message
* in a mailbox is just a pointer, nothing more.
*
* @defgroup sys_time Time
* @ingroup sys_layer
*
* @defgroup sys_prot Critical sections
* @ingroup sys_layer
* Used to protect short regions of code against concurrent access.
* - Your system is a bare-metal system (probably with an RTOS)
* and interrupts are under your control:
* Implement this as LockInterrupts() / UnlockInterrupts()
* - Your system uses an RTOS with deferred interrupt handling from a
* worker thread: Implement as a global mutex or lock/unlock scheduler
* - Your system uses a high-level OS with e.g. POSIX signals:
* Implement as a global mutex
*
* @defgroup sys_misc Misc
* @ingroup sys_os
*/
#include "lwip/opt.h"
#include "lwip/sys.h"
/* Most of the functions defined in sys.h must be implemented in the
* architecture-dependent file sys_arch.c */
#if !NO_SYS
#ifndef sys_msleep
/**
* Sleep for some ms. Timeouts are NOT processed while sleeping.
*
* @param ms number of milliseconds to sleep
*/
void
sys_msleep(u32_t ms)
{
if (ms > 0) {
sys_sem_t delaysem;
err_t err = sys_sem_new(&delaysem, 0);
if (err == ERR_OK) {
sys_arch_sem_wait(&delaysem, ms);
sys_sem_free(&delaysem);
}
}
}
#endif /* sys_msleep */
#endif /* !NO_SYS */

View File

@ -1,320 +0,0 @@
#include "sys.h"
#include <nds.h>
//
// Misc
//
//int errno;
void __attribute__((weak)) sys_init(void)
{
}
//
// Time
//
static vu32 val = 0;
void sys_now_inc(u32 amt)
{
val += amt;
}
u32_t
sys_now(void)
{
return val;
}
//
// Threading
//
#define MBOX_VAL_EMPTY (0x12345678)
#define MBOX_VAL_INVALID (0x12345679)
#define SEM_SIGNAL (0x12345678)
#define MTX_LOCKED (0x12345678)
err_t __attribute__((weak)) sys_mutex_new(sys_mutex_t *mutex)
{
*mutex = 0xFFFFFFFF;
return ERR_OK;
}
void __attribute__((weak)) sys_mutex_lock(sys_mutex_t *mutex)
{
if (!mutex) return;
if (!*mutex)
*mutex = 0xFFFFFFFF;
//wifi_printlnf("lock %p %x %x", mutex, *mutex, getCPSR() & 0x1F);
if ((getCPSR() & 0x1F) == 0x1F)
{
while (1)
{
if (*mutex == 0xFFFFFFFF) break;
}
}
*mutex = MTX_LOCKED;
}
void __attribute__((weak)) sys_mutex_unlock(sys_mutex_t *mutex)
{
if (!mutex) return;
//wifi_printlnf("unlock %p %x %x", mutex, *mutex, getCPSR() & 0x1F);
//if (*mutex == MTX_LOCKED)
*mutex = 0xFFFFFFFF;
}
void __attribute__((weak)) sys_mutex_free(sys_mutex_t *mutex)
{
if (!mutex) return;
*mutex = 0;
}
int __attribute__((weak)) sys_mutex_valid(sys_mutex_t *mutex)
{
return !!(mutex);
}
void __attribute__((weak)) sys_mutex_set_invalid(sys_mutex_t *mutex)
{
if (!mutex) return;
*mutex = 0;
}
err_t __attribute__((weak)) sys_sem_new(sys_sem_t *sem, u8_t count)
{
*sem = 0xFFFFFFFF;
return ERR_OK;
}
void __attribute__((weak)) sys_sem_signal(sys_sem_t *sem)
{
//wifi_printf("sem signal %p...\n", sem);
//while (*sem != 0xFFFFFFFF)
{
//wifi_printf("sem signal %p...\n", sem);
}
//wifi_printf("sem signal %p done\n", sem);
*sem = SEM_SIGNAL;
}
u32_t __attribute__((weak)) sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout)
{
//wifi_printf("sem wait %p...\n", sem);
if (!timeout)
{
//while (*sem != SEM_SIGNAL);
timeout = 1000;
while (timeout != 0)
{
if (*sem == SEM_SIGNAL) break;
sys_msleep(1);
timeout--;
}
if (*sem != SEM_SIGNAL)
return SYS_ARCH_TIMEOUT;
}
else
{
while (timeout != 0)
{
if (*sem == SEM_SIGNAL) break;
sys_msleep(1);
timeout--;
}
if (*sem != SEM_SIGNAL)
return SYS_ARCH_TIMEOUT;
}
//wifi_printf("sem got %p\n", sem);
*sem = 0xFFFFFFFF;
return 1;
}
void __attribute__((weak)) sys_sem_free(sys_sem_t *sem)
{
*sem = 0;
}
int __attribute__((weak)) sys_sem_valid(sys_sem_t *sem)
{
return !!(sem);
}
void __attribute__((weak)) sys_sem_set_invalid(sys_sem_t *sem)
{
*sem = 0;
}
void __attribute__((weak)) sys_msleep(u32_t ms)
{
vu32 target = val + ms;
// edge case, overflow
if (val > target) return;
// Don't do this in an IRQ
if ((getCPSR() & 0x1F) == 0x1F)
{
while (val < target) ;
}
}
err_t __attribute__((weak)) sys_mbox_new(sys_mbox_t *mbox, int size)
{
if (!mbox) return ERR_MEM;
*mbox = MBOX_VAL_EMPTY;
return ERR_OK;
}
void __attribute__((weak)) sys_mbox_post(sys_mbox_t *mbox, void *msg)
{
if (!mbox || *mbox == MBOX_VAL_INVALID) return;
while (*mbox != MBOX_VAL_EMPTY)
{
//wifi_printlnf("wait post");
}
/*if (*mbox == MBOX_VAL_INVALID)
{
wifi_printlnf("invalid invalid");
*mbox = 0xAAAAAAAA;
return;
}*/
*mbox = (uint32_t)msg;
}
err_t __attribute__((weak)) sys_mbox_trypost(sys_mbox_t *mbox, void *msg)
{
if (!mbox || *mbox == MBOX_VAL_INVALID) return ERR_MEM;
if (*mbox != MBOX_VAL_EMPTY)
{
//wifi_printlnf("invalid invalid 2--");
//*mbox = 0xAAAAAAAA;
return ERR_MEM;
}
//wifi_printlnf("put %x", msg);
/*if (*mbox == MBOX_VAL_INVALID)
{
wifi_printlnf("invalid invalid 2");
*mbox = 0xAAAAAAAA;
return ERR_MEM;
}*/
*mbox = (uint32_t)msg;
return ERR_OK;
}
err_t __attribute__((weak)) sys_mbox_trypost_fromisr(sys_mbox_t *mbox, void *msg)
{
if (!mbox || *mbox == MBOX_VAL_INVALID) return ERR_MEM;
if (*mbox != MBOX_VAL_EMPTY)
{
return ERR_MEM;
}
/*if (*mbox == MBOX_VAL_INVALID)
{
wifi_printlnf("invalid invalid 3");
*mbox = 0xAAAAAAAA;
return ERR_MEM;
}*/
*mbox = (uint32_t)msg;
return ERR_OK;
}
u32_t __attribute__((weak)) sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout)
{
if (!mbox || *mbox == MBOX_VAL_INVALID) return SYS_ARCH_TIMEOUT;
*msg = NULL;
if (!timeout)
{
while (*mbox == MBOX_VAL_EMPTY)
{
//wifi_printlnf("wait mbox %x", *mbox);
;
}
}
else
{
while (timeout != 0)
{
if (*mbox != MBOX_VAL_EMPTY) break;
sys_msleep(1);
timeout--;
}
if (*mbox == MBOX_VAL_EMPTY)
return SYS_ARCH_TIMEOUT;
}
*msg = (void*)(*mbox);
*mbox = MBOX_VAL_EMPTY;
//
return 0;
}
u32_t __attribute__((weak)) sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg)
{
if (!mbox || *mbox == MBOX_VAL_INVALID) return SYS_MBOX_EMPTY;
if (*mbox == MBOX_VAL_EMPTY)
{
*msg = NULL;
return SYS_MBOX_EMPTY;
}
*msg = (void*)(*mbox);
*mbox = MBOX_VAL_EMPTY;
return 0;
}
void __attribute__((weak)) sys_mbox_free(sys_mbox_t *mbox)
{
if (!mbox) return;
*mbox = MBOX_VAL_INVALID;
}
int __attribute__((weak)) sys_mbox_valid(sys_mbox_t *mbox)
{
if (!mbox) return 0;
return (*mbox != MBOX_VAL_INVALID);
}
void __attribute__((weak)) sys_mbox_set_invalid(sys_mbox_t *mbox)
{
*mbox = MBOX_VAL_INVALID;
}
sys_thread_t __attribute__((weak)) sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio)
{
return 0;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,451 +0,0 @@
/**
* @file
* Stack-internal timers implementation.
* This file includes timer callbacks for stack-internal timers as well as
* functions to set up or stop timers and check for expired timers.
*
*/
/*
* 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>
* Simon Goldschmidt
*
*/
#include "lwip/opt.h"
#include "lwip/timeouts.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/def.h"
#include "lwip/memp.h"
#include "lwip/priv/tcpip_priv.h"
#include "lwip/ip4_frag.h"
#include "lwip/etharp.h"
#include "lwip/dhcp.h"
#include "lwip/acd.h"
#include "lwip/igmp.h"
#include "lwip/dns.h"
#include "lwip/nd6.h"
#include "lwip/ip6_frag.h"
#include "lwip/mld6.h"
#include "lwip/dhcp6.h"
#include "lwip/sys.h"
#include "lwip/pbuf.h"
#if LWIP_DEBUG_TIMERNAMES
#define HANDLER(x) x, #x
#else /* LWIP_DEBUG_TIMERNAMES */
#define HANDLER(x) x
#endif /* LWIP_DEBUG_TIMERNAMES */
#define LWIP_MAX_TIMEOUT 0x7fffffff
/* Check if timer's expiry time is greater than time and care about u32_t wraparounds */
#define TIME_LESS_THAN(t, compare_to) ( (((u32_t)((t)-(compare_to))) > LWIP_MAX_TIMEOUT) ? 1 : 0 )
/** This array contains all stack-internal cyclic timers. To get the number of
* timers, use LWIP_ARRAYSIZE() */
const struct lwip_cyclic_timer lwip_cyclic_timers[] = {
#if LWIP_TCP
/* The TCP timer is a special case: it does not have to run always and
is triggered to start from TCP using tcp_timer_needed() */
{TCP_TMR_INTERVAL, HANDLER(tcp_tmr)},
#endif /* LWIP_TCP */
#if LWIP_IPV4
#if IP_REASSEMBLY
{IP_TMR_INTERVAL, HANDLER(ip_reass_tmr)},
#endif /* IP_REASSEMBLY */
#if LWIP_ARP
{ARP_TMR_INTERVAL, HANDLER(etharp_tmr)},
#endif /* LWIP_ARP */
#if LWIP_DHCP
{DHCP_COARSE_TIMER_MSECS, HANDLER(dhcp_coarse_tmr)},
{DHCP_FINE_TIMER_MSECS, HANDLER(dhcp_fine_tmr)},
#endif /* LWIP_DHCP */
#if LWIP_ACD
{ACD_TMR_INTERVAL, HANDLER(acd_tmr)},
#endif /* LWIP_ACD */
#if LWIP_IGMP
{IGMP_TMR_INTERVAL, HANDLER(igmp_tmr)},
#endif /* LWIP_IGMP */
#endif /* LWIP_IPV4 */
#if LWIP_DNS
{DNS_TMR_INTERVAL, HANDLER(dns_tmr)},
#endif /* LWIP_DNS */
#if LWIP_IPV6
{ND6_TMR_INTERVAL, HANDLER(nd6_tmr)},
#if LWIP_IPV6_REASS
{IP6_REASS_TMR_INTERVAL, HANDLER(ip6_reass_tmr)},
#endif /* LWIP_IPV6_REASS */
#if LWIP_IPV6_MLD
{MLD6_TMR_INTERVAL, HANDLER(mld6_tmr)},
#endif /* LWIP_IPV6_MLD */
#if LWIP_IPV6_DHCP6
{DHCP6_TIMER_MSECS, HANDLER(dhcp6_tmr)},
#endif /* LWIP_IPV6_DHCP6 */
#endif /* LWIP_IPV6 */
};
const int lwip_num_cyclic_timers = LWIP_ARRAYSIZE(lwip_cyclic_timers);
#if LWIP_TIMERS && !LWIP_TIMERS_CUSTOM
/** The one and only timeout list */
static struct sys_timeo *next_timeout;
static u32_t current_timeout_due_time;
#if LWIP_TESTMODE
struct sys_timeo**
sys_timeouts_get_next_timeout(void)
{
return &next_timeout;
}
#endif
#if LWIP_TCP
/** global variable that shows if the tcp timer is currently scheduled or not */
static int tcpip_tcp_timer_active;
/**
* Timer callback function that calls tcp_tmr() and reschedules itself.
*
* @param arg unused argument
*/
static void
tcpip_tcp_timer(void *arg)
{
LWIP_UNUSED_ARG(arg);
/* call TCP timer handler */
tcp_tmr();
/* timer still needed? */
if (tcp_active_pcbs || tcp_tw_pcbs) {
/* restart timer */
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
} else {
/* disable timer */
tcpip_tcp_timer_active = 0;
}
}
/**
* Called from TCP_REG when registering a new PCB:
* the reason is to have the TCP timer only running when
* there are active (or time-wait) PCBs.
*/
void
tcp_timer_needed(void)
{
LWIP_ASSERT_CORE_LOCKED();
/* timer is off but needed again? */
if (!tcpip_tcp_timer_active && (tcp_active_pcbs || tcp_tw_pcbs)) {
/* enable and start timer */
tcpip_tcp_timer_active = 1;
sys_timeout(TCP_TMR_INTERVAL, tcpip_tcp_timer, NULL);
}
}
#endif /* LWIP_TCP */
static void
#if LWIP_DEBUG_TIMERNAMES
sys_timeout_abs(u32_t abs_time, sys_timeout_handler handler, void *arg, const char *handler_name)
#else /* LWIP_DEBUG_TIMERNAMES */
sys_timeout_abs(u32_t abs_time, sys_timeout_handler handler, void *arg)
#endif
{
struct sys_timeo *timeout, *t;
timeout = (struct sys_timeo *)memp_malloc(MEMP_SYS_TIMEOUT);
if (timeout == NULL) {
LWIP_ASSERT("sys_timeout: timeout != NULL, pool MEMP_SYS_TIMEOUT is empty", timeout != NULL);
return;
}
timeout->next = NULL;
timeout->h = handler;
timeout->arg = arg;
timeout->time = abs_time;
#if LWIP_DEBUG_TIMERNAMES
timeout->handler_name = handler_name;
LWIP_DEBUGF(TIMERS_DEBUG, ("sys_timeout: %p abs_time=%"U32_F" handler=%s arg=%p\n",
(void *)timeout, abs_time, handler_name, (void *)arg));
#endif /* LWIP_DEBUG_TIMERNAMES */
if (next_timeout == NULL) {
next_timeout = timeout;
return;
}
if (TIME_LESS_THAN(timeout->time, next_timeout->time)) {
timeout->next = next_timeout;
next_timeout = timeout;
} else {
for (t = next_timeout; t != NULL; t = t->next) {
if ((t->next == NULL) || TIME_LESS_THAN(timeout->time, t->next->time)) {
timeout->next = t->next;
t->next = timeout;
break;
}
}
}
}
/**
* Timer callback function that calls cyclic->handler() and reschedules itself.
*
* @param arg unused argument
*/
#if !LWIP_TESTMODE
static
#endif
void
lwip_cyclic_timer(void *arg)
{
u32_t now;
u32_t next_timeout_time;
const struct lwip_cyclic_timer *cyclic = (const struct lwip_cyclic_timer *)arg;
#if LWIP_DEBUG_TIMERNAMES
LWIP_DEBUGF(TIMERS_DEBUG, ("tcpip: %s()\n", cyclic->handler_name));
#endif
cyclic->handler();
now = sys_now();
next_timeout_time = (u32_t)(current_timeout_due_time + cyclic->interval_ms); /* overflow handled by TIME_LESS_THAN macro */
if (TIME_LESS_THAN(next_timeout_time, now)) {
/* timer would immediately expire again -> "overload" -> restart without any correction */
#if LWIP_DEBUG_TIMERNAMES
sys_timeout_abs((u32_t)(now + cyclic->interval_ms), lwip_cyclic_timer, arg, cyclic->handler_name);
#else
sys_timeout_abs((u32_t)(now + cyclic->interval_ms), lwip_cyclic_timer, arg);
#endif
} else {
/* correct cyclic interval with handler execution delay and sys_check_timeouts jitter */
#if LWIP_DEBUG_TIMERNAMES
sys_timeout_abs(next_timeout_time, lwip_cyclic_timer, arg, cyclic->handler_name);
#else
sys_timeout_abs(next_timeout_time, lwip_cyclic_timer, arg);
#endif
}
}
/** Initialize this module */
void sys_timeouts_init(void)
{
size_t i;
/* tcp_tmr() at index 0 is started on demand */
for (i = (LWIP_TCP ? 1 : 0); i < LWIP_ARRAYSIZE(lwip_cyclic_timers); i++) {
/* we have to cast via size_t to get rid of const warning
(this is OK as cyclic_timer() casts back to const* */
sys_timeout(lwip_cyclic_timers[i].interval_ms, lwip_cyclic_timer, LWIP_CONST_CAST(void *, &lwip_cyclic_timers[i]));
}
}
/**
* Create a one-shot timer (aka timeout). Timeouts are processed in the
* following cases:
* - while waiting for a message using sys_timeouts_mbox_fetch()
* - by calling sys_check_timeouts() (NO_SYS==1 only)
*
* @param msecs time in milliseconds after that the timer should expire
* @param handler callback function to call when msecs have elapsed
* @param arg argument to pass to the callback function
*/
#if LWIP_DEBUG_TIMERNAMES
void
sys_timeout_debug(u32_t msecs, sys_timeout_handler handler, void *arg, const char *handler_name)
#else /* LWIP_DEBUG_TIMERNAMES */
void
sys_timeout(u32_t msecs, sys_timeout_handler handler, void *arg)
#endif /* LWIP_DEBUG_TIMERNAMES */
{
u32_t next_timeout_time;
LWIP_ASSERT_CORE_LOCKED();
LWIP_ASSERT("Timeout time too long, max is LWIP_UINT32_MAX/4 msecs", msecs <= (LWIP_UINT32_MAX / 4));
next_timeout_time = (u32_t)(sys_now() + msecs); /* overflow handled by TIME_LESS_THAN macro */
#if LWIP_DEBUG_TIMERNAMES
sys_timeout_abs(next_timeout_time, handler, arg, handler_name);
#else
sys_timeout_abs(next_timeout_time, handler, arg);
#endif
}
/**
* Go through timeout list (for this task only) and remove the first matching
* entry (subsequent entries remain untouched), even though the timeout has not
* triggered yet.
*
* @param handler callback function that would be called by the timeout
* @param arg callback argument that would be passed to handler
*/
void
sys_untimeout(sys_timeout_handler handler, void *arg)
{
struct sys_timeo *prev_t, *t;
LWIP_ASSERT_CORE_LOCKED();
if (next_timeout == NULL) {
return;
}
for (t = next_timeout, prev_t = NULL; t != NULL; prev_t = t, t = t->next) {
if ((t->h == handler) && (t->arg == arg)) {
/* We have a match */
/* Unlink from previous in list */
if (prev_t == NULL) {
next_timeout = t->next;
} else {
prev_t->next = t->next;
}
memp_free(MEMP_SYS_TIMEOUT, t);
return;
}
}
return;
}
/**
* @ingroup lwip_nosys
* Handle timeouts for NO_SYS==1 (i.e. without using
* tcpip_thread/sys_timeouts_mbox_fetch(). Uses sys_now() to call timeout
* handler functions when timeouts expire.
*
* Must be called periodically from your main loop.
*/
void
sys_check_timeouts(void)
{
u32_t now;
LWIP_ASSERT_CORE_LOCKED();
/* Process only timers expired at the start of the function. */
now = sys_now();
do {
struct sys_timeo *tmptimeout;
sys_timeout_handler handler;
void *arg;
PBUF_CHECK_FREE_OOSEQ();
tmptimeout = next_timeout;
if (tmptimeout == NULL) {
return;
}
if (TIME_LESS_THAN(now, tmptimeout->time)) {
return;
}
/* Timeout has expired */
next_timeout = tmptimeout->next;
handler = tmptimeout->h;
arg = tmptimeout->arg;
current_timeout_due_time = tmptimeout->time;
#if LWIP_DEBUG_TIMERNAMES
if (handler != NULL) {
LWIP_DEBUGF(TIMERS_DEBUG, ("sct calling h=%s t=%"U32_F" arg=%p\n",
tmptimeout->handler_name, sys_now() - tmptimeout->time, arg));
}
#endif /* LWIP_DEBUG_TIMERNAMES */
memp_free(MEMP_SYS_TIMEOUT, tmptimeout);
if (handler != NULL) {
handler(arg);
}
LWIP_TCPIP_THREAD_ALIVE();
/* Repeat until all expired timers have been called */
} while (1);
}
/** Rebase the timeout times to the current time.
* This is necessary if sys_check_timeouts() hasn't been called for a long
* time (e.g. while saving energy) to prevent all timer functions of that
* period being called.
*/
void
sys_restart_timeouts(void)
{
u32_t now;
u32_t base;
struct sys_timeo *t;
if (next_timeout == NULL) {
return;
}
now = sys_now();
base = next_timeout->time;
for (t = next_timeout; t != NULL; t = t->next) {
t->time = (t->time - base) + now;
}
}
/** Return the time left before the next timeout is due. If no timeouts are
* enqueued, returns 0xffffffff
*/
u32_t
sys_timeouts_sleeptime(void)
{
u32_t now;
LWIP_ASSERT_CORE_LOCKED();
if (next_timeout == NULL) {
return SYS_TIMEOUTS_SLEEPTIME_INFINITE;
}
now = sys_now();
if (TIME_LESS_THAN(next_timeout->time, now)) {
return 0;
} else {
u32_t ret = (u32_t)(next_timeout->time - now);
LWIP_ASSERT("invalid sleeptime", ret <= LWIP_MAX_TIMEOUT);
return ret;
}
}
#else /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */
/* Satisfy the TCP code which calls this function */
void
tcp_timer_needed(void)
{
}
#endif /* LWIP_TIMERS && !LWIP_TIMERS_CUSTOM */

Some files were not shown because too many files have changed in this diff Show More