From 9a5b3d8918048087319481b680506488ca9f2b0f Mon Sep 17 00:00:00 2001 From: Eric Pooch Date: Mon, 12 Mar 2018 21:40:46 -0700 Subject: [PATCH] Support for Macintosh System 1.1 on 128K Macintosh This port of lwip adds support for 128K Macintosh with the original 64K ROMs running System 1.1 or later. Modem port must be connected to a server running pppd at 9600 baud. --- .gitignore | 4 + apps/httpserver_raw/fs orig.c | 1 + apps/httpserver_raw/fs.c | 181 +- apps/httpserver_raw/fs.h | 141 +- apps/httpserver_raw/fsdata.h | 51 +- apps/httpserver_raw/httpd.c | 2534 +------------------------- apps/httpserver_raw/httpd.h | 245 +-- apps/httpserver_raw/httpd.orig.c | 2533 +++++++++++++++++++++++++ apps/httpserver_raw/httpd_structs.h | 120 +- head_support.h.patch | 15 + head_support.patch | 311 ++++ ports/mac/ElWhip.c | 1 + ports/mac/ElWhip.h | 1 + ports/mac/ElWhip.r | 1 + ports/mac/ElWhip_ICN.rsrc | 0 ports/mac/Makefile | 1 + ports/mac/include/arch/cc.h | 115 ++ ports/mac/include/arch/macos_debug.h | 1 + ports/mac/include/arch/perf.h | 50 + ports/mac/include/arch/sys_arch.h | 43 + ports/mac/include/fsdata_custom.c | 1 + ports/mac/include/lwipopts-SLIP.h | 1332 ++++++++++++++ ports/mac/include/lwipopts.h | 1364 ++++++++++++++ ports/mac/mac_httpd_ssi.c | 11 + ports/mac/mac_httpd_ssi.h | 9 + ports/mac/sio.c | 400 ++++ ports/mac/sys_arch.c | 139 ++ ports/mac/test.c | 1 + ports/mac/test.h | 1 + ports/mac/www/img/mac_hello.gif | Bin 0 -> 2400 bytes ports/mac/www/index.html | 49 + 31 files changed, 6390 insertions(+), 3266 deletions(-) create mode 100644 apps/httpserver_raw/fs orig.c create mode 100644 apps/httpserver_raw/httpd.orig.c create mode 100644 head_support.h.patch create mode 100644 head_support.patch create mode 100644 ports/mac/ElWhip.c create mode 100644 ports/mac/ElWhip.h create mode 100644 ports/mac/ElWhip.r create mode 100644 ports/mac/ElWhip_ICN.rsrc create mode 100644 ports/mac/Makefile create mode 100644 ports/mac/include/arch/cc.h create mode 100644 ports/mac/include/arch/macos_debug.h create mode 100644 ports/mac/include/arch/perf.h create mode 100644 ports/mac/include/arch/sys_arch.h create mode 100644 ports/mac/include/fsdata_custom.c create mode 100644 ports/mac/include/lwipopts-SLIP.h create mode 100644 ports/mac/include/lwipopts.h create mode 100644 ports/mac/mac_httpd_ssi.c create mode 100644 ports/mac/mac_httpd_ssi.h create mode 100644 ports/mac/sio.c create mode 100644 ports/mac/sys_arch.c create mode 100644 ports/mac/test.c create mode 100644 ports/mac/test.h create mode 100644 ports/mac/www/img/mac_hello.gif create mode 100644 ports/mac/www/index.html diff --git a/.gitignore b/.gitignore index c39fe30..c8da1ca 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ +.DS_Store +*.o +/ports/mac/ElWhip-HTTPD +/ports/mac/ElWhip\ 0.* /ports/win32/msvc/Debug /ports/win32/lwipcfg_msvc.h /ports/win32/msvc/Debug unittests diff --git a/apps/httpserver_raw/fs orig.c b/apps/httpserver_raw/fs orig.c new file mode 100644 index 0000000..9e655bb --- /dev/null +++ b/apps/httpserver_raw/fs orig.c @@ -0,0 +1 @@ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #include "lwip/opt.h" #include "lwip/def.h" #include "fs.h" #include "fsdata.h" #include /** Set this to 1 to include "fsdata_custom.c" instead of "fsdata.c" for the * file system (to prevent changing the file included in CVS) */ #ifndef HTTPD_USE_CUSTOM_FSDATA #define HTTPD_USE_CUSTOM_FSDATA 0 #endif #if HTTPD_USE_CUSTOM_FSDATA #include "fsdata_custom.c" #else /* HTTPD_USE_CUSTOM_FSDATA */ #include "fsdata.c" #endif /* HTTPD_USE_CUSTOM_FSDATA */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_CUSTOM_FILES int fs_open_custom(struct fs_file *file, const char *name); void fs_close_custom(struct fs_file *file); #if LWIP_HTTPD_FS_ASYNC_READ u8_t fs_canread_custom(struct fs_file *file); u8_t fs_wait_read_custom(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #endif /* LWIP_HTTPD_CUSTOM_FILES */ /*-----------------------------------------------------------------------------------*/ err_t fs_open(struct fs_file *file, const char *name) { const struct fsdata_file *f; if ((file == NULL) || (name == NULL)) { return ERR_ARG; } #if LWIP_HTTPD_CUSTOM_FILES if (fs_open_custom(file, name)) { file->is_custom_file = 1; return ERR_OK; } file->is_custom_file = 0; #endif /* LWIP_HTTPD_CUSTOM_FILES */ for (f = FS_ROOT; f != NULL; f = f->next) { if (!strcmp(name, (char *)f->name)) { file->data = (const char *)f->data; file->len = f->len; file->index = f->len; file->pextension = NULL; file->http_header_included = f->http_header_included; #if HTTPD_PRECALCULATED_CHECKSUM file->chksum_count = f->chksum_count; file->chksum = f->chksum; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ #if LWIP_HTTPD_FILE_STATE file->state = fs_state_init(file, name); #endif /* #if LWIP_HTTPD_FILE_STATE */ return ERR_OK; } } /* file not found */ return ERR_VAL; } /*-----------------------------------------------------------------------------------*/ void fs_close(struct fs_file *file) { #if LWIP_HTTPD_CUSTOM_FILES if (file->is_custom_file) { fs_close_custom(file); } #endif /* LWIP_HTTPD_CUSTOM_FILES */ #if LWIP_HTTPD_FILE_STATE fs_state_free(file, file->state); #endif /* #if LWIP_HTTPD_FILE_STATE */ LWIP_UNUSED_ARG(file); } /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_DYNAMIC_FILE_READ #if LWIP_HTTPD_FS_ASYNC_READ int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg) #else /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_read(struct fs_file *file, char *buffer, int count) #endif /* LWIP_HTTPD_FS_ASYNC_READ */ { int read; if(file->index == file->len) { return FS_READ_EOF; } #if LWIP_HTTPD_FS_ASYNC_READ #if LWIP_HTTPD_CUSTOM_FILES if (!fs_canread_custom(file)) { if (fs_wait_read_custom(file, callback_fn, callback_arg)) { return FS_READ_DELAYED; } } #else /* LWIP_HTTPD_CUSTOM_FILES */ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_CUSTOM_FILES */ #endif /* LWIP_HTTPD_FS_ASYNC_READ */ read = file->len - file->index; if(read > count) { read = count; } MEMCPY(buffer, (file->data + file->index), read); file->index += read; return(read); } #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_FS_ASYNC_READ int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg) { if (file != NULL) { #if LWIP_HTTPD_FS_ASYNC_READ #if LWIP_HTTPD_CUSTOM_FILES if (!fs_canread_custom(file)) { if (fs_wait_read_custom(file, callback_fn, callback_arg)) { return 0; } } #else /* LWIP_HTTPD_CUSTOM_FILES */ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_CUSTOM_FILES */ #endif /* LWIP_HTTPD_FS_ASYNC_READ */ } return 1; } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ /*-----------------------------------------------------------------------------------*/ int fs_bytes_left(struct fs_file *file) { return file->len - file->index; } \ No newline at end of file diff --git a/apps/httpserver_raw/fs.c b/apps/httpserver_raw/fs.c index 2cb7575..9e655bb 100644 --- a/apps/httpserver_raw/fs.c +++ b/apps/httpserver_raw/fs.c @@ -1,180 +1 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ -#include "lwip/opt.h" -#include "lwip/def.h" -#include "fs.h" -#include "fsdata.h" -#include - -/** Set this to 1 to include "fsdata_custom.c" instead of "fsdata.c" for the - * file system (to prevent changing the file included in CVS) */ -#ifndef HTTPD_USE_CUSTOM_FSDATA -#define HTTPD_USE_CUSTOM_FSDATA 0 -#endif - -#if HTTPD_USE_CUSTOM_FSDATA -#include "fsdata_custom.c" -#else /* HTTPD_USE_CUSTOM_FSDATA */ -#include "fsdata.c" -#endif /* HTTPD_USE_CUSTOM_FSDATA */ - -/*-----------------------------------------------------------------------------------*/ - -#if LWIP_HTTPD_CUSTOM_FILES -int fs_open_custom(struct fs_file *file, const char *name); -void fs_close_custom(struct fs_file *file); -#if LWIP_HTTPD_FS_ASYNC_READ -u8_t fs_canread_custom(struct fs_file *file); -u8_t fs_wait_read_custom(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ -#endif /* LWIP_HTTPD_CUSTOM_FILES */ - -/*-----------------------------------------------------------------------------------*/ -err_t -fs_open(struct fs_file *file, const char *name) -{ - const struct fsdata_file *f; - - if ((file == NULL) || (name == NULL)) { - return ERR_ARG; - } - -#if LWIP_HTTPD_CUSTOM_FILES - if (fs_open_custom(file, name)) { - file->is_custom_file = 1; - return ERR_OK; - } - file->is_custom_file = 0; -#endif /* LWIP_HTTPD_CUSTOM_FILES */ - - for (f = FS_ROOT; f != NULL; f = f->next) { - if (!strcmp(name, (char *)f->name)) { - file->data = (const char *)f->data; - file->len = f->len; - file->index = f->len; - file->pextension = NULL; - file->http_header_included = f->http_header_included; -#if HTTPD_PRECALCULATED_CHECKSUM - file->chksum_count = f->chksum_count; - file->chksum = f->chksum; -#endif /* HTTPD_PRECALCULATED_CHECKSUM */ -#if LWIP_HTTPD_FILE_STATE - file->state = fs_state_init(file, name); -#endif /* #if LWIP_HTTPD_FILE_STATE */ - return ERR_OK; - } - } - /* file not found */ - return ERR_VAL; -} - -/*-----------------------------------------------------------------------------------*/ -void -fs_close(struct fs_file *file) -{ -#if LWIP_HTTPD_CUSTOM_FILES - if (file->is_custom_file) { - fs_close_custom(file); - } -#endif /* LWIP_HTTPD_CUSTOM_FILES */ -#if LWIP_HTTPD_FILE_STATE - fs_state_free(file, file->state); -#endif /* #if LWIP_HTTPD_FILE_STATE */ - LWIP_UNUSED_ARG(file); -} -/*-----------------------------------------------------------------------------------*/ -#if LWIP_HTTPD_DYNAMIC_FILE_READ -#if LWIP_HTTPD_FS_ASYNC_READ -int -fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg) -#else /* LWIP_HTTPD_FS_ASYNC_READ */ -int -fs_read(struct fs_file *file, char *buffer, int count) -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ -{ - int read; - - if(file->index == file->len) { - return FS_READ_EOF; - } -#if LWIP_HTTPD_FS_ASYNC_READ -#if LWIP_HTTPD_CUSTOM_FILES - if (!fs_canread_custom(file)) { - if (fs_wait_read_custom(file, callback_fn, callback_arg)) { - return FS_READ_DELAYED; - } - } -#else /* LWIP_HTTPD_CUSTOM_FILES */ - LWIP_UNUSED_ARG(callback_fn); - LWIP_UNUSED_ARG(callback_arg); -#endif /* LWIP_HTTPD_CUSTOM_FILES */ -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - - read = file->len - file->index; - if(read > count) { - read = count; - } - - MEMCPY(buffer, (file->data + file->index), read); - file->index += read; - - return(read); -} -#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ -/*-----------------------------------------------------------------------------------*/ -#if LWIP_HTTPD_FS_ASYNC_READ -int -fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg) -{ - if (file != NULL) { -#if LWIP_HTTPD_FS_ASYNC_READ -#if LWIP_HTTPD_CUSTOM_FILES - if (!fs_canread_custom(file)) { - if (fs_wait_read_custom(file, callback_fn, callback_arg)) { - return 0; - } - } -#else /* LWIP_HTTPD_CUSTOM_FILES */ - LWIP_UNUSED_ARG(callback_fn); - LWIP_UNUSED_ARG(callback_arg); -#endif /* LWIP_HTTPD_CUSTOM_FILES */ -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - } - return 1; -} -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ -/*-----------------------------------------------------------------------------------*/ -int -fs_bytes_left(struct fs_file *file) -{ - return file->len - file->index; -} +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #include "lwip/opt.h" #include "lwip/def.h" #include "fs.h" #include "fsdata.h" #include /** Set this to 1 to include "fsdata_custom.c" instead of "fsdata.c" for the * file system (to prevent changing the file included in CVS) */ #ifndef HTTPD_USE_CUSTOM_FSDATA #define HTTPD_USE_CUSTOM_FSDATA 0 #endif #if HTTPD_USE_CUSTOM_FSDATA #include "fsdata_custom.c" #else /* HTTPD_USE_CUSTOM_FSDATA */ #include "fsdata.c" #endif /* HTTPD_USE_CUSTOM_FSDATA */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_CUSTOM_FILES int fs_open_custom(struct fs_file *file, const char *name); void fs_close_custom(struct fs_file *file); #if LWIP_HTTPD_FS_ASYNC_READ u8_t fs_canread_custom(struct fs_file *file); u8_t fs_wait_read_custom(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #endif /* LWIP_HTTPD_CUSTOM_FILES */ /*-----------------------------------------------------------------------------------*/ err_t fs_open(struct fs_file *file, const char *name) { const struct fsdata_file *f; if ((file == NULL) || (name == NULL)) { return ERR_ARG; } #if LWIP_HTTPD_CUSTOM_FILES if (fs_open_custom(file, name)) { file->is_custom_file = 1; return ERR_OK; } file->is_custom_file = 0; #endif /* LWIP_HTTPD_CUSTOM_FILES */ for (f = FS_ROOT; f != NULL; f = f->next) { if (!strcmp(name, (char *)f->name)) { file->data = (const char *)f->data; file->len = f->len; file->index = f->len; file->pextension = NULL; file->http_header_included = f->http_header_included; #if HTTPD_PRECALCULATED_CHECKSUM file->chksum_count = f->chksum_count; file->chksum = f->chksum; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ #if LWIP_HTTPD_FILE_STATE file->state = fs_state_init(file, name); #endif /* #if LWIP_HTTPD_FILE_STATE */ return ERR_OK; } } /* file not found */ return ERR_VAL; } /*-----------------------------------------------------------------------------------*/ void fs_close(struct fs_file *file) { #if LWIP_HTTPD_CUSTOM_FILES if (file->is_custom_file) { fs_close_custom(file); } #endif /* LWIP_HTTPD_CUSTOM_FILES */ #if LWIP_HTTPD_FILE_STATE fs_state_free(file, file->state); #endif /* #if LWIP_HTTPD_FILE_STATE */ LWIP_UNUSED_ARG(file); } /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_DYNAMIC_FILE_READ #if LWIP_HTTPD_FS_ASYNC_READ int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg) #else /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_read(struct fs_file *file, char *buffer, int count) #endif /* LWIP_HTTPD_FS_ASYNC_READ */ { int read; if(file->index == file->len) { return FS_READ_EOF; } #if LWIP_HTTPD_FS_ASYNC_READ #if LWIP_HTTPD_CUSTOM_FILES if (!fs_canread_custom(file)) { if (fs_wait_read_custom(file, callback_fn, callback_arg)) { return FS_READ_DELAYED; } } #else /* LWIP_HTTPD_CUSTOM_FILES */ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_CUSTOM_FILES */ #endif /* LWIP_HTTPD_FS_ASYNC_READ */ read = file->len - file->index; if(read > count) { read = count; } MEMCPY(buffer, (file->data + file->index), read); file->index += read; return(read); } #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ /*-----------------------------------------------------------------------------------*/ #if LWIP_HTTPD_FS_ASYNC_READ int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg) { if (file != NULL) { #if LWIP_HTTPD_FS_ASYNC_READ #if LWIP_HTTPD_CUSTOM_FILES if (!fs_canread_custom(file)) { if (fs_wait_read_custom(file, callback_fn, callback_arg)) { return 0; } } #else /* LWIP_HTTPD_CUSTOM_FILES */ LWIP_UNUSED_ARG(callback_fn); LWIP_UNUSED_ARG(callback_arg); #endif /* LWIP_HTTPD_CUSTOM_FILES */ #endif /* LWIP_HTTPD_FS_ASYNC_READ */ } return 1; } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ /*-----------------------------------------------------------------------------------*/ int fs_bytes_left(struct fs_file *file) { return file->len - file->index; } \ No newline at end of file diff --git a/apps/httpserver_raw/fs.h b/apps/httpserver_raw/fs.h index 68248c2..9841800 100644 --- a/apps/httpserver_raw/fs.h +++ b/apps/httpserver_raw/fs.h @@ -1,140 +1 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ -#ifndef LWIP_FS_H -#define LWIP_FS_H - -#include "lwip/opt.h" -#include "lwip/err.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** Set this to 1 and provide the functions: - * - "int fs_open_custom(struct fs_file *file, const char *name)" - * Called first for every opened file to allow opening files - * that are not included in fsdata(_custom).c - * - "void fs_close_custom(struct fs_file *file)" - * Called to free resources allocated by fs_open_custom(). - */ -#ifndef LWIP_HTTPD_CUSTOM_FILES -#define LWIP_HTTPD_CUSTOM_FILES 0 -#endif - -/** Set this to 1 to support fs_read() to dynamically read file data. - * Without this (default=off), only one-block files are supported, - * and the contents must be ready after fs_open(). - */ -#ifndef LWIP_HTTPD_DYNAMIC_FILE_READ -#define LWIP_HTTPD_DYNAMIC_FILE_READ 0 -#endif - -/** Set this to 1 to include an application state argument per file - * that is opened. This allows to keep a state per connection/file. - */ -#ifndef LWIP_HTTPD_FILE_STATE -#define LWIP_HTTPD_FILE_STATE 0 -#endif - -/** HTTPD_PRECALCULATED_CHECKSUM==1: include precompiled checksums for - * predefined (MSS-sized) chunks of the files to prevent having to calculate - * the checksums at runtime. */ -#ifndef HTTPD_PRECALCULATED_CHECKSUM -#define HTTPD_PRECALCULATED_CHECKSUM 0 -#endif - -/** LWIP_HTTPD_FS_ASYNC_READ==1: support asynchronous read operations - * (fs_read_async returns FS_READ_DELAYED and calls a callback when finished). - */ -#ifndef LWIP_HTTPD_FS_ASYNC_READ -#define LWIP_HTTPD_FS_ASYNC_READ 0 -#endif - -#define FS_READ_EOF -1 -#define FS_READ_DELAYED -2 - -#if HTTPD_PRECALCULATED_CHECKSUM -struct fsdata_chksum { - u32_t offset; - u16_t chksum; - u16_t len; -}; -#endif /* HTTPD_PRECALCULATED_CHECKSUM */ - -struct fs_file { - const char *data; - int len; - int index; - void *pextension; -#if HTTPD_PRECALCULATED_CHECKSUM - const struct fsdata_chksum *chksum; - u16_t chksum_count; -#endif /* HTTPD_PRECALCULATED_CHECKSUM */ - u8_t http_header_included; -#if LWIP_HTTPD_CUSTOM_FILES - u8_t is_custom_file; -#endif /* LWIP_HTTPD_CUSTOM_FILES */ -#if LWIP_HTTPD_FILE_STATE - void *state; -#endif /* LWIP_HTTPD_FILE_STATE */ -}; - -#if LWIP_HTTPD_FS_ASYNC_READ -typedef void (*fs_wait_cb)(void *arg); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - -err_t fs_open(struct fs_file *file, const char *name); -void fs_close(struct fs_file *file); -#if LWIP_HTTPD_DYNAMIC_FILE_READ -#if LWIP_HTTPD_FS_ASYNC_READ -int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg); -#else /* LWIP_HTTPD_FS_ASYNC_READ */ -int fs_read(struct fs_file *file, char *buffer, int count); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ -#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ -#if LWIP_HTTPD_FS_ASYNC_READ -int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ -int fs_bytes_left(struct fs_file *file); - -#if LWIP_HTTPD_FILE_STATE -/** This user-defined function is called when a file is opened. */ -void *fs_state_init(struct fs_file *file, const char *name); -/** This user-defined function is called when a file is closed. */ -void fs_state_free(struct fs_file *file, void *state); -#endif /* #if LWIP_HTTPD_FILE_STATE */ - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_FS_H */ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef LWIP_FS_H #define LWIP_FS_H #include "lwip/opt.h" #include "lwip/err.h" #ifdef __cplusplus extern "C" { #endif /** Set this to 1 and provide the functions: * - "int fs_open_custom(struct fs_file *file, const char *name)" * Called first for every opened file to allow opening files * that are not included in fsdata(_custom).c * - "void fs_close_custom(struct fs_file *file)" * Called to free resources allocated by fs_open_custom(). */ #ifndef LWIP_HTTPD_CUSTOM_FILES #define LWIP_HTTPD_CUSTOM_FILES 0 #endif /** Set this to 1 to support fs_read() to dynamically read file data. * Without this (default=off), only one-block files are supported, * and the contents must be ready after fs_open(). */ #ifndef LWIP_HTTPD_DYNAMIC_FILE_READ #define LWIP_HTTPD_DYNAMIC_FILE_READ 0 #endif /** Set this to 1 to include an application state argument per file * that is opened. This allows to keep a state per connection/file. */ #ifndef LWIP_HTTPD_FILE_STATE #define LWIP_HTTPD_FILE_STATE 0 #endif /** HTTPD_PRECALCULATED_CHECKSUM==1: include precompiled checksums for * predefined (MSS-sized) chunks of the files to prevent having to calculate * the checksums at runtime. */ #ifndef HTTPD_PRECALCULATED_CHECKSUM #define HTTPD_PRECALCULATED_CHECKSUM 0 #endif /** LWIP_HTTPD_FS_ASYNC_READ==1: support asynchronous read operations * (fs_read_async returns FS_READ_DELAYED and calls a callback when finished). */ #ifndef LWIP_HTTPD_FS_ASYNC_READ #define LWIP_HTTPD_FS_ASYNC_READ 0 #endif #define FS_READ_EOF -1 #define FS_READ_DELAYED -2 #if HTTPD_PRECALCULATED_CHECKSUM struct fsdata_chksum { u32_t offset; u16_t chksum; u16_t len; }; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ struct fs_file { const char *data; int len; int index; void *pextension; #if HTTPD_PRECALCULATED_CHECKSUM const struct fsdata_chksum *chksum; u16_t chksum_count; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ u8_t http_header_included; #if LWIP_HTTPD_CUSTOM_FILES u8_t is_custom_file; #endif /* LWIP_HTTPD_CUSTOM_FILES */ #if LWIP_HTTPD_FILE_STATE void *state; #endif /* LWIP_HTTPD_FILE_STATE */ }; #if LWIP_HTTPD_FS_ASYNC_READ typedef void (*fs_wait_cb)(void *arg); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ err_t fs_open(struct fs_file *file, const char *name); void fs_close(struct fs_file *file); #if LWIP_HTTPD_DYNAMIC_FILE_READ #if LWIP_HTTPD_FS_ASYNC_READ int fs_read_async(struct fs_file *file, char *buffer, int count, fs_wait_cb callback_fn, void *callback_arg); #else /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_read(struct fs_file *file, char *buffer, int count); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ #if LWIP_HTTPD_FS_ASYNC_READ int fs_is_file_ready(struct fs_file *file, fs_wait_cb callback_fn, void *callback_arg); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ int fs_bytes_left(struct fs_file *file); #if LWIP_HTTPD_FILE_STATE /** This user-defined function is called when a file is opened. */ void *fs_state_init(struct fs_file *file, const char *name); /** This user-defined function is called when a file is closed. */ void fs_state_free(struct fs_file *file, void *state); #endif /* #if LWIP_HTTPD_FILE_STATE */ #ifdef __cplusplus } #endif #endif /* LWIP_FS_H */ \ No newline at end of file diff --git a/apps/httpserver_raw/fsdata.h b/apps/httpserver_raw/fsdata.h index 818458a..ead4b62 100644 --- a/apps/httpserver_raw/fsdata.h +++ b/apps/httpserver_raw/fsdata.h @@ -1,50 +1 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - */ -#ifndef LWIP_FSDATA_H -#define LWIP_FSDATA_H - -#include "lwip/opt.h" -#include "fs.h" - -struct fsdata_file { - const struct fsdata_file *next; - const unsigned char *name; - const unsigned char *data; - int len; - u8_t http_header_included; -#if HTTPD_PRECALCULATED_CHECKSUM - u16_t chksum_count; - const struct fsdata_chksum *chksum; -#endif /* HTTPD_PRECALCULATED_CHECKSUM */ -}; - -#endif /* LWIP_FSDATA_H */ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #ifndef LWIP_FSDATA_H #define LWIP_FSDATA_H #include "lwip/opt.h" #include "fs.h" struct fsdata_file { const struct fsdata_file *next; const unsigned char *name; const unsigned char *data; int len; u8_t http_header_included; #if HTTPD_PRECALCULATED_CHECKSUM u16_t chksum_count; const struct fsdata_chksum *chksum; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ }; #endif /* LWIP_FSDATA_H */ \ No newline at end of file diff --git a/apps/httpserver_raw/httpd.c b/apps/httpserver_raw/httpd.c index 772b179..aef3796 100644 --- a/apps/httpserver_raw/httpd.c +++ b/apps/httpserver_raw/httpd.c @@ -1,2533 +1 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * Simon Goldschmidt - * - */ - -/* This httpd supports for a - * rudimentary server-side-include facility which will replace tags of the form - * in any file whose extension is .shtml, .shtm or .ssi with - * strings provided by an include handler whose pointer is provided to the - * module via function http_set_ssi_handler(). - * Additionally, a simple common - * gateway interface (CGI) handling mechanism has been added to allow clients - * to hook functions to particular request URIs. - * - * To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h. - * To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h. - * - * By default, the server assumes that HTTP headers are already present in - * each file stored in the file system. By defining LWIP_HTTPD_DYNAMIC_HEADERS in - * lwipopts.h, this behavior can be changed such that the server inserts the - * headers automatically based on the extension of the file being served. If - * this mode is used, be careful to ensure that the file system image used - * does not already contain the header information. - * - * File system images without headers can be created using the makefsfile - * tool with the -h command line option. - * - * - * Notes about valid SSI tags - * -------------------------- - * - * The following assumptions are made about tags used in SSI markers: - * - * 1. No tag may contain '-' or whitespace characters within the tag name. - * 2. Whitespace is allowed between the tag leadin "". - * 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters. - * - * Notes on CGI usage - * ------------------ - * - * The simple CGI support offered here works with GET method requests only - * and can handle up to 16 parameters encoded into the URI. The handler - * function may not write directly to the HTTP output but must return a - * filename that the HTTP server will send to the browser as a response to - * the incoming CGI request. - * - * - * - * The list of supported file types is quite short, so if makefsdata complains - * about an unknown extension, make sure to add it (and its doctype) to - * the 'g_psHTTPHeaders' list. - */ -#include "httpd.h" -#include "lwip/debug.h" -#include "lwip/stats.h" -#include "httpd_structs.h" -#include "lwip/tcp.h" -#include "fs.h" - -#include -#include - -#if LWIP_TCP - -#ifndef HTTPD_DEBUG -#define HTTPD_DEBUG LWIP_DBG_OFF -#endif - -/** Set this to 1, set MEMP_USE_CUSTOM_POOLS to 1 and add the next line to - * lwippools.h to use a memp pool for allocating struct http_state instead of - * the heap: - * - * LWIP_MEMPOOL(HTTPD_STATE, 20, 100, "HTTPD_STATE") - */ -#ifndef HTTPD_USE_MEM_POOL -#define HTTPD_USE_MEM_POOL 0 -#endif - -/** The server port for HTTPD to use */ -#ifndef HTTPD_SERVER_PORT -#define HTTPD_SERVER_PORT 80 -#endif - -/** Maximum retries before the connection is aborted/closed. - * - number of times pcb->poll is called -> default is 4*500ms = 2s; - * - reset when pcb->sent is called - */ -#ifndef HTTPD_MAX_RETRIES -#define HTTPD_MAX_RETRIES 4 -#endif - -/** The poll delay is X*500ms */ -#ifndef HTTPD_POLL_INTERVAL -#define HTTPD_POLL_INTERVAL 4 -#endif - -/** Priority for tcp pcbs created by HTTPD (very low by default). - * Lower priorities get killed first when running out of memory. - */ -#ifndef HTTPD_TCP_PRIO -#define HTTPD_TCP_PRIO TCP_PRIO_MIN -#endif - -/** Set this to 1 to enable timing each file sent */ -#ifndef LWIP_HTTPD_TIMING -#define LWIP_HTTPD_TIMING 0 -#endif -#ifndef HTTPD_DEBUG_TIMING -#define HTTPD_DEBUG_TIMING LWIP_DBG_OFF -#endif - -/** Set this to 1 on platforms where strnstr is not available */ -#ifndef LWIP_HTTPD_STRNSTR_PRIVATE -#define LWIP_HTTPD_STRNSTR_PRIVATE 1 -#endif - -/** Set this to one to show error pages when parsing a request fails instead - of simply closing the connection. */ -#ifndef LWIP_HTTPD_SUPPORT_EXTSTATUS -#define LWIP_HTTPD_SUPPORT_EXTSTATUS 0 -#endif - -/** Set this to 0 to drop support for HTTP/0.9 clients (to save some bytes) */ -#ifndef LWIP_HTTPD_SUPPORT_V09 -#define LWIP_HTTPD_SUPPORT_V09 1 -#endif - -/** Set this to 1 to enable HTTP/1.1 persistent connections. - * ATTENTION: If the generated file system includes HTTP headers, these must - * include the "Connection: keep-alive" header (pass argument "-11" to makefsdata). - */ -#ifndef LWIP_HTTPD_SUPPORT_11_KEEPALIVE -#define LWIP_HTTPD_SUPPORT_11_KEEPALIVE 0 -#endif - -/** Set this to 1 to support HTTP request coming in in multiple packets/pbufs */ -#ifndef LWIP_HTTPD_SUPPORT_REQUESTLIST -#define LWIP_HTTPD_SUPPORT_REQUESTLIST 1 -#endif - -#if LWIP_HTTPD_SUPPORT_REQUESTLIST -/** Number of rx pbufs to enqueue to parse an incoming request (up to the first - newline) */ -#ifndef LWIP_HTTPD_REQ_QUEUELEN -#define LWIP_HTTPD_REQ_QUEUELEN 5 -#endif - -/** Number of (TCP payload-) bytes (in pbufs) to enqueue to parse and incoming - request (up to the first double-newline) */ -#ifndef LWIP_HTTPD_REQ_BUFSIZE -#define LWIP_HTTPD_REQ_BUFSIZE LWIP_HTTPD_MAX_REQ_LENGTH -#endif - -/** Defines the maximum length of a HTTP request line (up to the first CRLF, - copied from pbuf into this a global buffer when pbuf- or packet-queues - are received - otherwise the input pbuf is used directly) */ -#ifndef LWIP_HTTPD_MAX_REQ_LENGTH -#define LWIP_HTTPD_MAX_REQ_LENGTH LWIP_MIN(1023, (LWIP_HTTPD_REQ_QUEUELEN * PBUF_POOL_BUFSIZE)) -#endif -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - -/** Maximum length of the filename to send as response to a POST request, - * filled in by the application when a POST is finished. - */ -#ifndef LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN -#define LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN 63 -#endif - -/** Set this to 0 to not send the SSI tag (default is on, so the tag will - * be sent in the HTML page */ -#ifndef LWIP_HTTPD_SSI_INCLUDE_TAG -#define LWIP_HTTPD_SSI_INCLUDE_TAG 1 -#endif - -/** Set this to 1 to call tcp_abort when tcp_close fails with memory error. - * This can be used to prevent consuming all memory in situations where the - * HTTP server has low priority compared to other communication. */ -#ifndef LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR -#define LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR 0 -#endif - -/** Set this to 1 to kill the oldest connection when running out of - * memory for 'struct http_state' or 'struct http_ssi_state'. - * ATTENTION: This puts all connections on a linked list, so may be kind of slow. - */ -#ifndef LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED -#define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 0 -#endif - -/** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */ -#define MIN_REQ_LEN 7 - -#define CRLF "\r\n" -#define HTTP11_CONNECTIONKEEPALIVE "Connection: keep-alive" - -#if LWIP_HTTPD_SSI -#define LWIP_HTTPD_IS_SSI(hs) ((hs)->ssi) -#else /* LWIP_HTTPD_SSI */ -#define LWIP_HTTPD_IS_SSI(hs) 0 -#endif /* LWIP_HTTPD_SSI */ - -/** These defines check whether tcp_write has to copy data or not */ - -/** This was TI's check whether to let TCP copy data or not -#define HTTP_IS_DATA_VOLATILE(hs) ((hs->file < (char *)0x20000000) ? 0 : TCP_WRITE_FLAG_COPY)*/ -#ifndef HTTP_IS_DATA_VOLATILE -#if LWIP_HTTPD_SSI -/* Copy for SSI files, no copy for non-SSI files */ -#define HTTP_IS_DATA_VOLATILE(hs) ((hs)->ssi ? TCP_WRITE_FLAG_COPY : 0) -#else /* LWIP_HTTPD_SSI */ -/** Default: don't copy if the data is sent from file-system directly */ -#define HTTP_IS_DATA_VOLATILE(hs) (((hs->file != NULL) && (hs->handle != NULL) && (hs->file == \ - (char*)hs->handle->data + hs->handle->len - hs->left)) \ - ? 0 : TCP_WRITE_FLAG_COPY) -#endif /* LWIP_HTTPD_SSI */ -#endif - -/** Default: headers are sent from ROM */ -#ifndef HTTP_IS_HDR_VOLATILE -#define HTTP_IS_HDR_VOLATILE(hs, ptr) 0 -#endif - -#if LWIP_HTTPD_SSI -/** Default: Tags are sent from struct http_state and are therefore volatile */ -#ifndef HTTP_IS_TAG_VOLATILE -#define HTTP_IS_TAG_VOLATILE(ptr) TCP_WRITE_FLAG_COPY -#endif -#endif /* LWIP_HTTPD_SSI */ - -/* By default, the httpd is limited to send 2*pcb->mss to keep resource usage low - when http is not an important protocol in the device. */ -#ifndef HTTPD_LIMIT_SENDING_TO_2MSS -#define HTTPD_LIMIT_SENDING_TO_2MSS 1 -#endif - -/* Define this to a function that returns the maximum amount of data to enqueue. - The function have this signature: u16_t fn(struct tcp_pcb* pcb); */ -#ifndef HTTPD_MAX_WRITE_LEN -#if HTTPD_LIMIT_SENDING_TO_2MSS -#define HTTPD_MAX_WRITE_LEN(pcb) (2 * tcp_mss(pcb)) -#endif -#endif - -/* Return values for http_send_*() */ -#define HTTP_DATA_TO_SEND_BREAK 2 -#define HTTP_DATA_TO_SEND_CONTINUE 1 -#define HTTP_NO_DATA_TO_SEND 0 - -#if HTTPD_USE_MEM_POOL -#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)memp_malloc(MEMP_HTTPD_SSI_STATE) -#define HTTP_ALLOC_HTTP_STATE() (struct http_state *)memp_malloc(MEMP_HTTPD_STATE) -#else /* HTTPD_USE_MEM_POOL */ -#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state)) -#define HTTP_ALLOC_HTTP_STATE() (struct http_state *)mem_malloc(sizeof(struct http_state)) -#endif /* HTTPD_USE_MEM_POOL */ - -typedef struct -{ - const char *name; - u8_t shtml; -} default_filename; - -const default_filename g_psDefaultFilenames[] = { - {"/index.shtml", 1 }, - {"/index.ssi", 1 }, - {"/index.shtm", 1 }, - {"/index.html", 0 }, - {"/index.htm", 0 } -}; - -#define NUM_DEFAULT_FILENAMES (sizeof(g_psDefaultFilenames) / \ - sizeof(default_filename)) - -#if LWIP_HTTPD_SUPPORT_REQUESTLIST -/** HTTP request is copied here from pbufs for simple parsing */ -static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH+1]; -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - -#if LWIP_HTTPD_SUPPORT_POST -/** Filename for response file to send when POST is finished */ -static char http_post_response_filename[LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN+1]; -#endif /* LWIP_HTTPD_SUPPORT_POST */ - -#if LWIP_HTTPD_DYNAMIC_HEADERS -/* The number of individual strings that comprise the headers sent before each - * requested file. - */ -#define NUM_FILE_HDR_STRINGS 3 -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ - -#if LWIP_HTTPD_SSI - -#define HTTPD_LAST_TAG_PART 0xFFFF - -enum tag_check_state { - TAG_NONE, /* Not processing an SSI tag */ - TAG_LEADIN, /* Tag lead in "" being processed */ - TAG_SENDING /* Sending tag replacement string */ -}; - -struct http_ssi_state { - const char *parsed; /* Pointer to the first unparsed byte in buf. */ -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - const char *tag_started;/* Pointer to the first opening '<' of the tag. */ -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ - const char *tag_end; /* Pointer to char after the closing '>' of the tag. */ - u32_t parse_left; /* Number of unparsed bytes in buf. */ - u16_t tag_index; /* Counter used by tag parsing state machine */ - u16_t tag_insert_len; /* Length of insert in string tag_insert */ -#if LWIP_HTTPD_SSI_MULTIPART - u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */ -#endif /* LWIP_HTTPD_SSI_MULTIPART */ - u8_t tag_name_len; /* Length of the tag name in string tag_name */ - char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */ - char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */ - enum tag_check_state tag_state; /* State of the tag processor */ -}; -#endif /* LWIP_HTTPD_SSI */ - -struct http_state { -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED - struct http_state *next; -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - struct fs_file file_handle; - struct fs_file *handle; - char *file; /* Pointer to first unsent byte in buf. */ - - struct tcp_pcb *pcb; -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - struct pbuf *req; -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - -#if LWIP_HTTPD_DYNAMIC_FILE_READ - char *buf; /* File read buffer. */ - int buf_len; /* Size of file read buffer, buf. */ -#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ - u32_t left; /* Number of unsent bytes in buf. */ - u8_t retries; -#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE - u8_t keepalive; -#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ -#if LWIP_HTTPD_SSI - struct http_ssi_state *ssi; -#endif /* LWIP_HTTPD_SSI */ -#if LWIP_HTTPD_CGI - char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */ - char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */ -#endif /* LWIP_HTTPD_CGI */ -#if LWIP_HTTPD_DYNAMIC_HEADERS - const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */ - u16_t hdr_pos; /* The position of the first unsent header byte in the - current string */ - u16_t hdr_index; /* The index of the hdr string currently being sent. */ -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ -#if LWIP_HTTPD_TIMING - u32_t time_started; -#endif /* LWIP_HTTPD_TIMING */ -#if LWIP_HTTPD_SUPPORT_POST - u32_t post_content_len_left; -#if LWIP_HTTPD_POST_MANUAL_WND - u32_t unrecved_bytes; - u8_t no_auto_wnd; - u8_t post_finished; -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ -#endif /* LWIP_HTTPD_SUPPORT_POST*/ -}; - -static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs); -static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn); -static err_t http_find_file(struct http_state *hs, const char *uri, int is_09); -static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check); -static err_t http_poll(void *arg, struct tcp_pcb *pcb); -static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs); -#if LWIP_HTTPD_FS_ASYNC_READ -static void http_continue(void *connection); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - -#if LWIP_HTTPD_SSI -/* SSI insert handler function pointer. */ -tSSIHandler g_pfnSSIHandler = NULL; -int g_iNumTags = 0; -const char **g_ppcTags = NULL; - -#define LEN_TAG_LEAD_IN 5 -const char * const g_pcTagLeadIn = ""; -#endif /* LWIP_HTTPD_SSI */ - -#if LWIP_HTTPD_CGI -/* CGI handler information */ -const tCGI *g_pCGIs; -int g_iNumCGIs; -#endif /* LWIP_HTTPD_CGI */ - -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED -/** global list of active HTTP connections, use to kill the oldest when - running out of memory */ -static struct http_state *http_connections; -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - -#if LWIP_HTTPD_STRNSTR_PRIVATE -/** Like strstr but does not need 'buffer' to be NULL-terminated */ -static char* -strnstr(const char* buffer, const char* token, size_t n) -{ - const char* p; - int tokenlen = (int)strlen(token); - if (tokenlen == 0) { - return (char *)buffer; - } - for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) { - if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) { - return (char *)p; - } - } - return NULL; -} -#endif /* LWIP_HTTPD_STRNSTR_PRIVATE */ - -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED -static void -http_kill_oldest_connection(u8_t ssi_required) -{ - struct http_state *hs = http_connections; - struct http_state *hs_free_next = NULL; - while(hs && hs->next) { -#if LWIP_HTTPD_SSI - if (ssi_required) { - if (hs->next->ssi != NULL) { - hs_free_next = hs; - } - } else -#else /* LWIP_HTTPD_SSI */ - LWIP_UNUSED_ARG(ssi_required); -#endif /* LWIP_HTTPD_SSI */ - { - hs_free_next = hs; - } - hs = hs->next; - } - if (hs_free_next != NULL) { - LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL); - LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL); - /* send RST when killing a connection because of memory shortage */ - http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */ - } -} -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - -#if LWIP_HTTPD_SSI -/** Allocate as struct http_ssi_state. */ -static struct http_ssi_state* -http_ssi_state_alloc(void) -{ - struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE(); -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED - if (ret == NULL) { - http_kill_oldest_connection(1); - ret = HTTP_ALLOC_SSI_STATE(); - } -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - if (ret != NULL) { - memset(ret, 0, sizeof(struct http_ssi_state)); - } - return ret; -} - -/** Free a struct http_ssi_state. */ -static void -http_ssi_state_free(struct http_ssi_state *ssi) -{ - if (ssi != NULL) { -#if HTTPD_USE_MEM_POOL - memp_free(MEMP_HTTPD_SSI_STATE, ssi); -#else /* HTTPD_USE_MEM_POOL */ - mem_free(ssi); -#endif /* HTTPD_USE_MEM_POOL */ - } -} -#endif /* LWIP_HTTPD_SSI */ - -/** Initialize a struct http_state. - */ -static void -http_state_init(struct http_state* hs) -{ - /* Initialize the structure. */ - memset(hs, 0, sizeof(struct http_state)); -#if LWIP_HTTPD_DYNAMIC_HEADERS - /* Indicate that the headers are not yet valid */ - hs->hdr_index = NUM_FILE_HDR_STRINGS; -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ -} - -/** Allocate a struct http_state. */ -static struct http_state* -http_state_alloc(void) -{ - struct http_state *ret = HTTP_ALLOC_HTTP_STATE(); -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED - if (ret == NULL) { - http_kill_oldest_connection(0); - ret = HTTP_ALLOC_HTTP_STATE(); - } -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - if (ret != NULL) { - http_state_init(ret); -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED - /* add the connection to the list */ - if (http_connections == NULL) { - http_connections = ret; - } else { - struct http_state *last; - for(last = http_connections; last->next != NULL; last = last->next); - LWIP_ASSERT("last != NULL", last != NULL); - last->next = ret; - } -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ - } - return ret; -} - -/** Free a struct http_state. - * Also frees the file data if dynamic. - */ -static void -http_state_eof(struct http_state *hs) -{ - if(hs->handle) { -#if LWIP_HTTPD_TIMING - u32_t ms_needed = sys_now() - hs->time_started; - u32_t needed = LWIP_MAX(1, (ms_needed/100)); - LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n", - ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed))); -#endif /* LWIP_HTTPD_TIMING */ - fs_close(hs->handle); - hs->handle = NULL; - } -#if LWIP_HTTPD_DYNAMIC_FILE_READ - if (hs->buf != NULL) { - mem_free(hs->buf); - hs->buf = NULL; - } -#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ -#if LWIP_HTTPD_SSI - if (hs->ssi) { - http_ssi_state_free(hs->ssi); - hs->ssi = NULL; - } -#endif /* LWIP_HTTPD_SSI */ -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - if (hs->req) { - pbuf_free(hs->req); - hs->req = NULL; - } -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ -} - -/** Free a struct http_state. - * Also frees the file data if dynamic. - */ -static void -http_state_free(struct http_state *hs) -{ - if (hs != NULL) { - http_state_eof(hs); -#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED - /* take the connection off the list */ - if (http_connections) { - if (http_connections == hs) { - http_connections = hs->next; - } else { - struct http_state *last; - for(last = http_connections; last->next != NULL; last = last->next) { - if (last->next == hs) { - last->next = hs->next; - break; - } - } - } - } -#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ -#if HTTPD_USE_MEM_POOL - memp_free(MEMP_HTTPD_STATE, hs); -#else /* HTTPD_USE_MEM_POOL */ - mem_free(hs); -#endif /* HTTPD_USE_MEM_POOL */ - } -} - -/** Call tcp_write() in a loop trying smaller and smaller length - * - * @param pcb tcp_pcb to send - * @param ptr Data to send - * @param length Length of data to send (in/out: on return, contains the - * amount of data sent) - * @param apiflags directly passed to tcp_write - * @return the return value of tcp_write - */ -static err_t -http_write(struct tcp_pcb *pcb, const void* ptr, u16_t *length, u8_t apiflags) -{ - u16_t len, max_len; - err_t err; - LWIP_ASSERT("length != NULL", length != NULL); - len = *length; - if (len == 0) { - return ERR_OK; - } - /* We cannot send more data than space available in the send buffer. */ - max_len = tcp_sndbuf(pcb); - if (max_len < len) { - len = max_len; - } -#ifdef HTTPD_MAX_WRITE_LEN - /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ - max_len = HTTPD_MAX_WRITE_LEN(pcb); - if(len > max_len) { - len = max_len; - } -#endif /* HTTPD_MAX_WRITE_LEN */ - do { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying go send %d bytes\n", len)); - err = tcp_write(pcb, ptr, len, apiflags); - if (err == ERR_MEM) { - if ((tcp_sndbuf(pcb) == 0) || - (tcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) { - /* no need to try smaller sizes */ - len = 1; - } else { - len /= 2; - } - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, - ("Send failed, trying less (%d bytes)\n", len)); - } - } while ((err == ERR_MEM) && (len > 1)); - - if (err == ERR_OK) { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len)); - *length = len; - } else { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err))); - *length = 0; - } - - return err; -} - -/** - * The connection shall be actively closed (using RST to close from fault states). - * Reset the sent- and recv-callbacks. - * - * @param pcb the tcp pcb to reset callbacks - * @param hs connection state to free - */ -static err_t -http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn) -{ - err_t err; - LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void*)pcb)); - -#if LWIP_HTTPD_SUPPORT_POST - if (hs != NULL) { - if ((hs->post_content_len_left != 0) -#if LWIP_HTTPD_POST_MANUAL_WND - || ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0)) -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - ) { - /* make sure the post code knows that the connection is closed */ - http_post_response_filename[0] = 0; - httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); - } - } -#endif /* LWIP_HTTPD_SUPPORT_POST*/ - - - tcp_arg(pcb, NULL); - tcp_recv(pcb, NULL); - tcp_err(pcb, NULL); - tcp_poll(pcb, NULL, 0); - tcp_sent(pcb, NULL); - if (hs != NULL) { - http_state_free(hs); - } - - if (abort_conn) { - tcp_abort(pcb); - return ERR_OK; - } - err = tcp_close(pcb); - if (err != ERR_OK) { - LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void*)pcb)); - /* error closing, try again later in poll */ - tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); - } - return err; -} - -/** - * The connection shall be actively closed. - * Reset the sent- and recv-callbacks. - * - * @param pcb the tcp pcb to reset callbacks - * @param hs connection state to free - */ -static err_t -http_close_conn(struct tcp_pcb *pcb, struct http_state *hs) -{ - return http_close_or_abort_conn(pcb, hs, 0); -} - -/** End of file: either close the connection (Connection: close) or - * close the file (Connection: keep-alive) - */ -static void -http_eof(struct tcp_pcb *pcb, struct http_state *hs) -{ - /* HTTP/1.1 persistent connection? (Not supported for SSI) */ -#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE - if (hs->keepalive && !LWIP_HTTPD_IS_SSI(hs)) { - http_state_eof(hs); - http_state_init(hs); - hs->keepalive = 1; - } else -#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ - { - http_close_conn(pcb, hs); - } -} - -#if LWIP_HTTPD_CGI -/** - * Extract URI parameters from the parameter-part of an URI in the form - * "test.cgi?x=y" @todo: better explanation! - * Pointers to the parameters are stored in hs->param_vals. - * - * @param hs http connection state - * @param params pointer to the NULL-terminated parameter string from the URI - * @return number of parameters extracted - */ -static int -extract_uri_parameters(struct http_state *hs, char *params) -{ - char *pair; - char *equals; - int loop; - - /* If we have no parameters at all, return immediately. */ - if(!params || (params[0] == '\0')) { - return(0); - } - - /* Get a pointer to our first parameter */ - pair = params; - - /* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the - * remainder (if any) */ - for(loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) { - - /* Save the name of the parameter */ - hs->params[loop] = pair; - - /* Remember the start of this name=value pair */ - equals = pair; - - /* Find the start of the next name=value pair and replace the delimiter - * with a 0 to terminate the previous pair string. */ - pair = strchr(pair, '&'); - if(pair) { - *pair = '\0'; - pair++; - } else { - /* We didn't find a new parameter so find the end of the URI and - * replace the space with a '\0' */ - pair = strchr(equals, ' '); - if(pair) { - *pair = '\0'; - } - - /* Revert to NULL so that we exit the loop as expected. */ - pair = NULL; - } - - /* Now find the '=' in the previous pair, replace it with '\0' and save - * the parameter value string. */ - equals = strchr(equals, '='); - if(equals) { - *equals = '\0'; - hs->param_vals[loop] = equals + 1; - } else { - hs->param_vals[loop] = NULL; - } - } - - return loop; -} -#endif /* LWIP_HTTPD_CGI */ - -#if LWIP_HTTPD_SSI -/** - * Insert a tag (found in an shtml in the form of "" into the file. - * The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement - * should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN). - * The amount of data written is stored to ssi->tag_insert_len. - * - * @todo: return tag_insert_len - maybe it can be removed from struct http_state? - * - * @param hs http connection state - */ -static void -get_tag_insert(struct http_state *hs) -{ - int loop; - size_t len; - struct http_ssi_state *ssi; - LWIP_ASSERT("hs != NULL", hs != NULL); - ssi = hs->ssi; - LWIP_ASSERT("ssi != NULL", ssi != NULL); -#if LWIP_HTTPD_SSI_MULTIPART - u16_t current_tag_part = ssi->tag_part; - ssi->tag_part = HTTPD_LAST_TAG_PART; -#endif /* LWIP_HTTPD_SSI_MULTIPART */ - - if(g_pfnSSIHandler && g_ppcTags && g_iNumTags) { - - /* Find this tag in the list we have been provided. */ - for(loop = 0; loop < g_iNumTags; loop++) { - if(strcmp(ssi->tag_name, g_ppcTags[loop]) == 0) { - ssi->tag_insert_len = g_pfnSSIHandler(loop, ssi->tag_insert, - LWIP_HTTPD_MAX_TAG_INSERT_LEN -#if LWIP_HTTPD_SSI_MULTIPART - , current_tag_part, &ssi->tag_part -#endif /* LWIP_HTTPD_SSI_MULTIPART */ -#if LWIP_HTTPD_FILE_STATE - , hs->handle->state -#endif /* LWIP_HTTPD_FILE_STATE */ - ); - return; - } - } - } - - /* If we drop out, we were asked to serve a page which contains tags that - * we don't have a handler for. Merely echo back the tags with an error - * marker. */ -#define UNKNOWN_TAG1_TEXT "***UNKNOWN TAG " -#define UNKNOWN_TAG1_LEN 18 -#define UNKNOWN_TAG2_TEXT "***" -#define UNKNOWN_TAG2_LEN 7 - len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name), - LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN))); - MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN); - MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len); - MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN); - ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0; - - len = strlen(ssi->tag_insert); - LWIP_ASSERT("len <= 0xffff", len <= 0xffff); - ssi->tag_insert_len = (u16_t)len; -} -#endif /* LWIP_HTTPD_SSI */ - -#if LWIP_HTTPD_DYNAMIC_HEADERS -/** - * Generate the relevant HTTP headers for the given filename and write - * them into the supplied buffer. - */ -static void -get_http_headers(struct http_state *pState, char *pszURI) -{ - unsigned int iLoop; - char *pszWork; - char *pszExt; - char *pszVars; - - /* Ensure that we initialize the loop counter. */ - iLoop = 0; - - /* In all cases, the second header we send is the server identification - so set it here. */ - pState->hdrs[1] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER]; - - /* Is this a normal file or the special case we use to send back the - default "404: Page not found" response? */ - if (pszURI == NULL) { - pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; - pState->hdrs[2] = g_psHTTPHeaderStrings[DEFAULT_404_HTML]; - - /* Set up to send the first header string. */ - pState->hdr_index = 0; - pState->hdr_pos = 0; - return; - } else { - /* We are dealing with a particular filename. Look for one other - special case. We assume that any filename with "404" in it must be - indicative of a 404 server error whereas all other files require - the 200 OK header. */ - if (strstr(pszURI, "404")) { - pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; - } else if (strstr(pszURI, "400")) { - pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST]; - } else if (strstr(pszURI, "501")) { - pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL]; - } else { - pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_OK]; - } - - /* Determine if the URI has any variables and, if so, temporarily remove - them. */ - pszVars = strchr(pszURI, '?'); - if(pszVars) { - *pszVars = '\0'; - } - - /* Get a pointer to the file extension. We find this by looking for the - last occurrence of "." in the filename passed. */ - pszExt = NULL; - pszWork = strchr(pszURI, '.'); - while(pszWork) { - pszExt = pszWork + 1; - pszWork = strchr(pszExt, '.'); - } - - /* Now determine the content type and add the relevant header for that. */ - for(iLoop = 0; (iLoop < NUM_HTTP_HEADERS) && pszExt; iLoop++) { - /* Have we found a matching extension? */ - if(!strcmp(g_psHTTPHeaders[iLoop].extension, pszExt)) { - pState->hdrs[2] = g_psHTTPHeaders[iLoop].content_type; - break; - } - } - - /* Reinstate the parameter marker if there was one in the original URI. */ - if(pszVars) { - *pszVars = '?'; - } - } - - /* Does the URL passed have any file extension? If not, we assume it - is a special-case URL used for control state notification and we do - not send any HTTP headers with the response. */ - if(!pszExt) { - /* Force the header index to a value indicating that all headers - have already been sent. */ - pState->hdr_index = NUM_FILE_HDR_STRINGS; - } else { - /* Did we find a matching extension? */ - if(iLoop == NUM_HTTP_HEADERS) { - /* No - use the default, plain text file type. */ - pState->hdrs[2] = HTTP_HDR_DEFAULT_TYPE; - } - - /* Set up to send the first header string. */ - pState->hdr_index = 0; - pState->hdr_pos = 0; - } -} - -/** Sub-function of http_send(): send dynamic headers - * - * @returns: - HTTP_NO_DATA_TO_SEND: no new data has been enqueued - * - HTTP_DATA_TO_SEND_CONTINUE: continue with sending HTTP body - * - HTTP_DATA_TO_SEND_BREAK: data has been enqueued, headers pending, - * so don't send HTTP body yet - */ -static u8_t -http_send_headers(struct tcp_pcb *pcb, struct http_state *hs) -{ - err_t err; - u16_t len; - u8_t data_to_send = HTTP_NO_DATA_TO_SEND; - u16_t hdrlen, sendlen; - - /* How much data can we send? */ - len = tcp_sndbuf(pcb); - sendlen = len; - - while(len && (hs->hdr_index < NUM_FILE_HDR_STRINGS) && sendlen) { - const void *ptr; - u16_t old_sendlen; - u8_t apiflags; - /* How much do we have to send from the current header? */ - hdrlen = (u16_t)strlen(hs->hdrs[hs->hdr_index]); - - /* How much of this can we send? */ - sendlen = (len < (hdrlen - hs->hdr_pos)) ? len : (hdrlen - hs->hdr_pos); - - /* Send this amount of data or as much as we can given memory - * constraints. */ - ptr = (const void *)(hs->hdrs[hs->hdr_index] + hs->hdr_pos); - old_sendlen = sendlen; - apiflags = HTTP_IS_HDR_VOLATILE(hs, ptr); - if (hs->hdr_index < NUM_FILE_HDR_STRINGS - 1) { - apiflags |= TCP_WRITE_FLAG_MORE; - } - err = http_write(pcb, ptr, &sendlen, apiflags); - if ((err == ERR_OK) && (old_sendlen != sendlen)) { - /* Remember that we added some more data to be transmitted. */ - data_to_send = HTTP_DATA_TO_SEND_CONTINUE; - } else if (err != ERR_OK) { - /* special case: http_write does not try to send 1 byte */ - sendlen = 0; - } - - /* Fix up the header position for the next time round. */ - hs->hdr_pos += sendlen; - len -= sendlen; - - /* Have we finished sending this string? */ - if(hs->hdr_pos == hdrlen) { - /* Yes - move on to the next one */ - hs->hdr_index++; - hs->hdr_pos = 0; - } - } - - if ((hs->hdr_index >= NUM_FILE_HDR_STRINGS) && (hs->file == NULL)) { - /* When we are at the end of the headers, check for data to send - * instead of waiting for ACK from remote side to continue - * (which would happen when sending files from async read). */ - http_check_eof(pcb, hs); - } - /* If we get here and there are still header bytes to send, we send - * the header information we just wrote immediately. If there are no - * more headers to send, but we do have file data to send, drop through - * to try to send some file data too. */ - if((hs->hdr_index < NUM_FILE_HDR_STRINGS) || !hs->file) { - LWIP_DEBUGF(HTTPD_DEBUG, ("tcp_output\n")); - return HTTP_DATA_TO_SEND_BREAK; - } - return data_to_send; -} -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ - -/** Sub-function of http_send(): end-of-file (or block) is reached, - * either close the file or read the next block (if supported). - * - * @returns: 0 if the file is finished or no data has been read - * 1 if the file is not finished and data has been read - */ -static u8_t -http_check_eof(struct tcp_pcb *pcb, struct http_state *hs) -{ - int bytes_left; -#if LWIP_HTTPD_DYNAMIC_FILE_READ - int count; -#ifdef HTTPD_MAX_WRITE_LEN - int max_write_len; -#endif /* HTTPD_MAX_WRITE_LEN */ -#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ - - /* Do we have a valid file handle? */ - if (hs->handle == NULL) { - /* No - close the connection. */ - http_eof(pcb, hs); - return 0; - } - bytes_left = fs_bytes_left(hs->handle); - if (bytes_left <= 0) { - /* We reached the end of the file so this request is done. */ - LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); - http_eof(pcb, hs); - return 0; - } -#if LWIP_HTTPD_DYNAMIC_FILE_READ - /* Do we already have a send buffer allocated? */ - if(hs->buf) { - /* Yes - get the length of the buffer */ - count = hs->buf_len; - } else { - /* We don't have a send buffer so allocate one now */ - count = tcp_sndbuf(pcb); - if(bytes_left < count) { - count = bytes_left; - } -#ifdef HTTPD_MAX_WRITE_LEN - /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ - max_write_len = HTTPD_MAX_WRITE_LEN(pcb); - if (count > max_write_len) { - count = max_write_len; - } -#endif /* HTTPD_MAX_WRITE_LEN */ - do { - hs->buf = (char*)mem_malloc((mem_size_t)count); - if (hs->buf != NULL) { - hs->buf_len = count; - break; - } - count = count / 2; - } while (count > 100); - - /* Did we get a send buffer? If not, return immediately. */ - if (hs->buf == NULL) { - LWIP_DEBUGF(HTTPD_DEBUG, ("No buff\n")); - return 0; - } - } - - /* Read a block of data from the file. */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Trying to read %d bytes.\n", count)); - -#if LWIP_HTTPD_FS_ASYNC_READ - count = fs_read_async(hs->handle, hs->buf, count, http_continue, hs); -#else /* LWIP_HTTPD_FS_ASYNC_READ */ - count = fs_read(hs->handle, hs->buf, count); -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - if (count < 0) { - if (count == FS_READ_DELAYED) { - /* Delayed read, wait for FS to unblock us */ - return 0; - } - /* We reached the end of the file so this request is done. - * @todo: don't close here for HTTP/1.1? */ - LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); - http_eof(pcb, hs); - return 0; - } - - /* Set up to send the block of data we just read */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Read %d bytes.\n", count)); - hs->left = count; - hs->file = hs->buf; -#if LWIP_HTTPD_SSI - if (hs->ssi) { - hs->ssi->parse_left = count; - hs->ssi->parsed = hs->buf; - } -#endif /* LWIP_HTTPD_SSI */ -#else /* LWIP_HTTPD_DYNAMIC_FILE_READ */ - LWIP_ASSERT("SSI and DYNAMIC_HEADERS turned off but eof not reached", 0); -#endif /* LWIP_HTTPD_SSI || LWIP_HTTPD_DYNAMIC_HEADERS */ - return 1; -} - -/** Sub-function of http_send(): This is the normal send-routine for non-ssi files - * - * @returns: - 1: data has been written (so call tcp_ouput) - * - 0: no data has been written (no need to call tcp_output) - */ -static u8_t -http_send_data_nonssi(struct tcp_pcb *pcb, struct http_state *hs) -{ - err_t err; - u16_t len; - u8_t data_to_send = 0; - - /* We are not processing an SHTML file so no tag checking is necessary. - * Just send the data as we received it from the file. */ - len = (u16_t)LWIP_MIN(hs->left, 0xffff); - - err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); - if (err == ERR_OK) { - data_to_send = 1; - hs->file += len; - hs->left -= len; - } - - return data_to_send; -} - -#if LWIP_HTTPD_SSI -/** Sub-function of http_send(): This is the send-routine for ssi files - * - * @returns: - 1: data has been written (so call tcp_ouput) - * - 0: no data has been written (no need to call tcp_output) - */ -static u8_t -http_send_data_ssi(struct tcp_pcb *pcb, struct http_state *hs) -{ - err_t err = ERR_OK; - u16_t len; - u8_t data_to_send = 0; - - struct http_ssi_state *ssi = hs->ssi; - LWIP_ASSERT("ssi != NULL", ssi != NULL); - /* We are processing an SHTML file so need to scan for tags and replace - * them with insert strings. We need to be careful here since a tag may - * straddle the boundary of two blocks read from the file and we may also - * have to split the insert string between two tcp_write operations. */ - - /* How much data could we send? */ - len = tcp_sndbuf(pcb); - - /* Do we have remaining data to send before parsing more? */ - if(ssi->parsed > hs->file) { - len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); - - err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); - if (err == ERR_OK) { - data_to_send = 1; - hs->file += len; - hs->left -= len; - } - - /* If the send buffer is full, return now. */ - if(tcp_sndbuf(pcb) == 0) { - return data_to_send; - } - } - - LWIP_DEBUGF(HTTPD_DEBUG, ("State %d, %d left\n", ssi->tag_state, (int)ssi->parse_left)); - - /* We have sent all the data that was already parsed so continue parsing - * the buffer contents looking for SSI tags. */ - while((ssi->parse_left) && (err == ERR_OK)) { - if (len == 0) { - return data_to_send; - } - switch(ssi->tag_state) { - case TAG_NONE: - /* We are not currently processing an SSI tag so scan for the - * start of the lead-in marker. */ - if(*ssi->parsed == g_pcTagLeadIn[0]) { - /* We found what could be the lead-in for a new tag so change - * state appropriately. */ - ssi->tag_state = TAG_LEADIN; - ssi->tag_index = 1; -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - ssi->tag_started = ssi->parsed; -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ - } - - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - break; - - case TAG_LEADIN: - /* We are processing the lead-in marker, looking for the start of - * the tag name. */ - - /* Have we reached the end of the leadin? */ - if(ssi->tag_index == LEN_TAG_LEAD_IN) { - ssi->tag_index = 0; - ssi->tag_state = TAG_FOUND; - } else { - /* Have we found the next character we expect for the tag leadin? */ - if(*ssi->parsed == g_pcTagLeadIn[ssi->tag_index]) { - /* Yes - move to the next one unless we have found the complete - * leadin, in which case we start looking for the tag itself */ - ssi->tag_index++; - } else { - /* We found an unexpected character so this is not a tag. Move - * back to idle state. */ - ssi->tag_state = TAG_NONE; - } - - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - } - break; - - case TAG_FOUND: - /* We are reading the tag name, looking for the start of the - * lead-out marker and removing any whitespace found. */ - - /* Remove leading whitespace between the tag leading and the first - * tag name character. */ - if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || - (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || - (*ssi->parsed == '\r'))) { - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - break; - } - - /* Have we found the end of the tag name? This is signalled by - * us finding the first leadout character or whitespace */ - if((*ssi->parsed == g_pcTagLeadOut[0]) || - (*ssi->parsed == ' ') || (*ssi->parsed == '\t') || - (*ssi->parsed == '\n') || (*ssi->parsed == '\r')) { - - if(ssi->tag_index == 0) { - /* We read a zero length tag so ignore it. */ - ssi->tag_state = TAG_NONE; - } else { - /* We read a non-empty tag so go ahead and look for the - * leadout string. */ - ssi->tag_state = TAG_LEADOUT; - LWIP_ASSERT("ssi->tag_index <= 0xff", ssi->tag_index <= 0xff); - ssi->tag_name_len = (u8_t)ssi->tag_index; - ssi->tag_name[ssi->tag_index] = '\0'; - if(*ssi->parsed == g_pcTagLeadOut[0]) { - ssi->tag_index = 1; - } else { - ssi->tag_index = 0; - } - } - } else { - /* This character is part of the tag name so save it */ - if(ssi->tag_index < LWIP_HTTPD_MAX_TAG_NAME_LEN) { - ssi->tag_name[ssi->tag_index++] = *ssi->parsed; - } else { - /* The tag was too long so ignore it. */ - ssi->tag_state = TAG_NONE; - } - } - - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - - break; - - /* We are looking for the end of the lead-out marker. */ - case TAG_LEADOUT: - /* Remove leading whitespace between the tag leading and the first - * tag leadout character. */ - if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || - (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || - (*ssi->parsed == '\r'))) { - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - break; - } - - /* Have we found the next character we expect for the tag leadout? */ - if(*ssi->parsed == g_pcTagLeadOut[ssi->tag_index]) { - /* Yes - move to the next one unless we have found the complete - * leadout, in which case we need to call the client to process - * the tag. */ - - /* Move on to the next character in the buffer */ - ssi->parse_left--; - ssi->parsed++; - - if(ssi->tag_index == (LEN_TAG_LEAD_OUT - 1)) { - /* Call the client to ask for the insert string for the - * tag we just found. */ -#if LWIP_HTTPD_SSI_MULTIPART - ssi->tag_part = 0; /* start with tag part 0 */ -#endif /* LWIP_HTTPD_SSI_MULTIPART */ - get_tag_insert(hs); - - /* Next time through, we are going to be sending data - * immediately, either the end of the block we start - * sending here or the insert string. */ - ssi->tag_index = 0; - ssi->tag_state = TAG_SENDING; - ssi->tag_end = ssi->parsed; -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - ssi->parsed = ssi->tag_started; -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ - - /* If there is any unsent data in the buffer prior to the - * tag, we need to send it now. */ - if (ssi->tag_end > hs->file) { - /* How much of the data can we send? */ -#if LWIP_HTTPD_SSI_INCLUDE_TAG - len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); -#else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ - /* we would include the tag in sending */ - len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); -#endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ - - err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); - if (err == ERR_OK) { - data_to_send = 1; -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - if(ssi->tag_started <= hs->file) { - /* pretend to have sent the tag, too */ - len += ssi->tag_end - ssi->tag_started; - } -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ - hs->file += len; - hs->left -= len; - } - } - } else { - ssi->tag_index++; - } - } else { - /* We found an unexpected character so this is not a tag. Move - * back to idle state. */ - ssi->parse_left--; - ssi->parsed++; - ssi->tag_state = TAG_NONE; - } - break; - - /* - * We have found a valid tag and are in the process of sending - * data as a result of that discovery. We send either remaining data - * from the file prior to the insert point or the insert string itself. - */ - case TAG_SENDING: - /* Do we have any remaining file data to send from the buffer prior - * to the tag? */ - if(ssi->tag_end > hs->file) { - /* How much of the data can we send? */ -#if LWIP_HTTPD_SSI_INCLUDE_TAG - len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); -#else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ - LWIP_ASSERT("hs->started >= hs->file", ssi->tag_started >= hs->file); - /* we would include the tag in sending */ - len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); -#endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ - if (len != 0) { - err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); - } else { - err = ERR_OK; - } - if (err == ERR_OK) { - data_to_send = 1; -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - if(ssi->tag_started <= hs->file) { - /* pretend to have sent the tag, too */ - len += ssi->tag_end - ssi->tag_started; - } -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ - hs->file += len; - hs->left -= len; - } - } else { -#if LWIP_HTTPD_SSI_MULTIPART - if(ssi->tag_index >= ssi->tag_insert_len) { - /* Did the last SSIHandler have more to send? */ - if (ssi->tag_part != HTTPD_LAST_TAG_PART) { - /* If so, call it again */ - ssi->tag_index = 0; - get_tag_insert(hs); - } - } -#endif /* LWIP_HTTPD_SSI_MULTIPART */ - - /* Do we still have insert data left to send? */ - if(ssi->tag_index < ssi->tag_insert_len) { - /* We are sending the insert string itself. How much of the - * insert can we send? */ - len = (ssi->tag_insert_len - ssi->tag_index); - - /* Note that we set the copy flag here since we only have a - * single tag insert buffer per connection. If we don't do - * this, insert corruption can occur if more than one insert - * is processed before we call tcp_output. */ - err = http_write(pcb, &(ssi->tag_insert[ssi->tag_index]), &len, - HTTP_IS_TAG_VOLATILE(hs)); - if (err == ERR_OK) { - data_to_send = 1; - ssi->tag_index += len; - /* Don't return here: keep on sending data */ - } - } else { -#if LWIP_HTTPD_SSI_MULTIPART - if (ssi->tag_part == HTTPD_LAST_TAG_PART) -#endif /* LWIP_HTTPD_SSI_MULTIPART */ - { - /* We have sent all the insert data so go back to looking for - * a new tag. */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Everything sent.\n")); - ssi->tag_index = 0; - ssi->tag_state = TAG_NONE; -#if !LWIP_HTTPD_SSI_INCLUDE_TAG - ssi->parsed = ssi->tag_end; -#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ - } - } - break; - } - } - } - - /* If we drop out of the end of the for loop, this implies we must have - * file data to send so send it now. In TAG_SENDING state, we've already - * handled this so skip the send if that's the case. */ - if((ssi->tag_state != TAG_SENDING) && (ssi->parsed > hs->file)) { - len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); - - err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); - if (err == ERR_OK) { - data_to_send = 1; - hs->file += len; - hs->left -= len; - } - } - return data_to_send; -} -#endif /* LWIP_HTTPD_SSI */ - -/** - * Try to send more data on this pcb. - * - * @param pcb the pcb to send data - * @param hs connection state - */ -static u8_t -http_send(struct tcp_pcb *pcb, struct http_state *hs) -{ - u8_t data_to_send = HTTP_NO_DATA_TO_SEND; - - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_send: pcb=%p hs=%p left=%d\n", (void*)pcb, - (void*)hs, hs != NULL ? (int)hs->left : 0)); - -#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND - if (hs->unrecved_bytes != 0) { - return 0; - } -#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ - - /* If we were passed a NULL state structure pointer, ignore the call. */ - if (hs == NULL) { - return 0; - } - -#if LWIP_HTTPD_FS_ASYNC_READ - /* Check if we are allowed to read from this file. - (e.g. SSI might want to delay sending until data is available) */ - if (!fs_is_file_ready(hs->handle, http_continue, hs)) { - return 0; - } -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - -#if LWIP_HTTPD_DYNAMIC_HEADERS - /* Do we have any more header data to send for this file? */ - if(hs->hdr_index < NUM_FILE_HDR_STRINGS) { - data_to_send = http_send_headers(pcb, hs); - if (data_to_send != HTTP_DATA_TO_SEND_CONTINUE) { - return data_to_send; - } - } -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ - - /* Have we run out of file data to send? If so, we need to read the next - * block from the file. */ - if (hs->left == 0) { - if (!http_check_eof(pcb, hs)) { - return 0; - } - } - -#if LWIP_HTTPD_SSI - if(hs->ssi) { - data_to_send = http_send_data_ssi(pcb, hs); - } else -#endif /* LWIP_HTTPD_SSI */ - { - data_to_send = http_send_data_nonssi(pcb, hs); - } - - if((hs->left == 0) && (fs_bytes_left(hs->handle) <= 0)) { - /* We reached the end of the file so this request is done. - * This adds the FIN flag right into the last data segment. */ - LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); - http_eof(pcb, hs); - return 0; - } - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("send_data end.\n")); - return data_to_send; -} - -#if LWIP_HTTPD_SUPPORT_EXTSTATUS -/** Initialize a http connection with a file to send for an error message - * - * @param hs http connection state - * @param error_nr HTTP error number - * @return ERR_OK if file was found and hs has been initialized correctly - * another err_t otherwise - */ -static err_t -http_find_error_file(struct http_state *hs, u16_t error_nr) -{ - const char *uri1, *uri2, *uri3; - err_t err; - - if (error_nr == 501) { - uri1 = "/501.html"; - uri2 = "/501.htm"; - uri3 = "/501.shtml"; - } else { - /* 400 (bad request is the default) */ - uri1 = "/400.html"; - uri2 = "/400.htm"; - uri3 = "/400.shtml"; - } - err = fs_open(&hs->file_handle, uri1); - if (err != ERR_OK) { - err = fs_open(&hs->file_handle, uri2); - if (err != ERR_OK) { - err = fs_open(&hs->file_handle, uri3); - if (err != ERR_OK) { - LWIP_DEBUGF(HTTPD_DEBUG, ("Error page for error %"U16_F" not found\n", - error_nr)); - return ERR_ARG; - } - } - } - return http_init_file(hs, &hs->file_handle, 0, NULL, 0); -} -#else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ -#define http_find_error_file(hs, error_nr) ERR_ARG -#endif /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ - -/** - * Get the file struct for a 404 error page. - * Tries some file names and returns NULL if none found. - * - * @param uri pointer that receives the actual file name URI - * @return file struct for the error page or NULL no matching file was found - */ -static struct fs_file * -http_get_404_file(struct http_state *hs, const char **uri) -{ - err_t err; - - *uri = "/404.html"; - err = fs_open(&hs->file_handle, *uri); - if (err != ERR_OK) { - /* 404.html doesn't exist. Try 404.htm instead. */ - *uri = "/404.htm"; - err = fs_open(&hs->file_handle, *uri); - if (err != ERR_OK) { - /* 404.htm doesn't exist either. Try 404.shtml instead. */ - *uri = "/404.shtml"; - err = fs_open(&hs->file_handle, *uri); - if (err != ERR_OK) { - /* 404.htm doesn't exist either. Indicate to the caller that it should - * send back a default 404 page. - */ - *uri = NULL; - return NULL; - } - } - } - - return &hs->file_handle; -} - -#if LWIP_HTTPD_SUPPORT_POST -static err_t -http_handle_post_finished(struct http_state *hs) -{ -#if LWIP_HTTPD_POST_MANUAL_WND - /* Prevent multiple calls to httpd_post_finished, since it might have already - been called before from httpd_post_data_recved(). */ - if (hs->post_finished) { - return ERR_OK; - } - hs->post_finished = 1; -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - /* application error or POST finished */ - /* NULL-terminate the buffer */ - http_post_response_filename[0] = 0; - httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); - return http_find_file(hs, http_post_response_filename, 0); -} - -/** Pass received POST body data to the application and correctly handle - * returning a response document or closing the connection. - * ATTENTION: The application is responsible for the pbuf now, so don't free it! - * - * @param hs http connection state - * @param p pbuf to pass to the application - * @return ERR_OK if passed successfully, another err_t if the response file - * hasn't been found (after POST finished) - */ -static err_t -http_post_rxpbuf(struct http_state *hs, struct pbuf *p) -{ - err_t err; - - /* adjust remaining Content-Length */ - if (hs->post_content_len_left < p->tot_len) { - hs->post_content_len_left = 0; - } else { - hs->post_content_len_left -= p->tot_len; - } - err = httpd_post_receive_data(hs, p); - if (err != ERR_OK) { - /* Ignore remaining content in case of application error */ - hs->post_content_len_left = 0; - } - if (hs->post_content_len_left == 0) { -#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND - if (hs->unrecved_bytes != 0) { - return ERR_OK; - } -#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ - /* application error or POST finished */ - return http_handle_post_finished(hs); - } - - return ERR_OK; -} - -/** Handle a post request. Called from http_parse_request when method 'POST' - * is found. - * - * @param p The input pbuf (containing the POST header and body). - * @param hs The http connection state. - * @param data HTTP request (header and part of body) from input pbuf(s). - * @param data_len Size of 'data'. - * @param uri The HTTP URI parsed from input pbuf(s). - * @param uri_end Pointer to the end of 'uri' (here, the rest of the HTTP - * header starts). - * @return ERR_OK: POST correctly parsed and accepted by the application. - * ERR_INPROGRESS: POST not completely parsed (no error yet) - * another err_t: Error parsing POST or denied by the application - */ -static err_t -http_post_request(struct pbuf *inp, struct http_state *hs, - char *data, u16_t data_len, char *uri, char *uri_end) -{ - err_t err; - /* search for end-of-header (first double-CRLF) */ - char* crlfcrlf = strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data)); - - if (crlfcrlf != NULL) { - /* search for "Content-Length: " */ -#define HTTP_HDR_CONTENT_LEN "Content-Length: " -#define HTTP_HDR_CONTENT_LEN_LEN 16 -#define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN 10 - char *scontent_len = strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1)); - if (scontent_len != NULL) { - char *scontent_len_end = strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN); - if (scontent_len_end != NULL) { - int content_len; - char *conten_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN; - content_len = atoi(conten_len_num); - if (content_len > 0) { - /* adjust length of HTTP header passed to application */ - const char *hdr_start_after_uri = uri_end + 1; - u16_t hdr_len = LWIP_MIN(data_len, crlfcrlf + 4 - data); - u16_t hdr_data_len = LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri); - u8_t post_auto_wnd = 1; - http_post_response_filename[0] = 0; - err = httpd_post_begin(hs, uri, hdr_start_after_uri, hdr_data_len, content_len, - http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN, &post_auto_wnd); - if (err == ERR_OK) { - /* try to pass in data of the first pbuf(s) */ - struct pbuf *q = inp; - u16_t start_offset = hdr_len; -#if LWIP_HTTPD_POST_MANUAL_WND - hs->no_auto_wnd = !post_auto_wnd; -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - /* set the Content-Length to be received for this POST */ - hs->post_content_len_left = (u32_t)content_len; - - /* get to the pbuf where the body starts */ - while((q != NULL) && (q->len <= start_offset)) { - start_offset -= q->len; - q = q->next; - } - if (q != NULL) { - /* hide the remaining HTTP header */ - pbuf_header(q, -(s16_t)start_offset); -#if LWIP_HTTPD_POST_MANUAL_WND - if (!post_auto_wnd) { - /* already tcp_recved() this data... */ - hs->unrecved_bytes = q->tot_len; - } -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - pbuf_ref(q); - return http_post_rxpbuf(hs, q); - } else { - return ERR_OK; - } - } else { - /* return file passed from application */ - return http_find_file(hs, http_post_response_filename, 0); - } - } else { - LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n", - conten_len_num)); - return ERR_ARG; - } - } - } - /* If we come here, headers are fully received (double-crlf), but Content-Length - was not included. Since this is currently the only supported method, we have - to fail in this case! */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Error when parsing Content-Length\n")); - return ERR_ARG; - } - /* if we come here, the POST is incomplete */ -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - return ERR_INPROGRESS; -#else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - return ERR_ARG; -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ -} - -#if LWIP_HTTPD_POST_MANUAL_WND -/** A POST implementation can call this function to update the TCP window. - * This can be used to throttle data reception (e.g. when received data is - * programmed to flash and data is received faster than programmed). - * - * @param connection A connection handle passed to httpd_post_begin for which - * httpd_post_finished has *NOT* been called yet! - * @param recved_len Length of data received (for window update) - */ -void httpd_post_data_recved(void *connection, u16_t recved_len) -{ - struct http_state *hs = (struct http_state*)connection; - if (hs != NULL) { - if (hs->no_auto_wnd) { - u16_t len = recved_len; - if (hs->unrecved_bytes >= recved_len) { - hs->unrecved_bytes -= recved_len; - } else { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("httpd_post_data_recved: recved_len too big\n")); - len = (u16_t)hs->unrecved_bytes; - hs->unrecved_bytes = 0; - } - if (hs->pcb != NULL) { - if (len != 0) { - tcp_recved(hs->pcb, len); - } - if ((hs->post_content_len_left == 0) && (hs->unrecved_bytes == 0)) { - /* finished handling POST */ - http_handle_post_finished(hs); - http_send(hs->pcb, hs); - } - } - } - } -} -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - -#endif /* LWIP_HTTPD_SUPPORT_POST */ - -#if LWIP_HTTPD_FS_ASYNC_READ -/** Try to send more data if file has been blocked before - * This is a callback function passed to fs_read_async(). - */ -static void -http_continue(void *connection) -{ - struct http_state *hs = (struct http_state*)connection; - if (hs && (hs->pcb) && (hs->handle)) { - LWIP_ASSERT("hs->pcb != NULL", hs->pcb != NULL); - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("httpd_continue: try to send more data\n")); - if (http_send(hs->pcb, hs)) { - /* If we wrote anything to be sent, go ahead and send it now. */ - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); - tcp_output(hs->pcb); - } - } -} -#endif /* LWIP_HTTPD_FS_ASYNC_READ */ - -/** - * When data has been received in the correct state, try to parse it - * as a HTTP request. - * - * @param p the received pbuf - * @param hs the connection state - * @param pcb the tcp_pcb which received this packet - * @return ERR_OK if request was OK and hs has been initialized correctly - * ERR_INPROGRESS if request was OK so far but not fully received - * another err_t otherwise - */ -static err_t -http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) -{ - char *data; - char *crlf; - u16_t data_len; - struct pbuf *p = inp; -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - u16_t clen; -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ -#if LWIP_HTTPD_SUPPORT_POST - err_t err; -#endif /* LWIP_HTTPD_SUPPORT_POST */ - - LWIP_UNUSED_ARG(pcb); /* only used for post */ - LWIP_ASSERT("p != NULL", p != NULL); - LWIP_ASSERT("hs != NULL", hs != NULL); - - if ((hs->handle != NULL) || (hs->file != NULL)) { - LWIP_DEBUGF(HTTPD_DEBUG, ("Received data while sending a file\n")); - /* already sending a file */ - /* @todo: abort? */ - return ERR_USE; - } - -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - - LWIP_DEBUGF(HTTPD_DEBUG, ("Received %"U16_F" bytes\n", p->tot_len)); - - /* first check allowed characters in this pbuf? */ - - /* enqueue the pbuf */ - if (hs->req == NULL) { - LWIP_DEBUGF(HTTPD_DEBUG, ("First pbuf\n")); - hs->req = p; - } else { - LWIP_DEBUGF(HTTPD_DEBUG, ("pbuf enqueued\n")); - pbuf_cat(hs->req, p); - } - /* increase pbuf ref counter as it is freed when we return but we want to - keep it on the req list */ - pbuf_ref(p); - - if (hs->req->next != NULL) { - data_len = LWIP_MIN(hs->req->tot_len, LWIP_HTTPD_MAX_REQ_LENGTH); - pbuf_copy_partial(hs->req, httpd_req_buf, data_len, 0); - data = httpd_req_buf; - } else -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - { - data = (char *)p->payload; - data_len = p->len; - if (p->len != p->tot_len) { - LWIP_DEBUGF(HTTPD_DEBUG, ("Warning: incomplete header due to chained pbufs\n")); - } - } - - /* received enough data for minimal request? */ - if (data_len >= MIN_REQ_LEN) { - /* wait for CRLF before parsing anything */ - crlf = strnstr(data, CRLF, data_len); - if (crlf != NULL) { -#if LWIP_HTTPD_SUPPORT_POST - int is_post = 0; -#endif /* LWIP_HTTPD_SUPPORT_POST */ - int is_09 = 0; - char *sp1, *sp2; - u16_t left_len, uri_len; - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n")); - /* parse method */ - if (!strncmp(data, "GET ", 4)) { - sp1 = data + 3; - /* received GET request */ - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n")); -#if LWIP_HTTPD_SUPPORT_POST - } else if (!strncmp(data, "POST ", 5)) { - /* store request type */ - is_post = 1; - sp1 = data + 4; - /* received GET request */ - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n")); -#endif /* LWIP_HTTPD_SUPPORT_POST */ - } else { - /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ - data[4] = 0; - /* unsupported method! */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n", - data)); - return http_find_error_file(hs, 501); - } - /* if we come here, method is OK, parse URI */ - left_len = data_len - ((sp1 +1) - data); - sp2 = strnstr(sp1 + 1, " ", left_len); -#if LWIP_HTTPD_SUPPORT_V09 - if (sp2 == NULL) { - /* HTTP 0.9: respond with correct protocol version */ - sp2 = strnstr(sp1 + 1, CRLF, left_len); - is_09 = 1; -#if LWIP_HTTPD_SUPPORT_POST - if (is_post) { - /* HTTP/0.9 does not support POST */ - goto badrequest; - } -#endif /* LWIP_HTTPD_SUPPORT_POST */ - } -#endif /* LWIP_HTTPD_SUPPORT_V09 */ - uri_len = sp2 - (sp1 + 1); - if ((sp2 != 0) && (sp2 > sp1)) { - /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */ - if (strnstr(data, CRLF CRLF, data_len) != NULL) { - char *uri = sp1 + 1; -#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE - if (!is_09 && strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len)) { - hs->keepalive = 1; - } -#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ - /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ - *sp1 = 0; - uri[uri_len] = 0; - LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n", - data, uri)); -#if LWIP_HTTPD_SUPPORT_POST - if (is_post) { -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - struct pbuf *q = hs->req; -#else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - struct pbuf *q = inp; -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - err = http_post_request(q, hs, data, data_len, uri, sp2); - if (err != ERR_OK) { - /* restore header for next try */ - *sp1 = ' '; - *sp2 = ' '; - uri[uri_len] = ' '; - } - if (err == ERR_ARG) { - goto badrequest; - } - return err; - } else -#endif /* LWIP_HTTPD_SUPPORT_POST */ - { - return http_find_file(hs, uri, is_09); - } - } - } else { - LWIP_DEBUGF(HTTPD_DEBUG, ("invalid URI\n")); - } - } - } - -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - clen = pbuf_clen(hs->req); - if ((hs->req->tot_len <= LWIP_HTTPD_REQ_BUFSIZE) && - (clen <= LWIP_HTTPD_REQ_QUEUELEN)) { - /* request not fully received (too short or CRLF is missing) */ - return ERR_INPROGRESS; - } else -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - { -#if LWIP_HTTPD_SUPPORT_POST -badrequest: -#endif /* LWIP_HTTPD_SUPPORT_POST */ - LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n")); - /* could not parse request */ - return http_find_error_file(hs, 400); - } -} - -/** Try to find the file specified by uri and, if found, initialize hs - * accordingly. - * - * @param hs the connection state - * @param uri the HTTP header URI - * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) - * @return ERR_OK if file was found and hs has been initialized correctly - * another err_t otherwise - */ -static err_t -http_find_file(struct http_state *hs, const char *uri, int is_09) -{ - size_t loop; - struct fs_file *file = NULL; - char *params; - err_t err; -#if LWIP_HTTPD_CGI - int i; - int count; -#endif /* LWIP_HTTPD_CGI */ -#if !LWIP_HTTPD_SSI - const -#endif /* !LWIP_HTTPD_SSI */ - /* By default, assume we will not be processing server-side-includes tags */ - u8_t tag_check = 0; - - /* Have we been asked for the default root file? */ - if((uri[0] == '/') && (uri[1] == 0)) { - /* Try each of the configured default filenames until we find one - that exists. */ - for (loop = 0; loop < NUM_DEFAULT_FILENAMES; loop++) { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Looking for %s...\n", g_psDefaultFilenames[loop].name)); - err = fs_open(&hs->file_handle, (char *)g_psDefaultFilenames[loop].name); - uri = (char *)g_psDefaultFilenames[loop].name; - if(err == ERR_OK) { - file = &hs->file_handle; - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opened.\n")); -#if LWIP_HTTPD_SSI - tag_check = g_psDefaultFilenames[loop].shtml; -#endif /* LWIP_HTTPD_SSI */ - break; - } - } - if (file == NULL) { - /* None of the default filenames exist so send back a 404 page */ - file = http_get_404_file(hs, &uri); -#if LWIP_HTTPD_SSI - tag_check = 0; -#endif /* LWIP_HTTPD_SSI */ - } - } else { - /* No - we've been asked for a specific file. */ - /* First, isolate the base URI (without any parameters) */ - params = (char *)strchr(uri, '?'); - if (params != NULL) { - /* URI contains parameters. NULL-terminate the base URI */ - *params = '\0'; - params++; - } - -#if LWIP_HTTPD_CGI - /* Does the base URI we have isolated correspond to a CGI handler? */ - if (g_iNumCGIs && g_pCGIs) { - for (i = 0; i < g_iNumCGIs; i++) { - if (strcmp(uri, g_pCGIs[i].pcCGIName) == 0) { - /* - * We found a CGI that handles this URI so extract the - * parameters and call the handler. - */ - count = extract_uri_parameters(hs, params); - uri = g_pCGIs[i].pfnCGIHandler(i, count, hs->params, - hs->param_vals); - break; - } - } - } -#endif /* LWIP_HTTPD_CGI */ - - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opening %s\n", uri)); - - err = fs_open(&hs->file_handle, uri); - if (err == ERR_OK) { - file = &hs->file_handle; - } else { - file = http_get_404_file(hs, &uri); - } -#if LWIP_HTTPD_SSI - if (file != NULL) { - /* See if we have been asked for an shtml file and, if so, - enable tag checking. */ - tag_check = 0; - for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) { - if (strstr(uri, g_pcSSIExtensions[loop])) { - tag_check = 1; - break; - } - } - } -#endif /* LWIP_HTTPD_SSI */ - } - return http_init_file(hs, file, is_09, uri, tag_check); -} - -/** Initialize a http connection with a file to send (if found). - * Called by http_find_file and http_find_error_file. - * - * @param hs http connection state - * @param file file structure to send (or NULL if not found) - * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) - * @param uri the HTTP header URI - * @param tag_check enable SSI tag checking - * @return ERR_OK if file was found and hs has been initialized correctly - * another err_t otherwise - */ -static err_t -http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check) -{ - if (file != NULL) { - /* file opened, initialise struct http_state */ -#if LWIP_HTTPD_SSI - if (tag_check) { - struct http_ssi_state *ssi = http_ssi_state_alloc(); - if (ssi != NULL) { - ssi->tag_index = 0; - ssi->tag_state = TAG_NONE; - ssi->parsed = file->data; - ssi->parse_left = file->len; - ssi->tag_end = file->data; - hs->ssi = ssi; - } - } -#else /* LWIP_HTTPD_SSI */ - LWIP_UNUSED_ARG(tag_check); -#endif /* LWIP_HTTPD_SSI */ - hs->handle = file; - hs->file = (char*)file->data; - LWIP_ASSERT("File length must be positive!", (file->len >= 0)); - hs->left = file->len; - hs->retries = 0; -#if LWIP_HTTPD_TIMING - hs->time_started = sys_now(); -#endif /* LWIP_HTTPD_TIMING */ -#if !LWIP_HTTPD_DYNAMIC_HEADERS - LWIP_ASSERT("HTTP headers not included in file system", hs->handle->http_header_included); -#endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ -#if LWIP_HTTPD_SUPPORT_V09 - if (hs->handle->http_header_included && is_09) { - /* HTTP/0.9 responses are sent without HTTP header, - search for the end of the header. */ - char *file_start = strnstr(hs->file, CRLF CRLF, hs->left); - if (file_start != NULL) { - size_t diff = file_start + 4 - hs->file; - hs->file += diff; - hs->left -= (u32_t)diff; - } - } -#endif /* LWIP_HTTPD_SUPPORT_V09*/ - } else { - hs->handle = NULL; - hs->file = NULL; - hs->left = 0; - hs->retries = 0; - } -#if LWIP_HTTPD_DYNAMIC_HEADERS - /* Determine the HTTP headers to send based on the file extension of - * the requested URI. */ - if ((hs->handle == NULL) || !hs->handle->http_header_included) { - get_http_headers(hs, (char*)uri); - } -#else /* LWIP_HTTPD_DYNAMIC_HEADERS */ - LWIP_UNUSED_ARG(uri); -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ - return ERR_OK; -} - -/** - * The pcb had an error and is already deallocated. - * The argument might still be valid (if != NULL). - */ -static void -http_err(void *arg, err_t err) -{ - struct http_state *hs = (struct http_state *)arg; - LWIP_UNUSED_ARG(err); - - LWIP_DEBUGF(HTTPD_DEBUG, ("http_err: %s", lwip_strerr(err))); - - if (hs != NULL) { - http_state_free(hs); - } -} - -/** - * Data has been sent and acknowledged by the remote host. - * This means that more data can be sent. - */ -static err_t -http_sent(void *arg, struct tcp_pcb *pcb, u16_t len) -{ - struct http_state *hs = (struct http_state *)arg; - - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_sent %p\n", (void*)pcb)); - - LWIP_UNUSED_ARG(len); - - if (hs == NULL) { - return ERR_OK; - } - - hs->retries = 0; - - http_send(pcb, hs); - - return ERR_OK; -} - -/** - * The poll function is called every 2nd second. - * If there has been no data sent (which resets the retries) in 8 seconds, close. - * If the last portion of a file has not been sent in 2 seconds, close. - * - * This could be increased, but we don't want to waste resources for bad connections. - */ -static err_t -http_poll(void *arg, struct tcp_pcb *pcb) -{ - struct http_state *hs = (struct http_state *)arg; - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: pcb=%p hs=%p pcb_state=%s\n", - (void*)pcb, (void*)hs, tcp_debug_state_str(pcb->state))); - - if (hs == NULL) { - err_t closed; - /* arg is null, close. */ - LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: arg is NULL, close\n")); - closed = http_close_conn(pcb, NULL); - LWIP_UNUSED_ARG(closed); -#if LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR - if (closed == ERR_MEM) { - tcp_abort(pcb); - return ERR_ABRT; - } -#endif /* LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR */ - return ERR_OK; - } else { - hs->retries++; - if (hs->retries == HTTPD_MAX_RETRIES) { - LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: too many retries, close\n")); - http_close_conn(pcb, hs); - return ERR_OK; - } - - /* If this connection has a file open, try to send some more data. If - * it has not yet received a GET request, don't do this since it will - * cause the connection to close immediately. */ - if(hs && (hs->handle)) { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: try to send more data\n")); - if(http_send(pcb, hs)) { - /* If we wrote anything to be sent, go ahead and send it now. */ - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); - tcp_output(pcb); - } - } - } - - return ERR_OK; -} - -/** - * Data has been received on this pcb. - * For HTTP 1.0, this should normally only happen once (if the request fits in one packet). - */ -static err_t -http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) -{ - err_t parsed = ERR_ABRT; - struct http_state *hs = (struct http_state *)arg; - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: pcb=%p pbuf=%p err=%s\n", (void*)pcb, - (void*)p, lwip_strerr(err))); - - if ((err != ERR_OK) || (p == NULL) || (hs == NULL)) { - /* error or closed by other side? */ - if (p != NULL) { - /* Inform TCP that we have taken the data. */ - tcp_recved(pcb, p->tot_len); - pbuf_free(p); - } - if (hs == NULL) { - /* this should not happen, only to be robust */ - LWIP_DEBUGF(HTTPD_DEBUG, ("Error, http_recv: hs is NULL, close\n")); - } - http_close_conn(pcb, hs); - return ERR_OK; - } - -#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND - if (hs->no_auto_wnd) { - hs->unrecved_bytes += p->tot_len; - } else -#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ - { - /* Inform TCP that we have taken the data. */ - tcp_recved(pcb, p->tot_len); - } - -#if LWIP_HTTPD_SUPPORT_POST - if (hs->post_content_len_left > 0) { - /* reset idle counter when POST data is received */ - hs->retries = 0; - /* this is data for a POST, pass the complete pbuf to the application */ - http_post_rxpbuf(hs, p); - /* pbuf is passed to the application, don't free it! */ - if (hs->post_content_len_left == 0) { - /* all data received, send response or close connection */ - http_send(pcb, hs); - } - return ERR_OK; - } else -#endif /* LWIP_HTTPD_SUPPORT_POST */ - { - if (hs->handle == NULL) { - parsed = http_parse_request(p, hs, pcb); - LWIP_ASSERT("http_parse_request: unexpected return value", parsed == ERR_OK - || parsed == ERR_INPROGRESS ||parsed == ERR_ARG || parsed == ERR_USE); - } else { - LWIP_DEBUGF(HTTPD_DEBUG, ("http_recv: already sending data\n")); - /* already sending but still receiving data, we might want to RST here? */ - pbuf_free(p); - } -#if LWIP_HTTPD_SUPPORT_REQUESTLIST - if (parsed != ERR_INPROGRESS) { - /* request fully parsed or error */ - if (hs->req != NULL) { - pbuf_free(hs->req); - hs->req = NULL; - } - } -#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ - pbuf_free(p); - if (parsed == ERR_OK) { -#if LWIP_HTTPD_SUPPORT_POST - if (hs->post_content_len_left == 0) -#endif /* LWIP_HTTPD_SUPPORT_POST */ - { - LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: data %p len %"S32_F"\n", hs->file, hs->left)); - http_send(pcb, hs); - } - } else if (parsed == ERR_ARG) { - /* @todo: close on ERR_USE? */ - http_close_conn(pcb, hs); - } - } - return ERR_OK; -} - -/** - * A new incoming connection has been accepted. - */ -static err_t -http_accept(void *arg, struct tcp_pcb *pcb, err_t err) -{ - struct http_state *hs; - struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)arg; - LWIP_UNUSED_ARG(err); - LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept %p / %p\n", (void*)pcb, arg)); - - /* Decrease the listen backlog counter */ - tcp_accepted(lpcb); - /* Set priority */ - tcp_setprio(pcb, HTTPD_TCP_PRIO); - - /* Allocate memory for the structure that holds the state of the - connection - initialized by that function. */ - hs = http_state_alloc(); - if (hs == NULL) { - LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept: Out of memory, RST\n")); - return ERR_MEM; - } - hs->pcb = pcb; - - /* Tell TCP that this is the structure we wish to be passed for our - callbacks. */ - tcp_arg(pcb, hs); - - /* Set up the various callback functions */ - tcp_recv(pcb, http_recv); - tcp_err(pcb, http_err); - tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); - tcp_sent(pcb, http_sent); - - return ERR_OK; -} - -/** - * Initialize the httpd with the specified local address. - */ -static void -httpd_init_addr(ip_addr_t *local_addr) -{ - struct tcp_pcb *pcb; - err_t err; - - pcb = tcp_new(); - LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL); - tcp_setprio(pcb, HTTPD_TCP_PRIO); - /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */ - err = tcp_bind(pcb, local_addr, HTTPD_SERVER_PORT); - LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK); - pcb = tcp_listen(pcb); - LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL); - /* initialize callback arg and accept callback */ - tcp_arg(pcb, pcb); - tcp_accept(pcb, http_accept); -} - -/** - * Initialize the httpd: set up a listening PCB and bind it to the defined port - */ -void -httpd_init(void) -{ -#if MEMP_MEM_MALLOC || MEM_USE_POOLS -#if HTTPD_USE_MEM_POOL - LWIP_ASSERT("memp_sizes[MEMP_HTTPD_STATE] >= sizeof(http_state)", - memp_sizes[MEMP_HTTPD_STATE] >= sizeof(struct http_state)); -#if LWIP_HTTPD_SSI - LWIP_ASSERT("memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(http_ssi_state)", - memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(struct http_ssi_state)); -#endif -#endif -#endif - LWIP_DEBUGF(HTTPD_DEBUG, ("httpd_init\n")); - - httpd_init_addr(IP_ADDR_ANY); -} - -#if LWIP_HTTPD_SSI -/** - * Set the SSI handler function. - * - * @param ssi_handler the SSI handler function - * @param tags an array of SSI tag strings to search for in SSI-enabled files - * @param num_tags number of tags in the 'tags' array - */ -void -http_set_ssi_handler(tSSIHandler ssi_handler, const char **tags, int num_tags) -{ - LWIP_DEBUGF(HTTPD_DEBUG, ("http_set_ssi_handler\n")); - - LWIP_ASSERT("no ssi_handler given", ssi_handler != NULL); - LWIP_ASSERT("no tags given", tags != NULL); - LWIP_ASSERT("invalid number of tags", num_tags > 0); - - g_pfnSSIHandler = ssi_handler; - g_ppcTags = tags; - g_iNumTags = num_tags; -} -#endif /* LWIP_HTTPD_SSI */ - -#if LWIP_HTTPD_CGI -/** - * Set an array of CGI filenames/handler functions - * - * @param cgis an array of CGI filenames/handler functions - * @param num_handlers number of elements in the 'cgis' array - */ -void -http_set_cgi_handlers(const tCGI *cgis, int num_handlers) -{ - LWIP_ASSERT("no cgis given", cgis != NULL); - LWIP_ASSERT("invalid number of handlers", num_handlers > 0); - - g_pCGIs = cgis; - g_iNumCGIs = num_handlers; -} -#endif /* LWIP_HTTPD_CGI */ - -#endif /* LWIP_TCP */ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * Simon Goldschmidt * */ /* This httpd supports for a * rudimentary server-side-include facility which will replace tags of the form * in any file whose extension is .shtml, .shtm or .ssi with * strings provided by an include handler whose pointer is provided to the * module via function http_set_ssi_handler(). * Additionally, a simple common * gateway interface (CGI) handling mechanism has been added to allow clients * to hook functions to particular request URIs. * * To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h. * To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h. * * By default, the server assumes that HTTP headers are already present in * each file stored in the file system. By defining LWIP_HTTPD_DYNAMIC_HEADERS in * lwipopts.h, this behavior can be changed such that the server inserts the * headers automatically based on the extension of the file being served. If * this mode is used, be careful to ensure that the file system image used * does not already contain the header information. * * File system images without headers can be created using the makefsfile * tool with the -h command line option. * * * Notes about valid SSI tags * -------------------------- * * The following assumptions are made about tags used in SSI markers: * * 1. No tag may contain '-' or whitespace characters within the tag name. * 2. Whitespace is allowed between the tag leadin "". * 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters. * * Notes on CGI usage * ------------------ * * The simple CGI support offered here works with GET method requests only * and can handle up to 16 parameters encoded into the URI. The handler * function may not write directly to the HTTP output but must return a * filename that the HTTP server will send to the browser as a response to * the incoming CGI request. * * * * The list of supported file types is quite short, so if makefsdata complains * about an unknown extension, make sure to add it (and its doctype) to * the 'g_psHTTPHeaders' list. */ #include "httpd.h" #include "lwip/debug.h" #include "lwip/stats.h" #include "httpd_structs.h" #include "lwip/tcp.h" #include "fs.h" #include #include #if LWIP_TCP #ifndef HTTPD_DEBUG #define HTTPD_DEBUG LWIP_DBG_OFF #endif /** Set this to 1, set MEMP_USE_CUSTOM_POOLS to 1 and add the next line to * lwippools.h to use a memp pool for allocating struct http_state instead of * the heap: * * LWIP_MEMPOOL(HTTPD_STATE, 20, 100, "HTTPD_STATE") */ #ifndef HTTPD_USE_MEM_POOL #define HTTPD_USE_MEM_POOL 0 #endif /** The server port for HTTPD to use */ #ifndef HTTPD_SERVER_PORT #define HTTPD_SERVER_PORT 80 #endif /** Maximum retries before the connection is aborted/closed. * - number of times pcb->poll is called -> default is 4*500ms = 2s; * - reset when pcb->sent is called */ #ifndef HTTPD_MAX_RETRIES #define HTTPD_MAX_RETRIES 4 #endif /** The poll delay is X*500ms */ #ifndef HTTPD_POLL_INTERVAL #define HTTPD_POLL_INTERVAL 4 #endif /** Priority for tcp pcbs created by HTTPD (very low by default). * Lower priorities get killed first when running out of memory. */ #ifndef HTTPD_TCP_PRIO #define HTTPD_TCP_PRIO TCP_PRIO_MIN #endif /** Set this to 1 to enable timing each file sent */ #ifndef LWIP_HTTPD_TIMING #define LWIP_HTTPD_TIMING 0 #endif #ifndef HTTPD_DEBUG_TIMING #define HTTPD_DEBUG_TIMING LWIP_DBG_OFF #endif /** Set this to 1 on platforms where strnstr is not available */ #ifndef LWIP_HTTPD_STRNSTR_PRIVATE #define LWIP_HTTPD_STRNSTR_PRIVATE 1 #endif /** Set this to one to show error pages when parsing a request fails instead of simply closing the connection. */ #ifndef LWIP_HTTPD_SUPPORT_EXTSTATUS #define LWIP_HTTPD_SUPPORT_EXTSTATUS 0 #endif /** Set this to 0 to drop support for HTTP/0.9 clients (to save some bytes) */ #ifndef LWIP_HTTPD_SUPPORT_V09 #define LWIP_HTTPD_SUPPORT_V09 1 #endif /** Set this to 1 to enable HTTP/1.1 persistent connections. * ATTENTION: If the generated file system includes HTTP headers, these must * include the "Connection: keep-alive" header (pass argument "-11" to makefsdata). */ #ifndef LWIP_HTTPD_SUPPORT_11_KEEPALIVE #define LWIP_HTTPD_SUPPORT_11_KEEPALIVE 0 #endif /** Set this to 1 to support HTTP request coming in in multiple packets/pbufs */ #ifndef LWIP_HTTPD_SUPPORT_REQUESTLIST #define LWIP_HTTPD_SUPPORT_REQUESTLIST 1 #endif #if LWIP_HTTPD_SUPPORT_REQUESTLIST /** Number of rx pbufs to enqueue to parse an incoming request (up to the first newline) */ #ifndef LWIP_HTTPD_REQ_QUEUELEN #define LWIP_HTTPD_REQ_QUEUELEN 5 #endif /** Number of (TCP payload-) bytes (in pbufs) to enqueue to parse and incoming request (up to the first double-newline) */ #ifndef LWIP_HTTPD_REQ_BUFSIZE #define LWIP_HTTPD_REQ_BUFSIZE LWIP_HTTPD_MAX_REQ_LENGTH #endif /** Defines the maximum length of a HTTP request line (up to the first CRLF, copied from pbuf into this a global buffer when pbuf- or packet-queues are received - otherwise the input pbuf is used directly) */ #ifndef LWIP_HTTPD_MAX_REQ_LENGTH #define LWIP_HTTPD_MAX_REQ_LENGTH LWIP_MIN(1023, (LWIP_HTTPD_REQ_QUEUELEN * PBUF_POOL_BUFSIZE)) #endif #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ /** Maximum length of the filename to send as response to a POST request, * filled in by the application when a POST is finished. */ #ifndef LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN #define LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN 63 #endif /** Set this to 0 to not send the SSI tag (default is on, so the tag will * be sent in the HTML page */ #ifndef LWIP_HTTPD_SSI_INCLUDE_TAG #define LWIP_HTTPD_SSI_INCLUDE_TAG 1 #endif /** Set this to 1 to call tcp_abort when tcp_close fails with memory error. * This can be used to prevent consuming all memory in situations where the * HTTP server has low priority compared to other communication. */ #ifndef LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR #define LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR 0 #endif /** Set this to 1 to kill the oldest connection when running out of * memory for 'struct http_state' or 'struct http_ssi_state'. * ATTENTION: This puts all connections on a linked list, so may be kind of slow. */ #ifndef LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED #define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 0 #endif /** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */ #define MIN_REQ_LEN 7 #define CRLF "\r\n" #define HTTP11_CONNECTIONKEEPALIVE "Connection: keep-alive" #if LWIP_HTTPD_SSI #define LWIP_HTTPD_IS_SSI(hs) ((hs)->ssi) #else /* LWIP_HTTPD_SSI */ #define LWIP_HTTPD_IS_SSI(hs) 0 #endif /* LWIP_HTTPD_SSI */ /** These defines check whether tcp_write has to copy data or not */ /** This was TI's check whether to let TCP copy data or not #define HTTP_IS_DATA_VOLATILE(hs) ((hs->file < (char *)0x20000000) ? 0 : TCP_WRITE_FLAG_COPY)*/ #ifndef HTTP_IS_DATA_VOLATILE #if LWIP_HTTPD_SSI /* Copy for SSI files, no copy for non-SSI files */ #define HTTP_IS_DATA_VOLATILE(hs) ((hs)->ssi ? TCP_WRITE_FLAG_COPY : 0) #else /* LWIP_HTTPD_SSI */ /** Default: don't copy if the data is sent from file-system directly */ #define HTTP_IS_DATA_VOLATILE(hs) (((hs->file != NULL) && (hs->handle != NULL) && (hs->file == \ (char*)hs->handle->data + hs->handle->len - hs->left)) \ ? 0 : TCP_WRITE_FLAG_COPY) #endif /* LWIP_HTTPD_SSI */ #endif /** Default: headers are sent from ROM */ #ifndef HTTP_IS_HDR_VOLATILE #define HTTP_IS_HDR_VOLATILE(hs, ptr) 0 #endif #if LWIP_HTTPD_SSI /** Default: Tags are sent from struct http_state and are therefore volatile */ #ifndef HTTP_IS_TAG_VOLATILE #define HTTP_IS_TAG_VOLATILE(ptr) TCP_WRITE_FLAG_COPY #endif #endif /* LWIP_HTTPD_SSI */ /* By default, the httpd is limited to send 2*pcb->mss to keep resource usage low when http is not an important protocol in the device. */ #ifndef HTTPD_LIMIT_SENDING_TO_2MSS #define HTTPD_LIMIT_SENDING_TO_2MSS 1 #endif /* Define this to a function that returns the maximum amount of data to enqueue. The function have this signature: u16_t fn(struct tcp_pcb* pcb); */ #ifndef HTTPD_MAX_WRITE_LEN #if HTTPD_LIMIT_SENDING_TO_2MSS #define HTTPD_MAX_WRITE_LEN(pcb) (2 * tcp_mss(pcb)) #endif #endif /* Return values for http_send_*() */ #define HTTP_DATA_TO_SEND_BREAK 2 #define HTTP_DATA_TO_SEND_CONTINUE 1 #define HTTP_NO_DATA_TO_SEND 0 #if HTTPD_USE_MEM_POOL #define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)memp_malloc(MEMP_HTTPD_SSI_STATE) #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)memp_malloc(MEMP_HTTPD_STATE) #else /* HTTPD_USE_MEM_POOL */ #define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state)) #define HTTP_ALLOC_HTTP_STATE() (struct http_state *)mem_malloc(sizeof(struct http_state)) #endif /* HTTPD_USE_MEM_POOL */ typedef struct { const char *name; u8_t shtml; } default_filename; const default_filename g_psDefaultFilenames[] = { {"/index.shtml", 1 }, {"/index.ssi", 1 }, {"/index.shtm", 1 }, {"/index.html", 0 }, {"/index.htm", 0 } }; #define NUM_DEFAULT_FILENAMES (sizeof(g_psDefaultFilenames) / \ sizeof(default_filename)) #if LWIP_HTTPD_SUPPORT_REQUESTLIST /** HTTP request is copied here from pbufs for simple parsing */ static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH+1]; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_SUPPORT_POST /** Filename for response file to send when POST is finished */ static char http_post_response_filename[LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN+1]; #endif /* LWIP_HTTPD_SUPPORT_POST */ #if LWIP_HTTPD_DYNAMIC_HEADERS /* The number of individual strings that comprise the headers sent before each * requested file. */ #define NUM_FILE_HDR_STRINGS 3 #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 enum request_method { METHOD_UNK, /* Unknown method */ METHOD_GET, /* HTTP 1.0 spec 8.1 - GET */ METHOD_HEAD, /* HTTP 1.0 spec 8.2 - HEAD */ METHOD_POST, /* HTTP 1.0 spec 8.3 - POST */ METHOD_V09_GET = 9 /* HTTP 0.9 - GET */ }; #endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09*/ #if LWIP_HTTPD_SSI #define HTTPD_LAST_TAG_PART 0xFFFF enum tag_check_state { TAG_NONE, /* Not processing an SSI tag */ TAG_LEADIN, /* Tag lead in "" being processed */ TAG_SENDING /* Sending tag replacement string */ }; struct http_ssi_state { const char *parsed; /* Pointer to the first unparsed byte in buf. */ #if !LWIP_HTTPD_SSI_INCLUDE_TAG const char *tag_started;/* Pointer to the first opening '<' of the tag. */ #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ const char *tag_end; /* Pointer to char after the closing '>' of the tag. */ u32_t parse_left; /* Number of unparsed bytes in buf. */ u16_t tag_index; /* Counter used by tag parsing state machine */ u16_t tag_insert_len; /* Length of insert in string tag_insert */ #if LWIP_HTTPD_SSI_MULTIPART u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */ #endif /* LWIP_HTTPD_SSI_MULTIPART */ u8_t tag_name_len; /* Length of the tag name in string tag_name */ char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */ char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */ enum tag_check_state tag_state; /* State of the tag processor */ }; #endif /* LWIP_HTTPD_SSI */ struct http_state { #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED struct http_state *next; #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ struct fs_file file_handle; struct fs_file *handle; char *file; /* Pointer to first unsent byte in buf. */ struct tcp_pcb *pcb; #if LWIP_HTTPD_SUPPORT_REQUESTLIST struct pbuf *req; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_DYNAMIC_FILE_READ char *buf; /* File read buffer. */ int buf_len; /* Size of file read buffer, buf. */ #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ u32_t left; /* Number of unsent bytes in buf. */ u8_t retries; #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE u8_t keepalive; #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ #if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 int method; #endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 */ #if LWIP_HTTPD_SSI struct http_ssi_state *ssi; #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */ char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */ #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_DYNAMIC_HEADERS const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */ u16_t hdr_pos; /* The position of the first unsent header byte in the current string */ u16_t hdr_index; /* The index of the hdr string currently being sent. */ #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_TIMING u32_t time_started; #endif /* LWIP_HTTPD_TIMING */ #if LWIP_HTTPD_SUPPORT_POST u32_t post_content_len_left; #if LWIP_HTTPD_POST_MANUAL_WND u32_t unrecved_bytes; u8_t no_auto_wnd; u8_t post_finished; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ #endif /* LWIP_HTTPD_SUPPORT_POST*/ }; static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs); static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn); static err_t http_find_file(struct http_state *hs, const char *uri); static err_t http_init_file(struct http_state *hs, struct fs_file *file, const char *uri, u8_t tag_check); static err_t http_poll(void *arg, struct tcp_pcb *pcb); static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs); #if LWIP_HTTPD_FS_ASYNC_READ static void http_continue(void *connection); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #if LWIP_HTTPD_SSI /* SSI insert handler function pointer. */ tSSIHandler g_pfnSSIHandler = NULL; int g_iNumTags = 0; const char **g_ppcTags = NULL; #define LEN_TAG_LEAD_IN 5 const char * const g_pcTagLeadIn = ""; #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI /* CGI handler information */ const tCGI *g_pCGIs; int g_iNumCGIs; #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED /** global list of active HTTP connections, use to kill the oldest when running out of memory */ static struct http_state *http_connections; #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ #if LWIP_HTTPD_STRNSTR_PRIVATE /** Like strstr but does not need 'buffer' to be NULL-terminated */ static char* strnstr(const char* buffer, const char* token, size_t n) { const char* p; int tokenlen = (int)strlen(token); if (tokenlen == 0) { return (char *)buffer; } for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) { if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) { return (char *)p; } } return NULL; } #endif /* LWIP_HTTPD_STRNSTR_PRIVATE */ #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED static void http_kill_oldest_connection(u8_t ssi_required) { struct http_state *hs = http_connections; struct http_state *hs_free_next = NULL; while(hs && hs->next) { #if LWIP_HTTPD_SSI if (ssi_required) { if (hs->next->ssi != NULL) { hs_free_next = hs; } } else #else /* LWIP_HTTPD_SSI */ LWIP_UNUSED_ARG(ssi_required); #endif /* LWIP_HTTPD_SSI */ { hs_free_next = hs; } hs = hs->next; } if (hs_free_next != NULL) { LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL); LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL); /* send RST when killing a connection because of memory shortage */ http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */ } } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ #if LWIP_HTTPD_SSI /** Allocate as struct http_ssi_state. */ static struct http_ssi_state* http_ssi_state_alloc(void) { struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE(); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED if (ret == NULL) { http_kill_oldest_connection(1); ret = HTTP_ALLOC_SSI_STATE(); } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ if (ret != NULL) { memset(ret, 0, sizeof(struct http_ssi_state)); } return ret; } /** Free a struct http_ssi_state. */ static void http_ssi_state_free(struct http_ssi_state *ssi) { if (ssi != NULL) { #if HTTPD_USE_MEM_POOL memp_free(MEMP_HTTPD_SSI_STATE, ssi); #else /* HTTPD_USE_MEM_POOL */ mem_free(ssi); #endif /* HTTPD_USE_MEM_POOL */ } } #endif /* LWIP_HTTPD_SSI */ /** Initialize a struct http_state. */ static void http_state_init(struct http_state* hs) { /* Initialize the structure. */ memset(hs, 0, sizeof(struct http_state)); #if LWIP_HTTPD_DYNAMIC_HEADERS /* Indicate that the headers are not yet valid */ hs->hdr_index = NUM_FILE_HDR_STRINGS; #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ } /** Allocate a struct http_state. */ static struct http_state* http_state_alloc(void) { struct http_state *ret = HTTP_ALLOC_HTTP_STATE(); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED if (ret == NULL) { http_kill_oldest_connection(0); ret = HTTP_ALLOC_HTTP_STATE(); } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ if (ret != NULL) { http_state_init(ret); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED /* add the connection to the list */ if (http_connections == NULL) { http_connections = ret; } else { struct http_state *last; for(last = http_connections; last->next != NULL; last = last->next); LWIP_ASSERT("last != NULL", last != NULL); last->next = ret; } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ } return ret; } /** Free a struct http_state. * Also frees the file data if dynamic. */ static void http_state_eof(struct http_state *hs) { if(hs->handle) { #if LWIP_HTTPD_TIMING u32_t ms_needed = sys_now() - hs->time_started; u32_t needed = LWIP_MAX(1, (ms_needed/100)); LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n", ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed))); #endif /* LWIP_HTTPD_TIMING */ fs_close(hs->handle); hs->handle = NULL; } #if LWIP_HTTPD_DYNAMIC_FILE_READ if (hs->buf != NULL) { mem_free(hs->buf); hs->buf = NULL; } #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ #if LWIP_HTTPD_SSI if (hs->ssi) { http_ssi_state_free(hs->ssi); hs->ssi = NULL; } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_SUPPORT_REQUESTLIST if (hs->req) { pbuf_free(hs->req); hs->req = NULL; } #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ } /** Free a struct http_state. * Also frees the file data if dynamic. */ static void http_state_free(struct http_state *hs) { if (hs != NULL) { http_state_eof(hs); #if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED /* take the connection off the list */ if (http_connections) { if (http_connections == hs) { http_connections = hs->next; } else { struct http_state *last; for(last = http_connections; last->next != NULL; last = last->next) { if (last->next == hs) { last->next = hs->next; break; } } } } #endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ #if HTTPD_USE_MEM_POOL memp_free(MEMP_HTTPD_STATE, hs); #else /* HTTPD_USE_MEM_POOL */ mem_free(hs); #endif /* HTTPD_USE_MEM_POOL */ } } /** Call tcp_write() in a loop trying smaller and smaller length * * @param pcb tcp_pcb to send * @param ptr Data to send * @param length Length of data to send (in/out: on return, contains the * amount of data sent) * @param apiflags directly passed to tcp_write * @return the return value of tcp_write */ static err_t http_write(struct tcp_pcb *pcb, const void* ptr, u16_t *length, u8_t apiflags) { u16_t len, max_len; err_t err; LWIP_ASSERT("length != NULL", length != NULL); len = *length; if (len == 0) { return ERR_OK; } /* We cannot send more data than space available in the send buffer. */ max_len = tcp_sndbuf(pcb); if (max_len < len) { len = max_len; } #ifdef HTTPD_MAX_WRITE_LEN /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ max_len = HTTPD_MAX_WRITE_LEN(pcb); if(len > max_len) { len = max_len; } #endif /* HTTPD_MAX_WRITE_LEN */ do { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying go send %d bytes\n", len)); err = tcp_write(pcb, ptr, len, apiflags); if (err == ERR_MEM) { if ((tcp_sndbuf(pcb) == 0) || (tcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) { /* no need to try smaller sizes */ len = 1; } else { len /= 2; } LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed, trying less (%d bytes)\n", len)); } } while ((err == ERR_MEM) && (len > 1)); if (err == ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len)); *length = len; } else { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err))); *length = 0; } return err; } /** * The connection shall be actively closed (using RST to close from fault states). * Reset the sent- and recv-callbacks. * * @param pcb the tcp pcb to reset callbacks * @param hs connection state to free */ static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn) { err_t err; LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void*)pcb)); #if LWIP_HTTPD_SUPPORT_POST if (hs != NULL) { if ((hs->post_content_len_left != 0) #if LWIP_HTTPD_POST_MANUAL_WND || ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0)) #endif /* LWIP_HTTPD_POST_MANUAL_WND */ ) { /* make sure the post code knows that the connection is closed */ http_post_response_filename[0] = 0; httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); } } #endif /* LWIP_HTTPD_SUPPORT_POST*/ tcp_arg(pcb, NULL); tcp_recv(pcb, NULL); tcp_err(pcb, NULL); tcp_poll(pcb, NULL, 0); tcp_sent(pcb, NULL); if (hs != NULL) { http_state_free(hs); } if (abort_conn) { tcp_abort(pcb); return ERR_OK; } err = tcp_close(pcb); if (err != ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void*)pcb)); /* error closing, try again later in poll */ tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); } return err; } /** * The connection shall be actively closed. * Reset the sent- and recv-callbacks. * * @param pcb the tcp pcb to reset callbacks * @param hs connection state to free */ static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs) { return http_close_or_abort_conn(pcb, hs, 0); } /** End of file: either close the connection (Connection: close) or * close the file (Connection: keep-alive) */ static void http_eof(struct tcp_pcb *pcb, struct http_state *hs) { /* HTTP/1.1 persistent connection? (Not supported for SSI) */ #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if (hs->keepalive && !LWIP_HTTPD_IS_SSI(hs)) { http_state_eof(hs); http_state_init(hs); hs->keepalive = 1; } else #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ { http_close_conn(pcb, hs); } } #if LWIP_HTTPD_CGI /** * Extract URI parameters from the parameter-part of an URI in the form * "test.cgi?x=y" @todo: better explanation! * Pointers to the parameters are stored in hs->param_vals. * * @param hs http connection state * @param params pointer to the NULL-terminated parameter string from the URI * @return number of parameters extracted */ static int extract_uri_parameters(struct http_state *hs, char *params) { char *pair; char *equals; int loop; /* If we have no parameters at all, return immediately. */ if(!params || (params[0] == '\0')) { return(0); } /* Get a pointer to our first parameter */ pair = params; /* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the * remainder (if any) */ for(loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) { /* Save the name of the parameter */ hs->params[loop] = pair; /* Remember the start of this name=value pair */ equals = pair; /* Find the start of the next name=value pair and replace the delimiter * with a 0 to terminate the previous pair string. */ pair = strchr(pair, '&'); if(pair) { *pair = '\0'; pair++; } else { /* We didn't find a new parameter so find the end of the URI and * replace the space with a '\0' */ pair = strchr(equals, ' '); if(pair) { *pair = '\0'; } /* Revert to NULL so that we exit the loop as expected. */ pair = NULL; } /* Now find the '=' in the previous pair, replace it with '\0' and save * the parameter value string. */ equals = strchr(equals, '='); if(equals) { *equals = '\0'; hs->param_vals[loop] = equals + 1; } else { hs->param_vals[loop] = NULL; } } return loop; } #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_SSI /** * Insert a tag (found in an shtml in the form of "" into the file. * The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement * should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN). * The amount of data written is stored to ssi->tag_insert_len. * * @todo: return tag_insert_len - maybe it can be removed from struct http_state? * * @param hs http connection state */ static void get_tag_insert(struct http_state *hs) { int loop; size_t len; struct http_ssi_state *ssi; LWIP_ASSERT("hs != NULL", hs != NULL); ssi = hs->ssi; LWIP_ASSERT("ssi != NULL", ssi != NULL); #if LWIP_HTTPD_SSI_MULTIPART u16_t current_tag_part = ssi->tag_part; ssi->tag_part = HTTPD_LAST_TAG_PART; #endif /* LWIP_HTTPD_SSI_MULTIPART */ if(g_pfnSSIHandler && g_ppcTags && g_iNumTags) { /* Find this tag in the list we have been provided. */ for(loop = 0; loop < g_iNumTags; loop++) { if(strcmp(ssi->tag_name, g_ppcTags[loop]) == 0) { ssi->tag_insert_len = g_pfnSSIHandler(loop, ssi->tag_insert, LWIP_HTTPD_MAX_TAG_INSERT_LEN #if LWIP_HTTPD_SSI_MULTIPART , current_tag_part, &ssi->tag_part #endif /* LWIP_HTTPD_SSI_MULTIPART */ #if LWIP_HTTPD_FILE_STATE , hs->handle->state #endif /* LWIP_HTTPD_FILE_STATE */ ); return; } } } /* If we drop out, we were asked to serve a page which contains tags that * we don't have a handler for. Merely echo back the tags with an error * marker. */ #define UNKNOWN_TAG1_TEXT "***UNKNOWN TAG " #define UNKNOWN_TAG1_LEN 18 #define UNKNOWN_TAG2_TEXT "***" #define UNKNOWN_TAG2_LEN 7 len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name), LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN))); MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN); MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len); MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN); ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0; len = strlen(ssi->tag_insert); LWIP_ASSERT("len <= 0xffff", len <= 0xffff); ssi->tag_insert_len = (u16_t)len; } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_DYNAMIC_HEADERS /** * Generate the relevant HTTP headers for the given filename and write * them into the supplied buffer. */ static void get_http_headers(struct http_state *pState, char *pszURI) { unsigned int iLoop; char *pszWork; char *pszExt; char *pszVars; /* Ensure that we initialize the loop counter. */ iLoop = 0; /* In all cases, the second header we send is the server identification so set it here. */ pState->hdrs[1] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER]; /* Is this a normal file or the special case we use to send back the default "404: Page not found" response? */ if (pszURI == NULL) { pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; pState->hdrs[2] = g_psHTTPHeaderStrings[DEFAULT_404_HTML]; /* Set up to send the first header string. */ pState->hdr_index = 0; pState->hdr_pos = 0; return; } else { /* We are dealing with a particular filename. Look for one other special case. We assume that any filename with "404" in it must be indicative of a 404 server error whereas all other files require the 200 OK header. */ if (strstr(pszURI, "404")) { pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; } else if (strstr(pszURI, "400")) { pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST]; } else if (strstr(pszURI, "501")) { pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL]; } else { pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_OK]; } /* Determine if the URI has any variables and, if so, temporarily remove them. */ pszVars = strchr(pszURI, '?'); if(pszVars) { *pszVars = '\0'; } /* Get a pointer to the file extension. We find this by looking for the last occurrence of "." in the filename passed. */ pszExt = NULL; pszWork = strchr(pszURI, '.'); while(pszWork) { pszExt = pszWork + 1; pszWork = strchr(pszExt, '.'); } /* Now determine the content type and add the relevant header for that. */ for(iLoop = 0; (iLoop < NUM_HTTP_HEADERS) && pszExt; iLoop++) { /* Have we found a matching extension? */ if(!strcmp(g_psHTTPHeaders[iLoop].extension, pszExt)) { pState->hdrs[2] = g_psHTTPHeaders[iLoop].content_type; break; } } /* Reinstate the parameter marker if there was one in the original URI. */ if(pszVars) { *pszVars = '?'; } } /* Does the URL passed have any file extension? If not, we assume it is a special-case URL used for control state notification and we do not send any HTTP headers with the response. */ if(!pszExt) { /* Force the header index to a value indicating that all headers have already been sent. */ pState->hdr_index = NUM_FILE_HDR_STRINGS; } else { /* Did we find a matching extension? */ if(iLoop == NUM_HTTP_HEADERS) { /* No - use the default, plain text file type. */ pState->hdrs[2] = HTTP_HDR_DEFAULT_TYPE; } /* Set up to send the first header string. */ pState->hdr_index = 0; pState->hdr_pos = 0; } } /** Sub-function of http_send(): send dynamic headers * * @returns: - HTTP_NO_DATA_TO_SEND: no new data has been enqueued * - HTTP_DATA_TO_SEND_CONTINUE: continue with sending HTTP body * - HTTP_DATA_TO_SEND_BREAK: data has been enqueued, headers pending, * so don't send HTTP body yet */ static u8_t http_send_headers(struct tcp_pcb *pcb, struct http_state *hs) { err_t err; u16_t len; u8_t data_to_send = HTTP_NO_DATA_TO_SEND; u16_t hdrlen, sendlen; /* How much data can we send? */ len = tcp_sndbuf(pcb); sendlen = len; while(len && (hs->hdr_index < NUM_FILE_HDR_STRINGS) && sendlen) { const void *ptr; u16_t old_sendlen; u8_t apiflags; /* How much do we have to send from the current header? */ hdrlen = (u16_t)strlen(hs->hdrs[hs->hdr_index]); /* How much of this can we send? */ sendlen = (len < (hdrlen - hs->hdr_pos)) ? len : (hdrlen - hs->hdr_pos); /* Send this amount of data or as much as we can given memory * constraints. */ ptr = (const void *)(hs->hdrs[hs->hdr_index] + hs->hdr_pos); old_sendlen = sendlen; apiflags = HTTP_IS_HDR_VOLATILE(hs, ptr); if (hs->hdr_index < NUM_FILE_HDR_STRINGS - 1) { apiflags |= TCP_WRITE_FLAG_MORE; } err = http_write(pcb, ptr, &sendlen, apiflags); if ((err == ERR_OK) && (old_sendlen != sendlen)) { /* Remember that we added some more data to be transmitted. */ data_to_send = HTTP_DATA_TO_SEND_CONTINUE; } else if (err != ERR_OK) { /* special case: http_write does not try to send 1 byte */ sendlen = 0; } /* Fix up the header position for the next time round. */ hs->hdr_pos += sendlen; len -= sendlen; /* Have we finished sending this string? */ if(hs->hdr_pos == hdrlen) { /* Yes - move on to the next one */ hs->hdr_index++; hs->hdr_pos = 0; } } if ((hs->hdr_index >= NUM_FILE_HDR_STRINGS) && (hs->file == NULL)) { /* When we are at the end of the headers, check for data to send * instead of waiting for ACK from remote side to continue * (which would happen when sending files from async read). */ http_check_eof(pcb, hs); } /* If we get here and there are still header bytes to send, we send * the header information we just wrote immediately. If there are no * more headers to send, but we do have file data to send, drop through * to try to send some file data too. */ if((hs->hdr_index < NUM_FILE_HDR_STRINGS) || !hs->file) { LWIP_DEBUGF(HTTPD_DEBUG, ("tcp_output\n")); return HTTP_DATA_TO_SEND_BREAK; } return data_to_send; } #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ /** Sub-function of http_send(): end-of-file (or block) is reached, * either close the file or read the next block (if supported). * * @returns: 0 if the file is finished or no data has been read * 1 if the file is not finished and data has been read */ static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs) { int bytes_left; #if LWIP_HTTPD_DYNAMIC_FILE_READ int count; #ifdef HTTPD_MAX_WRITE_LEN int max_write_len; #endif /* HTTPD_MAX_WRITE_LEN */ #endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ /* Do we have a valid file handle? */ if (hs->handle == NULL) { /* No - close the connection. */ http_eof(pcb, hs); return 0; } bytes_left = fs_bytes_left(hs->handle); if (bytes_left <= 0) { /* We reached the end of the file so this request is done. */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } #if LWIP_HTTPD_DYNAMIC_FILE_READ /* Do we already have a send buffer allocated? */ if(hs->buf) { /* Yes - get the length of the buffer */ count = hs->buf_len; } else { /* We don't have a send buffer so allocate one now */ count = tcp_sndbuf(pcb); if(bytes_left < count) { count = bytes_left; } #ifdef HTTPD_MAX_WRITE_LEN /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ max_write_len = HTTPD_MAX_WRITE_LEN(pcb); if (count > max_write_len) { count = max_write_len; } #endif /* HTTPD_MAX_WRITE_LEN */ do { hs->buf = (char*)mem_malloc((mem_size_t)count); if (hs->buf != NULL) { hs->buf_len = count; break; } count = count / 2; } while (count > 100); /* Did we get a send buffer? If not, return immediately. */ if (hs->buf == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("No buff\n")); return 0; } } /* Read a block of data from the file. */ LWIP_DEBUGF(HTTPD_DEBUG, ("Trying to read %d bytes.\n", count)); #if LWIP_HTTPD_FS_ASYNC_READ count = fs_read_async(hs->handle, hs->buf, count, http_continue, hs); #else /* LWIP_HTTPD_FS_ASYNC_READ */ count = fs_read(hs->handle, hs->buf, count); #endif /* LWIP_HTTPD_FS_ASYNC_READ */ if (count < 0) { if (count == FS_READ_DELAYED) { /* Delayed read, wait for FS to unblock us */ return 0; } /* We reached the end of the file so this request is done. * @todo: don't close here for HTTP/1.1? */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } /* Set up to send the block of data we just read */ LWIP_DEBUGF(HTTPD_DEBUG, ("Read %d bytes.\n", count)); hs->left = count; hs->file = hs->buf; #if LWIP_HTTPD_SSI if (hs->ssi) { hs->ssi->parse_left = count; hs->ssi->parsed = hs->buf; } #endif /* LWIP_HTTPD_SSI */ #else /* LWIP_HTTPD_DYNAMIC_FILE_READ */ LWIP_ASSERT("SSI and DYNAMIC_HEADERS turned off but eof not reached", 0); #endif /* LWIP_HTTPD_SSI || LWIP_HTTPD_DYNAMIC_HEADERS */ return 1; } /** Sub-function of http_send(): This is the normal send-routine for non-ssi files * * @returns: - 1: data has been written (so call tcp_ouput) * - 0: no data has been written (no need to call tcp_output) */ static u8_t http_send_data_nonssi(struct tcp_pcb *pcb, struct http_state *hs) { err_t err; u16_t len; u8_t data_to_send = 0; /* We are not processing an SHTML file so no tag checking is necessary. * Just send the data as we received it from the file. */ len = (u16_t)LWIP_MIN(hs->left, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } return data_to_send; } #if LWIP_HTTPD_SSI /** Sub-function of http_send(): This is the send-routine for ssi files * * @returns: - 1: data has been written (so call tcp_ouput) * - 0: no data has been written (no need to call tcp_output) */ static u8_t http_send_data_ssi(struct tcp_pcb *pcb, struct http_state *hs) { err_t err = ERR_OK; u16_t len; u8_t data_to_send = 0; struct http_ssi_state *ssi = hs->ssi; LWIP_ASSERT("ssi != NULL", ssi != NULL); /* We are processing an SHTML file so need to scan for tags and replace * them with insert strings. We need to be careful here since a tag may * straddle the boundary of two blocks read from the file and we may also * have to split the insert string between two tcp_write operations. */ /* How much data could we send? */ len = tcp_sndbuf(pcb); /* Do we have remaining data to send before parsing more? */ if(ssi->parsed > hs->file) { len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } /* If the send buffer is full, return now. */ if(tcp_sndbuf(pcb) == 0) { return data_to_send; } } LWIP_DEBUGF(HTTPD_DEBUG, ("State %d, %d left\n", ssi->tag_state, (int)ssi->parse_left)); /* We have sent all the data that was already parsed so continue parsing * the buffer contents looking for SSI tags. */ while((ssi->parse_left) && (err == ERR_OK)) { if (len == 0) { return data_to_send; } switch(ssi->tag_state) { case TAG_NONE: /* We are not currently processing an SSI tag so scan for the * start of the lead-in marker. */ if(*ssi->parsed == g_pcTagLeadIn[0]) { /* We found what could be the lead-in for a new tag so change * state appropriately. */ ssi->tag_state = TAG_LEADIN; ssi->tag_index = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->tag_started = ssi->parsed; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; case TAG_LEADIN: /* We are processing the lead-in marker, looking for the start of * the tag name. */ /* Have we reached the end of the leadin? */ if(ssi->tag_index == LEN_TAG_LEAD_IN) { ssi->tag_index = 0; ssi->tag_state = TAG_FOUND; } else { /* Have we found the next character we expect for the tag leadin? */ if(*ssi->parsed == g_pcTagLeadIn[ssi->tag_index]) { /* Yes - move to the next one unless we have found the complete * leadin, in which case we start looking for the tag itself */ ssi->tag_index++; } else { /* We found an unexpected character so this is not a tag. Move * back to idle state. */ ssi->tag_state = TAG_NONE; } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; } break; case TAG_FOUND: /* We are reading the tag name, looking for the start of the * lead-out marker and removing any whitespace found. */ /* Remove leading whitespace between the tag leading and the first * tag name character. */ if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r'))) { /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; } /* Have we found the end of the tag name? This is signalled by * us finding the first leadout character or whitespace */ if((*ssi->parsed == g_pcTagLeadOut[0]) || (*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r')) { if(ssi->tag_index == 0) { /* We read a zero length tag so ignore it. */ ssi->tag_state = TAG_NONE; } else { /* We read a non-empty tag so go ahead and look for the * leadout string. */ ssi->tag_state = TAG_LEADOUT; LWIP_ASSERT("ssi->tag_index <= 0xff", ssi->tag_index <= 0xff); ssi->tag_name_len = (u8_t)ssi->tag_index; ssi->tag_name[ssi->tag_index] = '\0'; if(*ssi->parsed == g_pcTagLeadOut[0]) { ssi->tag_index = 1; } else { ssi->tag_index = 0; } } } else { /* This character is part of the tag name so save it */ if(ssi->tag_index < LWIP_HTTPD_MAX_TAG_NAME_LEN) { ssi->tag_name[ssi->tag_index++] = *ssi->parsed; } else { /* The tag was too long so ignore it. */ ssi->tag_state = TAG_NONE; } } /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; /* We are looking for the end of the lead-out marker. */ case TAG_LEADOUT: /* Remove leading whitespace between the tag leading and the first * tag leadout character. */ if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || (*ssi->parsed == '\r'))) { /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; break; } /* Have we found the next character we expect for the tag leadout? */ if(*ssi->parsed == g_pcTagLeadOut[ssi->tag_index]) { /* Yes - move to the next one unless we have found the complete * leadout, in which case we need to call the client to process * the tag. */ /* Move on to the next character in the buffer */ ssi->parse_left--; ssi->parsed++; if(ssi->tag_index == (LEN_TAG_LEAD_OUT - 1)) { /* Call the client to ask for the insert string for the * tag we just found. */ #if LWIP_HTTPD_SSI_MULTIPART ssi->tag_part = 0; /* start with tag part 0 */ #endif /* LWIP_HTTPD_SSI_MULTIPART */ get_tag_insert(hs); /* Next time through, we are going to be sending data * immediately, either the end of the block we start * sending here or the insert string. */ ssi->tag_index = 0; ssi->tag_state = TAG_SENDING; ssi->tag_end = ssi->parsed; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->parsed = ssi->tag_started; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ /* If there is any unsent data in the buffer prior to the * tag, we need to send it now. */ if (ssi->tag_end > hs->file) { /* How much of the data can we send? */ #if LWIP_HTTPD_SSI_INCLUDE_TAG len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ /* we would include the tag in sending */ len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG if(ssi->tag_started <= hs->file) { /* pretend to have sent the tag, too */ len += ssi->tag_end - ssi->tag_started; } #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ hs->file += len; hs->left -= len; } } } else { ssi->tag_index++; } } else { /* We found an unexpected character so this is not a tag. Move * back to idle state. */ ssi->parse_left--; ssi->parsed++; ssi->tag_state = TAG_NONE; } break; /* * We have found a valid tag and are in the process of sending * data as a result of that discovery. We send either remaining data * from the file prior to the insert point or the insert string itself. */ case TAG_SENDING: /* Do we have any remaining file data to send from the buffer prior * to the tag? */ if(ssi->tag_end > hs->file) { /* How much of the data can we send? */ #if LWIP_HTTPD_SSI_INCLUDE_TAG len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); #else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ LWIP_ASSERT("hs->started >= hs->file", ssi->tag_started >= hs->file); /* we would include the tag in sending */ len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); #endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ if (len != 0) { err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); } else { err = ERR_OK; } if (err == ERR_OK) { data_to_send = 1; #if !LWIP_HTTPD_SSI_INCLUDE_TAG if(ssi->tag_started <= hs->file) { /* pretend to have sent the tag, too */ len += ssi->tag_end - ssi->tag_started; } #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ hs->file += len; hs->left -= len; } } else { #if LWIP_HTTPD_SSI_MULTIPART if(ssi->tag_index >= ssi->tag_insert_len) { /* Did the last SSIHandler have more to send? */ if (ssi->tag_part != HTTPD_LAST_TAG_PART) { /* If so, call it again */ ssi->tag_index = 0; get_tag_insert(hs); } } #endif /* LWIP_HTTPD_SSI_MULTIPART */ /* Do we still have insert data left to send? */ if(ssi->tag_index < ssi->tag_insert_len) { /* We are sending the insert string itself. How much of the * insert can we send? */ len = (ssi->tag_insert_len - ssi->tag_index); /* Note that we set the copy flag here since we only have a * single tag insert buffer per connection. If we don't do * this, insert corruption can occur if more than one insert * is processed before we call tcp_output. */ err = http_write(pcb, &(ssi->tag_insert[ssi->tag_index]), &len, HTTP_IS_TAG_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; ssi->tag_index += len; /* Don't return here: keep on sending data */ } } else { #if LWIP_HTTPD_SSI_MULTIPART if (ssi->tag_part == HTTPD_LAST_TAG_PART) #endif /* LWIP_HTTPD_SSI_MULTIPART */ { /* We have sent all the insert data so go back to looking for * a new tag. */ LWIP_DEBUGF(HTTPD_DEBUG, ("Everything sent.\n")); ssi->tag_index = 0; ssi->tag_state = TAG_NONE; #if !LWIP_HTTPD_SSI_INCLUDE_TAG ssi->parsed = ssi->tag_end; #endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ } } break; } } } /* If we drop out of the end of the for loop, this implies we must have * file data to send so send it now. In TAG_SENDING state, we've already * handled this so skip the send if that's the case. */ if((ssi->tag_state != TAG_SENDING) && (ssi->parsed > hs->file)) { len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); if (err == ERR_OK) { data_to_send = 1; hs->file += len; hs->left -= len; } } return data_to_send; } #endif /* LWIP_HTTPD_SSI */ /** * Try to send more data on this pcb. * * @param pcb the pcb to send data * @param hs connection state */ static u8_t http_send(struct tcp_pcb *pcb, struct http_state *hs) { u8_t data_to_send = HTTP_NO_DATA_TO_SEND; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_send: pcb=%p hs=%p left=%d\n", (void*)pcb, (void*)hs, hs != NULL ? (int)hs->left : 0)); #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND if (hs->unrecved_bytes != 0) { return 0; } #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ /* If we were passed a NULL state structure pointer, ignore the call. */ if (hs == NULL) { return 0; } #if LWIP_HTTPD_FS_ASYNC_READ /* Check if we are allowed to read from this file. (e.g. SSI might want to delay sending until data is available) */ if (!fs_is_file_ready(hs->handle, http_continue, hs)) { return 0; } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ #if LWIP_HTTPD_DYNAMIC_HEADERS /* Do we have any more header data to send for this file? */ if(hs->hdr_index < NUM_FILE_HDR_STRINGS) { data_to_send = http_send_headers(pcb, hs); if (data_to_send != HTTP_DATA_TO_SEND_CONTINUE) { return data_to_send; } } #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ /* Have we run out of file data to send? If so, we need to read the next * block from the file. */ if (hs->left == 0) { if (!http_check_eof(pcb, hs)) { return 0; } } #if LWIP_HTTPD_SSI if(hs->ssi) { data_to_send = http_send_data_ssi(pcb, hs); } else #endif /* LWIP_HTTPD_SSI */ { data_to_send = http_send_data_nonssi(pcb, hs); } if((hs->left == 0) && (fs_bytes_left(hs->handle) <= 0)) { /* We reached the end of the file so this request is done. * This adds the FIN flag right into the last data segment. */ LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); http_eof(pcb, hs); return 0; } LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("send_data end.\n")); return data_to_send; } #if LWIP_HTTPD_SUPPORT_EXTSTATUS /** Initialize a http connection with a file to send for an error message * * @param hs http connection state * @param error_nr HTTP error number * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_find_error_file(struct http_state *hs, u16_t error_nr) { const char *uri1, *uri2, *uri3; err_t err; if (error_nr == 501) { uri1 = "/501.html"; uri2 = "/501.htm"; uri3 = "/501.shtml"; } else { /* 400 (bad request is the default) */ uri1 = "/400.html"; uri2 = "/400.htm"; uri3 = "/400.shtml"; } err = fs_open(&hs->file_handle, uri1); if (err != ERR_OK) { err = fs_open(&hs->file_handle, uri2); if (err != ERR_OK) { err = fs_open(&hs->file_handle, uri3); if (err != ERR_OK) { LWIP_DEBUGF(HTTPD_DEBUG, ("Error page for error %"U16_F" not found\n", error_nr)); return ERR_ARG; } } } return http_init_file(hs, &hs->file_handle, NULL, 0); } #else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ #define http_find_error_file(hs, error_nr) ERR_ARG #endif /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ /** * Get the file struct for a 404 error page. * Tries some file names and returns NULL if none found. * * @param uri pointer that receives the actual file name URI * @return file struct for the error page or NULL no matching file was found */ static struct fs_file * http_get_404_file(struct http_state *hs, const char **uri) { err_t err; *uri = "/404.html"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.html doesn't exist. Try 404.htm instead. */ *uri = "/404.htm"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.htm doesn't exist either. Try 404.shtml instead. */ *uri = "/404.shtml"; err = fs_open(&hs->file_handle, *uri); if (err != ERR_OK) { /* 404.htm doesn't exist either. Indicate to the caller that it should * send back a default 404 page. */ *uri = NULL; return NULL; } } } return &hs->file_handle; } #if LWIP_HTTPD_SUPPORT_POST static err_t http_handle_post_finished(struct http_state *hs) { #if LWIP_HTTPD_POST_MANUAL_WND /* Prevent multiple calls to httpd_post_finished, since it might have already been called before from httpd_post_data_recved(). */ if (hs->post_finished) { return ERR_OK; } hs->post_finished = 1; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ /* application error or POST finished */ /* NULL-terminate the buffer */ http_post_response_filename[0] = 0; httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); return http_find_file(hs, http_post_response_filename); } /** Pass received POST body data to the application and correctly handle * returning a response document or closing the connection. * ATTENTION: The application is responsible for the pbuf now, so don't free it! * * @param hs http connection state * @param p pbuf to pass to the application * @return ERR_OK if passed successfully, another err_t if the response file * hasn't been found (after POST finished) */ static err_t http_post_rxpbuf(struct http_state *hs, struct pbuf *p) { err_t err; /* adjust remaining Content-Length */ if (hs->post_content_len_left < p->tot_len) { hs->post_content_len_left = 0; } else { hs->post_content_len_left -= p->tot_len; } err = httpd_post_receive_data(hs, p); if (err != ERR_OK) { /* Ignore remaining content in case of application error */ hs->post_content_len_left = 0; } if (hs->post_content_len_left == 0) { #if LWIP_HTTPD_POST_MANUAL_WND if (hs->unrecved_bytes != 0) { return ERR_OK; } #endif /* LWIP_HTTPD_POST_MANUAL_WND */ /* application error or POST finished */ return http_handle_post_finished(hs); } return ERR_OK; } /** Handle a post request. Called from http_parse_request when method 'POST' * is found. * * @param p The input pbuf (containing the POST header and body). * @param hs The http connection state. * @param data HTTP request (header and part of body) from input pbuf(s). * @param data_len Size of 'data'. * @param uri The HTTP URI parsed from input pbuf(s). * @param uri_end Pointer to the end of 'uri' (here, the rest of the HTTP * header starts). * @return ERR_OK: POST correctly parsed and accepted by the application. * ERR_INPROGRESS: POST not completely parsed (no error yet) * another err_t: Error parsing POST or denied by the application */ static err_t http_post_request(struct pbuf *inp, struct http_state *hs, char *data, u16_t data_len, char *uri, char *uri_end) { err_t err; /* search for end-of-header (first double-CRLF) */ char* crlfcrlf = strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data)); if (crlfcrlf != NULL) { /* search for "Content-Length: " */ #define HTTP_HDR_CONTENT_LEN "Content-Length: " #define HTTP_HDR_CONTENT_LEN_LEN 16 #define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN 10 char *scontent_len = strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1)); if (scontent_len != NULL) { char *scontent_len_end = strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN); if (scontent_len_end != NULL) { int content_len; char *conten_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN; content_len = atoi(conten_len_num); if (content_len > 0) { /* adjust length of HTTP header passed to application */ const char *hdr_start_after_uri = uri_end + 1; u16_t hdr_len = LWIP_MIN(data_len, crlfcrlf + 4 - data); u16_t hdr_data_len = LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri); u8_t post_auto_wnd = 1; http_post_response_filename[0] = 0; err = httpd_post_begin(hs, uri, hdr_start_after_uri, hdr_data_len, content_len, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN, &post_auto_wnd); if (err == ERR_OK) { /* try to pass in data of the first pbuf(s) */ struct pbuf *q = inp; u16_t start_offset = hdr_len; #if LWIP_HTTPD_POST_MANUAL_WND hs->no_auto_wnd = !post_auto_wnd; #endif /* LWIP_HTTPD_POST_MANUAL_WND */ /* set the Content-Length to be received for this POST */ hs->post_content_len_left = (u32_t)content_len; /* get to the pbuf where the body starts */ while((q != NULL) && (q->len <= start_offset)) { start_offset -= q->len; q = q->next; } if (q != NULL) { /* hide the remaining HTTP header */ pbuf_header(q, -(s16_t)start_offset); #if LWIP_HTTPD_POST_MANUAL_WND if (!post_auto_wnd) { /* already tcp_recved() this data... */ hs->unrecved_bytes = q->tot_len; } #endif /* LWIP_HTTPD_POST_MANUAL_WND */ pbuf_ref(q); return http_post_rxpbuf(hs, q); } else { return ERR_OK; } } else { /* return file passed from application */ return http_find_file(hs, http_post_response_filename); } } else { LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n", conten_len_num)); return ERR_ARG; } } } /* If we come here, headers are fully received (double-crlf), but Content-Length was not included. Since this is currently the only supported method, we have to fail in this case! */ LWIP_DEBUGF(HTTPD_DEBUG, ("Error when parsing Content-Length\n")); return ERR_ARG; } /* if we come here, the POST is incomplete */ #if LWIP_HTTPD_SUPPORT_REQUESTLIST return ERR_INPROGRESS; #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ return ERR_ARG; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ } #if LWIP_HTTPD_POST_MANUAL_WND /** A POST implementation can call this function to update the TCP window. * This can be used to throttle data reception (e.g. when received data is * programmed to flash and data is received faster than programmed). * * @param connection A connection handle passed to httpd_post_begin for which * httpd_post_finished has *NOT* been called yet! * @param recved_len Length of data received (for window update) */ void httpd_post_data_recved(void *connection, u16_t recved_len) { struct http_state *hs = (struct http_state*)connection; if (hs != NULL) { if (hs->no_auto_wnd) { u16_t len = recved_len; if (hs->unrecved_bytes >= recved_len) { hs->unrecved_bytes -= recved_len; } else { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("httpd_post_data_recved: recved_len too big\n")); len = (u16_t)hs->unrecved_bytes; hs->unrecved_bytes = 0; } if (hs->pcb != NULL) { if (len != 0) { tcp_recved(hs->pcb, len); } if ((hs->post_content_len_left == 0) && (hs->unrecved_bytes == 0)) { /* finished handling POST */ http_handle_post_finished(hs); http_send(hs->pcb, hs); } } } } } #endif /* LWIP_HTTPD_POST_MANUAL_WND */ #endif /* LWIP_HTTPD_SUPPORT_POST */ #if LWIP_HTTPD_FS_ASYNC_READ /** Try to send more data if file has been blocked before * This is a callback function passed to fs_read_async(). */ static void http_continue(void *connection) { struct http_state *hs = (struct http_state*)connection; if (hs && (hs->pcb) && (hs->handle)) { LWIP_ASSERT("hs->pcb != NULL", hs->pcb != NULL); LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("httpd_continue: try to send more data\n")); if (http_send(hs->pcb, hs)) { /* If we wrote anything to be sent, go ahead and send it now. */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); tcp_output(hs->pcb); } } } #endif /* LWIP_HTTPD_FS_ASYNC_READ */ /** * When data has been received in the correct state, try to parse it * as a HTTP request. * * @param p the received pbuf * @param hs the connection state * @param pcb the tcp_pcb which received this packet * @return ERR_OK if request was OK and hs has been initialized correctly * ERR_INPROGRESS if request was OK so far but not fully received * another err_t otherwise */ static err_t http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) { char *data; char *crlf; u16_t data_len; struct pbuf *p = inp; #if LWIP_HTTPD_SUPPORT_REQUESTLIST u16_t clen; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ #if LWIP_HTTPD_SUPPORT_POST err_t err; #endif /* LWIP_HTTPD_SUPPORT_POST */ LWIP_UNUSED_ARG(pcb); /* only used for post */ LWIP_ASSERT("p != NULL", p != NULL); LWIP_ASSERT("hs != NULL", hs != NULL); if ((hs->handle != NULL) || (hs->file != NULL)) { LWIP_DEBUGF(HTTPD_DEBUG, ("Received data while sending a file\n")); /* already sending a file */ /* @todo: abort? */ return ERR_USE; } #if LWIP_HTTPD_SUPPORT_REQUESTLIST LWIP_DEBUGF(HTTPD_DEBUG, ("Received %"U16_F" bytes\n", p->tot_len)); /* first check allowed characters in this pbuf? */ /* enqueue the pbuf */ if (hs->req == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("First pbuf\n")); hs->req = p; } else { LWIP_DEBUGF(HTTPD_DEBUG, ("pbuf enqueued\n")); pbuf_cat(hs->req, p); } /* increase pbuf ref counter as it is freed when we return but we want to keep it on the req list */ pbuf_ref(p); if (hs->req->next != NULL) { data_len = LWIP_MIN(hs->req->tot_len, LWIP_HTTPD_MAX_REQ_LENGTH); pbuf_copy_partial(hs->req, httpd_req_buf, data_len, 0); data = httpd_req_buf; } else #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ { data = (char *)p->payload; data_len = p->len; if (p->len != p->tot_len) { LWIP_DEBUGF(HTTPD_DEBUG, ("Warning: incomplete header due to chained pbufs\n")); } } /* received enough data for minimal request? */ if (data_len >= MIN_REQ_LEN) { /* wait for CRLF before parsing anything */ crlf = strnstr(data, CRLF, data_len); if (crlf != NULL) { char *sp1, *sp2; u16_t left_len, uri_len; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n")); /* parse method */ if (!strncmp(data, "GET ", 4)) { sp1 = data + 3; /* received GET request */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n")); #if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 hs->method = METHOD_GET; #endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 */ #if LWIP_HTTPD_SUPPORT_HEAD } else if (!strncmp(data, "HEAD ", 5)) { /* store request type */ hs->method = METHOD_HEAD; sp1 = data + 4; /* received HEAD request */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received HEAD request\n")); #endif /* LWIP_HTTPD_SUPPORT_HEAD */ #if LWIP_HTTPD_SUPPORT_POST } else if (!strncmp(data, "POST ", 5)) { /* store request type */ hs->method = METHOD_POST; sp1 = data + 4; /* received POST request */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n")); #endif /* LWIP_HTTPD_SUPPORT_POST */ } else { /* null-terminate the METHOD (pbuf is freed anyway when returning) */ data[4] = 0; /* unsupported method! */ LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n", data)); return http_find_error_file(hs, 501); } /* if we come here, method is OK, parse URI */ left_len = data_len - ((sp1 +1) - data); sp2 = strnstr(sp1 + 1, " ", left_len); #if LWIP_HTTPD_SUPPORT_V09 if (sp2 == NULL) { /* HTTP 0.9: respond with correct protocol version */ sp2 = strnstr(sp1 + 1, CRLF, left_len); #if LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD if (hs->method != METHOD_GET) { /* HTTP/0.9 only supports GET method */ goto badrequest; } #endif /* LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD */ hs->method = METHOD_V09_GET; } #endif /* LWIP_HTTPD_SUPPORT_V09 */ uri_len = sp2 - (sp1 + 1); if ((sp2 != 0) && (sp2 > sp1)) { /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */ if (strnstr(data, CRLF CRLF, data_len) != NULL) { char *uri = sp1 + 1; #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE if ((hs->method != METHOD_V09_GET && strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len)) { hs->keepalive = 1; } #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ /* null-terminate the METHOD (pbuf is freed anyway when returning) */ *sp1 = 0; uri[uri_len] = 0; LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n", data, uri)); #if LWIP_HTTPD_SUPPORT_POST if (method == METHOD_POST) { #if LWIP_HTTPD_SUPPORT_REQUESTLIST struct pbuf *q = hs->req; #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ struct pbuf *q = inp; #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ err = http_post_request(q, hs, data, data_len, uri, sp2); if (err != ERR_OK) { /* restore header for next try */ *sp1 = ' '; *sp2 = ' '; uri[uri_len] = ' '; } if (err == ERR_ARG) { goto badrequest; } return err; } else #endif /* LWIP_HTTPD_SUPPORT_POST */ { return http_find_file(hs, uri); } } } else { LWIP_DEBUGF(HTTPD_DEBUG, ("invalid URI\n")); } } } #if LWIP_HTTPD_SUPPORT_REQUESTLIST clen = pbuf_clen(hs->req); if ((hs->req->tot_len <= LWIP_HTTPD_REQ_BUFSIZE) && (clen <= LWIP_HTTPD_REQ_QUEUELEN)) { /* request not fully received (too short or CRLF is missing) */ return ERR_INPROGRESS; } else #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ { #if LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD badrequest: #endif /* LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD */ LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n")); /* could not parse request */ return http_find_error_file(hs, 400); } } /** Try to find the file specified by uri and, if found, initialize hs * accordingly. * * @param hs the connection state * @param uri the HTTP header URI * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_find_file(struct http_state *hs, const char *uri) { size_t loop; struct fs_file *file = NULL; char *params; err_t err; #if LWIP_HTTPD_CGI int i; int count; #endif /* LWIP_HTTPD_CGI */ #if !LWIP_HTTPD_SSI const #endif /* !LWIP_HTTPD_SSI */ /* By default, assume we will not be processing server-side-includes tags */ u8_t tag_check = 0; /* Have we been asked for the default root file? */ if((uri[0] == '/') && (uri[1] == 0)) { /* Try each of the configured default filenames until we find one that exists. */ for (loop = 0; loop < NUM_DEFAULT_FILENAMES; loop++) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Looking for %s...\n", g_psDefaultFilenames[loop].name)); err = fs_open(&hs->file_handle, (char *)g_psDefaultFilenames[loop].name); uri = (char *)g_psDefaultFilenames[loop].name; if(err == ERR_OK) { file = &hs->file_handle; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opened.\n")); #if LWIP_HTTPD_SSI tag_check = g_psDefaultFilenames[loop].shtml; #endif /* LWIP_HTTPD_SSI */ break; } } if (file == NULL) { /* None of the default filenames exist so send back a 404 page */ file = http_get_404_file(hs, &uri); #if LWIP_HTTPD_SSI tag_check = 0; #endif /* LWIP_HTTPD_SSI */ } } else { /* No - we've been asked for a specific file. */ /* First, isolate the base URI (without any parameters) */ params = (char *)strchr(uri, '?'); if (params != NULL) { /* URI contains parameters. NULL-terminate the base URI */ *params = '\0'; params++; } #if LWIP_HTTPD_CGI /* Does the base URI we have isolated correspond to a CGI handler? */ if (g_iNumCGIs && g_pCGIs) { for (i = 0; i < g_iNumCGIs; i++) { if (strcmp(uri, g_pCGIs[i].pcCGIName) == 0) { /* * We found a CGI that handles this URI so extract the * parameters and call the handler. */ count = extract_uri_parameters(hs, params); uri = g_pCGIs[i].pfnCGIHandler(i, count, hs->params, hs->param_vals); break; } } } #endif /* LWIP_HTTPD_CGI */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opening %s\n", uri)); err = fs_open(&hs->file_handle, uri); if (err == ERR_OK) { file = &hs->file_handle; } else { file = http_get_404_file(hs, &uri); } #if LWIP_HTTPD_SSI if (file != NULL) { /* See if we have been asked for an shtml file and, if so, enable tag checking. */ tag_check = 0; for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) { if (strstr(uri, g_pcSSIExtensions[loop])) { tag_check = 1; break; } } } #endif /* LWIP_HTTPD_SSI */ } return http_init_file(hs, file, uri, tag_check); } /** Initialize a http connection with a file to send (if found). * Called by http_find_file and http_find_error_file. * * @param hs http connection state * @param file file structure to send (or NULL if not found) * @param uri the HTTP header URI * @param tag_check enable SSI tag checking * @return ERR_OK if file was found and hs has been initialized correctly * another err_t otherwise */ static err_t http_init_file(struct http_state *hs, struct fs_file *file, const char *uri, u8_t tag_check) { if (file != NULL) { /* file opened, initialise struct http_state */ #if LWIP_HTTPD_SSI if (tag_check) { struct http_ssi_state *ssi = http_ssi_state_alloc(); if (ssi != NULL) { ssi->tag_index = 0; ssi->tag_state = TAG_NONE; ssi->parsed = file->data; ssi->parse_left = file->len; ssi->tag_end = file->data; hs->ssi = ssi; } } #else /* LWIP_HTTPD_SSI */ LWIP_UNUSED_ARG(tag_check); #endif /* LWIP_HTTPD_SSI */ hs->handle = file; hs->file = (char*)file->data; LWIP_ASSERT("File length must be positive!", (file->len >= 0)); hs->left = file->len; #if LWIP_HTTPD_DYNAMIC_FILE_READ if (hs->file == NULL) { /* Causes http_check_eof() to be called which will read the data. */ hs->left = 0; } #endif hs->retries = 0; #if LWIP_HTTPD_TIMING hs->time_started = sys_now(); #endif /* LWIP_HTTPD_TIMING */ #if !LWIP_HTTPD_DYNAMIC_HEADERS LWIP_ASSERT("HTTP headers not included in file system", hs->handle->http_header_included); #endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SUPPORT_V09 || LWIP_HTTPD_SUPPORT_HEAD if ( hs->handle->http_header_included && hs->method != METHOD_GET) { /* Search for the end of the header. */ char *head_end = strnstr(hs->file, CRLF CRLF, hs->left); size_t diff = head_end + 4 - hs->file; if (head_end == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("Expected HTTP header, but couldn't find it.\n")); hs->handle->http_header_included = 0; #if LWIP_HTTPD_SUPPORT_V09 } else if (hs->method == METHOD_V09_GET) { /* HTTP/0.9 responses are sent without HTTP header. */ hs->file += diff; hs->left -= (u32_t)diff; #endif /* LWIP_HTTPD_SUPPORT_V09*/ #if LWIP_HTTPD_SUPPORT_HEAD } else if (hs->method == METHOD_HEAD) { /* HEAD method responses are sent with only HTTP header. */ hs->left = (u32_t)diff; #endif /* LWIP_HTTPD_SUPPORT_HEAD*/ } } #endif /* LWIP_HTTPD_SUPPORT_V09 || LWIP_HTTPD_SUPPORT_HEAD*/ } else { hs->handle = NULL; hs->file = NULL; hs->left = 0; hs->retries = 0; } #if LWIP_HTTPD_DYNAMIC_HEADERS /* Determine the HTTP headers to send based on the file extension of * the requested URI. */ if ((hs->handle == NULL) || !hs->handle->http_header_included) { #if LWIP_HTTPD_SUPPORT_V09 if (hs->method != METHOD_V09_GET) /* Don't load the header. */ #endif /* LWIP_HTTPD_SUPPORT_V09*/ get_http_headers(hs, (char*)uri); #if LWIP_HTTPD_SUPPORT_HEAD if (hs->method == METHOD_HEAD) { /* Just the the header, not the file. */ hs->left = 0; hs->handle->len = 0; } #endif /* LWIP_HTTPD_SUPPORT_HEAD*/ } #else /* LWIP_HTTPD_DYNAMIC_HEADERS */ LWIP_UNUSED_ARG(uri); #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ return ERR_OK; } /** * The pcb had an error and is already deallocated. * The argument might still be valid (if != NULL). */ static void http_err(void *arg, err_t err) { struct http_state *hs = (struct http_state *)arg; LWIP_UNUSED_ARG(err); LWIP_DEBUGF(HTTPD_DEBUG, ("http_err: %s", lwip_strerr(err))); if (hs != NULL) { http_state_free(hs); } } /** * Data has been sent and acknowledged by the remote host. * This means that more data can be sent. */ static err_t http_sent(void *arg, struct tcp_pcb *pcb, u16_t len) { struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_sent %p\n", (void*)pcb)); LWIP_UNUSED_ARG(len); if (hs == NULL) { return ERR_OK; } hs->retries = 0; http_send(pcb, hs); return ERR_OK; } /** * The poll function is called every 2nd second. * If there has been no data sent (which resets the retries) in 8 seconds, close. * If the last portion of a file has not been sent in 2 seconds, close. * * This could be increased, but we don't want to waste resources for bad connections. */ static err_t http_poll(void *arg, struct tcp_pcb *pcb) { struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: pcb=%p hs=%p pcb_state=%s\n", (void*)pcb, (void*)hs, tcp_debug_state_str(pcb->state))); if (hs == NULL) { err_t closed; /* arg is null, close. */ LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: arg is NULL, close\n")); closed = http_close_conn(pcb, NULL); LWIP_UNUSED_ARG(closed); #if LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR if (closed == ERR_MEM) { tcp_abort(pcb); return ERR_ABRT; } #endif /* LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR */ return ERR_OK; } else { hs->retries++; if (hs->retries == HTTPD_MAX_RETRIES) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: too many retries, close\n")); http_close_conn(pcb, hs); return ERR_OK; } /* If this connection has a file open, try to send some more data. If * it has not yet received a GET request, don't do this since it will * cause the connection to close immediately. */ if(hs && (hs->handle)) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: try to send more data\n")); if(http_send(pcb, hs)) { /* If we wrote anything to be sent, go ahead and send it now. */ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); tcp_output(pcb); } } } return ERR_OK; } /** * Data has been received on this pcb. * For HTTP 1.0, this should normally only happen once (if the request fits in one packet). */ static err_t http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { err_t parsed = ERR_ABRT; struct http_state *hs = (struct http_state *)arg; LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: pcb=%p pbuf=%p err=%s\n", (void*)pcb, (void*)p, lwip_strerr(err))); if ((err != ERR_OK) || (p == NULL) || (hs == NULL)) { /* error or closed by other side? */ if (p != NULL) { /* Inform TCP that we have taken the data. */ tcp_recved(pcb, p->tot_len); pbuf_free(p); } if (hs == NULL) { /* this should not happen, only to be robust */ LWIP_DEBUGF(HTTPD_DEBUG, ("Error, http_recv: hs is NULL, close\n")); } http_close_conn(pcb, hs); return ERR_OK; } #if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND if (hs->no_auto_wnd) { hs->unrecved_bytes += p->tot_len; } else #endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ { /* Inform TCP that we have taken the data. */ tcp_recved(pcb, p->tot_len); } #if LWIP_HTTPD_SUPPORT_POST if (hs->post_content_len_left > 0) { /* reset idle counter when POST data is received */ hs->retries = 0; /* this is data for a POST, pass the complete pbuf to the application */ http_post_rxpbuf(hs, p); /* pbuf is passed to the application, don't free it! */ if (hs->post_content_len_left == 0) { /* all data received, send response or close connection */ http_send(pcb, hs); } return ERR_OK; } else #endif /* LWIP_HTTPD_SUPPORT_POST */ { if (hs->handle == NULL) { parsed = http_parse_request(p, hs, pcb); LWIP_ASSERT("http_parse_request: unexpected return value", parsed == ERR_OK || parsed == ERR_INPROGRESS ||parsed == ERR_ARG || parsed == ERR_USE); } else { LWIP_DEBUGF(HTTPD_DEBUG, ("http_recv: already sending data\n")); /* already sending but still receiving data, we might want to RST here? */ pbuf_free(p); } #if LWIP_HTTPD_SUPPORT_REQUESTLIST if (parsed != ERR_INPROGRESS) { /* request fully parsed or error */ if (hs->req != NULL) { pbuf_free(hs->req); hs->req = NULL; } } #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ pbuf_free(p); if (parsed == ERR_OK) { #if LWIP_HTTPD_SUPPORT_POST if (hs->post_content_len_left == 0) #endif /* LWIP_HTTPD_SUPPORT_POST */ { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: data %p len %"S32_F"\n", hs->file, hs->left)); http_send(pcb, hs); } } else if (parsed == ERR_ARG) { /* @todo: close on ERR_USE? */ http_close_conn(pcb, hs); } } return ERR_OK; } /** * A new incoming connection has been accepted. */ static err_t http_accept(void *arg, struct tcp_pcb *pcb, err_t err) { struct http_state *hs; struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)arg; LWIP_UNUSED_ARG(err); LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept %p / %p\n", (void*)pcb, arg)); /* Decrease the listen backlog counter */ tcp_accepted(lpcb); /* Set priority */ tcp_setprio(pcb, HTTPD_TCP_PRIO); /* Allocate memory for the structure that holds the state of the connection - initialized by that function. */ hs = http_state_alloc(); if (hs == NULL) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept: Out of memory, RST\n")); return ERR_MEM; } hs->pcb = pcb; /* Tell TCP that this is the structure we wish to be passed for our callbacks. */ tcp_arg(pcb, hs); /* Set up the various callback functions */ tcp_recv(pcb, http_recv); tcp_err(pcb, http_err); tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); tcp_sent(pcb, http_sent); return ERR_OK; } /** * Initialize the httpd with the specified local address. */ static void httpd_init_addr(ip_addr_t *local_addr) { struct tcp_pcb *pcb; err_t err; pcb = tcp_new(); LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL); tcp_setprio(pcb, HTTPD_TCP_PRIO); /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */ err = tcp_bind(pcb, local_addr, HTTPD_SERVER_PORT); LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK); pcb = tcp_listen(pcb); LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL); /* initialize callback arg and accept callback */ tcp_arg(pcb, pcb); tcp_accept(pcb, http_accept); } /** * Initialize the httpd: set up a listening PCB and bind it to the defined port */ void httpd_init(void) { #if MEMP_MEM_MALLOC || MEM_USE_POOLS #if HTTPD_USE_MEM_POOL LWIP_ASSERT("memp_sizes[MEMP_HTTPD_STATE] >= sizeof(http_state)", memp_sizes[MEMP_HTTPD_STATE] >= sizeof(struct http_state)); #if LWIP_HTTPD_SSI LWIP_ASSERT("memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(http_ssi_state)", memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(struct http_ssi_state)); #endif #endif #endif LWIP_DEBUGF(HTTPD_DEBUG, ("httpd_init\n")); httpd_init_addr(IP_ADDR_ANY); } #if LWIP_HTTPD_SSI /** * Set the SSI handler function. * * @param ssi_handler the SSI handler function * @param tags an array of SSI tag strings to search for in SSI-enabled files * @param num_tags number of tags in the 'tags' array */ void http_set_ssi_handler(tSSIHandler ssi_handler, const char **tags, int num_tags) { LWIP_DEBUGF(HTTPD_DEBUG, ("http_set_ssi_handler\n")); LWIP_ASSERT("no ssi_handler given", ssi_handler != NULL); LWIP_ASSERT("no tags given", tags != NULL); LWIP_ASSERT("invalid number of tags", num_tags > 0); g_pfnSSIHandler = ssi_handler; g_ppcTags = tags; g_iNumTags = num_tags; } #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_CGI /** * Set an array of CGI filenames/handler functions * * @param cgis an array of CGI filenames/handler functions * @param num_handlers number of elements in the 'cgis' array */ void http_set_cgi_handlers(const tCGI *cgis, int num_handlers) { LWIP_ASSERT("no cgis given", cgis != NULL); LWIP_ASSERT("invalid number of handlers", num_handlers > 0); g_pCGIs = cgis; g_iNumCGIs = num_handlers; } #endif /* LWIP_HTTPD_CGI */ #endif /* LWIP_TCP */ \ No newline at end of file diff --git a/apps/httpserver_raw/httpd.h b/apps/httpserver_raw/httpd.h index 3962f72..1f6e4a0 100644 --- a/apps/httpserver_raw/httpd.h +++ b/apps/httpserver_raw/httpd.h @@ -1,244 +1 @@ -/* - * Copyright (c) 2001-2003 Swedish Institute of Computer Science. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, - * are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING - * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - * - * This file is part of the lwIP TCP/IP stack. - * - * Author: Adam Dunkels - * - * This version of the file has been modified by Texas Instruments to offer - * simple server-side-include (SSI) and Common Gateway Interface (CGI) - * capability. - */ - -#ifndef LWIP_HTTPD_H -#define LWIP_HTTPD_H - -#include "lwip/opt.h" -#include "lwip/err.h" -#include "lwip/pbuf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** Set this to 1 to support CGI */ -#ifndef LWIP_HTTPD_CGI -#define LWIP_HTTPD_CGI 0 -#endif - -/** Set this to 1 to support SSI (Server-Side-Includes) */ -#ifndef LWIP_HTTPD_SSI -#define LWIP_HTTPD_SSI 0 -#endif - -/** Set this to 1 to support HTTP POST */ -#ifndef LWIP_HTTPD_SUPPORT_POST -#define LWIP_HTTPD_SUPPORT_POST 0 -#endif - - -#if LWIP_HTTPD_CGI - -/* - * Function pointer for a CGI script handler. - * - * This function is called each time the HTTPD server is asked for a file - * whose name was previously registered as a CGI function using a call to - * http_set_cgi_handler. The iIndex parameter provides the index of the - * CGI within the ppcURLs array passed to http_set_cgi_handler. Parameters - * pcParam and pcValue provide access to the parameters provided along with - * the URI. iNumParams provides a count of the entries in the pcParam and - * pcValue arrays. Each entry in the pcParam array contains the name of a - * parameter with the corresponding entry in the pcValue array containing the - * value for that parameter. Note that pcParam may contain multiple elements - * with the same name if, for example, a multi-selection list control is used - * in the form generating the data. - * - * The function should return a pointer to a character string which is the - * path and filename of the response that is to be sent to the connected - * browser, for example "/thanks.htm" or "/response/error.ssi". - * - * The maximum number of parameters that will be passed to this function via - * iNumParams is defined by LWIP_HTTPD_MAX_CGI_PARAMETERS. Any parameters in the incoming - * HTTP request above this number will be discarded. - * - * Requests intended for use by this CGI mechanism must be sent using the GET - * method (which encodes all parameters within the URI rather than in a block - * later in the request). Attempts to use the POST method will result in the - * request being ignored. - * - */ -typedef const char *(*tCGIHandler)(int iIndex, int iNumParams, char *pcParam[], - char *pcValue[]); - -/* - * Structure defining the base filename (URL) of a CGI and the associated - * function which is to be called when that URL is requested. - */ -typedef struct -{ - const char *pcCGIName; - tCGIHandler pfnCGIHandler; -} tCGI; - -void http_set_cgi_handlers(const tCGI *pCGIs, int iNumHandlers); - - -/* The maximum number of parameters that the CGI handler can be sent. */ -#ifndef LWIP_HTTPD_MAX_CGI_PARAMETERS -#define LWIP_HTTPD_MAX_CGI_PARAMETERS 16 -#endif - -#endif /* LWIP_HTTPD_CGI */ - -#if LWIP_HTTPD_SSI - -/** LWIP_HTTPD_SSI_MULTIPART==1: SSI handler function is called with 2 more - * arguments indicating a counter for insert string that are too long to be - * inserted at once: the SSI handler function must then set 'next_tag_part' - * which will be passed back to it in the next call. */ -#ifndef LWIP_HTTPD_SSI_MULTIPART -#define LWIP_HTTPD_SSI_MULTIPART 0 -#endif - -/* - * Function pointer for the SSI tag handler callback. - * - * This function will be called each time the HTTPD server detects a tag of the - * form in a .shtml, .ssi or .shtm file where "name" appears as - * one of the tags supplied to http_set_ssi_handler in the ppcTags array. The - * returned insert string, which will be appended after the the string - * "" in file sent back to the client,should be written to pointer - * pcInsert. iInsertLen contains the size of the buffer pointed to by - * pcInsert. The iIndex parameter provides the zero-based index of the tag as - * found in the ppcTags array and identifies the tag that is to be processed. - * - * The handler returns the number of characters written to pcInsert excluding - * any terminating NULL or a negative number to indicate a failure (tag not - * recognized, for example). - * - * Note that the behavior of this SSI mechanism is somewhat different from the - * "normal" SSI processing as found in, for example, the Apache web server. In - * this case, the inserted text is appended following the SSI tag rather than - * replacing the tag entirely. This allows for an implementation that does not - * require significant additional buffering of output data yet which will still - * offer usable SSI functionality. One downside to this approach is when - * attempting to use SSI within JavaScript. The SSI tag is structured to - * resemble an HTML comment but this syntax does not constitute a comment - * within JavaScript and, hence, leaving the tag in place will result in - * problems in these cases. To work around this, any SSI tag which needs to - * output JavaScript code must do so in an encapsulated way, sending the whole - * HTML section as a single include. - */ -typedef u16_t (*tSSIHandler)(int iIndex, char *pcInsert, int iInsertLen -#if LWIP_HTTPD_SSI_MULTIPART - , u16_t current_tag_part, u16_t *next_tag_part -#endif /* LWIP_HTTPD_SSI_MULTIPART */ -#if LWIP_HTTPD_FILE_STATE - , void *connection_state -#endif /* LWIP_HTTPD_FILE_STATE */ - ); - -void http_set_ssi_handler(tSSIHandler pfnSSIHandler, - const char **ppcTags, int iNumTags); - -/* The maximum length of the string comprising the tag name */ -#ifndef LWIP_HTTPD_MAX_TAG_NAME_LEN -#define LWIP_HTTPD_MAX_TAG_NAME_LEN 8 -#endif - -/* The maximum length of string that can be returned to replace any given tag */ -#ifndef LWIP_HTTPD_MAX_TAG_INSERT_LEN -#define LWIP_HTTPD_MAX_TAG_INSERT_LEN 192 -#endif - -#endif /* LWIP_HTTPD_SSI */ - -#if LWIP_HTTPD_SUPPORT_POST - -/* These functions must be implemented by the application */ - -/** Called when a POST request has been received. The application can decide - * whether to accept it or not. - * - * @param connection Unique connection identifier, valid until httpd_post_end - * is called. - * @param uri The HTTP header URI receiving the POST request. - * @param http_request The raw HTTP request (the first packet, normally). - * @param http_request_len Size of 'http_request'. - * @param content_len Content-Length from HTTP header. - * @param response_uri Filename of response file, to be filled when denying the - * request - * @param response_uri_len Size of the 'response_uri' buffer. - * @param post_auto_wnd Set this to 0 to let the callback code handle window - * updates by calling 'httpd_post_data_recved' (to throttle rx speed) - * default is 1 (httpd handles window updates automatically) - * @return ERR_OK: Accept the POST request, data may be passed in - * another err_t: Deny the POST request, send back 'bad request'. - */ -err_t httpd_post_begin(void *connection, const char *uri, const char *http_request, - u16_t http_request_len, int content_len, char *response_uri, - u16_t response_uri_len, u8_t *post_auto_wnd); - -/** Called for each pbuf of data that has been received for a POST. - * ATTENTION: The application is responsible for freeing the pbufs passed in! - * - * @param connection Unique connection identifier. - * @param p Received data. - * @return ERR_OK: Data accepted. - * another err_t: Data denied, http_post_get_response_uri will be called. - */ -err_t httpd_post_receive_data(void *connection, struct pbuf *p); - -/** Called when all data is received or when the connection is closed. - * The application must return the filename/URI of a file to send in response - * to this POST request. If the response_uri buffer is untouched, a 404 - * response is returned. - * - * @param connection Unique connection identifier. - * @param response_uri Filename of response file, to be filled when denying the request - * @param response_uri_len Size of the 'response_uri' buffer. - */ -void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len); - -#ifndef LWIP_HTTPD_POST_MANUAL_WND -#define LWIP_HTTPD_POST_MANUAL_WND 0 -#endif - -#if LWIP_HTTPD_POST_MANUAL_WND -void httpd_post_data_recved(void *connection, u16_t recved_len); -#endif /* LWIP_HTTPD_POST_MANUAL_WND */ - -#endif /* LWIP_HTTPD_SUPPORT_POST */ - -void httpd_init(void); - - -#ifdef __cplusplus -} -#endif - -#endif /* LWIP_HTTPD_H */ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * * This version of the file has been modified by Texas Instruments to offer * simple server-side-include (SSI) and Common Gateway Interface (CGI) * capability. */ #ifndef LWIP_HTTPD_H #define LWIP_HTTPD_H #include "lwip/opt.h" #include "lwip/err.h" #include "lwip/pbuf.h" #ifdef __cplusplus extern "C" { #endif /** Set this to 1 to support CGI */ #ifndef LWIP_HTTPD_CGI #define LWIP_HTTPD_CGI 0 #endif /** Set this to 1 to support SSI (Server-Side-Includes) */ #ifndef LWIP_HTTPD_SSI #define LWIP_HTTPD_SSI 0 #endif /** Set this to 1 to support HTTP POST */ #ifndef LWIP_HTTPD_SUPPORT_POST #define LWIP_HTTPD_SUPPORT_POST 0 #endif /** Set this to 1 to support HTTP HEAD */ #ifndef LWIP_HTTPD_SUPPORT_HEAD #define LWIP_HTTPD_SUPPORT_HEAD 0 #endif #if LWIP_HTTPD_CGI /* * Function pointer for a CGI script handler. * * This function is called each time the HTTPD server is asked for a file * whose name was previously registered as a CGI function using a call to * http_set_cgi_handler. The iIndex parameter provides the index of the * CGI within the ppcURLs array passed to http_set_cgi_handler. Parameters * pcParam and pcValue provide access to the parameters provided along with * the URI. iNumParams provides a count of the entries in the pcParam and * pcValue arrays. Each entry in the pcParam array contains the name of a * parameter with the corresponding entry in the pcValue array containing the * value for that parameter. Note that pcParam may contain multiple elements * with the same name if, for example, a multi-selection list control is used * in the form generating the data. * * The function should return a pointer to a character string which is the * path and filename of the response that is to be sent to the connected * browser, for example "/thanks.htm" or "/response/error.ssi". * * The maximum number of parameters that will be passed to this function via * iNumParams is defined by LWIP_HTTPD_MAX_CGI_PARAMETERS. Any parameters in the incoming * HTTP request above this number will be discarded. * * Requests intended for use by this CGI mechanism must be sent using the GET * method (which encodes all parameters within the URI rather than in a block * later in the request). Attempts to use the POST method will result in the * request being ignored. * */ typedef const char *(*tCGIHandler)(int iIndex, int iNumParams, char *pcParam[], char *pcValue[]); /* * Structure defining the base filename (URL) of a CGI and the associated * function which is to be called when that URL is requested. */ typedef struct { const char *pcCGIName; tCGIHandler pfnCGIHandler; } tCGI; void http_set_cgi_handlers(const tCGI *pCGIs, int iNumHandlers); /* The maximum number of parameters that the CGI handler can be sent. */ #ifndef LWIP_HTTPD_MAX_CGI_PARAMETERS #define LWIP_HTTPD_MAX_CGI_PARAMETERS 16 #endif #endif /* LWIP_HTTPD_CGI */ #if LWIP_HTTPD_SSI /** LWIP_HTTPD_SSI_MULTIPART==1: SSI handler function is called with 2 more * arguments indicating a counter for insert string that are too long to be * inserted at once: the SSI handler function must then set 'next_tag_part' * which will be passed back to it in the next call. */ #ifndef LWIP_HTTPD_SSI_MULTIPART #define LWIP_HTTPD_SSI_MULTIPART 0 #endif /* * Function pointer for the SSI tag handler callback. * * This function will be called each time the HTTPD server detects a tag of the * form in a .shtml, .ssi or .shtm file where "name" appears as * one of the tags supplied to http_set_ssi_handler in the ppcTags array. The * returned insert string, which will be appended after the the string * "" in file sent back to the client,should be written to pointer * pcInsert. iInsertLen contains the size of the buffer pointed to by * pcInsert. The iIndex parameter provides the zero-based index of the tag as * found in the ppcTags array and identifies the tag that is to be processed. * * The handler returns the number of characters written to pcInsert excluding * any terminating NULL or a negative number to indicate a failure (tag not * recognized, for example). * * Note that the behavior of this SSI mechanism is somewhat different from the * "normal" SSI processing as found in, for example, the Apache web server. In * this case, the inserted text is appended following the SSI tag rather than * replacing the tag entirely. This allows for an implementation that does not * require significant additional buffering of output data yet which will still * offer usable SSI functionality. One downside to this approach is when * attempting to use SSI within JavaScript. The SSI tag is structured to * resemble an HTML comment but this syntax does not constitute a comment * within JavaScript and, hence, leaving the tag in place will result in * problems in these cases. To work around this, any SSI tag which needs to * output JavaScript code must do so in an encapsulated way, sending the whole * HTML section as a single include. */ typedef u16_t (*tSSIHandler)(int iIndex, char *pcInsert, int iInsertLen #if LWIP_HTTPD_SSI_MULTIPART , u16_t current_tag_part, u16_t *next_tag_part #endif /* LWIP_HTTPD_SSI_MULTIPART */ #if LWIP_HTTPD_FILE_STATE , void *connection_state #endif /* LWIP_HTTPD_FILE_STATE */ ); void http_set_ssi_handler(tSSIHandler pfnSSIHandler, const char **ppcTags, int iNumTags); /* The maximum length of the string comprising the tag name */ #ifndef LWIP_HTTPD_MAX_TAG_NAME_LEN #define LWIP_HTTPD_MAX_TAG_NAME_LEN 8 #endif /* The maximum length of string that can be returned to replace any given tag */ #ifndef LWIP_HTTPD_MAX_TAG_INSERT_LEN #define LWIP_HTTPD_MAX_TAG_INSERT_LEN 192 #endif #endif /* LWIP_HTTPD_SSI */ #if LWIP_HTTPD_SUPPORT_POST /* These functions must be implemented by the application */ /** Called when a POST request has been received. The application can decide * whether to accept it or not. * * @param connection Unique connection identifier, valid until httpd_post_end * is called. * @param uri The HTTP header URI receiving the POST request. * @param http_request The raw HTTP request (the first packet, normally). * @param http_request_len Size of 'http_request'. * @param content_len Content-Length from HTTP header. * @param response_uri Filename of response file, to be filled when denying the * request * @param response_uri_len Size of the 'response_uri' buffer. * @param post_auto_wnd Set this to 0 to let the callback code handle window * updates by calling 'httpd_post_data_recved' (to throttle rx speed) * default is 1 (httpd handles window updates automatically) * @return ERR_OK: Accept the POST request, data may be passed in * another err_t: Deny the POST request, send back 'bad request'. */ err_t httpd_post_begin(void *connection, const char *uri, const char *http_request, u16_t http_request_len, int content_len, char *response_uri, u16_t response_uri_len, u8_t *post_auto_wnd); /** Called for each pbuf of data that has been received for a POST. * ATTENTION: The application is responsible for freeing the pbufs passed in! * * @param connection Unique connection identifier. * @param p Received data. * @return ERR_OK: Data accepted. * another err_t: Data denied, http_post_get_response_uri will be called. */ err_t httpd_post_receive_data(void *connection, struct pbuf *p); /** Called when all data is received or when the connection is closed. * The application must return the filename/URI of a file to send in response * to this POST request. If the response_uri buffer is untouched, a 404 * response is returned. * * @param connection Unique connection identifier. * @param response_uri Filename of response file, to be filled when denying the request * @param response_uri_len Size of the 'response_uri' buffer. */ void httpd_post_finished(void *connection, char *response_uri, u16_t response_uri_len); #ifndef LWIP_HTTPD_POST_MANUAL_WND #define LWIP_HTTPD_POST_MANUAL_WND 0 #endif #if LWIP_HTTPD_POST_MANUAL_WND void httpd_post_data_recved(void *connection, u16_t recved_len); #endif /* LWIP_HTTPD_POST_MANUAL_WND */ #endif /* LWIP_HTTPD_SUPPORT_POST */ void httpd_init(void); #ifdef __cplusplus } #endif #endif /* LWIP_HTTPD_H */ \ No newline at end of file diff --git a/apps/httpserver_raw/httpd.orig.c b/apps/httpserver_raw/httpd.orig.c new file mode 100644 index 0000000..772b179 --- /dev/null +++ b/apps/httpserver_raw/httpd.orig.c @@ -0,0 +1,2533 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Simon Goldschmidt + * + */ + +/* This httpd supports for a + * rudimentary server-side-include facility which will replace tags of the form + * in any file whose extension is .shtml, .shtm or .ssi with + * strings provided by an include handler whose pointer is provided to the + * module via function http_set_ssi_handler(). + * Additionally, a simple common + * gateway interface (CGI) handling mechanism has been added to allow clients + * to hook functions to particular request URIs. + * + * To enable SSI support, define label LWIP_HTTPD_SSI in lwipopts.h. + * To enable CGI support, define label LWIP_HTTPD_CGI in lwipopts.h. + * + * By default, the server assumes that HTTP headers are already present in + * each file stored in the file system. By defining LWIP_HTTPD_DYNAMIC_HEADERS in + * lwipopts.h, this behavior can be changed such that the server inserts the + * headers automatically based on the extension of the file being served. If + * this mode is used, be careful to ensure that the file system image used + * does not already contain the header information. + * + * File system images without headers can be created using the makefsfile + * tool with the -h command line option. + * + * + * Notes about valid SSI tags + * -------------------------- + * + * The following assumptions are made about tags used in SSI markers: + * + * 1. No tag may contain '-' or whitespace characters within the tag name. + * 2. Whitespace is allowed between the tag leadin "". + * 3. The maximum tag name length is LWIP_HTTPD_MAX_TAG_NAME_LEN, currently 8 characters. + * + * Notes on CGI usage + * ------------------ + * + * The simple CGI support offered here works with GET method requests only + * and can handle up to 16 parameters encoded into the URI. The handler + * function may not write directly to the HTTP output but must return a + * filename that the HTTP server will send to the browser as a response to + * the incoming CGI request. + * + * + * + * The list of supported file types is quite short, so if makefsdata complains + * about an unknown extension, make sure to add it (and its doctype) to + * the 'g_psHTTPHeaders' list. + */ +#include "httpd.h" +#include "lwip/debug.h" +#include "lwip/stats.h" +#include "httpd_structs.h" +#include "lwip/tcp.h" +#include "fs.h" + +#include +#include + +#if LWIP_TCP + +#ifndef HTTPD_DEBUG +#define HTTPD_DEBUG LWIP_DBG_OFF +#endif + +/** Set this to 1, set MEMP_USE_CUSTOM_POOLS to 1 and add the next line to + * lwippools.h to use a memp pool for allocating struct http_state instead of + * the heap: + * + * LWIP_MEMPOOL(HTTPD_STATE, 20, 100, "HTTPD_STATE") + */ +#ifndef HTTPD_USE_MEM_POOL +#define HTTPD_USE_MEM_POOL 0 +#endif + +/** The server port for HTTPD to use */ +#ifndef HTTPD_SERVER_PORT +#define HTTPD_SERVER_PORT 80 +#endif + +/** Maximum retries before the connection is aborted/closed. + * - number of times pcb->poll is called -> default is 4*500ms = 2s; + * - reset when pcb->sent is called + */ +#ifndef HTTPD_MAX_RETRIES +#define HTTPD_MAX_RETRIES 4 +#endif + +/** The poll delay is X*500ms */ +#ifndef HTTPD_POLL_INTERVAL +#define HTTPD_POLL_INTERVAL 4 +#endif + +/** Priority for tcp pcbs created by HTTPD (very low by default). + * Lower priorities get killed first when running out of memory. + */ +#ifndef HTTPD_TCP_PRIO +#define HTTPD_TCP_PRIO TCP_PRIO_MIN +#endif + +/** Set this to 1 to enable timing each file sent */ +#ifndef LWIP_HTTPD_TIMING +#define LWIP_HTTPD_TIMING 0 +#endif +#ifndef HTTPD_DEBUG_TIMING +#define HTTPD_DEBUG_TIMING LWIP_DBG_OFF +#endif + +/** Set this to 1 on platforms where strnstr is not available */ +#ifndef LWIP_HTTPD_STRNSTR_PRIVATE +#define LWIP_HTTPD_STRNSTR_PRIVATE 1 +#endif + +/** Set this to one to show error pages when parsing a request fails instead + of simply closing the connection. */ +#ifndef LWIP_HTTPD_SUPPORT_EXTSTATUS +#define LWIP_HTTPD_SUPPORT_EXTSTATUS 0 +#endif + +/** Set this to 0 to drop support for HTTP/0.9 clients (to save some bytes) */ +#ifndef LWIP_HTTPD_SUPPORT_V09 +#define LWIP_HTTPD_SUPPORT_V09 1 +#endif + +/** Set this to 1 to enable HTTP/1.1 persistent connections. + * ATTENTION: If the generated file system includes HTTP headers, these must + * include the "Connection: keep-alive" header (pass argument "-11" to makefsdata). + */ +#ifndef LWIP_HTTPD_SUPPORT_11_KEEPALIVE +#define LWIP_HTTPD_SUPPORT_11_KEEPALIVE 0 +#endif + +/** Set this to 1 to support HTTP request coming in in multiple packets/pbufs */ +#ifndef LWIP_HTTPD_SUPPORT_REQUESTLIST +#define LWIP_HTTPD_SUPPORT_REQUESTLIST 1 +#endif + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST +/** Number of rx pbufs to enqueue to parse an incoming request (up to the first + newline) */ +#ifndef LWIP_HTTPD_REQ_QUEUELEN +#define LWIP_HTTPD_REQ_QUEUELEN 5 +#endif + +/** Number of (TCP payload-) bytes (in pbufs) to enqueue to parse and incoming + request (up to the first double-newline) */ +#ifndef LWIP_HTTPD_REQ_BUFSIZE +#define LWIP_HTTPD_REQ_BUFSIZE LWIP_HTTPD_MAX_REQ_LENGTH +#endif + +/** Defines the maximum length of a HTTP request line (up to the first CRLF, + copied from pbuf into this a global buffer when pbuf- or packet-queues + are received - otherwise the input pbuf is used directly) */ +#ifndef LWIP_HTTPD_MAX_REQ_LENGTH +#define LWIP_HTTPD_MAX_REQ_LENGTH LWIP_MIN(1023, (LWIP_HTTPD_REQ_QUEUELEN * PBUF_POOL_BUFSIZE)) +#endif +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + +/** Maximum length of the filename to send as response to a POST request, + * filled in by the application when a POST is finished. + */ +#ifndef LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN +#define LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN 63 +#endif + +/** Set this to 0 to not send the SSI tag (default is on, so the tag will + * be sent in the HTML page */ +#ifndef LWIP_HTTPD_SSI_INCLUDE_TAG +#define LWIP_HTTPD_SSI_INCLUDE_TAG 1 +#endif + +/** Set this to 1 to call tcp_abort when tcp_close fails with memory error. + * This can be used to prevent consuming all memory in situations where the + * HTTP server has low priority compared to other communication. */ +#ifndef LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR +#define LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR 0 +#endif + +/** Set this to 1 to kill the oldest connection when running out of + * memory for 'struct http_state' or 'struct http_ssi_state'. + * ATTENTION: This puts all connections on a linked list, so may be kind of slow. + */ +#ifndef LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED +#define LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED 0 +#endif + +/** Minimum length for a valid HTTP/0.9 request: "GET /\r\n" -> 7 bytes */ +#define MIN_REQ_LEN 7 + +#define CRLF "\r\n" +#define HTTP11_CONNECTIONKEEPALIVE "Connection: keep-alive" + +#if LWIP_HTTPD_SSI +#define LWIP_HTTPD_IS_SSI(hs) ((hs)->ssi) +#else /* LWIP_HTTPD_SSI */ +#define LWIP_HTTPD_IS_SSI(hs) 0 +#endif /* LWIP_HTTPD_SSI */ + +/** These defines check whether tcp_write has to copy data or not */ + +/** This was TI's check whether to let TCP copy data or not +#define HTTP_IS_DATA_VOLATILE(hs) ((hs->file < (char *)0x20000000) ? 0 : TCP_WRITE_FLAG_COPY)*/ +#ifndef HTTP_IS_DATA_VOLATILE +#if LWIP_HTTPD_SSI +/* Copy for SSI files, no copy for non-SSI files */ +#define HTTP_IS_DATA_VOLATILE(hs) ((hs)->ssi ? TCP_WRITE_FLAG_COPY : 0) +#else /* LWIP_HTTPD_SSI */ +/** Default: don't copy if the data is sent from file-system directly */ +#define HTTP_IS_DATA_VOLATILE(hs) (((hs->file != NULL) && (hs->handle != NULL) && (hs->file == \ + (char*)hs->handle->data + hs->handle->len - hs->left)) \ + ? 0 : TCP_WRITE_FLAG_COPY) +#endif /* LWIP_HTTPD_SSI */ +#endif + +/** Default: headers are sent from ROM */ +#ifndef HTTP_IS_HDR_VOLATILE +#define HTTP_IS_HDR_VOLATILE(hs, ptr) 0 +#endif + +#if LWIP_HTTPD_SSI +/** Default: Tags are sent from struct http_state and are therefore volatile */ +#ifndef HTTP_IS_TAG_VOLATILE +#define HTTP_IS_TAG_VOLATILE(ptr) TCP_WRITE_FLAG_COPY +#endif +#endif /* LWIP_HTTPD_SSI */ + +/* By default, the httpd is limited to send 2*pcb->mss to keep resource usage low + when http is not an important protocol in the device. */ +#ifndef HTTPD_LIMIT_SENDING_TO_2MSS +#define HTTPD_LIMIT_SENDING_TO_2MSS 1 +#endif + +/* Define this to a function that returns the maximum amount of data to enqueue. + The function have this signature: u16_t fn(struct tcp_pcb* pcb); */ +#ifndef HTTPD_MAX_WRITE_LEN +#if HTTPD_LIMIT_SENDING_TO_2MSS +#define HTTPD_MAX_WRITE_LEN(pcb) (2 * tcp_mss(pcb)) +#endif +#endif + +/* Return values for http_send_*() */ +#define HTTP_DATA_TO_SEND_BREAK 2 +#define HTTP_DATA_TO_SEND_CONTINUE 1 +#define HTTP_NO_DATA_TO_SEND 0 + +#if HTTPD_USE_MEM_POOL +#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)memp_malloc(MEMP_HTTPD_SSI_STATE) +#define HTTP_ALLOC_HTTP_STATE() (struct http_state *)memp_malloc(MEMP_HTTPD_STATE) +#else /* HTTPD_USE_MEM_POOL */ +#define HTTP_ALLOC_SSI_STATE() (struct http_ssi_state *)mem_malloc(sizeof(struct http_ssi_state)) +#define HTTP_ALLOC_HTTP_STATE() (struct http_state *)mem_malloc(sizeof(struct http_state)) +#endif /* HTTPD_USE_MEM_POOL */ + +typedef struct +{ + const char *name; + u8_t shtml; +} default_filename; + +const default_filename g_psDefaultFilenames[] = { + {"/index.shtml", 1 }, + {"/index.ssi", 1 }, + {"/index.shtm", 1 }, + {"/index.html", 0 }, + {"/index.htm", 0 } +}; + +#define NUM_DEFAULT_FILENAMES (sizeof(g_psDefaultFilenames) / \ + sizeof(default_filename)) + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST +/** HTTP request is copied here from pbufs for simple parsing */ +static char httpd_req_buf[LWIP_HTTPD_MAX_REQ_LENGTH+1]; +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + +#if LWIP_HTTPD_SUPPORT_POST +/** Filename for response file to send when POST is finished */ +static char http_post_response_filename[LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN+1]; +#endif /* LWIP_HTTPD_SUPPORT_POST */ + +#if LWIP_HTTPD_DYNAMIC_HEADERS +/* The number of individual strings that comprise the headers sent before each + * requested file. + */ +#define NUM_FILE_HDR_STRINGS 3 +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ + +#if LWIP_HTTPD_SSI + +#define HTTPD_LAST_TAG_PART 0xFFFF + +enum tag_check_state { + TAG_NONE, /* Not processing an SSI tag */ + TAG_LEADIN, /* Tag lead in "" being processed */ + TAG_SENDING /* Sending tag replacement string */ +}; + +struct http_ssi_state { + const char *parsed; /* Pointer to the first unparsed byte in buf. */ +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + const char *tag_started;/* Pointer to the first opening '<' of the tag. */ +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ + const char *tag_end; /* Pointer to char after the closing '>' of the tag. */ + u32_t parse_left; /* Number of unparsed bytes in buf. */ + u16_t tag_index; /* Counter used by tag parsing state machine */ + u16_t tag_insert_len; /* Length of insert in string tag_insert */ +#if LWIP_HTTPD_SSI_MULTIPART + u16_t tag_part; /* Counter passed to and changed by tag insertion function to insert multiple times */ +#endif /* LWIP_HTTPD_SSI_MULTIPART */ + u8_t tag_name_len; /* Length of the tag name in string tag_name */ + char tag_name[LWIP_HTTPD_MAX_TAG_NAME_LEN + 1]; /* Last tag name extracted */ + char tag_insert[LWIP_HTTPD_MAX_TAG_INSERT_LEN + 1]; /* Insert string for tag_name */ + enum tag_check_state tag_state; /* State of the tag processor */ +}; +#endif /* LWIP_HTTPD_SSI */ + +struct http_state { +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED + struct http_state *next; +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + struct fs_file file_handle; + struct fs_file *handle; + char *file; /* Pointer to first unsent byte in buf. */ + + struct tcp_pcb *pcb; +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + struct pbuf *req; +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + +#if LWIP_HTTPD_DYNAMIC_FILE_READ + char *buf; /* File read buffer. */ + int buf_len; /* Size of file read buffer, buf. */ +#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ + u32_t left; /* Number of unsent bytes in buf. */ + u8_t retries; +#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE + u8_t keepalive; +#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ +#if LWIP_HTTPD_SSI + struct http_ssi_state *ssi; +#endif /* LWIP_HTTPD_SSI */ +#if LWIP_HTTPD_CGI + char *params[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Params extracted from the request URI */ + char *param_vals[LWIP_HTTPD_MAX_CGI_PARAMETERS]; /* Values for each extracted param */ +#endif /* LWIP_HTTPD_CGI */ +#if LWIP_HTTPD_DYNAMIC_HEADERS + const char *hdrs[NUM_FILE_HDR_STRINGS]; /* HTTP headers to be sent. */ + u16_t hdr_pos; /* The position of the first unsent header byte in the + current string */ + u16_t hdr_index; /* The index of the hdr string currently being sent. */ +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ +#if LWIP_HTTPD_TIMING + u32_t time_started; +#endif /* LWIP_HTTPD_TIMING */ +#if LWIP_HTTPD_SUPPORT_POST + u32_t post_content_len_left; +#if LWIP_HTTPD_POST_MANUAL_WND + u32_t unrecved_bytes; + u8_t no_auto_wnd; + u8_t post_finished; +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ +#endif /* LWIP_HTTPD_SUPPORT_POST*/ +}; + +static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs); +static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn); +static err_t http_find_file(struct http_state *hs, const char *uri, int is_09); +static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check); +static err_t http_poll(void *arg, struct tcp_pcb *pcb); +static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs); +#if LWIP_HTTPD_FS_ASYNC_READ +static void http_continue(void *connection); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + +#if LWIP_HTTPD_SSI +/* SSI insert handler function pointer. */ +tSSIHandler g_pfnSSIHandler = NULL; +int g_iNumTags = 0; +const char **g_ppcTags = NULL; + +#define LEN_TAG_LEAD_IN 5 +const char * const g_pcTagLeadIn = ""; +#endif /* LWIP_HTTPD_SSI */ + +#if LWIP_HTTPD_CGI +/* CGI handler information */ +const tCGI *g_pCGIs; +int g_iNumCGIs; +#endif /* LWIP_HTTPD_CGI */ + +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED +/** global list of active HTTP connections, use to kill the oldest when + running out of memory */ +static struct http_state *http_connections; +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + +#if LWIP_HTTPD_STRNSTR_PRIVATE +/** Like strstr but does not need 'buffer' to be NULL-terminated */ +static char* +strnstr(const char* buffer, const char* token, size_t n) +{ + const char* p; + int tokenlen = (int)strlen(token); + if (tokenlen == 0) { + return (char *)buffer; + } + for (p = buffer; *p && (p + tokenlen <= buffer + n); p++) { + if ((*p == *token) && (strncmp(p, token, tokenlen) == 0)) { + return (char *)p; + } + } + return NULL; +} +#endif /* LWIP_HTTPD_STRNSTR_PRIVATE */ + +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED +static void +http_kill_oldest_connection(u8_t ssi_required) +{ + struct http_state *hs = http_connections; + struct http_state *hs_free_next = NULL; + while(hs && hs->next) { +#if LWIP_HTTPD_SSI + if (ssi_required) { + if (hs->next->ssi != NULL) { + hs_free_next = hs; + } + } else +#else /* LWIP_HTTPD_SSI */ + LWIP_UNUSED_ARG(ssi_required); +#endif /* LWIP_HTTPD_SSI */ + { + hs_free_next = hs; + } + hs = hs->next; + } + if (hs_free_next != NULL) { + LWIP_ASSERT("hs_free_next->next != NULL", hs_free_next->next != NULL); + LWIP_ASSERT("hs_free_next->next->pcb != NULL", hs_free_next->next->pcb != NULL); + /* send RST when killing a connection because of memory shortage */ + http_close_or_abort_conn(hs_free_next->next->pcb, hs_free_next->next, 1); /* this also unlinks the http_state from the list */ + } +} +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + +#if LWIP_HTTPD_SSI +/** Allocate as struct http_ssi_state. */ +static struct http_ssi_state* +http_ssi_state_alloc(void) +{ + struct http_ssi_state *ret = HTTP_ALLOC_SSI_STATE(); +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED + if (ret == NULL) { + http_kill_oldest_connection(1); + ret = HTTP_ALLOC_SSI_STATE(); + } +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + if (ret != NULL) { + memset(ret, 0, sizeof(struct http_ssi_state)); + } + return ret; +} + +/** Free a struct http_ssi_state. */ +static void +http_ssi_state_free(struct http_ssi_state *ssi) +{ + if (ssi != NULL) { +#if HTTPD_USE_MEM_POOL + memp_free(MEMP_HTTPD_SSI_STATE, ssi); +#else /* HTTPD_USE_MEM_POOL */ + mem_free(ssi); +#endif /* HTTPD_USE_MEM_POOL */ + } +} +#endif /* LWIP_HTTPD_SSI */ + +/** Initialize a struct http_state. + */ +static void +http_state_init(struct http_state* hs) +{ + /* Initialize the structure. */ + memset(hs, 0, sizeof(struct http_state)); +#if LWIP_HTTPD_DYNAMIC_HEADERS + /* Indicate that the headers are not yet valid */ + hs->hdr_index = NUM_FILE_HDR_STRINGS; +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ +} + +/** Allocate a struct http_state. */ +static struct http_state* +http_state_alloc(void) +{ + struct http_state *ret = HTTP_ALLOC_HTTP_STATE(); +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED + if (ret == NULL) { + http_kill_oldest_connection(0); + ret = HTTP_ALLOC_HTTP_STATE(); + } +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + if (ret != NULL) { + http_state_init(ret); +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED + /* add the connection to the list */ + if (http_connections == NULL) { + http_connections = ret; + } else { + struct http_state *last; + for(last = http_connections; last->next != NULL; last = last->next); + LWIP_ASSERT("last != NULL", last != NULL); + last->next = ret; + } +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ + } + return ret; +} + +/** Free a struct http_state. + * Also frees the file data if dynamic. + */ +static void +http_state_eof(struct http_state *hs) +{ + if(hs->handle) { +#if LWIP_HTTPD_TIMING + u32_t ms_needed = sys_now() - hs->time_started; + u32_t needed = LWIP_MAX(1, (ms_needed/100)); + LWIP_DEBUGF(HTTPD_DEBUG_TIMING, ("httpd: needed %"U32_F" ms to send file of %d bytes -> %"U32_F" bytes/sec\n", + ms_needed, hs->handle->len, ((((u32_t)hs->handle->len) * 10) / needed))); +#endif /* LWIP_HTTPD_TIMING */ + fs_close(hs->handle); + hs->handle = NULL; + } +#if LWIP_HTTPD_DYNAMIC_FILE_READ + if (hs->buf != NULL) { + mem_free(hs->buf); + hs->buf = NULL; + } +#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ +#if LWIP_HTTPD_SSI + if (hs->ssi) { + http_ssi_state_free(hs->ssi); + hs->ssi = NULL; + } +#endif /* LWIP_HTTPD_SSI */ +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + if (hs->req) { + pbuf_free(hs->req); + hs->req = NULL; + } +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ +} + +/** Free a struct http_state. + * Also frees the file data if dynamic. + */ +static void +http_state_free(struct http_state *hs) +{ + if (hs != NULL) { + http_state_eof(hs); +#if LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED + /* take the connection off the list */ + if (http_connections) { + if (http_connections == hs) { + http_connections = hs->next; + } else { + struct http_state *last; + for(last = http_connections; last->next != NULL; last = last->next) { + if (last->next == hs) { + last->next = hs->next; + break; + } + } + } + } +#endif /* LWIP_HTTPD_KILL_OLD_ON_CONNECTIONS_EXCEEDED */ +#if HTTPD_USE_MEM_POOL + memp_free(MEMP_HTTPD_STATE, hs); +#else /* HTTPD_USE_MEM_POOL */ + mem_free(hs); +#endif /* HTTPD_USE_MEM_POOL */ + } +} + +/** Call tcp_write() in a loop trying smaller and smaller length + * + * @param pcb tcp_pcb to send + * @param ptr Data to send + * @param length Length of data to send (in/out: on return, contains the + * amount of data sent) + * @param apiflags directly passed to tcp_write + * @return the return value of tcp_write + */ +static err_t +http_write(struct tcp_pcb *pcb, const void* ptr, u16_t *length, u8_t apiflags) +{ + u16_t len, max_len; + err_t err; + LWIP_ASSERT("length != NULL", length != NULL); + len = *length; + if (len == 0) { + return ERR_OK; + } + /* We cannot send more data than space available in the send buffer. */ + max_len = tcp_sndbuf(pcb); + if (max_len < len) { + len = max_len; + } +#ifdef HTTPD_MAX_WRITE_LEN + /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ + max_len = HTTPD_MAX_WRITE_LEN(pcb); + if(len > max_len) { + len = max_len; + } +#endif /* HTTPD_MAX_WRITE_LEN */ + do { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Trying go send %d bytes\n", len)); + err = tcp_write(pcb, ptr, len, apiflags); + if (err == ERR_MEM) { + if ((tcp_sndbuf(pcb) == 0) || + (tcp_sndqueuelen(pcb) >= TCP_SND_QUEUELEN)) { + /* no need to try smaller sizes */ + len = 1; + } else { + len /= 2; + } + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, + ("Send failed, trying less (%d bytes)\n", len)); + } + } while ((err == ERR_MEM) && (len > 1)); + + if (err == ERR_OK) { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Sent %d bytes\n", len)); + *length = len; + } else { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Send failed with err %d (\"%s\")\n", err, lwip_strerr(err))); + *length = 0; + } + + return err; +} + +/** + * The connection shall be actively closed (using RST to close from fault states). + * Reset the sent- and recv-callbacks. + * + * @param pcb the tcp pcb to reset callbacks + * @param hs connection state to free + */ +static err_t +http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn) +{ + err_t err; + LWIP_DEBUGF(HTTPD_DEBUG, ("Closing connection %p\n", (void*)pcb)); + +#if LWIP_HTTPD_SUPPORT_POST + if (hs != NULL) { + if ((hs->post_content_len_left != 0) +#if LWIP_HTTPD_POST_MANUAL_WND + || ((hs->no_auto_wnd != 0) && (hs->unrecved_bytes != 0)) +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + ) { + /* make sure the post code knows that the connection is closed */ + http_post_response_filename[0] = 0; + httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); + } + } +#endif /* LWIP_HTTPD_SUPPORT_POST*/ + + + tcp_arg(pcb, NULL); + tcp_recv(pcb, NULL); + tcp_err(pcb, NULL); + tcp_poll(pcb, NULL, 0); + tcp_sent(pcb, NULL); + if (hs != NULL) { + http_state_free(hs); + } + + if (abort_conn) { + tcp_abort(pcb); + return ERR_OK; + } + err = tcp_close(pcb); + if (err != ERR_OK) { + LWIP_DEBUGF(HTTPD_DEBUG, ("Error %d closing %p\n", err, (void*)pcb)); + /* error closing, try again later in poll */ + tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); + } + return err; +} + +/** + * The connection shall be actively closed. + * Reset the sent- and recv-callbacks. + * + * @param pcb the tcp pcb to reset callbacks + * @param hs connection state to free + */ +static err_t +http_close_conn(struct tcp_pcb *pcb, struct http_state *hs) +{ + return http_close_or_abort_conn(pcb, hs, 0); +} + +/** End of file: either close the connection (Connection: close) or + * close the file (Connection: keep-alive) + */ +static void +http_eof(struct tcp_pcb *pcb, struct http_state *hs) +{ + /* HTTP/1.1 persistent connection? (Not supported for SSI) */ +#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE + if (hs->keepalive && !LWIP_HTTPD_IS_SSI(hs)) { + http_state_eof(hs); + http_state_init(hs); + hs->keepalive = 1; + } else +#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ + { + http_close_conn(pcb, hs); + } +} + +#if LWIP_HTTPD_CGI +/** + * Extract URI parameters from the parameter-part of an URI in the form + * "test.cgi?x=y" @todo: better explanation! + * Pointers to the parameters are stored in hs->param_vals. + * + * @param hs http connection state + * @param params pointer to the NULL-terminated parameter string from the URI + * @return number of parameters extracted + */ +static int +extract_uri_parameters(struct http_state *hs, char *params) +{ + char *pair; + char *equals; + int loop; + + /* If we have no parameters at all, return immediately. */ + if(!params || (params[0] == '\0')) { + return(0); + } + + /* Get a pointer to our first parameter */ + pair = params; + + /* Parse up to LWIP_HTTPD_MAX_CGI_PARAMETERS from the passed string and ignore the + * remainder (if any) */ + for(loop = 0; (loop < LWIP_HTTPD_MAX_CGI_PARAMETERS) && pair; loop++) { + + /* Save the name of the parameter */ + hs->params[loop] = pair; + + /* Remember the start of this name=value pair */ + equals = pair; + + /* Find the start of the next name=value pair and replace the delimiter + * with a 0 to terminate the previous pair string. */ + pair = strchr(pair, '&'); + if(pair) { + *pair = '\0'; + pair++; + } else { + /* We didn't find a new parameter so find the end of the URI and + * replace the space with a '\0' */ + pair = strchr(equals, ' '); + if(pair) { + *pair = '\0'; + } + + /* Revert to NULL so that we exit the loop as expected. */ + pair = NULL; + } + + /* Now find the '=' in the previous pair, replace it with '\0' and save + * the parameter value string. */ + equals = strchr(equals, '='); + if(equals) { + *equals = '\0'; + hs->param_vals[loop] = equals + 1; + } else { + hs->param_vals[loop] = NULL; + } + } + + return loop; +} +#endif /* LWIP_HTTPD_CGI */ + +#if LWIP_HTTPD_SSI +/** + * Insert a tag (found in an shtml in the form of "" into the file. + * The tag's name is stored in ssi->tag_name (NULL-terminated), the replacement + * should be written to hs->tag_insert (up to a length of LWIP_HTTPD_MAX_TAG_INSERT_LEN). + * The amount of data written is stored to ssi->tag_insert_len. + * + * @todo: return tag_insert_len - maybe it can be removed from struct http_state? + * + * @param hs http connection state + */ +static void +get_tag_insert(struct http_state *hs) +{ + int loop; + size_t len; + struct http_ssi_state *ssi; + LWIP_ASSERT("hs != NULL", hs != NULL); + ssi = hs->ssi; + LWIP_ASSERT("ssi != NULL", ssi != NULL); +#if LWIP_HTTPD_SSI_MULTIPART + u16_t current_tag_part = ssi->tag_part; + ssi->tag_part = HTTPD_LAST_TAG_PART; +#endif /* LWIP_HTTPD_SSI_MULTIPART */ + + if(g_pfnSSIHandler && g_ppcTags && g_iNumTags) { + + /* Find this tag in the list we have been provided. */ + for(loop = 0; loop < g_iNumTags; loop++) { + if(strcmp(ssi->tag_name, g_ppcTags[loop]) == 0) { + ssi->tag_insert_len = g_pfnSSIHandler(loop, ssi->tag_insert, + LWIP_HTTPD_MAX_TAG_INSERT_LEN +#if LWIP_HTTPD_SSI_MULTIPART + , current_tag_part, &ssi->tag_part +#endif /* LWIP_HTTPD_SSI_MULTIPART */ +#if LWIP_HTTPD_FILE_STATE + , hs->handle->state +#endif /* LWIP_HTTPD_FILE_STATE */ + ); + return; + } + } + } + + /* If we drop out, we were asked to serve a page which contains tags that + * we don't have a handler for. Merely echo back the tags with an error + * marker. */ +#define UNKNOWN_TAG1_TEXT "***UNKNOWN TAG " +#define UNKNOWN_TAG1_LEN 18 +#define UNKNOWN_TAG2_TEXT "***" +#define UNKNOWN_TAG2_LEN 7 + len = LWIP_MIN(sizeof(ssi->tag_name), LWIP_MIN(strlen(ssi->tag_name), + LWIP_HTTPD_MAX_TAG_INSERT_LEN - (UNKNOWN_TAG1_LEN + UNKNOWN_TAG2_LEN))); + MEMCPY(ssi->tag_insert, UNKNOWN_TAG1_TEXT, UNKNOWN_TAG1_LEN); + MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN], ssi->tag_name, len); + MEMCPY(&ssi->tag_insert[UNKNOWN_TAG1_LEN + len], UNKNOWN_TAG2_TEXT, UNKNOWN_TAG2_LEN); + ssi->tag_insert[UNKNOWN_TAG1_LEN + len + UNKNOWN_TAG2_LEN] = 0; + + len = strlen(ssi->tag_insert); + LWIP_ASSERT("len <= 0xffff", len <= 0xffff); + ssi->tag_insert_len = (u16_t)len; +} +#endif /* LWIP_HTTPD_SSI */ + +#if LWIP_HTTPD_DYNAMIC_HEADERS +/** + * Generate the relevant HTTP headers for the given filename and write + * them into the supplied buffer. + */ +static void +get_http_headers(struct http_state *pState, char *pszURI) +{ + unsigned int iLoop; + char *pszWork; + char *pszExt; + char *pszVars; + + /* Ensure that we initialize the loop counter. */ + iLoop = 0; + + /* In all cases, the second header we send is the server identification + so set it here. */ + pState->hdrs[1] = g_psHTTPHeaderStrings[HTTP_HDR_SERVER]; + + /* Is this a normal file or the special case we use to send back the + default "404: Page not found" response? */ + if (pszURI == NULL) { + pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; + pState->hdrs[2] = g_psHTTPHeaderStrings[DEFAULT_404_HTML]; + + /* Set up to send the first header string. */ + pState->hdr_index = 0; + pState->hdr_pos = 0; + return; + } else { + /* We are dealing with a particular filename. Look for one other + special case. We assume that any filename with "404" in it must be + indicative of a 404 server error whereas all other files require + the 200 OK header. */ + if (strstr(pszURI, "404")) { + pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_FOUND]; + } else if (strstr(pszURI, "400")) { + pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_BAD_REQUEST]; + } else if (strstr(pszURI, "501")) { + pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_NOT_IMPL]; + } else { + pState->hdrs[0] = g_psHTTPHeaderStrings[HTTP_HDR_OK]; + } + + /* Determine if the URI has any variables and, if so, temporarily remove + them. */ + pszVars = strchr(pszURI, '?'); + if(pszVars) { + *pszVars = '\0'; + } + + /* Get a pointer to the file extension. We find this by looking for the + last occurrence of "." in the filename passed. */ + pszExt = NULL; + pszWork = strchr(pszURI, '.'); + while(pszWork) { + pszExt = pszWork + 1; + pszWork = strchr(pszExt, '.'); + } + + /* Now determine the content type and add the relevant header for that. */ + for(iLoop = 0; (iLoop < NUM_HTTP_HEADERS) && pszExt; iLoop++) { + /* Have we found a matching extension? */ + if(!strcmp(g_psHTTPHeaders[iLoop].extension, pszExt)) { + pState->hdrs[2] = g_psHTTPHeaders[iLoop].content_type; + break; + } + } + + /* Reinstate the parameter marker if there was one in the original URI. */ + if(pszVars) { + *pszVars = '?'; + } + } + + /* Does the URL passed have any file extension? If not, we assume it + is a special-case URL used for control state notification and we do + not send any HTTP headers with the response. */ + if(!pszExt) { + /* Force the header index to a value indicating that all headers + have already been sent. */ + pState->hdr_index = NUM_FILE_HDR_STRINGS; + } else { + /* Did we find a matching extension? */ + if(iLoop == NUM_HTTP_HEADERS) { + /* No - use the default, plain text file type. */ + pState->hdrs[2] = HTTP_HDR_DEFAULT_TYPE; + } + + /* Set up to send the first header string. */ + pState->hdr_index = 0; + pState->hdr_pos = 0; + } +} + +/** Sub-function of http_send(): send dynamic headers + * + * @returns: - HTTP_NO_DATA_TO_SEND: no new data has been enqueued + * - HTTP_DATA_TO_SEND_CONTINUE: continue with sending HTTP body + * - HTTP_DATA_TO_SEND_BREAK: data has been enqueued, headers pending, + * so don't send HTTP body yet + */ +static u8_t +http_send_headers(struct tcp_pcb *pcb, struct http_state *hs) +{ + err_t err; + u16_t len; + u8_t data_to_send = HTTP_NO_DATA_TO_SEND; + u16_t hdrlen, sendlen; + + /* How much data can we send? */ + len = tcp_sndbuf(pcb); + sendlen = len; + + while(len && (hs->hdr_index < NUM_FILE_HDR_STRINGS) && sendlen) { + const void *ptr; + u16_t old_sendlen; + u8_t apiflags; + /* How much do we have to send from the current header? */ + hdrlen = (u16_t)strlen(hs->hdrs[hs->hdr_index]); + + /* How much of this can we send? */ + sendlen = (len < (hdrlen - hs->hdr_pos)) ? len : (hdrlen - hs->hdr_pos); + + /* Send this amount of data or as much as we can given memory + * constraints. */ + ptr = (const void *)(hs->hdrs[hs->hdr_index] + hs->hdr_pos); + old_sendlen = sendlen; + apiflags = HTTP_IS_HDR_VOLATILE(hs, ptr); + if (hs->hdr_index < NUM_FILE_HDR_STRINGS - 1) { + apiflags |= TCP_WRITE_FLAG_MORE; + } + err = http_write(pcb, ptr, &sendlen, apiflags); + if ((err == ERR_OK) && (old_sendlen != sendlen)) { + /* Remember that we added some more data to be transmitted. */ + data_to_send = HTTP_DATA_TO_SEND_CONTINUE; + } else if (err != ERR_OK) { + /* special case: http_write does not try to send 1 byte */ + sendlen = 0; + } + + /* Fix up the header position for the next time round. */ + hs->hdr_pos += sendlen; + len -= sendlen; + + /* Have we finished sending this string? */ + if(hs->hdr_pos == hdrlen) { + /* Yes - move on to the next one */ + hs->hdr_index++; + hs->hdr_pos = 0; + } + } + + if ((hs->hdr_index >= NUM_FILE_HDR_STRINGS) && (hs->file == NULL)) { + /* When we are at the end of the headers, check for data to send + * instead of waiting for ACK from remote side to continue + * (which would happen when sending files from async read). */ + http_check_eof(pcb, hs); + } + /* If we get here and there are still header bytes to send, we send + * the header information we just wrote immediately. If there are no + * more headers to send, but we do have file data to send, drop through + * to try to send some file data too. */ + if((hs->hdr_index < NUM_FILE_HDR_STRINGS) || !hs->file) { + LWIP_DEBUGF(HTTPD_DEBUG, ("tcp_output\n")); + return HTTP_DATA_TO_SEND_BREAK; + } + return data_to_send; +} +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ + +/** Sub-function of http_send(): end-of-file (or block) is reached, + * either close the file or read the next block (if supported). + * + * @returns: 0 if the file is finished or no data has been read + * 1 if the file is not finished and data has been read + */ +static u8_t +http_check_eof(struct tcp_pcb *pcb, struct http_state *hs) +{ + int bytes_left; +#if LWIP_HTTPD_DYNAMIC_FILE_READ + int count; +#ifdef HTTPD_MAX_WRITE_LEN + int max_write_len; +#endif /* HTTPD_MAX_WRITE_LEN */ +#endif /* LWIP_HTTPD_DYNAMIC_FILE_READ */ + + /* Do we have a valid file handle? */ + if (hs->handle == NULL) { + /* No - close the connection. */ + http_eof(pcb, hs); + return 0; + } + bytes_left = fs_bytes_left(hs->handle); + if (bytes_left <= 0) { + /* We reached the end of the file so this request is done. */ + LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); + http_eof(pcb, hs); + return 0; + } +#if LWIP_HTTPD_DYNAMIC_FILE_READ + /* Do we already have a send buffer allocated? */ + if(hs->buf) { + /* Yes - get the length of the buffer */ + count = hs->buf_len; + } else { + /* We don't have a send buffer so allocate one now */ + count = tcp_sndbuf(pcb); + if(bytes_left < count) { + count = bytes_left; + } +#ifdef HTTPD_MAX_WRITE_LEN + /* Additional limitation: e.g. don't enqueue more than 2*mss at once */ + max_write_len = HTTPD_MAX_WRITE_LEN(pcb); + if (count > max_write_len) { + count = max_write_len; + } +#endif /* HTTPD_MAX_WRITE_LEN */ + do { + hs->buf = (char*)mem_malloc((mem_size_t)count); + if (hs->buf != NULL) { + hs->buf_len = count; + break; + } + count = count / 2; + } while (count > 100); + + /* Did we get a send buffer? If not, return immediately. */ + if (hs->buf == NULL) { + LWIP_DEBUGF(HTTPD_DEBUG, ("No buff\n")); + return 0; + } + } + + /* Read a block of data from the file. */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Trying to read %d bytes.\n", count)); + +#if LWIP_HTTPD_FS_ASYNC_READ + count = fs_read_async(hs->handle, hs->buf, count, http_continue, hs); +#else /* LWIP_HTTPD_FS_ASYNC_READ */ + count = fs_read(hs->handle, hs->buf, count); +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + if (count < 0) { + if (count == FS_READ_DELAYED) { + /* Delayed read, wait for FS to unblock us */ + return 0; + } + /* We reached the end of the file so this request is done. + * @todo: don't close here for HTTP/1.1? */ + LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); + http_eof(pcb, hs); + return 0; + } + + /* Set up to send the block of data we just read */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Read %d bytes.\n", count)); + hs->left = count; + hs->file = hs->buf; +#if LWIP_HTTPD_SSI + if (hs->ssi) { + hs->ssi->parse_left = count; + hs->ssi->parsed = hs->buf; + } +#endif /* LWIP_HTTPD_SSI */ +#else /* LWIP_HTTPD_DYNAMIC_FILE_READ */ + LWIP_ASSERT("SSI and DYNAMIC_HEADERS turned off but eof not reached", 0); +#endif /* LWIP_HTTPD_SSI || LWIP_HTTPD_DYNAMIC_HEADERS */ + return 1; +} + +/** Sub-function of http_send(): This is the normal send-routine for non-ssi files + * + * @returns: - 1: data has been written (so call tcp_ouput) + * - 0: no data has been written (no need to call tcp_output) + */ +static u8_t +http_send_data_nonssi(struct tcp_pcb *pcb, struct http_state *hs) +{ + err_t err; + u16_t len; + u8_t data_to_send = 0; + + /* We are not processing an SHTML file so no tag checking is necessary. + * Just send the data as we received it from the file. */ + len = (u16_t)LWIP_MIN(hs->left, 0xffff); + + err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); + if (err == ERR_OK) { + data_to_send = 1; + hs->file += len; + hs->left -= len; + } + + return data_to_send; +} + +#if LWIP_HTTPD_SSI +/** Sub-function of http_send(): This is the send-routine for ssi files + * + * @returns: - 1: data has been written (so call tcp_ouput) + * - 0: no data has been written (no need to call tcp_output) + */ +static u8_t +http_send_data_ssi(struct tcp_pcb *pcb, struct http_state *hs) +{ + err_t err = ERR_OK; + u16_t len; + u8_t data_to_send = 0; + + struct http_ssi_state *ssi = hs->ssi; + LWIP_ASSERT("ssi != NULL", ssi != NULL); + /* We are processing an SHTML file so need to scan for tags and replace + * them with insert strings. We need to be careful here since a tag may + * straddle the boundary of two blocks read from the file and we may also + * have to split the insert string between two tcp_write operations. */ + + /* How much data could we send? */ + len = tcp_sndbuf(pcb); + + /* Do we have remaining data to send before parsing more? */ + if(ssi->parsed > hs->file) { + len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); + + err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); + if (err == ERR_OK) { + data_to_send = 1; + hs->file += len; + hs->left -= len; + } + + /* If the send buffer is full, return now. */ + if(tcp_sndbuf(pcb) == 0) { + return data_to_send; + } + } + + LWIP_DEBUGF(HTTPD_DEBUG, ("State %d, %d left\n", ssi->tag_state, (int)ssi->parse_left)); + + /* We have sent all the data that was already parsed so continue parsing + * the buffer contents looking for SSI tags. */ + while((ssi->parse_left) && (err == ERR_OK)) { + if (len == 0) { + return data_to_send; + } + switch(ssi->tag_state) { + case TAG_NONE: + /* We are not currently processing an SSI tag so scan for the + * start of the lead-in marker. */ + if(*ssi->parsed == g_pcTagLeadIn[0]) { + /* We found what could be the lead-in for a new tag so change + * state appropriately. */ + ssi->tag_state = TAG_LEADIN; + ssi->tag_index = 1; +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + ssi->tag_started = ssi->parsed; +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG */ + } + + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + break; + + case TAG_LEADIN: + /* We are processing the lead-in marker, looking for the start of + * the tag name. */ + + /* Have we reached the end of the leadin? */ + if(ssi->tag_index == LEN_TAG_LEAD_IN) { + ssi->tag_index = 0; + ssi->tag_state = TAG_FOUND; + } else { + /* Have we found the next character we expect for the tag leadin? */ + if(*ssi->parsed == g_pcTagLeadIn[ssi->tag_index]) { + /* Yes - move to the next one unless we have found the complete + * leadin, in which case we start looking for the tag itself */ + ssi->tag_index++; + } else { + /* We found an unexpected character so this is not a tag. Move + * back to idle state. */ + ssi->tag_state = TAG_NONE; + } + + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + } + break; + + case TAG_FOUND: + /* We are reading the tag name, looking for the start of the + * lead-out marker and removing any whitespace found. */ + + /* Remove leading whitespace between the tag leading and the first + * tag name character. */ + if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || + (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || + (*ssi->parsed == '\r'))) { + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + break; + } + + /* Have we found the end of the tag name? This is signalled by + * us finding the first leadout character or whitespace */ + if((*ssi->parsed == g_pcTagLeadOut[0]) || + (*ssi->parsed == ' ') || (*ssi->parsed == '\t') || + (*ssi->parsed == '\n') || (*ssi->parsed == '\r')) { + + if(ssi->tag_index == 0) { + /* We read a zero length tag so ignore it. */ + ssi->tag_state = TAG_NONE; + } else { + /* We read a non-empty tag so go ahead and look for the + * leadout string. */ + ssi->tag_state = TAG_LEADOUT; + LWIP_ASSERT("ssi->tag_index <= 0xff", ssi->tag_index <= 0xff); + ssi->tag_name_len = (u8_t)ssi->tag_index; + ssi->tag_name[ssi->tag_index] = '\0'; + if(*ssi->parsed == g_pcTagLeadOut[0]) { + ssi->tag_index = 1; + } else { + ssi->tag_index = 0; + } + } + } else { + /* This character is part of the tag name so save it */ + if(ssi->tag_index < LWIP_HTTPD_MAX_TAG_NAME_LEN) { + ssi->tag_name[ssi->tag_index++] = *ssi->parsed; + } else { + /* The tag was too long so ignore it. */ + ssi->tag_state = TAG_NONE; + } + } + + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + + break; + + /* We are looking for the end of the lead-out marker. */ + case TAG_LEADOUT: + /* Remove leading whitespace between the tag leading and the first + * tag leadout character. */ + if((ssi->tag_index == 0) && ((*ssi->parsed == ' ') || + (*ssi->parsed == '\t') || (*ssi->parsed == '\n') || + (*ssi->parsed == '\r'))) { + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + break; + } + + /* Have we found the next character we expect for the tag leadout? */ + if(*ssi->parsed == g_pcTagLeadOut[ssi->tag_index]) { + /* Yes - move to the next one unless we have found the complete + * leadout, in which case we need to call the client to process + * the tag. */ + + /* Move on to the next character in the buffer */ + ssi->parse_left--; + ssi->parsed++; + + if(ssi->tag_index == (LEN_TAG_LEAD_OUT - 1)) { + /* Call the client to ask for the insert string for the + * tag we just found. */ +#if LWIP_HTTPD_SSI_MULTIPART + ssi->tag_part = 0; /* start with tag part 0 */ +#endif /* LWIP_HTTPD_SSI_MULTIPART */ + get_tag_insert(hs); + + /* Next time through, we are going to be sending data + * immediately, either the end of the block we start + * sending here or the insert string. */ + ssi->tag_index = 0; + ssi->tag_state = TAG_SENDING; + ssi->tag_end = ssi->parsed; +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + ssi->parsed = ssi->tag_started; +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ + + /* If there is any unsent data in the buffer prior to the + * tag, we need to send it now. */ + if (ssi->tag_end > hs->file) { + /* How much of the data can we send? */ +#if LWIP_HTTPD_SSI_INCLUDE_TAG + len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); +#else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ + /* we would include the tag in sending */ + len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); +#endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ + + err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); + if (err == ERR_OK) { + data_to_send = 1; +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + if(ssi->tag_started <= hs->file) { + /* pretend to have sent the tag, too */ + len += ssi->tag_end - ssi->tag_started; + } +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ + hs->file += len; + hs->left -= len; + } + } + } else { + ssi->tag_index++; + } + } else { + /* We found an unexpected character so this is not a tag. Move + * back to idle state. */ + ssi->parse_left--; + ssi->parsed++; + ssi->tag_state = TAG_NONE; + } + break; + + /* + * We have found a valid tag and are in the process of sending + * data as a result of that discovery. We send either remaining data + * from the file prior to the insert point or the insert string itself. + */ + case TAG_SENDING: + /* Do we have any remaining file data to send from the buffer prior + * to the tag? */ + if(ssi->tag_end > hs->file) { + /* How much of the data can we send? */ +#if LWIP_HTTPD_SSI_INCLUDE_TAG + len = (u16_t)LWIP_MIN(ssi->tag_end - hs->file, 0xffff); +#else /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ + LWIP_ASSERT("hs->started >= hs->file", ssi->tag_started >= hs->file); + /* we would include the tag in sending */ + len = (u16_t)LWIP_MIN(ssi->tag_started - hs->file, 0xffff); +#endif /* LWIP_HTTPD_SSI_INCLUDE_TAG*/ + if (len != 0) { + err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); + } else { + err = ERR_OK; + } + if (err == ERR_OK) { + data_to_send = 1; +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + if(ssi->tag_started <= hs->file) { + /* pretend to have sent the tag, too */ + len += ssi->tag_end - ssi->tag_started; + } +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ + hs->file += len; + hs->left -= len; + } + } else { +#if LWIP_HTTPD_SSI_MULTIPART + if(ssi->tag_index >= ssi->tag_insert_len) { + /* Did the last SSIHandler have more to send? */ + if (ssi->tag_part != HTTPD_LAST_TAG_PART) { + /* If so, call it again */ + ssi->tag_index = 0; + get_tag_insert(hs); + } + } +#endif /* LWIP_HTTPD_SSI_MULTIPART */ + + /* Do we still have insert data left to send? */ + if(ssi->tag_index < ssi->tag_insert_len) { + /* We are sending the insert string itself. How much of the + * insert can we send? */ + len = (ssi->tag_insert_len - ssi->tag_index); + + /* Note that we set the copy flag here since we only have a + * single tag insert buffer per connection. If we don't do + * this, insert corruption can occur if more than one insert + * is processed before we call tcp_output. */ + err = http_write(pcb, &(ssi->tag_insert[ssi->tag_index]), &len, + HTTP_IS_TAG_VOLATILE(hs)); + if (err == ERR_OK) { + data_to_send = 1; + ssi->tag_index += len; + /* Don't return here: keep on sending data */ + } + } else { +#if LWIP_HTTPD_SSI_MULTIPART + if (ssi->tag_part == HTTPD_LAST_TAG_PART) +#endif /* LWIP_HTTPD_SSI_MULTIPART */ + { + /* We have sent all the insert data so go back to looking for + * a new tag. */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Everything sent.\n")); + ssi->tag_index = 0; + ssi->tag_state = TAG_NONE; +#if !LWIP_HTTPD_SSI_INCLUDE_TAG + ssi->parsed = ssi->tag_end; +#endif /* !LWIP_HTTPD_SSI_INCLUDE_TAG*/ + } + } + break; + } + } + } + + /* If we drop out of the end of the for loop, this implies we must have + * file data to send so send it now. In TAG_SENDING state, we've already + * handled this so skip the send if that's the case. */ + if((ssi->tag_state != TAG_SENDING) && (ssi->parsed > hs->file)) { + len = (u16_t)LWIP_MIN(ssi->parsed - hs->file, 0xffff); + + err = http_write(pcb, hs->file, &len, HTTP_IS_DATA_VOLATILE(hs)); + if (err == ERR_OK) { + data_to_send = 1; + hs->file += len; + hs->left -= len; + } + } + return data_to_send; +} +#endif /* LWIP_HTTPD_SSI */ + +/** + * Try to send more data on this pcb. + * + * @param pcb the pcb to send data + * @param hs connection state + */ +static u8_t +http_send(struct tcp_pcb *pcb, struct http_state *hs) +{ + u8_t data_to_send = HTTP_NO_DATA_TO_SEND; + + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_send: pcb=%p hs=%p left=%d\n", (void*)pcb, + (void*)hs, hs != NULL ? (int)hs->left : 0)); + +#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND + if (hs->unrecved_bytes != 0) { + return 0; + } +#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ + + /* If we were passed a NULL state structure pointer, ignore the call. */ + if (hs == NULL) { + return 0; + } + +#if LWIP_HTTPD_FS_ASYNC_READ + /* Check if we are allowed to read from this file. + (e.g. SSI might want to delay sending until data is available) */ + if (!fs_is_file_ready(hs->handle, http_continue, hs)) { + return 0; + } +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + +#if LWIP_HTTPD_DYNAMIC_HEADERS + /* Do we have any more header data to send for this file? */ + if(hs->hdr_index < NUM_FILE_HDR_STRINGS) { + data_to_send = http_send_headers(pcb, hs); + if (data_to_send != HTTP_DATA_TO_SEND_CONTINUE) { + return data_to_send; + } + } +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ + + /* Have we run out of file data to send? If so, we need to read the next + * block from the file. */ + if (hs->left == 0) { + if (!http_check_eof(pcb, hs)) { + return 0; + } + } + +#if LWIP_HTTPD_SSI + if(hs->ssi) { + data_to_send = http_send_data_ssi(pcb, hs); + } else +#endif /* LWIP_HTTPD_SSI */ + { + data_to_send = http_send_data_nonssi(pcb, hs); + } + + if((hs->left == 0) && (fs_bytes_left(hs->handle) <= 0)) { + /* We reached the end of the file so this request is done. + * This adds the FIN flag right into the last data segment. */ + LWIP_DEBUGF(HTTPD_DEBUG, ("End of file.\n")); + http_eof(pcb, hs); + return 0; + } + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("send_data end.\n")); + return data_to_send; +} + +#if LWIP_HTTPD_SUPPORT_EXTSTATUS +/** Initialize a http connection with a file to send for an error message + * + * @param hs http connection state + * @param error_nr HTTP error number + * @return ERR_OK if file was found and hs has been initialized correctly + * another err_t otherwise + */ +static err_t +http_find_error_file(struct http_state *hs, u16_t error_nr) +{ + const char *uri1, *uri2, *uri3; + err_t err; + + if (error_nr == 501) { + uri1 = "/501.html"; + uri2 = "/501.htm"; + uri3 = "/501.shtml"; + } else { + /* 400 (bad request is the default) */ + uri1 = "/400.html"; + uri2 = "/400.htm"; + uri3 = "/400.shtml"; + } + err = fs_open(&hs->file_handle, uri1); + if (err != ERR_OK) { + err = fs_open(&hs->file_handle, uri2); + if (err != ERR_OK) { + err = fs_open(&hs->file_handle, uri3); + if (err != ERR_OK) { + LWIP_DEBUGF(HTTPD_DEBUG, ("Error page for error %"U16_F" not found\n", + error_nr)); + return ERR_ARG; + } + } + } + return http_init_file(hs, &hs->file_handle, 0, NULL, 0); +} +#else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ +#define http_find_error_file(hs, error_nr) ERR_ARG +#endif /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ + +/** + * Get the file struct for a 404 error page. + * Tries some file names and returns NULL if none found. + * + * @param uri pointer that receives the actual file name URI + * @return file struct for the error page or NULL no matching file was found + */ +static struct fs_file * +http_get_404_file(struct http_state *hs, const char **uri) +{ + err_t err; + + *uri = "/404.html"; + err = fs_open(&hs->file_handle, *uri); + if (err != ERR_OK) { + /* 404.html doesn't exist. Try 404.htm instead. */ + *uri = "/404.htm"; + err = fs_open(&hs->file_handle, *uri); + if (err != ERR_OK) { + /* 404.htm doesn't exist either. Try 404.shtml instead. */ + *uri = "/404.shtml"; + err = fs_open(&hs->file_handle, *uri); + if (err != ERR_OK) { + /* 404.htm doesn't exist either. Indicate to the caller that it should + * send back a default 404 page. + */ + *uri = NULL; + return NULL; + } + } + } + + return &hs->file_handle; +} + +#if LWIP_HTTPD_SUPPORT_POST +static err_t +http_handle_post_finished(struct http_state *hs) +{ +#if LWIP_HTTPD_POST_MANUAL_WND + /* Prevent multiple calls to httpd_post_finished, since it might have already + been called before from httpd_post_data_recved(). */ + if (hs->post_finished) { + return ERR_OK; + } + hs->post_finished = 1; +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + /* application error or POST finished */ + /* NULL-terminate the buffer */ + http_post_response_filename[0] = 0; + httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); + return http_find_file(hs, http_post_response_filename, 0); +} + +/** Pass received POST body data to the application and correctly handle + * returning a response document or closing the connection. + * ATTENTION: The application is responsible for the pbuf now, so don't free it! + * + * @param hs http connection state + * @param p pbuf to pass to the application + * @return ERR_OK if passed successfully, another err_t if the response file + * hasn't been found (after POST finished) + */ +static err_t +http_post_rxpbuf(struct http_state *hs, struct pbuf *p) +{ + err_t err; + + /* adjust remaining Content-Length */ + if (hs->post_content_len_left < p->tot_len) { + hs->post_content_len_left = 0; + } else { + hs->post_content_len_left -= p->tot_len; + } + err = httpd_post_receive_data(hs, p); + if (err != ERR_OK) { + /* Ignore remaining content in case of application error */ + hs->post_content_len_left = 0; + } + if (hs->post_content_len_left == 0) { +#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND + if (hs->unrecved_bytes != 0) { + return ERR_OK; + } +#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ + /* application error or POST finished */ + return http_handle_post_finished(hs); + } + + return ERR_OK; +} + +/** Handle a post request. Called from http_parse_request when method 'POST' + * is found. + * + * @param p The input pbuf (containing the POST header and body). + * @param hs The http connection state. + * @param data HTTP request (header and part of body) from input pbuf(s). + * @param data_len Size of 'data'. + * @param uri The HTTP URI parsed from input pbuf(s). + * @param uri_end Pointer to the end of 'uri' (here, the rest of the HTTP + * header starts). + * @return ERR_OK: POST correctly parsed and accepted by the application. + * ERR_INPROGRESS: POST not completely parsed (no error yet) + * another err_t: Error parsing POST or denied by the application + */ +static err_t +http_post_request(struct pbuf *inp, struct http_state *hs, + char *data, u16_t data_len, char *uri, char *uri_end) +{ + err_t err; + /* search for end-of-header (first double-CRLF) */ + char* crlfcrlf = strnstr(uri_end + 1, CRLF CRLF, data_len - (uri_end + 1 - data)); + + if (crlfcrlf != NULL) { + /* search for "Content-Length: " */ +#define HTTP_HDR_CONTENT_LEN "Content-Length: " +#define HTTP_HDR_CONTENT_LEN_LEN 16 +#define HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN 10 + char *scontent_len = strnstr(uri_end + 1, HTTP_HDR_CONTENT_LEN, crlfcrlf - (uri_end + 1)); + if (scontent_len != NULL) { + char *scontent_len_end = strnstr(scontent_len + HTTP_HDR_CONTENT_LEN_LEN, CRLF, HTTP_HDR_CONTENT_LEN_DIGIT_MAX_LEN); + if (scontent_len_end != NULL) { + int content_len; + char *conten_len_num = scontent_len + HTTP_HDR_CONTENT_LEN_LEN; + content_len = atoi(conten_len_num); + if (content_len > 0) { + /* adjust length of HTTP header passed to application */ + const char *hdr_start_after_uri = uri_end + 1; + u16_t hdr_len = LWIP_MIN(data_len, crlfcrlf + 4 - data); + u16_t hdr_data_len = LWIP_MIN(data_len, crlfcrlf + 4 - hdr_start_after_uri); + u8_t post_auto_wnd = 1; + http_post_response_filename[0] = 0; + err = httpd_post_begin(hs, uri, hdr_start_after_uri, hdr_data_len, content_len, + http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN, &post_auto_wnd); + if (err == ERR_OK) { + /* try to pass in data of the first pbuf(s) */ + struct pbuf *q = inp; + u16_t start_offset = hdr_len; +#if LWIP_HTTPD_POST_MANUAL_WND + hs->no_auto_wnd = !post_auto_wnd; +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + /* set the Content-Length to be received for this POST */ + hs->post_content_len_left = (u32_t)content_len; + + /* get to the pbuf where the body starts */ + while((q != NULL) && (q->len <= start_offset)) { + start_offset -= q->len; + q = q->next; + } + if (q != NULL) { + /* hide the remaining HTTP header */ + pbuf_header(q, -(s16_t)start_offset); +#if LWIP_HTTPD_POST_MANUAL_WND + if (!post_auto_wnd) { + /* already tcp_recved() this data... */ + hs->unrecved_bytes = q->tot_len; + } +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + pbuf_ref(q); + return http_post_rxpbuf(hs, q); + } else { + return ERR_OK; + } + } else { + /* return file passed from application */ + return http_find_file(hs, http_post_response_filename, 0); + } + } else { + LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n", + conten_len_num)); + return ERR_ARG; + } + } + } + /* If we come here, headers are fully received (double-crlf), but Content-Length + was not included. Since this is currently the only supported method, we have + to fail in this case! */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Error when parsing Content-Length\n")); + return ERR_ARG; + } + /* if we come here, the POST is incomplete */ +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + return ERR_INPROGRESS; +#else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + return ERR_ARG; +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ +} + +#if LWIP_HTTPD_POST_MANUAL_WND +/** A POST implementation can call this function to update the TCP window. + * This can be used to throttle data reception (e.g. when received data is + * programmed to flash and data is received faster than programmed). + * + * @param connection A connection handle passed to httpd_post_begin for which + * httpd_post_finished has *NOT* been called yet! + * @param recved_len Length of data received (for window update) + */ +void httpd_post_data_recved(void *connection, u16_t recved_len) +{ + struct http_state *hs = (struct http_state*)connection; + if (hs != NULL) { + if (hs->no_auto_wnd) { + u16_t len = recved_len; + if (hs->unrecved_bytes >= recved_len) { + hs->unrecved_bytes -= recved_len; + } else { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("httpd_post_data_recved: recved_len too big\n")); + len = (u16_t)hs->unrecved_bytes; + hs->unrecved_bytes = 0; + } + if (hs->pcb != NULL) { + if (len != 0) { + tcp_recved(hs->pcb, len); + } + if ((hs->post_content_len_left == 0) && (hs->unrecved_bytes == 0)) { + /* finished handling POST */ + http_handle_post_finished(hs); + http_send(hs->pcb, hs); + } + } + } + } +} +#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + +#endif /* LWIP_HTTPD_SUPPORT_POST */ + +#if LWIP_HTTPD_FS_ASYNC_READ +/** Try to send more data if file has been blocked before + * This is a callback function passed to fs_read_async(). + */ +static void +http_continue(void *connection) +{ + struct http_state *hs = (struct http_state*)connection; + if (hs && (hs->pcb) && (hs->handle)) { + LWIP_ASSERT("hs->pcb != NULL", hs->pcb != NULL); + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("httpd_continue: try to send more data\n")); + if (http_send(hs->pcb, hs)) { + /* If we wrote anything to be sent, go ahead and send it now. */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); + tcp_output(hs->pcb); + } + } +} +#endif /* LWIP_HTTPD_FS_ASYNC_READ */ + +/** + * When data has been received in the correct state, try to parse it + * as a HTTP request. + * + * @param p the received pbuf + * @param hs the connection state + * @param pcb the tcp_pcb which received this packet + * @return ERR_OK if request was OK and hs has been initialized correctly + * ERR_INPROGRESS if request was OK so far but not fully received + * another err_t otherwise + */ +static err_t +http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) +{ + char *data; + char *crlf; + u16_t data_len; + struct pbuf *p = inp; +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + u16_t clen; +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ +#if LWIP_HTTPD_SUPPORT_POST + err_t err; +#endif /* LWIP_HTTPD_SUPPORT_POST */ + + LWIP_UNUSED_ARG(pcb); /* only used for post */ + LWIP_ASSERT("p != NULL", p != NULL); + LWIP_ASSERT("hs != NULL", hs != NULL); + + if ((hs->handle != NULL) || (hs->file != NULL)) { + LWIP_DEBUGF(HTTPD_DEBUG, ("Received data while sending a file\n")); + /* already sending a file */ + /* @todo: abort? */ + return ERR_USE; + } + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + + LWIP_DEBUGF(HTTPD_DEBUG, ("Received %"U16_F" bytes\n", p->tot_len)); + + /* first check allowed characters in this pbuf? */ + + /* enqueue the pbuf */ + if (hs->req == NULL) { + LWIP_DEBUGF(HTTPD_DEBUG, ("First pbuf\n")); + hs->req = p; + } else { + LWIP_DEBUGF(HTTPD_DEBUG, ("pbuf enqueued\n")); + pbuf_cat(hs->req, p); + } + /* increase pbuf ref counter as it is freed when we return but we want to + keep it on the req list */ + pbuf_ref(p); + + if (hs->req->next != NULL) { + data_len = LWIP_MIN(hs->req->tot_len, LWIP_HTTPD_MAX_REQ_LENGTH); + pbuf_copy_partial(hs->req, httpd_req_buf, data_len, 0); + data = httpd_req_buf; + } else +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + { + data = (char *)p->payload; + data_len = p->len; + if (p->len != p->tot_len) { + LWIP_DEBUGF(HTTPD_DEBUG, ("Warning: incomplete header due to chained pbufs\n")); + } + } + + /* received enough data for minimal request? */ + if (data_len >= MIN_REQ_LEN) { + /* wait for CRLF before parsing anything */ + crlf = strnstr(data, CRLF, data_len); + if (crlf != NULL) { +#if LWIP_HTTPD_SUPPORT_POST + int is_post = 0; +#endif /* LWIP_HTTPD_SUPPORT_POST */ + int is_09 = 0; + char *sp1, *sp2; + u16_t left_len, uri_len; + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n")); + /* parse method */ + if (!strncmp(data, "GET ", 4)) { + sp1 = data + 3; + /* received GET request */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n")); +#if LWIP_HTTPD_SUPPORT_POST + } else if (!strncmp(data, "POST ", 5)) { + /* store request type */ + is_post = 1; + sp1 = data + 4; + /* received GET request */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n")); +#endif /* LWIP_HTTPD_SUPPORT_POST */ + } else { + /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ + data[4] = 0; + /* unsupported method! */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n", + data)); + return http_find_error_file(hs, 501); + } + /* if we come here, method is OK, parse URI */ + left_len = data_len - ((sp1 +1) - data); + sp2 = strnstr(sp1 + 1, " ", left_len); +#if LWIP_HTTPD_SUPPORT_V09 + if (sp2 == NULL) { + /* HTTP 0.9: respond with correct protocol version */ + sp2 = strnstr(sp1 + 1, CRLF, left_len); + is_09 = 1; +#if LWIP_HTTPD_SUPPORT_POST + if (is_post) { + /* HTTP/0.9 does not support POST */ + goto badrequest; + } +#endif /* LWIP_HTTPD_SUPPORT_POST */ + } +#endif /* LWIP_HTTPD_SUPPORT_V09 */ + uri_len = sp2 - (sp1 + 1); + if ((sp2 != 0) && (sp2 > sp1)) { + /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */ + if (strnstr(data, CRLF CRLF, data_len) != NULL) { + char *uri = sp1 + 1; +#if LWIP_HTTPD_SUPPORT_11_KEEPALIVE + if (!is_09 && strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len)) { + hs->keepalive = 1; + } +#endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ + /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ + *sp1 = 0; + uri[uri_len] = 0; + LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n", + data, uri)); +#if LWIP_HTTPD_SUPPORT_POST + if (is_post) { +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + struct pbuf *q = hs->req; +#else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + struct pbuf *q = inp; +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + err = http_post_request(q, hs, data, data_len, uri, sp2); + if (err != ERR_OK) { + /* restore header for next try */ + *sp1 = ' '; + *sp2 = ' '; + uri[uri_len] = ' '; + } + if (err == ERR_ARG) { + goto badrequest; + } + return err; + } else +#endif /* LWIP_HTTPD_SUPPORT_POST */ + { + return http_find_file(hs, uri, is_09); + } + } + } else { + LWIP_DEBUGF(HTTPD_DEBUG, ("invalid URI\n")); + } + } + } + +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + clen = pbuf_clen(hs->req); + if ((hs->req->tot_len <= LWIP_HTTPD_REQ_BUFSIZE) && + (clen <= LWIP_HTTPD_REQ_QUEUELEN)) { + /* request not fully received (too short or CRLF is missing) */ + return ERR_INPROGRESS; + } else +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + { +#if LWIP_HTTPD_SUPPORT_POST +badrequest: +#endif /* LWIP_HTTPD_SUPPORT_POST */ + LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n")); + /* could not parse request */ + return http_find_error_file(hs, 400); + } +} + +/** Try to find the file specified by uri and, if found, initialize hs + * accordingly. + * + * @param hs the connection state + * @param uri the HTTP header URI + * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) + * @return ERR_OK if file was found and hs has been initialized correctly + * another err_t otherwise + */ +static err_t +http_find_file(struct http_state *hs, const char *uri, int is_09) +{ + size_t loop; + struct fs_file *file = NULL; + char *params; + err_t err; +#if LWIP_HTTPD_CGI + int i; + int count; +#endif /* LWIP_HTTPD_CGI */ +#if !LWIP_HTTPD_SSI + const +#endif /* !LWIP_HTTPD_SSI */ + /* By default, assume we will not be processing server-side-includes tags */ + u8_t tag_check = 0; + + /* Have we been asked for the default root file? */ + if((uri[0] == '/') && (uri[1] == 0)) { + /* Try each of the configured default filenames until we find one + that exists. */ + for (loop = 0; loop < NUM_DEFAULT_FILENAMES; loop++) { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Looking for %s...\n", g_psDefaultFilenames[loop].name)); + err = fs_open(&hs->file_handle, (char *)g_psDefaultFilenames[loop].name); + uri = (char *)g_psDefaultFilenames[loop].name; + if(err == ERR_OK) { + file = &hs->file_handle; + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opened.\n")); +#if LWIP_HTTPD_SSI + tag_check = g_psDefaultFilenames[loop].shtml; +#endif /* LWIP_HTTPD_SSI */ + break; + } + } + if (file == NULL) { + /* None of the default filenames exist so send back a 404 page */ + file = http_get_404_file(hs, &uri); +#if LWIP_HTTPD_SSI + tag_check = 0; +#endif /* LWIP_HTTPD_SSI */ + } + } else { + /* No - we've been asked for a specific file. */ + /* First, isolate the base URI (without any parameters) */ + params = (char *)strchr(uri, '?'); + if (params != NULL) { + /* URI contains parameters. NULL-terminate the base URI */ + *params = '\0'; + params++; + } + +#if LWIP_HTTPD_CGI + /* Does the base URI we have isolated correspond to a CGI handler? */ + if (g_iNumCGIs && g_pCGIs) { + for (i = 0; i < g_iNumCGIs; i++) { + if (strcmp(uri, g_pCGIs[i].pcCGIName) == 0) { + /* + * We found a CGI that handles this URI so extract the + * parameters and call the handler. + */ + count = extract_uri_parameters(hs, params); + uri = g_pCGIs[i].pfnCGIHandler(i, count, hs->params, + hs->param_vals); + break; + } + } + } +#endif /* LWIP_HTTPD_CGI */ + + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Opening %s\n", uri)); + + err = fs_open(&hs->file_handle, uri); + if (err == ERR_OK) { + file = &hs->file_handle; + } else { + file = http_get_404_file(hs, &uri); + } +#if LWIP_HTTPD_SSI + if (file != NULL) { + /* See if we have been asked for an shtml file and, if so, + enable tag checking. */ + tag_check = 0; + for (loop = 0; loop < NUM_SHTML_EXTENSIONS; loop++) { + if (strstr(uri, g_pcSSIExtensions[loop])) { + tag_check = 1; + break; + } + } + } +#endif /* LWIP_HTTPD_SSI */ + } + return http_init_file(hs, file, is_09, uri, tag_check); +} + +/** Initialize a http connection with a file to send (if found). + * Called by http_find_file and http_find_error_file. + * + * @param hs http connection state + * @param file file structure to send (or NULL if not found) + * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) + * @param uri the HTTP header URI + * @param tag_check enable SSI tag checking + * @return ERR_OK if file was found and hs has been initialized correctly + * another err_t otherwise + */ +static err_t +http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check) +{ + if (file != NULL) { + /* file opened, initialise struct http_state */ +#if LWIP_HTTPD_SSI + if (tag_check) { + struct http_ssi_state *ssi = http_ssi_state_alloc(); + if (ssi != NULL) { + ssi->tag_index = 0; + ssi->tag_state = TAG_NONE; + ssi->parsed = file->data; + ssi->parse_left = file->len; + ssi->tag_end = file->data; + hs->ssi = ssi; + } + } +#else /* LWIP_HTTPD_SSI */ + LWIP_UNUSED_ARG(tag_check); +#endif /* LWIP_HTTPD_SSI */ + hs->handle = file; + hs->file = (char*)file->data; + LWIP_ASSERT("File length must be positive!", (file->len >= 0)); + hs->left = file->len; + hs->retries = 0; +#if LWIP_HTTPD_TIMING + hs->time_started = sys_now(); +#endif /* LWIP_HTTPD_TIMING */ +#if !LWIP_HTTPD_DYNAMIC_HEADERS + LWIP_ASSERT("HTTP headers not included in file system", hs->handle->http_header_included); +#endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ +#if LWIP_HTTPD_SUPPORT_V09 + if (hs->handle->http_header_included && is_09) { + /* HTTP/0.9 responses are sent without HTTP header, + search for the end of the header. */ + char *file_start = strnstr(hs->file, CRLF CRLF, hs->left); + if (file_start != NULL) { + size_t diff = file_start + 4 - hs->file; + hs->file += diff; + hs->left -= (u32_t)diff; + } + } +#endif /* LWIP_HTTPD_SUPPORT_V09*/ + } else { + hs->handle = NULL; + hs->file = NULL; + hs->left = 0; + hs->retries = 0; + } +#if LWIP_HTTPD_DYNAMIC_HEADERS + /* Determine the HTTP headers to send based on the file extension of + * the requested URI. */ + if ((hs->handle == NULL) || !hs->handle->http_header_included) { + get_http_headers(hs, (char*)uri); + } +#else /* LWIP_HTTPD_DYNAMIC_HEADERS */ + LWIP_UNUSED_ARG(uri); +#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ + return ERR_OK; +} + +/** + * The pcb had an error and is already deallocated. + * The argument might still be valid (if != NULL). + */ +static void +http_err(void *arg, err_t err) +{ + struct http_state *hs = (struct http_state *)arg; + LWIP_UNUSED_ARG(err); + + LWIP_DEBUGF(HTTPD_DEBUG, ("http_err: %s", lwip_strerr(err))); + + if (hs != NULL) { + http_state_free(hs); + } +} + +/** + * Data has been sent and acknowledged by the remote host. + * This means that more data can be sent. + */ +static err_t +http_sent(void *arg, struct tcp_pcb *pcb, u16_t len) +{ + struct http_state *hs = (struct http_state *)arg; + + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_sent %p\n", (void*)pcb)); + + LWIP_UNUSED_ARG(len); + + if (hs == NULL) { + return ERR_OK; + } + + hs->retries = 0; + + http_send(pcb, hs); + + return ERR_OK; +} + +/** + * The poll function is called every 2nd second. + * If there has been no data sent (which resets the retries) in 8 seconds, close. + * If the last portion of a file has not been sent in 2 seconds, close. + * + * This could be increased, but we don't want to waste resources for bad connections. + */ +static err_t +http_poll(void *arg, struct tcp_pcb *pcb) +{ + struct http_state *hs = (struct http_state *)arg; + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: pcb=%p hs=%p pcb_state=%s\n", + (void*)pcb, (void*)hs, tcp_debug_state_str(pcb->state))); + + if (hs == NULL) { + err_t closed; + /* arg is null, close. */ + LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: arg is NULL, close\n")); + closed = http_close_conn(pcb, NULL); + LWIP_UNUSED_ARG(closed); +#if LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR + if (closed == ERR_MEM) { + tcp_abort(pcb); + return ERR_ABRT; + } +#endif /* LWIP_HTTPD_ABORT_ON_CLOSE_MEM_ERROR */ + return ERR_OK; + } else { + hs->retries++; + if (hs->retries == HTTPD_MAX_RETRIES) { + LWIP_DEBUGF(HTTPD_DEBUG, ("http_poll: too many retries, close\n")); + http_close_conn(pcb, hs); + return ERR_OK; + } + + /* If this connection has a file open, try to send some more data. If + * it has not yet received a GET request, don't do this since it will + * cause the connection to close immediately. */ + if(hs && (hs->handle)) { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_poll: try to send more data\n")); + if(http_send(pcb, hs)) { + /* If we wrote anything to be sent, go ahead and send it now. */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("tcp_output\n")); + tcp_output(pcb); + } + } + } + + return ERR_OK; +} + +/** + * Data has been received on this pcb. + * For HTTP 1.0, this should normally only happen once (if the request fits in one packet). + */ +static err_t +http_recv(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) +{ + err_t parsed = ERR_ABRT; + struct http_state *hs = (struct http_state *)arg; + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: pcb=%p pbuf=%p err=%s\n", (void*)pcb, + (void*)p, lwip_strerr(err))); + + if ((err != ERR_OK) || (p == NULL) || (hs == NULL)) { + /* error or closed by other side? */ + if (p != NULL) { + /* Inform TCP that we have taken the data. */ + tcp_recved(pcb, p->tot_len); + pbuf_free(p); + } + if (hs == NULL) { + /* this should not happen, only to be robust */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Error, http_recv: hs is NULL, close\n")); + } + http_close_conn(pcb, hs); + return ERR_OK; + } + +#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND + if (hs->no_auto_wnd) { + hs->unrecved_bytes += p->tot_len; + } else +#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ + { + /* Inform TCP that we have taken the data. */ + tcp_recved(pcb, p->tot_len); + } + +#if LWIP_HTTPD_SUPPORT_POST + if (hs->post_content_len_left > 0) { + /* reset idle counter when POST data is received */ + hs->retries = 0; + /* this is data for a POST, pass the complete pbuf to the application */ + http_post_rxpbuf(hs, p); + /* pbuf is passed to the application, don't free it! */ + if (hs->post_content_len_left == 0) { + /* all data received, send response or close connection */ + http_send(pcb, hs); + } + return ERR_OK; + } else +#endif /* LWIP_HTTPD_SUPPORT_POST */ + { + if (hs->handle == NULL) { + parsed = http_parse_request(p, hs, pcb); + LWIP_ASSERT("http_parse_request: unexpected return value", parsed == ERR_OK + || parsed == ERR_INPROGRESS ||parsed == ERR_ARG || parsed == ERR_USE); + } else { + LWIP_DEBUGF(HTTPD_DEBUG, ("http_recv: already sending data\n")); + /* already sending but still receiving data, we might want to RST here? */ + pbuf_free(p); + } +#if LWIP_HTTPD_SUPPORT_REQUESTLIST + if (parsed != ERR_INPROGRESS) { + /* request fully parsed or error */ + if (hs->req != NULL) { + pbuf_free(hs->req); + hs->req = NULL; + } + } +#endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + pbuf_free(p); + if (parsed == ERR_OK) { +#if LWIP_HTTPD_SUPPORT_POST + if (hs->post_content_len_left == 0) +#endif /* LWIP_HTTPD_SUPPORT_POST */ + { + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("http_recv: data %p len %"S32_F"\n", hs->file, hs->left)); + http_send(pcb, hs); + } + } else if (parsed == ERR_ARG) { + /* @todo: close on ERR_USE? */ + http_close_conn(pcb, hs); + } + } + return ERR_OK; +} + +/** + * A new incoming connection has been accepted. + */ +static err_t +http_accept(void *arg, struct tcp_pcb *pcb, err_t err) +{ + struct http_state *hs; + struct tcp_pcb_listen *lpcb = (struct tcp_pcb_listen*)arg; + LWIP_UNUSED_ARG(err); + LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept %p / %p\n", (void*)pcb, arg)); + + /* Decrease the listen backlog counter */ + tcp_accepted(lpcb); + /* Set priority */ + tcp_setprio(pcb, HTTPD_TCP_PRIO); + + /* Allocate memory for the structure that holds the state of the + connection - initialized by that function. */ + hs = http_state_alloc(); + if (hs == NULL) { + LWIP_DEBUGF(HTTPD_DEBUG, ("http_accept: Out of memory, RST\n")); + return ERR_MEM; + } + hs->pcb = pcb; + + /* Tell TCP that this is the structure we wish to be passed for our + callbacks. */ + tcp_arg(pcb, hs); + + /* Set up the various callback functions */ + tcp_recv(pcb, http_recv); + tcp_err(pcb, http_err); + tcp_poll(pcb, http_poll, HTTPD_POLL_INTERVAL); + tcp_sent(pcb, http_sent); + + return ERR_OK; +} + +/** + * Initialize the httpd with the specified local address. + */ +static void +httpd_init_addr(ip_addr_t *local_addr) +{ + struct tcp_pcb *pcb; + err_t err; + + pcb = tcp_new(); + LWIP_ASSERT("httpd_init: tcp_new failed", pcb != NULL); + tcp_setprio(pcb, HTTPD_TCP_PRIO); + /* set SOF_REUSEADDR here to explicitly bind httpd to multiple interfaces */ + err = tcp_bind(pcb, local_addr, HTTPD_SERVER_PORT); + LWIP_ASSERT("httpd_init: tcp_bind failed", err == ERR_OK); + pcb = tcp_listen(pcb); + LWIP_ASSERT("httpd_init: tcp_listen failed", pcb != NULL); + /* initialize callback arg and accept callback */ + tcp_arg(pcb, pcb); + tcp_accept(pcb, http_accept); +} + +/** + * Initialize the httpd: set up a listening PCB and bind it to the defined port + */ +void +httpd_init(void) +{ +#if MEMP_MEM_MALLOC || MEM_USE_POOLS +#if HTTPD_USE_MEM_POOL + LWIP_ASSERT("memp_sizes[MEMP_HTTPD_STATE] >= sizeof(http_state)", + memp_sizes[MEMP_HTTPD_STATE] >= sizeof(struct http_state)); +#if LWIP_HTTPD_SSI + LWIP_ASSERT("memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(http_ssi_state)", + memp_sizes[MEMP_HTTPD_SSI_STATE] >= sizeof(struct http_ssi_state)); +#endif +#endif +#endif + LWIP_DEBUGF(HTTPD_DEBUG, ("httpd_init\n")); + + httpd_init_addr(IP_ADDR_ANY); +} + +#if LWIP_HTTPD_SSI +/** + * Set the SSI handler function. + * + * @param ssi_handler the SSI handler function + * @param tags an array of SSI tag strings to search for in SSI-enabled files + * @param num_tags number of tags in the 'tags' array + */ +void +http_set_ssi_handler(tSSIHandler ssi_handler, const char **tags, int num_tags) +{ + LWIP_DEBUGF(HTTPD_DEBUG, ("http_set_ssi_handler\n")); + + LWIP_ASSERT("no ssi_handler given", ssi_handler != NULL); + LWIP_ASSERT("no tags given", tags != NULL); + LWIP_ASSERT("invalid number of tags", num_tags > 0); + + g_pfnSSIHandler = ssi_handler; + g_ppcTags = tags; + g_iNumTags = num_tags; +} +#endif /* LWIP_HTTPD_SSI */ + +#if LWIP_HTTPD_CGI +/** + * Set an array of CGI filenames/handler functions + * + * @param cgis an array of CGI filenames/handler functions + * @param num_handlers number of elements in the 'cgis' array + */ +void +http_set_cgi_handlers(const tCGI *cgis, int num_handlers) +{ + LWIP_ASSERT("no cgis given", cgis != NULL); + LWIP_ASSERT("invalid number of handlers", num_handlers > 0); + + g_pCGIs = cgis; + g_iNumCGIs = num_handlers; +} +#endif /* LWIP_HTTPD_CGI */ + +#endif /* LWIP_TCP */ diff --git a/apps/httpserver_raw/httpd_structs.h b/apps/httpserver_raw/httpd_structs.h index a49ce6d..538d741 100644 --- a/apps/httpserver_raw/httpd_structs.h +++ b/apps/httpserver_raw/httpd_structs.h @@ -1,119 +1 @@ -#ifndef LWIP_HTTPD_STRUCTS_H -#define LWIP_HTTPD_STRUCTS_H - -#include "httpd.h" - -/** This string is passed in the HTTP header as "Server: " */ -#ifndef HTTPD_SERVER_AGENT -#define HTTPD_SERVER_AGENT "lwIP/1.3.1 (http://savannah.nongnu.org/projects/lwip)" -#endif - -/** Set this to 1 if you want to include code that creates HTTP headers - * at runtime. Default is off: HTTP headers are then created statically - * by the makefsdata tool. Static headers mean smaller code size, but - * the (readonly) fsdata will grow a bit as every file includes the HTTP - * header. */ -#ifndef LWIP_HTTPD_DYNAMIC_HEADERS -#define LWIP_HTTPD_DYNAMIC_HEADERS 0 -#endif - - -#if LWIP_HTTPD_DYNAMIC_HEADERS -/** This struct is used for a list of HTTP header strings for various - * filename extensions. */ -typedef struct -{ - const char *extension; - const char *content_type; -} tHTTPHeader; - -/** A list of strings used in HTTP headers (see RFC 1945 HTTP/1.0 and - * RFC 2616 HTTP/1.1 for header field definitions) */ -static const char * const g_psHTTPHeaderStrings[] = -{ - "HTTP/1.0 200 OK\r\n", - "HTTP/1.0 404 File not found\r\n", - "HTTP/1.0 400 Bad Request\r\n", - "HTTP/1.0 501 Not Implemented\r\n", - "HTTP/1.1 200 OK\r\n", - "HTTP/1.1 404 File not found\r\n", - "HTTP/1.1 400 Bad Request\r\n", - "HTTP/1.1 501 Not Implemented\r\n", - "Content-Length: ", - "Connection: Close\r\n", - "Connection: keep-alive\r\n", - "Server: "HTTPD_SERVER_AGENT"\r\n", - "\r\n

404: The requested file cannot be found.

\r\n" -}; - -/* Indexes into the g_psHTTPHeaderStrings array */ -#define HTTP_HDR_OK 0 /* 200 OK */ -#define HTTP_HDR_NOT_FOUND 1 /* 404 File not found */ -#define HTTP_HDR_BAD_REQUEST 2 /* 400 Bad request */ -#define HTTP_HDR_NOT_IMPL 3 /* 501 Not Implemented */ -#define HTTP_HDR_OK_11 4 /* 200 OK */ -#define HTTP_HDR_NOT_FOUND_11 5 /* 404 File not found */ -#define HTTP_HDR_BAD_REQUEST_11 6 /* 400 Bad request */ -#define HTTP_HDR_NOT_IMPL_11 7 /* 501 Not Implemented */ -#define HTTP_HDR_CONTENT_LENGTH 8 /* Content-Length: (HTTP 1.1)*/ -#define HTTP_HDR_CONN_CLOSE 9 /* Connection: Close (HTTP 1.1) */ -#define HTTP_HDR_CONN_KEEPALIVE 10 /* Connection: keep-alive (HTTP 1.1) */ -#define HTTP_HDR_SERVER 11 /* Server: HTTPD_SERVER_AGENT */ -#define DEFAULT_404_HTML 12 /* default 404 body */ - - -#define HTTP_HDR_HTML "Content-type: text/html\r\n\r\n" -#define HTTP_HDR_SSI "Content-type: text/html\r\nExpires: Fri, 10 Apr 2008 14:00:00 GMT\r\nPragma: no-cache\r\n\r\n" -#define HTTP_HDR_GIF "Content-type: image/gif\r\n\r\n" -#define HTTP_HDR_PNG "Content-type: image/png\r\n\r\n" -#define HTTP_HDR_JPG "Content-type: image/jpeg\r\n\r\n" -#define HTTP_HDR_BMP "Content-type: image/bmp\r\n\r\n" -#define HTTP_HDR_ICO "Content-type: image/x-icon\r\n\r\n" -#define HTTP_HDR_APP "Content-type: application/octet-stream\r\n\r\n" -#define HTTP_HDR_JS "Content-type: application/javascript\r\n\r\n" -#define HTTP_HDR_RA "Content-type: application/javascript\r\n\r\n" -#define HTTP_HDR_CSS "Content-type: text/css\r\n\r\n" -#define HTTP_HDR_SWF "Content-type: application/x-shockwave-flash\r\n\r\n" -#define HTTP_HDR_XML "Content-type: text/xml\r\n\r\n" -#define HTTP_HDR_PDF "Content-type: application/pdf\r\n\r\n" - -#define HTTP_HDR_DEFAULT_TYPE "Content-type: text/plain\r\n\r\n" - -/** A list of extension-to-HTTP header strings (see outdated RFC 1700 MEDIA TYPES - * and http://www.iana.org/assignments/media-types for registered content types - * and subtypes) */ -static const tHTTPHeader g_psHTTPHeaders[] = -{ - { "html", HTTP_HDR_HTML}, - { "htm", HTTP_HDR_HTML}, - { "shtml",HTTP_HDR_SSI}, - { "shtm", HTTP_HDR_SSI}, - { "ssi", HTTP_HDR_SSI}, - { "gif", HTTP_HDR_GIF}, - { "png", HTTP_HDR_PNG}, - { "jpg", HTTP_HDR_JPG}, - { "bmp", HTTP_HDR_BMP}, - { "ico", HTTP_HDR_ICO}, - { "class",HTTP_HDR_APP}, - { "cls", HTTP_HDR_APP}, - { "js", HTTP_HDR_JS}, - { "ram", HTTP_HDR_RA}, - { "css", HTTP_HDR_CSS}, - { "swf", HTTP_HDR_SWF}, - { "xml", HTTP_HDR_XML}, - { "xsl", HTTP_HDR_XML}, - { "pdf", HTTP_HDR_PDF} -}; - -#define NUM_HTTP_HEADERS (sizeof(g_psHTTPHeaders) / sizeof(tHTTPHeader)) - -#endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ - -#if LWIP_HTTPD_SSI -static const char * const g_pcSSIExtensions[] = { - ".shtml", ".shtm", ".ssi", ".xml" -}; -#define NUM_SHTML_EXTENSIONS (sizeof(g_pcSSIExtensions) / sizeof(const char *)) -#endif /* LWIP_HTTPD_SSI */ - -#endif /* LWIP_HTTPD_STRUCTS_H */ +#ifndef LWIP_HTTPD_STRUCTS_H #define LWIP_HTTPD_STRUCTS_H #include "httpd.h" /** This string is passed in the HTTP header as "Server: " */ #ifndef HTTPD_SERVER_AGENT #define HTTPD_SERVER_AGENT "lwIP/1.3.1 (http://savannah.nongnu.org/projects/lwip)" #endif /** Set this to 1 if you want to include code that creates HTTP headers * at runtime. Default is off: HTTP headers are then created statically * by the makefsdata tool. Static headers mean smaller code size, but * the (readonly) fsdata will grow a bit as every file includes the HTTP * header. */ #ifndef LWIP_HTTPD_DYNAMIC_HEADERS #define LWIP_HTTPD_DYNAMIC_HEADERS 0 #endif #if LWIP_HTTPD_DYNAMIC_HEADERS /** This struct is used for a list of HTTP header strings for various * filename extensions. */ typedef struct { const char *extension; const char *content_type; } tHTTPHeader; /** A list of strings used in HTTP headers (see RFC 1945 HTTP/1.0 and * RFC 2616 HTTP/1.1 for header field definitions) */ static const char * const g_psHTTPHeaderStrings[] = { "HTTP/1.0 200 OK\r\n", "HTTP/1.0 404 File not found\r\n", "HTTP/1.0 400 Bad Request\r\n", "HTTP/1.0 501 Not Implemented\r\n", "HTTP/1.1 200 OK\r\n", "HTTP/1.1 404 File not found\r\n", "HTTP/1.1 400 Bad Request\r\n", "HTTP/1.1 501 Not Implemented\r\n", "Content-Length: ", "Connection: Close\r\n", "Connection: keep-alive\r\n", "Server: "HTTPD_SERVER_AGENT"\r\n", "\r\n

404: The requested file cannot be found.

\r\n" }; /* Indexes into the g_psHTTPHeaderStrings array */ #define HTTP_HDR_OK 0 /* 200 OK */ #define HTTP_HDR_NOT_FOUND 1 /* 404 File not found */ #define HTTP_HDR_BAD_REQUEST 2 /* 400 Bad request */ #define HTTP_HDR_NOT_IMPL 3 /* 501 Not Implemented */ #define HTTP_HDR_OK_11 4 /* 200 OK */ #define HTTP_HDR_NOT_FOUND_11 5 /* 404 File not found */ #define HTTP_HDR_BAD_REQUEST_11 6 /* 400 Bad request */ #define HTTP_HDR_NOT_IMPL_11 7 /* 501 Not Implemented */ #define HTTP_HDR_CONTENT_LENGTH 8 /* Content-Length: (HTTP 1.1)*/ #define HTTP_HDR_CONN_CLOSE 9 /* Connection: Close (HTTP 1.1) */ #define HTTP_HDR_CONN_KEEPALIVE 10 /* Connection: keep-alive (HTTP 1.1) */ #define HTTP_HDR_SERVER 11 /* Server: HTTPD_SERVER_AGENT */ #define DEFAULT_404_HTML 12 /* default 404 body */ #define HTTP_HDR_HTML "Content-type: text/html\r\n\r\n" #define HTTP_HDR_SSI "Content-type: text/html\r\nExpires: Fri, 10 Apr 2008 14:00:00 GMT\r\nPragma: no-cache\r\n\r\n" #define HTTP_HDR_GIF "Content-type: image/gif\r\n\r\n" #define HTTP_HDR_PNG "Content-type: image/png\r\n\r\n" #define HTTP_HDR_JPG "Content-type: image/jpeg\r\n\r\n" #define HTTP_HDR_BMP "Content-type: image/bmp\r\n\r\n" #define HTTP_HDR_ICO "Content-type: image/x-icon\r\n\r\n" #define HTTP_HDR_APP "Content-type: application/octet-stream\r\n\r\n" #define HTTP_HDR_JS "Content-type: application/javascript\r\n\r\n" #define HTTP_HDR_RA "Content-type: application/javascript\r\n\r\n" #define HTTP_HDR_CSS "Content-type: text/css\r\n\r\n" #define HTTP_HDR_SWF "Content-type: application/x-shockwave-flash\r\n\r\n" #define HTTP_HDR_XML "Content-type: text/xml\r\n\r\n" #define HTTP_HDR_PDF "Content-type: application/pdf\r\n\r\n" /* Typical Mac mime types */ #define HTTP_HDR_BIN "Content-type: application/mac-binary\r\n\r\n" #define HTTP_HDR_CPT "Content-type: application/mac-compactpro\r\n\r\n" #define HTTP_HDR_HQX "Content-type: application/mac-binhex\r\n\r\n" #define HTTP_HDR_SIT "Content-type: application/application/x-stuffit\r\n\r\n" #define HTTP_HDR_DEFAULT_TYPE "Content-type: text/plain\r\n\r\n" /** A list of extension-to-HTTP header strings (see outdated RFC 1700 MEDIA TYPES * and http://www.iana.org/assignments/media-types for registered content types * and subtypes) */ static const tHTTPHeader g_psHTTPHeaders[] = { { "html", HTTP_HDR_HTML}, { "htm", HTTP_HDR_HTML}, { "shtml",HTTP_HDR_SSI}, { "shtm", HTTP_HDR_SSI}, { "ssi", HTTP_HDR_SSI}, { "gif", HTTP_HDR_GIF}, { "png", HTTP_HDR_PNG}, { "jpg", HTTP_HDR_JPG}, { "bmp", HTTP_HDR_BMP}, { "ico", HTTP_HDR_ICO}, // { "class",HTTP_HDR_APP}, // { "cls", HTTP_HDR_APP}, // { "js", HTTP_HDR_JS}, // { "ram", HTTP_HDR_RA}, { "css", HTTP_HDR_CSS}, // { "swf", HTTP_HDR_SWF}, // { "xml", HTTP_HDR_XML}, // { "xsl", HTTP_HDR_XML}, { "pdf", HTTP_HDR_PDF}, { "bin", HTTP_HDR_BIN}, { "cpt", HTTP_HDR_CPT}, { "hqx", HTTP_HDR_HQX}, { "sit", HTTP_HDR_SIT} }; #define NUM_HTTP_HEADERS (sizeof(g_psHTTPHeaders) / sizeof(tHTTPHeader)) #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ #if LWIP_HTTPD_SSI static const char * const g_pcSSIExtensions[] = { ".shtml", ".shtm", ".ssi", ".xml" }; #define NUM_SHTML_EXTENSIONS (sizeof(g_pcSSIExtensions) / sizeof(const char *)) #endif /* LWIP_HTTPD_SSI */ #endif /* LWIP_HTTPD_STRUCTS_H */ \ No newline at end of file diff --git a/head_support.h.patch b/head_support.h.patch new file mode 100644 index 0000000..527e31c --- /dev/null +++ b/head_support.h.patch @@ -0,0 +1,15 @@ +diff --git a/apps/httpserver_raw/httpd.h b/apps/httpserver_raw/httpd.h +index 3962f72..e0a9d18 100644 +--- a/apps/httpserver_raw/httpd.h ++++ b/apps/httpserver_raw/httpd.h +@@ -59,6 +59,10 @@ extern "C" { + #define LWIP_HTTPD_SUPPORT_POST 0 + #endif + ++/** Set this to 1 to support HTTP HEAD */ ++#ifndef LWIP_HTTPD_SUPPORT_HEAD ++#define LWIP_HTTPD_SUPPORT_HEAD 0 ++#endif + + #if LWIP_HTTPD_CGI + diff --git a/head_support.patch b/head_support.patch new file mode 100644 index 0000000..59e8deb --- /dev/null +++ b/head_support.patch @@ -0,0 +1,311 @@ +diff --git a/apps/httpserver_raw/httpd.c b/apps/httpserver_raw/httpd.c +index 772b179..b6199a4 100644 +--- a/apps/httpserver_raw/httpd.c ++++ b/apps/httpserver_raw/httpd.c +@@ -317,6 +317,17 @@ static char http_post_response_filename[LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN+1]; + #define NUM_FILE_HDR_STRINGS 3 + #endif /* LWIP_HTTPD_DYNAMIC_HEADERS */ + ++#if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 ++enum request_method { ++ METHOD_UNK, /* Unknown method */ ++ METHOD_GET, /* HTTP 1.0 spec 8.1 - GET */ ++ METHOD_HEAD, /* HTTP 1.0 spec 8.2 - HEAD */ ++ METHOD_POST, /* HTTP 1.0 spec 8.3 - POST */ ++ METHOD_V09_GET = 9 /* HTTP 0.9 - GET */ ++}; ++#endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09*/ ++ ++ + #if LWIP_HTTPD_SSI + + #define HTTPD_LAST_TAG_PART 0xFFFF +@@ -370,6 +381,9 @@ struct http_state { + #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE + u8_t keepalive; + #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ ++#if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 ++ int method; ++#endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 */ + #if LWIP_HTTPD_SSI + struct http_ssi_state *ssi; + #endif /* LWIP_HTTPD_SSI */ +@@ -398,8 +412,8 @@ struct http_state { + + static err_t http_close_conn(struct tcp_pcb *pcb, struct http_state *hs); + static err_t http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_conn); +-static err_t http_find_file(struct http_state *hs, const char *uri, int is_09); +-static err_t http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check); ++static err_t http_find_file(struct http_state *hs, const char *uri); ++static err_t http_init_file(struct http_state *hs, struct fs_file *file, const char *uri, u8_t tag_check); + static err_t http_poll(void *arg, struct tcp_pcb *pcb); + static u8_t http_check_eof(struct tcp_pcb *pcb, struct http_state *hs); + #if LWIP_HTTPD_FS_ASYNC_READ +@@ -706,7 +720,6 @@ http_close_or_abort_conn(struct tcp_pcb *pcb, struct http_state *hs, u8_t abort_ + } + #endif /* LWIP_HTTPD_SUPPORT_POST*/ + +- + tcp_arg(pcb, NULL); + tcp_recv(pcb, NULL); + tcp_err(pcb, NULL); +@@ -1620,7 +1633,7 @@ http_find_error_file(struct http_state *hs, u16_t error_nr) + } + } + } +- return http_init_file(hs, &hs->file_handle, 0, NULL, 0); ++ return http_init_file(hs, &hs->file_handle, NULL, 0); + } + #else /* LWIP_HTTPD_SUPPORT_EXTSTATUS */ + #define http_find_error_file(hs, error_nr) ERR_ARG +@@ -1677,7 +1690,7 @@ http_handle_post_finished(struct http_state *hs) + /* NULL-terminate the buffer */ + http_post_response_filename[0] = 0; + httpd_post_finished(hs, http_post_response_filename, LWIP_HTTPD_POST_MAX_RESPONSE_URI_LEN); +- return http_find_file(hs, http_post_response_filename, 0); ++ return http_find_file(hs, http_post_response_filename); + } + + /** Pass received POST body data to the application and correctly handle +@@ -1706,11 +1719,11 @@ http_post_rxpbuf(struct http_state *hs, struct pbuf *p) + hs->post_content_len_left = 0; + } + if (hs->post_content_len_left == 0) { +-#if LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND ++#if LWIP_HTTPD_POST_MANUAL_WND + if (hs->unrecved_bytes != 0) { + return ERR_OK; + } +-#endif /* LWIP_HTTPD_SUPPORT_POST && LWIP_HTTPD_POST_MANUAL_WND */ ++#endif /* LWIP_HTTPD_POST_MANUAL_WND */ + /* application error or POST finished */ + return http_handle_post_finished(hs); + } +@@ -1792,7 +1805,7 @@ http_post_request(struct pbuf *inp, struct http_state *hs, + } + } else { + /* return file passed from application */ +- return http_find_file(hs, http_post_response_filename, 0); ++ return http_find_file(hs, http_post_response_filename); + } + } else { + LWIP_DEBUGF(HTTPD_DEBUG, ("POST received invalid Content-Length: %s\n", +@@ -1946,11 +1959,7 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) + if (data_len >= MIN_REQ_LEN) { + /* wait for CRLF before parsing anything */ + crlf = strnstr(data, CRLF, data_len); +- if (crlf != NULL) { +-#if LWIP_HTTPD_SUPPORT_POST +- int is_post = 0; +-#endif /* LWIP_HTTPD_SUPPORT_POST */ +- int is_09 = 0; ++ if (crlf != NULL) { + char *sp1, *sp2; + u16_t left_len, uri_len; + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("CRLF received, parsing request\n")); +@@ -1959,16 +1968,27 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) + sp1 = data + 3; + /* received GET request */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received GET request\"\n")); ++#if LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 ++ hs->method = METHOD_GET; ++#endif /* LWIP_HTTPD_SUPPORT_HEAD || LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_V09 */ ++#if LWIP_HTTPD_SUPPORT_HEAD ++ } else if (!strncmp(data, "HEAD ", 5)) { ++ /* store request type */ ++ hs->method = METHOD_HEAD; ++ sp1 = data + 4; ++ /* received HEAD request */ ++ LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received HEAD request\n")); ++#endif /* LWIP_HTTPD_SUPPORT_HEAD */ + #if LWIP_HTTPD_SUPPORT_POST + } else if (!strncmp(data, "POST ", 5)) { + /* store request type */ +- is_post = 1; ++ hs->method = METHOD_POST; + sp1 = data + 4; +- /* received GET request */ ++ /* received POST request */ + LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("Received POST request\n")); + #endif /* LWIP_HTTPD_SUPPORT_POST */ + } else { +- /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ ++ /* null-terminate the METHOD (pbuf is freed anyway when returning) */ + data[4] = 0; + /* unsupported method! */ + LWIP_DEBUGF(HTTPD_DEBUG, ("Unsupported request method (not implemented): \"%s\"\n", +@@ -1982,32 +2002,33 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) + if (sp2 == NULL) { + /* HTTP 0.9: respond with correct protocol version */ + sp2 = strnstr(sp1 + 1, CRLF, left_len); +- is_09 = 1; +-#if LWIP_HTTPD_SUPPORT_POST +- if (is_post) { +- /* HTTP/0.9 does not support POST */ ++#if LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD ++ if (hs->method != METHOD_GET) { ++ /* HTTP/0.9 only supports GET method */ + goto badrequest; + } +-#endif /* LWIP_HTTPD_SUPPORT_POST */ ++#endif /* LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD */ ++ hs->method = METHOD_V09_GET; + } + #endif /* LWIP_HTTPD_SUPPORT_V09 */ ++ + uri_len = sp2 - (sp1 + 1); + if ((sp2 != 0) && (sp2 > sp1)) { + /* wait for CRLFCRLF (indicating end of HTTP headers) before parsing anything */ + if (strnstr(data, CRLF CRLF, data_len) != NULL) { + char *uri = sp1 + 1; + #if LWIP_HTTPD_SUPPORT_11_KEEPALIVE +- if (!is_09 && strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len)) { ++ if ((hs->method != METHOD_V09_GET && strnstr(data, HTTP11_CONNECTIONKEEPALIVE, data_len)) { + hs->keepalive = 1; + } + #endif /* LWIP_HTTPD_SUPPORT_11_KEEPALIVE */ +- /* null-terminate the METHOD (pbuf is freed anyway wen returning) */ ++ /* null-terminate the METHOD (pbuf is freed anyway when returning) */ + *sp1 = 0; + uri[uri_len] = 0; + LWIP_DEBUGF(HTTPD_DEBUG, ("Received \"%s\" request for URI: \"%s\"\n", + data, uri)); + #if LWIP_HTTPD_SUPPORT_POST +- if (is_post) { ++ if (method == METHOD_POST) { + #if LWIP_HTTPD_SUPPORT_REQUESTLIST + struct pbuf *q = hs->req; + #else /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ +@@ -2027,7 +2048,7 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) + } else + #endif /* LWIP_HTTPD_SUPPORT_POST */ + { +- return http_find_file(hs, uri, is_09); ++ return http_find_file(hs, uri); + } + } + } else { +@@ -2045,9 +2066,9 @@ http_parse_request(struct pbuf *inp, struct http_state *hs, struct tcp_pcb *pcb) + } else + #endif /* LWIP_HTTPD_SUPPORT_REQUESTLIST */ + { +-#if LWIP_HTTPD_SUPPORT_POST ++#if LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD + badrequest: +-#endif /* LWIP_HTTPD_SUPPORT_POST */ ++#endif /* LWIP_HTTPD_SUPPORT_POST || LWIP_HTTPD_SUPPORT_HEAD */ + LWIP_DEBUGF(HTTPD_DEBUG, ("bad request\n")); + /* could not parse request */ + return http_find_error_file(hs, 400); +@@ -2059,12 +2080,11 @@ badrequest: + * + * @param hs the connection state + * @param uri the HTTP header URI +- * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) + * @return ERR_OK if file was found and hs has been initialized correctly + * another err_t otherwise + */ + static err_t +-http_find_file(struct http_state *hs, const char *uri, int is_09) ++http_find_file(struct http_state *hs, const char *uri) + { + size_t loop; + struct fs_file *file = NULL; +@@ -2154,7 +2174,7 @@ http_find_file(struct http_state *hs, const char *uri, int is_09) + } + #endif /* LWIP_HTTPD_SSI */ + } +- return http_init_file(hs, file, is_09, uri, tag_check); ++ return http_init_file(hs, file, uri, tag_check); + } + + /** Initialize a http connection with a file to send (if found). +@@ -2162,14 +2182,13 @@ http_find_file(struct http_state *hs, const char *uri, int is_09) + * + * @param hs http connection state + * @param file file structure to send (or NULL if not found) +- * @param is_09 1 if the request is HTTP/0.9 (no HTTP headers in response) + * @param uri the HTTP header URI + * @param tag_check enable SSI tag checking + * @return ERR_OK if file was found and hs has been initialized correctly + * another err_t otherwise + */ + static err_t +-http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const char *uri, u8_t tag_check) ++http_init_file(struct http_state *hs, struct fs_file *file, const char *uri, u8_t tag_check) + { + if (file != NULL) { + /* file opened, initialise struct http_state */ +@@ -2192,25 +2211,41 @@ http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const cha + hs->file = (char*)file->data; + LWIP_ASSERT("File length must be positive!", (file->len >= 0)); + hs->left = file->len; ++#if LWIP_HTTPD_DYNAMIC_FILE_READ ++ if (hs->file == NULL) { ++ /* Causes http_check_eof() to be called which will read the data. */ ++ hs->left = 0; ++ } ++#endif + hs->retries = 0; + #if LWIP_HTTPD_TIMING + hs->time_started = sys_now(); + #endif /* LWIP_HTTPD_TIMING */ + #if !LWIP_HTTPD_DYNAMIC_HEADERS + LWIP_ASSERT("HTTP headers not included in file system", hs->handle->http_header_included); +-#endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ ++#endif /* !LWIP_HTTPD_DYNAMIC_HEADERS */ ++#if LWIP_HTTPD_SUPPORT_V09 || LWIP_HTTPD_SUPPORT_HEAD ++ if ( hs->handle->http_header_included && hs->method != METHOD_GET) { ++ /* Search for the end of the header. */ ++ char *head_end = strnstr(hs->file, CRLF CRLF, hs->left); ++ size_t diff = head_end + 4 - hs->file; ++ if (head_end == NULL) { ++ LWIP_DEBUGF(HTTPD_DEBUG, ("Expected HTTP header, but couldn't find it.\n")); ++ hs->handle->http_header_included = 0; + #if LWIP_HTTPD_SUPPORT_V09 +- if (hs->handle->http_header_included && is_09) { +- /* HTTP/0.9 responses are sent without HTTP header, +- search for the end of the header. */ +- char *file_start = strnstr(hs->file, CRLF CRLF, hs->left); +- if (file_start != NULL) { +- size_t diff = file_start + 4 - hs->file; +- hs->file += diff; +- hs->left -= (u32_t)diff; +- } +- } ++ } else if (hs->method == METHOD_V09_GET) { ++ /* HTTP/0.9 responses are sent without HTTP header. */ ++ hs->file += diff; ++ hs->left -= (u32_t)diff; + #endif /* LWIP_HTTPD_SUPPORT_V09*/ ++#if LWIP_HTTPD_SUPPORT_HEAD ++ } else if (hs->method == METHOD_HEAD) { ++ /* HEAD method responses are sent with only HTTP header. */ ++ hs->left = (u32_t)diff; ++#endif /* LWIP_HTTPD_SUPPORT_HEAD*/ ++ } ++ } ++#endif /* LWIP_HTTPD_SUPPORT_V09 || LWIP_HTTPD_SUPPORT_HEAD*/ + } else { + hs->handle = NULL; + hs->file = NULL; +@@ -2221,7 +2256,18 @@ http_init_file(struct http_state *hs, struct fs_file *file, int is_09, const cha + /* Determine the HTTP headers to send based on the file extension of + * the requested URI. */ + if ((hs->handle == NULL) || !hs->handle->http_header_included) { +- get_http_headers(hs, (char*)uri); ++#if LWIP_HTTPD_SUPPORT_V09 ++ if (hs->method != METHOD_V09_GET) ++ /* Don't load the header. */ ++#endif /* LWIP_HTTPD_SUPPORT_V09*/ ++ get_http_headers(hs, (char*)uri); ++#if LWIP_HTTPD_SUPPORT_HEAD ++ if (hs->method == METHOD_HEAD) { ++ /* Just the the header, not the file. */ ++ hs->left = 0; ++ hs->handle->len = 0; ++ } ++#endif /* LWIP_HTTPD_SUPPORT_HEAD*/ + } + #else /* LWIP_HTTPD_DYNAMIC_HEADERS */ + LWIP_UNUSED_ARG(uri); diff --git a/ports/mac/ElWhip.c b/ports/mac/ElWhip.c new file mode 100644 index 0000000..bf91760 --- /dev/null +++ b/ports/mac/ElWhip.c @@ -0,0 +1 @@ +/* ElWhip.c * * * Created by Eric Pooch on 1/26/14. * Copyright 2014 __MyCompanyName__. All rights reserved. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "arch/macos_debug.h" #include #include #include "ElWhip.h" #include "test.h" /* GMac is used to hold the result of a SysEnvirons call. This makes it convenient for any routine to check the environment. */ SysEnvRec gMac; /* set up by Initialize */ /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent trap is available. If it is false, we know that we must call GetNextEvent. */ //Boolean gHasWaitNextEvent; /* set up by Initialize */ /* GInBackground is maintained by our osEvent handling routines. Any part of the program can check it to find out if it is currently in the background. */ Boolean gInBackground; /* maintained by Initialize and DoEvent */ /* Here are declarations for all of the C routines. In MPW 3.0 we can use actual prototypes for parameter type checking. */ void EventLoop( void ); void DoEvent( EventRecord *event ); void DoMenuCommand( long menuResult ); void MemoryInit( void ); void MacintoshInit( void ); void Restart(void); void Terminate( void ); void GetTERect(WindowPtr window, Rect *teRect); Boolean TrapAvailable( short tNumber, TrapType tType ); void AlertUser( void ); /* Define HiWrd and LoWrd macros for efficiency. */ #define HiWrd(aLong) (((aLong) >> 16) & 0xFFFF) #define LoWrd(aLong) ((aLong) & 0xFFFF) /* This routine is part of the MPW runtime library. This external reference to it is done so that we can unload its segment, %A5Init. */ extern void _DataInit(); int main(void) { OSErr error = 0; FILE *fildes; char buff[255]; UnloadSeg((Ptr) _DataInit); MemoryInit(); MacintoshInit(); /* initialize the program */ test_init(); EventLoop(); /* call the main event loop */ return 0; } /* Get events forever, and handle them by calling DoEvent. Get the events by calling WaitNextEvent, if it's available, otherwise by calling GetNextEvent. Also call AdjustCursor each time through the loop. */ #pragma segment Main void EventLoop() { Boolean gotEvent; EventRecord event; RgnHandle cursorRgn; do { /* use WNE if it is available */ //if ( gHasWaitNextEvent ) //{ // gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn); //} else //{ SystemTask(); gotEvent = GetNextEvent(everyEvent, &event); //} if ( gotEvent ) { /* Handle the event */ DoEvent(&event); } test_poll(); } while ( true ); /* loop forever; we quit via ExitToShell */ } /*EventLoop*/ /* Do the right thing for an event. Determine what kind of event it is, and call the appropriate routines. */ void DoEvent( EventRecord *event ) { short part, err; WindowPtr window; Boolean hit; char key; switch ( event->what ) { case mouseDown: part = FindWindow(event->where, &window); switch ( part ) { case inMenuBar: /* process a mouse menu command (if any) */ DoMenuCommand(MenuSelect(event->where)); break; case inSysWindow: /* let the system handle the mouseDown */ SystemClick(event, window); break; } break; case keyDown: case autoKey: /* check for menukey equivalents */ key = event->message & charCodeMask; if ( event->modifiers & cmdKey ) /* Command key down */ { if ( event->what == keyDown ) { DoMenuCommand(MenuKey(key)); } } break; case kOSEvent: /* 1.02 - must BitAND with 0x0FF to get only low byte */ switch ((event->message >> 24) & 0x0FF) { /* high byte of message */ case kSuspendResumeMessage: /* suspend/resume is also an activate/deactivate */ gInBackground = (event->message & kResumeMask) == 0; //DoActivate(FrontWindow(), !gInBackground); break; } break; } } /*DoEvent*/ /* This is called when an item is chosen from the menu bar (after calling MenuSelect or MenuKey). It performs the right operation for each command. It is good to have both the result of MenuSelect and MenuKey go to one routine like this to keep everything organized. */ void DoMenuCommand(long menuResult) { short menuID = HiWord(menuResult); /* the resource ID of the selected menu */ short menuItem = LoWord(menuResult); /* the item number of the selected menu */ short itemHit; Str255 daName; short daRefNum; Boolean handledByDA; switch ( menuID ) { case mApple: switch ( menuItem ) { case iAbout: /* bring up alert for About */ itemHit = Alert(rAboutAlert, nil); break; default: /* all non-About items in this menu are DAs */ /* type Str255 is an array in MPW 3 */ GetItem(GetMHandle(mApple), menuItem, daName); daRefNum = OpenDeskAcc(daName); break; } break; case mFile: switch ( menuItem ) { case iQuit: Terminate(); break; } break; } HiliteMenu(0); /* unhighlight what MenuSelect (or MenuKey) hilited */ } /*DoMenuCommand*/ #pragma segment LWUPDN void MemoryInit() { /* If you have stack requirements that differ from the default, then you could use SetApplLimit to increase StackSpace at this point, before calling MaxApplZone. */ MaxApplZone(); /* expand the heap so code segments load at the top */ //LWIP_DEBUGF(LWIP_DBG_LEVEL_WARNING, ("App Limit: %lu \n", (long)GetApplLimit() )); //LWIP_DEBUGF(LWIP_DBG_LEVEL_WARNING, ("Free Memory: %lu \n", (long)FreeMem() )); } /* Set up the whole world, including global variables, Toolbox managers, and menus. */ void MacintoshInit() { Handle menuBar; WindowPtr window; long total, contig; EventRecord event; short count; gInBackground = false; InitGraf((Ptr) &qd.thePort); InitFonts(); InitWindows(); InitMenus(); InitDialogs(nil); InitCursor(); /* Allow the default button of our alert be outlined. */ for (count = 1; count <= 3; count++) EventAvail(everyEvent, &event); SysEnvirons(kSysEnvironsVersion, &gMac); /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */ //if (gMac.machineType < 0) AlertUser(); /* 1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell in TrapAvailable if a tool trap value is out of range. */ // gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap); // if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser(); /* ZeroScrap(); */ //PurgeSpace(&total, &contig); //if (total < kMinSpace) AlertUser(); menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */ if ( menuBar == nil ) AlertUser(); SetMenuBar(menuBar); /* install menus */ DisposHandle(menuBar); AddResMenu(GetMHandle(mApple), 'DRVR'); /* add DA names to Apple menu */ DrawMenuBar(); #ifdef MACOS_BROWSER BrowserInit(); #endif } /*Initialize*/ #pragma segment Main void Terminate() { test_stop(); ExitToShell(); /* exit if no cancellation */ } /*Terminate*/ void Restart(void) { test_restart(); //UnloadSeg((Ptr) MacintoshInit); } /* Return a rectangle that is inset from the portRect by the size of the scrollbars and a little extra margin. */ void GetTERect(WindowPtr window, Rect *teRect) { *teRect = window->portRect; InsetRect(teRect, kTextMargin, kTextMargin); /* adjust for margin */ teRect->bottom = teRect->bottom - kScrollWidth; /* and for the scrollbars */ teRect->right = teRect->right - kScrollWidth; } /*GetTERect*/ /* Check to see if a window belongs to a desk accessory. */ Boolean IsDAWindow(WindowPtr window) { if ( window == nil ) return false; else /* DA windows have negative windowKinds */ return ((WindowPeek) window)->windowKind < 0; } /*IsDAWindow*/ void AlertUser() { short itemHit; SetCursor(&qd.arrow); itemHit = Alert(rUserAlert, nil); ExitToShell(); } /* AlertUser */ /* Check to see if a given trap is implemented. This is only used by the Initialize routine in this program, so we put it in the Initialize segment. The recommended approach to see if a trap is implemented is to see if the address of the trap routine is the same as the address of the Unimplemented trap. */ #pragma segment LWUPDN Boolean TrapAvailable(short tNumber, TrapType tType) { if ( ( tType == ToolTrap ) && ( gMac.machineType > envMachUnknown ) && ( gMac.machineType < envMacII ) ) { /* it's a 512KE, Plus, or SE */ tNumber = tNumber & 0x03FF; if ( tNumber > 0x01FF ) /* which means the tool traps */ tNumber = _Unimplemented; /* only go to 0x01FF */ } return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented); } /*TrapAvailable*/ \ No newline at end of file diff --git a/ports/mac/ElWhip.h b/ports/mac/ElWhip.h new file mode 100644 index 0000000..80fadfa --- /dev/null +++ b/ports/mac/ElWhip.h @@ -0,0 +1 @@ +/* * ElWhip.h * * * Created by Eric Pooch on 1/26/14. * Copyright 2014 __MyCompanyName__. All rights reserved. * */ #define kMinSize 128 /* application's minimum size (in K) */ /* We made the preferred size bigger than the minimum size by 12K, so that there would be even more room for the scrap, FKEYs, etc. */ #define kPrefSize 192 /* application's preferred size (in K) */ #define rMenuBar 128 /* application's menu bar */ #define rAboutAlert 128 /* about alert */ #define rUserAlert 129 /* error user alert */ /* kSysEnvironsVersion is passed to SysEnvirons to tell it which version of the SysEnvRec we understand. */ #define kSysEnvironsVersion 1 /* kTextMargin is the number of pixels we leave blank at the edge of the window. */ #define kTextMargin 2 /* kScrollWidth is the width of the scroll bar. */ #define kScrollWidth 15 /* kCrChar is used to match with a carriage return when calculating the number of lines in the TextEdit record. kDelChar is used to check for delete in keyDowns. */ #define kCrChar 13 #define kDelChar 8 /* kMaxTELength is an arbitrary number used to limit the length of text in the TERec so that various errors won't occur from too many characters in the text. */ #define kMaxTELength 32000 /* kOSEvent is the event number of the suspend/resume and mouse-moved events sent by MultiFinder. Once we determine that an event is an osEvent, we look at the high byte of the message sent to determine which kind it is. To differentiate suspend and resume events we check the resumeMask bit. */ #define kOSEvent app4Evt /* event used by MultiFinder */ #define kSuspendResumeMessage 1 /* high byte of suspend/resume event message */ #define kResumeMask 1 /* bit of message field for resume vs. suspend */ #define kMouseMovedMessage 0xFA /* high byte of mouse-moved event message */ #define kNoEvents 0 /* no events mask */ /* The following constants are used to identify menus and their items. The menu IDs have an "m" prefix and the item numbers within each menu have an "i" prefix. */ #define mApple 128 /* Apple menu */ #define iAbout 1 #define mFile 129 /* File menu */ /*#define iNew 1 #define iClose 4*/ #define iQuit 1 /*2*/ #define mEdit 130 /* Edit menu */ /*#define iUndo 1 #define iCut 3 #define iCopy 4 #define iPaste 5 #define iClear 6 #define mConn 131 */ /* Connection menu */ /*#define iConn 1 #define iDcon 2*/ /* 1.01 - kTopLeft - This is for positioning the Disk Initialization dialogs. */ /* #define kDITop 0x0050 #define kDILeft 0x0070 */ /* 1.01 - kMinHeap - This is the minimum result from the following equation: ORD(GetApplLimit) - ORD(ApplicZone) for the application to run. It will insure that enough memory will be around for reasonable-sized scraps, FKEYs, etc. to exist with the application, and still give the application some 'breathing room'. To derive this number, we ran under a MultiFinder partition that was our requested minimum size, as given in the 'SIZE' resource. */ #define kMinHeap 21 * 1024 /* 1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called at initialization time, for the application to run. This number acts as a double-check to insure that there really is enough memory for the application to run, including what has been taken up already by pre-loaded resources, the scrap, code, and other sundry memory blocks. */ #define kMinSpace 8 * 1024 /* kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions. */ #define kExtremeNeg -32768 #define kExtremePos 32767 - 1 /* required to address an old region bug */ /* these #defines are used to set enable/disable flags of a menu */ #define AllItems 0b1111111111111111111111111111111 /* 31 flags */ #define NoItems 0b0000000000000000000000000000000 #define MenuItem1 0b0000000000000000000000000000001 #define MenuItem2 0b0000000000000000000000000000010 #define MenuItem3 0b0000000000000000000000000000100 #define MenuItem4 0b0000000000000000000000000001000 #define MenuItem5 0b0000000000000000000000000010000 #define MenuItem6 0b0000000000000000000000000100000 #define MenuItem7 0b0000000000000000000000001000000 #define MenuItem8 0b0000000000000000000000010000000 #define MenuItem9 0b0000000000000000000000100000000 #define MenuItem10 0b0000000000000000000001000000000 #define MenuItem11 0b0000000000000000000010000000000 #define MenuItem12 0b0000000000000000000100000000000 \ No newline at end of file diff --git a/ports/mac/ElWhip.r b/ports/mac/ElWhip.r new file mode 100644 index 0000000..8aa898e --- /dev/null +++ b/ports/mac/ElWhip.r @@ -0,0 +1 @@ +/*------------------------------------------------------------------------------*/ #include "Types.r" #include "ElWhip.h" resource 'vers' (1) { 0x02, 0x00, release, 0x00, verUS, ".071", ".071, Copyright \251 Eric Pooch 2014, 2015" }; /* we use an MBAR resource to conveniently load all the menus */ resource 'MBAR' (rMenuBar, preload) { { mApple, mFile, mEdit }; /* three menus */ }; resource 'MENU' (mApple, preload) { mApple, textMenuProc, AllItems & ~MenuItem2, /* Disable dashed line, enable About and DAs */ enabled, apple, { "About ElWhipÉ", noicon, nokey, nomark, plain; "-", noicon, nokey, nomark, plain } }; resource 'MENU' (mFile, preload) { mFile, textMenuProc, AllItems, /* enable Quit only, program enables others */ enabled, "File", { /* "New", noicon, "N", nomark, plain; "Open", noicon, "O", nomark, plain; "-", noicon, nokey, nomark, plain; "Close", noicon, "W", nomark, plain; "Save", noicon, "S", nomark, plain; "Save AsÉ", noicon, nokey, nomark, plain; "Revert", noicon, nokey, nomark, plain; "-", noicon, nokey, nomark, plain; "Page SetupÉ", noicon, nokey, nomark, plain; "PrintÉ", noicon, nokey, nomark, plain; "-", noicon, nokey, nomark, plain;*/ "Quit", noicon, "Q", nomark, plain } }; resource 'MENU' (mEdit, preload) { mEdit, textMenuProc, NoItems, // disable everything, program does the enabling enabled, "Edit", { "Undo", noicon, "Z", nomark, plain; "-", noicon, nokey, nomark, plain; "Cut", noicon, "X", nomark, plain; "Copy", noicon, "C", nomark, plain; "Paste", noicon, "V", nomark, plain; "Clear", noicon, nokey, nomark, plain } }; /* this ALRT and DITL are used as an About screen */ resource 'ALRT' (rAboutAlert, purgeable) { {40, 20, 160, 300}, rAboutAlert, { /* array: 4 elements */ /* [1] */ OK, visible, silent, /* [2] */ OK, visible, silent, /* [3] */ OK, visible, silent, /* [4] */ OK, visible, silent }, centerMainScreen }; resource 'DITL' (rAboutAlert, purgeable) { { /* array DITLarray: 4 elements */ /* [1] */ {88, 180, 108, 240}, Button { enabled, "OK" }, /* [2] */ {8, 8, 24, 260}, StaticText { disabled, "El Whip with lwip networking stack" }, /* [3] */ {32, 8, 48, 260}, StaticText { disabled, " © 2014, 2015 Eric Pooch" }, /* [5] */ {56, 8, 72, 260}, StaticText { disabled, "Thanks to RetroChallenge 2014WW" } } }; /* this ALRT and DITL are used as an error screen */ resource 'ALRT' (rUserAlert, purgeable) { {40, 20, 120, 260}, rUserAlert, { /* array: 4 elements */ /* [1] */ OK, visible, silent, /* [2] */ OK, visible, silent, /* [3] */ OK, visible, silent, /* [4] */ OK, visible, silent }, centerMainScreen }; resource 'DITL' (rUserAlert, purgeable) { { /* array DITLarray: 3 elements */ /* [1] */ {50, 150, 70, 230}, Button { enabled, "OK" }, /* [2] */ {10, 60, 30, 230}, StaticText { disabled, "ElWhip - Fatal Error occurred!" }, /* [3] */ {8, 8, 40, 40}, Icon { disabled, 2 } } }; #ifdef TESTING_1234 /* here is the quintessential MultiFinder friendliness device, the SIZE resource */ resource 'SIZE' (-1) { dontSaveScreen, acceptSuspendResumeEvents, enableOptionSwitch, canBackground, /* we can background; we don't currently, but our sleep value */ /* guarantees we don't hog the Mac while we are in the background */ multiFinderAware, /* this says we do our own activate/deactivate; don't fake us out */ backgroundAndForeground, /* this is definitely not a background-only application! */ dontGetFrontClicks, /* change this is if you want "do first click" behavior like the Finder */ ignoreChildDiedEvents, /* essentially, I'm not a debugger (sub-launching) */ not32BitCompatible, /* this app should not be run in 32-bit address space */ reserved, reserved, reserved, reserved, reserved, reserved, reserved, kPrefSize * 1024, kMinSize * 1024 }; #endif \ No newline at end of file diff --git a/ports/mac/ElWhip_ICN.rsrc b/ports/mac/ElWhip_ICN.rsrc new file mode 100644 index 0000000..e69de29 diff --git a/ports/mac/Makefile b/ports/mac/Makefile new file mode 100644 index 0000000..2097be4 --- /dev/null +++ b/ports/mac/Makefile @@ -0,0 +1 @@ +# File: Makefile # Target: TestEcho (MPW 3.1 libraries), ElWhip (MPW 3.1 libraries) # Created: Sunday, November 29, 2009 11:11:08 PM # # ElWhip uses Link (rather than iLink) and the Libraries and Interfaces from MPW 3.1 # to build a program to run on System 6.08 and earlier. # Copy (or make an Alias of) the Interfaces:CIncludes and Libraries folders from MPW 3.1 # and name them Interfaces:CIncludes-3.1 and Libraries-3.1 MAKEFILE = MakeFile ¥MondoBuild¥ = {MAKEFILE} # Make blank to avoid rebuilds when makefile is modified ObjDir = : SrcDir = ::::lwip:src: IncDir = {SrcDir}include: APISrc = "{SrcDir}api:" CoreSrc = "{SrcDir}core:" IPV4Src = "{CoreSrc}ipv4:" NetISrc = "{SrcDir}netif:" PPPISrc = "{NetISrc}ppp:" ContribDir = ::: PortsDir = {ContribDir}ports: AppsDir = {ContribDir}apps: MacSrc = {PortsDir}mac: # Use the includes from MPW 3.1 Includes = ¶ -i "{CIncludes}:CIncludes-3.1:" ¶ -i {MacSrc}include: ¶ -i {MacSrc}include:arch: ¶ -i {AppsDir} ¶ -i {IncDir} ¶ -i {IncDir}lwip: ¶ -i {IncDir}ipv4: ¶ -i {IncDir}ipv6: ¶ -i {IncDir}netif: ¶ -i {AppsDir}httpserver_raw: ¶ -i {IncDir}netif:ppp: # -i {IncDir}netif:ppp:polarssl: Sym-68K = -sym off COptions = -includes unix {Includes} {Sym-68K} -mbg off -model near -opt space -w off #-includes unix #-model far LOptions = -mf -d -t 'APPL' -c 'LWIP' -model near AddDebugOpt = -d LWIP_DEBUG -u LWIP_NOASSERT NoDebugOpt = -u LWIP_DEBUG -d LWIP_NOASSERT ### Source Files ### SrcFiles = {MacSrc}test.c ¶ {MacSrc}sys_arch.c ¶ {MacSrc}sio.c ¶ # {AppsDir}tcpecho_raw:echo.c ¶ {AppsDir}httpserver_raw:httpd.c ¶ {AppsDir}httpserver_raw:fs.c ¶ {APISrc}err.c ¶ # {CoreSrc}init.c ¶ # {CoreSrc}mem.c ¶ {CoreSrc}memp.c ¶ {CoreSrc}netif.c ¶ {CoreSrc}inet_chksum.c ¶ {CoreSrc}pbuf.c ¶ {CoreSrc}raw.c ¶ # {CoreSrc}stats.c ¶ {CoreSrc}tcp_in.c ¶ {CoreSrc}tcp_out.c ¶ {CoreSrc}tcp.c ¶ # {CoreSrc}udp.c ¶ {CoreSrc}timers.c ¶ # {IPV4Src}icmp.c ¶ # {IPV4Src}igmp.c ¶ {IPV4Src}ip4.c ¶ {IPV4Src}ip4_addr.c ¶ # {IPV4Src}ip_frag.c ¶ # {NetISrc}etharp.c ¶ # {NetISrc}slipif.c ¶ {PPPISrc}ppp.c ¶ {PPPISrc}lcp.c ¶ {PPPISrc}magic.c ¶ {PPPISrc}auth.c ¶ # {PPPISrc}upap.c ¶ {PPPISrc}ipcp.c ¶ {PPPISrc}utils.c ¶ {PPPISrc}fsm.c # {PPPISrc}polarssl:md5.c ### Object Files ### ObjectFiles = "{MacSrc}sys_arch.c.l.o" ¶ "{MacSrc}sio.c.p.o" ¶ # "{AppsDir}echo.c.a.o" ¶ "{AppsDir}httpserver_raw:httpd.c.a.o" ¶ "{AppsDir}httpserver_raw:fs.c.a.o" ¶ "{SrcDir}err.c.l.o" ¶ # "{SrcDir}init.c.l.o" ¶ # "{SrcDir}mem.c.l.o" ¶ "{SrcDir}memp.c.l.o" ¶ "{SrcDir}netif.c.ud.o" ¶ "{SrcDir}inet_chksum.c.l.o" ¶ "{SrcDir}pbuf.c.l.o" ¶ "{SrcDir}raw.c.l.o" ¶ # "{SrcDir}stats.c.l.o" ¶ "{SrcDir}tcp_in.c.l.o" ¶ "{SrcDir}tcp_out.c.l.o" ¶ "{SrcDir}tcp.c.l.o" ¶ # "{SrcDir}udp.c.l.o" ¶ "{SrcDir}timers.c.l.o" ¶ # "{SrcDir}autoip.c.l.o" ¶ # "{SrcDir}icmp.c.l.o" ¶ # "{SrcDir}igmp.c.l.o" ¶ "{SrcDir}ip4.c.l.o" ¶ "{SrcDir}ip4_addr.c.l.o" ¶ # "{SrcDir}ip_frag.c.l.o" ¶ # "{NetISrc}etharp.c.l.o" ¶ # "{NetISrc}slipif.c.p.o" ¶ "{NetISrc}ppp.c.p.o" ¶ "{NetISrc}lcp.c.ud.o" ¶ "{NetISrc}magic.c.p.o" ¶ "{NetISrc}auth.c.ud.o" ¶ # "{NetISrc}upap.c.p.o" ¶ "{NetISrc}ipcp.c.ud.o" ¶ "{NetISrc}utils.c.p.o" ¶ "{NetISrc}fsm.c.ud.o" # "{NetISrc}md5.c.p.o" ### Libraries ### # Use the Libraries from MPW 3.1 CLibraries-Old = {CLibraries}::Libraries-3.1:CLibraries: Libraries-Old = {Libraries}::Libraries-3.1:Libraries: #CLibraries-Old = {CLibraries} #Libraries-Old = {Libraries LibFiles-Old = ¶ # "{CLibraries-Old}CSANELib.o" ¶ # "{CLibraries-Old}Math.o" ¶ # "{CLibraries-Old}Complex.o" ¶ "{CLibraries-Old}StdCLib.o" ¶ "{CLibraries-Old}CInterface.o" ¶ "{CLibraries-Old}CRuntime.o" ¶ # "{Libraries-Old}ToolLibs.o" ¶ # "{Libraries-Old}Runtime.o" ¶ "{Libraries-Old}Interface.o" LibFiles-68K = ¶ # "{Libraries}MathLib.o" ¶ "{CLibraries}StdCLib.o" ¶ "{Libraries}MacRuntime.o" ¶ "{Libraries}IntEnv.o" ¶ "{Libraries}Interface.o" # Special case because of the /r/n issues. "{AppsDir}httpserver_raw:httpd.c.a.o" Ä "{AppsDir}httpserver_raw:httpd.c" {C} {Deps} -o {Targ} {COptions} -noMapCR {NoDebugOpt} -seg LWAPP ### Default Rules ### .c.m.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.m.o {COptions} {NoDebugOpt} -seg Main .c.n.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.n.o {COptions} {NoDebugOpt} -seg Main -d TEST_MAIN_DISABLE .c.pp.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.pp.o {COptions} {NoDebugOpt} -seg LWPPPL .c.p.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.p.o {COptions} {NoDebugOpt} -seg LWPPP .c.ud.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.ud.o {COptions} {NoDebugOpt} -seg LWUPDN .c.a.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.a.o {COptions} {NoDebugOpt} -seg LWAPP .c.l.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.l.o {COptions} {NoDebugOpt} -seg LWTCPIP .c.o Ä .c {¥MondoBuild¥} {C} {depDir}{default}.c -o {targDir}{default}.c.o {COptions} {NoDebugOpt} -seg Main {MacSrc} Ä {MacSrc} {NetISrc} Ä {NetISrc} {PPPISrc} {SrcDir} Ä {CoreSrc} {IPV4Src} {APISrc} ### Build Rules ### TestEcho ÄÄ "{MacSrc}test.c.m.o" {ObjectFiles} {LibFiles-Old} {¥MondoBuild¥} Link ¶ -o {Targ} ¶ "{MacSrc}test.c.m.o" ¶ {ObjectFiles} ¶ {LibFiles-Old} ¶ {Sym-68K} ¶ {LOptions} If "{Sym-68K}" =~ /-sym Å[nNuU]Å/ ILinkToSYM {Targ}.NJ -mf -sym 3.2 -c 'sade' End CObjs = "{MacSrc}test.c.n.o" ¶ "{MacSrc}ElWhip.c.n.o" ¶ {ObjectFiles} ElWhip ÄÄ {CObjs} {LibFiles-Old} {¥MondoBuild¥} Link ¶ -o {Targ} ¶ {CObjs} ¶ {LibFiles-Old} ¶ {Sym-68K} ¶ {LOptions} ElWhip ÄÄ ElWhip.r ElWhip.h {¥MondoBuild¥} Rez -rd -o {Targ} ElWhip.r -append DeRez "ElWhip_ICN.rsrc" | Rez -o {Targ} -append #ElWhip-distrib Ä ElWhip DiskImg = 'Mac OS X:Users:epooch:Documents:MacOS6.dmg' ElWhip-vMac Ä ElWhip {DiskImg} Open -f 'Mac OS X:Users:epooch:Documents:MacOS6.dmg' Alert "Click OK after the volume mounts to continue..." Loop If `Exists 'MacOS6:'` Break End End Duplicate ElWhip 'MacOS6:ElWhip-vMac'; Eject MacOS6 ### Optional Dependencies ### ### Build this target to generate "include file" dependencies. ### Dependencies Ä $OutOfDate MakeDepend ¶ -append {MAKEFILE} ¶ -ignore "{CIncludes}" ¶ -objdir "{ObjDir}" ¶ -objext .o ¶ {Includes} ¶ {SrcFiles} \ No newline at end of file diff --git a/ports/mac/include/arch/cc.h b/ports/mac/include/arch/cc.h new file mode 100644 index 0000000..d06ae04 --- /dev/null +++ b/ports/mac/include/arch/cc.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __ARCH_CC_H__ +#define __ARCH_CC_H__ + + +/* Turn debugging on */ +// We define with the compiler on a per-file basis +//#define LWIP_DEBUG +//#undef LWIP_DEBUG + +#if defined LWIP_DEBUG +#include +#endif + +#define BYTE_ORDER BIG_ENDIAN + +typedef unsigned char u_char; +typedef unsigned char u8_t; +typedef signed char s8_t; +typedef unsigned short u16_t; +typedef signed short s16_t; +typedef unsigned int u32_t; +typedef signed int s32_t; + +typedef u32_t mem_ptr_t; + +#define __sio_fd_t_defined +typedef void * sio_fd_t; + +/* Compiler hints for packing structures */ +#define PACK_STRUCT_BEGIN //#pragma options align=mac68k +#define PACK_STRUCT_STRUCT +#define PACK_STRUCT_END //#pragma options align=reset +#define PACK_STRUCT_FIELD(x) x +//#define ALIGN_STRUCT_8_BEGIN #pragma options align=power +//#define ALIGN_STRUCT_END #pragma options align=reset + + +/* + * Debug printing formats + */ +#define X16_F "x" +#define U16_F "u" + +#define S16_F "d" + +#define X32_F "x" +#define U32_F "u" +#define S32_F "d" + +/* Plaform specific diagnostic output */ +#ifdef LWIP_DEBUG + +#if SER_DEBUG +/* Proto for the serial debug print function in test.c */ +void ser_debug_print( const char *fmt, ...); + +#define LWIP_PLATFORM_DIAG(x) do {ser_debug_print x;} while(0) +#else +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) +#endif + +#define LWIP_PLATFORM_ASSERT(x) LWIP_PLATFORM_DIAG(("Assertion Failed: \"%s\" at line %d in %s\n", \ + x, __LINE__, __FILE__)) + +#define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ + LWIP_PLATFORM_DIAG(("Error: %s", message)); handler;}} while(0) + +#else + +#define LWIP_PLATFORM_DIAG(x) +#define LWIP_PLATFORM_ASSERT(x) +#endif + + +/* +#define LWIP_PLATFORM_DIAG(x) +#define LWIP_PLATFORM_DIAG(x) lwip_debug_print x +#define LWIP_PLATFORM_DIAG(x) do {printf x;} while(0) + +#define LWIP_PLATFORM_ASSERT(x) lwip_debug_print( "Assertion \"%s\" failed at line %d in %s\n", \ + x, __LINE__, __FILE__) +*/ + +#endif /* __ARCH_CC_H__ */ diff --git a/ports/mac/include/arch/macos_debug.h b/ports/mac/include/arch/macos_debug.h new file mode 100644 index 0000000..329511a --- /dev/null +++ b/ports/mac/include/arch/macos_debug.h @@ -0,0 +1 @@ +/* * macos_debug.h * * * Created by Eric Pooch on 2/1/15. * Copyright 2015 Eric Pooch. All rights reserved. * * #include "arch/macos_debug.h" instead of debug.h to take advantage of dialog boxes, etc. */ /* MAC_DIALOG DEF? NO-> LWIP_DEBUGF DEF? NO-> Nothing YES YES v v printf() SER_DEBUG ? -NO-> printf() -> Mac dialog box v YES Mac dialog box |-> ser_debug_print() -> Printer port */ #define MAC_DIALOG #undef LWIP_DEBUG #if defined MAC_DIALOG #include #include "lwip/opt.h" #endif /* MAC_DLOGF: Enable modal dialog notices. * Not for use in timing sensitive portions of code. * Use MACOS_STATE to send the buffer. */ #ifndef MACOS_DEBUG #define MACOS_DEBUG (LWIP_DBG_ON | LWIP_DBG_LEVEL_WARNING) #define MACOS_TRACE (LWIP_DBG_OFF | LWIP_DBG_TRACE ) #define MACOS_STATE (LWIP_DBG_ON | LWIP_DBG_STATE | LWIP_DBG_MASK_LEVEL) #endif #ifdef MACOS_DIALOG #define MACOS_DLOGF(debug, message) do { printf message; if (debug & LWIP_DBG_STATE) { fflush(stdout); } } while (0) #define LWIP_ERROR(message, expression, handler) do { if (!(expression)) { \ MACOS_DLOGF(LWIP_DBG_STATE, ("Error: %s", message)); handler;}} while(0) #else #define MACOS_DLOGF(debug, message) LWIP_DEBUGF(debug, message) #endif /*MAC_DIALOG*/ \ No newline at end of file diff --git a/ports/mac/include/arch/perf.h b/ports/mac/include/arch/perf.h new file mode 100644 index 0000000..e4ced30 --- /dev/null +++ b/ports/mac/include/arch/perf.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __ARCH_PERF_H__ +#define __ARCH_PERF_H__ + +/*#include */ + +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ + +#if 0 +void perf_print(unsigned long c1l, unsigned long c1h, + unsigned long c2l, unsigned long c2h, + char *key); + +void perf_print_times(struct tms *start, struct tms *end, char *key); + +void perf_init(char *fname); +#endif + +#endif /* __ARCH_PERF_H__ */ diff --git a/ports/mac/include/arch/sys_arch.h b/ports/mac/include/arch/sys_arch.h new file mode 100644 index 0000000..74dd7f0 --- /dev/null +++ b/ports/mac/include/arch/sys_arch.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __SYS_MAC_H__ +#define __SYS_MAC_H__ + +#define SYS_MBOX_NULL 0 + +typedef u8_t sys_sem_t; +typedef u8_t sys_mutex_t; +typedef u8_t sys_mbox_t; + +typedef int sys_thread_t; + +#endif /* __SYS_MAC_H__ */ diff --git a/ports/mac/include/fsdata_custom.c b/ports/mac/include/fsdata_custom.c new file mode 100644 index 0000000..289bd09 --- /dev/null +++ b/ports/mac/include/fsdata_custom.c @@ -0,0 +1 @@ +/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels * */ #include "lwip/opt.h" #include "lwip/def.h" #include "fs.h" #include "fsdata.h" #include #include #include #include #define FS_ROOT NULL #define FS_FILE_BUFF_SIZE 4096 #if !HTTPD_PRECALCULATED_CHECKSUM static char *fileBuff; static unsigned int fileBuffSize; #endif /* HTTPD_PRECALCULATED_CHECKSUM */ /*-----------------------------------------------------------------------------------*/ void fs_close_custom(struct fs_file *file) { OSErr error; #if HTTPD_PRECALCULATED_CHECKSUM && LWIP_HTTPD_DYNAMIC_FILE_READ /* Slyly store the file reference in the checksum */ long refNum = (long)file->chksum_count; error = FSClose(refNum); LWIP_ERROR("Unable to close File", (error == noErr ), return;); LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("fs_close_custom()\n")); #endif } /*-----------------------------------------------------------------------------------*/ int fs_path_to_mac(char *path_string) { char *curr_loc = path_string; /* HFS Only */ curr_loc = strchr(curr_loc, '/'); while (curr_loc != NULL) { *curr_loc = ':'; curr_loc = strchr(curr_loc, '/'); } } /*-----------------------------------------------------------------------------------*/ #if HTTPD_PRECALCULATED_CHECKSUM && LWIP_HTTPD_DYNAMIC_FILE_READ int fs_open_custom(struct fs_file *file, const char *name) { OSErr error = fsDSIntErr; long readCount; Str255 pName; short vRefNum = 0; short refNum; char firstChar; /* Only open files with an extension for 'security'.*/ if ( strchr(name, '.') == NULL ) return 0; /* Convert file name to pascal string. */ strncpy((char *)pName, name, 255); //fs_path_to_mac((char *)pName); pName[0] = (char)strlen(name)-1; /* Overwrite the first character which is a ':' or '/' */ /* Open the file. */ error = FSOpen(pName, vRefNum, &refNum); if (error != noErr) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("FSopen() error:%d\n", error)); return 0; } /* Figure out how long the file is. */ error = GetEOF(refNum, &readCount); file->len = readCount; file->index = 0; file->pextension = NULL; /* Slyly store the file reference in the checksum. */ file->chksum_count = (u16_t)refNum; //file->http_header_included = false; /* Check if the first letter of the file is 'H' which indicates that the HTTP header is included. This doesn't work because if LWIP_HTTPD_DYNAMIC_FILE_READ is enabled, the file is not read until after http_init_file which is where the header is separated. */ readCount = 1; error = FSRead(refNum, &readCount, &firstChar); LWIP_ERROR(("Unable to read file."), (error == noErr), fs_close_custom(file); return 0;); file->http_header_included = (firstChar == 'H'); /* Reset to start of file. */ error = SetFPos(refNum, fsFromStart, 0); return 1; } #else /*HTTPD_PRECALCULATED_CHECKSUM*/ /*-----------------------------------------------------------------------------------*/ int fs_open_custom(struct fs_file *file, const char *name) { OSErr error = fsDSIntErr; long readCount; Str255 pName; short vRefNum = 0; short refNum; /* Only open files with an extension for 'security'.*/ if ( strchr(name, '.') == NULL ) return 0; /* Allocate a file buffer, if necessary.*/ if (fileBuff == NULL) { for (fileBuffSize = FS_FILE_BUFF_SIZE; fileBuff == NULL && fileBuffSize >= 512; fileBuffSize /= 2) { fileBuff = (char *)malloc(fileBuffSize); } LWIP_ERROR(("Unable to allocate memory for file buffer."), (fileBuff != NULL), return 0;); } file->data = fileBuff; /* Convert file name to pascal string. */ strncpy((char *)pName, name, 255); //fs_path_to_mac((char *)pName); pName[0] = (char)strlen(name)-1; /* Overwrite the first character which is a ':' or '/' */ /* Open the file. */ error = FSOpen(pName, vRefNum, &refNum); if (error != noErr) { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("FSopen() error:%d\n", error)); return 0; } /* Figure out how long the file is. */ error = GetEOF(refNum, &readCount); LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("GetEOF readCount:%d\n", readCount)); LWIP_ERROR(("File is too big to load."), (file->len < fileBuffSize), readCount = fileBuffSize;); /* Read the file. */ error = FSRead(refNum, &readCount, (char *)file->data); LWIP_ERROR(("FSRead() error"), (error == noErr), return 1;); LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_TRACE, ("FSRead readCount:%d\n", readCount)); file->len = readCount; file->index = file->len; file->pextension = NULL; file->http_header_included = true; if (file->data[0] != 'H') { LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("Warning: Header Not Included in File: %P\n", name)); file->http_header_included = false; } /* Close the file. */ error = FSClose(refNum); LWIP_ERROR("Unable to close File", (error == noErr ), return;); return 1; } #endif /*HTTPD_PRECALCULATED_CHECKSUM*/ #if HTTPD_PRECALCULATED_CHECKSUM && LWIP_HTTPD_DYNAMIC_FILE_READ /* Set these as 0, so that the methods in fs.c are eliminated, and we can use our own. */ #define LWIP_HTTPD_DYNAMIC_FILE_READ 0 #define LWIP_HTTPD_FS_ASYNC_READ 0 int fs_read(struct fs_file *file, char *buffer, int count) { OSErr error = fsDSIntErr; long readCount = (long)count; short refNum = (short)file->chksum_count; if (file->index >= file->len) { return FS_READ_EOF; } else if ((file->index + count) > file->len) { readCount = (long)(file->len - file->index); } error = FSRead(refNum, &readCount, buffer); LWIP_ERROR(("FSRead() error\n"), (error == noErr), LWIP_DEBUGF(HTTPD_DEBUG | LWIP_DBG_LEVEL_WARNING, ("FSRead() error:%d\n", error)); return FS_READ_EOF;); file->index += readCount; return((int)readCount); } #endif /*HTTPD_PRECALCULATED_CHECKSUM*/ \ No newline at end of file diff --git a/ports/mac/include/lwipopts-SLIP.h b/ports/mac/include/lwipopts-SLIP.h new file mode 100644 index 0000000..7846833 --- /dev/null +++ b/ports/mac/include/lwipopts-SLIP.h @@ -0,0 +1,1332 @@ +/** + * @file + * + * lwIP Options Configuration + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +/* + * The lwIP stack configuration file. + * This is based on the lwip/opts.h file. + */ + +/* + ----------------------------------------------- + ---------- Platform specific locking ---------- + ----------------------------------------------- +*/ + +/** + * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain + * critical regions during buffer allocation, deallocation and memory + * allocation and deallocation. + */ +#ifndef SYS_LIGHTWEIGHT_PROT +#define SYS_LIGHTWEIGHT_PROT 0 +#endif + +/** + * NO_SYS==1: Provides VERY minimal functionality. Otherwise, + * use lwIP facilities. + */ +#ifndef NO_SYS +#define NO_SYS 1 +#endif + +/* + ------------------------------------ + ---------- Memory options ---------- + ------------------------------------ +*/ +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library + * instead of the lwip internal allocator. Can save code size if you + * already use it. + */ +#ifndef MEM_LIBC_MALLOC +#define MEM_LIBC_MALLOC 1 +#endif + +/** +* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. +* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution +* speed and usage from interrupts! +*/ +#ifndef MEMP_MEM_MALLOC +#define MEMP_MEM_MALLOC 1 +#endif + +/** + * MEM_ALIGNMENT: should be set to the alignment of the CPU + * 4 byte alignment -> #define MEM_ALIGNMENT 4 + * 2 byte alignment -> #define MEM_ALIGNMENT 2 + */ +#ifndef MEM_ALIGNMENT +#define MEM_ALIGNMENT 4 +#endif + +/** + * MEM_SIZE: the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#ifndef MEM_SIZE +#define MEM_SIZE (2*1024) +#endif + + +/* + --------------------------------- + ---------- ARP options ---------- + --------------------------------- +*/ +/** + * LWIP_ARP==1: Enable ARP functionality. + */ +#ifndef LWIP_ARP +#define LWIP_ARP 0 +#endif + + +/* + -------------------------------- + ---------- IP options ---------- + -------------------------------- +*/ +/** + * IP_FORWARD==1: Enables the ability to forward IP packets across network + * interfaces. If you are going to run lwIP on a device with only one network + * interface, define this to 0. + */ +#ifndef IP_FORWARD +#define IP_FORWARD 0 +#endif + +/** + * IP_OPTIONS_ALLOWED: Defines the behavior for IP options. + * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. + * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). + */ +#ifndef IP_OPTIONS_ALLOWED +#define IP_OPTIONS_ALLOWED 0 +#endif + +/** + * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that + * this option does not affect outgoing packet sizes, which can be controlled + * via IP_FRAG. + */ +#ifndef IP_REASSEMBLY +#define IP_REASSEMBLY 0 +#endif + +/** + * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note + * that this option does not affect incoming packet sizes, which can be + * controlled via IP_REASSEMBLY. + */ +#ifndef IP_FRAG +#define IP_FRAG 0 +#endif + + +/* + ---------------------------------- + ---------- ICMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_ICMP==1: Enable ICMP module inside the IP stack. + * Be careful, disable that make your product non-compliant to RFC1122 + */ +#ifndef LWIP_ICMP +#define LWIP_ICMP 0 +#endif + + +/* + --------------------------------- + ---------- RAW options ---------- + --------------------------------- +*/ +/** + * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. + */ +#ifndef LWIP_RAW +#define LWIP_RAW 1 +#endif + + +/* + ---------------------------------- + ---------- SNMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP + * transport. + */ +#ifndef LWIP_SNMP +#define LWIP_SNMP 0 +#endif + + +/* + ---------------------------------- + ---------- IGMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_IGMP==1: Turn on IGMP module. + */ +#ifndef LWIP_IGMP +#define LWIP_IGMP 0 +#endif + +/* + ---------------------------------- + ---------- DNS options ----------- + ---------------------------------- +*/ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#ifndef LWIP_DNS +#define LWIP_DNS 0 +#endif + +/** DNS maximum number of entries to maintain locally. */ +#ifndef DNS_TABLE_SIZE +#define DNS_TABLE_SIZE 4 +#endif + +/** DNS maximum host name length supported in the name table. */ +#ifndef DNS_MAX_NAME_LENGTH +#define DNS_MAX_NAME_LENGTH 256 +#endif + +/** The maximum of DNS servers */ +#ifndef DNS_MAX_SERVERS +#define DNS_MAX_SERVERS 2 +#endif + +/** DNS do a name checking between the query and the response. */ +#ifndef DNS_DOES_NAME_CHECK +#define DNS_DOES_NAME_CHECK 1 +#endif + +/** DNS message max. size. Default value is RFC compliant. */ +#ifndef DNS_MSG_SIZE +#define DNS_MSG_SIZE 512 +#endif + +/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, + * you have to define + * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} + * (an array of structs name/address, where address is an u32_t in network + * byte order). + * + * Instead, you can also use an external function: + * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) + * that returns the IP address or INADDR_NONE if not found. + */ +#ifndef DNS_LOCAL_HOSTLIST +#define DNS_LOCAL_HOSTLIST 0 +#endif /* DNS_LOCAL_HOSTLIST */ + +/** If this is turned on, the local host-list can be dynamically changed + * at runtime. */ +#ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +/* + --------------------------------- + ---------- UDP options ---------- + --------------------------------- +*/ +/** + * LWIP_UDP==1: Turn on UDP. + */ +#ifndef LWIP_UDP +#define LWIP_UDP 0 +#endif + +/** + * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) + */ +#ifndef LWIP_UDPLITE +#define LWIP_UDPLITE 0 +#endif + + +/* + --------------------------------- + ---------- TCP options ---------- + --------------------------------- +*/ +/** + * LWIP_TCP==1: Turn on TCP. + */ +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif + +/** + * TCP_WND: The size of a TCP window. This must be at least + * (2 * TCP_MSS) for things to work well + */ +#ifndef TCP_WND +#define TCP_WND (2 * TCP_MSS) +#endif + +/** + * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. + * Define to 0 if your device is low on memory. + */ +#ifndef TCP_QUEUE_OOSEQ +#define TCP_QUEUE_OOSEQ 0 +//(LWIP_TCP) +#endif + +/** + * TCP_MSS: TCP Maximum segment size. (default is 536, a conservative default, + * you might want to increase this.) + * For the receive side, this MSS is advertised to the remote side + * when opening a connection. For the transmit size, this MSS sets + * an upper limit on the MSS advertised by the remote host. + */ +#ifndef TCP_MSS +#define TCP_MSS 536 +#endif + +/** + * TCP_SND_BUF: TCP sender buffer space (bytes). + * To achieve good performance, this should be at least 2 * TCP_MSS. + */ +#ifndef TCP_SND_BUF +#define TCP_SND_BUF (2 * TCP_MSS) +#endif + +/** + * LWIP_TCP_TIMESTAMPS==1: support the TCP timestamp option. + */ +#ifndef LWIP_TCP_TIMESTAMPS +#define LWIP_TCP_TIMESTAMPS 0 +#endif + +/** + * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1. + * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all + * events (accept, sent, etc) that happen in the system. + * LWIP_CALLBACK_API==1: The PCB callback function is called directly + * for the event. This is the default. + */ +#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) +#define LWIP_EVENT_API 0 +#define LWIP_CALLBACK_API 1 +#endif + + +/* + ---------------------------------- + ---------- Pbuf options ---------- + ---------------------------------- +*/ +/** + * PBUF_LINK_HLEN: the number of bytes that should be allocated for a + * link level header. The default is 14, the standard value for + * Ethernet. + */ +#ifndef PBUF_LINK_HLEN +#define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) +#endif + +/** + * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is + * designed to accomodate single full size TCP frame in one pbuf, including + * TCP_MSS, IP header, and link header. + */ +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN) +#endif + +/* + ------------------------------------------------ + ---------- Network Interfaces options ---------- + ------------------------------------------------ +*/ +/** + * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname + * field. + */ +#ifndef LWIP_NETIF_HOSTNAME +#define LWIP_NETIF_HOSTNAME 0 +#endif + +/** + * LWIP_NETIF_API==1: Support netif api (in netifapi.c) + */ +#ifndef LWIP_NETIF_API +#define LWIP_NETIF_API 0 +#endif + +/** + * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface + * changes its up/down status (i.e., due to DHCP IP acquistion) + */ +#ifndef LWIP_NETIF_STATUS_CALLBACK +#define LWIP_NETIF_STATUS_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface + * whenever the link changes (i.e., link down) + */ +#ifndef LWIP_NETIF_LINK_CALLBACK +#define LWIP_NETIF_LINK_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_REMOVE_CALLBACK==1: Support a callback function that is called + * when a netif has been removed + */ +#ifndef LWIP_NETIF_REMOVE_CALLBACK +#define LWIP_NETIF_REMOVE_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP + * address equal to the netif IP address, looping them back up the stack. + */ +#ifndef LWIP_NETIF_LOOPBACK +#define LWIP_NETIF_LOOPBACK 0 +#endif + +/** + * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback + * sending for each netif (0 = disabled) + */ +#ifndef LWIP_LOOPBACK_MAX_PBUFS +#define LWIP_LOOPBACK_MAX_PBUFS 0 +#endif + + +/** + * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data + * to be sent into one single pbuf. This is for compatibility with DMA-enabled + * MACs that do not support scatter-gather. + * Beware that this might involve CPU-memcpy before transmitting that would not + * be needed without this flag! Use this only if you need to! + * + * @todo: TCP and IP-frag do not work with this, yet: + */ +#ifndef LWIP_NETIF_TX_SINGLE_PBUF +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + +/* + ------------------------------------ + ---------- LOOPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c + */ +#ifndef LWIP_HAVE_LOOPIF +#define LWIP_HAVE_LOOPIF 0 +#endif + +/* + ------------------------------------ + ---------- SLIPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c + */ +#ifndef LWIP_HAVE_SLIPIF +#define LWIP_HAVE_SLIPIF 1 +#endif + +/* + ---------------------------------------------- + ---------- Sequential layer options ---------- + ---------------------------------------------- +*/ +/** + * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) + */ +#ifndef LWIP_NETCONN +#define LWIP_NETCONN (NO_SYS==0) +#endif + +/** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout to create + * timers running in tcpip_thread from another thread. + */ +#ifndef LWIP_TCPIP_TIMEOUT +#define LWIP_TCPIP_TIMEOUT 0 +#endif + +/* + ------------------------------------ + ---------- Socket options ---------- + ------------------------------------ +*/ +/** + * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) + */ +#define LWIP_SOCKET (NO_SYS==0) + +/** + * LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names. + * (only used if you use sockets.c) + */ +#define LWIP_COMPAT_SOCKETS (NO_SYS==0) + +/** + * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names. + * Disable this option if you use a POSIX operating system that uses the same + * names (read, write & close). (only used if you use sockets.c) + */ +#define LWIP_POSIX_SOCKETS_IO_NAMES (LWIP_SOCKET) + +/** + * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT + * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set + * in seconds. (does not require sockets.c, and will affect tcp.c) + */ +#ifndef LWIP_TCP_KEEPALIVE +#define LWIP_TCP_KEEPALIVE 0 +#endif + +/** + * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and + * SO_SNDTIMEO processing. + */ +#ifndef LWIP_SO_SNDTIMEO +#define LWIP_SO_SNDTIMEO 0 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and + * SO_RCVTIMEO processing. + */ +#ifndef LWIP_SO_RCVTIMEO +#define LWIP_SO_RCVTIMEO 0 +#endif + +/** + * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. + */ +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 0 +#endif + +/** + * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. + */ +#ifndef RECV_BUFSIZE_DEFAULT +#define RECV_BUFSIZE_DEFAULT INT_MAX +#endif + +/** + * SO_REUSE==1: Enable SO_REUSEADDR option. + */ +#ifndef SO_REUSE +#define SO_REUSE 0 +#endif + +/** + * SO_REUSE_RXTOALL==1: Pass a copy of incoming broadcast/multicast packets + * to all local matches if SO_REUSEADDR is turned on. + * WARNING: Adds a memcpy for every packet if passing to more than one pcb! + */ +#ifndef SO_REUSE_RXTOALL +#define SO_REUSE_RXTOALL 0 +#endif + +/** + * LWIP_FIONREAD_LINUXMODE==0 (default): ioctl/FIONREAD returns the amount of + * pending data in the network buffer. This is the way windows does it. It's + * the default for lwIP since it is smaller. + * LWIP_FIONREAD_LINUXMODE==1: ioctl/FIONREAD returns the size of the next + * pending datagram in bytes. This is the way linux does it. This code is only + * here for compatibility. + */ +#ifndef LWIP_FIONREAD_LINUXMODE +#define LWIP_FIONREAD_LINUXMODE 0 +#endif + +/* + ---------------------------------------- + ---------- Statistics options ---------- + ---------------------------------------- +*/ +/** + * LWIP_STATS==1: Enable statistics collection in lwip_stats. + */ +#ifndef LWIP_STATS +#define LWIP_STATS 0 +#endif + +#if LWIP_STATS + +/** + * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. + */ +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 0 +#endif + +/** + * LINK_STATS==1: Enable link stats. + */ +#ifndef LINK_STATS +#define LINK_STATS 1 +#endif + +/** + * ETHARP_STATS==1: Enable etharp stats. + */ +#ifndef ETHARP_STATS +#define ETHARP_STATS (LWIP_ARP) +#endif + +/** + * IP_STATS==1: Enable IP stats. + */ +#ifndef IP_STATS +#define IP_STATS 1 +#endif + +/** + * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is + * on if using either frag or reass. + */ +#ifndef IPFRAG_STATS +#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) +#endif + +/** + * ICMP_STATS==1: Enable ICMP stats. + */ +#ifndef ICMP_STATS +#define ICMP_STATS 1 +#endif + +/** + * IGMP_STATS==1: Enable IGMP stats. + */ +#ifndef IGMP_STATS +#define IGMP_STATS (LWIP_IGMP) +#endif + +/** + * UDP_STATS==1: Enable UDP stats. Default is on if + * UDP enabled, otherwise off. + */ +#ifndef UDP_STATS +#define UDP_STATS (LWIP_UDP) +#endif + +/** + * TCP_STATS==1: Enable TCP stats. Default is on if TCP + * enabled, otherwise off. + */ +#ifndef TCP_STATS +#define TCP_STATS (LWIP_TCP) +#endif + +/** + * MEM_STATS==1: Enable mem.c stats. + */ +#ifndef MEM_STATS +#define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) +#endif + +/** + * MEMP_STATS==1: Enable memp.c pool stats. + */ +#ifndef MEMP_STATS +#define MEMP_STATS (MEMP_MEM_MALLOC == 0) +#endif + +/** + * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). + */ +#ifndef SYS_STATS +#define SYS_STATS (NO_SYS == 0) +#endif + +/** + * IP6_STATS==1: Enable IPv6 stats. + */ +#ifndef IP6_STATS +#define IP6_STATS (LWIP_IPV6) +#endif + +/** + * ICMP6_STATS==1: Enable ICMP for IPv6 stats. + */ +#ifndef ICMP6_STATS +#define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6) +#endif + +/** + * IP6_FRAG_STATS==1: Enable IPv6 fragmentation stats. + */ +#ifndef IP6_FRAG_STATS +#define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS)) +#endif + +/** + * MLD6_STATS==1: Enable MLD for IPv6 stats. + */ +#ifndef MLD6_STATS +#define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD) +#endif + +/** + * ND6_STATS==1: Enable Neighbor discovery for IPv6 stats. + */ +#ifndef ND6_STATS +#define ND6_STATS (LWIP_IPV6) +#endif + +#else + +#define LINK_STATS 0 +#define IP_STATS 0 +#define IPFRAG_STATS 0 +#define ICMP_STATS 0 +#define IGMP_STATS 0 +#define UDP_STATS 0 +#define TCP_STATS 0 +#define MEM_STATS 0 +#define MEMP_STATS 0 +#define SYS_STATS 0 +#define LWIP_STATS_DISPLAY 0 +#define IP6_STATS 0 +#define ICMP6_STATS 0 +#define IP6_FRAG_STATS 0 +#define MLD6_STATS 0 +#define ND6_STATS 0 + +#endif /* LWIP_STATS */ + +/* + --------------------------------- + ---------- PPP options ---------- + --------------------------------- +*/ +/** + * PPP_SUPPORT==1: Enable PPP. + */ +#define PPP_SUPPORT 0 + +/** + * PPPOS_SUPPORT==1: Enable PPP Over Serial + */ +#define PPPOS_SUPPORT PPP_SUPPORT + +#if PPP_SUPPORT + +#define PPP_NOTIFY_PHASE 1 + +/** + * PPP_INPROC_MULTITHREADED==1 call ppp_input() using tcpip_callback(). + * Set this to 0 if pppos_input() is called inside tcpip_thread or with NO_SYS==1. + * Default is 1 for NO_SYS==0 (multithreaded) and 0 for NO_SYS==1 (single-threaded). + */ +#define PPP_INPROC_MULTITHREADED (NO_SYS==0) + +/** + * LWIP_PPP_API==1: Support PPP API (in pppapi.c) + */ +#define LWIP_PPP_API 0 + +/** + * PAP_SUPPORT==1: Support PAP. + */ +#define PAP_SUPPORT 0 + +/** + * CHAP_SUPPORT==1: Support CHAP. + */ +#define CHAP_SUPPORT 0 + +/** + * MSCHAP_SUPPORT==1: Support MSCHAP. + */ +#define MSCHAP_SUPPORT 0 +#if MSCHAP_SUPPORT +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 /* MSCHAP require CHAP support */ +#endif /* MSCHAP_SUPPORT */ + +#if PAP_SUPPORT || CHAP_SUPPORT +#define PPP_AUTH 1 +#else +#define PPP_AUTH 0 +#endif + +#undef PPP_OPTIONS + +/** + * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. + */ +#define LQR_SUPPORT 0 + +/** + * VJ_SUPPORT==1: Support VJ header compression. + */ +#define VJ_SUPPORT 0 +#if !PPPOS_SUPPORT +#undef VJ_SUPPORT +#define VJ_SUPPORT 0 /* Only PPPoS may need VJ compression */ +#endif /* !PPPOS_SUPPORT */ + +/** + * PPP_MD5_RANDM==1: Use MD5 for better randomness. Automatically enabled if CHAP or L2TP AUTH support is enabled. + */ +#define PPP_MD5_RANDM 0 +#if CHAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT +#undef PPP_MD5_RANDM +#define PPP_MD5_RANDM 1 /* MD5 Random is required for CHAP and L2TP AUTH */ +#endif /* CHAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT */ + +#undef PPP_FCS_TABLE +#undef PPP_PROTOCOLNAME + +/** + * PolarSSL library, used if necessary and not previously disabled + * + * + * lwIP contains some files fetched from the latest BSD release of + * the PolarSSL project 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: + * + * The following defines are available for flexibility: + * + * LWIP_INCLUDED_POLARSSL_MD4 ; Use lwIP internal PolarSSL for MD4 + * LWIP_INCLUDED_POLARSSL_MD5 ; Use lwIP internal PolarSSL for MD5 + * LWIP_INCLUDED_POLARSSL_SHA1 ; Use lwIP internal PolarSSL for SHA1 + * LWIP_INCLUDED_POLARSSL_DES ; Use lwIP internal PolarSSL for DES + * + * If set (=1), the default if required by another enabled PPP feature unless + * explicitly set to 0, using included lwIP PolarSSL. + * + * If clear (=0), using external PolarSSL. + * + * Undefined if not needed. + * + * Beware of the stack requirements which can be a lot larger if you are not + * using our cleaned PolarSSL library. + */ + +#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM +#define LWIP_INCLUDED_POLARSSL_MD5 1 /* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ +#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ + +#if MSCHAP_SUPPORT +#define LWIP_INCLUDED_POLARSSL_MD4 1 /* MSCHAP require MD4 support */ +#define LWIP_INCLUDED_POLARSSL_SHA1 1 /* MSCHAP require SHA1 support */ +#define LWIP_INCLUDED_POLARSSL_DES 1 /* MSCHAP require DES support */ +#endif /* MSCHAP_SUPPORT */ + +/* + * Timeouts + */ +#define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */ +#define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ +#define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ +#define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ +#define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ +#define UPAP_DEFTRANSMITS 10 /* Maximum number of auth-reqs to send */ + +#if PPP_SERVER +#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#endif /* PPP_SERVER */ + +#define CHAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ +#define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */ + +#if PPP_SERVER +#define CHAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#endif /* PPP_SERVER */ + +#define EAP_DEFREQTIME 6 /* Time to wait for peer request */ +#define EAP_DEFALLOWREQ 10 /* max # times to accept requests */ + +#if PPP_SERVER +#define EAP_DEFTIMEOUT 6 /* Timeout (seconds) for rexmit */ +#define EAP_DEFTRANSMITS 10 /* max # times to transmit */ +#endif /* PPP_SERVER */ + +/* Default number of times we receive our magic number from the peer + before deciding the link is looped-back. */ +#define LCP_DEFLOOPBACKFAIL 10 + +/* Interval in seconds between keepalive echo requests, 0 to disable. */ +#define LCP_ECHOINTERVAL 0 + +/* Number of unanswered echo requests before failure. */ +#define LCP_MAXECHOFAILS 3 + +/* Max Xmit idle time (in jiffies) before resend flag char. */ +#define PPP_MAXIDLEFLAG 100 + +/* + * Packet sizes + * + * Note - lcp shouldn't be allowed to negotiate stuff outside these + * limits. See lcp.h in the pppd directory. + * (XXX - these constants should simply be shared by lcp.c instead + * of living in lcp.h) + */ +#define PPP_MTU 1500 /* Default MTU (size of Info field) */ +/* #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) */ +#define PPP_MAXMTU 1500 /* Largest MTU we allow */ +#define PPP_MINMTU 64 +#define PPP_MRU 1500 /* default MRU = max length of info field */ +#define PPP_MAXMRU 1500 /* Largest MRU we allow */ +#define PPP_DEFMRU 296 /* Try for this */ +#define PPP_MINMRU 128 /* No MRUs below this */ + +#define MAXNAMELEN 256 /* max length of hostname or name for auth */ +#define MAXSECRETLEN 256 /* max length of password or secret */ + +#endif /* PPP_SUPPORT */ + +/* + -------------------------------------- + ---------- Checksum options ---------- + -------------------------------------- +*/ +/** + * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. + */ +#define CHECKSUM_GEN_IP 1 + +/** + * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. + */ +#define CHECKSUM_GEN_UDP 0 + +/** + * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. + */ +#define CHECKSUM_GEN_TCP 1 + +/** + * CHECKSUM_GEN_ICMP==1: Generate checksums in software for outgoing ICMP packets. + */ +#define CHECKSUM_GEN_ICMP 1 + +/** + * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. + */ +#define CHECKSUM_CHECK_IP 0 + +/** + * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. + */ +#define CHECKSUM_CHECK_UDP 0 + +/** + * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. + */ +#define CHECKSUM_CHECK_TCP 0 + +/** + * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from + * application buffers to pbufs. + */ +#define LWIP_CHECKSUM_ON_COPY 0 + +/* + --------------------------------------- + ---------- IPv6 options --------------- + --------------------------------------- +*/ +/** + * LWIP_IPV6==1: Enable IPv6 + */ +#define LWIP_IPV6 0 + +/* + --------------------------------------- + ---------- Hook options --------------- + --------------------------------------- +*/ + +/* Hooks are undefined by default, define them to a function if you need them. */ + +/** + * LWIP_HOOK_IP4_INPUT(pbuf, input_netif): + * - called from ip_input() (IPv4) + * - pbuf: received struct pbuf passed to ip_input() + * - input_netif: struct netif on which the packet has been received + * Return values: + * - 0: Hook has not consumed the packet, packet is processed as normal + * - != 0: Hook has consumed the packet. + * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook + * (i.e. free it when done). + */ + +/** + * LWIP_HOOK_IP4_ROUTE(dest): + * - called from ip_route() (IPv4) + * - dest: destination IPv4 address + * Returns the destination netif or NULL if no destination netif is found. In + * that case, ip_route() continues as normal. + */ + +/* + --------------------------------------- + ---------- Debugging options ---------- + --------------------------------------- +*/ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + */ +#ifndef LWIP_DBG_MIN_LEVEL +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_WARNING +//LWIP_DBG_LEVEL_ALL + +//WARNING +// +#endif + +/** + * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable + * debug messages of certain types. + */ +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON LWIP_DBG_ON +//(LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_ON) +//LWIP_DBG_ON +#endif + +/** + * ETHARP_DEBUG: Enable debugging in etharp.c. + */ +#ifndef ETHARP_DEBUG +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif + +/** + * NETIF_DEBUG: Enable debugging in netif.c. + */ +#ifndef NETIF_DEBUG +#define NETIF_DEBUG LWIP_DBG_ON +#endif + +/** + * PBUF_DEBUG: Enable debugging in pbuf.c. + */ +#ifndef PBUF_DEBUG +#define PBUF_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_LIB_DEBUG: Enable debugging in api_lib.c. + */ +#ifndef API_LIB_DEBUG +#define API_LIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_MSG_DEBUG: Enable debugging in api_msg.c. + */ +#ifndef API_MSG_DEBUG +#define API_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SOCKETS_DEBUG: Enable debugging in sockets.c. + */ +#ifndef SOCKETS_DEBUG +#define SOCKETS_DEBUG LWIP_DBG_OFF +#endif + +/** + * ICMP_DEBUG: Enable debugging in icmp.c. + */ +#ifndef ICMP_DEBUG +#define ICMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * IGMP_DEBUG: Enable debugging in igmp.c. + */ +#ifndef IGMP_DEBUG +#define IGMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * INET_DEBUG: Enable debugging in inet.c. + */ +#ifndef INET_DEBUG +#define INET_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP_DEBUG: Enable debugging for IP. + */ +#ifndef IP_DEBUG +#define IP_DEBUG LWIP_DBG_OFF +//LWIP_DBG_OFF +#endif + +/** + * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. + */ +#ifndef IP_REASS_DEBUG +#define IP_REASS_DEBUG LWIP_DBG_OFF +#endif + +/** + * RAW_DEBUG: Enable debugging in raw.c. + */ +#ifndef RAW_DEBUG +#define RAW_DEBUG LWIP_DBG_ON +#endif + +/** + * MEM_DEBUG: Enable debugging in mem.c. + */ +#ifndef MEM_DEBUG +#define MEM_DEBUG LWIP_DBG_OFF +#endif + +/** + * MEMP_DEBUG: Enable debugging in memp.c. + */ +#ifndef MEMP_DEBUG +#define MEMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SYS_DEBUG: Enable debugging in sys.c. + */ +#ifndef SYS_DEBUG +#define SYS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TIMERS_DEBUG: Enable debugging in timers.c. + */ +#ifndef TIMERS_DEBUG +#define TIMERS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_DEBUG: Enable debugging for TCP. + */ +#ifndef TCP_DEBUG +#define TCP_DEBUG LWIP_DBG_ON +#endif + +/** + * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. + */ +#ifndef TCP_INPUT_DEBUG +#define TCP_INPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. + */ +#ifndef TCP_FR_DEBUG +#define TCP_FR_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit + * timeout. + */ +#ifndef TCP_RTO_DEBUG +#define TCP_RTO_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. + */ +#ifndef TCP_CWND_DEBUG +#define TCP_CWND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. + */ +#ifndef TCP_WND_DEBUG +#define TCP_WND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. + */ +#ifndef TCP_OUTPUT_DEBUG +#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. + */ +#ifndef TCP_RST_DEBUG +#define TCP_RST_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. + */ +#ifndef TCP_QLEN_DEBUG +#define TCP_QLEN_DEBUG LWIP_DBG_OFF +#endif + +/** + * UDP_DEBUG: Enable debugging in UDP. + */ +#ifndef UDP_DEBUG +#define UDP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCPIP_DEBUG: Enable debugging in tcpip.c. + */ +#ifndef TCPIP_DEBUG +#define TCPIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * PPP_DEBUG: Enable debugging for PPP. + */ +#ifndef PPP_DEBUG +#define PPP_DEBUG LWIP_DBG_OFF +//(LWIP_DBG_ON | LWIP_DBG_LEVEL_WARNING) +#endif + + +/** + * SLIP_DEBUG: Enable debugging in slipif.c. + */ +#ifndef SLIP_DEBUG +#define SLIP_DEBUG LWIP_DBG_ON +#endif + +/** + * DHCP_DEBUG: Enable debugging in dhcp.c. + */ +#ifndef DHCP_DEBUG +#define DHCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * AUTOIP_DEBUG: Enable debugging in autoip.c. + */ +#ifndef AUTOIP_DEBUG +#define AUTOIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MSG_DEBUG: Enable debugging for SNMP messages. + */ +#ifndef SNMP_MSG_DEBUG +#define SNMP_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. + */ +#ifndef SNMP_MIB_DEBUG +#define SNMP_MIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * DNS_DEBUG: Enable debugging for DNS. + */ +#ifndef DNS_DEBUG +#define DNS_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP6_DEBUG: Enable debugging for IPv6. + */ +#ifndef IP6_DEBUG +#define IP6_DEBUG LWIP_DBG_OFF +#endif + +/** + * SIO_DEBUG: Enable debugging for Serial I/O. + */ +#define SIO_DEBUG LWIP_DBG_OFF +#define SIO_TRACE (LWIP_DBG_TRACE | LWIP_DBG_OFF) +#define SIO_STATE (LWIP_DBG_STATE | LWIP_DBG_MASK_LEVEL | LWIP_DBG_OFF) + +/** + * MAC_DEBUG: Enable debugging for Macintosh. + */ +#define MAC_DEBUG LWIP_DBG_ON +#define MAC_TRACE (LWIP_DBG_TRACE | LWIP_DBG_OFF) +#define MAC_STATE (LWIP_DBG_STATE | LWIP_DBG_MASK_LEVEL | LWIP_DBG_ON) + + +#define MAC_SIO_BUFF_SIZE 512 + +#define SER_DEBUG 1 + +/** + * HTTPD Options: + */ +#define LWIP_HTTPD_APP 1 +#define HTTPD_POLL_INTERVAL 4 +//#define HTTPD_USE_CUSTOM_FSDATA 1 +#define HTTPD_DEBUG LWIP_DBG_OFF + +#define PRINTPKT_SUPPORT 0 + +#endif /* __LWIPOPTS_H__ */ diff --git a/ports/mac/include/lwipopts.h b/ports/mac/include/lwipopts.h new file mode 100644 index 0000000..d43b706 --- /dev/null +++ b/ports/mac/include/lwipopts.h @@ -0,0 +1,1364 @@ +/** + * @file + * + * lwIP Options Configuration + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +/* + * The lwIP stack configuration file. + * This is based on the lwip/opts.h file. + */ + +/* + ----------------------------------------------- + ---------- Platform specific locking ---------- + ----------------------------------------------- +*/ + +/** + * SYS_LIGHTWEIGHT_PROT==1: if you want inter-task protection for certain + * critical regions during buffer allocation, deallocation and memory + * allocation and deallocation. + */ +#ifndef SYS_LIGHTWEIGHT_PROT +#define SYS_LIGHTWEIGHT_PROT 0 +#endif + +/** + * NO_SYS==1: Provides VERY minimal functionality. Otherwise, + * use lwIP facilities. + */ +#ifndef NO_SYS +#define NO_SYS 1 +#endif + +/* + ------------------------------------ + ---------- Memory options ---------- + ------------------------------------ +*/ +/** + * MEM_LIBC_MALLOC==1: Use malloc/free/realloc provided by your C-library + * instead of the lwip internal allocator. Can save code size if you + * already use it. + */ +#ifndef MEM_LIBC_MALLOC +#define MEM_LIBC_MALLOC 1 +#endif + +/** +* MEMP_MEM_MALLOC==1: Use mem_malloc/mem_free instead of the lwip pool allocator. +* Especially useful with MEM_LIBC_MALLOC but handle with care regarding execution +* speed and usage from interrupts! +*/ +#ifndef MEMP_MEM_MALLOC +#define MEMP_MEM_MALLOC 1 +#endif + +/** + * MEM_ALIGNMENT: should be set to the alignment of the CPU + * 4 byte alignment -> #define MEM_ALIGNMENT 4 + * 2 byte alignment -> #define MEM_ALIGNMENT 2 + */ +#ifndef MEM_ALIGNMENT +#define MEM_ALIGNMENT 4 +#endif + +/** + * MEM_SIZE: the size of the heap memory. If the application will send + * a lot of data that needs to be copied, this should be set high. + */ +#ifndef MEM_SIZE +#define MEM_SIZE (2*1024) +#endif + + +/* + --------------------------------- + ---------- ARP options ---------- + --------------------------------- +*/ +/** + * LWIP_ARP==1: Enable ARP functionality. + */ +#ifndef LWIP_ARP +#define LWIP_ARP 0 +#endif + + +/* + -------------------------------- + ---------- IP options ---------- + -------------------------------- +*/ +/** + * IP_FORWARD==1: Enables the ability to forward IP packets across network + * interfaces. If you are going to run lwIP on a device with only one network + * interface, define this to 0. + */ +#ifndef IP_FORWARD +#define IP_FORWARD 0 +#endif + +/** + * IP_OPTIONS_ALLOWED: Defines the behavior for IP options. + * IP_OPTIONS_ALLOWED==0: All packets with IP options are dropped. + * IP_OPTIONS_ALLOWED==1: IP options are allowed (but not parsed). + */ +#ifndef IP_OPTIONS_ALLOWED +#define IP_OPTIONS_ALLOWED 0 +#endif + +/** + * IP_REASSEMBLY==1: Reassemble incoming fragmented IP packets. Note that + * this option does not affect outgoing packet sizes, which can be controlled + * via IP_FRAG. + */ +#ifndef IP_REASSEMBLY +#define IP_REASSEMBLY 0 +#endif + +/** + * IP_FRAG==1: Fragment outgoing IP packets if their size exceeds MTU. Note + * that this option does not affect incoming packet sizes, which can be + * controlled via IP_REASSEMBLY. + */ +#ifndef IP_FRAG +#define IP_FRAG 0 +#endif + + +/* + ---------------------------------- + ---------- ICMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_ICMP==1: Enable ICMP module inside the IP stack. + * Be careful, disable that make your product non-compliant to RFC1122 + */ +#ifndef LWIP_ICMP +#define LWIP_ICMP 0 +#endif + + +/* + --------------------------------- + ---------- RAW options ---------- + --------------------------------- +*/ +/** + * LWIP_RAW==1: Enable application layer to hook into the IP layer itself. + */ +#ifndef LWIP_RAW +#define LWIP_RAW 1 +#endif + + +/* + ---------------------------------- + ---------- SNMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_SNMP==1: Turn on SNMP module. UDP must be available for SNMP + * transport. + */ +#ifndef LWIP_SNMP +#define LWIP_SNMP 0 +#endif + + +/* + ---------------------------------- + ---------- IGMP options ---------- + ---------------------------------- +*/ +/** + * LWIP_IGMP==1: Turn on IGMP module. + */ +#ifndef LWIP_IGMP +#define LWIP_IGMP 0 +#endif + +/* + ---------------------------------- + ---------- DNS options ----------- + ---------------------------------- +*/ +/** + * LWIP_DNS==1: Turn on DNS module. UDP must be available for DNS + * transport. + */ +#ifndef LWIP_DNS +#define LWIP_DNS 0 +#endif + +/** DNS maximum number of entries to maintain locally. */ +#ifndef DNS_TABLE_SIZE +#define DNS_TABLE_SIZE 4 +#endif + +/** DNS maximum host name length supported in the name table. */ +#ifndef DNS_MAX_NAME_LENGTH +#define DNS_MAX_NAME_LENGTH 256 +#endif + +/** The maximum of DNS servers */ +#ifndef DNS_MAX_SERVERS +#define DNS_MAX_SERVERS 2 +#endif + +/** DNS do a name checking between the query and the response. */ +#ifndef DNS_DOES_NAME_CHECK +#define DNS_DOES_NAME_CHECK 1 +#endif + +/** DNS message max. size. Default value is RFC compliant. */ +#ifndef DNS_MSG_SIZE +#define DNS_MSG_SIZE 512 +#endif + +/** DNS_LOCAL_HOSTLIST: Implements a local host-to-address list. If enabled, + * you have to define + * #define DNS_LOCAL_HOSTLIST_INIT {{"host1", 0x123}, {"host2", 0x234}} + * (an array of structs name/address, where address is an u32_t in network + * byte order). + * + * Instead, you can also use an external function: + * #define DNS_LOOKUP_LOCAL_EXTERN(x) extern u32_t my_lookup_function(const char *name) + * that returns the IP address or INADDR_NONE if not found. + */ +#ifndef DNS_LOCAL_HOSTLIST +#define DNS_LOCAL_HOSTLIST 0 +#endif /* DNS_LOCAL_HOSTLIST */ + +/** If this is turned on, the local host-list can be dynamically changed + * at runtime. */ +#ifndef DNS_LOCAL_HOSTLIST_IS_DYNAMIC +#define DNS_LOCAL_HOSTLIST_IS_DYNAMIC 0 +#endif /* DNS_LOCAL_HOSTLIST_IS_DYNAMIC */ + +/* + --------------------------------- + ---------- UDP options ---------- + --------------------------------- +*/ +/** + * LWIP_UDP==1: Turn on UDP. + */ +#ifndef LWIP_UDP +#define LWIP_UDP 0 +#endif + +/** + * LWIP_UDPLITE==1: Turn on UDP-Lite. (Requires LWIP_UDP) + */ +#ifndef LWIP_UDPLITE +#define LWIP_UDPLITE 0 +#endif + + +/* + --------------------------------- + ---------- TCP options ---------- + --------------------------------- +*/ +/** + * LWIP_TCP==1: Turn on TCP. + */ +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif + +/** + * TCP_WND: The size of a TCP window. This must be at least + * (2 * TCP_MSS) for things to work well + */ +#ifndef TCP_WND +#define TCP_WND (2 * TCP_MSS) +#endif + +/** + * TCP_QUEUE_OOSEQ==1: TCP will queue segments that arrive out of order. + * Define to 0 if your device is low on memory. + */ +#ifndef TCP_QUEUE_OOSEQ +#define TCP_QUEUE_OOSEQ 0 +//(LWIP_TCP) +#endif + +/** + * TCP_MSS: TCP Maximum segment size. (default is 536, a conservative default, + * you might want to increase this.) + * For the receive side, this MSS is advertised to the remote side + * when opening a connection. For the transmit size, this MSS sets + * an upper limit on the MSS advertised by the remote host. + */ +#ifndef TCP_MSS +#define TCP_MSS 536 +#endif + +/** + * TCP_SND_BUF: TCP sender buffer space (bytes). + * To achieve good performance, this should be at least 2 * TCP_MSS. + */ +#ifndef TCP_SND_BUF +#define TCP_SND_BUF (2 * TCP_MSS) +#endif + +/** + * LWIP_TCP_TIMESTAMPS==1: support the TCP timestamp option. + */ +#ifndef LWIP_TCP_TIMESTAMPS +#define LWIP_TCP_TIMESTAMPS 0 +#endif + +/** + * LWIP_EVENT_API and LWIP_CALLBACK_API: Only one of these should be set to 1. + * LWIP_EVENT_API==1: The user defines lwip_tcp_event() to receive all + * events (accept, sent, etc) that happen in the system. + * LWIP_CALLBACK_API==1: The PCB callback function is called directly + * for the event. This is the default. + */ +#if !defined(LWIP_EVENT_API) && !defined(LWIP_CALLBACK_API) +#define LWIP_EVENT_API 0 +#define LWIP_CALLBACK_API 1 +#endif + + +/* + ---------------------------------- + ---------- Pbuf options ---------- + ---------------------------------- +*/ +/** + * PBUF_LINK_HLEN: the number of bytes that should be allocated for a + * link level header. The default is 14, the standard value for + * Ethernet. + */ +#ifndef PBUF_LINK_HLEN +#define PBUF_LINK_HLEN (14 + ETH_PAD_SIZE) +#endif + +/** + * PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. The default is + * designed to accomodate single full size TCP frame in one pbuf, including + * TCP_MSS, IP header, and link header. + */ +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS+40+PBUF_LINK_HLEN) +#endif + +/* + ------------------------------------------------ + ---------- Network Interfaces options ---------- + ------------------------------------------------ +*/ +/** + * LWIP_NETIF_HOSTNAME==1: use DHCP_OPTION_HOSTNAME with netif's hostname + * field. + */ +#ifndef LWIP_NETIF_HOSTNAME +#define LWIP_NETIF_HOSTNAME 0 +#endif + +/** + * LWIP_NETIF_API==1: Support netif api (in netifapi.c) + */ +#ifndef LWIP_NETIF_API +#define LWIP_NETIF_API 0 +#endif + +/** + * LWIP_NETIF_STATUS_CALLBACK==1: Support a callback function whenever an interface + * changes its up/down status (i.e., due to DHCP IP acquistion) + */ +#ifndef LWIP_NETIF_STATUS_CALLBACK +#define LWIP_NETIF_STATUS_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_LINK_CALLBACK==1: Support a callback function from an interface + * whenever the link changes (i.e., link down) + */ +#ifndef LWIP_NETIF_LINK_CALLBACK +#define LWIP_NETIF_LINK_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_REMOVE_CALLBACK==1: Support a callback function that is called + * when a netif has been removed + */ +#ifndef LWIP_NETIF_REMOVE_CALLBACK +#define LWIP_NETIF_REMOVE_CALLBACK 0 +#endif + +/** + * LWIP_NETIF_LOOPBACK==1: Support sending packets with a destination IP + * address equal to the netif IP address, looping them back up the stack. + */ +#ifndef LWIP_NETIF_LOOPBACK +#define LWIP_NETIF_LOOPBACK 0 +#endif + +/** + * LWIP_LOOPBACK_MAX_PBUFS: Maximum number of pbufs on queue for loopback + * sending for each netif (0 = disabled) + */ +#ifndef LWIP_LOOPBACK_MAX_PBUFS +#define LWIP_LOOPBACK_MAX_PBUFS 0 +#endif + + +/** + * LWIP_NETIF_TX_SINGLE_PBUF: if this is set to 1, lwIP tries to put all data + * to be sent into one single pbuf. This is for compatibility with DMA-enabled + * MACs that do not support scatter-gather. + * Beware that this might involve CPU-memcpy before transmitting that would not + * be needed without this flag! Use this only if you need to! + * + * @todo: TCP and IP-frag do not work with this, yet: + */ +#ifndef LWIP_NETIF_TX_SINGLE_PBUF +#define LWIP_NETIF_TX_SINGLE_PBUF 0 +#endif /* LWIP_NETIF_TX_SINGLE_PBUF */ + +/* + ------------------------------------ + ---------- LOOPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_LOOPIF==1: Support loop interface (127.0.0.1) and loopif.c + */ +#ifndef LWIP_HAVE_LOOPIF +#define LWIP_HAVE_LOOPIF 0 +#endif + +/* + ------------------------------------ + ---------- SLIPIF options ---------- + ------------------------------------ +*/ +/** + * LWIP_HAVE_SLIPIF==1: Support slip interface and slipif.c + */ +#ifndef LWIP_HAVE_SLIPIF +#define LWIP_HAVE_SLIPIF 0 +#endif + +/* + ---------------------------------------------- + ---------- Sequential layer options ---------- + ---------------------------------------------- +*/ +/** + * LWIP_NETCONN==1: Enable Netconn API (require to use api_lib.c) + */ +#ifndef LWIP_NETCONN +#define LWIP_NETCONN (NO_SYS==0) +#endif + +/** LWIP_TCPIP_TIMEOUT==1: Enable tcpip_timeout/tcpip_untimeout to create + * timers running in tcpip_thread from another thread. + */ +#ifndef LWIP_TCPIP_TIMEOUT +#define LWIP_TCPIP_TIMEOUT 0 +#endif + +/* + ------------------------------------ + ---------- Socket options ---------- + ------------------------------------ +*/ +/** + * LWIP_SOCKET==1: Enable Socket API (require to use sockets.c) + */ +#define LWIP_SOCKET (NO_SYS==0) + +/** + * LWIP_COMPAT_SOCKETS==1: Enable BSD-style sockets functions names. + * (only used if you use sockets.c) + */ +#define LWIP_COMPAT_SOCKETS (NO_SYS==0) + +/** + * LWIP_POSIX_SOCKETS_IO_NAMES==1: Enable POSIX-style sockets functions names. + * Disable this option if you use a POSIX operating system that uses the same + * names (read, write & close). (only used if you use sockets.c) + */ +#define LWIP_POSIX_SOCKETS_IO_NAMES (LWIP_SOCKET) + +/** + * LWIP_TCP_KEEPALIVE==1: Enable TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT + * options processing. Note that TCP_KEEPIDLE and TCP_KEEPINTVL have to be set + * in seconds. (does not require sockets.c, and will affect tcp.c) + */ +#ifndef LWIP_TCP_KEEPALIVE +#define LWIP_TCP_KEEPALIVE 0 +#endif + +/** + * LWIP_SO_SNDTIMEO==1: Enable send timeout for sockets/netconns and + * SO_SNDTIMEO processing. + */ +#ifndef LWIP_SO_SNDTIMEO +#define LWIP_SO_SNDTIMEO 0 +#endif + +/** + * LWIP_SO_RCVTIMEO==1: Enable receive timeout for sockets/netconns and + * SO_RCVTIMEO processing. + */ +#ifndef LWIP_SO_RCVTIMEO +#define LWIP_SO_RCVTIMEO 0 +#endif + +/** + * LWIP_SO_RCVBUF==1: Enable SO_RCVBUF processing. + */ +#ifndef LWIP_SO_RCVBUF +#define LWIP_SO_RCVBUF 0 +#endif + +/** + * If LWIP_SO_RCVBUF is used, this is the default value for recv_bufsize. + */ +#ifndef RECV_BUFSIZE_DEFAULT +#define RECV_BUFSIZE_DEFAULT INT_MAX +#endif + +/** + * SO_REUSE==1: Enable SO_REUSEADDR option. + */ +#ifndef SO_REUSE +#define SO_REUSE 0 +#endif + +/** + * SO_REUSE_RXTOALL==1: Pass a copy of incoming broadcast/multicast packets + * to all local matches if SO_REUSEADDR is turned on. + * WARNING: Adds a memcpy for every packet if passing to more than one pcb! + */ +#ifndef SO_REUSE_RXTOALL +#define SO_REUSE_RXTOALL 0 +#endif + +/** + * LWIP_FIONREAD_LINUXMODE==0 (default): ioctl/FIONREAD returns the amount of + * pending data in the network buffer. This is the way windows does it. It's + * the default for lwIP since it is smaller. + * LWIP_FIONREAD_LINUXMODE==1: ioctl/FIONREAD returns the size of the next + * pending datagram in bytes. This is the way linux does it. This code is only + * here for compatibility. + */ +#ifndef LWIP_FIONREAD_LINUXMODE +#define LWIP_FIONREAD_LINUXMODE 0 +#endif + +/* + ---------------------------------------- + ---------- Statistics options ---------- + ---------------------------------------- +*/ +/** + * LWIP_STATS==1: Enable statistics collection in lwip_stats. + */ +#ifndef LWIP_STATS +#define LWIP_STATS 0 +#endif + +#if LWIP_STATS + +/** + * LWIP_STATS_DISPLAY==1: Compile in the statistics output functions. + */ +#ifndef LWIP_STATS_DISPLAY +#define LWIP_STATS_DISPLAY 0 +#endif + +/** + * LINK_STATS==1: Enable link stats. + */ +#ifndef LINK_STATS +#define LINK_STATS 1 +#endif + +/** + * ETHARP_STATS==1: Enable etharp stats. + */ +#ifndef ETHARP_STATS +#define ETHARP_STATS (LWIP_ARP) +#endif + +/** + * IP_STATS==1: Enable IP stats. + */ +#ifndef IP_STATS +#define IP_STATS 1 +#endif + +/** + * IPFRAG_STATS==1: Enable IP fragmentation stats. Default is + * on if using either frag or reass. + */ +#ifndef IPFRAG_STATS +#define IPFRAG_STATS (IP_REASSEMBLY || IP_FRAG) +#endif + +/** + * ICMP_STATS==1: Enable ICMP stats. + */ +#ifndef ICMP_STATS +#define ICMP_STATS 1 +#endif + +/** + * IGMP_STATS==1: Enable IGMP stats. + */ +#ifndef IGMP_STATS +#define IGMP_STATS (LWIP_IGMP) +#endif + +/** + * UDP_STATS==1: Enable UDP stats. Default is on if + * UDP enabled, otherwise off. + */ +#ifndef UDP_STATS +#define UDP_STATS (LWIP_UDP) +#endif + +/** + * TCP_STATS==1: Enable TCP stats. Default is on if TCP + * enabled, otherwise off. + */ +#ifndef TCP_STATS +#define TCP_STATS (LWIP_TCP) +#endif + +/** + * MEM_STATS==1: Enable mem.c stats. + */ +#ifndef MEM_STATS +#define MEM_STATS ((MEM_LIBC_MALLOC == 0) && (MEM_USE_POOLS == 0)) +#endif + +/** + * MEMP_STATS==1: Enable memp.c pool stats. + */ +#ifndef MEMP_STATS +#define MEMP_STATS (MEMP_MEM_MALLOC == 0) +#endif + +/** + * SYS_STATS==1: Enable system stats (sem and mbox counts, etc). + */ +#ifndef SYS_STATS +#define SYS_STATS (NO_SYS == 0) +#endif + +/** + * IP6_STATS==1: Enable IPv6 stats. + */ +#ifndef IP6_STATS +#define IP6_STATS (LWIP_IPV6) +#endif + +/** + * ICMP6_STATS==1: Enable ICMP for IPv6 stats. + */ +#ifndef ICMP6_STATS +#define ICMP6_STATS (LWIP_IPV6 && LWIP_ICMP6) +#endif + +/** + * IP6_FRAG_STATS==1: Enable IPv6 fragmentation stats. + */ +#ifndef IP6_FRAG_STATS +#define IP6_FRAG_STATS (LWIP_IPV6 && (LWIP_IPV6_FRAG || LWIP_IPV6_REASS)) +#endif + +/** + * MLD6_STATS==1: Enable MLD for IPv6 stats. + */ +#ifndef MLD6_STATS +#define MLD6_STATS (LWIP_IPV6 && LWIP_IPV6_MLD) +#endif + +/** + * ND6_STATS==1: Enable Neighbor discovery for IPv6 stats. + */ +#ifndef ND6_STATS +#define ND6_STATS (LWIP_IPV6) +#endif + +#else + +#define LINK_STATS 0 +#define IP_STATS 0 +#define IPFRAG_STATS 0 +#define ICMP_STATS 0 +#define IGMP_STATS 0 +#define UDP_STATS 0 +#define TCP_STATS 0 +#define MEM_STATS 0 +#define MEMP_STATS 0 +#define SYS_STATS 0 +#define LWIP_STATS_DISPLAY 0 +#define IP6_STATS 0 +#define ICMP6_STATS 0 +#define IP6_FRAG_STATS 0 +#define MLD6_STATS 0 +#define ND6_STATS 0 + +#endif /* LWIP_STATS */ + +/* + --------------------------------- + ---------- PPP options ---------- + --------------------------------- +*/ +/** + * PPP_SUPPORT==1: Enable PPP. + */ +#define PPP_SUPPORT 1 + +/** + * PPPOS_SUPPORT==1: Enable PPP Over Serial + */ +#define PPPOS_SUPPORT PPP_SUPPORT + +#if PPP_SUPPORT + +#define PPP_NOTIFY_PHASE 1 + +/** + * PPP_INPROC_MULTITHREADED==1 call ppp_input() using tcpip_callback(). + * Set this to 0 if pppos_input() is called inside tcpip_thread or with NO_SYS==1. + * Default is 1 for NO_SYS==0 (multithreaded) and 0 for NO_SYS==1 (single-threaded). + */ +#define PPP_INPROC_MULTITHREADED (NO_SYS==0) + +/** + * LWIP_PPP_API==1: Support PPP API (in pppapi.c) + */ +#define LWIP_PPP_API 0 + +/** + * PAP_SUPPORT==1: Support PAP. + */ +#define PAP_SUPPORT 0 + +/** + * CHAP_SUPPORT==1: Support CHAP. + */ +#define CHAP_SUPPORT 0 + +/** + * MSCHAP_SUPPORT==1: Support MSCHAP. + */ +#define MSCHAP_SUPPORT 0 +#if MSCHAP_SUPPORT +#undef CHAP_SUPPORT +#define CHAP_SUPPORT 1 /* MSCHAP require CHAP support */ +#endif /* MSCHAP_SUPPORT */ + +#if PAP_SUPPORT || CHAP_SUPPORT +#define PPP_AUTH 1 +#else +#define PPP_AUTH 0 +#endif + +#undef PPP_OPTIONS + +/** + * LQR_SUPPORT==1: Support Link Quality Report. Do nothing except exchanging some LCP packets. + */ +#define LQR_SUPPORT 0 + +/** + * VJ_SUPPORT==1: Support VJ header compression. + */ +#define VJ_SUPPORT 0 +#if !PPPOS_SUPPORT +#undef VJ_SUPPORT +#define VJ_SUPPORT 0 /* Only PPPoS may need VJ compression */ +#endif /* !PPPOS_SUPPORT */ + +/** + * PPP_MD5_RANDM==1: Use MD5 for better randomness. Automatically enabled if CHAP or L2TP AUTH support is enabled. + */ +#define PPP_MD5_RANDM 0 +#if CHAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT +#undef PPP_MD5_RANDM +#define PPP_MD5_RANDM 1 /* MD5 Random is required for CHAP and L2TP AUTH */ +#endif /* CHAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT */ + +#undef PPP_FCS_TABLE +#undef PPP_PROTOCOLNAME + +/** + * PolarSSL library, used if necessary and not previously disabled + * + * + * lwIP contains some files fetched from the latest BSD release of + * the PolarSSL project 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: + * + * The following defines are available for flexibility: + * + * LWIP_INCLUDED_POLARSSL_MD4 ; Use lwIP internal PolarSSL for MD4 + * LWIP_INCLUDED_POLARSSL_MD5 ; Use lwIP internal PolarSSL for MD5 + * LWIP_INCLUDED_POLARSSL_SHA1 ; Use lwIP internal PolarSSL for SHA1 + * LWIP_INCLUDED_POLARSSL_DES ; Use lwIP internal PolarSSL for DES + * + * If set (=1), the default if required by another enabled PPP feature unless + * explicitly set to 0, using included lwIP PolarSSL. + * + * If clear (=0), using external PolarSSL. + * + * Undefined if not needed. + * + * Beware of the stack requirements which can be a lot larger if you are not + * using our cleaned PolarSSL library. + */ + +#if CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM +#define LWIP_INCLUDED_POLARSSL_MD5 1 /* CHAP, EAP, L2TP AUTH and MD5 Random require MD5 support */ +#endif /* CHAP_SUPPORT || EAP_SUPPORT || PPPOL2TP_AUTH_SUPPORT || PPP_MD5_RANDM */ + +#if MSCHAP_SUPPORT +#define LWIP_INCLUDED_POLARSSL_MD4 1 /* MSCHAP require MD4 support */ +#define LWIP_INCLUDED_POLARSSL_SHA1 1 /* MSCHAP require SHA1 support */ +#define LWIP_INCLUDED_POLARSSL_DES 1 /* MSCHAP require DES support */ +#endif /* MSCHAP_SUPPORT */ + +/* + * Timeouts + */ +#define FSM_DEFTIMEOUT 6 /* Timeout time in seconds */ +#define FSM_DEFMAXTERMREQS 2 /* Maximum Terminate-Request transmissions */ +#define FSM_DEFMAXCONFREQS 10 /* Maximum Configure-Request transmissions */ +#define FSM_DEFMAXNAKLOOPS 5 /* Maximum number of nak loops */ +#define UPAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ +#define UPAP_DEFTRANSMITS 10 /* Maximum number of auth-reqs to send */ + +#if PPP_SERVER +#define UPAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#endif /* PPP_SERVER */ + +#define CHAP_DEFTIMEOUT 6 /* Timeout (seconds) for retransmitting req */ +#define CHAP_DEFTRANSMITS 10 /* max # times to send challenge */ + +#if PPP_SERVER +#define CHAP_DEFREQTIME 30 /* Time to wait for auth-req from peer */ +#endif /* PPP_SERVER */ + +#define EAP_DEFREQTIME 6 /* Time to wait for peer request */ +#define EAP_DEFALLOWREQ 10 /* max # times to accept requests */ + +#if PPP_SERVER +#define EAP_DEFTIMEOUT 6 /* Timeout (seconds) for rexmit */ +#define EAP_DEFTRANSMITS 10 /* max # times to transmit */ +#endif /* PPP_SERVER */ + +/* Default number of times we receive our magic number from the peer + before deciding the link is looped-back. */ +#define LCP_DEFLOOPBACKFAIL 10 + +/* Interval in seconds between keepalive echo requests, 0 to disable. */ +/* We need to disable this since we bring down AUTH, FSM, LCP and IPCP after startup to save memory */ +#define LCP_ECHOINTERVAL 0 + +/* Number of unanswered echo requests before failure. */ +#define LCP_MAXECHOFAILS 3 + +/* Max Xmit idle time (in jiffies) before resend flag char. */ +#define PPP_MAXIDLEFLAG 100 + +/* + * Packet sizes + * + * Note - lcp shouldn't be allowed to negotiate stuff outside these + * limits. See lcp.h in the pppd directory. + * (XXX - these constants should simply be shared by lcp.c instead + * of living in lcp.h) + */ +#define PPP_MTU 1500 /* Default MTU (size of Info field) */ +/* #define PPP_MAXMTU 65535 - (PPP_HDRLEN + PPP_FCSLEN) */ +#define PPP_MAXMTU 1500 /* Largest MTU we allow */ +#define PPP_MINMTU 64 +#define PPP_MRU 1500 /* default MRU = max length of info field */ +#define PPP_MAXMRU 1500 /* Largest MRU we allow */ +#define PPP_DEFMRU 296 /* Try for this */ +#define PPP_MINMRU 128 /* No MRUs below this */ + +#define MAXNAMELEN 256 /* max length of hostname or name for auth */ +#define MAXSECRETLEN 256 /* max length of password or secret */ + +#endif /* PPP_SUPPORT */ + +/* + -------------------------------------- + ---------- Checksum options ---------- + -------------------------------------- +*/ +/** + * CHECKSUM_GEN_IP==1: Generate checksums in software for outgoing IP packets. + */ +#define CHECKSUM_GEN_IP 1 + +/** + * CHECKSUM_GEN_UDP==1: Generate checksums in software for outgoing UDP packets. + */ +#define CHECKSUM_GEN_UDP 0 + +/** + * CHECKSUM_GEN_TCP==1: Generate checksums in software for outgoing TCP packets. + */ +#define CHECKSUM_GEN_TCP 1 + +/** + * CHECKSUM_GEN_ICMP==1: Generate checksums in software for outgoing ICMP packets. + */ +#define CHECKSUM_GEN_ICMP 1 + +/** + * CHECKSUM_CHECK_IP==1: Check checksums in software for incoming IP packets. + */ +#define CHECKSUM_CHECK_IP 0 + +/** + * CHECKSUM_CHECK_UDP==1: Check checksums in software for incoming UDP packets. + */ +#define CHECKSUM_CHECK_UDP 0 + +/** + * CHECKSUM_CHECK_TCP==1: Check checksums in software for incoming TCP packets. + */ +#define CHECKSUM_CHECK_TCP 0 + +/** + * LWIP_CHECKSUM_ON_COPY==1: Calculate checksum when copying data from + * application buffers to pbufs. + */ +#define LWIP_CHECKSUM_ON_COPY 0 + +/* + --------------------------------------- + ---------- IPv6 options --------------- + --------------------------------------- +*/ +/** + * LWIP_IPV6==1: Enable IPv6 + */ +#define LWIP_IPV6 0 + +/* + --------------------------------------- + ---------- Hook options --------------- + --------------------------------------- +*/ + +/* Hooks are undefined by default, define them to a function if you need them. */ + +/** + * LWIP_HOOK_IP4_INPUT(pbuf, input_netif): + * - called from ip_input() (IPv4) + * - pbuf: received struct pbuf passed to ip_input() + * - input_netif: struct netif on which the packet has been received + * Return values: + * - 0: Hook has not consumed the packet, packet is processed as normal + * - != 0: Hook has consumed the packet. + * If the hook consumed the packet, 'pbuf' is in the responsibility of the hook + * (i.e. free it when done). + */ + +/** + * LWIP_HOOK_IP4_ROUTE(dest): + * - called from ip_route() (IPv4) + * - dest: destination IPv4 address + * Returns the destination netif or NULL if no destination netif is found. In + * that case, ip_route() continues as normal. + */ + +/* + --------------------------------------- + ---------- Debugging options ---------- + --------------------------------------- +*/ +/** + * LWIP_DBG_MIN_LEVEL: After masking, the value of the debug is + * compared against this value. If it is smaller, then debugging + * messages are written. + */ +#ifndef LWIP_DBG_MIN_LEVEL +#define LWIP_DBG_MIN_LEVEL LWIP_DBG_LEVEL_WARNING +//LWIP_DBG_LEVEL_ALL + +#endif + +/** + * LWIP_DBG_TYPES_ON: A mask that can be used to globally enable/disable + * debug messages of certain types. + */ +#ifndef LWIP_DBG_TYPES_ON +#define LWIP_DBG_TYPES_ON (LWIP_DBG_TRACE|LWIP_DBG_STATE|LWIP_DBG_ON) + +//LWIP_DBG_ON +#endif + +/** + * ETHARP_DEBUG: Enable debugging in etharp.c. + */ +#ifndef ETHARP_DEBUG +#define ETHARP_DEBUG LWIP_DBG_OFF +#endif + +/** + * NETIF_DEBUG: Enable debugging in netif.c. + */ +#ifndef NETIF_DEBUG +#define NETIF_DEBUG LWIP_DBG_OFF +#endif + +/** + * PBUF_DEBUG: Enable debugging in pbuf.c. + */ +#ifndef PBUF_DEBUG +#define PBUF_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_LIB_DEBUG: Enable debugging in api_lib.c. + */ +#ifndef API_LIB_DEBUG +#define API_LIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * API_MSG_DEBUG: Enable debugging in api_msg.c. + */ +#ifndef API_MSG_DEBUG +#define API_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SOCKETS_DEBUG: Enable debugging in sockets.c. + */ +#ifndef SOCKETS_DEBUG +#define SOCKETS_DEBUG LWIP_DBG_OFF +#endif + +/** + * ICMP_DEBUG: Enable debugging in icmp.c. + */ +#ifndef ICMP_DEBUG +#define ICMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * IGMP_DEBUG: Enable debugging in igmp.c. + */ +#ifndef IGMP_DEBUG +#define IGMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * INET_DEBUG: Enable debugging in inet.c. + */ +#ifndef INET_DEBUG +#define INET_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP_DEBUG: Enable debugging for IP. + */ +#ifndef IP_DEBUG +#define IP_DEBUG LWIP_DBG_OFF +//LWIP_DBG_OFF +#endif + +/** + * IP_REASS_DEBUG: Enable debugging in ip_frag.c for both frag & reass. + */ +#ifndef IP_REASS_DEBUG +#define IP_REASS_DEBUG LWIP_DBG_OFF +#endif + +/** + * RAW_DEBUG: Enable debugging in raw.c. + */ +#ifndef RAW_DEBUG +#define RAW_DEBUG LWIP_DBG_OFF +#endif + +/** + * MEM_DEBUG: Enable debugging in mem.c. + */ +#ifndef MEM_DEBUG +#define MEM_DEBUG LWIP_DBG_OFF +#endif + +/** + * MEMP_DEBUG: Enable debugging in memp.c. + */ +#ifndef MEMP_DEBUG +#define MEMP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SYS_DEBUG: Enable debugging in sys.c. + */ +#ifndef SYS_DEBUG +#define SYS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TIMERS_DEBUG: Enable debugging in timers.c. + */ +#ifndef TIMERS_DEBUG +#define TIMERS_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_DEBUG: Enable debugging for TCP. + */ +#ifndef TCP_DEBUG +#define TCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_INPUT_DEBUG: Enable debugging in tcp_in.c for incoming debug. + */ +#ifndef TCP_INPUT_DEBUG +#define TCP_INPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_FR_DEBUG: Enable debugging in tcp_in.c for fast retransmit. + */ +#ifndef TCP_FR_DEBUG +#define TCP_FR_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RTO_DEBUG: Enable debugging in TCP for retransmit + * timeout. + */ +#ifndef TCP_RTO_DEBUG +#define TCP_RTO_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_CWND_DEBUG: Enable debugging for TCP congestion window. + */ +#ifndef TCP_CWND_DEBUG +#define TCP_CWND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_WND_DEBUG: Enable debugging in tcp_in.c for window updating. + */ +#ifndef TCP_WND_DEBUG +#define TCP_WND_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_OUTPUT_DEBUG: Enable debugging in tcp_out.c output functions. + */ +#ifndef TCP_OUTPUT_DEBUG +#define TCP_OUTPUT_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_RST_DEBUG: Enable debugging for TCP with the RST message. + */ +#ifndef TCP_RST_DEBUG +#define TCP_RST_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCP_QLEN_DEBUG: Enable debugging for TCP queue lengths. + */ +#ifndef TCP_QLEN_DEBUG +#define TCP_QLEN_DEBUG LWIP_DBG_OFF +#endif + +/** + * UDP_DEBUG: Enable debugging in UDP. + */ +#ifndef UDP_DEBUG +#define UDP_DEBUG LWIP_DBG_OFF +#endif + +/** + * TCPIP_DEBUG: Enable debugging in tcpip.c. + */ +#ifndef TCPIP_DEBUG +#define TCPIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * PPP_DEBUG: Enable debugging for PPP. + */ +#ifndef PPP_DEBUG +#define PPP_DEBUG LWIP_DBG_OFF +//#define PPP_DEBUG (LWIP_DBG_ON | LWIP_DBG_LEVEL_WARNING) +#endif + + +/** + * SLIP_DEBUG: Enable debugging in slipif.c. + */ +#ifndef SLIP_DEBUG +#define SLIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * DHCP_DEBUG: Enable debugging in dhcp.c. + */ +#ifndef DHCP_DEBUG +#define DHCP_DEBUG LWIP_DBG_OFF +#endif + +/** + * AUTOIP_DEBUG: Enable debugging in autoip.c. + */ +#ifndef AUTOIP_DEBUG +#define AUTOIP_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MSG_DEBUG: Enable debugging for SNMP messages. + */ +#ifndef SNMP_MSG_DEBUG +#define SNMP_MSG_DEBUG LWIP_DBG_OFF +#endif + +/** + * SNMP_MIB_DEBUG: Enable debugging for SNMP MIBs. + */ +#ifndef SNMP_MIB_DEBUG +#define SNMP_MIB_DEBUG LWIP_DBG_OFF +#endif + +/** + * DNS_DEBUG: Enable debugging for DNS. + */ +#ifndef DNS_DEBUG +#define DNS_DEBUG LWIP_DBG_OFF +#endif + +/** + * IP6_DEBUG: Enable debugging for IPv6. + */ +#ifndef IP6_DEBUG +#define IP6_DEBUG LWIP_DBG_OFF +#endif + +#define PRINTPKT_SUPPORT 0 + + +/** + * SIO_DEBUG: Enable debugging for Serial I/O. + */ +#define SIO_DEBUG LWIP_DBG_OFF +#define SIO_TRACE (LWIP_DBG_TRACE | SIO_DEBUG) +#define SIO_STATE (LWIP_DBG_STATE | LWIP_DBG_MASK_LEVEL | SIO_DEBUG) + +/** + * SER_DEBUG: Debugging on the Printer port. + */ +#define SER_DEBUG 1 + +#define LWIP_DEBUG +#undef MACOS_DIALOG + +/** + * MACOS_DEBUG: Enable debugging for Macintosh. + */ +#ifndef MACOS_DEBUG +#define MACOS_DEBUG (LWIP_DBG_ON | LWIP_DBG_LEVEL_WARNING) +#define MACOS_TRACE (LWIP_DBG_OFF | LWIP_DBG_TRACE ) +#define MACOS_STATE (LWIP_DBG_ON | LWIP_DBG_STATE | LWIP_DBG_MASK_LEVEL) +#endif + +#define MACOS_SIO_BUFF_SIZE 512 + + +/** + * HTTPD Options: + */ +#define LWIP_HTTPD_APP 1 + +#define HTTPD_USE_CUSTOM_FSDATA 1 +#define LWIP_HTTPD_DYNAMIC_HEADERS 1 +#define LWIP_HTTPD_CUSTOM_FILES 1 +#define LWIP_HTTPD_DYNAMIC_FILE_READ 1 +#define LWIP_HTTPD_FS_ASYNC_READ 0 +#define LWIP_HTTPD_SUPPORT_V09 1 +#define LWIP_HTTPD_SUPPORT_HEAD 1 + +/* This enables a hack in fsdata_custom.c to save a bunch of buffer RAM */ +#define HTTPD_PRECALCULATED_CHECKSUM 1 + +#define HTTPD_DEBUG (LWIP_DBG_ON | LWIP_DBG_LEVEL_WARNING) + + +#define MACOS_LOW_MEM 1 +#if MACOS_LOW_MEM + +#define HTTPD_DEBUG LWIP_DBG_OFF + +#define SER_DEBUG 0 + +#undef LWIP_DEBUG +#define MACOS_DIALOG + +#endif + + +#endif /* __LWIPOPTS_H__ */ diff --git a/ports/mac/mac_httpd_ssi.c b/ports/mac/mac_httpd_ssi.c new file mode 100644 index 0000000..f3dca9e --- /dev/null +++ b/ports/mac/mac_httpd_ssi.c @@ -0,0 +1,11 @@ +/* + * mac_httpd_ssi.c + * + * + * Created by Eric Pooch on 2/11/15. + * Copyright 2015 __MyCompanyName__. All rights reserved. + * + */ + +#include "mac_httpd_ssi.h" + diff --git a/ports/mac/mac_httpd_ssi.h b/ports/mac/mac_httpd_ssi.h new file mode 100644 index 0000000..198b438 --- /dev/null +++ b/ports/mac/mac_httpd_ssi.h @@ -0,0 +1,9 @@ +/* + * mac_httpd_ssi.h + * + * + * Created by Eric Pooch on 2/11/15. + * Copyright 2015 __MyCompanyName__. All rights reserved. + * + */ + diff --git a/ports/mac/sio.c b/ports/mac/sio.c new file mode 100644 index 0000000..0731abd --- /dev/null +++ b/ports/mac/sio.c @@ -0,0 +1,400 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + */ + +#include "lwip/opt.h" +#include "lwip/sys.h" +#include "lwip/sio.h" + +#include +#include +#include + +#include +#include +#include +#include + +/** + * SIO_DEBUG: Enable debugging for SIO. + */ +#ifndef SIO_DEBUG +#define SIO_DEBUG LWIP_DBG_OFF +#endif + +/** + * MACOS_INPUT_BUFF_SIZE: Set the ppp input buffer. + * 64 or less uses driver's default 64 byte buffer. + */ +#ifndef MACOS_SIO_BUFF_SIZE +#define MACOS_SIO_BUFF_SIZE 64 +#endif + + +/* sio_fd_t is supposed to be a void pointer, so we need to do some casting back. */ +#define PORT_NUM(sd) (*(short *)sd) + +#define IN_REF(sd) (int)(PORT_NUM(sd) + 3) * -2 +#define OUT_REF(sd) (int)IN_REF(sd)-1 + +u8_t sio_setup(sio_fd_t sd); +OSErr ROMSDOpen(SPortSel whichPort); + +char *sio_input_buffer; + +#if NO_SYS==0 +static unsigned char sio_abort = 0xFF; +#endif + +#pragma segment LWUPDN +u8_t sio_setup(sio_fd_t fd) +{ + OSErr error; + + unsigned short baud; + short databits; + short stopbits; + short parity; + short config; + SerShk shake; + + /* Set the new data */ + baud = baud19200; /* 19200 */ + parity = noParity; /* None*/ + databits = data8; /* 8 */ + stopbits = stop10; /* 1 */ + + /* do not use flow control */ + shake.fXOn = 0; + shake.fCTS = 0; + shake.xOn = 0; + shake.xOff = 0; + shake.errs = 0; + shake.evts = 0; + shake.fInX = 0; + shake.fDTR = 0; + + config = baud + parity + databits + stopbits; + //config = (baud | parity | databits | stopbits); + + LWIP_DEBUGF(SIO_DEBUG, ("sio_setup(%d, %d)\n", IN_REF(fd), OUT_REF(fd))) ; + + if (error = SerReset(IN_REF(fd), config)) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_setup(%d) can't configure serial port due to \'SerReset\' error:%d. Continuing...\n", IN_REF(fd), error)) ; + if (error = SerHShake(IN_REF(fd), &shake)) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_setup(%d) can't disable serial handshake due to \'SerHShake\' error:%d. Continuing...\n", IN_REF(fd), error)) ; + + if (error = SerReset(OUT_REF(fd), config)) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_setup(%d) can't configure serial port due to \'SerReset\' error:%d. Continuing...\n", OUT_REF(fd), error)) ; + if (error = SerHShake(OUT_REF(fd), &shake)) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_setup(%d) can't disable serial handshake due to \'SerHShake\' error:%d. Continuing...\n", OUT_REF(fd), error)) ; + + return 1; +} + + +OSErr ROMSDOpen(SPortSel whichPort) +{ + OSErr error = fnfErr; + short inRef, outRef; + + char *inDriver; + char *outDriver; + + switch (whichPort) + { + case sPortA: + inDriver = ".AIn"; + outDriver = ".AOut"; + break; + + case sPortB: + inDriver = ".BIn"; + outDriver = ".BOut"; + break; + + default: + return error; + break; + } + + error = opendriver(outDriver, &outRef); + LWIP_DEBUGF(SIO_DEBUG, ("ROMSDOpen(%d) 'opendriver(%s, %d)\n", whichPort, outDriver, outRef )) ; + if (error == noErr) + { + error = opendriver(inDriver, &inRef); + LWIP_DEBUGF(SIO_DEBUG, ("ROMSDOpen(%d) 'opendriver(%s, %d)\n", whichPort, inDriver, inRef )) ; + } + + LWIP_DEBUGF(SIO_DEBUG, ("ROMSDOpen(%d) will return: %d\n", whichPort, error)); + + return error; +} + +/** + * Opens a serial device for communication. + * + * @param devnum device number + * @return handle to serial device if successful, NULL otherwise + */ +sio_fd_t sio_open(u8_t devnum) +{ + OSErr error = fnfErr; + /* These are the the serial port numbers that 'sio_fd_t sd' points to. */ + static const short modemPort = sPortA; + static const short printerPort = sPortB; + /* The serial port device is just a pointer to one of the constant port numbers. */ + sio_fd_t sd; + + /* Keep track of the port name for debugging and warnings. */ + char* port_name; + + /* We don't have devices, but sPortA (0) is Modem and sPortB (1) is Printer. */ + switch (devnum) + { + case 'P' : + case 'p' : + case 'b' : + case 'B' : + case sPortB : + port_name = "Printer"; + sd = (sio_fd_t)&printerPort; + error = ROMSDOpen(sPortB); + break; + + case 'M' : + case 'm' : + case 'a' : + case 'A' : + case sPortA : + default: + port_name = "Modem"; + sd = (sio_fd_t)&modemPort; + error = ROMSDOpen(sPortA); + + /* PPP was overflowing the input buffer, so make it bigger.*/ + if (MACOS_SIO_BUFF_SIZE > 64 && sio_input_buffer == NULL) + { + sio_input_buffer = (char *)malloc(MACOS_SIO_BUFF_SIZE); + LWIP_ASSERT("sio_open() can't allocate memory", sio_input_buffer != NULL); + } + if ( error == noErr && sio_input_buffer) + SerSetBuf(IN_REF(sd), sio_input_buffer, MACOS_SIO_BUFF_SIZE); + break; + } + + switch (error) + { + case (int)noErr: //0 + LWIP_DEBUGF(SIO_TRACE, ("Serial Port successfully opened.\n", devnum)); + break; + case (int)badUnitErr: //-21 + LWIP_ERROR("Bad Reference Number for Serial Port.\n", (error == noErr ), return NULL;); + break; + case (int)dInstErr: //-26 + LWIP_ERROR("Couldn't Find Serial Driver in Resource File.\n", (error == noErr ), return NULL;); + break; + case (int)openErr: //-23 + LWIP_ERROR("Driver can't perform the requested reading or writing.\n", (error == noErr ), return NULL;); + break; + case (int)unitEmptyErr: //-22 + LWIP_ERROR("Bad Reference Number for Serial Port.\n", (error == noErr ), return NULL;); + break; + case (int)fnfErr: //-43 + LWIP_ERROR(("Serial Port Not Found.\n"), (error == noErr ), return NULL;); + break; + default: + //printf("%d", (int)error); + LWIP_ERROR("Unknown Error opening Serial Port.\n", (error == noErr ), return NULL;); + break; + } + + sio_setup(sd); + + LWIP_DEBUGF(SIO_DEBUG, ("%s Port Successfully Opened.\n", (PORT_NUM(sd) == (int)sPortA)? "Modem":"Printer")); + + return sd; +} + + +/** + * Closes a serial device. + * + * @param fd device + */ +void +sio_close(sio_fd_t fd) +{ + if (PORT_NUM(fd) == (int)sPortA && sio_input_buffer) + SerSetBuf(IN_REF(fd), sio_input_buffer, 0); + + /* Don't Close the ROM Serial Driver */ +} + +/** + * Sends a single character to the serial device. + * + * @param c character to send + * @param fd serial device handle + * + * @note This function will block until the character can be sent. + */ +#pragma segment LWPPP +void sio_send(u8_t c, sio_fd_t fd) +{ + OSErr error; + long count = 1; + + error = FSWrite(OUT_REF(fd), &count, &(char)c); + + if (error) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_send(%c, %d) failed due to \'FSWrite\' error: %d.\n", c, PORT_NUM(fd), error)); + + return; +} + +/** + * Receives a single character from the serial device. + * + * @param fd serial device handle + * + * @note This function will block until a character is received. The blocking + * can be cancelled by calling sio_read_abort(). + */ + +#if NO_SYS==0 +u8_t sio_recv(sio_fd_t fd) +{ + static unsigned char cbuff; + + sio_read(fd, &(char)cbuff, 1); + + return cbuff; +} +#endif + + +/** + * Reads from the serial device. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received - may be 0 if aborted by sio_read_abort + * + * @note If NO_SYS is > 0, this function will block until data can be received. + * The blocking can be cancelled by calling sio_read_abort(). + */ + +u32_t sio_read(sio_fd_t fd, u8_t* data, u32_t len) +{ + long count = 0; + +#if NO_SYS==0 + while (sio_abort != IN_REF(fd) && count < len) +#endif + { + count = sio_tryread(fd, data, len); + } +#if NO_SYS==0 + if (sio_abort == IN_REF(fd)) + sio_abort = 0xFF; +#endif + + return count; +} + + +/** + * Non-Blocking Read from the serial device. + * + * @param fd serial device handle + * @param data pointer to data buffer for receiving + * @param len maximum length (in bytes) of data to receive + * @return number of bytes actually received - may be 0 + * + */ +u32_t sio_tryread(sio_fd_t fd, u8_t* data, u32_t len) +{ + OSErr error; + long count = 0; + + (void)SerGetBuf(IN_REF(fd), &count); + + if (count) + { + /* only get up to the length asked for. */ + if (count > len) count = (long)len; + + if ((error = FSRead(IN_REF(fd), &count, (char *)data))) + LWIP_DEBUGF(SIO_DEBUG | LWIP_DBG_LEVEL_WARNING, ("sio_read(%d, %d) failed due to \'FSRead\' error: %d.\n", IN_REF(fd), len, error)); + } + return count; +} + + +/** + * Writes to the serial device. + * + * @param fd serial device handle + * @param data pointer to data to send + * @param len length (in bytes) of data to send + * @return number of bytes actually sent + * + * @note This function will block until all data can be sent. + */ +u32_t sio_write(sio_fd_t fd, u8_t* data, u32_t len) +{ + OSErr error; + long count = (long)len; + + error = FSWrite(OUT_REF(fd), &count, (char *)data); + + // The ppp module will log the error for us. + if (error) + return error; + + return len; +} + +#if NO_SYS==0 +/** + * Aborts a blocking sio_read() call. + * + * @param fd serial device handle + */ +void sio_read_abort(sio_fd_t fd) +{ + LWIP_DEBUGF(SIO_DEBUG, ("sio_read_abort(%d)\n", IN_REF(fd) )); + sio_abort = IN_REF(fd); + return; +} + +#endif + diff --git a/ports/mac/sys_arch.c b/ports/mac/sys_arch.c new file mode 100644 index 0000000..00ce9af --- /dev/null +++ b/ports/mac/sys_arch.c @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2001-2003 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +#include + + +#include ":lwip:sys.h" +#include ":lwip:def.h" +#include ":lwip:opt.h" + +#if NO_SYS +struct thread_struct_wrapper *lwip_system_threads = NULL; // a list of all threads created by lwIP + +u32_t +sys_jiffies(void) +{ + return (u32_t)clock(); +} + +#else + +static clock_t sys_start; + +u32_t +sys_jiffies(void) +{ + return (u32_t)(clock() - sys_start); +} + +u32_t +sys_now(void) +{ + return (u32_t)(sys_jiffies() * (1000/CLOCKS_PER_SEC) ); +} + +void +sys_init(void) +{ + sys_start = clock(); + return; +} + +void +sys_arch_block(u16_t time) +{ + u16_t ticks; + + ticks = (time * (1000/CLOCKS_PER_SEC)) + clock(); + + while (clock() != ticks) {} +} + +err_t +sys_mbox_new(sys_mbox_t *mbox, int size) +{ + mbox = SYS_MBOX_NULL; + return ERR_OK; +} + +void +sys_mbox_free(sys_mbox_t *mbox) +{ + return; +} + + +err_t +sys_mbox_trypost(sys_mbox_t *mbox, void *msg) +{ + return ERR_OK; +} + +err_t +sys_sem_new(sys_sem_t *sem, u8_t count) +{ + sem = 0; + return ERR_OK; +} + +u32_t +sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) +{ + sys_arch_block(timeout); + return 0; +} + +void +sys_sem_signal(sys_sem_t *sem) +{ + return; +} + +void +sys_sem_free(sys_sem_t *sem) +{ + return; +} + +sys_thread_t +sys_thread_new(const char *name, lwip_thread_fn thread, void *arg, int stacksize, int prio) +{ + return 0; +} +#endif + +u32_t +sys_now(void) +{ + return (u32_t)(sys_jiffies() * (1000/CLOCKS_PER_SEC)); +} diff --git a/ports/mac/test.c b/ports/mac/test.c new file mode 100644 index 0000000..88b1eab --- /dev/null +++ b/ports/mac/test.c @@ -0,0 +1 @@ +/* * test.c * * * Created by Eric Pooch on 1/4/14. * Copyright 2014 Eric Pooch. All rights reserved. * */ #include //#include #include #include #include #include #include #include "arch/macos_debug.h" #include "lwip/sys.h" #include "lwip/sio.h" #include "fs.h" #include "lwip/init.h" #include "lwip/ip.h" #include "lwip/tcp_impl.h" #include "lwip/tcpip.h" #include "lwip/netif.h" #if SER_DEBUG #include #endif #include "test.h" #if PPP_SUPPORT #include "netif/ppp/ppp.h" #endif #define MIN_FREE_MEM 28000 #if LWIP_HAVE_SLIPIF #include "netif/slipif.h" #endif //#include "echo.h" #include "httpserver_raw/httpd.h" #if SER_DEBUG sio_fd_t debug_sio; #endif #if PPP_SUPPORT sio_fd_t ppp_sio; struct ppp_pcb_s *ppps; void ppp_link_status_cb(ppp_pcb *pcb, int err_code, void *ctx); void test_intf(void); void ppp_poll(void); void apps_init(void); #if PPP_NOTIFY_PHASE void ppp_notify_phase_cb(ppp_pcb *pcb, u8_t phase, void *ctx); //static u8_t ppp_phase; #endif /*PPP_NOTIFY_PHASE*/ #endif /*PPP_SUPPORT*/ #if LWIP_HAVE_SLIPIF static struct netif slipif; void test_intf(void); /* (manual) host IP configuration */ static ip_addr_t ipaddr, netmask, gw; #endif #if LWIP_HAVE_LOOPIF static struct netif loopif; #endif // lwIP interval timer struct test_timer { u32_t time; // Current time counter in ms u32_t interval; // Interval in ms void (*timed_func)(void); // Function to call }; // List of lwIP interval timers #define PPP_TMR_INTERVAL 16 #define PING_TMR_INTERVAL 1200 static struct test_timer test_timers[] = { #if LWIP_TCP //{ 0, TCP_TMR_INTERVAL, tcp_tmr }, #endif #if LWIP_ARP { 0, ARP_TMR_INTERVAL, etharp_tmr }, #endif #if IP_REASSEMBLY { 0, IP_TMR_INTERVAL, ip_reass_tmr }, #endif #if LWIP_AUTOIP { 0, AUTOIP_TMR_INTERVAL, autoip_tmr }, #endif #if LWIP_IGMP { 0, IGMP_TMR_INTERVAL, igmp_tmr }, #endif #if LWIP_DNS { 0, DNS_TMR_INTERVAL, dns_tmr }, #endif #if PPP_SUPPORT //{ 0, PPP_TMR_INTERVAL, ppp_poll }, { 0, 15000, test_intf }, #endif #ifndef TEST_MAIN_DISABLE { 0, 60000, test_stop }, #endif { 0, 0, NULL } }; static short apps_started; static u32_t last_ticks; #ifndef TEST_MAIN_DISABLE int main(void) { /* Initialize menus Initialize user settings Initialize browser window */ /* initialize the program */ /* Chat with modem/server */ /* Start PPP/SLIP */ test_init(); while (1) { test_poll(); } return 0; } #endif /* This function initializes applications */ void apps_init(void) { #if LWIP_DNS_APP && LWIP_DNS /* wait until the netif is up (for dhcp, autoip or ppp) */ //sys_timeout(5000, dns_dorequest, NULL); #endif /* LWIP_DNS_APP && LWIP_DNS */ #if LWIP_CHARGEN_APP && LWIP_SOCKET chargen_init(); #endif /* LWIP_CHARGEN_APP && LWIP_SOCKET */ #if LWIP_PING_APP && LWIP_RAW && LWIP_ICMP ping_init(); #endif /* LWIP_PING_APP && LWIP_RAW && LWIP_ICMP */ #if LWIP_NETBIOS_APP && LWIP_UDP netbios_init(); #endif /* LWIP_NETBIOS_APP && LWIP_UDP */ #if LWIP_HTTPD_APP && LWIP_TCP #ifdef LWIP_HTTPD_APP_NETCONN http_server_netconn_init(); #else /* LWIP_HTTPD_APP_NETCONN */ httpd_init(); #endif /* LWIP_HTTPD_APP_NETCONN */ #endif /* LWIP_HTTPD_APP && LWIP_TCP */ #if LWIP_NETIO_APP && LWIP_TCP netio_init(); #endif /* LWIP_NETIO_APP && LWIP_TCP */ #if LWIP_RTP_APP && LWIP_SOCKET && LWIP_IGMP rtp_init(); #endif /* LWIP_RTP_APP && LWIP_SOCKET && LWIP_IGMP */ #if LWIP_SNTP_APP && LWIP_SOCKET sntp_init(); #endif /* LWIP_SNTP_APP && LWIP_SOCKET */ #if LWIP_SHELL_APP && LWIP_NETCONN shell_init(); #endif /* LWIP_SHELL_APP && LWIP_NETCONN */ #if LWIP_TCPECHO_APP #if LWIP_NETCONN && defined(LWIP_TCPECHO_APP_NETCONN) tcpecho_init(); #else /* LWIP_NETCONN && defined(LWIP_TCPECHO_APP_NETCONN) */ echo_init(); #endif /* LWIP_TCPECHO_APP && LWIP_NETCONN */ #endif #if LWIP_UDPECHO_APP && LWIP_NETCONN udpecho_init(); #endif /* LWIP_UDPECHO_APP && LWIP_NETCONN */ #if LWIP_SOCKET_EXAMPLES_APP && LWIP_SOCKET socket_examples_init(); #endif /* LWIP_SOCKET_EXAMPLES_APP && LWIP_SOCKET */ #ifdef LWIP_APP_INIT LWIP_APP_INIT(); #endif } #pragma segment LWUPDN void test_init() { static short initialized; #if PPP_SUPPORT const char *username = "myuser"; const char *password = "mypassword"; int error = PPPERR_NONE; // Only initialize once if (ppp_sio && initialized) return; #else lwip_init(); #endif initialized = true; //setvbuf(stdout, NULL,_IONBF, 0); last_ticks = sys_now(); #if SER_DEBUG debug_sio = sio_open(1); LWIP_ERROR("Unable to open Printer port\n", debug_sio != NULL, NULL); #endif #if PPP_SUPPORT ppp_sio = sio_open(0); LWIP_ERROR("Unable to open Modem port\n", ppp_sio != NULL, exit(EXIT_FAILURE)); ppps = ppp_new(); //LWIP_DEBUGF(MACOS_TRACE, ("ppp_set_auth()\n")); //ppp_set_auth(ppps, PPPAUTHTYPE_ANY, NULL, NULL); //ppp_set_auth(ppps, PPPAUTHTYPE_PAP, "login", "password"); #if PPP_NOTIFY_PHASE ppp_set_notify_phase_callback(ppps, ppp_notify_phase_cb); #endif error = ppp_over_serial_create(ppps, ppp_sio, ppp_link_status_cb, NULL); if (error != PPPERR_NONE) { ppp_link_status_cb(ppps, error, NULL); return; } ppp_open(ppps, 0); #endif #if LWIP_HAVE_LOOPIF { struct ip_addr addr, netmask, gateway; /* Setup default loopback device instance */ IP4_ADDR(&addr, 127,0,0,1); IP4_ADDR(&netmask, 255,255,255,0); IP4_ADDR(&gateway, 127,0,0,1); netif_add(&loopif, &addr, &netmask, &gateway, NULL, loopif_init, ip_input); netif_set_default(&loopif); } #endif /* LWIP_HAVE_LOOPIF */ #if LWIP_HAVE_SLIPIF { struct ip_addr addr, netmask, gateway; /* Setup default SLIP device instance */ IP4_ADDR(&addr, 192,168,11,15); IP4_ADDR(&netmask, 255,255,255,0); IP4_ADDR(&gateway, 192,168,11,1); netif_add(&slipif, &addr, &netmask, &gateway, NULL, slipif_init, ip_input); netif_set_default(&slipif); netif_set_up(&slipif); } apps_init(); #endif /* LWIP_HAVE_SLIPIF */ } #if PPP_SUPPORT #if PPP_NOTIFY_PHASE void ppp_notify_phase_cb(ppp_pcb *pcb, u8_t phase, void *ctx) { /* * Values for phase from ppp.h. #define PPP_PHASE_DEAD 0 #define PPP_PHASE_INITIALIZE 1 #define PPP_PHASE_SERIALCONN 2 #define PPP_PHASE_DORMANT 3 #define PPP_PHASE_ESTABLISH 4 #define PPP_PHASE_AUTHENTICATE 5 #define PPP_PHASE_CALLBACK 6 #define PPP_PHASE_NETWORK 7 #define PPP_PHASE_RUNNING 8 #define PPP_PHASE_TERMINATE 9 #define PPP_PHASE_DISCONNECT 10 #define PPP_PHASE_HOLDOFF 11 #define PPP_PHASE_MASTER 12 */ // ppp_phase = phase; // switch(phase) /* open a non-modal window, and update a string with the status.*/ switch (phase) { case 1: case 2: case 4: case 5: /* release LCP */ case 7: /* init ICPC */ case 8: /* release ICPC */ default: LWIP_DEBUGF(MACOS_TRACE, ("ppp_notify_phase_cb: %d", phase)); MACOS_DLOGF(MACOS_DEBUG, ("PPP Phase Changed to: %d\n", phase)); break; } LWIP_DEBUGF(MACOS_STATE, ("App Limit: %lu \n", (long)GetApplLimit() )); LWIP_DEBUGF(MACOS_STATE, ("Free Memory: %lu \n", (long)FreeMem() )); } #endif void ppp_link_status_cb(ppp_pcb *pcb, int err_code, void *ctx) { LWIP_UNUSED_ARG(ctx); switch(err_code) { case PPPERR_NONE: /* No error. */ { struct netif *pppnetif = &pcb->netif; struct ppp_addrs *ppp_addrs = ppp_addrs(pcb); netif_set_default(pppnetif); MACOS_DLOGF(MACOS_STATE, ("\n")); MACOS_DLOGF(MACOS_DEBUG, (" Remote IP Addr\t: %s\n", ip_ntoa(&ppp_addrs->his_ipaddr))); MACOS_DLOGF(MACOS_DEBUG, (" Local IP Addr\t\t: %s\n", ip_ntoa(&ppp_addrs->our_ipaddr))); MACOS_DLOGF(MACOS_DEBUG, (" Subnet Mask\t\t: %s\n", ip_ntoa(&ppp_addrs->netmask))); MACOS_DLOGF(MACOS_DEBUG, (" DNS Server 1\t\t: %s\n", ip_ntoa(&ppp_addrs->dns1))); MACOS_DLOGF(MACOS_DEBUG, (" DNS Server 2\t\t: %s\n", ip_ntoa(&ppp_addrs->dns2))); if ((struct ppp_addrs *)ctx) { LWIP_DEBUGF(MACOS_STATE, ("ppp_link_status_cb PPPERR__NONE -connect %d\n", err_code)); } else { LWIP_DEBUGF(MACOS_STATE, ("ppp_link_status_cb PPPERR__NONE %d\n", err_code)); } break; } case PPPERR_PARAM: { /* Invalid parameter. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_PARAM\n")); break; } case PPPERR_OPEN: { /* Unable to open PPP session. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_OPEN\n")); break; } case PPPERR_DEVICE: { /* Invalid I/O device for PPP. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_DEVICE\n")); break; } case PPPERR_ALLOC: { /* Unable to allocate resources. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_ALLOC\n")); break; } case PPPERR_USER: { /* User interrupt. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_USER\n")); break; } case PPPERR_CONNECT: { /* Connection lost. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_CONNECT\n")); break; } case PPPERR_AUTHFAIL: { /* Failed authentication challenge. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_AUTHFAIL\n")); break; } case PPPERR_PROTOCOL: { /* Failed to meet protocol. */ LWIP_DEBUGF(MACOS_DEBUG, ("pppLinkStatusCallback: PPPERR_PROTOCOL\n")); break; } default: { LWIP_DEBUGF((MACOS_DEBUG | LWIP_DBG_LEVEL_WARNING), ("pppLinkStatusCallback: unknown errCode %d\n", err_code)); break; } } MACOS_DLOGF(MACOS_STATE, ("\n")); } #endif /*PPP_SUPPORT*/ #pragma segment Main void test_stop() { #if PPP_SUPPORT if (ppps >= 0) { LWIP_DEBUGF(MACOS_STATE, ("Exiting on Schedule...\n")); if (((long)FreeMem() < MIN_FREE_MEM) && apps_started) LWIP_ERROR("Insufficent Free Memory to terminate PPP connection before Quitting.\n", false, return;); LWIP_DEBUGF(MACOS_STATE, ("Still up...\n")); ppp_close(ppps); sys_msleep(500); } sio_close(ppp_sio); ppp_sio = NULL; #endif #if SER_DEBUG sio_close(debug_sio); debug_sio = NULL; #endif #ifndef TEST_MAIN_DISABLE MACOS_DLOGF(MACOS_STATE, ("Exiting on Schedule...\n")); exit(0); #endif } void test_restart(void) { LWIP_DEBUGF(MACOS_TRACE, ("test_restart()\n")); test_stop(); test_init(); } void test_poll(void) { u32_t ticks; u32_t delta; struct test_timer *curr_timer; #if LWIP_HAVE_SLIPIF slipif_poll(&slipif); #endif #if PPP_SUPPORT ppp_poll(); #endif // Process timers ticks = sys_now(); delta = ticks - last_ticks; last_ticks = ticks; // The following check skips a potential wrap-around in the // system ticks counter. // It also skips when sys_now hasn't incremented due to 16 ms passing per clock tick. if (delta > 0) { for (curr_timer = test_timers; curr_timer->timed_func != NULL; curr_timer++) { /* if (curr_timer->active_phase == ppp_phase || curr_timer->active_phase == 0xFF ) { */ curr_timer->time += delta; if (curr_timer->time >= curr_timer->interval) { curr_timer->timed_func(); curr_timer->time -= curr_timer->interval; } // } } } } #if SER_DEBUG void ser_debug_print( const char *fmt, ...) { OSErr error; int len; unsigned char buffer[128]; va_list args; va_start(args, fmt); len = vsprintf((char *)buffer, fmt, args); if (debug_sio) error = sio_write(debug_sio, buffer, len); /*else printf((char *)buffer);*/ va_end(args); } #endif /* Check if connection is up yet. */ #if PPP_SUPPORT void test_intf(void) { #if LWIP_TCP if ( !ppps->if_up ) { MACOS_DLOGF(MACOS_STATE, ("PPP stuck at Phase %d.\n Check your connection and click 'OK' to renegotiate.\n", ppps->phase)); apps_started = false; test_restart(); } else if ( !apps_started ) { /* Start up the TCP apps here, because if we do it in the link status callback, the stack is too big, and there isn't enough memory available. */ Size grow; UnloadSeg((Ptr) sio_open); MaxMem(&grow); LWIP_DEBUGF(MACOS_STATE, ("Free Mem: %lu \n", (long)FreeMem() )); LWIP_DEBUGF(MACOS_STATE, ("Max Memory: %lu \n", grow)); LWIP_DEBUGF(MACOS_STATE, ("Starting Apps.\n")); apps_init(); apps_started = true; } LWIP_DEBUGF(MACOS_STATE, ("App Limit: %lu \n", (long)GetApplLimit() )); LWIP_DEBUGF(MACOS_STATE, ("Free Memory: %lu \n", (long)FreeMem() )); #endif } void ppp_poll(void) { u8_t buffer[MACOS_SIO_BUFF_SIZE]; int len; len = sio_read(ppp_sio, buffer, MACOS_SIO_BUFF_SIZE); if (len < 0) { LWIP_DEBUGF((MACOS_DEBUG | LWIP_DBG_LEVEL_SERIOUS), ("Error reading from serial port: %d", len)); } else if (len > 0) { /*int i; LWIP_DEBUGF(MACOS_DEBUG, ("ppp_poll(): got %d bytes: ", len)); for (i=0; ir!)`3QMpumogwgZ7M zVz9%*I=;FCf({hhL99Dk#epClD`KqL##P(kt0`-{p~vl}R+mk`f85_azjJ<{@BQ6- z?y}`e_34F6fw{nc0YDWV=5;w3j)hR%>yyWe2`;bK?e+Si2ZK#skK5~Uc|9Jl+vDJA zmc%{or$0V?=ykiiZl~AnKskYbFn(`D5I9O0yu@=X&(XaDS2>nuIktQB@jtI{4xSY_ zM&NuGEXOf=5M)^fBpDKiodU~tHt{S=lbDld96WRE+}93{VUF#k3A}mup}^4sPdhmJ zaEp~92#UZN5^Lp#2^@zBvhL^!n#4(xAPF2saT87uoUpsGVK0vBaS~>@(_P0I3a5@V zvs5iiQr7N^K3AKKKycE4lc3E|XYT|CM;ko?S@$4>6Y-$e-0+;b5nNE`ua0;NfmBGEP3i;%580z~-8<^lrs z0Z|e|j?olE(mI@CC=w=V6b2E7Ev9>Xk8un^C>CaTia=1Lm}hC4qI9^=mBwHYg-sA> zGC>gLs}qLa+Vr*o@zrZ8tw1T?37Iy*2tv>TOX~@mX6SPaO))gXGBnFVpl@Oj z3HnngWI!Pk4EcDV58FYMBM^wdCIkj~mhnxGWf;Miunfzxv*ynQ|Fi}(SLLnVv~6YP zd>8_^tTt32;L4q45DYWE2EicgL&FFNBM^*k-cjc9dd7c#B0QUTe1G)1L*N{a)AxUJ zUgy3UJmcWlp`o*vE}iBsa-R%21fFSfJSO?uME@x6aN`aaE;w=CiFIAVcqhsV2+bkB zwy-S8um?|H_ISM)yIO~OD3&6%fKPw!0wA3Pf~3(VmL9N3LuapI;c7`)teGxWv;!Dr*955&)VheP3ZWP)akbl#l*~Wbmn*GT|ct+WKWP%y;^-(=V#im zAspwo!po~VR|b6zrCcqXl^dOZV`NUQ+4>qFuS}oNJs$KA)oWk8XuMSto>0JCD7hD~ zgKwQ{pr1qkSnz}1kX&(I_c#Y?n`2ZUxv!0e_3bqLR?V@WWy$XRu{&Z-QJy2RtaAPh zT`>{((fu#qu-dPfXTDn=&hMMNY*1vLui9AJp*plYwPjArF3ypo`SQy5BMWi2x_>eD z>yLMmZ|wegW58c3Gu^5K?}yb{f`LZ`$}Jy0I{aO3#(3|km5No+_6M>BT7h1o5IMx@ zuG%z({$GG*hSYtfr7fynceAbj*M0ifC8|u*=t9*NWtQxZXQ5)L?wmL;qswLqczuCn zY)qye=S~IU2d`li$Z= zSzWt8{S95RqG4LYh8fZ~`IelFI~AUePcp%)wFf_#O#(+Z0MYktO#s<8~GSt=DA9@7!)y#9b(O_jt(N(reub+L13- z1;#KZsskR`ZVmKDm5{mVh%jvLnlU`@^NkA>FhvFs0K?)8DZKj&m{}eEBn$lHdl}d37pt}Xa1LMA>VzQIJWO% z&{@ekXK@SvYxGR;htYopWAnCo3Z85 z?q_o+l9emu(&wusqFr&y=Mw$xyv6GDsdXW_ZdIM`hh-XT#N9q#67%tSP^wl+*WOhX zzaLi}KzQ0l0?cM*;LMeP=c;lTV9Qf5@>`~tt5pp}`N zb+2oCtAA~g_!gX%GP~&j(oqyyVpyiLHAxeBKSjUCKcs!CB%9MjrpjufiNr?4tDH(u z!}BLk8XK#+J__5fmc*6Atte5X>Vu7d#gUO{GsrZad)n`HqS9=mVkab0D+g>VBt}`8 zw=OcYH@JlBjTnIZ6UXV0g(Gd@!5|+)ai>47&61gs8i}?NkZ`r4X;_2&-PSS$TdBZP4 z&x>@tsFY}r_{L<=*qcn&b+kyndDHY|qzqzl`J~bkjkp4m3L5=SnJft=jocjH9$E(Z zM|BPauD{?HTCQI1gW*r#x6g{BEmKY<%9B& +ElWhip: Featuring lwip - A Lightweight TCP/IP Stack + + + + +
+ Macintosh hello + +

ElWhip: Featuring lwIP - A Lightweight TCP/IP Stack

+

+ The web page you are viewing is being served on an original + Macintosh with 512K RAM. This is the first known TCP/IP stack + running on a Macintosh with the original 64K ROMs. This is made + possible by the lightweight TCP/IP stack lwIP. +

+

+ lwIP is an open source implementation of the TCP/IP + protocol suite that was originally written by Adam Dunkels + of the Swedish Institute of Computer Science but now is + being actively developed by a team of developers + distributed world-wide. Since it's release, lwIP has + spurred a lot of interest and has been ported to several + platforms and operating systems. lwIP can be used either + with or without an underlying OS. +

+

+ The focus of the lwIP TCP/IP implementation is to reduce + the RAM usage while still having a full scale TCP. This + makes lwIP suitable for use in embedded systems with tens + of kilobytes of free RAM and room for around 40 kilobytes + of code ROM. +

+

+ More information about lwIP can be found at the lwIP + homepage at http://savannah.nongnu.org/projects/lwip/ + or at the lwIP wiki at http://lwip.wikia.com/. +

+
+   +
+ + +