diff options
Diffstat (limited to 'apps/netutils')
64 files changed, 19268 insertions, 0 deletions
diff --git a/apps/netutils/Makefile b/apps/netutils/Makefile new file mode 100644 index 000000000..3c3f11c43 --- /dev/null +++ b/apps/netutils/Makefile @@ -0,0 +1,62 @@ +############################################################################ +# apps/netutils/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config # Current configuration + +# Sub-directories + +ifeq ($(CONFIG_NET),y) +SUBDIRS = uiplib dhcpc dhcpd resolv smtp telnetd webclient webserver tftpc thttpd +endif + +all: nothing +.PHONY: nothing depend clean distclean + +nothing: + +define DOMAKE + @(MAKE) -C $1 $2 TOPDIR="$(TOPDIR) APPDIR=$(APPDIR)" +endef + +depend: + $(foreach DIR, $(SUBDIRS), $(eval $(call DOMAKE,$(DIR),depend))) + +clean: + $(foreach DIR, $(SUBDIRS), $(eval $(call DOMAKE,$(DIR),clean))) + +distclean: clean + $(foreach DIR, $(SUBDIRS), $(eval $(call DOMAKE,$(DIR),distclean))) + +-include Make.dep diff --git a/apps/netutils/README.txt b/apps/netutils/README.txt new file mode 100644 index 000000000..e4b05eb21 --- /dev/null +++ b/apps/netutils/README.txt @@ -0,0 +1,39 @@ +netutils +^^^^^^^^ + +This directory contains most of the network applications contained +under the uIP-1.0 apps directory. As the uIP apps/README says, +these applications "are not all heavily tested." These uIP apps +include: + + dhcpc - Dynamic Host Configuration Protocol (DHCP) client + resolv - uIP DNS resolver + smtp - Simple Mail Transfer Protocol (SMTP) client + telnetd - TELNET server + webclient - HTTP web client + webserver - HTTP web server + +You may find additional information on these apps in the uIP forum +accessible through: http://www.sics.se/~adam/uip/index.php/Main_Page + +Additional applications that were not part of uIP (but which are +highly influenced by uIP) include: + + dhcpd - Dynamic Host Configuration Protocol (DHCP) server + tftpc - TFTP client + thttpd - This is a port of Jef Poskanzer's THTTPD HTPPD server. + See http://acme.com/software/thttpd/. + +If you use DHCPC/D, then some special configuration network options are +required. These include: + + CONFIG_NET=y Of course + CONFIG_NSOCKET_DESCRIPTORS And, of course, you must allocate some + socket descriptors. + CONFIG_NET_UDP=y UDP support is required for DHCP + (as well as various other UDP-related + configuration settings). + CONFIG_NET_BROADCAST=y UDP broadcast support is needed. + CONFIG_NET_BUFSIZE=650 The client must be prepared to receive + (or larger) DHCP messages of up to 576 bytes (excluding + Ethernet, IP, or UDP headers and FCS). diff --git a/apps/netutils/dhcpc/Makefile b/apps/netutils/dhcpc/Makefile new file mode 100644 index 000000000..7209907de --- /dev/null +++ b/apps/netutils/dhcpc/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/dhcpc/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# DHCP Client Library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_UDP),y) +CSRCS += dhcpc.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/dhcpc/dhcpc.c b/apps/netutils/dhcpc/dhcpc.c new file mode 100644 index 000000000..dc80988bb --- /dev/null +++ b/apps/netutils/dhcpc/dhcpc.c @@ -0,0 +1,607 @@ +/**************************************************************************** + * netutils/dhcpc/dhcpc.c + * + * Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based heavily on portions of uIP: + * + * Author: Adam Dunkels <adam@dunkels.com> + * Copyright (c) 2005, Swedish Institute of Computer Science + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <sys/types.h> +#include <sys/socket.h> + +#include <stdlib.h> +#include <stdint.h> +#include <string.h> +#include <unistd.h> +#include <time.h> +#include <errno.h> +#include <debug.h> + +#include <net/uip/uip.h> +#include <apps/netutils/dhcpc.h> +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#define STATE_INITIAL 0 +#define STATE_HAVE_OFFER 1 +#define STATE_HAVE_LEASE 2 + +#define BOOTP_BROADCAST 0x8000 + +#define DHCP_REQUEST 1 +#define DHCP_REPLY 2 +#define DHCP_HTYPE_ETHERNET 1 +#define DHCP_HLEN_ETHERNET 6 +#define DHCP_MSG_LEN 236 + +#define DHCPC_SERVER_PORT 67 +#define DHCPC_CLIENT_PORT 68 + +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNAK 6 +#define DHCPRELEASE 7 + +#define DHCP_OPTION_SUBNET_MASK 1 +#define DHCP_OPTION_ROUTER 3 +#define DHCP_OPTION_DNS_SERVER 6 +#define DHCP_OPTION_REQ_IPADDR 50 +#define DHCP_OPTION_LEASE_TIME 51 +#define DHCP_OPTION_MSG_TYPE 53 +#define DHCP_OPTION_SERVER_ID 54 +#define DHCP_OPTION_REQ_LIST 55 +#define DHCP_OPTION_END 255 + +#define BUFFER_SIZE 256 + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct dhcp_msg +{ + uint8_t op; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint8_t xid[4]; + uint16_t secs; + uint16_t flags; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[16]; +#ifndef CONFIG_NET_DHCP_LIGHT + uint8_t sname[64]; + uint8_t file[128]; +#endif + uint8_t options[312]; +}; + +struct dhcpc_state_s +{ + struct uip_udp_conn *ds_conn; + const void *ds_macaddr; + int ds_maclen; + int sockfd; + struct in_addr ipaddr; + struct in_addr serverid; + struct dhcp_msg packet; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static const uint8_t xid[4] = {0xad, 0xde, 0x12, 0x23}; +static const uint8_t magic_cookie[4] = {99, 130, 83, 99}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: dhcpc_add<option> + ****************************************************************************/ + +static uint8_t *dhcpc_addmsgtype(uint8_t *optptr, uint8_t type) +{ + *optptr++ = DHCP_OPTION_MSG_TYPE; + *optptr++ = 1; + *optptr++ = type; + return optptr; +} + +static uint8_t *dhcpc_addserverid(struct in_addr *serverid, uint8_t *optptr) +{ + *optptr++ = DHCP_OPTION_SERVER_ID; + *optptr++ = 4; + memcpy(optptr, &serverid->s_addr, 4); + return optptr + 4; +} + +static uint8_t *dhcpc_addreqipaddr(struct in_addr *ipaddr, uint8_t *optptr) +{ + *optptr++ = DHCP_OPTION_REQ_IPADDR; + *optptr++ = 4; + memcpy(optptr, &ipaddr->s_addr, 4); + return optptr + 4; +} + +static uint8_t *dhcpc_addreqoptions(uint8_t *optptr) +{ + *optptr++ = DHCP_OPTION_REQ_LIST; + *optptr++ = 3; + *optptr++ = DHCP_OPTION_SUBNET_MASK; + *optptr++ = DHCP_OPTION_ROUTER; + *optptr++ = DHCP_OPTION_DNS_SERVER; + return optptr; +} + +static uint8_t *dhcpc_addend(uint8_t *optptr) +{ + *optptr++ = DHCP_OPTION_END; + return optptr; +} + +/**************************************************************************** + * Name: dhcpc_sendmsg + ****************************************************************************/ + +static int dhcpc_sendmsg(struct dhcpc_state_s *pdhcpc, + struct dhcpc_state *presult, int msgtype) +{ + struct sockaddr_in addr; + uint8_t *pend; + in_addr_t serverid = INADDR_BROADCAST; + int len; + + /* Create the common message header settings */ + + memset(&pdhcpc->packet, 0, sizeof(struct dhcp_msg)); + pdhcpc->packet.op = DHCP_REQUEST; + pdhcpc->packet.htype = DHCP_HTYPE_ETHERNET; + pdhcpc->packet.hlen = pdhcpc->ds_maclen; + memcpy(pdhcpc->packet.xid, xid, 4); + memcpy(pdhcpc->packet.chaddr, pdhcpc->ds_macaddr, pdhcpc->ds_maclen); + memset(&pdhcpc->packet.chaddr[pdhcpc->ds_maclen], 0, 16 - pdhcpc->ds_maclen); + memcpy(pdhcpc->packet.options, magic_cookie, sizeof(magic_cookie)); + + /* Add the common header options */ + + pend = &pdhcpc->packet.options[4]; + pend = dhcpc_addmsgtype(pend, msgtype); + + /* Handle the message specific settings */ + + switch (msgtype) + { + /* Broadcast DISCOVER message to all servers */ + + case DHCPDISCOVER: + pdhcpc->packet.flags = HTONS(BOOTP_BROADCAST); /* Broadcast bit. */ + pend = dhcpc_addreqoptions(pend); + break; + + /* Send REQUEST message to the server that sent the *first* OFFER */ + + case DHCPREQUEST: + pdhcpc->packet.flags = HTONS(BOOTP_BROADCAST); /* Broadcast bit. */ + memcpy(pdhcpc->packet.ciaddr, &pdhcpc->ipaddr.s_addr, 4); + pend = dhcpc_addserverid(&pdhcpc->serverid, pend); + pend = dhcpc_addreqipaddr(&pdhcpc->ipaddr, pend); + break; + + /* Send DECLINE message to the server that sent the *last* OFFER */ + + case DHCPDECLINE: + memcpy(pdhcpc->packet.ciaddr, &presult->ipaddr.s_addr, 4); + pend = dhcpc_addserverid(&presult->serverid, pend); + serverid = presult->serverid.s_addr; + break; + + default: + return ERROR; + } + + pend = dhcpc_addend(pend); + len = pend - (uint8_t*)&pdhcpc->packet; + + /* Send the request */ + + addr.sin_family = AF_INET; + addr.sin_port = HTONS(DHCPC_SERVER_PORT); + addr.sin_addr.s_addr = serverid; + + return sendto(pdhcpc->sockfd, &pdhcpc->packet, len, 0, + (struct sockaddr*)&addr, sizeof(struct sockaddr_in)); +} + +/**************************************************************************** + * Name: dhcpc_parseoptions + ****************************************************************************/ + +static uint8_t dhcpc_parseoptions(struct dhcpc_state *presult, uint8_t *optptr, int len) +{ + uint8_t *end = optptr + len; + uint8_t type = 0; + + while (optptr < end) + { + switch(*optptr) + { + case DHCP_OPTION_SUBNET_MASK: + /* Get subnet mask in network order */ + + memcpy(&presult->netmask.s_addr, optptr + 2, 4); + break; + + case DHCP_OPTION_ROUTER: + /* Get the default router address in network order */ + + memcpy(&presult->default_router.s_addr, optptr + 2, 4); + break; + + case DHCP_OPTION_DNS_SERVER: + /* Get the DNS server address in network order */ + + memcpy(&presult->dnsaddr.s_addr, optptr + 2, 4); + break; + + case DHCP_OPTION_MSG_TYPE: + /* Get message type */ + + type = *(optptr + 2); + break; + + case DHCP_OPTION_SERVER_ID: + /* Get server address in network order */ + + memcpy(&presult->serverid.s_addr, optptr + 2, 4); + break; + + case DHCP_OPTION_LEASE_TIME: + { + /* Get lease time (in seconds) in host order */ + + uint16_t tmp[2]; + memcpy(tmp, optptr + 2, 4); + presult->lease_time = ((uint32_t)ntohs(tmp[0])) << 16 | (uint32_t)ntohs(tmp[1]); + } + break; + + case DHCP_OPTION_END: + return type; + } + + optptr += optptr[1] + 2; + } + return type; +} + +/**************************************************************************** + * Name: dhcpc_parsemsg + ****************************************************************************/ + +static uint8_t dhcpc_parsemsg(struct dhcpc_state_s *pdhcpc, int buflen, + struct dhcpc_state *presult) +{ + if (pdhcpc->packet.op == DHCP_REPLY && + memcmp(pdhcpc->packet.xid, xid, sizeof(xid)) == 0 && + memcmp(pdhcpc->packet.chaddr, pdhcpc->ds_macaddr, pdhcpc->ds_maclen) == 0) + { + memcpy(&presult->ipaddr.s_addr, pdhcpc->packet.yiaddr, 4); + return dhcpc_parseoptions(presult, &pdhcpc->packet.options[4], buflen); + } + return 0; +} + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: dhcpc_open + ****************************************************************************/ + +void *dhcpc_open(const void *macaddr, int maclen) +{ + struct dhcpc_state_s *pdhcpc; + struct sockaddr_in addr; + struct timeval tv; + + dbg("MAC: %02x:%02x:%02x:%02x:%02x:%02x\n", + ((uint8_t*)macaddr)[0], ((uint8_t*)macaddr)[1], ((uint8_t*)macaddr)[2], + ((uint8_t*)macaddr)[3], ((uint8_t*)macaddr)[4], ((uint8_t*)macaddr)[5]); + + /* Allocate an internal DHCP structure */ + + pdhcpc = (struct dhcpc_state_s *)malloc(sizeof(struct dhcpc_state_s)); + if (pdhcpc) + { + /* Initialize the allocated structure */ + + memset(pdhcpc, 0, sizeof(struct dhcpc_state_s)); + pdhcpc->ds_macaddr = macaddr; + pdhcpc->ds_maclen = maclen; + + /* Create a UDP socket */ + + pdhcpc->sockfd = socket(PF_INET, SOCK_DGRAM, 0); + if (pdhcpc->sockfd < 0) + { + free(pdhcpc); + return NULL; + } + + /* bind the socket */ + + addr.sin_family = AF_INET; + addr.sin_port = HTONS(DHCPC_CLIENT_PORT); + addr.sin_addr.s_addr = INADDR_ANY; + + if (bind(pdhcpc->sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) < 0) + { + close(pdhcpc->sockfd); + free(pdhcpc); + return NULL; + } + + /* Configure for read timeouts */ + + tv.tv_sec = 10; + tv.tv_usec = 0; + if (setsockopt(pdhcpc->sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)) < 0) + { + close(pdhcpc->sockfd); + free(pdhcpc); + return NULL; + } + } + + return (void*)pdhcpc; +} + +/**************************************************************************** + * Name: dhcpc_close + ****************************************************************************/ + +void dhcpc_close(void *handle) +{ + struct dchcpc_state_internal *pdhcpc = (struct dchcpc_state_internal *)handle; + if (pdhcpc) + { + free(pdhcpc); + } +} + +/**************************************************************************** + * Name: dhcpc_request + ****************************************************************************/ + +int dhcpc_request(void *handle, struct dhcpc_state *presult) +{ + struct dhcpc_state_s *pdhcpc = (struct dhcpc_state_s *)handle; + struct in_addr oldaddr; + struct in_addr newaddr; + ssize_t result; + uint8_t msgtype; + int retries; + int state; + + /* Save the currently assigned IP address (should be INADDR_ANY) */ + + oldaddr.s_addr = 0; + uip_gethostaddr("eth0", &oldaddr); + + /* Loop until we receive the lease (or an error occurs) */ + + do + { + /* Set the IP address to INADDR_ANY. */ + + newaddr.s_addr = INADDR_ANY; + (void)uip_sethostaddr("eth0", &newaddr); + + /* Loop sending DISCOVER until we receive an OFFER from a DHCP + * server. We will lock on to the first OFFER and decline any + * subsequent offers (which will happen if there are more than one + * DHCP servers on the network. + */ + + state = STATE_INITIAL; + do + { + /* Send the DISCOVER command */ + + dbg("Broadcast DISCOVER\n"); + if (dhcpc_sendmsg(pdhcpc, presult, DHCPDISCOVER) < 0) + { + return ERROR; + } + + /* Get the DHCPOFFER response */ + + result = recv(pdhcpc->sockfd, &pdhcpc->packet, sizeof(struct dhcp_msg), 0); + if (result >= 0) + { + msgtype = dhcpc_parsemsg(pdhcpc, result, presult); + if (msgtype == DHCPOFFER) + { + /* Save the servid from the presult so that it is not clobbered + * by a new OFFER. + */ + + dbg("Received OFFER from %08x\n", ntohl(presult->serverid.s_addr)); + pdhcpc->ipaddr.s_addr = presult->ipaddr.s_addr; + pdhcpc->serverid.s_addr = presult->serverid.s_addr; + + /* Temporarily use the address offered by the server and break + * out of the loop. + */ + + (void)uip_sethostaddr("eth0", &presult->ipaddr); + state = STATE_HAVE_OFFER; + } + } + + /* An error has occurred. If this was a timeout error (meaning that + * nothing was received on this socket for a long period of time). + * Then loop and send the DISCOVER command again. + */ + + else if (*get_errno_ptr() != EAGAIN) + { + /* An error other than a timeout was received -- error out */ + + return ERROR; + } + } + while (state == STATE_INITIAL); + + + /* Loop sending the REQUEST up to three times (if there is no response) */ + + retries = 0; + do + { + /* Send the REQUEST message to obtain the lease that was offered to us. */ + + dbg("Send REQUEST\n"); + if (dhcpc_sendmsg(pdhcpc, presult, DHCPREQUEST) < 0) + { + return ERROR; + } + retries++; + + /* Get the ACK/NAK response to the REQUEST (or timeout) */ + + result = recv(pdhcpc->sockfd, &pdhcpc->packet, sizeof(struct dhcp_msg), 0); + if (result >= 0) + { + /* Parse the response */ + + msgtype = dhcpc_parsemsg(pdhcpc, result, presult); + + /* The ACK response means that the server has accepted our request + * and we have the lease. + */ + + if (msgtype == DHCPACK) + { + dbg("Received ACK\n"); + state = STATE_HAVE_LEASE; + } + + /* NAK means the server has refused our request. Break out of + * this loop with state == STATE_HAVE_OFFER and send DISCOVER again + */ + + else if (msgtype == DHCPNAK) + { + dbg("Received NAK\n"); + break; + } + + /* If we get any OFFERs from other servers, then decline them now + * and continue waiting for the ACK from the server that we + * requested from. + */ + + else if (msgtype == DHCPOFFER) + { + dbg("Received another OFFER, send DECLINE\n"); + (void)dhcpc_sendmsg(pdhcpc, presult, DHCPDECLINE); + } + + /* Otherwise, it is something that we do not recognize */ + + else + { + dbg("Ignoring msgtype=%d\n", msgtype); + } + } + + /* An error has occurred. If this was a timeout error (meaning + * that nothing was received on this socket for a long period of time). + * Then break out and send the DISCOVER command again (at most + * 3 times). + */ + + else if (*get_errno_ptr() != EAGAIN) + { + /* An error other than a timeout was received */ + + (void)uip_sethostaddr("eth0", &oldaddr); + return ERROR; + } + } + while (state == STATE_HAVE_OFFER && retries < 3); + } + while (state != STATE_HAVE_LEASE); + + dbg("Got IP address %d.%d.%d.%d\n", + (presult->ipaddr.s_addr >> 24 ) & 0xff, + (presult->ipaddr.s_addr >> 16 ) & 0xff, + (presult->ipaddr.s_addr >> 8 ) & 0xff, + (presult->ipaddr.s_addr ) & 0xff); + dbg("Got netmask %d.%d.%d.%d\n", + (presult->netmask.s_addr >> 24 ) & 0xff, + (presult->netmask.s_addr >> 16 ) & 0xff, + (presult->netmask.s_addr >> 8 ) & 0xff, + (presult->netmask.s_addr ) & 0xff); + dbg("Got DNS server %d.%d.%d.%d\n", + (presult->dnsaddr.s_addr >> 24 ) & 0xff, + (presult->dnsaddr.s_addr >> 16 ) & 0xff, + (presult->dnsaddr.s_addr >> 8 ) & 0xff, + (presult->dnsaddr.s_addr ) & 0xff); + dbg("Got default router %d.%d.%d.%d\n", + (presult->default_router.s_addr >> 24 ) & 0xff, + (presult->default_router.s_addr >> 16 ) & 0xff, + (presult->default_router.s_addr >> 8 ) & 0xff, + (presult->default_router.s_addr ) & 0xff); + dbg("Lease expires in %d seconds\n", presult->lease_time); + return OK; +} diff --git a/apps/netutils/dhcpd/Makefile b/apps/netutils/dhcpd/Makefile new file mode 100644 index 000000000..bcfb0330f --- /dev/null +++ b/apps/netutils/dhcpd/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/dhcpd/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# DHCP Daemn Library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_UDP),y) +CSRCS += dhcpd.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/dhcpd/dhcpd.c b/apps/netutils/dhcpd/dhcpd.c new file mode 100644 index 000000000..39050bd62 --- /dev/null +++ b/apps/netutils/dhcpd/dhcpd.c @@ -0,0 +1,1393 @@ +/**************************************************************************** + * netutils/dhcpd/dhcpd.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_DHCPD_HOST +# include <stdio.h> + +# define HTONS(a) htons(a) +# define HTONL(a) htonl(a) + +# define CONFIG_CPP_HAVE_WARNING 1 +# define FAR + +# define ndbg(...) printf(__VA_ARGS__) +# define nvdbg(...) printf(__VA_ARGS__) + +# define ERROR (-1) +# define OK (0) +#else +# include <nuttx/config.h> /* NuttX configuration */ +# include <debug.h> /* For ndbg, vdbg */ +# include <nuttx/compiler.h> /* For CONFIG_CPP_HAVE_WARNING */ +# include <arch/irq.h> /* For irqstore() and friends -- REVISIT */ +# include <net/uip/uip-arp.h> /* For low-level ARP interfaces -- REVISIT */ +# include <apps/netutils/dhcpd.h> /* Advertised DHCPD APIs */ +#endif + +#include <sys/socket.h> +#include <sys/ioctl.h> + +#include <stdint.h> +#include <stdbool.h> +#include <string.h> +#include <unistd.h> +#include <time.h> +#include <errno.h> + +#include <net/if.h> +#include <netinet/in.h> +#include <arpa/inet.h> + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +#define DHCP_SERVER_PORT 67 +#define DHCP_CLIENT_PORT 68 + +/* Option codes understood in this file */ +/* Code Data Description */ +/* Length */ +#define DHCP_OPTION_PAD 1 /* 1 Pad */ +#define DHCP_OPTION_REQ_IPADDR 50 /* 4 Requested IP Address */ +#define DHCP_OPTION_LEASE_TIME 51 /* 4 IP address lease time */ +#define DHCP_OPTION_OVERLOAD 52 /* 1 Option overload */ +#define DHCP_OPTION_MSG_TYPE 53 /* 1 DHCP message type */ +#define DHCP_OPTION_SERVER_ID 54 /* 4 Server identifier */ +#define DHCP_OPTION_END 255 /* 0 End */ + +/* Values for the dhcp msg 'op' field */ + +#define DHCP_REQUEST 1 +#define DHCP_REPLY 2 + +/* DHCP message types understood in this file */ + +#define DHCPDISCOVER 1 /* Received from client only */ +#define DHCPOFFER 2 /* Sent from server only */ +#define DHCPREQUEST 3 /* Received from client only */ +#define DHCPDECLINE 4 /* Received from client only */ +#define DHCPACK 5 /* Sent from server only */ +#define DHCPNAK 6 /* Sent from server only */ +#define DHCPRELEASE 7 /* Received from client only */ +#define DHCPINFORM 8 /* Not used */ + +/* The form of an option is: + * code - 1 byte + * length - 1 byte + * data - variable number of bytes + */ + +#define DHCPD_OPTION_CODE 0 +#define DHCPD_OPTION_LENGTH 1 +#define DHCPD_OPTION_DATA 2 + +/* Size of options in DHCP message */ + +#define DHCPD_OPTIONS_SIZE 312 + +/* Values for htype and hlen field */ + +#define DHCP_HTYPE_ETHERNET 1 +#define DHCP_HLEN_ETHERNET 6 + +/* Values for flags field */ + +#define BOOTP_BROADCAST 0x8000 + +/* Legal values for this option are: + * + * 1 the 'file' field is used to hold options + * 2 the 'sname' field is used to hold options + * 3 both fields are used to hold options + */ + +#define DHCPD_OPTION_FIELD 0 +#define DHCPD_FILE_FIELD 1 +#define DHCPD_SNAME_FIELD 2 + +#ifndef CONFIG_NETUTILS_DHCPD_LEASETIME +# define CONFIG_NETUTILS_DHCPD_LEASETIME (60*60*24*10) /* 10 days */ +# undef CONFIG_NETUTILS_DHCPD_MINLEASETIME +# undef CONFIG_NETUTILS_DHCPD_MAXLEASETIME +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_MINLEASETIME +# define CONFIG_NETUTILS_DHCPD_MINLEASETIME (60*60*24*1) /* 1 days */ +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_MAXLEASETIME +# define CONFIG_NETUTILS_DHCPD_MAXLEASETIME (60*60*24*30) /* 30 days */ +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_INTERFACE +# define CONFIG_NETUTILS_DHCPD_INTERFACE "eth0" +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_MAXLEASES +# define CONFIG_NETUTILS_DHCPD_MAXLEASES 16 +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_STARTIP +# define CONFIG_NETUTILS_DHCPD_STARTIP (10L<<24|0L<<16|0L<<16|2L) +#endif + +#undef CONFIG_NETUTILS_DHCP_OPTION_ENDIP +#define CONFIG_NETUTILS_DHCP_OPTION_ENDIP \ + (CONFIG_NETUTILS_DHCPD_STARTIP + CONFIG_NETUTILS_DHCPD_MAXLEASES - 1) + +#ifndef CONFIG_NETUTILS_DHCPD_OFFERTIME +# define CONFIG_NETUTILS_DHCPD_OFFERTIME (60*60) /* 1 hour */ +#endif + +#ifndef CONFIG_NETUTILS_DHCPD_DECLINETIME +# define CONFIG_NETUTILS_DHCPD_DECLINETIME (60*60) /* 1 hour */ +#endif + +#undef HAVE_LEASE_TIME +#if defined(CONFIG_NETUTILS_DHCPD_HOST) || !defined(CONFIG_DISABLE_POSIX_TIMERS) +# define HAVE_LEASE_TIME 1 +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/* This structure describes one element in the lease table. There is one slot + * in the lease table for each assign-able IP address (hence, the IP address + * itself does not have to be in the table. + */ + +struct lease_s +{ + uint8_t mac[DHCP_HLEN_ETHERNET]; /* MAC address (network order) -- could be larger! */ + bool allocated; /* true: IP address is allocated */ +#ifdef HAVE_LEASE_TIME + time_t expiry; /* Lease expiration time (seconds past Epoch) */ +#endif +}; + +struct dhcpmsg_s +{ + uint8_t op; + uint8_t htype; + uint8_t hlen; + uint8_t hops; + uint8_t xid[4]; + uint16_t secs; + uint16_t flags; + uint8_t ciaddr[4]; + uint8_t yiaddr[4]; + uint8_t siaddr[4]; + uint8_t giaddr[4]; + uint8_t chaddr[16]; +#ifndef CONFIG_NET_DHCP_LIGHT + uint8_t sname[64]; + uint8_t file[128]; +#endif + uint8_t options[312]; +}; + +struct dhcpd_state_s +{ + /* Server configuration */ + + in_addr_t ds_serverip; /* The server IP address */ + + /* Message buffers */ + + struct dhcpmsg_s ds_inpacket; /* Holds the incoming DHCP client message */ + struct dhcpmsg_s ds_outpacket; /* Holds the outgoing DHCP server message */ + + /* Parsed options from the incoming DHCP client message */ + + uint8_t ds_optmsgtype; /* Incoming DHCP message type */ + in_addr_t ds_optreqip; /* Requested IP address (host order) */ + in_addr_t ds_optserverip; /* Serverip IP address (host order) */ + time_t ds_optleasetime; /* Requested lease time (host order) */ + + /* End option pointer for outgoing DHCP server message */ + + uint8_t *ds_optend; + + /* Leases */ + + struct lease_s ds_leases[CONFIG_NETUTILS_DHCPD_MAXLEASES]; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static const uint8_t g_magiccookie[4] = {99, 130, 83, 99}; +static const uint8_t g_anyipaddr[4] = {0, 0, 0, 0}; +static struct dhcpd_state_s g_state; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: dhcpd_arpupdate + ****************************************************************************/ + +#ifndef CONFIG_NETUTILS_DHCPD_HOST +static inline void dhcpd_arpupdate(uint16_t *pipaddr, uint8_t *phwaddr) +{ + uip_lock_t flags; + + /* Disable interrupts and update the ARP table -- very non-portable hack. + * REVISIT -- switch to the SIOCSARP ioctl call if/when it is implemented. + */ + + flags = uip_lock(); + uip_arp_update(pipaddr, phwaddr); + uip_unlock(flags); +} +#else +# define dhcpd_arpupdate(pipaddr,phwaddr) +#endif + +/**************************************************************************** + * Name: dhcpd_time + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_DHCPD_HOST +# define dhcpd_time() time(0) +#elif defined(HAVE_LEASE_TIME) +static time_t dhcpd_time(void) +{ + struct timespec time; + time_t ret = 0; + + if (clock_gettime(CLOCK_REALTIME, &time) == OK) + { + ret = time.tv_sec; + } + return ret; +} +#else +# define dhcpd_time() (0) +#endif + +/**************************************************************************** + * Name: dhcpd_leaseexpired + ****************************************************************************/ + +#ifdef HAVE_LEASE_TIME +static inline bool dhcpd_leaseexpired(struct lease_s *lease) +{ + if (lease->expiry < dhcpd_time()) + { + return false; + } + else + { + memset(lease, 0, sizeof(struct lease_s)); + return true; + } +} +#else +# define dhcpd_leaseexpired(lease) (false) +#endif + +/**************************************************************************** + * Name: dhcpd_setlease + ****************************************************************************/ + +struct lease_s *dhcpd_setlease(const uint8_t *mac, in_addr_t ipaddr, time_t expiry) +{ + int ndx = ntohl(ipaddr) - CONFIG_NETUTILS_DHCPD_STARTIP; + struct lease_s *ret = NULL; + + if (ndx >= 0 && ndx < CONFIG_NETUTILS_DHCPD_MAXLEASES) + { + ret = &g_state.ds_leases[ndx]; + memcpy(ret->mac, mac, DHCP_HLEN_ETHERNET); + ret->allocated = true; +#ifdef HAVE_LEASE_TIME + ret->expiry = dhcpd_time() + expiry; +#endif + } + return ret; +} + +/**************************************************************************** + * Name: dhcp_leaseipaddr + ****************************************************************************/ + +static inline in_addr_t dhcp_leaseipaddr( struct lease_s *lease) +{ + return htonl((g_state.ds_leases - lease)/sizeof(struct lease_s) + CONFIG_NETUTILS_DHCPD_STARTIP); +} + +/**************************************************************************** + * Name: dhcpd_findbymac + ****************************************************************************/ + +static struct lease_s *dhcpd_findbymac(const uint8_t *mac) +{ + int i; + + for (i = 0; i < CONFIG_NETUTILS_DHCPD_MAXLEASES; i++) + { + if (memcmp(g_state.ds_leases[i].mac, mac, DHCP_HLEN_ETHERNET) == 0) + { + return &(g_state.ds_leases[i]); + } + } + + return NULL; +} + +/**************************************************************************** + * Name: dhcpd_findbyipaddr + ****************************************************************************/ + +static struct lease_s *dhcpd_findbyipaddr(in_addr_t ipaddr) +{ + if (ipaddr >= CONFIG_NETUTILS_DHCPD_STARTIP && + ipaddr <= CONFIG_NETUTILS_DHCP_OPTION_ENDIP) + { + struct lease_s *lease = &g_state.ds_leases[ipaddr - CONFIG_NETUTILS_DHCPD_STARTIP]; + if (lease->allocated > 0) + { + return lease; + } + } + return NULL; +} + +/**************************************************************************** + * Name: dhcpd_allocipaddr + ****************************************************************************/ + +in_addr_t dhcpd_allocipaddr(void) +{ + struct lease_s *lease = NULL; + in_addr_t ipaddr; + + ipaddr = CONFIG_NETUTILS_DHCPD_STARTIP; + for (; ipaddr <= CONFIG_NETUTILS_DHCP_OPTION_ENDIP; ipaddr++) + { + if ((ipaddr & 0xff) == 0 || (ipaddr & 0xff) == 0xff) + { + continue; + } + + lease = dhcpd_findbyipaddr(ipaddr); + if ((!lease || dhcpd_leaseexpired(lease))) + { +#ifdef CONFIG_CPP_HAVE_WARNING +# warning "FIXME: Should check if anything responds to an ARP request or ping" +# warning " to verify that there is no other user of this IP address" +#endif + memset(g_state.ds_leases[ipaddr - CONFIG_NETUTILS_DHCPD_STARTIP].mac, 0, DHCP_HLEN_ETHERNET); + g_state.ds_leases[ipaddr - CONFIG_NETUTILS_DHCPD_STARTIP].allocated = true; +#ifdef HAVE_LEASE_TIME + g_state.ds_leases[ipaddr - CONFIG_NETUTILS_DHCPD_STARTIP].expiry = dhcpd_time() + CONFIG_NETUTILS_DHCPD_OFFERTIME; +#endif + return ntohl(ipaddr); + } + } + return 0; +} + +/**************************************************************************** + * Name: dhcpd_parseoptions + ****************************************************************************/ + +static inline bool dhcpd_parseoptions(void) +{ + uint32_t tmp; + uint8_t *ptr; + uint8_t overloaded; + uint8_t currfield; + int optlen = 0; + int remaining; + + /* Verify that the option field starts with a valid magic number */ + + ptr = g_state.ds_inpacket.options; + if (memcmp(ptr, g_magiccookie, 4) != 0) + { + /* Bad magic number... skip g_state.ds_outpacket */ + + ndbg("Bad magic: %d,%d,%d,%d\n", ptr[0], ptr[1], ptr[2], ptr[3]); + return false; + } + + /* Set up to parse the options */ + + ptr += 4; + remaining = DHCPD_OPTIONS_SIZE - 4; + overloaded = DHCPD_OPTION_FIELD; + currfield = DHCPD_OPTION_FIELD; + + /* Set all options to the default value */ + + g_state.ds_optmsgtype = 0; /* Incoming DHCP message type */ + g_state.ds_optreqip = 0; /* Requested IP address (host order) */ + g_state.ds_optserverip = 0; /* Serverip IP address (host order) */ + g_state.ds_optleasetime = 0; /* Requested lease time (host order) */ + g_state.ds_optend = NULL; + + do + { + /* The form of an option is: + * code - 1 byte + * length - 1 byte + * data - variable number of bytes + */ + + switch (ptr[DHCPD_OPTION_CODE]) + { + /* Skip over any padding bytes */ + + case DHCP_OPTION_PAD: + optlen = 1; + break; + + /* the Overload option is used to indicate that the DHCP 'sname' or 'file' + * fields are being overloaded by using them to carry DHCP options. A DHCP + * server inserts this option if the returned parameters will exceed the + * usual space allotted for options. + * + * If this option is present, the client interprets the specified additional + * fields after it concludes interpretation of the standard option fields. + * + * Legal values for this option are: + * + * 1 the 'file' field is used to hold options + * 2 the 'sname' field is used to hold options + * 3 both fields are used to hold options + */ + +#ifndef CONFIG_NET_DHCP_LIGHT + case DHCP_OPTION_OVERLOAD: + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + if (optlen >= 1 && optlen < remaining) + { + overloaded = ptr[DHCPD_OPTION_DATA]; + } + break; +#endif + + case DHCP_OPTION_END: +#ifndef CONFIG_NET_DHCP_LIGHT + if (currfield == DHCPD_OPTION_FIELD && + (overloaded & DHCPD_FILE_FIELD) != 0) + { + ptr = g_state.ds_inpacket.file; + remaining = sizeof(g_state.ds_inpacket.file); + currfield = DHCPD_FILE_FIELD; + } + else if (currfield == DHCPD_FILE_FIELD && + (overloaded & DHCPD_SNAME_FIELD) != 0) + { + ptr = g_state.ds_inpacket.sname; + remaining = sizeof(g_state.ds_inpacket.sname); + currfield = DHCPD_SNAME_FIELD; + } + else + { + return true; + } + break; +#else + return true; +#endif + + case DHCP_OPTION_REQ_IPADDR: /* Requested IP Address */ + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + if (optlen >= 4 && optlen < remaining) + { + memcpy(&tmp, &ptr[DHCPD_OPTION_DATA], 4); + g_state.ds_optreqip = (in_addr_t)ntohl(tmp); + } + break; + + case DHCP_OPTION_LEASE_TIME: /* IP address lease time */ + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + if (optlen >= 4 && optlen < remaining) + { + memcpy(&tmp, &ptr[DHCPD_OPTION_DATA], 4); + g_state.ds_optleasetime = (time_t)ntohl(tmp); + } + break; + + case DHCP_OPTION_MSG_TYPE: /* DHCP message type */ + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + if (optlen >= 1 && optlen < remaining) + { + g_state.ds_optmsgtype = ptr[DHCPD_OPTION_DATA]; + } + break; + + case DHCP_OPTION_SERVER_ID: /* Server identifier */ + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + if (optlen >= 4 && optlen < remaining) + { + memcpy(&tmp, &ptr[DHCPD_OPTION_DATA], 4); + g_state.ds_optserverip = (in_addr_t)ntohl(tmp); + } + break; + + default: + /* Skip over unsupported options */ + + optlen = ptr[DHCPD_OPTION_LENGTH] + 2; + break; + } + + /* Advance to the next option */ + + ptr += optlen; + remaining -= optlen; + } + while (remaining > 0); + return false; +} + +/**************************************************************************** + * Name: dhcpd_verifyreqip + ****************************************************************************/ + +static inline bool dhcpd_verifyreqip(void) +{ + struct lease_s *lease; + + /* Verify that the requested IP address is within the supported lease range */ + + if (g_state.ds_optreqip > 0 && + g_state.ds_optreqip >= CONFIG_NETUTILS_DHCPD_STARTIP && + g_state.ds_optreqip <= CONFIG_NETUTILS_DHCP_OPTION_ENDIP) + { + /* And verify that the lease has not already been taken or offered + * (unless the lease/offer is expired, then the address is free game). + */ + + lease = dhcpd_findbyipaddr(g_state.ds_optreqip); + if (!lease || dhcpd_leaseexpired(lease)) + { + return true; + } + } + return false; +} + +/**************************************************************************** + * Name: dhcpd_verifyreqleasetime + ****************************************************************************/ + +static inline bool dhcpd_verifyreqleasetime(uint32_t *leasetime) +{ + uint32_t tmp = g_state.ds_optleasetime; + + /* Did the client request a specific lease time? */ + + if (tmp != 0) + { + /* Yes.. Verify that the requested lease time is within a valid range */ + + if (tmp > CONFIG_NETUTILS_DHCPD_MAXLEASETIME) + { + tmp = CONFIG_NETUTILS_DHCPD_MAXLEASETIME; + } + else if (tmp < CONFIG_NETUTILS_DHCPD_MINLEASETIME) + { + tmp = CONFIG_NETUTILS_DHCPD_MINLEASETIME; + } + + /* Return the clipped lease time */ + + *leasetime = tmp; + return true; + } + return false; +} + +/**************************************************************************** + * Name: dhcpd_addoption + ****************************************************************************/ + +static int dhcpd_addoption(uint8_t *option) +{ + int offset; + int len = 4; + + if (g_state.ds_optend) + { + offset = g_state.ds_outpacket.options - g_state.ds_optend; + len = option[DHCPD_OPTION_LENGTH] + 2; + + /* Check if the option will fit into the options array */ + + if (offset + len + 1 < DHCPD_OPTIONS_SIZE) + { + /* Copy the option into the option array */ + + memcpy(g_state.ds_optend, option, len); + g_state.ds_optend += len; + *g_state.ds_optend = DHCP_OPTION_END; + } + } + return len; +} + +/**************************************************************************** + * Name: dhcpd_addoption8 + ****************************************************************************/ + +static int dhcpd_addoption8(uint8_t code, uint8_t value) +{ + uint8_t option[3]; + + /* Construct the option sequence */ + + option[DHCPD_OPTION_CODE] = code; + option[DHCPD_OPTION_LENGTH] = 1; + option[DHCPD_OPTION_DATA] = value; + + /* Add the option sequence to the response */ + + return dhcpd_addoption(option); +} + +/**************************************************************************** + * Name: dhcpd_addoption32 + ****************************************************************************/ + +static int dhcpd_addoption32(uint8_t code, uint32_t value) +{ + uint8_t option[6]; + + /* Construct the option sequence */ + + option[DHCPD_OPTION_CODE] = code; + option[DHCPD_OPTION_LENGTH] = 4; + memcpy(&option[DHCPD_OPTION_DATA], &value, 4); + + /* Add the option sequence to the response */ + + return dhcpd_addoption(option); +} + +/**************************************************************************** + * Name: dhcpd_soclet + ****************************************************************************/ + +static inline int dhcpd_socket(void) +{ + int sockfd; +#if defined(HAVE_SO_REUSEADDR) || defined(HAVE_SO_BROADCAST) + int optval; + int ret; +#endif + + /* Create a socket to listen for requests from DHCP clients */ + + sockfd = socket(PF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) + { + ndbg("socket failed: %d\n", errno); + return ERROR; + } + + /* Configure the socket */ + +#ifdef HAVE_SO_REUSEADDR + optval = 1; + ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, sizeof(int)); + if (ret < 0) + { + ndbg("setsockopt SO_REUSEADDR failed: %d\n", errno); + close(sockfd); + return ERROR; + } +#endif + +#ifdef HAVE_SO_BROADCAST + optval = 1; + ret = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (void*)&optval, sizeof(int)); + if (ret < 0) + { + ndbg("setsockopt SO_BROADCAST failed: %d\n", errno); + close(sockfd); + return ERROR; + } +#endif + + return sockfd; + +} + +/**************************************************************************** + * Name: dhcpd_openresponder + ****************************************************************************/ + +static inline int dhcpd_openresponder(void) +{ + struct sockaddr_in addr; + int sockfd; + int ret; + + nvdbg("Responder: %08lx\n", (long)g_state.ds_serverip); + + /* Create a socket to listen for requests from DHCP clients */ + + sockfd = dhcpd_socket(); + if (sockfd < 0) + { + ndbg("socket failed: %d\n", errno); + return ERROR; + } + + /* Bind the socket to a local port.*/ + + addr.sin_family = AF_INET; + addr.sin_port = 0; + addr.sin_addr.s_addr = g_state.ds_serverip; + + ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); + if (ret < 0) + { + ndbg("bind failed, port=%d addr=%08lx: %d\n", + addr.sin_port, (long)addr.sin_addr.s_addr, errno); + close(sockfd); + return ERROR; + } + + return sockfd; +} + +/**************************************************************************** + * Name: dhcpd_initpacket + ****************************************************************************/ + +static void dhcpd_initpacket(uint8_t mtype) +{ + uint32_t nulladdr = 0; + + /* Set up the generic parts of the DHCP server message */ + + memset(&g_state.ds_outpacket, 0, sizeof(struct dhcpmsg_s)); + + g_state.ds_outpacket.op = DHCP_REPLY; + g_state.ds_outpacket.htype = g_state.ds_inpacket.htype; + g_state.ds_outpacket.hlen = g_state.ds_inpacket.hlen; + + memcpy(&g_state.ds_outpacket.xid, &g_state.ds_inpacket.xid, 4); + memcpy(g_state.ds_outpacket.chaddr, g_state.ds_inpacket.chaddr, 16); + + if (memcmp(g_state.ds_outpacket.giaddr, &nulladdr, 4) != 0) + { + g_state.ds_outpacket.flags = g_state.ds_inpacket.flags; + } + else + { + g_state.ds_outpacket.flags = 0; + } + memset(g_state.ds_outpacket.giaddr, 0, 4); + + /* Add the generic options */ + + memcpy(g_state.ds_outpacket.options, g_magiccookie, 4); + g_state.ds_optend = &g_state.ds_outpacket.options[4]; + *g_state.ds_optend = DHCP_OPTION_END; + dhcpd_addoption8(DHCP_OPTION_MSG_TYPE, mtype); + dhcpd_addoption32(DHCP_OPTION_SERVER_ID, g_state.ds_serverip); +} + +/**************************************************************************** + * Name: dhcpd_sendpacket + ****************************************************************************/ + +static int dhcpd_sendpacket(int bbroadcast) +{ + struct sockaddr_in addr; + in_addr_t ipaddr; + int sockfd; + int len; + int ret = ERROR; + +#ifdef CONFIG_NETUTILS_DHCPD_IGNOREBROADCAST + /* This is a hack. I've had problems with Windows machines responding + * to unicast. I think this is associated with a Windows registry key in + * HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DHCPServer\Parameters: + * The IgnoreBroadcastFlag value controls this behavior: A value of 1 will + * cause the server to ignore the client broadcast flag and always respond + * with multicast; the value 0 to allows clients to request unicast. + */ + + ipaddr = INADDR_BROADCAST; +#else + /* Determine which address to respond to (or if we need to broadcast the response) + * + * (1) If he caller know that it needs to multicast the response, it will set bbroadcast. + * (2) Otherwise, if the client already has and address (ciaddr), then use that for uni-cast + * (3) Broadcast if the client says it can't handle uni-cast (BOOTP_BROADCAST set) + * (4) Otherwise, the client claims it can handle the uni-casst response and we + * will uni-cast to the offered address (yiaddr). + * + * NOTE: We really should also check the giaddr field. If no zero, the server should + * send any return messages to the 'DHCP server' port on the BOOTP relay agent whose + * address appears in 'giaddr'. + */ + + if (bbroadcast) + { + ipaddr = INADDR_BROADCAST; + } + else if (memcmp(g_state.ds_outpacket.ciaddr, g_anyipaddr, 4) != 0) + { + dhcpd_arpupdate((uint16_t*)g_state.ds_outpacket.ciaddr, g_state.ds_outpacket.chaddr); + memcpy(&ipaddr, g_state.ds_outpacket.ciaddr, 4); + } + else if (g_state.ds_outpacket.flags & HTONS(BOOTP_BROADCAST)) + { + ipaddr = INADDR_BROADCAST; + } + else + { + dhcpd_arpupdate((uint16_t*)g_state.ds_outpacket.yiaddr, g_state.ds_outpacket.chaddr); + memcpy(&ipaddr, g_state.ds_outpacket.yiaddr, 4); + } +#endif + + /* Create a socket to respond with a packet to the client. We + * cannot re-use the listener socket because it is not bound correctly + */ + + sockfd = dhcpd_openresponder(); + if (sockfd >= 0) + { + /* Then send the reponse to the DHCP client port at that address */ + + memset(&addr, 0, sizeof(struct sockaddr_in)); + addr.sin_family = AF_INET; + addr.sin_port = HTONS(DHCP_CLIENT_PORT); + addr.sin_addr.s_addr = ipaddr; + + /* Send the minimum sized packet that includes the END option */ + + len = (g_state.ds_optend - (uint8_t*)&g_state.ds_outpacket) + 1; + nvdbg("sendto %08lx:%04x len=%d\n", + (long)addr.sin_addr.s_addr, addr.sin_port, len); + + ret = sendto(sockfd, &g_state.ds_outpacket, len, 0, + (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); + close(sockfd); + } + return ret; +} + +/**************************************************************************** + * Name: dhcpd_sendoffer + ****************************************************************************/ + +static inline int dhcpd_sendoffer(in_addr_t ipaddr, uint32_t leasetime) +{ + nvdbg("Sending offer: %08lx\n", (long)ipaddr); + + /* Initialize the outgoing packet */ + + dhcpd_initpacket(DHCPOFFER); + + /* Add the address offered to the client */ + + memcpy(g_state.ds_outpacket.yiaddr, &ipaddr, 4); + + /* Add the leasetime to the response options */ + + dhcpd_addoption32(DHCP_OPTION_LEASE_TIME, htonl(leasetime)); + + /* Send the offer response */ + +#ifdef CONFIG_NETUTILS_DHCPD_IGNOREBROADCAST + return dhcpd_sendpacket(true); +#else + return dhcpd_sendpacket(false); +#endif +} + +/**************************************************************************** + * Name: dhcpd_sendnak + ****************************************************************************/ + +static int dhcpd_sendnak(void) +{ + /* Initialize and send the NAK response */ + + dhcpd_initpacket(DHCPNAK); + memcpy(g_state.ds_outpacket.ciaddr, g_state.ds_inpacket.ciaddr, 4); + return dhcpd_sendpacket(true); +} + +/**************************************************************************** + * Name: dhcpd_sendack + ****************************************************************************/ + +int dhcpd_sendack(in_addr_t ipaddr) +{ + uint32_t leasetime = CONFIG_NETUTILS_DHCPD_LEASETIME; + + /* Initialize the ACK response */ + + dhcpd_initpacket(DHCPACK); + memcpy(g_state.ds_outpacket.ciaddr, g_state.ds_inpacket.ciaddr, 4); + + /* Add the IP address assigned to the client */ + + memcpy(g_state.ds_outpacket.yiaddr, &ipaddr, 4); + + /* Did the client request a specific lease time? */ + + (void)dhcpd_verifyreqleasetime(&leasetime); + + /* Add the lease time to the response */ + + dhcpd_addoption32(DHCP_OPTION_LEASE_TIME, htonl(leasetime)); + +#ifdef CONFIG_NETUTILS_DHCPD_IGNOREBROADCAST + if (dhcpd_sendpacket(true) < 0) +#else + if (dhcpd_sendpacket(false) < 0) +#endif + { + return ERROR; + } + + dhcpd_setlease(g_state.ds_inpacket.chaddr, ipaddr, leasetime); + return OK; +} + +/**************************************************************************** + * Name: dhcpd_discover + ****************************************************************************/ + +static inline int dhcpd_discover(void) +{ + struct lease_s *lease; + in_addr_t ipaddr; + uint32_t leasetime = CONFIG_NETUTILS_DHCPD_LEASETIME; + + /* Check if the client is aleady in the lease table */ + + lease = dhcpd_findbymac(g_state.ds_inpacket.chaddr); + if (lease) + { + /* Yes... get the remaining time on the lease */ + +#ifdef HAVE_LEASE_TIME + if (!dhcpd_leaseexpired(lease)) + { + leasetime = lease->expiry - dhcpd_time(); + if (leasetime < CONFIG_NETUTILS_DHCPD_MINLEASETIME) + { + leasetime = CONFIG_NETUTILS_DHCPD_MINLEASETIME; + } + } +#endif + /* Get the IP address associated with the lease */ + + ipaddr = dhcp_leaseipaddr(lease); + nvdbg("Already have lease for IP %08lx\n", (long)ipaddr); + } + + /* Check if the client has requested a specific IP address */ + + else if (dhcpd_verifyreqip()) + { + /* Use the requested IP address */ + + ipaddr = g_state.ds_optreqip; + nvdbg("Use requested IP %08lx\n", (long)ipaddr); + } + else + { + /* No... allocate a new IP address */ + + ipaddr = dhcpd_allocipaddr(); + nvdbg("Allocated IP %08lx\n", (long)ipaddr); + } + + /* Did we get any IP address? */ + + if (!ipaddr) + { + /* Nope... return failure */ + + ndbg("Failed to get IP address\n"); + return ERROR; + } + + /* Reserve the leased IP for a shorter time for the offer */ + + if (!dhcpd_setlease(g_state.ds_inpacket.chaddr, ipaddr, CONFIG_NETUTILS_DHCPD_OFFERTIME)) + { + ndbg("Failed to set lease\n"); + return ERROR; + } + + /* Check if the client has requested a specific lease time */ + + (void)dhcpd_verifyreqleasetime(&leasetime); + + /* Send the offer response */ + + return dhcpd_sendoffer(ipaddr, leasetime); +} + +/**************************************************************************** + * Name: dhcpd_request + ****************************************************************************/ + +static inline int dhcpd_request(void) +{ + struct lease_s *lease; + in_addr_t ipaddr; + uint8_t response = 0; + + /* Check if this client already holds a lease. This can happen when the client (1) + * the IP is reserved for the client from a previous offer, or (2) the client is + * re-initializing or rebooting while the lease is still valid. + */ + + lease = dhcpd_findbymac(g_state.ds_inpacket.chaddr); + if (lease) + { + /* Yes.. the client already holds a lease. Verify that the request is consistent + * with the existing lease. + */ + + ipaddr = dhcp_leaseipaddr(lease); + if (g_state.ds_optserverip) + { + /* ACK if the serverip is correct and the requested IP address is the one + * already offered to the client. + */ + + if (g_state.ds_optserverip == ntohl(g_state.ds_serverip) && + (g_state.ds_optreqip != 0 || g_state.ds_optreqip == ipaddr)) + { + response = DHCPACK; + } + else + { + response = DHCPNAK; + } + } + + /* We have the lease and no server IP was requested. Was as specific IP address + * requested? + */ + + else if (g_state.ds_optreqip) + { + /* Yes..ACK if the requested IP address is the one already leased */ + + if (ipaddr == g_state.ds_optreqip) + { + response = DHCPACK; + } + else + { + response = DHCPNAK; + } + } + + /* The client has specified neither a server IP nor requested IP address */ + + else + { + /* ACK if the IP used by the client is the one already assigned to it */ + + if (memcmp(&ipaddr, g_state.ds_inpacket.ciaddr, 4) == 0) + { + response = DHCPACK; + } + else + { + response = DHCPNAK; + } + } + } + + /* The client does not hold a lease (referenced by its MAC address) and is + * requesting a specific IP address that was, apparently, never offered to + * to the client. Perform some sanity checks before sending the NAK. + */ + + else if (g_state.ds_optreqip && !g_state.ds_optserverip) + { + /* Is this IP address already assigned? */ + + lease = dhcpd_findbyipaddr(g_state.ds_optreqip); + if (lease) + { + /* Yes.. Send NAK unless the lease has expired */ + + if (!dhcpd_leaseexpired(lease)) + { + response = DHCPNAK; + } + } + + /* No.. is the requested IP address in range? NAK if not */ + + else if (g_state.ds_optreqip < CONFIG_NETUTILS_DHCPD_STARTIP || + g_state.ds_optreqip > CONFIG_NETUTILS_DHCP_OPTION_ENDIP) + { + response = DHCPNAK; + } + } + + /* Finally, either (1) send the ACK, (2) send a NAK, or (3) remain silent + * based on the checks above. + */ + + if (response == DHCPACK) + { + nvdbg("ACK IP %08lx\n", (long)ipaddr); + dhcpd_sendack(ipaddr); + } + else if (response == DHCPNAK) + { + nvdbg("NAK IP %08lx\n", (long)ipaddr); + dhcpd_sendnak(); + } + + return OK; +} + +/**************************************************************************** + * Name: dhcpd_decline + ****************************************************************************/ + +static inline int dhcpd_decline(void) +{ + struct lease_s *lease; + + /* Find the lease associated with this hardware address */ + + lease = dhcpd_findbymac(g_state.ds_inpacket.chaddr); + if (lease) + { + /* Disassociate the IP from the MAC, but prevent re-used of this + * address for a period of time. + */ + + memset(lease->mac, 0, DHCP_HLEN_ETHERNET); +#ifdef HAVE_LEASE_TIME + lease->expiry = dhcpd_time() + CONFIG_NETUTILS_DHCPD_DECLINETIME; +#endif + } + return OK; +} + +static inline int dhcpd_release(void) +{ + struct lease_s *lease; + + /* Find the lease associated with this hardware address */ + + lease = dhcpd_findbymac(g_state.ds_inpacket.chaddr); + if (lease) + { + /* Release the IP address now */ + + memset(lease, 0, sizeof(struct lease_s)); + } + return OK; +} + +/**************************************************************************** + * Name: dhcpd_openlistener + ****************************************************************************/ + +static inline int dhcpd_openlistener(void) +{ + struct sockaddr_in addr; + struct ifreq req; + int sockfd; + int ret; + + /* Create a socket to listen for requests from DHCP clients */ + + sockfd = dhcpd_socket(); + if (sockfd < 0) + { + ndbg("socket failed: %d\n", errno); + return ERROR; + } + + /* Get the IP address of the selected device */ + + strncpy(req.ifr_name, CONFIG_NETUTILS_DHCPD_INTERFACE, IFNAMSIZ); + ret = ioctl(sockfd, SIOCGIFADDR, (unsigned long)&req); + if (ret < 0) + { + ndbg("setsockopt SIOCGIFADDR failed: %d\n", errno); + close(sockfd); + return ERROR; + } + g_state.ds_serverip = ((struct sockaddr_in*)&req.ifr_addr)->sin_addr.s_addr; + nvdbg("serverip: %08lx\n", ntohl(g_state.ds_serverip)); + + /* Bind the socket to a local port. We have to bind to INADDRY_ANY to + * receive broadcast messages. + */ + + addr.sin_family = AF_INET; + addr.sin_port = htons(DHCP_SERVER_PORT); + addr.sin_addr.s_addr = INADDR_ANY; + + ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)); + if (ret < 0) + { + ndbg("bind failed, port=%d addr=%08lx: %d\n", + addr.sin_port, (long)addr.sin_addr.s_addr, errno); + close(sockfd); + return ERROR; + } + + return sockfd; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: dhcpd_run + ****************************************************************************/ + +int dhcpd_run(void) +{ + int sockfd; + int nbytes; + + nvdbg("Started\n"); + + /* Initialize everything to zero */ + + memset(&g_state, 0, sizeof(struct dhcpd_state_s)); + + /* Now loop indefinitely, reading packets from the DHCP server socket */ + + sockfd = -1; + for (;;) + { + /* Create a socket to listen for requests from DHCP clients */ + + if (sockfd < 0) + { + sockfd = dhcpd_openlistener(); + if (sockfd < 0) + { + ndbg("Failed to create socket\n"); + break; + } + } + + /* Read the next g_state.ds_outpacket */ + + nbytes = recv(sockfd, &g_state.ds_inpacket, sizeof(struct dhcpmsg_s), 0); + if (nbytes < 0) + { + /* On errors (other EINTR), close the socket and try again */ + + ndbg("recv failed: %d\n", errno); + if (errno != EINTR) + { + close(sockfd); + sockfd = -1; + } + continue; + } + + /* Parse the incoming message options */ + + if (!dhcpd_parseoptions()) + { + /* Failed to parse the message options */ + + ndbg("No msg type\n"); + continue; + } + +#ifdef CONFIG_NETUTILS_DHCPD_HOST + /* Get the poor little uC a change to get its recvfrom in place */ + + usleep(500*1000); +#endif + + /* Now process the incoming DHCP message by its message type */ + + switch (g_state.ds_optmsgtype) + { + case DHCPDISCOVER: + nvdbg("DHCPDISCOVER\n"); + dhcpd_discover(); + break; + + case DHCPREQUEST: + nvdbg("DHCPREQUEST\n"); + dhcpd_request(); + break; + + case DHCPDECLINE: + nvdbg("DHCPDECLINE\n"); + dhcpd_decline(); + break; + + case DHCPRELEASE: + nvdbg("DHCPRELEASE\n"); + dhcpd_release(); + break; + + case DHCPINFORM: /* Not supported */ + default: + ndbg("Unsupported message type: %d\n", g_state.ds_optmsgtype); + break; + } + } + return OK; +} diff --git a/apps/netutils/resolv/Makefile b/apps/netutils/resolv/Makefile new file mode 100644 index 000000000..b3ed975dd --- /dev/null +++ b/apps/netutils/resolv/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/resolv/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# Resolver library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_UDP),y) +CSRCS = resolv.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/resolv/resolv.c b/apps/netutils/resolv/resolv.c new file mode 100644 index 000000000..db9e00085 --- /dev/null +++ b/apps/netutils/resolv/resolv.c @@ -0,0 +1,440 @@ +/**************************************************************************** + * uip-resolv.c + * DNS host name to IP address resolver. + * + * The uIP DNS resolver functions are used to lookup a hostname and + * map it to a numerical IP address. It maintains a list of resolved + * hostnames that can be queried with the resolv_lookup() + * function. New hostnames can be resolved using the resolv_query() + * function. + * + * When a hostname has been resolved (or found to be non-existant), + * the resolver code calls a callback function called resolv_found() + * that must be implemented by the module that uses the resolver. + * + * Copyright (C) 2007, 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based heavily on portions of uIP: + * + * Author: Adam Dunkels <adam@dunkels.com> + * Copyright (c) 2002-2003, Adam Dunkels. + * 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdint.h> +#include <string.h> +#include <unistd.h> +#include <time.h> +#include <errno.h> +#include <debug.h> + +#include <sys/socket.h> +#include <arpa/inet.h> + +#include <apps/netutils/resolv.h> + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#ifndef CONFIG_NET_RESOLV_ENTRIES +#define RESOLV_ENTRIES 4 +#else /* CONFIG_NET_RESOLV_ENTRIES */ +#define RESOLV_ENTRIES CONFIG_NET_RESOLV_ENTRIES +#endif /* CONFIG_NET_RESOLV_ENTRIES */ + +#ifndef NULL +#define NULL (void *)0 +#endif /* NULL */ + +/* The maximum number of retries when asking for a name */ + +#define MAX_RETRIES 8 + +#define DNS_FLAG1_RESPONSE 0x80 +#define DNS_FLAG1_OPCODE_STATUS 0x10 +#define DNS_FLAG1_OPCODE_INVERSE 0x08 +#define DNS_FLAG1_OPCODE_STANDARD 0x00 +#define DNS_FLAG1_AUTHORATIVE 0x04 +#define DNS_FLAG1_TRUNC 0x02 +#define DNS_FLAG1_RD 0x01 +#define DNS_FLAG2_RA 0x80 +#define DNS_FLAG2_ERR_MASK 0x0f +#define DNS_FLAG2_ERR_NONE 0x00 +#define DNS_FLAG2_ERR_NAME 0x03 + +#define SEND_BUFFER_SIZE 64 +#define RECV_BUFFER_SIZE 64 + +#ifdef CONFIG_NET_IPv6 +#define ADDRLEN sizeof(struct sockaddr_in6) +#else +#define ADDRLEN sizeof(struct sockaddr_in) +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/* The DNS message header */ + +struct dns_hdr +{ + uint16_t id; + uint8_t flags1, flags2; + uint16_t numquestions; + uint16_t numanswers; + uint16_t numauthrr; + uint16_t numextrarr; +}; + +/* The DNS answer message structure */ + +struct dns_answer +{ + /* DNS answer record starts with either a domain name or a pointer + * to a name already present somewhere in the packet. + */ + + uint16_t type; + uint16_t class; + uint16_t ttl[2]; + uint16_t len; +#ifdef CONFIG_NET_IPv6 + struct in6_addr ipaddr; +#else + struct in_addr ipaddr; +#endif +}; + +struct namemap +{ + uint8_t state; + uint8_t tmr; + uint8_t retries; + uint8_t seqno; + uint8_t err; + char name[32]; +#ifdef CONFIG_NET_IPv6 + struct in6_addr ipaddr; +#else + struct in_addr ipaddr; +#endif +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static uint8_t g_seqno; +static int g_sockfd = -1; +#ifdef CONFIG_NET_IPv6 +static struct sockaddr_in6 g_dnsserver; +#else +static struct sockaddr_in g_dnsserver; +#endif + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/* Walk through a compact encoded DNS name and return the end of it. */ + +static unsigned char *parse_name(unsigned char *query) +{ + unsigned char n; + + do + { + n = *query++; + + while(n > 0) + { + ++query; + --n; + } + } + while(*query != 0); + return query + 1; +} + +/* Runs through the list of names to see if there are any that have + * not yet been queried and, if so, sends out a query. + */ + +#ifdef CONFIG_NET_IPv6 +static int send_query(const char *name, struct sockaddr_in6 *addr) +#else +static int send_query(const char *name, struct sockaddr_in *addr) +#endif +{ + register struct dns_hdr *hdr; + char *query; + char *nptr; + const char *nameptr; + uint8_t seqno = g_seqno++; + static unsigned char endquery[] = {0, 0, 1, 0, 1}; + char buffer[SEND_BUFFER_SIZE]; + int n; + + hdr = (struct dns_hdr*)buffer; + memset(hdr, 0, sizeof(struct dns_hdr)); + hdr->id = htons(seqno); + hdr->flags1 = DNS_FLAG1_RD; + hdr->numquestions = HTONS(1); + query = buffer + 12; + + /* Convert hostname into suitable query format. */ + + nameptr = name - 1; + do + { + nameptr++; + nptr = query++; + for (n = 0; *nameptr != '.' && *nameptr != 0; nameptr++) + { + *query++ = *nameptr; + n++; + } + *nptr = n; + } + while(*nameptr != 0); + + memcpy(query, endquery, 5); + return sendto(g_sockfd, buffer, query + 5 - buffer, 0, (struct sockaddr*)addr, ADDRLEN); +} + +/* Called when new UDP data arrives */ + +#ifdef CONFIG_NET_IPv6 +#error "Not implemented" +#else +int recv_response(struct sockaddr_in *addr) +#endif +{ + unsigned char *nameptr; + char buffer[RECV_BUFFER_SIZE]; + struct dns_answer *ans; + struct dns_hdr *hdr; + uint8_t nquestions; + uint8_t nanswers; + int ret; + + /* Receive the response */ + + ret = recv(g_sockfd, buffer, RECV_BUFFER_SIZE, 0); + if (ret < 0) + { + return ret; + } + + hdr = (struct dns_hdr *)buffer; + + dbg( "ID %d\n", htons(hdr->id)); + dbg( "Query %d\n", hdr->flags1 & DNS_FLAG1_RESPONSE); + dbg( "Error %d\n", hdr->flags2 & DNS_FLAG2_ERR_MASK); + dbg( "Num questions %d, answers %d, authrr %d, extrarr %d\n", + htons(hdr->numquestions), htons(hdr->numanswers), + htons(hdr->numauthrr), htons(hdr->numextrarr)); + + /* Check for error. If so, call callback to inform */ + + if ((hdr->flags2 & DNS_FLAG2_ERR_MASK) != 0) + { + return ERROR; + } + + /* We only care about the question(s) and the answers. The authrr + * and the extrarr are simply discarded. + */ + + nquestions = htons(hdr->numquestions); + nanswers = htons(hdr->numanswers); + + /* Skip the name in the question. XXX: This should really be + * checked agains the name in the question, to be sure that they + * match. + */ + + nameptr = parse_name((unsigned char *)buffer + 12) + 4; + + for (; nanswers > 0; nanswers--) + { + /* The first byte in the answer resource record determines if it + * is a compressed record or a normal one. + */ + + if (*nameptr & 0xc0) + { + /* Compressed name. */ + + nameptr +=2; + dbg("Compressed anwser\n"); + } + else + { + /* Not compressed name. */ + nameptr = parse_name(nameptr); + } + + ans = (struct dns_answer *)nameptr; + dbg("Answer: type %x, class %x, ttl %x, length %x\n", + htons(ans->type), htons(ans->class), (htons(ans->ttl[0]) << 16) | htons(ans->ttl[1]), + htons(ans->len)); + + /* Check for IP address type and Internet class. Others are discarded. */ + + if (ans->type == HTONS(1) && ans->class == HTONS(1) && ans->len == HTONS(4)) + { + dbg("IP address %d.%d.%d.%d\n", + (ans->ipaddr.s_addr >> 24 ) & 0xff, + (ans->ipaddr.s_addr >> 16 ) & 0xff, + (ans->ipaddr.s_addr >> 8 ) & 0xff, + (ans->ipaddr.s_addr ) & 0xff); + + /* XXX: we should really check that this IP address is the one + * we want. + */ + + addr->sin_addr.s_addr = ans->ipaddr.s_addr; + return OK; + } + else + { + nameptr = nameptr + 10 + htons(ans->len); + } + } + return ERROR; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/* Get the binding for name. */ + +#ifdef CONFIG_NET_IPv6 +int resolv_query(FAR const char *name, FAR struct sockaddr_in6 *addr) +#else +int resolv_query(FAR const char *name, FAR struct sockaddr_in *addr) +#endif +{ + int retries; + int ret; + + /* Loop while receive timeout errors occur and there are remaining retries */ + + for (retries = 0; retries < 3; retries++) + { + if (send_query(name, addr) < 0) + { + return ERROR; + } + + ret = recv_response(addr); + if (ret >= 0) + { + /* Response received successfully */ + + return OK; + } + + else if (errno != EAGAIN) + { + /* Some failure other than receive timeout occurred */ + + return ERROR; + } + } + + return ERROR; +} + +/* Obtain the currently configured DNS server. */ + +#ifdef CONFIG_NET_IPv6 +void resolv_getserver(struct in6_addr *dnsserver) +#else +void resolv_getserver(struct in_addr *dnsserver) +#endif +{ +#ifdef CONFIG_NET_IPv6 + memcpy(dnsserver, &g_dnsserver.sin6_addr, ADDRLEN); +#else + dnsserver->s_addr = g_dnsserver.sin_addr.s_addr; +#endif +} + +/* Configure which DNS server to use for queries */ + +#ifdef CONFIG_NET_IPv6 +void resolv_conf(const struct in6_addr *dnsserver) +#else +void resolv_conf(const struct in_addr *dnsserver) +#endif +{ + g_dnsserver.sin_family = AF_INET; + g_dnsserver.sin_port = HTONS(53); +#ifdef CONFIG_NET_IPv6 + memcpy(&g_dnsserver.sin6_addr, dnsserver, ADDRLEN); +#else + g_dnsserver.sin_addr.s_addr = dnsserver->s_addr; +#endif +} + +/* Initalize the resolver. */ + +int resolv_init(void) +{ + struct timeval tv; + g_sockfd = socket(PF_INET, SOCK_DGRAM, 0); + if (g_sockfd < 0) + { + return ERROR; + } + + /* Set up a receive timeout */ + + tv.tv_sec = 30; + tv.tv_usec = 0; + if (setsockopt(g_sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)) < 0) + { + close(g_sockfd); + g_sockfd = -1; + return ERROR; + } + + return OK; +} diff --git a/apps/netutils/smtp/Makefile b/apps/netutils/smtp/Makefile new file mode 100644 index 000000000..05ace5c53 --- /dev/null +++ b/apps/netutils/smtp/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/smtp/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# SMTP Library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_TCP),y) +CSRCS += smtp.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/smtp/smtp.c b/apps/netutils/smtp/smtp.c new file mode 100644 index 000000000..d758c6f6b --- /dev/null +++ b/apps/netutils/smtp/smtp.c @@ -0,0 +1,376 @@ +/**************************************************************************** + * apps/netutitls/smtp/smtp.c + * smtp SMTP E-mail sender + * + * Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Heavily leveraged from uIP 1.0 which also has a BSD-like license: + * + * The Simple Mail Transfer Protocol (SMTP) as defined by RFC821 is + * the standard way of sending and transfering e-mail on the + * Internet. This simple example implementation is intended as an + * example of how to implement protocols in uIP, and is able to send + * out e-mail but has not been extensively tested. + * + * Author: Adam Dunkels <adam@dunkels.com> + * Copyright (c) 2004, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdint.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <semaphore.h> +#include <sys/socket.h> + +#include <net/uip/uip.h> +#include <apps/netutils/smtp.h> + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#define SMTP_INPUT_BUFFER_SIZE 512 + +#define ISO_nl 0x0a +#define ISO_cr 0x0d + +#define ISO_period 0x2e + +#define ISO_2 0x32 +#define ISO_3 0x33 +#define ISO_4 0x34 +#define ISO_5 0x35 + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/* This structure represents the state of a single SMTP transaction */ + +struct smtp_state +{ + uint8_t state; + bool connected; + sem_t sem; + uip_ipaddr_t smtpserver; + const char *localhostname; + const char *to; + const char *cc; + const char *from; + const char *subject; + const char *msg; + int msglen; + int sentlen; + int textlen; + int sendptr; + char buffer[SMTP_INPUT_BUFFER_SIZE]; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static const char g_smtp220[] = "220"; +static const char g_smtpcrnlperiodcrnl[] = "\r\n.\r\n"; +static const char g_smtpdata[] = "DATA\r\n"; +static const char g_smtpfrom[] = "From: "; +static const char g_smtphelo[] = "HELO "; +static const char g_smtpmailfrom[] = "MAIL FROM: "; +static const char g_smtpquit[] = "QUIT\r\n"; +static const char g_smtprcptto[] = "RCPT TO: "; +static const char g_smtpsubject[] = "Subject: "; +static const char g_smtpto[] = "To: "; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static inline int smtp_send_message(int sockfd, struct smtp_state *psmtp) +{ + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (strncmp(psmtp->buffer, g_smtp220, strlen(g_smtp220)) != 0) + { + return ERROR; + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtphelo, psmtp->localhostname); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_2) + { + return ERROR; + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtpmailfrom, psmtp->from); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_2) + { + return ERROR; + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtprcptto, psmtp->to); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_2) + { + return ERROR; + } + + if (psmtp->cc != 0) + { + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtprcptto, psmtp->cc); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_2) + { + return ERROR; + } + } + + if (send(sockfd, g_smtpdata, strlen(g_smtpdata), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_3) + { + return ERROR; + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtpto, psmtp->to); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (psmtp->cc != 0) + { + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtpto, psmtp->cc); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtpfrom, psmtp->from); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + snprintf(psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, "%s%s\r\n", g_smtpsubject, psmtp->subject); + if (send(sockfd, psmtp->buffer, strlen(psmtp->buffer), 0) < 0) + { + return ERROR; + } + + if (send(sockfd, psmtp->msg, psmtp->msglen, 0) < 0) + { + return ERROR; + } + + if (send(sockfd, g_smtpcrnlperiodcrnl, strlen(g_smtpcrnlperiodcrnl), 0) < 0) + { + return ERROR; + } + + if (recv(sockfd, psmtp->buffer, SMTP_INPUT_BUFFER_SIZE, 0) < 0) + { + return ERROR; + } + + if (psmtp->buffer[0] != ISO_2) + { + return ERROR; + } + + if (send(sockfd, g_smtpquit, strlen(g_smtpquit), 0) < 0) + { + return ERROR; + } + return OK; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/* Specificy an SMTP server and hostname. + * + * This function is used to configure the SMTP module with an SMTP server and + * the hostname of the host. + * + * lhostname - The hostname of the local, uIP host. + * + * paddr - A pointer to the IP address of the SMTP server to be + * configured. + */ + +void smtp_configure(void *handle, const char *lhostname, + const uip_ipaddr_t *paddr) +{ + struct smtp_state *psmtp = (struct smtp_state *)handle; + psmtp->localhostname = lhostname; + uip_ipaddr_copy(psmtp->smtpserver, paddr); +} + +/* Send an e-mail. + * + * to - The e-mail address of the receiver of the e-mail. + * cc - The e-mail address of the CC: receivers of the e-mail. + * from - The e-mail address of the sender of the e-mail. + * subject - The subject of the e-mail. + * msg - The actual e-mail message. + * msglen - The length of the e-mail message. + */ + +int smtp_send(void *handle, const char *to, const char *cc, const char *from, + const char *subject, const char *msg, int msglen) +{ + struct smtp_state *psmtp = (struct smtp_state *)handle; + struct sockaddr_in server; + int sockfd; + int ret; + + /* Setup */ + + psmtp->connected = true; + psmtp->to = to; + psmtp->cc = cc; + psmtp->from = from; + psmtp->subject = subject; + psmtp->msg = msg; + psmtp->msglen = msglen; + + /* Create a socket */ + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd < 0) + { + return ERROR; + } + + /* Connect to server. First we have to set some fields in the + * 'server' structure. The system will assign me an arbitrary + * local port that is not in use. + */ + + server.sin_family = AF_INET; + memcpy(&server.sin_addr.s_addr, &psmtp->smtpserver, sizeof(in_addr_t)); + server.sin_port = HTONS(25); + + if (connect(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) < 0) + { + close(sockfd); + return ERROR; + } + + /* Send the message */ + + ret = smtp_send_message(sockfd, psmtp); + + close(sockfd); + return ret; +} + +void *smtp_open(void) +{ + /* Allocate the handle */ + + struct smtp_state *psmtp = (struct smtp_state *)malloc(sizeof(struct smtp_state)); + if (psmtp) + { + /* Initialize the handle */ + + memset(psmtp, 0, sizeof(struct smtp_state)); + (void)sem_init(&psmtp->sem, 0, 0); + } + return (void*)psmtp; +} + +void smtp_close(void *handle) +{ + struct smtp_state *psmtp = (struct smtp_state *)handle; + if (psmtp) + { + sem_destroy(&psmtp->sem); + free(psmtp); + } +} diff --git a/apps/netutils/telnetd/Makefile b/apps/netutils/telnetd/Makefile new file mode 100644 index 000000000..4c345d487 --- /dev/null +++ b/apps/netutils/telnetd/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/telnetd/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# Telnet daemon + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_TCP),y) +CSRCS += telnetd.c shell.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/telnetd/README.txt b/apps/netutils/telnetd/README.txt new file mode 100644 index 000000000..24fcba7d5 --- /dev/null +++ b/apps/netutils/telnetd/README.txt @@ -0,0 +1,7 @@ +This directory is here for historical reasons. Nothing contained in this +directory is currently used by NuttX. This directly contains a functional +port of the tiny uIP shell. In the NuttX environment, the NuttShell (at +apps/nshlib) supercedes this tiny shell and also supports telnetd. + +This example is retained here for reference purposes only. + diff --git a/apps/netutils/telnetd/shell.c b/apps/netutils/telnetd/shell.c new file mode 100644 index 000000000..93fd11601 --- /dev/null +++ b/apps/netutils/telnetd/shell.c @@ -0,0 +1,139 @@ +/**************************************************************************** + * netutils/telnetd/telnetd.c + * + * Copyright (C) 2007 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * This is a leverage of similar logic from uIP: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2003, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <string.h> +#include "shell.h" + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#define SHELL_PROMPT "uIP 1.0> " + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct ptentry_s +{ + char *commandstr; + void (* pfunc)(void *handle, char *str); +}; + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void parse(void *handle, register char *str, struct ptentry_s *t); +static void help(void *handle, char *str); +static void unknown(void *handle, char *str); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static struct ptentry_s g_parsetab[] = +{ + {"stats", help}, + {"conn", help}, + {"help", help}, + {"exit", shell_quit}, + {"?", help}, + {NULL, unknown} +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void parse(void *handle, char *str, struct ptentry_s *t) +{ + struct ptentry_s *p; + + for (p = t; p->commandstr != NULL; ++p) + { + if (strncmp(p->commandstr, str, strlen(p->commandstr)) == 0) + { + break; + } + } + + p->pfunc(handle, str); +} + +static void help(void *handle, char *str) +{ + shell_output(handle, "Available commands:"); + shell_output(handle, "stats - show network statistics"); + shell_output(handle, "conn - show TCP connections"); + shell_output(handle, "help, ? - show help"); + shell_output(handle, "exit - exit shell"); +} + +static void unknown(void *handle, char *str) +{ + if (strlen(str) > 0) + { + shell_output(handle, "Unknown command: ", str); + } +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void shell_init(void *handle) +{ +} + +void shell_start(void *handle) +{ + shell_output(handle, "uIP command shell"); + shell_output(handle, "Type '?' and return for help"); + shell_prompt(handle, SHELL_PROMPT); +} + +void shell_input(void *handle, char *cmd) +{ + parse(handle, cmd, g_parsetab); + shell_prompt(handle, SHELL_PROMPT); +} diff --git a/apps/netutils/telnetd/shell.h b/apps/netutils/telnetd/shell.h new file mode 100644 index 000000000..32325fe17 --- /dev/null +++ b/apps/netutils/telnetd/shell.h @@ -0,0 +1,97 @@ +/**************************************************************************** + * netutils/telnetd/shell.h + * Interface for the Contiki shell. + * + * Copyright (C) 2007 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@dunkels.com> + * Copyright (c) 2003, Adam Dunkels. + * 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. + * + ****************************************************************************/ + +/* Some of the functions declared in this file must be implemented as + * a shell back-end in the architecture specific files of a Contiki + * port. + */ + +#ifndef __SHELL_H__ +#define __SHELL_H__ + +/* Initialize the shell. + * + * Called when the shell front-end process starts. This function may + * be used to start listening for signals. + */ + +void shell_init(void *handle); + +/* Start the shell back-end. + * + * Called by the front-end when a new shell is started. + */ + +void shell_start(void *handle); + +/* Process a shell command. + * + * This function will be called by the shell GUI / telnet server whan + * a command has been entered that should be processed by the shell + * back-end. + * + * command The command to be processed. + */ + +void shell_input(void *handle, char *command); + +/* Quit the shell. */ + +void shell_quit(void *handle, char *); + +/* Print a string to the shell window. + * + * This function is implemented by the shell GUI / telnet server and + * can be called by the shell back-end to output a string in the + * shell window. The string is automatically appended with a linebreak. + */ + +void shell_output(void *handle, const char *fmt, ...); + +/* Print a prompt to the shell window. + * + * This function can be used by the shell back-end to print out a + * prompt to the shell window. + * + */ + +void shell_prompt(void *handle, char *prompt); + +#endif /* __SHELL_H__ */ diff --git a/apps/netutils/telnetd/telnetd.c b/apps/netutils/telnetd/telnetd.c new file mode 100644 index 000000000..ccadd60dd --- /dev/null +++ b/apps/netutils/telnetd/telnetd.c @@ -0,0 +1,459 @@ +/**************************************************************************** + * netutils/telnetd/telnetd.c + * + * Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * This is a leverage of similar logic from uIP: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2003, Adam Dunkels. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <stdint.h> +#include <stdio.h> +#include <unistd.h> +#include <stdlib.h> +#include <stdarg.h> +#include <string.h> +#include <pthread.h> +#include <debug.h> + +#include <apps/netutils/telnetd.h> +#include <apps/netutils/uiplib.h> + +#include "shell.h" + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#define ISO_nl 0x0a +#define ISO_cr 0x0d + +#define STATE_NORMAL 0 +#define STATE_IAC 1 +#define STATE_WILL 2 +#define STATE_WONT 3 +#define STATE_DO 4 +#define STATE_DONT 5 +#define STATE_CLOSE 6 + +#define TELNET_IAC 255 +#define TELNET_WILL 251 +#define TELNET_WONT 252 +#define TELNET_DO 253 +#define TELNET_DONT 254 + +/* Configurable settings */ + +#ifndef CONFIG_NETUTILS_IOBUFFER_SIZE +# define CONFIG_NETUTILS_IOBUFFER_SIZE 512 +#endif + +#ifndef CONFIG_NETUTILS_CMD_SIZE +# define CONFIG_NETUTILS_CMD_SIZE 40 +#endif + +/* As threads are created to handle each request, a stack must be allocated + * for the thread. Use a default if the user provided no stacksize. + */ + +#ifndef CONFIG_NETUTILS_TELNETDSTACKSIZE +# define CONFIG_NETUTILS_TELNETDSTACKSIZE 4096 +#endif + +/* Enabled dumping of all input/output buffers */ + +#undef CONFIG_NETUTILS_TELNETD_DUMPBUFFER + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct telnetd_s +{ + int tn_sockfd; + char tn_iobuffer[CONFIG_NETUTILS_IOBUFFER_SIZE]; + char tn_cmd[CONFIG_NETUTILS_CMD_SIZE]; + uint8_t tn_bufndx; + uint8_t tn_state; +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: telnetd_dumpbuffer + * + * Description: + * Dump a buffer of data (debug only) + * + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_TELNETD_DUMPBUFFER +static inline void telnetd_dumpbuffer(FAR const char *msg, FAR const char *buffer, unsigned int nbytes) +{ + /* CONFIG_DEBUG, CONFIG_DEBUG_VERBOSE, and CONFIG_DEBUG_NET have to be + * defined or the following does nothing. + */ + + nvdbgdumpbuffer(msg, (FAR const uint8_t*)buffer, nbytes); +} +#else +# define telnetd_dumpbuffer(msg,buffer,nbytes) +#endif + +/**************************************************************************** + * Name: telnetd_putchar + * + * Description: + * Add another parsed character to the TELNET command string + * + ****************************************************************************/ + +static void telnetd_putchar(struct telnetd_s *pstate, uint8_t ch) +{ + /* Ignore carriage returns */ + + if (ch == ISO_cr) + { + return; + } + + /* Add all other characters to the cmd buffer */ + + pstate->tn_cmd[pstate->tn_bufndx] = ch; + + /* If a newline was added or if the buffer is full, then process it now */ + + if (ch == ISO_nl || pstate->tn_bufndx == (CONFIG_NETUTILS_CMD_SIZE - 1)) + { + if (pstate->tn_bufndx > 0) + { + pstate->tn_cmd[pstate->tn_bufndx] = '\0'; + } + + telnetd_dumpbuffer("TELNET CMD", pstate->tn_cmd, strlen(pstate->tn_cmd)); + shell_input(pstate, pstate->tn_cmd); + pstate->tn_bufndx = 0; + } + else + { + pstate->tn_bufndx++; + vdbg("Add '%c', bufndx=%d\n", ch, pstate->tn_bufndx); + } +} + +/**************************************************************************** + * Name: telnetd_sendopt + * + * Description: + * + ****************************************************************************/ + +static void telnetd_sendopt(struct telnetd_s *pstate, uint8_t option, uint8_t value) +{ + uint8_t optbuf[4]; + optbuf[0] = TELNET_IAC; + optbuf[1] = option; + optbuf[2] = value; + optbuf[3] = 0; + + telnetd_dumpbuffer("Send optbuf", optbuf, 4); + if (send(pstate->tn_sockfd, optbuf, 4, 0) < 0) + { + dbg("[%d] Failed to send TELNET_IAC\n", pstate->tn_sockfd); + } +} + +/**************************************************************************** + * Name: telnetd_receive + * + * Description: + * Process a received TELENET buffer + * + ****************************************************************************/ + +static int telnetd_receive(struct telnetd_s *pstate, size_t len) +{ + char *ptr = pstate->tn_iobuffer; + uint8_t ch; + + while (len > 0) + { + ch = *ptr++; + len--; + + vdbg("ch=%02x state=%d\n", ch, pstate->tn_state); + switch (pstate->tn_state) + { + case STATE_IAC: + if (ch == TELNET_IAC) + { + telnetd_putchar(pstate, ch); + pstate->tn_state = STATE_NORMAL; + } + else + { + switch (ch) + { + case TELNET_WILL: + pstate->tn_state = STATE_WILL; + break; + + case TELNET_WONT: + pstate->tn_state = STATE_WONT; + break; + + case TELNET_DO: + pstate->tn_state = STATE_DO; + break; + + case TELNET_DONT: + pstate->tn_state = STATE_DONT; + break; + + default: + pstate->tn_state = STATE_NORMAL; + break; + } + } + break; + + case STATE_WILL: + /* Reply with a DONT */ + + telnetd_sendopt(pstate, TELNET_DONT, ch); + pstate->tn_state = STATE_NORMAL; + break; + + case STATE_WONT: + /* Reply with a DONT */ + + telnetd_sendopt(pstate, TELNET_DONT, ch); + pstate->tn_state = STATE_NORMAL; + break; + + case STATE_DO: + /* Reply with a WONT */ + + telnetd_sendopt(pstate, TELNET_WONT, ch); + pstate->tn_state = STATE_NORMAL; + break; + + case STATE_DONT: + /* Reply with a WONT */ + + telnetd_sendopt(pstate, TELNET_WONT, ch); + pstate->tn_state = STATE_NORMAL; + break; + + case STATE_NORMAL: + if (ch == TELNET_IAC) + { + pstate->tn_state = STATE_IAC; + } + else + { + telnetd_putchar(pstate, ch); + } + break; + } + } + return OK; +} + +/**************************************************************************** + * Name: telnetd_handler + * + * Description: + * Each time a new connection to port 23 is made, a new thread is created + * that begins at this entry point. There should be exactly one argument + * and it should be the socket descriptor (+1). + * + ****************************************************************************/ + +static void *telnetd_handler(void *arg) +{ + struct telnetd_s *pstate = (struct telnetd_s *)malloc(sizeof(struct telnetd_s)); + int sockfd = (int)arg; + int ret = ERROR; + + dbg("[%d] Started\n", sockfd); + + /* Verify that the state structure was successfully allocated */ + + if (pstate) + { + /* Initialize the thread state structure */ + + memset(pstate, 0, sizeof(struct telnetd_s)); + pstate->tn_sockfd = sockfd; + pstate->tn_state = STATE_NORMAL; + + /* Start up the shell */ + + shell_init(pstate); + shell_start(pstate); + + /* Loop processing each TELNET command */ + do + { + /* Read a buffer of data from the TELNET client */ + + ret = recv(pstate->tn_sockfd, pstate->tn_iobuffer, CONFIG_NETUTILS_IOBUFFER_SIZE, 0); + if (ret > 0) + { + + /* Process the received TELNET data */ + + telnetd_dumpbuffer("Received buffer", pstate->tn_iobuffer, ret); + ret = telnetd_receive(pstate, ret); + } + } + while (ret >= 0 && pstate->tn_state != STATE_CLOSE); + dbg("[%d] ret=%d tn_state=%d\n", sockfd, ret, pstate->tn_state); + + /* End of command processing -- Clean up and exit */ + + free(pstate); + } + + /* Exit the task */ + + dbg("[%d] Exitting\n", sockfd); + close(sockfd); + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: telnetd_init + * + * Description: + * This is the main processing thread for telnetd. It never returns + * unless an error occurs + * + ****************************************************************************/ + +void telnetd_init(void) +{ + /* Execute telnetd_handler on each connection to port 23 */ + + uip_server(HTONS(23), telnetd_handler, CONFIG_NETUTILS_TELNETDSTACKSIZE); +} + +/**************************************************************************** + * Name: shell_prompt + * + * Description: + * Print a prompt to the shell window. + * + * This function can be used by the shell back-end to print out a prompt + * to the shell window. + * + ****************************************************************************/ + +void shell_prompt(void *handle, char *str) +{ + struct telnetd_s *pstate = (struct telnetd_s *)handle; + int len = strlen(str); + + strncpy(pstate->tn_iobuffer, str, len); + telnetd_dumpbuffer("Shell prompt", pstate->tn_iobuffer, len); + if (send(pstate->tn_sockfd, pstate->tn_iobuffer, len, 0) < 0) + { + dbg("[%d] Failed to send prompt\n", pstate->tn_sockfd); + } +} + +/**************************************************************************** + * Name: shell_output + * + * Description: + * Print a string to the shell window. + * + * This function is implemented by the shell GUI / telnet server and + * can be called by the shell back-end to output a string in the + * shell window. The string is automatically appended with a linebreak. + * + ****************************************************************************/ + +void shell_output(void *handle, const char *fmt, ...) +{ + struct telnetd_s *pstate = (struct telnetd_s *)handle; + unsigned len; + va_list ap; + + va_start(ap, fmt); + vsnprintf(pstate->tn_iobuffer, CONFIG_NETUTILS_IOBUFFER_SIZE, fmt, ap); + va_end(ap); + + len = strlen(pstate->tn_iobuffer); + if (len < CONFIG_NETUTILS_IOBUFFER_SIZE - 2) + { + pstate->tn_iobuffer[len] = ISO_cr; + pstate->tn_iobuffer[len+1] = ISO_nl; + pstate->tn_iobuffer[len+2] = '\0'; + } + + telnetd_dumpbuffer("Shell output", pstate->tn_iobuffer, len+2); + if (send(pstate->tn_sockfd, pstate->tn_iobuffer, len+2, 0) < 0) + { + dbg("[%d] Failed to send response\n", pstate->tn_sockfd); + } +} + +/**************************************************************************** + * Name: shell_quit + * + * Description: + * Quit the shell + * + ****************************************************************************/ + +void shell_quit(void *handle, char *str) +{ + struct telnetd_s *pstate = (struct telnetd_s *)handle; + pstate->tn_state = STATE_CLOSE; +} + diff --git a/apps/netutils/tftpc/Makefile b/apps/netutils/tftpc/Makefile new file mode 100644 index 000000000..24bf1d4c6 --- /dev/null +++ b/apps/netutils/tftpc/Makefile @@ -0,0 +1,96 @@ +############################################################################ +# apps/netutils/tftpc/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# TFTP Client Library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_UDP),y) +ifneq ($(CONFIG_NFILE_DESCRIPTORS),0) +CSRCS += tftpc_get.c tftpc_put.c tftpc_packets.c +endif +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/tftpc/tftpc_get.c b/apps/netutils/tftpc/tftpc_get.c new file mode 100644 index 000000000..e0779d17d --- /dev/null +++ b/apps/netutils/tftpc/tftpc_get.c @@ -0,0 +1,328 @@ +/**************************************************************************** + * netuils/tftp/tftpc_get.c + * + * Copyright (C) 2008-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, TFTP_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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <stdint.h> +#include <stdbool.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <errno.h> +#include <debug.h> + +#include <net/uip/uipopt.h> +#include <net/uip/uip.h> +#include <apps/netutils/tftp.h> + +#include "tftpc_internal.h" + +#if defined(CONFIG_NET) && defined(CONFIG_NET_UDP) && CONFIG_NFILE_DESCRIPTORS > 0 + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define TFTP_RETRIES 3 + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftp_write + ****************************************************************************/ + +static inline ssize_t tftp_write(int fd, const uint8_t *buf, size_t len) +{ + size_t left = len; + ssize_t nbyteswritten; + + while (left > 0) + { + /* Write the data... repeating the write in the event that it was + * interrupted by a signal. + */ + + do + { + nbyteswritten = write(fd, buf, left); + } + while (nbyteswritten < 0 && errno == EINTR); + + /* Check for non-EINTR errors */ + + if (nbyteswritten < 0) + { + ndbg("write failed: %d\n", errno); + return ERROR; + } + + /* Handle partial writes */ + + nvdbg("Wrote %d bytes to file\n", nbyteswritten); + left -= nbyteswritten; + buf += nbyteswritten; + } + return len; +} + +/**************************************************************************** + * Name: tftp_parsedatapacket + ****************************************************************************/ + +static inline int tftp_parsedatapacket(const uint8_t *packet, + uint16_t *opcode, uint16_t *blockno) +{ + *opcode = (uint16_t)packet[0] << 8 | (uint16_t)packet[1]; + if (*opcode == TFTP_DATA) + { + *blockno = (uint16_t)packet[2] << 8 | (uint16_t)packet[3]; + return OK; + } +#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET) + else if (*opcode == TFTP_ERR) + { + (void)tftp_parseerrpacket(packet); + } +#endif + return ERROR; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftpget + * + * Input Parameters: + * remote - The name of the file on the TFTP server. + * local - Path to the location on a mounted filesystem where the file + * will be stored. + * addr - The IP address of the server in network order + * binary - TRUE: Perform binary ('octect') transfer + * FALSE: Perform text ('netascii') transfer + * + ****************************************************************************/ + +int tftpget(const char *remote, const char *local, in_addr_t addr, bool binary) +{ + struct sockaddr_in server; /* The address of the TFTP server */ + struct sockaddr_in from; /* The address the last UDP message recv'd from */ + uint8_t *packet; /* Allocated memory to hold one packet */ + uint16_t blockno = 0; /* The current transfer block number */ + uint16_t opcode; /* Received opcode */ + uint16_t rblockno; /* Received block number */ + int len; /* Generic length */ + int sd; /* Socket descriptor for socket I/O */ + int fd; /* File descriptor for file I/O */ + int retry; /* Retry counter */ + int nbytesrecvd = 0; /* The number of bytes received in the packet */ + int ndatabytes; /* The number of data bytes received */ + int result = ERROR; /* Assume failure */ + int ret; /* Generic return status */ + + /* Allocate the buffer to used for socket/disk I/O */ + + packet = (uint8_t*)zalloc(TFTP_IOBUFSIZE); + if (!packet) + { + ndbg("packet memory allocation failure\n"); + errno = ENOMEM; + goto errout; + } + + /* Open the file for writing */ + + fd = open(local, O_WRONLY|O_CREAT|O_TRUNC, 0666); + if (fd < 0) + { + ndbg("open failed: %d\n", errno); + goto errout_with_packet; + } + + /* Initialize a UDP socket and setup the server addresss */ + + sd = tftp_sockinit(&server, addr); + if (sd < 0) + { + goto errout_with_fd; + } + + /* Then enter the transfer loop. Loop until the entire file has + * been received or until an error occurs. + */ + + do + { + /* Increment the TFTP block number for the next transfer */ + + blockno++; + + /* Send the next block if the file within a loop. We will + * retry up to TFTP_RETRIES times before giving up on the + * transfer. + */ + + for (retry = 0; retry < TFTP_RETRIES; retry++) + { + /* Send the read request using the well-known port number before + * receiving the first block. Each retry of the first block will + * re-send the request. + */ + + if (blockno == 1) + { + len = tftp_mkreqpacket(packet, TFTP_RRQ, remote, binary); + server.sin_port = HTONS(CONFIG_NETUTILS_TFTP_PORT); + ret = tftp_sendto(sd, packet, len, &server); + if (ret != len) + { + goto errout_with_sd; + } + + /* Subsequent sendto will use the port number selected by the TFTP + * server in the DATA packet. Setting the server port to zero + * here indicates that we have not yet received the server port number. + */ + + server.sin_port = 0; + } + + /* Get the next packet from the server */ + + nbytesrecvd = tftp_recvfrom(sd, packet, TFTP_IOBUFSIZE, &from); + + /* Check if anything valid was received */ + + if (nbytesrecvd >= 0) + { + /* Verify the sender address and port number */ + + if (server.sin_addr.s_addr != from.sin_addr.s_addr) + { + nvdbg("Invalid address in DATA\n"); + retry--; + continue; + } + + if (server.sin_port && server.sin_port != from.sin_port) + { + nvdbg("Invalid port in DATA\n"); + len = tftp_mkerrpacket(packet, TFTP_ERR_UNKID, TFTP_ERRST_UNKID); + ret = tftp_sendto(sd, packet, len, &from); + retry--; + continue; + } + + /* Parse the incoming DATA packet */ + + if (nbytesrecvd < TFTP_DATAHEADERSIZE || + tftp_parsedatapacket(packet, &opcode, &rblockno) != OK || + blockno != rblockno) + { + nvdbg("Parse failure\n"); + if (opcode > TFTP_MAXRFC1350) + { + len = tftp_mkerrpacket(packet, TFTP_ERR_ILLEGALOP, TFTP_ERRST_ILLEGALOP); + ret = tftp_sendto(sd, packet, len, &from); + } + continue; + } + + /* Replace the server port to the one in the good data response */ + + if (!server.sin_port) + { + server.sin_port = from.sin_port; + } + + /* Then break out of the loop */ + + break; + } + } + + /* Did we exhaust all of the retries? */ + + if (retry == TFTP_RETRIES) + { + nvdbg("Retry limit exceeded\n"); + goto errout_with_sd; + } + + /* Write the received data chunk to the file */ + + ndatabytes = nbytesrecvd - TFTP_DATAHEADERSIZE; + tftp_dumpbuffer("Recvd DATA", packet + TFTP_DATAHEADERSIZE, ndatabytes); + if (tftp_write(fd, packet + TFTP_DATAHEADERSIZE, ndatabytes) < 0) + { + goto errout_with_sd; + } + + /* Send the acknowledgment */ + + len = tftp_mkackpacket(packet, blockno); + ret = tftp_sendto(sd, packet, len, &server); + if (ret != len) + { + goto errout_with_sd; + } + nvdbg("ACK blockno %d\n", blockno); + } + while (ndatabytes >= TFTP_DATASIZE); + + /* Return success */ + + result = OK; + +errout_with_sd: + close(sd); +errout_with_fd: + close(fd); +errout_with_packet: + free(packet); +errout: + return result; +} + +#endif /* CONFIG_NET && CONFIG_NET_UDP && CONFIG_NFILE_DESCRIPTORS > 0 */ diff --git a/apps/netutils/tftpc/tftpc_internal.h b/apps/netutils/tftpc/tftpc_internal.h new file mode 100644 index 000000000..ffaecdb13 --- /dev/null +++ b/apps/netutils/tftpc/tftpc_internal.h @@ -0,0 +1,173 @@ +/**************************************************************************** + * netutils/tftoc/tftpc_internal.h + * + * Copyright (C) 2008-2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_TFTP_TFTPC_INTERNAL_H +#define __NETUTILS_TFTP_TFTPC_INTERNAL_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <nuttx/compiler.h> + +#include <sys/types.h> +#include <stdint.h> +#include <stdbool.h> + +#include <net/uip/uipopt.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* Verify TFTP configuration settings ***************************************/ +/* The settings beginning with CONFIG_NETUTILS_TFTP_* can all be set in the + * NuttX configuration file. If they are are defined in the configuration + * then default values are assigned here. + */ + +/* The "well-known" server TFTP port number (usually 69). This port number + * is only used for the initial server contact. The server will negotiate + * a new transfer port number after the initial client request. + */ + +#ifndef CONFIG_NETUTILS_TFTP_PORT +# define CONFIG_NETUTILS_TFTP_PORT 69 +#endif + +/* recvfrom timeout in deci-seconds */ + +#ifndef CONFIG_NETUTILS_TFTP_TIMEOUT +# define CONFIG_NETUTILS_TFTP_TIMEOUT 10 /* One second */ +#endif + +/* Dump received buffers */ + +#undef CONFIG_NETUTILS_TFTP_DUMPBUFFERS + +/* Sizes of TFTP messsage headers */ + +#define TFTP_ACKHEADERSIZE 4 +#define TFTP_ERRHEADERSIZE 4 +#define TFTP_DATAHEADERSIZE 4 + +/* The maximum size for TFTP data is determined by the configured uIP packet + * size (but cannot exceed 512 + sizeof(TFTP_DATA header). + */ + +#define TFTP_DATAHEADERSIZE 4 +#define TFTP_MAXPACKETSIZE (TFTP_DATAHEADERSIZE+512) + +#if UIP_UDP_MSS < TFTP_MAXPACKETSIZE +# define TFTP_PACKETSIZE UIP_UDP_MSS +# ifdef CONFIG_CPP_HAVE_WARNING +# warning "uIP MSS is too small for TFTP" +# endif +#else +# define TFTP_PACKETSIZE TFTP_MAXPACKETSIZE +#endif + +#define TFTP_DATASIZE (TFTP_PACKETSIZE-TFTP_DATAHEADERSIZE) +#define TFTP_IOBUFSIZE (TFTP_PACKETSIZE+8) + +/* TFTP Opcodes *************************************************************/ + +#define TFTP_RRQ 1 /* Read Request RFC 1350, RFC 2090 */ +#define TFTP_WRQ 2 /* Write Request RFC 1350 */ +#define TFTP_DATA 3 /* Data chunk RFC 1350 */ +#define TFTP_ACK 4 /* Acknowledgement RFC 1350 */ +#define TFTP_ERR 5 /* Error Message RFC 1350 */ +#define TFTP_OACK 6 /* Option acknowledgment RFC 2347 */ + +#define TFTP_MAXRFC1350 5 + +/* TFTP Error Codes *********************************************************/ + +/* Error codes */ + +#define TFTP_ERR_NONE 0 /* No error */ +#define TFTP_ERR_NOSUCHFILE 1 /* File not found */ +#define TFTP_ERR_ACCESS 2 /* Access violation */ +#define TFTP_ERR_FULL 3 /* Disk full or allocation exceeded */ +#define TFTP_ERR_ILLEGALOP 4 /* Illegal TFTP operation */ +#define TFTP_ERR_UNKID 5 /* Unknown transfer ID */ +#define TFTP_ERR_EXISTS 6 /* File already exists */ +#define TFTP_ERR_UNKUSER 7 /* No such user */ +#define TFTP_ERR_NEGOTIATE 8 /* Terminate transfer due to option negotiation */ + +/* Error strings */ + +#define TFTP_ERR_STNOSUCHFILE "File not found" +#define TFTP_ERRST_ACCESS "Access violation" +#define TFTP_ERRST_FULL "Disk full or allocation exceeded" +#define TFTP_ERRST_ILLEGALOP "Illegal TFTP operation" +#define TFTP_ERRST_UNKID "Unknown transfer ID" +#define TFTP_ERRST_EXISTS "File already exists" +#define TFTP_ERRST_UNKUSER "No such user" +#define TFTP_ERRST_NEGOTIATE "Terminate transfer due to option negotiation" + +/**************************************************************************** + * Public Type Definitions + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/* Defined in tftp_packet.c *************************************************/ + +extern int tftp_sockinit(struct sockaddr_in *server, in_addr_t addr); +extern int tftp_mkreqpacket(uint8_t *buffer, int opcode, const char *path, bool binary); +extern int tftp_mkackpacket(uint8_t *buffer, uint16_t blockno); +extern int tftp_mkerrpacket(uint8_t *buffer, uint16_t errorcode, const char *errormsg); +#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET) +extern int tftp_parseerrpacket(const uint8_t *packet); +#endif + +extern ssize_t tftp_recvfrom(int sd, void *buf, size_t len, struct sockaddr_in *from); +extern ssize_t tftp_sendto(int sd, const void *buf, size_t len, struct sockaddr_in *to); + +#ifdef CONFIG_NETUTILS_TFTP_DUMPBUFFERS +# define tftp_dumpbuffer(msg, buffer, nbytes) nvdbgdumpbuffer(msg, buffer, nbytes) +#else +# define tftp_dumpbuffer(msg, buffer, nbytes) +#endif + +#endif /* __NETUTILS_TFTP_TFTPC_INTERNAL_H */ diff --git a/apps/netutils/tftpc/tftpc_packets.c b/apps/netutils/tftpc/tftpc_packets.c new file mode 100644 index 000000000..d43410ff4 --- /dev/null +++ b/apps/netutils/tftpc/tftpc_packets.c @@ -0,0 +1,330 @@ +/**************************************************************************** + * netuils/tftp/tftpc_packets.c + * + * Copyright (C) 2008-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, TFTP_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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <stdint.h> +#include <stdbool.h> +#include <stdio.h> +#include <string.h> +#include <time.h> +#include <errno.h> +#include <debug.h> + +#include <netinet/in.h> + +#include <net/uip/uipopt.h> +#include <net/uip/uip.h> +#include <apps/netutils/tftp.h> + +#include "tftpc_internal.h" + +#if defined(CONFIG_NET) && defined(CONFIG_NET_UDP) && CONFIG_NFILE_DESCRIPTORS > 0 + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftp_mode + ****************************************************************************/ + +static inline const char *tftp_mode(bool binary) +{ + return binary ? "octet" : "netascii"; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftp_sockinit + * + * Description: + * Common initialization logic: Create the socket and initialize the + * server address structure. + * + ****************************************************************************/ + +int tftp_sockinit(struct sockaddr_in *server, in_addr_t addr) +{ + struct timeval timeo; + int sd; + int ret; + + /* Create the UDP socket */ + + sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sd < 0) + { + ndbg("socket failed: %d\n", errno); + return ERROR; + } + + /* Set the recvfrom timeout */ + + timeo.tv_sec = CONFIG_NETUTILS_TFTP_TIMEOUT / 10; + timeo.tv_usec = (CONFIG_NETUTILS_TFTP_TIMEOUT % 10) * 100000; + ret = setsockopt(sd, SOL_SOCKET, SO_RCVTIMEO, &timeo, sizeof(struct timeval)); + if (ret < 0) + { + ndbg("setsockopt failed: %d\n", errno); + } + + /* Initialize the server address structure */ + + memset(server, 0, sizeof(struct sockaddr_in)); + server->sin_family = AF_INET; + server->sin_addr.s_addr = addr; + server->sin_port = HTONS(CONFIG_NETUTILS_TFTP_PORT); + return sd; +} + +/**************************************************************************** + * Name: tftp_mkreqpacket + * + * Description: + * RRQ or WRQ message format: + * + * 2 bytes: Opcode (network order == big-endian) + * N bytes: Filename + * 1 byte: 0 + * N bytes: mode + * 1 byte: 0 + * + * Return + * Then number of bytes in the request packet (never fails) + * + ****************************************************************************/ + +int tftp_mkreqpacket(uint8_t *buffer, int opcode, const char *path, bool binary) +{ + buffer[0] = opcode >> 8; + buffer[1] = opcode & 0xff; + return sprintf((char*)&buffer[2], "%s%c%s", path, 0, tftp_mode(binary)) + 3; +} + +/**************************************************************************** + * Name: tftp_mkackpacket + * + * Description: + * ACK message format: + * + * 2 bytes: Opcode (network order == big-endian) + * 2 bytes: Block number (network order == big-endian) + * + ****************************************************************************/ + +int tftp_mkackpacket(uint8_t *buffer, uint16_t blockno) +{ + buffer[0] = TFTP_ACK >> 8; + buffer[1] = TFTP_ACK & 0xff; + buffer[2] = blockno >> 8; + buffer[3] = blockno & 0xff; + return 4; +} + +/**************************************************************************** + * Name: tftp_mkerrpacket + * + * Description: + * ERROR message format: + * + * 2 bytes: Opcode (network order == big-endian) + * 2 bytes: Error number (network order == big-endian) + * N bytes: Error string + * 1 byte: 0 + * + ****************************************************************************/ + +int tftp_mkerrpacket(uint8_t *buffer, uint16_t errorcode, const char *errormsg) +{ + buffer[0] = TFTP_ERR >> 8; + buffer[1] = TFTP_ERR & 0xff; + buffer[2] = errorcode >> 8; + buffer[3] = errorcode & 0xff; + strcpy((char*)&buffer[4], errormsg); + return strlen(errormsg) + 5; +} + +/**************************************************************************** + * Name: tftp_parseerrpacket + * + * Description: + * ERROR message format: + * + * 2 bytes: Opcode (network order == big-endian) + * 2 bytes: Error number (network order == big-endian) + * N bytes: Error string + * 1 byte: 0 + * + ****************************************************************************/ + +#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET) +int tftp_parseerrpacket(const uint8_t *buffer) +{ + uint16_t opcode = (uint16_t)buffer[0] << 8 | (uint16_t)buffer[1]; + uint16_t errcode = (uint16_t)buffer[2] << 8 | (uint16_t)buffer[3]; + const char *errmsg = (const char *)&buffer[4]; + + if (opcode == TFTP_ERR) + { + ndbg("ERR message: %s (%d)\n", errmsg, errcode); + return OK; + } + return ERROR; +} +#endif + +/**************************************************************************** + * Name: tftp_recvfrom + * + * Description: + * recvfrom helper + * + ****************************************************************************/ + +ssize_t tftp_recvfrom(int sd, void *buf, size_t len, struct sockaddr_in *from) +{ + int addrlen; + ssize_t nbytes; + + /* Loop handles the case where the recvfrom is interrupted by a signal and + * we should unconditionally try again. + */ + + for (;;) + { + /* For debugging, it is helpful to start with a clean buffer */ + +#if defined(CONFIG_DEBUG_VERBOSE) && defined(CONFIG_DEBUG_NET) + memset(buf, 0, len); +#endif + + /* Receive the packet */ + + addrlen = sizeof(struct sockaddr_in); + nbytes = recvfrom(sd, buf, len, 0, (struct sockaddr*)from, (socklen_t*)&addrlen); + + /* Check for errors */ + + if (nbytes < 0) + { + /* Check for a timeout */ + + if (errno == EAGAIN) + { + ndbg("recvfrom timed out\n"); + return ERROR; + } + + /* If EINTR, then loop and try again. Other errors are fatal */ + + else if (errno != EINTR) + { + ndbg("recvfrom failed: %d\n", errno); + return ERROR; + } + } + + /* No errors? Return the number of bytes received */ + + else + { + return nbytes; + } + } +} + +/**************************************************************************** + * Name: tftp_sendto + * + * Description: + * sendto helper + * + ****************************************************************************/ + +ssize_t tftp_sendto(int sd, const void *buf, size_t len, struct sockaddr_in *to) +{ + ssize_t nbytes; + + /* Loop handles the case where the sendto is interrupted by a signal and + * we should unconditionally try again. + */ + + for (;;) + { + /* Send the packet */ + + nbytes = sendto(sd, buf, len, 0, (struct sockaddr*)to, sizeof(struct sockaddr_in)); + + /* Check for errors */ + + if (nbytes < 0) + { + /* If EINTR, then loop and try again. Other errors are fatal */ + + if (errno != EINTR) + { + ndbg("sendto failed: %d\n", errno); + return ERROR; + } + } + + /* No errors? Return the number of bytes received */ + + else + { + return nbytes; + } + } +} + +#endif /* CONFIG_NET && CONFIG_NET_UDP && CONFIG_NFILE_DESCRIPTORS */ diff --git a/apps/netutils/tftpc/tftpc_put.c b/apps/netutils/tftpc/tftpc_put.c new file mode 100644 index 000000000..4d87ba908 --- /dev/null +++ b/apps/netutils/tftpc/tftpc_put.c @@ -0,0 +1,477 @@ +/**************************************************************************** + * netuils/tftp/tftpc_put.c + * + * Copyright (C) 2008-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, TFTP_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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <stdint.h> +#include <stdbool.h> +#include <stdlib.h> +#include <unistd.h> +#include <fcntl.h> +#include <errno.h> +#include <debug.h> + +#include <net/uip/uipopt.h> +#include <net/uip/uip.h> +#include <apps/netutils/tftp.h> + +#include "tftpc_internal.h" + +#if defined(CONFIG_NET) && defined(CONFIG_NET_UDP) && CONFIG_NFILE_DESCRIPTORS > 0 + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define TFTP_RETRIES 3 + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftp_read + ****************************************************************************/ + +static inline ssize_t tftp_read(int fd, uint8_t *buf, size_t buflen) +{ + ssize_t nbytesread; + ssize_t totalread = 0; + + while (totalread < buflen) + { + /* Read the data... repeating the read in the event that it was + * interrupted by a signal. + */ + + do + { + nbytesread = read(fd, buf, buflen - totalread); + } + while (nbytesread < 0 && errno == EINTR); + + /* Check for non-EINTR errors */ + + if (nbytesread < 0) + { + ndbg("read failed: %d\n", errno); + return ERROR; + } + + /* Check for end of file */ + + else if (nbytesread == 0) + { + break; + } + + /* Handle partial reads. Partial reads can happen normally + * when the source is some device driver that returns data + * in bits and pieces as received (such as a pipe) + */ + + totalread += nbytesread; + buf += nbytesread; + } + return totalread; +} + +/**************************************************************************** + * Name: tftp_mkdatapacket + * + * Description: + * DATA message format: + * + * 2 bytes: Opcode (network order == big-endian) + * 2 bytes: Block number (network order == big-endian) + * N bytes: Data (where N <= 512) + * + * Input Parameters: + * fd - File descriptor used to read from the file + * offset - File offset to read from + * packet - Buffer to write the data packet into + * blockno - The block number of the packet + * + * Return Value: + * Number of bytes read into the packet. <TFTP_PACKETSIZE means end of file; + * <1 if an error occurs. + * + ****************************************************************************/ + +int tftp_mkdatapacket(int fd, off_t offset, uint8_t *packet, uint16_t blockno) +{ + off_t tmp; + int nbytesread; + + /* Format the DATA message header */ + + packet[0] = TFTP_DATA >> 8; + packet[1] = TFTP_DATA & 0xff; + packet[2] = blockno >> 8; + packet[3] = blockno & 0xff; + + /* Seek to the correct offset in the file */ + + tmp = lseek(fd, offset, SEEK_SET); + if (tmp == (off_t)-1) + { + ndbg("lseek failed: %d\n", errno); + return ERROR; + } + + /* Read the file data into the packet buffer */ + + nbytesread = tftp_read(fd, &packet[TFTP_DATAHEADERSIZE], TFTP_DATASIZE); + if (nbytesread < 0) + { + return ERROR; + } + return nbytesread + TFTP_DATAHEADERSIZE; +} + +/**************************************************************************** + * Name: tftp_rcvack + * + * Description: + * ACK message format: + * + * 2 bytes: Opcode (network order == big-endian) + * 2 bytes: Block number (network order == big-endian) + * + * Input Parameters: + * sd - Socket descriptor to use in in the transfer + * packet - buffer to use for the tranfers + * server - The address of the server + * port - The port number of the server (0 if not yet known) + * blockno - Location to return block number in the received ACK + * + * Returned Value: + * OK:success and blockno valid, ERROR:failure. + * + ****************************************************************************/ + +static int tftp_rcvack(int sd, uint8_t *packet, struct sockaddr_in *server, + uint16_t *port, uint16_t *blockno) +{ + struct sockaddr_in from; /* The address the last UDP message recv'd from */ + ssize_t nbytes; /* The number of bytes received. */ + uint16_t opcode; /* The received opcode */ + uint16_t rblockno; /* The received block number */ + int packetlen; /* Packet length */ + int retry; /* Retry counter */ + + /* Try up to TFTP_RETRIES times */ + + for (retry = 0; retry < TFTP_RETRIES; retry++) + { + /* Try for until a valid ACK is received or some error occurs */ + + for (;;) + { + /* Receive the next UDP packet from the server */ + + nbytes = tftp_recvfrom(sd, packet, TFTP_IOBUFSIZE, &from); + if (nbytes < TFTP_ACKHEADERSIZE) + { + /* Failed to receive a good packet */ + + if (nbytes >= 0) + { + ndbg("tftp_recvfrom short packet: %d bytes\n", nbytes); + } + + /* Break out to bump up the retry count */ + + break; + } + else + { + /* Get the port being used by the server if that has not yet been established */ + + if (!*port) + { + *port = from.sin_port; + server->sin_port = from.sin_port; + } + + /* Verify that the packet was received from the correct host and port */ + + if (server->sin_addr.s_addr != from.sin_addr.s_addr) + { + nvdbg("Invalid address in DATA\n"); + continue; + } + + if (*port != server->sin_port) + { + nvdbg("Invalid port in DATA\n"); + packetlen = tftp_mkerrpacket(packet, TFTP_ERR_UNKID, TFTP_ERRST_UNKID); + (void)tftp_sendto(sd, packet, packetlen, server); + continue; + } + + /* Parse the error message */ + + opcode = (uint16_t)packet[0] << 8 | (uint16_t)packet[1]; + rblockno = (uint16_t)packet[2] << 8 | (uint16_t)packet[3]; + + /* Verify that the message that we received is an ACK for the + * expected block number. + */ + + if (opcode != TFTP_ACK) + { + nvdbg("Bad opcode\n"); +#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET) + if (opcode == TFTP_ERR) + { + (void)tftp_parseerrpacket(packet); + } + else +#endif + if (opcode > TFTP_MAXRFC1350) + { + packetlen = tftp_mkerrpacket(packet, TFTP_ERR_ILLEGALOP, TFTP_ERRST_ILLEGALOP); + (void)tftp_sendto(sd, packet, packetlen, server); + } + + /* Break out an bump up the retry count */ + + break; + } + + /* Success! */ + + nvdbg("Received ACK for block %d\n", rblockno); + *blockno = rblockno; + return OK; + } + } + } + + /* We have tried TFTP_RETRIES times */ + + ndbg("Timeout, Waiting for ACK\n"); + return ERROR; /* Will never get here */ +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: tftpput + * + * Input Parameters: + * local - Path to the file system object to be sent. + * remote - The name of the file on the TFTP server. + * addr - The IP address of the server in network order + * binary - TRUE: Perform binary ('octect') transfer + * FALSE: Perform text ('netascii') transfer + * + ****************************************************************************/ + +int tftpput(const char *local, const char *remote, in_addr_t addr, bool binary) +{ + struct sockaddr_in server; /* The address of the TFTP server */ + uint8_t *packet; /* Allocated memory to hold one packet */ + off_t offset; /* Offset into source file */ + uint16_t blockno; /* The current transfer block number */ + uint16_t rblockno; /* The ACK'ed block number */ + uint16_t port = 0; /* This is the port number for the transfer */ + int packetlen; /* The length of the data packet */ + int sd; /* Socket descriptor for socket I/O */ + int fd; /* File descriptor for file I/O */ + int retry; /* Retry counter */ + int result = ERROR; /* Assume failure */ + int ret; /* Generic return status */ + + /* Allocate the buffer to used for socket/disk I/O */ + + packet = (uint8_t*)zalloc(TFTP_IOBUFSIZE); + if (!packet) + { + ndbg("packet memory allocation failure\n"); + errno = ENOMEM; + goto errout; + } + + /* Open the file for reading */ + + fd = open(local, O_RDONLY); + if (fd < 0) + { + ndbg("open failed: %d\n", errno); + goto errout_with_packet; + } + + /* Initialize a UDP socket and setup the server addresss */ + + sd = tftp_sockinit(&server, addr); + if (sd < 0) + { + goto errout_with_fd; + } + + /* Send the write request using the well known port. This may need + * to be done several times because (1) UDP is inherenly unreliable + * and packets may be lost normally, and (2) uIP has a nasty habit + * of droppying packets if there is nothing hit in the ARP table. + */ + + blockno = 1; + retry = 0; + for (;;) + { + packetlen = tftp_mkreqpacket(packet, TFTP_WRQ, remote, binary); + ret = tftp_sendto(sd, packet, packetlen, &server); + if (ret != packetlen) + { + goto errout_with_sd; + } + + /* Receive the ACK for the write request */ + + if (tftp_rcvack(sd, packet, &server, &port, NULL) == 0) + { + break; + } + + ndbg("Re-sending request\n"); + + /* We are going to loop and re-send the request packet. Check the + * retry count so that we do not loop forever. + */ + + if (++retry > TFTP_RETRIES) + { + ndbg("Retry count exceeded\n"); + errno = ETIMEDOUT; + goto errout_with_sd; + } + } + + /* Then loop sending the entire file to the server in chunks */ + + offset = 0; + retry = 0; + + for (;;) + { + /* Construct the next data packet */ + + packetlen = tftp_mkdatapacket(fd, offset, packet, blockno); + if (packetlen < 0) + { + goto errout_with_sd; + } + + /* Send the next data chunk */ + + ret = tftp_sendto(sd, packet, packetlen, &server); + if (ret != packetlen) + { + goto errout_with_sd; + } + + /* Check for an ACK for the data chunk */ + + if (tftp_rcvack(sd, packet, &server, &port, &rblockno) == OK) + { + /* Check if the packet that we just sent was ACK'ed. If not, + * we just loop to resend the same packet (same blockno, same + * file offset). + */ + + if (rblockno == blockno) + { + /* Yes.. If we are at the end of the file and if all of the packets + * have been ACKed, then we are done. + */ + + if (packetlen < TFTP_PACKETSIZE) + { + break; + } + + /* Not the last block.. set up for the next block */ + + blockno++; + offset += TFTP_DATASIZE; + retry = 0; + + /* Skip the retry test */ + + continue; + } + } + + /* We are going to loop and re-send the data packet. Check the retry + * count so that we do not loop forever. + */ + + if (++retry > TFTP_RETRIES) + { + ndbg("Retry count exceeded\n"); + errno = ETIMEDOUT; + goto errout_with_sd; + } + } + + /* Return success */ + + result = OK; + +errout_with_sd: + close(sd); +errout_with_fd: + close(fd); +errout_with_packet: + free(packet); +errout: + return result; +} + +#endif /* CONFIG_NET && CONFIG_NET_UDP && CONFIG_NFILE_DESCRIPTORS > 0 */ diff --git a/apps/netutils/thttpd/Makefile b/apps/netutils/thttpd/Makefile new file mode 100644 index 000000000..85e603f22 --- /dev/null +++ b/apps/netutils/thttpd/Makefile @@ -0,0 +1,121 @@ +############################################################################# +# apps/netutils/thttpd/Makefile +# +# Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################# + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# THTTPD Library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_TCP),y) +CSRCS += thttpd.c libhttpd.c thttpd_cgi.c thttpd_alloc.c thttpd_strings.c timers.c fdwatch.c tdate_parse.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# CGI binaries (examples only, not used in the build) + +CGIBINDIR = $(APPDIR)/netutils/thttpd/cgi-bin + +SUBDIRS = +ifeq ($(CONFIG_NXFLAT),y) +SUBDIRS = cgi-src +SUBDIR_BIN1 = phf +SUBDIR_BIN2 = redirect +SUBDIR_BIN3 = ssi +SUBDIR_BIN += cgi-bin/$(SUBDIR_BIN1) cgi-bin/$(SUBDIR_BIN2) cgi-bin/$(SUBDIR_BIN3) +endif + +all: $(SUBDIR_BIN) $(BIN) +.PHONY: depend clean distclean + +ifeq ($(CONFIG_NXFLAT),y) +cgi-bin: + @mkdir cgi-bin + +cgi-src/$(SUBDIR_BIN1): + @$(MAKE) -C cgi-src $(SUBDIR_BIN1) + +cgi-bin/$(SUBDIR_BIN1): cgi-bin cgi-src/$(SUBDIR_BIN1) + @cp -a cgi-src/$(SUBDIR_BIN1) $@ + +cgi-src/$(SUBDIR_BIN2): + @$(MAKE) -C cgi-src $(SUBDIR_BIN2) + +cgi-bin/$(SUBDIR_BIN2): cgi-bin cgi-src/$(SUBDIR_BIN2) + @cp -a cgi-src/$(SUBDIR_BIN2) $@ + +cgi-src/$(SUBDIR_BIN3): + @$(MAKE) -C cgi-src $(SUBDIR_BIN3) + +cgi-bin/$(SUBDIR_BIN3): cgi-bin cgi-src/$(SUBDIR_BIN3) + @cp -a cgi-src/$(SUBDIR_BIN3) $@ +endif + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/thttpd/cgi-src/Makefile b/apps/netutils/thttpd/cgi-src/Makefile new file mode 100644 index 000000000..3f025dec3 --- /dev/null +++ b/apps/netutils/thttpd/cgi-src/Makefile @@ -0,0 +1,136 @@ +############################################################################ +# apps/netutils/cgi-src/Makefile +# +# Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs + +CFLAGS += -I$(APPDIR)/netutils/thttpd -I$(APPDIR)/netutils/thttpd/cgi-src +CGIBINDIR = $(APPDIR)/netutils/thttpd/cgi-bin +CLEANFILES = *.o redirect ssi phf + +BIN1 = phf +BIN2 = redirect +BIN3 = ssi +BIN = $(BIN1) $(BIN2) $(BIN3) + +R1SRCS1 = $(BIN1).c +R1OBJS1 = $(R1SRCS1:.c=.o) +R2SRC1 = $(BIN1)-thunk.S +R2OBJ1 = $(R2SRC1:.S=.o) + +R1SRCS2 = $(BIN2).c +R1OBJS2 = $(R1SRCS2:.c=.o) +R2SRC2 = $(BIN2)-thunk.S +R2OBJ2 = $(R2SRC2:.S=.o) + +R1SRCS3 = $(BIN3).c +R1OBJS3 = $(R1SRCS3:.c=.o) +R2SRC3 = $(BIN3)-thunk.S +R2OBJ3 = $(R2SRC3:.S=.o) + +DERIVED = $(R2SRC1) $(R2SRC2) $(R2SRC3) + +R1COBJS = $(R1OBJS1) $(R1OBJS2) $(R1OBJS3) +R2AOBJS = $(R2OBJ1) $(R2OBJ2) $(R2OBJ3) + +all: $(BIN1) $(BIN2) $(BIN3) + +$(R1COBJS): %.o: %.c + @echo "CC: $<" + @$(CC) -c $(CPICFLAGS) $< -o $@ + +$(R2AOBJS): %.o: %.S + @echo "AS: $<" + @$(CC) -c $(CPICFLAGS) $< -o $@ + +# BIN1 + +$(BIN1).r1: $(R1OBJS1) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS1) -o $@ $^ + +$(R2SRC1): $(BIN1).r1 + @echo "MK: $<" + @$(MKNXFLAT) -o $@ $^ + +$(BIN1).r2: $(R2OBJ1) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS2) -o $@ $(R1OBJS1) $(R2OBJ1) + +$(BIN1): $(BIN1).r2 + @echo "LD: $<" + @$(LDNXFLAT) $(LDNXFLATFLAGS) -o $@ $^ + +#BIN2 + +$(BIN2).r1: $(R1OBJS2) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS1) -o $@ $^ + +$(R2SRC2): $(BIN2).r1 + @echo "MK: $<" + @$(MKNXFLAT) -o $@ $^ + +$(BIN2).r2: $(R2OBJ2) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS2) -o $@ $(R1OBJS2) $(R2OBJ2) + +$(BIN2): $(BIN2).r2 + @echo "LD: $<" + @$(LDNXFLAT) $(LDNXFLATFLAGS) -o $@ $^ +# BIN3 + +$(BIN3).r1: $(R1OBJS3) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS1) -o $@ $^ + +$(R2SRC3): $(BIN3).r1 + @echo "MK: $<" + @$(MKNXFLAT) -o $@ $^ + +$(BIN3).r2: $(R2OBJ3) + @echo "LD: $<" + @$(LD) $(NXFLATLDFLAGS2) -o $@ $(R1OBJS3) $(R2OBJ3) + +$(BIN3): $(BIN3).r2 + @echo "LD: $<" + @$(LDNXFLAT) $(LDNXFLATFLAGS) -o $@ $^ + +clean: + @rm -f $(BIN1) $(BIN2) $(BIN3) *.r1 *.r2 *-thunk.S *~ .*.swp + $(call CLEAN) + +distclean: clean + diff --git a/apps/netutils/thttpd/cgi-src/phf.c b/apps/netutils/thttpd/cgi-src/phf.c new file mode 100644 index 000000000..2541481c4 --- /dev/null +++ b/apps/netutils/thttpd/cgi-src/phf.c @@ -0,0 +1,77 @@ +/**************************************************************************** + * netutils/thttpd/cgi-src/phf.c + * Cracker trap + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1996 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/* Old distributions of the NCSA and Apache web servers included a + * version of the phf program that had a bug. The program could + * easily be made to run arbitrary shell commands. There is no real + * legitimate use for phf, so any attempts to run it must be considered + * to be attacks. Accordingly, this version of phf logs the attack + * on stderr and then returns a page on CONFIG_THTTPD_CGI_OUTFD indicating + * that phf doesn't exist. + */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "config.h" + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int main(int argc, char *argv[]) +{ + fprintf(stderr, "phf CGI probe from %s\n", getenv("REMOTE_ADDR")); + + (void)printf("\ +Content-type: text/html\n\ +Status: 404/html\n\ +\n\ +<HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD>\n\ +<BODY><H2>404 Not Found</H2>\n\ +The requested object does not exist on this server.\n\ +The link you followed is either outdated, inaccurate,\n\ +or the server has been instructed not to let you have it.\n\ +</BODY></HTML>\n"); + return 0; +} diff --git a/apps/netutils/thttpd/cgi-src/redirect.c b/apps/netutils/thttpd/cgi-src/redirect.c new file mode 100644 index 000000000..84f3b8712 --- /dev/null +++ b/apps/netutils/thttpd/cgi-src/redirect.c @@ -0,0 +1,269 @@ +/**************************************************************************** + * netutils/thttpd/cgi-src/redirect.c + * Simple redirection CGI program + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/* Three steps to set up a redirection: + * + * 1. Make sure your web server is set up to allow CGI programs. + * 2. Make a symbolic link from the file you want to redirect, + * pointing at this program in the CGI bin directory. + * 3. Add an entry to the file ".redirects" in the directory where your + * http server runs CGI programs. For most servers, this is the + * directory where the given CGI program lives. The format of the + * file is a bunch of lines with a filename, whitespace, and the new + * URL. For example: + * + * /test/oldfile.html http://www.acme.com/test/newfile.html + * + * The easiest way to figure out precisely what filename to put into + * .redirects is to set up the symlink and then click on it. You'll get + * back a "404 Not Found" page which includes the filename as received by + * the redirect program, and that's what you want to use. + * + * Note: this is designed for thttpd (http://www.acme.com/software/thttpd/) + * and using it with other web servers may require some hacking. A possible + * gotcha is with the symbolic link from the old file pointing at this + * script - servers other than thttpd may not allow that link to be run + * as a CGI program, because they don't check the link to see that it + * points into the allowed CGI directory. + * + * Note two: It would be really cool to have this program look for + * the .redirects file in the same directory as the file being redirected, + * instead of in the binaries directory. Unfortunately, this appears + * to be impossible with the information CGI gives, plus the non-standardized + * but widespread practice of running CGI programs in the directory where + * the binary lives. Perhaps CGI 1.2 will address this. + */ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> + +#include "config.h" + +/**************************************************************************** + * Pre-Processor Definitions + ****************************************************************************/ + +#define LINE_SIZE 80 + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static char g_iobuffer[LINE_SIZE]; +static char g_file[LINE_SIZE]; +static char g_url[LINE_SIZE]; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void internal_error(char *reason) +{ + char *title = "500 Internal Error"; + + (void)printf("\ +Status: %s\n\ +Content-type: text/html\n\ +\n\ +<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n\ +<BODY><H2>%s</H2>\n\ +Something unusual went wrong during a redirection request:\n\ +<BLOCKQUOTE>\n\ +%s\n\ +</BLOCKQUOTE>\n\ +</BODY></HTML>\n", title, title, title, reason); +} + +static void not_found(char *script_name) +{ + char *title = "404 Not Found"; + + (void)printf("\ +Status: %s\n\ +Content-type: text/html\n\ +\n\ +<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n\ +<BODY><H2>%s</H2>\n\ +The requested filename, %s, is set up to be redirected to another URL;\n\ +however, the new URL has not yet been specified.\n\ +</BODY></HTML>\n", title, title, title, script_name); +} + +static void moved(char *script_name, char *url) +{ + char *title = "Moved"; + + (void)printf("\ +Location: %s\n\ +Content-type: text/html\n\ +\n\ +<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n\ +<BODY><H2>%s</H2>\n\ +The requested filename, %s, has moved to a new URL:\n\ +<A HREF=\"%s\">%s</A>.\n\ +</BODY></HTML>\n", url, title, title, script_name, url, url); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int main(int argc, char **argv) +{ + char *script_name; + char *path_info; + char *cp = 0; + FILE *fp; + char *star; + int err = 0; + + /* Get the name that we were run as, which is the filename being ** + * redirected. + */ + + script_name = getenv("SCRIPT_NAME"); + if (!script_name) + { + internal_error("Couldn't get SCRIPT_NAME environment variable."); + return 1; + } + + /* Append the PATH_INFO, if any. This allows redirection of whole ** + * directories. + */ + + path_info = getenv("PATH_INFO"); + if (path_info) + { + cp = (char *)malloc(strlen(script_name) + strlen(path_info) + 1); + if (!cp) + { + internal_error("Out of memory."); + return 2; + } + + (void)sprintf(cp, "%s%s", script_name, path_info); + script_name = cp; + } + + /* Open the redirects file. */ + + fp = fopen(".redirects", "r"); + if (fp == (FILE *) 0) + { + internal_error("Couldn't open .redirects file."); + err = 3; + goto errout_with_cp; + } + + /* Search the file for a matching entry. */ + + while (fgets(g_iobuffer, LINE_SIZE, fp) != NULL) + { + /* Remove comments. */ + + cp = strchr(g_iobuffer, '#'); + if (cp) + { + *cp = '\0'; + } + + /* Skip leading whitespace. */ + + cp = g_iobuffer; + cp += strspn(cp, " \t"); + + /* Check for blank line. */ + + if (*cp != '\0') + { + /* Parse line. */ + + if (sscanf(cp, "%[^ \t\n] %[^ \t\n]", g_file, g_url) == 2) + { + /* Check for wildcard match. */ + + star = strchr(g_file, '*'); + if (star != (char *)0) + { + /* Check for leading match. */ + + if (strncmp(g_file, script_name, star - g_file) == 0) + { + /* Got it; put together the full name. */ + + strcat(g_url, script_name + (star - g_file)); + + /* XXX Whack the script_name, too? */ + + moved(script_name, g_url); + goto success_out; + } + } + + /* Check for exact match. */ + + if (strcmp(g_file, script_name) == 0) + { + /* Got it. */ + + moved(script_name, g_url); + goto success_out; + } + } + } + } + + /* No match found. */ + + not_found(script_name); + err = 4; + +success_out: + fclose(fp); +errout_with_cp: + if (cp) + { + free(cp); + } + return err; +} diff --git a/apps/netutils/thttpd/cgi-src/ssi.c b/apps/netutils/thttpd/cgi-src/ssi.c new file mode 100644 index 000000000..4afb141f9 --- /dev/null +++ b/apps/netutils/thttpd/cgi-src/ssi.c @@ -0,0 +1,957 @@ +/**************************************************************************** + * netutils/thttpd/cgi-src/ssi.c + * Server-side-includes CGI program + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/time.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <errno.h> + +#include <nuttx/regex.h> + +#include "config.h" + +/**************************************************************************** + * Pre-Processor Definitions + ****************************************************************************/ + +#define ST_GROUND 0 +#define ST_LESSTHAN 1 +#define ST_BANG 2 +#define ST_MINUS1 3 +#define ST_MINUS2 4 + +#define SF_BYTES 0 +#define SF_ABBREV 1 + +#define DI_CONFIG 0 +#define DI_INCLUDE 1 +#define DI_ECHO 2 +#define DI_FSIZE 3 +#define DI_FLASTMOD 4 + +#define BUFFER_SIZE 512 +#define TIMEFMT_SIZE 80 +#define MAX_TAGS 32 + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void read_file(FILE *instream, char *vfilename, char *filename); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static char *g_url; +static char g_timeformat[TIMEFMT_SIZE]; +static char g_iobuffer1[BUFFER_SIZE]; +static char g_iobuffer2[BUFFER_SIZE]; +static char *g_tags[MAX_TAGS]; +static int g_sizefmt; +static struct stat g_sb; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void internal_error(char *reason) +{ + char *title = "500 Internal Error"; + + (void)printf("\ +<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n\ +<BODY><H2>%s</H2>\n\ +Something unusual went wrong during a server-side-includes request:\n\ +<BLOCKQUOTE>\n\ +%s\n\ +</BLOCKQUOTE>\n\ +</BODY></HTML>\n", title, title, reason); +} + +static void not_found(char *filename) +{ + char *title = "404 Not Found"; + + (void)printf("\ +<HTML><HEAD><TITLE>%s</TITLE></HEAD>\n\ +<BODY><H2>%s</H2>\n\ +The requested server-side-includes filename, %s,\n\ +does not seem to exist.\n\ +</BODY></HTML>\n", title, title, filename); +} + +static void not_found2(char *directive, char *tag, char *filename) +{ + char *title = "Not Found"; + + (void)printf("\ +<HR><H2>%s</H2>\n\ +The filename requested in a %s %s directive, %s,\n\ +does not seem to exist.\n\ +<HR>\n", title, directive, tag, filename); +} + +static void not_permitted(char *directive, char *tag, char *val) +{ + char *title = "Not Permitted"; + + (void)printf("\ +<HR><H2>%s</H2>\n\ +The filename requested in the %s %s=%s directive\n\ +may not be fetched.\n\ +<HR>\n", title, directive, tag, val); +} + +static void unknown_directive(char *filename, char *directive) +{ + char *title = "Unknown Directive"; + + (void)printf("\ +<HR><H2>%s</H2>\n\ +The requested server-side-includes filename, %s,\n\ +tried to use an unknown directive, %s.\n\ +<HR>\n", title, filename, directive); +} + +static void unknown_tag(char *filename, char *directive, char *tag) +{ + char *title = "Unknown Tag"; + + (void)printf("\ +<HR><H2>%s</H2>\n\ +The requested server-side-includes filename, %s,\n\ +tried to use the directive %s with an unknown tag, %s.\n\ +<HR>\n", title, filename, directive, tag); +} + +static void unknown_value(char *filename, char *directive, char *tag, char *val) +{ + char *title = "Unknown Value"; + + (void)printf("\ +<HR><H2>%s</H2>\n\ +The requested server-side-includes filename, %s,\n\ +tried to use the directive %s %s with an unknown value, %s.\n\ +<HR>\n", title, filename, directive, tag, val); +} + +static int get_filename(char *vfilename, char *filename, + char *directive, char *tag, char *val, char *fn, + int fnsize) +{ + char *cp; + int vl; + int fl; + + /* Used for the various commands that accept a file name. These commands + * accept two tags: virtual Gives a virtual path to a document on the + * server. file Gives a pathname relative to the current directory. ../ + * cannot be used in this pathname, nor can absolute paths be used. + */ + + vl = strlen(vfilename); + fl = strlen(filename); + + if (strcmp(tag, "virtual") == 0) + { + if (strstr(val, "../") != (char *)0) + { + not_permitted(directive, tag, val); + return -1; + } + + /* Figure out root using difference between vfilename and filename. */ + + if (vl > fl || strcmp(vfilename, &filename[fl - vl]) != 0) + { + return -1; + } + + if (fl - vl + strlen(val) >= fnsize) + { + return -1; + } + + (void)strncpy(fn, filename, fl - vl); + (void)strcpy(&fn[fl - vl], val); + } + else if (strcmp(tag, "file") == 0) + { + if (val[0] == '/' || strstr(val, "../") != (char *)0) + { + not_permitted(directive, tag, val); + return -1; + } + if (fl + 1 + strlen(val) >= fnsize) + { + return -1; + } + + (void)strcpy(fn, filename); + cp = strrchr(fn, '/'); + if (cp == (char *)0) + { + cp = &fn[strlen(fn)]; + *cp = '/'; + } + (void)strcpy(++cp, val); + } + else + { + unknown_tag(filename, directive, tag); + return -1; + } + return 0; +} + +static int check_filename(char *filename) +{ + static int inited = 0; + static char *cgi_pattern; +#ifdef CONFIG_AUTH_FILE + struct stat sb; + char *dirname; + char *authname; + char *cp; + int fnl; + int r; +#endif + + if (!inited) + { + /* Get the cgi pattern. */ + + cgi_pattern = getenv("CGI_PATTERN"); +#ifdef CGI_PATTERN + if (cgi_pattern == (char *)0) + { + cgi_pattern = CGI_PATTERN; + } +#endif /* CGI_PATTERN */ + inited = 1; + } + + /* ../ is not permitted. */ + + if (strstr(filename, "../") !=NULL) + { + return 0; + } + + /* Ensure that we are not reading a basic auth password file. */ + +#ifdef CONFIG_AUTH_FILE + fnl = strlen(filename); + if (strcmp(filename, CONFIG_AUTH_FILE) == 0 || + (fnl >= sizeof(CONFIG_AUTH_FILE) && + strcmp(&filename[fnl - sizeof(CONFIG_AUTH_FILE) + 1], CONFIG_AUTH_FILE) == 0 && + filename[fnl - sizeof(CONFIG_AUTH_FILE)] == '/')) + { + return 0; + } + + /* Check for an auth file in the same directory. We can't do an actual ** + * auth password check here because CGI programs are not given the ** + * authorization header, for security reasons. So instead we just ** + * prohibit access to all auth-protected files. + */ + + dirname = strdup(filename); + if (dirname == (char *)0) + { + /* out of memory */ + + return 0; + } + + cp = strrchr(dirname, '/'); + if (cp == (char *)0) + { + (void)strcpy(dirname, "."); + } + else + { + *cp = '\0'; + } + + authname = malloc(strlen(dirname) + 1 + sizeof(CONFIG_AUTH_FILE)); + if (!authname) + { + /* out of memory */ + + free(dirname); + return 0; + } + + (void)sprintf(authname, "%s/%s", dirname, CONFIG_AUTH_FILE); + r = stat(authname, &sb); + + free(dirname); + free(authname); + + if (r == 0) + { + return 0; + } +#endif /* CONFIG_AUTH_FILE */ + + /* Ensure that we are not reading a CGI file. */ + + if (cgi_pattern != (char *)0 && match(cgi_pattern, filename)) + { + return 0; + } + return 1; +} + +static void show_time(time_t t, int gmt) +{ + struct tm *tmP; + + if (gmt) + { + tmP = gmtime(&t); + } + else + { + tmP = localtime(&t); + } + + if (strftime(g_iobuffer2, BUFFER_SIZE, g_timeformat, tmP) > 0) + { + (void)puts(g_iobuffer2); + } +} + +static void show_size(off_t size) +{ + switch (g_sizefmt) + { + case SF_BYTES: + (void)printf("%ld", (long)size); /* spec says should have commas */ + break; + + case SF_ABBREV: + if (size < 1024) + { + (void)printf("%ld", (long)size); + } + else if (size < 1024) + { + (void)printf("%ldK", (long)size / 1024L); + } + else if (size < 1024 * 1024) + { + (void)printf("%ldM", (long)size / (1024L * 1024L)); + } + else + { + (void)printf("%ldG", (long)size / (1024L * 1024L * 1024L)); + } + break; + } +} + +static void do_config(FILE *instream, char *vfilename, char *filename, + char *directive, char *tag, char *val) +{ + /* The config directive controls various aspects of the file parsing. ** + * There are two valid tags: g_timeformat Gives the server a new format to + * use when providing dates. This is a string compatible with the + * strftime library call. g_sizefmt Determines the formatting to be used + * when displaying the size of a file. Valid choices are bytes, for a + * formatted byte count (formatted as 1,234,567), or abbrev for an + * abbreviated version displaying the number of kilobytes or megabytes the + * file occupies. + */ + + if (strcmp(tag, "g_timeformat") == 0) + { + (void)strncpy(g_timeformat, val, TIMEFMT_SIZE - 1); + g_timeformat[TIMEFMT_SIZE - 1] = '\0'; + } + else if (strcmp(tag, "g_sizefmt") == 0) + { + if (strcmp(val, "bytes") == 0) + { + g_sizefmt = SF_BYTES; + } + else if (strcmp(val, "abbrev") == 0) + { + g_sizefmt = SF_ABBREV; + } + else + { + unknown_value(filename, directive, tag, val); + } + } + else + { + unknown_tag(filename, directive, tag); + } +} + +static void do_include(FILE *instream, char *vfilename, char *filename, + char *directive, char *tag, char *val) +{ + FILE *instream2; + int ret; + + /* Inserts the text of another document into the parsed document. */ + + ret = get_filename(vfilename, filename, directive, tag, val, g_iobuffer1, BUFFER_SIZE); + if (ret < 0) + { + return; + } + + if (!check_filename(g_iobuffer1)) + { + not_permitted(directive, tag, g_iobuffer1); + return; + } + + instream2 = fopen(g_iobuffer1, "r"); + if (instream2 == (FILE *) 0) + { + not_found2(directive, tag, g_iobuffer1); + return; + } + + if (strcmp(tag, "virtual") == 0) + { + if (strlen(val) <BUFFER_SIZE) + { + (void)strcpy(g_iobuffer2, val); + } + else + { + (void)strcpy(g_iobuffer2, g_iobuffer1); /* same size, has to fit */ + } + } + else + { + if (strlen(vfilename) + 1 + strlen(val) < BUFFER_SIZE) + { + char *cp; + (void)strcpy(g_iobuffer2, vfilename); + cp = strrchr(g_iobuffer2, '/'); + if (cp == (char *)0) + { + cp = &g_iobuffer2[strlen(g_iobuffer2)]; + *cp = '/'; + } + (void)strcpy(++cp, val); + } + else + { + (void)strcpy(g_iobuffer2, g_iobuffer1); /* same size, has to fit */ + } + } + + read_file(instream2, g_iobuffer2, g_iobuffer1); + (void)fclose(instream2); +} + +static void do_echo(FILE *instream, char *vfilename, char *filename, + char *directive, char *tag, char *val) +{ + char *cp; + + /* Prints the value of one of the include variables. Any dates are + * printed subject to the currently configured g_timeformat. The only valid + * tag is var, whose value is the name of the variable you wish to echo. + */ + + if (strcmp(tag, "var") != 0) + { + unknown_tag(filename, directive, tag); + } + else + { + if (strcmp(val, "DOCUMENT_NAME") == 0) + { + /* The current filename. */ + + (void)puts(filename); + } + else if (strcmp(val, "DOCUMENT_URI") == 0) + { + /* The virtual path to this file (such as /~robm/foo.shtml). */ + + (void)puts(vfilename); + } + else if (strcmp(val, "QUERY_STRING_UNESCAPED") == 0) + { + /* The unescaped version of any search query the client sent. */ + + cp = getenv("QUERY_STRING"); + if (cp != (char *)0) + { + (void)puts(cp); + } + } + else if (strcmp(val, "DATE_LOCAL") == 0) + { + struct timeval tm; + + /* The current date, local time zone. */ + + gettimeofday(&tm, NULL); + show_time(tm.tv_sec, 0); + } + else if (strcmp(val, "DATE_GMT") == 0) + { + struct timeval tm; + + /* Same as DATE_LOCAL but in Greenwich mean time. */ + + gettimeofday(&tm, NULL); + show_time(tm.tv_sec, 1); + } + else if (strcmp(val, "LAST_MODIFIED") == 0) + { + /* The last modification date of the current document. */ + + if (fstat(fileno(instream), &g_sb) >= 0) + { + show_time(g_sb.st_mtime, 0); + } + } + else + { + /* Try an environment variable. */ + + cp = getenv(val); + if (cp == (char *)0) + { + unknown_value(filename, directive, tag, val); + } + else + { + (void)puts(cp); + } + } + } +} + +static void do_fsize(FILE *instream, char *vfilename, char *filename, + char *directive, char *tag, char *val) +{ + int ret; + + /* Prints the size of the specified file. */ + + ret = get_filename(vfilename, filename, directive, tag, val, g_iobuffer1, BUFFER_SIZE); + if (ret < 0) + { + return; + } + + if (stat(g_iobuffer1, &g_sb) < 0) + { + not_found2(directive, tag, g_iobuffer1); + return; + } + + show_size(g_sb.st_size); +} + +static void do_flastmod(FILE *instream, char *vfilename, char *filename, + char *directive, char *tag, char *val) +{ + int ret; + + /* Prints the last modification date of the specified file. */ + + ret = get_filename(vfilename, filename, directive, tag, val, g_iobuffer1, BUFFER_SIZE); + if (ret < 0) + { + return; + } + + if (stat(g_iobuffer1, &g_sb) < 0) + { + not_found2(directive, tag, g_iobuffer1); + return; + } + show_time(g_sb.st_mtime, 0); +} + +static void parse(FILE *instream, char *vfilename, char *filename, char *str) +{ + char *directive; + char *cp; + int ntags; + int dirn; + int i; + char *val; + + directive = str; + directive += strspn(directive, " \t\n\r"); + + ntags = 0; + cp = directive; + for (;;) + { + cp = strpbrk(cp, " \t\n\r\""); + if (cp == (char *)0) + { + break; + } + + if (*cp == '"') + { + cp = strpbrk(cp + 1, "\""); + cp++; + if (*cp == '\0') + { + break; + } + } + + *cp++ = '\0'; + cp += strspn(cp, " \t\n\r"); + if (*cp == '\0') + { + break; + } + + if (ntags < MAX_TAGS) + { + g_tags[ntags++] = cp; + } + } + + if (strcmp(directive, "config") == 0) + { + dirn = DI_CONFIG; + } + else if (strcmp(directive, "include") == 0) + { + dirn = DI_INCLUDE; + } + else if (strcmp(directive, "echo") == 0) + { + dirn = DI_ECHO; + } + else if (strcmp(directive, "fsize") == 0) + { + dirn = DI_FSIZE; + } + else if (strcmp(directive, "flastmod") == 0) + { + dirn = DI_FLASTMOD; + } + else + { + unknown_directive(filename, directive); + return; + } + + for (i = 0; i < ntags; ++i) + { + if (i > 0) + { + putchar(' '); + } + + val = strchr(g_tags[i], '='); + if (val == (char *)0) + { + val = ""; + } + else + { + *val++ = '\0'; + } + + if (*val == '"' && val[strlen(val) - 1] == '"') + { + val[strlen(val) - 1] = '\0'; + ++val; + } + + switch (dirn) + { + case DI_CONFIG: + do_config(instream, vfilename, filename, directive, g_tags[i], val); + break; + + case DI_INCLUDE: + do_include(instream, vfilename, filename, directive, g_tags[i], val); + break; + + case DI_ECHO: + do_echo(instream, vfilename, filename, directive, g_tags[i], val); + break; + + case DI_FSIZE: + do_fsize(instream, vfilename, filename, directive, g_tags[i], val); + break; + + case DI_FLASTMOD: + do_flastmod(instream, vfilename, filename, directive, g_tags[i], val); + break; + } + } +} + +static void slurp(FILE *instream, char *vfilename, char *filename) +{ + int state; + int ich; + int i; + + /* Now slurp in the rest of the comment from the input file. */ + + i = 0; + state = ST_GROUND; + while ((ich = getc(instream)) != EOF) + { + switch (state) + { + case ST_GROUND: + if (ich == '-') + { + state = ST_MINUS1; + } + break; + + case ST_MINUS1: + if (ich == '-') + { + state = ST_MINUS2; + } + else + { + state = ST_GROUND; + } + break; + + case ST_MINUS2: + if (ich == '>') + { + g_iobuffer1[i - 2] = '\0'; + parse(instream, vfilename, filename, g_iobuffer1); + return; + } + else if (ich != '-') + { + state = ST_GROUND; + } + break; + } + + if (i < BUFFER_SIZE - 1) + { + g_iobuffer1[i++] = (char)ich; + } + } +} + +static void read_file(FILE *instream, char *vfilename, char *filename) +{ + int ich; + int state; + + /* Copy it to output, while running a state-machine to look for SSI + * directives. + */ + + state = ST_GROUND; + while ((ich = getc(instream)) != EOF) + { + switch (state) + { + case ST_GROUND: + if (ich == '<') + { + state = ST_LESSTHAN; + continue; + } + break; + + case ST_LESSTHAN: + if (ich == '!') + { + state = ST_BANG; + continue; + } + else + { + state = ST_GROUND; + putchar('<'); + } + break; + + case ST_BANG: + if (ich == '-') + { + state = ST_MINUS1; + continue; + } + else + { + state = ST_GROUND; + (void)puts("<!"); + } + break; + + case ST_MINUS1: + if (ich == '-') + { + state = ST_MINUS2; + continue; + } + else + { + state = ST_GROUND; + (void)puts("<!-"); + } + break; + + case ST_MINUS2: + if (ich == '#') + { + slurp(instream, vfilename, filename); + state = ST_GROUND; + continue; + } + else + { + state = ST_GROUND; + (void)puts("<!--"); + } + break; + } + + putchar((char)ich); + } +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int main(int argc, char **argv) +{ + FILE *instream; + char *script_name; + char *path_info; + char *path_translated; + int err = 0; + + /* Default formats. */ + + (void)strcpy(g_timeformat, "%a %b %e %T %Z %Y"); + g_sizefmt = SF_BYTES; + + /* The MIME type has to be text/html. */ + + (void)puts("Content-type: text/html\n\n"); + + /* Get the name that we were run as. */ + + script_name = getenv("SCRIPT_NAME"); + if (!script_name) + { + internal_error("Couldn't get SCRIPT_NAME environment variable."); + return 1; + } + + /* Append the PATH_INFO, if any, to get the full URL. */ + + path_info = getenv("PATH_INFO"); + if (!path_info) + { + path_info = ""; + } + + g_url = (char*)malloc(strlen(script_name) + strlen(path_info) + 1); + if (!g_url) + { + internal_error("Out of memory."); + return 2; + } + (void)sprintf(g_url, "%s%s", script_name, path_info); + + /* Get the name of the file to parse. */ + + path_translated = getenv("PATH_TRANSLATED"); + if (!path_translated) + { + internal_error("Couldn't get PATH_TRANSLATED environment variable."); + err = 3; + goto errout_with_g_url; + } + + if (!check_filename(path_translated)) + { + not_permitted("initial", "PATH_TRANSLATED", path_translated); + err = 4; + goto errout_with_g_url; + } + + /* Open it. */ + + instream = fopen(path_translated, "r"); + if (!instream) + { + not_found(path_translated); + err = 5; + goto errout_with_g_url; + } + + /* Read and handle the file. */ + + read_file(instream, path_info, path_translated); + + (void)fclose(instream); + +errout_with_g_url: + free(g_url); + return err; +} diff --git a/apps/netutils/thttpd/config.h b/apps/netutils/thttpd/config.h new file mode 100644 index 000000000..f1b4c2d4c --- /dev/null +++ b/apps/netutils/thttpd/config.h @@ -0,0 +1,253 @@ +/**************************************************************************** + * netutils/thttpd/config.h + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_CONFIG_H +#define __NETUTILS_THTTPD_CONFIG_H + +/**************************************************************************** + * Included files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <nuttx/compiler.h> +#include <stdint.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* Make sure that the system is configured to handle THTTPD */ + +#undef CONFIG_THTTPD +#if defined(CONFIG_NET) && defined(CONFIG_NET_TCP) && \ + defined(CONFIG_NET_TCPBACKLOG) && !defined(CONFIG_DISABLE_ENVIRONMENT) && \ + !defined(CONFIG_SDCLONE_DISABLE) && CONFIG_NET_NTCP_READAHEAD_BUFFERS > 0 + +# define CONFIG_THTTPD 1 + +/* Check all THTTPD configuration settings. Complain on any that should have + * been defined but were not. Supply some kind of reasonable value for all + * undefined settings. + */ + +/* Server port number */ + +# ifndef CONFIG_THTTPD_PORT +# define CONFIG_THTTPD_PORT 80 +# endif + +/* Server IP address (no host name) */ + +# ifndef CONFIG_THTTPD_IPADDR +# ifdef CONFIG_CPP_HAVE_WARNING +# warning "CONFIG_THTTPD_IPADDR not defined" +# endif +# define CONFIG_THTTPD_IPADDR (10<<24|0<<16|0<<8|2) +# endif + +/* SERVER_ADDRESS: response */ + +# ifndef CONFIG_THTTPD_SERVER_ADDRESS +# define CONFIG_THTTPD_SERVER_ADDRESS "http://www.nuttx.org" +# endif + +/* SERVER_SOFTWARE: response */ + +# ifndef CONFIG_THTTPD_SERVER_SOFTWARE +# define CONFIG_THTTPD_SERVER_SOFTWARE "thttpd/2.25b 29dec2003-NuttX" +# endif + +# ifndef CONFIG_THTTPD_PATH +# ifdef CONFIG_CPP_HAVE_WARNING +# warning "CONFIG_THTTPD_PATH not defined" +# endif +# define CONFIG_THTTPD_PATH "/mnt/www" +# endif + +# ifndef CONFIG_THTTPD_CGI_PATH +# ifdef CONFIG_CPP_HAVE_WARNING +# warning "CONFIG_THTTPD_CGI_PATH not defined" +# endif +# define CONFIG_THTTPD_CGI_PATH "/mnt/www/cgi-bin" +# endif + +/* Only CGI programs whose fully expanded pathes match this pattern will be executed. In fact, + * if this value is not defined then no CGI logic will be built. + */ + +# ifndef CONFIG_THTTPD_CGI_PATTERN +# define CONFIG_THTTPD_CGI_PATTERN "/mnt/www/cgi-bin/*" +# endif + +/* These provide the priority and stack size of the CGI child tasks */ + +# ifndef CONFIG_THTTPD_CGI_PRIORITY +# define CONFIG_THTTPD_CGI_PRIORITY 50 +# endif + +# ifndef CONFIG_THTTPD_CGI_STACKSIZE +# define CONFIG_THTTPD_CGI_STACKSIZE 2048 +# endif + +/* Byte output limit for CGI tasks */ + +# ifndef CONFIG_THTTPD_CGI_BYTECOUNT +# define CONFIG_THTTPD_CGI_BYTECOUNT 200000 +# endif + +/* How many seconds to allow CGI programs to run before killing them. */ + +# ifndef CONFIG_THTTPD_CGI_TIMELIMIT +# define CONFIG_THTTPD_CGI_TIMELIMIT 0 /* No time limit */ +# endif + +/* The default character set name to use with text MIME types. */ + +# ifndef CONFIG_THTTPD_CHARSET +# define CONFIG_THTTPD_CHARSET "iso-8859-1" +# endif + +/* Initial buffer size, buffer reallocation increment, maximum buffer size */ + +# ifndef CONFIG_THTTPD_IOBUFFERSIZE +# define CONFIG_THTTPD_IOBUFFERSIZE 256 +# endif + +# ifndef CONFIG_THTTPD_MINSTRSIZE +# define CONFIG_THTTPD_MINSTRSIZE 64 +# endif + +# ifndef CONFIG_THTTPD_REALLOCINCR +# define CONFIG_THTTPD_REALLOCINCR 64 +# endif + +# ifndef CONFIG_THTTPD_MAXREALLOC +# define CONFIG_THTTPD_MAXREALLOC 4096 +# endif + +# ifndef CONFIG_THTTPD_CGIINBUFFERSIZE +# define CONFIG_THTTPD_CGIINBUFFERSIZE 512 /* Size of buffer to interpose input */ +# endif + +# ifndef CONFIG_THTTPD_CGIOUTBUFFERSIZE +# define CONFIG_THTTPD_CGIOUTBUFFERSIZE 512 /* Size of buffer to interpose output */ +# endif + +# if CONFIG_THTTPD_IOBUFFERSIZE > 65535 +# error "Can't use uint16_t for buffer size" +# endif + +/* A list of index filenames to check. The files are searched for in this order. */ + +# ifndef CONFIG_THTTPD_INDEX_NAMES +# define CONFIG_THTTPD_INDEX_NAMES "index.html", "index.htm", "index.cgi" +# endif + +/* CONFIG_AUTH_FILE - The file to use for authentication. If this is defined then + * thttpd checks for this file in the local directory before every fetch. If the + * file exists then authentication is done, otherwise the fetch proceeds as usual. + * If you leave this undefined then thttpd will not implement authentication at + * all and will not check for auth files, which saves a bit of CPU time. + * A typical value is ".htpasswd" + */ + +/* The listen() backlog queue length. */ + +# ifndef CONFIG_THTTPD_LISTEN_BACKLOG +# define CONFIG_THTTPD_LISTEN_BACKLOG 8 +# endif + +/* How many milliseconds to leave a connection open while doing a lingering close */ + +# ifndef CONFIG_THTTPD_LINGER_MSEC +# define CONFIG_THTTPD_LINGER_MSEC 500 +# endif + +/* How often to run the occasional cleanup job.*/ + +# ifndef CONFIG_THTTPD_OCCASIONAL_MSEC +# define CONFIG_THTTPD_OCCASIONAL_MSEC 120 /* Two minutes */ +# endif + +/* How many seconds to allow for reading the initial request on a new connection. */ + +# ifndef CONFIG_THTTPD_IDLE_READ_LIMIT_SEC +# define CONFIG_THTTPD_IDLE_READ_LIMIT_SEC 300 +# endif + +/* How many seconds before an idle connection gets closed. */ + +# ifndef CONFIG_THTTPD_IDLE_SEND_LIMIT_SEC +# define CONFIG_THTTPD_IDLE_SEND_LIMIT_SEC 300 +# endif + +/* Memory debug instrumentation depends on other debug options */ + +#if (!defined(CONFIG_DEBUG) || !defined(CONFIG_DEBUG_NET)) && defined(CONFIG_THTTPD_MEMDEBUG) +# undef CONFIG_THTTPD_MEMDEBUG +#endif + +/* Tilde mapping. Many URLs use ~username to indicate a user's home directory. thttpd + * provides two options for mapping this construct to an actual filename. + * + * 1) Map ~username to <prefix>/username. This is the recommended choice. Each user + * gets a subdirectory in the main web tree, and the tilde construct points there. + * The prefix could be something like "users", or it could be empty. + * 2) Map ~username to <user's homedir>/<postfix>. The postfix would be the name of + * a subdirectory off of the user's actual home dir, something like "public_html". + * + * You can also leave both options undefined, and thttpd will not do anything special + * about tildes. Enabling both options is an error. + * + * Typical values, if they're defined, are "users" for CONFIG_THTTPD_TILDE_MAP1 and "public_html" + * for CONFIG_THTTPD_TILDE_MAP2. + */ + +# if defined(CONFIG_THTTPD_TILDE_MAP1) && defined(CONFIG_THTTPD_TILDE_MAP2) +# error "Both CONFIG_THTTPD_TILDE_MAP1 andCONFIG_THTTPD_TILDE_MAP2 are defined" +# endif + +/* If CONFIG_THTTPD_URLPATTERN is defined, then it will be used to match and verify + * referrers. + */ + +#else /* Dependencies not provided */ +# ifdef CONFIG_CPP_HAVE_WARNING +# warning "THTTPD not built because dependencies not selected in configuration" +# endif +#endif /* Dependencies not provided */ + +#endif /* __NETUTILS_THTTPD_CONFIG_H */ + diff --git a/apps/netutils/thttpd/fdwatch.c b/apps/netutils/thttpd/fdwatch.c new file mode 100644 index 000000000..24ea7a1e0 --- /dev/null +++ b/apps/netutils/thttpd/fdwatch.c @@ -0,0 +1,371 @@ +/**************************************************************************** + * netutils/thttpd/timers.c + * FD watcher routines for poll() + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1999,2000 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdint.h> +#include <stdlib.h> +#include <debug.h> +#include <poll.h> +#include <debug.h> + +#include "config.h" +#include "thttpd_alloc.h" +#include "fdwatch.h" + +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Pre-Processor Definitions + ****************************************************************************/ + +/* Debug output from this file is normally suppressed. If enabled, be aware + * that output to stdout will interfere with CGI programs (you could use the + * the low-level debug (lldbg) functions which probably do not use stdout + */ + +#ifdef CONFIG_THTTPD_FDWATCH_DEBUG +# ifdef CONFIG_CPP_HAVE_VARARGS +# define fwdbg(format, arg...) ndbg(format, ##arg) +# define fwlldbg(format, arg...) nlldbg(format, ##arg) +# define fwvdbg(format, arg...) nvdbg(format, ##arg) +# define fwllvdbg(format, arg...) nllvdbg(format, ##arg) +# else +# define fwdbg ndbg +# define fwlldbg nlldbg +# define fwvdbg nvdbg +# define fwllvdbg nllvdbg +# endif +#else +# ifdef CONFIG_CPP_HAVE_VARARGS +# define fwdbg(x...) +# define fwlldbg(x...) +# define fwvdbg(x...) +# define fwllvdbg(x...) +# else +# define fwdbg (void) +# define fwlldbg (void) +# define fwvdbg (void) +# define fwllvdbg (void) +# endif +#endif + +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +#ifdef CONFIG_THTTPD_FDWATCH_DEBUG +static void fdwatch_dump(const char *msg, FAR struct fdwatch_s *fw) +{ + int i; + + fwvdbg("%s\n", msg); + fwvdbg("nwatched: %d nfds: %d\n", fw->nwatched, fw->nfds); + for (i = 0; i < fw->nwatched; i++) + { + fwvdbg("%2d. pollfds: {fd: %d events: %02x revents: %02x} client: %p\n", + i+1, fw->pollfds[i].fd, fw->pollfds[i].events, + fw->pollfds[i].revents, fw->client[i]); + } + fwvdbg("nactive: %d next: %d\n", fw->nactive, fw->next); + for (i = 0; i < fw->nactive; i++) + { + fwvdbg("%2d. %d active\n", i, fw->ready[i]); + } +} +#else +# define fdwatch_dump(m,f) +#endif + +static int fdwatch_pollndx(FAR struct fdwatch_s *fw, int fd) +{ + int pollndx; + + /* Get the index associated with the fd */ + + for (pollndx = 0; pollndx < fw->nwatched; pollndx++) + { + if (fw->pollfds[pollndx].fd == fd) + { + fwvdbg("pollndx: %d\n", pollndx); + return pollndx; + } + } + + fwdbg("No poll index for fd %d: %d\n", fd); + return -1; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/* Initialize the fdwatch data structures. Returns -1 on failure. */ + +struct fdwatch_s *fdwatch_initialize(int nfds) +{ + FAR struct fdwatch_s *fw; + + /* Allocate the fdwatch data structure */ + + fw = (struct fdwatch_s*)zalloc(sizeof(struct fdwatch_s)); + if (!fw) + { + fwdbg("Failed to allocate fdwatch\n"); + return NULL; + } + + /* Initialize the fdwatch data structures. */ + + fw->nfds = nfds; + + fw->client = (void**)httpd_malloc(sizeof(void*) * nfds); + if (!fw->client) + { + goto errout_with_allocations; + } + + fw->pollfds = (struct pollfd*)httpd_malloc(sizeof(struct pollfd) * nfds); + if (!fw->pollfds) + { + goto errout_with_allocations; + } + + fw->ready = (uint8_t*)httpd_malloc(sizeof(uint8_t) * nfds); + if (!fw->ready) + { + goto errout_with_allocations; + } + + fdwatch_dump("Initial state:", fw); + return fw; + +errout_with_allocations: + fdwatch_uninitialize(fw); + return NULL; +} + +/* Uninitialize the fwdatch data structure */ + +void fdwatch_uninitialize(struct fdwatch_s *fw) +{ + if (fw) + { + fdwatch_dump("Uninitializing:", fw); + if (fw->client) + { + httpd_free(fw->client); + } + + if (fw->pollfds) + { + httpd_free(fw->pollfds); + } + + if (fw->ready) + { + httpd_free(fw->ready); + } + + httpd_free(fw); + } +} + +/* Add a descriptor to the watch list. rw is either FDW_READ or FDW_WRITE. */ + +void fdwatch_add_fd(struct fdwatch_s *fw, int fd, void *client_data) +{ + fwvdbg("fd: %d client_data: %p\n", fd, client_data); + fdwatch_dump("Before adding:", fw); + + if (fw->nwatched >= fw->nfds) + { + fwdbg("too many fds\n"); + return; + } + + /* Save the new fd at the end of the list */ + + fw->pollfds[fw->nwatched].fd = fd; + fw->pollfds[fw->nwatched].events = POLLIN; + fw->client[fw->nwatched] = client_data; + + /* Increment the count of watched descriptors */ + + fw->nwatched++; + fdwatch_dump("After adding:", fw); +} + +/* Remove a descriptor from the watch list. */ + +void fdwatch_del_fd(struct fdwatch_s *fw, int fd) +{ + int pollndx; + + fwvdbg("fd: %d\n", fd); + fdwatch_dump("Before deleting:", fw); + + /* Get the index associated with the fd */ + + pollndx = fdwatch_pollndx(fw, fd); + if (pollndx >= 0) + { + /* Decrement the number of fds in the poll table */ + + fw->nwatched--; + + /* Replace the deleted one with the one at the the end + * of the list. + */ + + if (pollndx != fw->nwatched) + { + fw->pollfds[pollndx] = fw->pollfds[fw->nwatched]; + fw->client[pollndx] = fw->client[fw->nwatched]; + } + } + fdwatch_dump("After deleting:", fw); +} + +/* Do the watch. Return value is the number of descriptors that are ready, + * or 0 if the timeout expired, or -1 on errors. A timeout of INFTIM means + * wait indefinitely. + */ + +int fdwatch(struct fdwatch_s *fw, long timeout_msecs) +{ + int ret; + int i; + + /* Wait for activity on any of the desciptors. When poll() returns, ret + * will hold the number of descriptors with activity (or zero on a timeout + * or <0 on an error. + */ + + fdwatch_dump("Before waiting:", fw); + fwvdbg("Waiting... (timeout %d)\n", timeout_msecs); + fw->nactive = 0; + fw->next = 0; + ret = poll(fw->pollfds, fw->nwatched, (int)timeout_msecs); + fwvdbg("Awakened: %d\n", ret); + + /* Look through all of the descriptors and make a list of all of them than + * have activity. + */ + + if (ret > 0) + { + for (i = 0; i < fw->nwatched; i++) + { + /* Is there activity on this descriptor? */ + + if (fw->pollfds[i].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL)) + { + /* Yes... save it in a shorter list */ + + fwvdbg("pollndx: %d fd: %d revents: %04x\n", + i, fw->pollfds[i].fd, fw->pollfds[i].revents); + + fw->ready[fw->nactive++] = fw->pollfds[i].fd; + if (fw->nactive == ret) + { + /* We have all of them, break out early */ + + break; + } + } + } + } + + /* Return the number of descriptors with activity */ + + fwvdbg("nactive: %d\n", fw->nactive); + fdwatch_dump("After wakeup:", fw); + return ret; +} + +/* Check if a descriptor was ready. */ + +int fdwatch_check_fd(struct fdwatch_s *fw, int fd) +{ + int pollndx; + + fwvdbg("fd: %d\n", fd); + fdwatch_dump("Checking:", fw); + + /* Get the index associated with the fd */ + + pollndx = fdwatch_pollndx(fw, fd); + if (pollndx >= 0 && (fw->pollfds[pollndx].revents & POLLERR) == 0) + { + return fw->pollfds[pollndx].revents & (POLLIN | POLLHUP | POLLNVAL); + } + + fwvdbg("POLLERR fd: %d\n", fd); + return 0; +} + +void *fdwatch_get_next_client_data(struct fdwatch_s *fw) +{ + fdwatch_dump("Before getting client data:", fw); + if (fw->next >= fw->nwatched) + { + fwvdbg("All client data returned: %d\n", fw->next); + return (void*)-1; + } + + fwvdbg("client_data[%d]: %p\n", fw->next, fw->client[fw->next]); + return fw->client[fw->next++]; +} + +#endif /* CONFIG_THTTPD */ + diff --git a/apps/netutils/thttpd/fdwatch.h b/apps/netutils/thttpd/fdwatch.h new file mode 100644 index 000000000..e60727db1 --- /dev/null +++ b/apps/netutils/thttpd/fdwatch.h @@ -0,0 +1,111 @@ +/**************************************************************************** + * netutils/thttpd/fdwatch.h + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in THTTPD: + * + * Copyright © 1999 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_FDWATCH_H +#define __NETUTILS_THTTPD_FDWATCH_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <stdint.h> + +/**************************************************************************** + * Pre-Processor Definitions + ****************************************************************************/ + +/* Define to enable detailed FDWATCH debug output */ + +#undef CONFIG_THTTPD_FDWATCH_DEBUG + +#ifndef INFTIM +# define INFTIM -1 +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct fdwatch_s +{ + struct pollfd *pollfds; /* Poll data (allocated) */ + void **client; /* Client data (allocated) */ + uint8_t *ready; /* The list of fds with activity (allocated) */ + uint8_t nfds; /* The configured maximum number of fds */ + uint8_t nwatched; /* The number of fds currently watched */ + uint8_t nactive; /* The number of fds with activity */ + uint8_t next; /* The index to the next client data */ +}; + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/* Initialize the fdwatch data structures. Returns NULL on failure. */ + +extern struct fdwatch_s *fdwatch_initialize(int nfds); + +/* Uninitialize the fwdatch data structure */ + +extern void fdwatch_uninitialize(struct fdwatch_s *fw); + +/* Add a descriptor to the watch list */ + +extern void fdwatch_add_fd(struct fdwatch_s *fw, int fd, void *client_data); + +/* Delete a descriptor from the watch list. */ + +extern void fdwatch_del_fd(struct fdwatch_s *fw, int fd); + +/* Do the watch. Return value is the number of descriptors that are ready, + * or 0 if the timeout expired, or -1 on errors. A timeout of INFTIM means + * wait indefinitely. + */ + +extern int fdwatch(struct fdwatch_s *fw, long timeout_msecs); + +/* Check if a descriptor was ready. */ + +extern int fdwatch_check_fd(struct fdwatch_s *fw, int fd); + +/* Get the client data for the next returned event. Returns -1 when there + * are no more events. + */ + +extern void *fdwatch_get_next_client_data(struct fdwatch_s *fw); + +#endif /* __NETUTILS_THTTPD_FDWATCH_H */ + diff --git a/apps/netutils/thttpd/libhttpd.c b/apps/netutils/thttpd/libhttpd.c new file mode 100644 index 000000000..05831b335 --- /dev/null +++ b/apps/netutils/thttpd/libhttpd.c @@ -0,0 +1,3525 @@ +/**************************************************************************** + * netutils/thttpd/libhttpd.c + * HTTP Protocol Library + * + * Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/time.h> +#include <stdint.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <stdarg.h> +#include <ctype.h> +#include <fcntl.h> +#include <dirent.h> +#include <signal.h> +#include <sched.h> +#include <errno.h> +#include <debug.h> + +#include <nuttx/regex.h> +#include <apps/netutils/thttpd.h> + +#include "config.h" +#include "libhttpd.h" +#include "thttpd_alloc.h" +#include "thttpd_strings.h" +#include "thttpd_cgi.h" +#include "timers.h" +#include "tdate_parse.h" +#include "fdwatch.h" + +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifndef STDIN_FILENO +# define STDIN_FILENO 0 +#endif +#ifndef STDOUT_FILENO +# define STDOUT_FILENO 1 +#endif +#ifndef STDERR_FILENO +# define STDERR_FILENO 2 +#endif + +#define NAMLEN(dirent) strlen((dirent)->d_name) + +extern char *crypt(const char *key, const char *setting); + +#ifndef MAX +# define MAX(a,b) ((a) > (b) ? (a) : (b)) +#endif + +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/* Conditional macro to allow two alternate forms for use in the built-in + * error pages. If EXPLICIT_ERROR_PAGES is defined, the second and more + * explicit error form is used; otherwise, the first and more generic + * form is used. + */ + +#ifdef EXPLICIT_ERROR_PAGES +# define ERROR_FORM(a,b) b +#else +# define ERROR_FORM(a,b) a +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void free_httpd_server(httpd_server *hs); +static int initialize_listen_socket(httpd_sockaddr *saP); +static void add_response(httpd_conn *hc, const char *str); +static void send_mime(httpd_conn *hc, int status, const char *title, const char *encodings, + const char *extraheads, const char *type, off_t length, time_t mod); +static void send_response(httpd_conn *hc, int status, const char *title, + const char *extraheads, const char *form, const char *arg); +static void send_response_tail(httpd_conn *hc); +static void defang(const char *str, char *dfstr, int dfsize); +#ifdef CONFIG_THTTPD_ERROR_DIRECTORY +static int send_err_file(httpd_conn *hc, int status, char *title, + char *extraheads, char *filename); +#endif +#ifdef CONFIG_THTTPD_AUTH_FILE +static void send_authenticate(httpd_conn *hc, char *realm); +static int b64_decode(const char *str, unsigned char *space, int size); +static int auth_check(httpd_conn *hc, char *dirname); +static int auth_check2(httpd_conn *hc, char *dirname); +#endif +static void send_dirredirect(httpd_conn *hc); +#ifdef CONFIG_THTTPD_TILDE_MAP1 +static int httpd_tilde_map1(httpd_conn *hc); +#endif +#ifdef CONFIG_THTTPD_TILDE_MAP2 +static int httpd_tilde_map2(httpd_conn *hc); +#endif +#ifdef CONFIG_THTTPD_VHOST +static int vhost_map(httpd_conn *hc); +#endif +static char *expand_filename(char *path, char **restP, bool tildemapped); +static char *bufgets(httpd_conn *hc); +static void de_dotdot(char *file); +static void init_mime(void); +static void figure_mime(httpd_conn *hc); +#ifdef CONFIG_THTTPD_GENERATE_INDICES +static void ls_child(int argc, char **argv); +static int ls(httpd_conn *hc); +#endif +#ifdef SERVER_NAME_LIST +static char *hostname_map(char *hostname); +#endif + +static int check_referer(httpd_conn *hc); +#ifdef CONFIG_THTTPD_URLPATTERN +static int really_check_referer(httpd_conn *hc); +#endif +#ifdef CONFIG_DEBUG +static int sockaddr_check(httpd_sockaddr *saP); +#else +# define sockaddr_check(saP) (1) +#endif +static size_t sockaddr_len(httpd_sockaddr *saP); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* This global keeps track of whether we are in the main task or a + * sub-task. The reason is that httpd_write_response() can get called + * in either context; when it is called from the main task it must use + * non-blocking I/O to avoid stalling the server, but when it is called + * from a sub-task it wants to use blocking I/O so that the whole + * response definitely gets written. So, it checks this variable. A bit + * of a hack but it seems to do the right thing. + */ + +static pid_t main_thread; + +/* Include MIME encodings and types */ + +#include "mime_types.h" + +/* Names for index file */ + +static const char *index_names[] = { CONFIG_THTTPD_INDEX_NAMES }; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void free_httpd_server(httpd_server * hs) +{ + if (hs) + { + if (hs->hostname) + { + httpd_free(hs->hostname); + } + + httpd_free(hs); + } +} + +static int initialize_listen_socket(httpd_sockaddr *saP) +{ + int listen_fd; + int on; + int flags; + + /* Check sockaddr. */ + +#ifdef CONFIG_DEBUG + if (!sockaddr_check(saP)) + { + ndbg("unknown sockaddr family on listen socket\n"); + return -1; + } +#endif + + /* Create socket. */ + + nvdbg("Create listen socket\n"); + listen_fd = socket(saP->sin_family, SOCK_STREAM, 0); + if (listen_fd < 0) + { + ndbg("socket failed: %d\n", errno); + return -1; + } + + /* Allow reuse of local addresses. */ + + on = 1; + if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) + { + ndbg("setsockopt(SO_REUSEADDR) failed: %d\n", errno); + } + + /* Bind to it. */ + + if (bind(listen_fd, (struct sockaddr*)saP, sockaddr_len(saP)) < 0) + { + ndbg("bind to %s failed: %d\n", httpd_ntoa(saP), errno); + (void)close(listen_fd); + return -1; + } + + /* Set the listen file descriptor to no-delay / non-blocking mode. */ + + flags = fcntl(listen_fd, F_GETFL, 0); + if (flags == -1) + { + ndbg("fcntl(F_GETFL) failed: %d\n", errno); + (void)close(listen_fd); + return -1; + } + + if (fcntl(listen_fd, F_SETFL, flags | O_NDELAY) < 0) + { + ndbg("fcntl(O_NDELAY) failed: %d\n", errno); + (void)close(listen_fd); + return -1; + } + + /* Start a listen going. */ + + if (listen(listen_fd, CONFIG_THTTPD_LISTEN_BACKLOG) < 0) + { + ndbg("listen failed: %d\n", errno); + (void)close(listen_fd); + return -1; + } + + return listen_fd; +} + +/* Append a string to the buffer waiting to be sent as response. */ + +static void add_response(httpd_conn *hc, const char *str) +{ + int resplen; + int len; + + len = strlen(str); + resplen = hc->buflen + len; + + if (resplen > CONFIG_THTTPD_IOBUFFERSIZE) + { + ndbg("resplen(%d) > buffer size(%d)\n", resplen, CONFIG_THTTPD_IOBUFFERSIZE); + resplen = CONFIG_THTTPD_IOBUFFERSIZE; + len = resplen - hc->buflen; + } + + memcpy(&(hc->buffer[hc->buflen]), str, len); + hc->buflen = resplen; +} + +static void send_mime(httpd_conn *hc, int status, const char *title, const char *encodings, + const char *extraheads, const char *type, off_t length, time_t mod) +{ + struct timeval now; + const char *rfc1123fmt = "%a, %d %b %Y %H:%M:%S GMT"; + char tmbuf[72]; +#ifdef CONFIG_THTTPD_MAXAGE + time_t expires; + char expbuf[72]; +#endif + char fixed_type[72]; + char buf[128]; + int partial_content; + int s100; + + hc->bytes_to_send = length; + if (hc->mime_flag) + { + if (status == 200 && hc->got_range && + (hc->range_end >= hc->range_start) && + ((hc->range_end != length - 1) || + (hc->range_start != 0)) && + (hc->range_if == (time_t) - 1 || hc->range_if == hc->sb.st_mtime)) + { + partial_content = 1; + status = 206; + title = ok206title; + } + else + { + partial_content = 0; + hc->got_range = false; + } + + gettimeofday(&now, NULL); + if (mod == (time_t)0) + { + mod = now.tv_sec; + } + + (void)snprintf(fixed_type, sizeof(fixed_type), type, CONFIG_THTTPD_CHARSET); + (void)snprintf(buf, sizeof(buf), "%.20s %d %s\r\n", hc->protocol, status, title); + add_response(hc, buf); + (void)snprintf(buf, sizeof(buf), "Server: %s\r\n", "thttpd"); + add_response(hc, buf); + (void)snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", fixed_type); + add_response(hc, buf); + (void)strftime(tmbuf, sizeof(tmbuf), rfc1123fmt, gmtime(&now.tv_sec)); + (void)snprintf(buf, sizeof(buf), "Date: %s\r\n", tmbuf); + add_response(hc, buf); + (void)strftime(tmbuf, sizeof(tmbuf), rfc1123fmt, gmtime(&mod)); + (void)snprintf(buf, sizeof(buf), "Last-Modified: %s\r\n", tmbuf); + add_response(hc, buf); + add_response(hc, "Accept-Ranges: bytes\r\n"); + add_response(hc, "Connection: close\r\n"); + + s100 = status / 100; + if (s100 != 2 && s100 != 3) + { + (void)snprintf(buf, sizeof(buf), "Cache-Control: no-cache,no-store\r\n"); + add_response(hc, buf); + } + + if (encodings[0] != '\0') + { + (void)snprintf(buf, sizeof(buf), "Content-Encoding: %s\r\n", encodings); + add_response(hc, buf); + } + + if (partial_content) + { + (void)snprintf(buf, sizeof(buf),"Content-Range: bytes %ld-%ld/%ld\r\n", + (long)hc->range_start, (long)hc->range_end, (long)length); + add_response(hc, buf); + (void)snprintf(buf, sizeof(buf),"Content-Length: %ld\r\n", + (long)(hc->range_end - hc->range_start + 1)); + add_response(hc, buf); + } + else if (length >= 0) + { + (void)snprintf(buf, sizeof(buf), "Content-Length: %ld\r\n", (long)length); + add_response(hc, buf); + } + +#ifdef CONFIG_THTTPD_P3P + (void)snprintf(buf, sizeof(buf), "P3P: %s\r\n", CONFIG_THTTPD_P3P); + add_response(hc, buf); +#endif + +#ifdef CONFIG_THTTPD_MAXAGE + expires = now + CONFIG_THTTPD_MAXAGE; + (void)strftime(expbuf, sizeof(expbuf), rfc1123fmt, gmtime(&expires)); + (void)snprintf(buf, sizeof(buf), + "Cache-Control: max-age=%d\r\nExpires: %s\r\n", + CONFIG_THTTPD_MAXAGE, expbuf); + add_response(hc, buf); +#endif + + if (extraheads[0] != '\0') + { + add_response(hc, extraheads); + } + add_response(hc, "\r\n"); + } +} + +static void send_response(httpd_conn *hc, int status, const char *title, const char *extraheads, + const char *form, const char *arg) +{ + char defanged[72]; + char buf[128]; + + nvdbg("title: \"%s\" form: \"%s\"\n", title, form); + + send_mime(hc, status, title, "", extraheads, "text/html; charset=%s", (off_t)-1, (time_t)0); + add_response(hc, html_html); + add_response(hc, html_hdtitle); + (void)snprintf(buf, sizeof(buf), "%d %s", status, title); + add_response(hc, buf); + add_response(hc, html_titlehd); + add_response(hc, html_body); + add_response(hc, html_hdr2); + add_response(hc, buf); + add_response(hc, html_endhdr2); + + defang(arg, defanged, sizeof(defanged)); + (void)snprintf(buf, sizeof(buf), form, defanged); + add_response(hc, buf); + + if (match("**MSIE**", hc->useragent)) + { + int n; + add_response(hc, "<!--\n"); + for (n = 0; n < 6; ++n) + add_response(hc, + "Padding so that MSIE deigns to show this error instead of its own canned one.\n"); + add_response(hc, "-->\n"); + } + + send_response_tail(hc); +} + +static void send_response_tail(httpd_conn *hc) +{ + add_response(hc, "<HR>\r\n<ADDRESS><A HREF=\""); + add_response(hc, CONFIG_THTTPD_SERVER_ADDRESS); + add_response(hc, "\">"); + add_response(hc, "thttpd"); + add_response(hc, "</A></ADDRESS>\r\n"); + add_response(hc, html_endbody); + add_response(hc, html_endhtml); +} + +static void defang(const char *str, char *dfstr, int dfsize) +{ + const char *cp1; + char *cp2; + + for (cp1 = str, cp2 = dfstr; + *cp1 != '\0' && cp2 - dfstr < dfsize - 5; ++cp1, ++cp2) + { + switch (*cp1) + { + case '<': + *cp2++ = '&'; + *cp2++ = 'l'; + *cp2++ = 't'; + *cp2 = ';'; + break; + case '>': + *cp2++ = '&'; + *cp2++ = 'g'; + *cp2++ = 't'; + *cp2 = ';'; + break; + default: + *cp2 = *cp1; + break; + } + } + *cp2 = '\0'; +} + +#ifdef CONFIG_THTTPD_ERROR_DIRECTORY +static int send_err_file(httpd_conn *hc, int status, char *title, char *extraheads, + char *filename) +{ + FILE *fp; + char buf[1000]; + size_t nread; + + fp = fopen(filename, "r"); + if (fp == NULL) + { + return 0; + } + + send_mime(hc, status, title, "", extraheads, "text/html; charset=%s", + (off_t)-1, (time_t)0); + for (;;) + { + nread = fread(buf, 1, sizeof(buf) - 1, fp); + if (nread == 0) + break; + buf[nread] = '\0'; + add_response(hc, buf); + } + (void)fclose(fp); + +#ifdef ERR_APPEND_SERVER_INFO + send_response_tail(hc); +#endif + + return 1; +} +#endif + +#ifdef CONFIG_THTTPD_AUTH_FILE +static void send_authenticate(httpd_conn *hc, char *realm) +{ + static char *header; + static size_t maxheader = 0; + static char headstr[] = "WWW-Authenticate: Basic realm=\""; + + httpd_realloc_str(&header, &maxheader, sizeof(headstr) + strlen(realm) + 3); + (void)snprintf(header, maxheader, "%s%s\"\r\n", headstr, realm); + httpd_send_err(hc, 401, err401title, header, err401form, hc->encodedurl); + + /* If the request was a POST then there might still be data to be read, so + * we need to do a lingering close. + */ + + if (hc->method == METHOD_POST) + { + hc->should_linger = true; + } +} + +/* Base-64 decoding. This represents binary data as printable ASCII + * characters. Three 8-bit binary bytes are turned into four 6-bit + * values, like so: + * + * [11111111][22222222][33333333] -> [111111][112222][222233][333333] + * + * Then the 6-bit values are represented using the characters "A-Za-z0-9+/". + */ + +static inline b64_charmap(char *ch) +{ + char bin6; + + bin6 = -1; + if (c == 0x20) /* ' ' */ + { + bin6 = 62; /* ' ' maps to 62 */ + } + elseif (c == 0x2f) /* '/' */ + { + bin6 = 63; /* '/' maps to 63 */ + } + else if (c >= 0x30) /* '0' */ + { + else if (c <= 0x39) /* '9' */ + { + bin6 = (c - 0x39 + 52); /* '0'-'9' maps to 52-61 */ + } + else if (c >= 0x41) /* 'A' */ + { + if (c <= 0x5a) /* 'Z' */ + { + bin6 = c - 0x41; /* 'A'-'Z' map to 0 - 25 */ + } + else if (c >= 0x61) /* 'a' */ + { + if (c <= 0x7a) /* 'z' */ + { + bin6 = c - 0x61 + 26; /* 'a'-'z' map to 0 - 25 */ + } + } + } + } + +} + +/* Do base-64 decoding on a string. Ignore any non-base64 bytes. + * Return the actual number of bytes generated. The decoded size will + * be at most 3/4 the size of the encoded, and may be smaller if there + * are padding characters (blanks, newlines). + */ + +static int b64_decode(const char *str, unsigned char *space, int size) +{ + const char *cp; + int ndx; + int phase; + int decoded; + int prev_decoded = 0; + unsigned char packed; + + ndx = 0; + phase = 0; + for (cp = str; *cp != '\0', ndx < size; cp++) + { + /* Decode base-64 */ + + decoded = b64_charmap(*cp); /* Decode ASCII representations to 6-bit binary */ + if (decoded != -1) + { + switch (phase) + { + case 0: + phase = 1; + break; + + case 1: + space[ndx++] = ((prev_decoded << 2) | ((decoded & 0x30) >> 4)); + phase = 2; + break; + + case 2: + space[ndx++] =(((prev_decoded & 0xf) << 4) | ((decoded & 0x3packed) >> 2)); + phase = 3; + break; + + case 3: + space[ndx++] =(((prev_decoded & 0x03) << 6) | decoded); + phase = 0; + break; + } + prev_decoded = decoded; + } + } + return ndx; +} + +/* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */ + +static int auth_check(httpd_conn *hc, char *dirname) +{ +#ifdef CONFIG_THTTPD_GLOBALPASSWD + char *topdir; + +#ifdef CONFIG_THTTPD_VHOST + if (hc->hostdir[0] != '\0') + { + topdir = hc->hostdir; + } + else +#endif + { + topdir = httpd_root; + } + + switch (auth_check2(hc, topdir)) + { + case -1: + return -1; + case 1: + return 1; + } +#endif + return auth_check2(hc, dirname); +} + +/* Returns -1 == unauthorized, 0 == no auth file, 1 = authorized. */ + +static int auth_check2(httpd_conn *hc, char *dirname) +{ + static char *authpath; + static size_t maxauthpath = 0; + struct stat sb; + char authinfo[500]; + char *authpass; + char *colon; + int l; + FILE *fp; + char line[500]; + char *cryp; + static char *prevauthpath; + static size_t maxprevauthpath = 0; + static time_t prevmtime; + static char *prevuser; + static size_t maxprevuser = 0; + static char *prevcryp; + static size_t maxprevcryp = 0; + + /* Construct auth filename. */ + + httpd_realloc_str(&authpath, &maxauthpath, + strlen(dirname) + 1 + sizeof(CONFIG_THTTPD_AUTH_FILE)); + (void)snprintf(authpath, maxauthpath, "%s/%s", dirname, CONFIG_THTTPD_AUTH_FILE); + + /* Does this directory have an auth file? */ + + if (stat(authpath, &sb) < 0) + { + /* Nope, let the request go through. */ + + return 0; + } + + /* Does this request contain basic authorization info? */ + + if (hc->authorization[0] == '\0' || strncmp(hc->authorization, "Basic ", 6) != 0) + { + /* Nope, return a 401 Unauthorized. */ + + send_authenticate(hc, dirname); + return -1; + } + + /* Decode it. */ + + l = b64_decode(&(hc->authorization[6]), (unsigned char *)authinfo, sizeof(authinfo) - 1); + authinfo[l] = '\0'; + + /* Split into user and password. */ + + authpass = strchr(authinfo, ':'); + if (!authpass) + { + /* No colon? Bogus auth info. */ + + send_authenticate(hc, dirname); + return -1; + } + *authpass++ = '\0'; + + /* If there are more fields, cut them off. */ + + colon = strchr(authpass, ':'); + if (colon) + { + *colon = '\0'; + } + + /* See if we have a cached entry and can use it. */ + + if (maxprevauthpath != 0 && + strcmp(authpath, prevauthpath) == 0 && + sb.st_mtime == prevmtime && strcmp(authinfo, prevuser) == 0) + { + /* Yes. Check against the cached encrypted password. */ + + if (strcmp(crypt(authpass, prevcryp), prevcryp) == 0) + { + /* Ok! */ + + httpd_realloc_str(&hc->remoteuser, &hc->maxremoteuser, + strlen(authinfo)); + (void)strcpy(hc->remoteuser, authinfo); + return 1; + } + else + { + /* No. */ + + send_authenticate(hc, dirname); + return -1; + } + } + + /* Open the password file. */ + + fp = fopen(authpath, "r"); + if (fp == NULL) + { + /* The file exists but we can't open it? Disallow access. */ + + ndbg("%s auth file %s could not be opened: %d\n", + httpd_ntoa(&hc->client_addr), authpath, errno); + + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' is protected by an authentication file, " + "but the authentication file cannot be opened.\n"), + hc->encodedurl); + return -1; + } + + /* Read it. */ + + while (fgets(line, sizeof(line), fp) != NULL) + { + /* Nuke newline. */ + + l = strlen(line); + if (line[l - 1] == '\n') + { + line[l - 1] = '\0'; + } + + /* Split into user and encrypted password. */ + + cryp = strchr(line, ':'); + if (!cryp) + { + continue; + } + *cryp++ = '\0'; + + /* Is this the right user? */ + + if (strcmp(line, authinfo) == 0) + { + /* Yes. */ + + (void)fclose(fp); + + /* So is the password right? */ + + if (strcmp(crypt(authpass, cryp), cryp) == 0) + { + /* Ok! */ + + httpd_realloc_str(&hc->remoteuser, &hc->maxremoteuser, strlen(line)); + (void)strcpy(hc->remoteuser, line); + + /* And cache this user's info for next time. */ + + httpd_realloc_str(&prevauthpath, &maxprevauthpath, strlen(authpath)); + (void)strcpy(prevauthpath, authpath); + prevmtime = sb.st_mtime; + httpd_realloc_str(&prevuser, &maxprevuser, strlen(authinfo)); + (void)strcpy(prevuser, authinfo); + httpd_realloc_str(&prevcryp, &maxprevcryp, strlen(cryp)); + (void)strcpy(prevcryp, cryp); + return 1; + } + else + { + /* No. */ + + send_authenticate(hc, dirname); + return -1; + } + } + } + + /* Didn't find that user. Access denied. */ + + (void)fclose(fp); + send_authenticate(hc, dirname); + return -1; +} +#endif /* CONFIG_THTTPD_AUTH_FILE */ + +static void send_dirredirect(httpd_conn *hc) +{ + static char *location; + static char *header; + static size_t maxlocation = 0; + static size_t maxheader = 0; + static char headstr[] = "Location: "; + + if (hc->query[0] != '\0') + { + char *cp = strchr(hc->encodedurl, '?'); + if (cp) + { + *cp = '\0'; + } + + httpd_realloc_str(&location, &maxlocation, strlen(hc->encodedurl) + 2 + strlen(hc->query)); + (void)snprintf(location, maxlocation, "%s/?%s", hc->encodedurl, hc->query); + } + else + { + httpd_realloc_str(&location, &maxlocation, strlen(hc->encodedurl) + 1); + (void)snprintf(location, maxlocation, "%s/", hc->encodedurl); + } + + httpd_realloc_str(&header, &maxheader, sizeof(headstr) + strlen(location)); + (void)snprintf(header, maxheader, "%s%s\r\n", headstr, location); + send_response(hc, 302, err302title, header, err302form, location); +} + +/* Map a ~username/whatever URL into <prefix>/username. */ + +#ifdef CONFIG_THTTPD_TILDE_MAP1 +static int httpd_tilde_map1(httpd_conn *hc) +{ + static char *temp; + static size_t maxtemp = 0; + int len; + static char *prefix = CONFIG_THTTPD_TILDE_MAP1; + + len = strlen(hc->expnfilename) - 1; + httpd_realloc_str(&temp, &maxtemp, len); + (void)strcpy(temp, &hc->expnfilename[1]); + + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, strlen(prefix) + 1 + len); + (void)strcpy(hc->expnfilename, prefix); + + if (prefix[0] != '\0') + { + (void)strcat(hc->expnfilename, "/"); + } + + (void)strcat(hc->expnfilename, temp); + return 1; +} +#endif + +/* Map a ~username/whatever URL into <user's homedir>/<postfix>. */ + +#ifdef CONFIG_THTTPD_TILDE_MAP2 +static int httpd_tilde_map2(httpd_conn *hc) +{ + static char *temp; + static size_t maxtemp = 0; + static char *postfix = CONFIG_THTTPD_TILDE_MAP2; + char *cp; + struct passwd *pw; + char *alt; + char *rest; + + /* Get the username. */ + + httpd_realloc_str(&temp, &maxtemp, strlen(hc->expnfilename) - 1); + (void)strcpy(temp, &hc->expnfilename[1]); + + cp = strchr(temp, '/'); + if (cp) + { + *cp++ = '\0'; + } + else + { + cp = ""; + } + + /* Get the passwd entry. */ + + pw = getpwnam(temp); + if (!pw) + { + return 0; + } + + /* Set up altdir. */ + + httpd_realloc_str(&hc->altdir, &hc->maxaltdir, strlen(pw->pw_dir) + 1 + strlen(postfix)); + (void)strcpy(hc->altdir, pw->pw_dir); + if (postfix[0] != '\0') + { + (void)strcat(hc->altdir, "/"); + (void)strcat(hc->altdir, postfix); + } + + alt = expand_filename(hc->altdir, &rest, true); + if (rest[0] != '\0') + { + return 0; + } + + httpd_realloc_str(&hc->altdir, &hc->maxaltdir, strlen(alt)); + (void)strcpy(hc->altdir, alt); + + /* And the filename becomes altdir plus the post-~ part of the original. */ + + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, strlen(hc->altdir) + 1 + strlen(cp)); + (void)snprintf(hc->expnfilename, hc->maxexpnfilename, "%s/%s", hc->altdir, cp); + + /* For this type of tilde mapping, we want to defeat vhost mapping. */ + + hc->tildemapped = true; + return 1; +} +#endif + +/* Virtual host mapping. */ + +#ifdef CONFIG_THTTPD_VHOST +static int vhost_map(httpd_conn *hc) +{ + httpd_sockaddr sa; + socklen_t sz; + static char *tempfilename; + static size_t maxtempfilename = 0; + char *cp1; + int len; +#ifdef VHOST_DIRLEVELS + int i; + char *cp2; +#endif + + /* Figure out the virtual hostname. */ + + if (hc->reqhost[0] != '\0') + { + hc->vhostname = hc->reqhost; + } + else if (hc->hdrhost[0] != '\0') + { + hc->vhostname = hc->hdrhost; + } + else + { + sz = sizeof(sa); + if (getsockname(hc->conn_fd, &sa.sa, &sz) < 0) + { + ndbg("getsockname: %d\n", errno); + return 0; + } + hc->vhostname = httpd_ntoa(&sa); + } + + /* Pound it to lower case. */ + + for (cp1 = hc->vhostname; *cp1 != '\0'; ++cp1) + { + if (isupper(*cp1)) + { + *cp1 = tolower(*cp1); + } + } + + if (hc->tildemapped) + { + return 1; + } + + /* Figure out the host directory. */ + +#ifdef VHOST_DIRLEVELS + httpd_realloc_str(&hc->hostdir, &hc->maxhostdir, strlen(hc->vhostname) + 2 * VHOST_DIRLEVELS); + if (strncmp(hc->vhostname, "www.", 4) == 0) + { + cp1 = &hc->vhostname[4]; + } + else + { + cp1 = hc->vhostname; + } + + for (cp2 = hc->hostdir, i = 0; i < VHOST_DIRLEVELS; ++i) + { + /* Skip dots in the hostname. If we don't, then we get vhost + * directories in higher level of filestructure if dot gets involved + * into path construction. It's `while' used here instead of `if' for + * it's possible to have a hostname formed with two dots at the end of + * it. + */ + + while (*cp1 == '.') + { + ++cp1; + } + + /* Copy a character from the hostname, or '_' if we ran out. */ + + if (*cp1 != '\0') + { + *cp2++ = *cp1++; + } + else + { + *cp2++ = '_'; + } + + /* Copy a slash. */ + + *cp2++ = '/'; + } + (void)strcpy(cp2, hc->vhostname); +#else /* VHOST_DIRLEVELS */ + httpd_realloc_str(&hc->hostdir, &hc->maxhostdir, strlen(hc->vhostname)); + (void)strcpy(hc->hostdir, hc->vhostname); +#endif /* VHOST_DIRLEVELS */ + + /* Prepend hostdir to the filename. */ + + len = strlen(hc->expnfilename); + httpd_realloc_str(&tempfilename, &maxtempfilename, len); + (void)strcpy(tempfilename, hc->expnfilename); + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, strlen(hc->hostdir) + 1 + len); + (void)strcpy(hc->expnfilename, hc->hostdir); + (void)strcat(hc->expnfilename, "/"); + (void)strcat(hc->expnfilename, tempfilename); + return 1; +} +#endif + +/* Expands filename, deleting ..'s and leading /'s. + * Returns the expanded path (pointer to static string), or NULL on + * errors. Also returns, in the string pointed to by restP, any trailing + * parts of the path that don't exist. + */ + +static char *expand_filename(char *path, char **restP, bool tildemapped) +{ + static char *checked; + static char *rest; + static size_t maxchecked = 0, maxrest = 0; + size_t checkedlen, restlen, prevcheckedlen, prevrestlen; +#if 0 // REVISIT + struct stat sb; +#endif + int nlinks, i; + char *r; + char *cp1; + char *cp2; + + nvdbg("path: \"%s\"\n", path); +#if 0 // REVISIT + /* We need to do the pathinfo check. we do a single stat() of the whole + * filename - if it exists, then we return it as is with nothing in restP. + * If it doesn't exist, we fall through to the existing code. + */ + + if (stat(path, &sb) != -1) + { + checkedlen = strlen(path); + httpd_realloc_str(&checked, &maxchecked, checkedlen); + (void)strcpy(checked, path); + + /* Trim trailing slashes. */ + + while (checked[checkedlen - 1] == '/') + { + checked[checkedlen - 1] = '\0'; + --checkedlen; + } + + httpd_realloc_str(&rest, &maxrest, 0); + rest[0] = '\0'; + *restP = rest; + return checked; + } +#endif + + /* Handle leading / or . and relative pathes by copying the default directory into checked */ + + if ((path[0] == '/' && strncmp(path, httpd_root, strlen(httpd_root)) != 0) || path[0] != '/') + { + /* Start out with httpd_root in checked. Allow space in the reallocation + * include NULL terminator and possibly a '/' + */ + + checkedlen = strlen(httpd_root); + httpd_realloc_str(&checked, &maxchecked, checkedlen+2); + strcpy(checked, httpd_root); + + /* Skip over leading '.' */ + + if (path[0] == '.') + { + path++; + } + + /* Add '/' to separate relative pathes */ + + else if (path[0] != '/') + { + checked[checkedlen] = '/'; + checked[checkedlen+1] = '\0'; + } + } + else + { + /* Start out with nothing in checked */ + + httpd_realloc_str(&checked, &maxchecked, 1); + checked[0] = '\0'; + checkedlen = 0; + } + + /* Copy the whole filename (minus the leading '.') into rest. */ + + restlen = strlen(path); + httpd_realloc_str(&rest, &maxrest, restlen+1); + (void)strcpy(rest, path); + + /* trim trailing slash */ + + if (rest[restlen - 1] == '/') + { + rest[--restlen] = '\0'; + } + + r = rest; + nlinks = 0; + + /* While there are still components to check... */ + + while (restlen > 0) + { + /* Save current checkedlen. Save current restlen in case we get a non-existant component. */ + + prevcheckedlen = checkedlen; + prevrestlen = restlen; + + /* Grab one component from r and transfer it to checked. */ + + cp1 = strchr(r, '/'); + if (cp1) + { + i = cp1 - r; + if (i == 0) + { + /* Special case for absolute paths. */ + + httpd_realloc_str(&checked, &maxchecked, checkedlen + 1); + (void)strncpy(&checked[checkedlen], r, 1); + checkedlen += 1; + } + else if (strncmp(r, "..", MAX(i, 2)) == 0) + { + /* Ignore ..'s that go above the start of the path. */ + + if (checkedlen != 0) + { + cp2 = strrchr(checked, '/'); + if (!cp2) + { + checkedlen = 0; + } + else if (cp2 == checked) + { + checkedlen = 1; + } + else + { + checkedlen = cp2 - checked; + } + } + } + else + { + httpd_realloc_str(&checked, &maxchecked, checkedlen + 1 + i); + if (checkedlen > 0 && checked[checkedlen - 1] != '/') + { + checked[checkedlen++] = '/'; + } + + (void)strncpy(&checked[checkedlen], r, i); + checkedlen += i; + } + + checked[checkedlen] = '\0'; + r += i + 1; + restlen -= i + 1; + } + else + { + /* No slashes remaining, r is all one component. */ + + if (strcmp(r, "..") == 0) + { + /* Ignore ..'s that go above the start of the path. */ + + if (checkedlen != 0) + { + cp2 = strrchr(checked, '/'); + if (!cp2) + { + checkedlen = 0; + } + else if (cp2 == checked) + { + checkedlen = 1; + } + else + { + checkedlen = cp2 - checked; + } + + checked[checkedlen] = '\0'; + } + } + else + { + httpd_realloc_str(&checked, &maxchecked, checkedlen + 1 + restlen); + if (checkedlen > 0 && checked[checkedlen - 1] != '/') + { + checked[checkedlen++] = '/'; + } + + (void)strcpy(&checked[checkedlen], r); + checkedlen += restlen; + } + + r += restlen; + restlen = 0; + } + } + + /* Ok. */ + + *restP = r; + if (checked[0] == '\0') + { + (void)strcpy(checked, httpd_root); + } + + nvdbg("checked: \"%s\"\n", checked); + return checked; +} + +static char *bufgets(httpd_conn *hc) +{ + int i; + char c; + + for (i = hc->checked_idx; hc->checked_idx < hc->read_idx; ++hc->checked_idx) + { + c = hc->read_buf[hc->checked_idx]; + if (c == '\012' || c == '\015') + { + hc->read_buf[hc->checked_idx] = '\0'; + ++hc->checked_idx; + if (c == '\015' && hc->checked_idx < hc->read_idx && + hc->read_buf[hc->checked_idx] == '\012') + { + hc->read_buf[hc->checked_idx] = '\0'; + ++hc->checked_idx; + } + return &(hc->read_buf[i]); + } + } + return NULL; +} + +static void de_dotdot(char *file) +{ + char *cp; + char *cp2; + int l; + + /* Collapse any multiple / sequences. */ + + while ((cp = strstr(file, "//")) != NULL) + { + for (cp2 = cp + 2; *cp2 == '/'; ++cp2) + { + continue; + } + + (void)strcpy(cp + 1, cp2); + } + + /* Remove leading ./ and any /./ sequences. */ + + while (strncmp(file, "./", 2) == 0) + { + (void)strcpy(file, file + 2); + } + + while ((cp = strstr(file, "/./")) != NULL) + { + (void)strcpy(cp, cp + 2); + } + + /* Alternate between removing leading ../ and removing xxx/../ */ + + for (;;) + { + while (strncmp(file, "../", 3) == 0) + { + (void)strcpy(file, file + 3); + } + + cp = strstr(file, "/../"); + if (!cp) + { + break; + } + + for (cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2) + { + continue; + } + + (void)strcpy(cp2 + 1, cp + 4); + } + + /* Also elide any xxx/.. at the end. */ + + while ((l = strlen(file)) > 3 && strcmp((cp = file + l - 3), "/..") == 0) + { + for (cp2 = cp - 1; cp2 >= file && *cp2 != '/'; --cp2) + { + continue; + } + + if (cp2 < file) + { + break; + } + + *cp2 = '\0'; + } +} + +static void init_mime(void) +{ + int i; + + /* Fill in the lengths. */ + + for (i = 0; i < n_enc_tab; ++i) + { + enc_tab[i].ext_len = strlen(enc_tab[i].ext); + enc_tab[i].val_len = strlen(enc_tab[i].val); + } + + for (i = 0; i < n_typ_tab; ++i) + { + typ_tab[i].ext_len = strlen(typ_tab[i].ext); + typ_tab[i].val_len = strlen(typ_tab[i].val); + } +} + +/* Figure out MIME encodings and type based on the filename. Multiple + * encodings are separated by commas, and are listed in the order in + * which they were applied to the file. + */ + +static void figure_mime(httpd_conn *hc) +{ + char *prev_dot; + char *dot; + char *ext; + int me_indexes[100], n_me_indexes; + size_t ext_len, encodings_len; + int i, top, bot, mid; + int r; + char *default_type = "text/plain; charset=%s"; + + /* Peel off encoding extensions until there aren't any more. */ + + n_me_indexes = 0; + for (prev_dot = &hc->expnfilename[strlen(hc->expnfilename)];; prev_dot = dot) + { + for (dot = prev_dot - 1; dot >= hc->expnfilename && *dot != '.'; --dot) + ; + + if (dot < hc->expnfilename) + { + /* No dot found. No more encoding extensions, and no type + * extension either. + */ + + hc->type = default_type; + goto done; + } + + ext = dot + 1; + ext_len = prev_dot - ext; + + /* Search the encodings table. Linear search is fine here, there are + * only a few entries. + */ + + for (i = 0; i < n_enc_tab; ++i) + { + if (ext_len == enc_tab[i].ext_len && + strncasecmp(ext, enc_tab[i].ext, ext_len) == 0) + { + if (n_me_indexes < sizeof(me_indexes) / sizeof(*me_indexes)) + { + me_indexes[n_me_indexes] = i; + ++n_me_indexes; + } + goto next; + } + } + + /* No encoding extension found. Break and look for a type extension. */ + + break; + + next:; + } + + /* Binary search for a matching type extension. */ + + top = n_typ_tab - 1; + bot = 0; + while (top >= bot) + { + mid = (top + bot) / 2; + r = strncasecmp(ext, typ_tab[mid].ext, ext_len); + if (r < 0) + { + top = mid - 1; + } + else if (r > 0) + { + bot = mid + 1; + } + else if (ext_len < typ_tab[mid].ext_len) + { + top = mid - 1; + } + else if (ext_len > typ_tab[mid].ext_len) + { + bot = mid + 1; + } + else + { + hc->type = typ_tab[mid].val; + goto done; + } + } + hc->type = default_type; + +done: + + /* The last thing we do is actually generate the mime-encoding header. */ + + hc->encodings[0] = '\0'; + encodings_len = 0; + for (i = n_me_indexes - 1; i >= 0; --i) + { + httpd_realloc_str(&hc->encodings, &hc->maxencodings, + encodings_len + enc_tab[me_indexes[i]].val_len + 1); + if (hc->encodings[0] != '\0') + { + (void)strcpy(&hc->encodings[encodings_len], ","); + ++encodings_len; + } + + (void)strcpy(&hc->encodings[encodings_len], enc_tab[me_indexes[i]].val); + encodings_len += enc_tab[me_indexes[i]].val_len; + } +} + +/* qsort comparison routine. */ + +#ifdef CONFIG_THTTPD_GENERATE_INDICES +static int name_compare(char **a, char **b) +{ + return strcmp(*a, *b); +} + +static void ls_child(int argc, char **argv) +{ + FAR httpd_conn *hc = (FAR httpd_conn*)strtoul(argv[1], NULL, 16); + DIR *dirp; + struct dirent *de; + int namlen; + static int maxnames = 0; + int nnames; + static char *names; + static char **nameptrs; + static char *name; + static size_t maxname = 0; + static char *rname; + static size_t maxrname = 0; + static char *encrname; + static size_t maxencrname = 0; + FILE *fp; + int i, r; + struct stat sb; + struct stat lsb; + char modestr[20]; + char *linkprefix; + char link[MAXPATHLEN + 1]; + char *fileclass; + time_t now; + char *timestr; + ClientData client_data; + + httpd_unlisten(hc->hs); + send_mime(hc, 200, ok200title, "", "", "text/html; charset=%s", + (off_t) - 1, hc->sb.st_mtime); + httpd_write_response(hc); + + /* Open a stdio stream so that we can use fprintf, which is more + * efficient than a bunch of separate write()s. We don't have to + * worry about double closes or file descriptor leaks cause we're + * in a sub-task. + */ + + fp = fdopen(hc->conn_fd, "w"); + if (fp == NULL) + { + ndbg("fdopen: %d\n", errno); + INTERNALERROR("fdopen"); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + httpd_write_response(hc); + closedir(dirp); + exit(1); + } + + fputs(html_html, fp); + fputs(html_hdtitle, fp); + (void)fprintf(fp, "Index of %s", hc->encodedurl, hc->encodedurl); + fputs(html_titlehd, fp); + fputs(html_body, fp); + fputs(html_hdr2, fp); + (void)fprintf(fp, "Index of %s", hc->encodedurl, hc->encodedurl); + fputs(html_endhdr2, fp); + fputs(html_crlf, fp); + fputs("<PRE>\r\nmode links bytes last-changed name\r\n<HR>", fp); + + /* Read in names. */ + + nnames = 0; + while ((de = readdir(dirp)) != 0) /* dirent or direct */ + { + if (nnames >= maxnames) + { + if (maxnames == 0) + { + maxnames = 100; + names = NEW(char, maxnames * (MAXPATHLEN + 1)); + nameptrs = NEW(char*, maxnames); + } + else + { + oldmax = maxnames; + maxnames *= 2; + names = RENEW(names, char, oldmax*(MAXPATHLEN+1), maxnames*(MAXPATHLEN + 1)); + nameptrs = RENEW(nameptrs, char*, oldmax, maxnames); + } + + if (!names || !nameptrs) + { + ndbg("out of memory reallocating directory names\n"); + exit(1); + } + + for (i = 0; i < maxnames; ++i) + { + nameptrs[i] = &names[i * (MAXPATHLEN + 1)]; + } + } + + namlen = NAMLEN(de); + (void)strncpy(nameptrs[nnames], de->d_name, namlen); + nameptrs[nnames][namlen] = '\0'; + ++nnames; + } + closedir(dirp); + + /* Sort the names. */ + + qsort(nameptrs, nnames, sizeof(*nameptrs), name_compare); + + /* Generate output. */ + + for (i = 0; i < nnames; ++i) + { + httpd_realloc_str(&name, &maxname, + strlen(hc->expnfilename) + 1 + + strlen(nameptrs[i])); + httpd_realloc_str(&rname, &maxrname, + strlen(hc->origfilename) + 1 + + strlen(nameptrs[i])); + + if (hc->expnfilename[0] == '\0' || strcmp(hc->expnfilename, ".") == 0) + { + (void)strcpy(name, nameptrs[i]); + (void)strcpy(rname, nameptrs[i]); + } + else + { + (void)snprintf(name, maxname, "%s/%s", hc->expnfilename, nameptrs[i]); + if (strcmp(hc->origfilename, ".") == 0) + { + (void)snprintf(rname, maxrname, "%s", nameptrs[i]); + } + else + { + (void)snprintf(rname, maxrname, "%s%s", hc->origfilename, nameptrs[i]); + } + } + + httpd_realloc_str(&encrname, &maxencrname, 3 * strlen(rname) + 1); + httpd_strencode(encrname, maxencrname, rname); + + if (stat(name, &sb) < 0 || lstat(name, &lsb) < 0) + { + continue; + } + + linkprefix = ""; + link[0] = '\0'; + + /* Break down mode word. First the file type. */ + + switch (lsb.st_mode & S_IFMT) + { + case S_IFIFO: + modestr[0] = 'p'; + break; + + case S_IFCHR: + modestr[0] = 'c'; + break; + + case S_IFDIR: + modestr[0] = 'd'; + break; + + case S_IFBLK: + modestr[0] = 'b'; + break; + + case S_IFREG: + modestr[0] = '-'; + break; + + case S_IFSOCK: + modestr[0] = 's'; + break; + + case S_IFLNK: + default: + modestr[0] = '?'; + break; + } + + /* Now the world permissions. Owner and group permissions are + * not of interest to web clients. + */ + + modestr[1] = (lsb.st_mode & S_IROTH) ? 'r' : '-'; + modestr[2] = (lsb.st_mode & S_IWOTH) ? 'w' : '-'; + modestr[3] = (lsb.st_mode & S_IXOTH) ? 'x' : '-'; + modestr[4] = '\0'; + + /* We also leave out the owner and group name */ + + /* Get time string. */ + + now = time(NULL); + timestr = ctime(&lsb.st_mtime); + timestr[0] = timestr[4]; + timestr[1] = timestr[5]; + timestr[2] = timestr[6]; + timestr[3] = ' '; + timestr[4] = timestr[8]; + timestr[5] = timestr[9]; + timestr[6] = ' '; + + if (now - lsb.st_mtime > 60 * 60 * 24 * 182) /* 1/2 year */ + { + timestr[7] = ' '; + timestr[8] = timestr[20]; + timestr[9] = timestr[21]; + timestr[10] = timestr[22]; + timestr[11] = timestr[23]; + } + else + { + timestr[7] = timestr[11]; + timestr[8] = timestr[12]; + timestr[9] = ':'; + timestr[10] = timestr[14]; + timestr[11] = timestr[15]; + } + timestr[12] = '\0'; + + /* The ls -F file class. */ + + switch (sb.st_mode & S_IFMT) + { + case S_IFDIR: + fileclass = "/"; + break; + + case S_IFSOCK: + fileclass = "="; + break; + + case S_IFLNK: + fileclass = "@"; + break; + + default: + fileclass = (sb.st_mode & S_IXOTH) ? "*" : ""; + break; + } + + /* And print. */ + + (void)fprintf(fp, "%s %3ld %10lld %s <A HREF=\"/%.500s%s\">%s</A>%s%s%s\n", + modestr, (long)lsb.st_nlink, (int16_t) lsb.st_size, + timestr, encrname, S_ISDIR(sb.st_mode) ? "/" : "", + nameptrs[i], linkprefix, link, fileclass); + } + + fputs("</PRE>", fp); + fputs(html_endbody, fp); + fputs(html_endhtml, fp); + (void)fclose(fp); + exit(0); +} + +static int ls(httpd_conn *hc) +{ + DIR *dirp; + struct dirent *de; + int namlen; + static int maxnames = 0; + int nnames; + static char *names; + static char **nameptrs; + static char *name; + static size_t maxname = 0; + static char *rname; + static size_t maxrname = 0; + static char *encrname; + static size_t maxencrname = 0; + FILE *fp; + int i, child; + struct stat sb; + struct stat lsb; + char modestr[20]; + char *linkprefix; + char link[MAXPATHLEN + 1]; + char *fileclass; + time_t now; + char *timestr; + char arg[16]; + char *argv[1]; +#if CONFIG_THTTPD_CGI_TIMELIMIT > 0 + ClientData client_data; +#endif + + dirp = opendir(hc->expnfilename); + if (dirp == NULL) + { + ndbg("opendir %s: %d\n", hc->expnfilename, errno); + httpd_send_err(hc, 404, err404title, "", err404form, hc->encodedurl); + return -1; + } + + if (hc->method == METHOD_HEAD) + { + closedir(dirp); + send_mime(hc, 200, ok200title, "", "", "text/html; charset=%s", + (off_t) - 1, hc->sb.st_mtime); + } + else if (hc->method == METHOD_GET) + { +#ifdef CONFIG_THTTPD_CGILIMIT + if (hc->hs->cgi_count >= CONFIG_THTTPD_CGILIMIT) + { + closedir(dirp); + httpd_send_err(hc, 503, httpd_err503title, "", httpd_err503form, + hc->encodedurl); + return -1; + } +#endif + ++hc->hs->cgi_count; + + /* Start the child task. */ + + snprintf(arg, 16, "%p", hc); /* task_create doesn't handle binary arguments. */ + argv[0] = arg; + +#ifndef CONFIG_CUSTOM_STACK + child = task_create("CGI child", CONFIG_THTTPD_CGI_PRIORITY, + CONFIG_THTTPD_CGI_STACKSIZE, + (main_t)ls_child, (const char **)argv); +#else + child = task_create("CGI child", CONFIG_THTTPD_CGI_PRIORITY, + (main_t)ls_child, (const char **)argv); +#endif + if (child < 0) + { + ndbg("task_create: %d\n", errno); + closedir(dirp); + INTERNALERROR("task_create"); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } + + closedir(dirp); + ndbg("spawned indexing task %d for directory '%s'\n", child, hc->expnfilename); + + /* Schedule a kill for the child task, in case it runs too long */ + +#if CONFIG_THTTPD_CGI_TIMELIMIT > 0 + client_data.i = child; + if (tmr_create(NULL, cgi_kill, client_data, CONFIG_THTTPD_CGI_TIMELIMIT * 1000L, 0) == NULL) + { + ndbg("tmr_create(cgi_kill ls) failed\n"); + exit(1); + } +#endif + + hc->bytes_sent = CONFIG_THTTPD_CGI_BYTECOUNT; + hc->should_linger = false; + } + else + { + closedir(dirp); + NOTIMPLEMENTED(httpd_method_str(hc->method)); + httpd_send_err(hc, 501, err501title, "", err501form, httpd_method_str(hc->method)); + return -1; + } + + return 0; +} +#endif /* CONFIG_THTTPD_GENERATE_INDICES */ + +/* Returns 1 if ok to serve the url, 0 if not. */ + +static int check_referer(httpd_conn *hc) +{ + /* Are we doing referer checking at all? */ + +#ifdef CONFIG_THTTPD_URLPATTERN + int r; + char *cp; + + child = really_check_referer(hc); + + if (!r) + { +#ifdef CONFIG_THTTPD_VHOST + if (hc->vhostname != NULL) + { + cp = hc->vhostname; + } + else +#endif + { + cp = hc->hs->hostname; + } + + if (cp == NULL) + { + cp = ""; + } + + ndbg("%s non-local referer \"%s%s\" \"%s\"\n", + httpd_ntoa(&hc->client_addr), cp, hc->encodedurl, hc->referer); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "You must supply a local referer to get URL '%s' from this server.\n"), + hc->encodedurl); + } + return r; +#else + return 1; +#endif +} + +/* Returns 1 if ok to serve the url, 0 if not. */ + +#ifdef CONFIG_THTTPD_URLPATTERN +static int really_check_referer(httpd_conn *hc) +{ + httpd_server *hs; + char *cp1; + char *cp2; + char *cp3; + static char *refhost = NULL; + static size_t refhost_size = 0; + char *lp; + + hs = hc->hs; + + /* Check for an empty referer. */ + + if (hc->referer == NULL || hc->referer[0] == '\0' || + (cp1 = strstr(hc->referer, "//")) == NULL) + { + /* Disallow if the url matches. */ + + if (match(CONFIG_THTTPD_URLPATTERN, hc->origfilename)) + { + return 0; + } + + /* Otherwise ok. */ + + return 1; + } + + /* Extract referer host. */ + + cp1 += 2; + for (cp2 = cp1; *cp2 != '/' && *cp2 != ':' && *cp2 != '\0'; ++cp2) + { + continue; + } + + httpd_realloc_str(&refhost, &refhost_size, cp2 - cp1); + for (cp3 = refhost; cp1 < cp2; ++cp1, ++cp3) + if (isupper(*cp1)) + { + *cp3 = tolower(*cp1); + } + else + { + *cp3 = *cp1; + } + *cp3 = '\0'; + + /* Local pattern? */ + +#ifdef CONFIG_THTTPD_LOCALPATTERN + lp = CONFIG_THTTPD_LOCALPATTERN; +#else + + /* No local pattern. What's our hostname? */ + +#ifndef CONFIG_THTTPD_VHOST + /* Not vhosting, use the server name. */ + + lp = hs->hostname; + if (!lp) + { + /* Couldn't figure out local hostname - give up. */ + + return 1; + } + +#else + /* We are vhosting, use the hostname on this connection. */ + + lp = hc->vhostname; + if (!lp) + { + /* Oops, no hostname. Maybe it's an old browser that doesn't + * send a Host: header. We could figure out the default + * hostname for this IP address, but it's not worth it for the + * few requests like this. + */ + + return 1; + } +#endif +#endif /* CONFIG_THTTPD_LOCALPATTERN */ + + /* If the referer host doesn't match the local host pattern, and the + * filename does match the url pattern, it's an illegal reference. + */ + +#ifdef CONFIG_THTTPD_URLPATTERN + if (!match(lp, refhost) && match(CONFIG_THTTPD_URLPATTERN, hc->origfilename)) + { + return 0; + } +#endif + + /* Otherwise ok. */ + + return 1; +} +#endif + +#ifdef CONFIG_DEBUG +static int sockaddr_check(httpd_sockaddr *saP) +{ + switch (saP->sin_family) + { + case AF_INET: + return 1; + +#ifdef CONFIG_NET_IPv6 + case AF_INET6: + return 1; +#endif + + default: + return 0; + } +} +#endif + +static size_t sockaddr_len(httpd_sockaddr *saP) +{ + switch (saP->sin_family) + { + case AF_INET: + return sizeof(struct sockaddr_in); + +#ifdef CONFIG_NET_IPv6 + case AF_INET6: + return sizeof(struct sockaddr_in6); +#endif + + default: + break; + } + return 0; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +FAR httpd_server *httpd_initialize(FAR httpd_sockaddr *sa) +{ + FAR httpd_server *hs; + + /* Save the PID of the main thread */ + + main_thread = getpid(); + + /* Allocate the server structure */ + + hs = (FAR httpd_server *)zalloc(sizeof(httpd_server)); + if (!hs) + { + ndbg("out of memory allocating an httpd_server\n"); + return NULL; + } + +#ifdef CONFIG_THTTPD_HOSTNAME + hs->hostname = httpd_strdup(CONFIG_THTTPD_HOSTNAME); +#else + hs->hostname = httpd_strdup(httpd_ntoa(sa)); +#endif + nvdbg("hostname: %s\n", hs->hostname); + + if (!hs->hostname) + { + ndbg("out of memory copying hostname\n"); + return NULL; + } + + hs->cgi_count = 0; + + /* Initialize listen sockets */ + + hs->listen_fd = initialize_listen_socket(sa); + if (hs->listen_fd == -1) + { + ndbg("Failed to create listen socket\n"); + free_httpd_server(hs); + return NULL; + } + + init_mime(); + + /* Done initializing. */ + + ndbg("%s starting on port %d\n", CONFIG_THTTPD_SERVER_SOFTWARE, (int)CONFIG_THTTPD_PORT); + return hs; +} + +void httpd_terminate(httpd_server * hs) +{ + httpd_unlisten(hs); + free_httpd_server(hs); +} + +void httpd_unlisten(httpd_server * hs) +{ + if (hs->listen_fd != -1) + { + (void)close(hs->listen_fd); + hs->listen_fd = -1; + } +} + +/* Send the buffered response. */ + +void httpd_write_response(httpd_conn *hc) +{ + /* If we are in a sub-task, turn off no-delay mode. */ + + if (main_thread != getpid()) + { + httpd_clear_ndelay(hc->conn_fd); + } + + /* Send the response, if necessary. */ + + if (hc->buflen > 0) + { + (void)httpd_write(hc->conn_fd, hc->buffer, hc->buflen); + hc->buflen = 0; + } +} + +/* Set no-delay / non-blocking mode on a socket. */ + +void httpd_set_ndelay(int fd) +{ + int flags, newflags; + + flags = fcntl(fd, F_GETFL, 0); + if (flags != -1) + { + newflags = flags | (int)O_NDELAY; + if (newflags != flags) + (void)fcntl(fd, F_SETFL, newflags); + } +} + +/* Clear no-delay / non-blocking mode on a socket. */ + +void httpd_clear_ndelay(int fd) +{ + int flags, newflags; + + flags = fcntl(fd, F_GETFL, 0); + if (flags != -1) + { + newflags = flags & ~(int)O_NDELAY; + if (newflags != flags) + { + (void)fcntl(fd, F_SETFL, newflags); + } + } +} + +void httpd_send_err(httpd_conn *hc, int status, const char *title, const char *extraheads, + const char *form, const char *arg) +{ +#ifdef CONFIG_THTTPD_ERROR_DIRECTORY + char filename[1000]; + + /* Try virtual host error page. */ + + ndbg("title: \"%s\" form: \"%s\"\n", title, form); + +#ifdef CONFIG_THTTPD_VHOST + if (hc->hostdir[0] != '\0') + { + (void)snprintf(filename, sizeof(filename), + "%s/%s/err%d.html", hc->hostdir, CONFIG_THTTPD_ERROR_DIRECTORY, status); + if (send_err_file(hc, status, title, extraheads, filename)) + { + nvdbg("Sent VHOST error file\n"); + return; + } + } +#endif + + /* Try server-wide error page. */ + + (void)snprintf(filename, sizeof(filename), "%s/err%d.html", CONFIG_THTTPD_ERROR_DIRECTORY, status); + if (send_err_file(hc, status, title, extraheads, filename)) + { + nvdbg("Sent server-wide error page\n"); + return; + } + + /* Fall back on built-in error page. */ + + send_response(hc, status, title, extraheads, form, arg); + +#else + + send_response(hc, status, title, extraheads, form, arg); + +#endif +} + +const char *httpd_method_str(int method) +{ + switch (method) + { + case METHOD_GET: + return "GET"; + + case METHOD_HEAD: + return "HEAD"; + + case METHOD_POST: + return "POST"; + + default: + return "UNKNOWN"; + } +} + +int httpd_get_conn(httpd_server *hs, int listen_fd, httpd_conn *hc) +{ + httpd_sockaddr sa; + socklen_t sz; + + if (!hc->initialized) + { + hc->read_size = 0; + httpd_realloc_str(&hc->read_buf, &hc->read_size, CONFIG_THTTPD_IOBUFFERSIZE); + hc->maxdecodedurl = + hc->maxorigfilename = hc->maxexpnfilename = hc->maxencodings = + hc->maxpathinfo = hc->maxquery = hc->maxaccept = + hc->maxaccepte = hc->maxreqhost = hc->maxhostdir = + hc->maxremoteuser = 0; +#ifdef CONFIG_THTTPD_TILDE_MAP2 + hc->maxaltdir = 0; +#endif + httpd_realloc_str(&hc->decodedurl, &hc->maxdecodedurl, 1); + httpd_realloc_str(&hc->origfilename, &hc->maxorigfilename, 1); + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, 0); + httpd_realloc_str(&hc->encodings, &hc->maxencodings, 0); + httpd_realloc_str(&hc->pathinfo, &hc->maxpathinfo, 0); + httpd_realloc_str(&hc->query, &hc->maxquery, 0); + httpd_realloc_str(&hc->accept, &hc->maxaccept, 0); + httpd_realloc_str(&hc->accepte, &hc->maxaccepte, 0); + httpd_realloc_str(&hc->reqhost, &hc->maxreqhost, 0); + httpd_realloc_str(&hc->hostdir, &hc->maxhostdir, 0); + httpd_realloc_str(&hc->remoteuser, &hc->maxremoteuser, 0); +#ifdef CONFIG_THTTPD_TILDE_MAP2 + httpd_realloc_str(&hc->altdir, &hc->maxaltdir, 0); +#endif + hc->initialized = 1; + } + + /* Accept the new connection. */ + + nvdbg("accept() new connection on listen_fd %d\n", listen_fd); + sz = sizeof(sa); + hc->conn_fd = accept(listen_fd, (struct sockaddr*)&sa, &sz); + if (hc->conn_fd < 0) + { + if (errno == EWOULDBLOCK) + { + return GC_NO_MORE; + } + + ndbg("accept failed: %d\n", errno); + return GC_FAIL; + } + +#ifdef CONFIG_DEBUG + if (!sockaddr_check(&sa)) + { + ndbg("unknown sockaddr family\n"); + close(hc->conn_fd); + hc->conn_fd = -1; + return GC_FAIL; + } +#endif + + hc->hs = hs; + (void)memset(&hc->client_addr, 0, sizeof(hc->client_addr)); + (void)memmove(&hc->client_addr, &sa, sockaddr_len(&sa)); + hc->read_idx = 0; + hc->checked_idx = 0; + hc->checked_state = CHST_FIRSTWORD; + hc->method = METHOD_UNKNOWN; + hc->bytes_to_send = 0; + hc->bytes_sent = 0; + hc->encodedurl = ""; + hc->decodedurl[0] = '\0'; + hc->protocol = "UNKNOWN"; + hc->origfilename[0] = '\0'; + hc->expnfilename[0] = '\0'; + hc->encodings[0] = '\0'; + hc->pathinfo[0] = '\0'; + hc->query[0] = '\0'; + hc->referer = ""; + hc->useragent = ""; + hc->accept[0] = '\0'; + hc->accepte[0] = '\0'; + hc->acceptl = ""; + hc->cookie = ""; + hc->contenttype = ""; + hc->reqhost[0] = '\0'; + hc->hdrhost = ""; + hc->hostdir[0] = '\0'; + hc->authorization = ""; + hc->remoteuser[0] = '\0'; + hc->buffer[0] = '\0'; +#ifdef CONFIG_THTTPD_TILDE_MAP2 + hc->altdir[0] = '\0'; +#endif + hc->buflen = 0; + hc->if_modified_since = (time_t) - 1; + hc->range_if = (time_t)-1; + hc->contentlength = -1; + hc->type = ""; +#ifdef CONFIG_THTTPD_VHOST + hc->vhostname = NULL; +#endif + hc->mime_flag = true; + hc->one_one = false; + hc->got_range = false; + hc->tildemapped = false; + hc->range_start = 0; + hc->range_end = -1; + hc->keep_alive = false; + hc->should_linger = false; + hc->file_fd = -1; + + nvdbg("New connection accepted on %d\n", hc->conn_fd); + return GC_OK; +} + +/* Checks hc->read_buf to see whether a complete request has been read so far; + * either the first line has two words (an HTTP/0.9 request), or the first + * line has three words and there's a blank line present. + * + * hc->read_idx is how much has been read in; hc->checked_idx is how much we + * have checked so far; and hc->checked_state is the current state of the + * finite state machine. + */ + +int httpd_got_request(httpd_conn *hc) +{ + char c; + + for (; hc->checked_idx < hc->read_idx; ++hc->checked_idx) + { + c = hc->read_buf[hc->checked_idx]; + switch (hc->checked_state) + { + case CHST_FIRSTWORD: + switch (c) + { + case ' ': + case '\t': + hc->checked_state = CHST_FIRSTWS; + break; + + case '\012': + case '\015': + hc->checked_state = CHST_BOGUS; + return GR_BAD_REQUEST; + } + break; + + case CHST_FIRSTWS: + switch (c) + { + case ' ': + case '\t': + break; + + case '\012': + case '\015': + hc->checked_state = CHST_BOGUS; + return GR_BAD_REQUEST; + + default: + hc->checked_state = CHST_SECONDWORD; + break; + } + break; + + case CHST_SECONDWORD: + switch (c) + { + case ' ': + case '\t': + hc->checked_state = CHST_SECONDWS; + break; + + case '\012': + case '\015': + /* The first line has only two words - an HTTP/0.9 request. */ + return GR_GOT_REQUEST; + } + break; + + case CHST_SECONDWS: + switch (c) + { + case ' ': + case '\t': + break; + + case '\012': + case '\015': + hc->checked_state = CHST_BOGUS; + return GR_BAD_REQUEST; + + default: + hc->checked_state = CHST_THIRDWORD; + break; + } + break; + + case CHST_THIRDWORD: + switch (c) + { + case ' ': + case '\t': + hc->checked_state = CHST_THIRDWS; + break; + + case '\012': + hc->checked_state = CHST_LF; + break; + + case '\015': + hc->checked_state = CHST_CR; + break; + } + break; + + case CHST_THIRDWS: + switch (c) + { + case ' ': + case '\t': + break; + + case '\012': + hc->checked_state = CHST_LF; + break; + + case '\015': + hc->checked_state = CHST_CR; + break; + + default: + hc->checked_state = CHST_BOGUS; + return GR_BAD_REQUEST; + } + break; + + case CHST_LINE: + switch (c) + { + case '\012': + hc->checked_state = CHST_LF; + break; + + case '\015': + hc->checked_state = CHST_CR; + break; + } + break; + + case CHST_LF: + switch (c) + { + case '\012': + /* Two newlines in a row - a blank line - end of request. */ + + return GR_GOT_REQUEST; + + case '\015': + hc->checked_state = CHST_CR; + break; + + default: + hc->checked_state = CHST_LINE; + break; + } + break; + + case CHST_CR: + switch (c) + { + case '\012': + hc->checked_state = CHST_CRLF; + break; + + case '\015': + /* Two returns in a row - end of request. */ + + return GR_GOT_REQUEST; + + default: + hc->checked_state = CHST_LINE; + break; + } + break; + + case CHST_CRLF: + switch (c) + { + case '\012': + /* Two newlines in a row - end of request. */ + + return GR_GOT_REQUEST; + + case '\015': + hc->checked_state = CHST_CRLFCR; + break; + + default: + hc->checked_state = CHST_LINE; + break; + } + break; + + case CHST_CRLFCR: + switch (c) + { + case '\012': + case '\015': + /* Two CRLFs or two CRs in a row - end of request. */ + + return GR_GOT_REQUEST; + + default: + hc->checked_state = CHST_LINE; + break; + } + break; + + case CHST_BOGUS: + return GR_BAD_REQUEST; + } + } + return GR_NO_REQUEST; +} + +int httpd_parse_request(httpd_conn *hc) +{ + char *buf; + char *method_str; + char *url; + char *protocol; + char *reqhost; + char *eol; + char *cp; + char *pi; + + hc->checked_idx = 0; /* reset */ + method_str = bufgets(hc); + nvdbg("method_str: \"%s\"\n", method_str); + + url = strpbrk(method_str, " \t\012\015"); + if (!url) + { + BADREQUEST("url-1"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + *url++ = '\0'; + url += strspn(url, " \t\012\015"); + nvdbg("url: \"%s\"\n", url); + + protocol = strpbrk(url, " \t\012\015"); + nvdbg("protocol: \"%s\"\n", protocol ? protocol : "<null>"); + + if (!protocol) + { + protocol = "HTTP/0.9"; + hc->mime_flag = false; + } + else + { + *protocol++ = '\0'; + protocol += strspn(protocol, " \t\012\015"); + if (*protocol != '\0') + { + eol = strpbrk(protocol, " \t\012\015"); + if (eol) + { + *eol = '\0'; + } + + if (strcasecmp(protocol, "HTTP/1.0") != 0) + { + hc->one_one = true; + } + } + } + hc->protocol = protocol; + + /* Check for HTTP/1.1 absolute URL. */ + + if (strncasecmp(url, "http://", 7) == 0) + { + if (!hc->one_one) + { + BADREQUEST("one_one"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + reqhost = url + 7; + url = strchr(reqhost, '/'); + if (!url) + { + BADREQUEST("reqhost-1"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + *url = '\0'; + + if (strchr(reqhost, '/') != NULL || reqhost[0] == '.') + { + BADREQUEST("reqhost-2"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + httpd_realloc_str(&hc->reqhost, &hc->maxreqhost, strlen(reqhost)); + (void)strcpy(hc->reqhost, reqhost); + *url = '/'; + } + + if (*url != '/') + { + BADREQUEST("url-2"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + if (strcasecmp(method_str, httpd_method_str(METHOD_GET)) == 0) + { + hc->method = METHOD_GET; + } + else if (strcasecmp(method_str, httpd_method_str(METHOD_HEAD)) == 0) + { + hc->method = METHOD_HEAD; + } + else if (strcasecmp(method_str, httpd_method_str(METHOD_POST)) == 0) + { + hc->method = METHOD_POST; + } + else + { + NOTIMPLEMENTED(method_str); + httpd_send_err(hc, 501, err501title, "", err501form, method_str); + return -1; + } + + hc->encodedurl = url; + httpd_realloc_str(&hc->decodedurl, &hc->maxdecodedurl, strlen(hc->encodedurl)); + httpd_strdecode(hc->decodedurl, hc->encodedurl); + + httpd_realloc_str(&hc->origfilename, &hc->maxorigfilename, strlen(hc->decodedurl)); + (void)strcpy(hc->origfilename, &hc->decodedurl[1]); + + /* Special case for top-level URL. */ + + if (hc->origfilename[0] == '\0') + { + (void)strcpy(hc->origfilename, "."); + } + + /* Extract query string from encoded URL. */ + + cp = strchr(hc->encodedurl, '?'); + if (cp) + { + ++cp; + httpd_realloc_str(&hc->query, &hc->maxquery, strlen(cp)); + (void)strcpy(hc->query, cp); + + /* Remove query from (decoded) origfilename. */ + + cp = strchr(hc->origfilename, '?'); + if (cp) + { + *cp = '\0'; + } + } + + de_dotdot(hc->origfilename); + if (hc->origfilename[0] == '/' || + (hc->origfilename[0] == '.' && hc->origfilename[1] == '.' && + (hc->origfilename[2] == '\0' || hc->origfilename[2] == '/'))) + { + BADREQUEST("origfilename"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + if (hc->mime_flag) + { + /* Read the MIME headers. */ + while ((buf = bufgets(hc)) != NULL) + { + if (buf[0] == '\0') + { + break; + } + + if (strncasecmp(buf, "Referer:", 8) == 0) + { + cp = &buf[8]; + cp += strspn(cp, " \t"); + hc->referer = cp; + } + else if (strncasecmp(buf, "User-Agent:", 11) == 0) + { + cp = &buf[11]; + cp += strspn(cp, " \t"); + hc->useragent = cp; + } + else if (strncasecmp(buf, "Host:", 5) == 0) + { + cp = &buf[5]; + cp += strspn(cp, " \t"); + hc->hdrhost = cp; + cp = strchr(hc->hdrhost, ':'); + if (cp) + { + *cp = '\0'; + } + + if (strchr(hc->hdrhost, '/') != NULL || hc->hdrhost[0] == '.') + { + BADREQUEST("hdrhost"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + } + else if (strncasecmp(buf, "Accept:", 7) == 0) + { + cp = &buf[7]; + cp += strspn(cp, " \t"); + if (hc->accept[0] != '\0') + { + if (strlen(hc->accept) > CONFIG_THTTPD_MAXREALLOC) + { + ndbg("%s way too much Accept: data\n", + httpd_ntoa(&hc->client_addr)); + continue; + } + httpd_realloc_str(&hc->accept, &hc->maxaccept, strlen(hc->accept) + 2 + strlen(cp)); + (void)strcat(hc->accept, ", "); + } + else + { + httpd_realloc_str(&hc->accept, &hc->maxaccept, strlen(cp)); + } + (void)strcat(hc->accept, cp); + } + else if (strncasecmp(buf, "Accept-Encoding:", 16) == 0) + { + cp = &buf[16]; + cp += strspn(cp, " \t"); + if (hc->accepte[0] != '\0') + { + if (strlen(hc->accepte) > CONFIG_THTTPD_MAXREALLOC) + { + ndbg("%s way too much Accept-Encoding: data\n", + httpd_ntoa(&hc->client_addr)); + continue; + } + httpd_realloc_str(&hc->accepte, &hc->maxaccepte, strlen(hc->accepte) + 2 + strlen(cp)); + (void)strcat(hc->accepte, ", "); + } + else + { + httpd_realloc_str(&hc->accepte, &hc->maxaccepte, strlen(cp)); + } + (void)strcpy(hc->accepte, cp); + } + else if (strncasecmp(buf, "Accept-Language:", 16) == 0) + { + cp = &buf[16]; + cp += strspn(cp, " \t"); + hc->acceptl = cp; + } + else if (strncasecmp(buf, "If-Modified-Since:", 18) == 0) + { + cp = &buf[18]; + hc->if_modified_since = tdate_parse(cp); + if (hc->if_modified_since == (time_t) - 1) + ndbg("unparsable time: %s\n", cp); + } + else if (strncasecmp(buf, "Cookie:", 7) == 0) + { + cp = &buf[7]; + cp += strspn(cp, " \t"); + hc->cookie = cp; + } + else if (strncasecmp(buf, "Range:", 6) == 0) + { + /* Only support %d- and %d-%d, not %d-%d,%d-%d or -%d. */ + if (strchr(buf, ',') == NULL) + { + char *cp_dash; + cp = strpbrk(buf, "="); + if (cp) + { + cp_dash = strchr(cp + 1, '-'); + if (cp_dash != NULL && cp_dash != cp + 1) + { + *cp_dash = '\0'; + hc->got_range = true; + hc->range_start = atoll(cp + 1); + if (hc->range_start < 0) + { + hc->range_start = 0; + } + + if (isdigit((int)cp_dash[1])) + { + hc->range_end = atoll(cp_dash + 1); + if (hc->range_end < 0) + hc->range_end = -1; + } + } + } + } + } + else if (strncasecmp(buf, "Range-If:", 9) == 0 || + strncasecmp(buf, "If-Range:", 9) == 0) + { + cp = &buf[9]; + hc->range_if = tdate_parse(cp); + if (hc->range_if == (time_t) - 1) + { + ndbg("unparsable time: %s\n", cp); + } + } + else if (strncasecmp(buf, "Content-Type:", 13) == 0) + { + cp = &buf[13]; + cp += strspn(cp, " \t"); + hc->contenttype = cp; + } + else if (strncasecmp(buf, "Content-Length:", 15) == 0) + { + cp = &buf[15]; + hc->contentlength = atol(cp); + } + else if (strncasecmp(buf, "Authorization:", 14) == 0) + { + cp = &buf[14]; + cp += strspn(cp, " \t"); + hc->authorization = cp; + } + else if (strncasecmp(buf, "Connection:", 11) == 0) + { + cp = &buf[11]; + cp += strspn(cp, " \t"); + if (strcasecmp(cp, "keep-alive") == 0) + { + hc->keep_alive = true; + } + } +#ifdef LOG_UNKNOWN_HEADERS + else if (strncasecmp(buf, "Accept-Charset:", 15) == 0 || + strncasecmp(buf, "Accept-Language:", 16) == 0 || + strncasecmp(buf, "Agent:", 6) == 0 || + strncasecmp(buf, "Cache-Control:", 14) == 0 || + strncasecmp(buf, "Cache-Info:", 11) == 0 || + strncasecmp(buf, "Charge-To:", 10) == 0 || + strncasecmp(buf, "Client-IP:", 10) == 0 || + strncasecmp(buf, "Date:", 5) == 0 || + strncasecmp(buf, "Extension:", 10) == 0 || + strncasecmp(buf, "Forwarded:", 10) == 0 || + strncasecmp(buf, "From:", 5) == 0 || + strncasecmp(buf, "HTTP-Version:", 13) == 0 || + strncasecmp(buf, "Max-Forwards:", 13) == 0 || + strncasecmp(buf, "Message-Id:", 11) == 0 || + strncasecmp(buf, "MIME-Version:", 13) == 0 || + strncasecmp(buf, "Negotiate:", 10) == 0 || + strncasecmp(buf, "Pragma:", 7) == 0 || + strncasecmp(buf, "Proxy-Agent:", 12) == 0 || + strncasecmp(buf, "Proxy-Connection:", 17) == 0 || + strncasecmp(buf, "Security-Scheme:", 16) == 0 || + strncasecmp(buf, "Session-Id:", 11) == 0 || + strncasecmp(buf, "UA-Color:", 9) == 0 || + strncasecmp(buf, "UA-CPU:", 7) == 0 || + strncasecmp(buf, "UA-Disp:", 8) == 0 || + strncasecmp(buf, "UA-OS:", 6) == 0 || + strncasecmp(buf, "UA-Pixels:", 10) == 0 || + strncasecmp(buf, "User:", 5) == 0 || + strncasecmp(buf, "Via:", 4) == 0 || + strncasecmp(buf, "X-", 2) == 0) + ; /* ignore */ + else + { + ndbg("unknown request header: %s\n", buf); + } +#endif + } + } + + if (hc->one_one) + { + /* Check that HTTP/1.1 requests specify a host, as required. */ + + if (hc->reqhost[0] == '\0' && hc->hdrhost[0] == '\0') + { + BADREQUEST("reqhost-3"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + return -1; + } + + /* If the client wants to do keep-alives, it might also be doing + * pipelining. There's no way for us to tell. Since we don't + * implement keep-alives yet, if we close such a connection there + * might be unread pipelined requests waiting. So, we have to do a + * lingering close. + */ + + if (hc->keep_alive) + { + hc->should_linger = true; + } + } + + /* Ok, the request has been parsed. Now we resolve stuff that may require + * the entire request. + */ + + /* Copy original filename to expanded filename. */ + + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, + strlen(hc->origfilename)); + (void)strcpy(hc->expnfilename, hc->origfilename); + + /* Tilde mapping. */ + + if (hc->expnfilename[0] == '~') + { +#ifdef CONFIG_THTTPD_TILDE_MAP1 + if (!httpd_tilde_map1(hc)) + { + httpd_send_err(hc, 404, err404title, "", err404form, hc->encodedurl); + return -1; + } +#endif +#ifdef CONFIG_THTTPD_TILDE_MAP2 + if (!httpd_tilde_map2(hc)) + { + httpd_send_err(hc, 404, err404title, "", err404form, hc->encodedurl); + return -1; + } +#endif + } + + /* Virtual host mapping. */ + +#ifdef CONFIG_THTTPD_VHOST + if (!vhost_map(hc)) + { + INTERNALERROR("VHOST"); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } +#endif + + /* Expand the filename */ + + cp = expand_filename(hc->expnfilename, &pi, hc->tildemapped); + if (!cp) + { + INTERNALERROR(hc->expnfilename); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } + + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, strlen(cp)); + (void)strcpy(hc->expnfilename, cp); + httpd_realloc_str(&hc->pathinfo, &hc->maxpathinfo, strlen(pi)); + (void)strcpy(hc->pathinfo, pi); + nvdbg("expnfilename: \"%s\" pathinfo: \"%s\"\n", hc->expnfilename, hc->pathinfo); + + /* Remove pathinfo stuff from the original filename too. */ + + if (hc->pathinfo[0] != '\0') + { + int i; + i = strlen(hc->origfilename) - strlen(hc->pathinfo); + if (i > 0 && strcmp(&hc->origfilename[i], hc->pathinfo) == 0) + { + hc->origfilename[i - 1] = '\0'; + } + } + + /* If the expanded filename is an absolute path, check that it's still + * within the current directory or the alternate directory. + */ + + if (hc->expnfilename[0] == '/') + { + if (strncmp(hc->expnfilename, httpd_root, strlen(httpd_root)) == 0) + { + } +#ifdef CONFIG_THTTPD_TILDE_MAP2 + else if (hc->altdir[0] != '\0' && + (strncmp(hc->expnfilename, hc->altdir, strlen(hc->altdir)) == 0 && + (hc->expnfilename[strlen(hc->altdir)] == '\0' || + hc->expnfilename[strlen(hc->altdir)] == '/'))) + { + } +#endif + else + { + ndbg("%s URL \"%s\" goes outside the web tree\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to a file outside the permitted web server directory tree.\n"), + hc->encodedurl); + return -1; + } + } + + return 0; +} + +void httpd_close_conn(httpd_conn *hc) +{ + if (hc->file_fd >= 0) + { + (void)close(hc->file_fd); + hc->file_fd = -1; + } + + if (hc->conn_fd >= 0) + { + (void)close(hc->conn_fd); + hc->conn_fd = -1; + } +} + +void httpd_destroy_conn(httpd_conn *hc) +{ + if (hc->initialized) + { + httpd_free((void *)hc->read_buf); + httpd_free((void *)hc->decodedurl); + httpd_free((void *)hc->origfilename); + httpd_free((void *)hc->expnfilename); + httpd_free((void *)hc->encodings); + httpd_free((void *)hc->pathinfo); + httpd_free((void *)hc->query); + httpd_free((void *)hc->accept); + httpd_free((void *)hc->accepte); + httpd_free((void *)hc->reqhost); + httpd_free((void *)hc->hostdir); + httpd_free((void *)hc->remoteuser); + httpd_free((void *)hc->buffer); +#ifdef CONFIG_THTTPD_TILDE_MAP2 + httpd_free((void *)hc->altdir); +#endif /*CONFIG_THTTPD_TILDE_MAP2 */ + hc->initialized = 0; + } +} + +int httpd_start_request(httpd_conn *hc, struct timeval *nowP) +{ + static char *indexname; + static size_t maxindexname = 0; +#ifdef CONFIG_THTTPD_AUTH_FILE + static char *dirname; + static size_t maxdirname = 0; +#endif /* CONFIG_THTTPD_AUTH_FILE */ + size_t expnlen, indxlen; + char *cp; + char *pi; + int i; + + nvdbg("File: \"%s\"\n", hc->expnfilename); + expnlen = strlen(hc->expnfilename); + + if (hc->method != METHOD_GET && hc->method != METHOD_HEAD && + hc->method != METHOD_POST) + { + NOTIMPLEMENTED("start"); + httpd_send_err(hc, 501, err501title, "", err501form, + httpd_method_str(hc->method)); + return -1; + } + + /* Stat the file. */ + + if (stat(hc->expnfilename, &hc->sb) < 0) + { + INTERNALERROR(hc->expnfilename); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } + + /* Is it world-readable or world-executable? We check explicitly instead + * of just trying to open it, so that no one ever gets surprised by a file + * that's not set world-readable and yet somehow is readable by the HTTP + * server and therefore the *whole* world. + */ + + if (!(hc->sb.st_mode & (S_IROTH | S_IXOTH))) + { + ndbg("%s URL \"%s\" resolves to a non world-readable file\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to a file that is not world-readable.\n"), + hc->encodedurl); + return -1; + } + + /* Is it a directory? */ + + if (S_ISDIR(hc->sb.st_mode)) + { + /* If there's pathinfo, it's just a non-existent file. */ + + if (hc->pathinfo[0] != '\0') + { + httpd_send_err(hc, 404, err404title, "", err404form, hc->encodedurl); + return -1; + } + + /* Special handling for directory URLs that don't end in a slash. We + * send back an explicit redirect with the slash, because otherwise + * many clients can't build relative URLs properly. + */ + + if (strcmp(hc->origfilename, "") != 0 && + strcmp(hc->origfilename, ".") != 0 && + hc->origfilename[strlen(hc->origfilename) - 1] != '/') + { + send_dirredirect(hc); + return -1; + } + + /* Check for an index file. */ + + for (i = 0; i < sizeof(index_names) / sizeof(char *); ++i) + { + httpd_realloc_str(&indexname, &maxindexname, + expnlen + 1 + strlen(index_names[i])); + (void)strcpy(indexname, hc->expnfilename); + indxlen = strlen(indexname); + if (indxlen == 0 || indexname[indxlen - 1] != '/') + { + (void)strcat(indexname, "/"); + } + + if (strcmp(indexname, "./") == 0) + { + indexname[0] = '\0'; + } + + (void)strcat(indexname, index_names[i]); + if (stat(indexname, &hc->sb) >= 0) + { + goto got_one; + } + } + + /* Nope, no index file, so it's an actual directory request. */ +#ifdef CONFIG_THTTPD_GENERATE_INDICES + /* Directories must be readable for indexing. */ + if (!(hc->sb.st_mode & S_IROTH)) + { + ndbg("%s URL \"%s\" tried to index a directory with indexing disabled\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to a directory that has indexing disabled.\n"), + hc->encodedurl); + return -1; + } +# ifdef CONFIG_THTTPD_AUTH_FILE + /* Check authorization for this directory. */ + + if (auth_check(hc, hc->expnfilename) == -1) + { + return -1; + } +# endif /* CONFIG_THTTPD_AUTH_FILE */ + + /* Referer check. */ + + if (!check_referer(hc)) + { + return -1; + } + + /* Ok, generate an index. */ + return ls(hc); +#else + ndbg("%s URL \"%s\" tried to index a directory\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' is a directory, and directory indexing is disabled on this server.\n"), + hc->encodedurl); + return -1; +#endif + + got_one: + + /* Got an index file. Expand again. More pathinfo means + * something went wrong. + */ + + cp = expand_filename(indexname, &pi, hc->tildemapped); + if (cp == NULL || pi[0] != '\0') + { + INTERNALERROR(indexname); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } + + expnlen = strlen(cp); + httpd_realloc_str(&hc->expnfilename, &hc->maxexpnfilename, expnlen); + (void)strcpy(hc->expnfilename, cp); + + /* Now, is the index version world-readable or world-executable? */ + + if (!(hc->sb.st_mode & (S_IROTH | S_IXOTH))) + { + ndbg("%s URL \"%s\" resolves to a non-world-readable index file\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to an index file that is not world-readable.\n"), + hc->encodedurl); + return -1; + } + } + + /* Check authorization for this directory. */ + +#ifdef CONFIG_THTTPD_AUTH_FILE + httpd_realloc_str(&dirname, &maxdirname, expnlen); + (void)strcpy(dirname, hc->expnfilename); + cp = strrchr(dirname, '/'); + if (!cp) + { + (void)strcpy(dirname, httpd_root); + } + else + { + *cp = '\0'; + } + + if (auth_check(hc, dirname) == -1) + { + return -1; + } + + /* Check if the filename is the CONFIG_THTTPD_AUTH_FILE itself - that's verboten. */ + + if (expnlen == sizeof(CONFIG_THTTPD_AUTH_FILE) - 1) + { + if (strcmp(hc->expnfilename, CONFIG_THTTPD_AUTH_FILE) == 0) + { + ndbg("%s URL \"%s\" tried to retrieve an auth file\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' is an authorization file, retrieving it is not permitted.\n"), + hc->encodedurl); + return -1; + } + } + else if (expnlen >= sizeof(CONFIG_THTTPD_AUTH_FILE) && + strcmp(&(hc->expnfilename[expnlen - sizeof(CONFIG_THTTPD_AUTH_FILE) + 1]), + CONFIG_THTTPD_AUTH_FILE) == 0 && + hc->expnfilename[expnlen - sizeof(CONFIG_THTTPD_AUTH_FILE)] == '/') + { + ndbg("%s URL \"%s\" tried to retrieve an auth file\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' is an authorization file, retrieving it is not permitted.\n"), + hc->encodedurl); + return -1; + } +#endif + + /* Referer check. */ + + if (!check_referer(hc)) + return -1; + + /* Is it in the CGI area? */ + +#ifdef CONFIG_THTTPD_CGI_PATTERN + if (match(CONFIG_THTTPD_CGI_PATTERN, hc->expnfilename)) + { + return cgi(hc); + } +#endif + + /* It's not CGI. If it's executable or there's pathinfo, someone's trying + * to either serve or run a non-CGI file as CGI. Either case is + * prohibited. + */ + + if (hc->sb.st_mode & S_IXOTH) + { + ndbg("%s URL \"%s\" is executable but isn't CGI\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to a file which is marked executable but is not a CGI file; retrieving it is forbidden.\n"), + hc->encodedurl); + return -1; + } + + if (hc->pathinfo[0] != '\0') + { + ndbg("%s URL \"%s\" has pathinfo but isn't CGI\n", + httpd_ntoa(&hc->client_addr), hc->encodedurl); + httpd_send_err(hc, 403, err403title, "", + ERROR_FORM(err403form, + "The requested URL '%s' resolves to a file plus CGI-style pathinfo, but the file is not a valid CGI file.\n"), + hc->encodedurl); + return -1; + } + + /* Fill in range_end, if necessary. */ + + if (hc->got_range && + (hc->range_end == -1 || hc->range_end >= hc->sb.st_size)) + { + hc->range_end = hc->sb.st_size - 1; + } + + figure_mime(hc); + + if (hc->method == METHOD_HEAD) + { + send_mime(hc, 200, ok200title, hc->encodings, "", hc->type, + hc->sb.st_size, hc->sb.st_mtime); + } + else if (hc->if_modified_since != (time_t) - 1 && + hc->if_modified_since >= hc->sb.st_mtime) + { + send_mime(hc, 304, err304title, hc->encodings, "", hc->type, (off_t) - 1, + hc->sb.st_mtime); + } + else + { + hc->file_fd = open(hc->expnfilename, O_RDONLY); + if (!hc->file_fd < 0) + { + INTERNALERROR(hc->expnfilename); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + return -1; + } + send_mime(hc, 200, ok200title, hc->encodings, "", hc->type, + hc->sb.st_size, hc->sb.st_mtime); + } + + return 0; +} + +char *httpd_ntoa(httpd_sockaddr *saP) +{ +#ifdef CONFIG_NET_IPv6 + static char str[200]; + + if (getnameinfo + (&saP->sa, sockaddr_len(saP), str, sizeof(str), 0, 0, + NI_NUMERICHOST) != 0) + { + str[0] = '?'; + str[1] = '\0'; + } + else if (IN6_IS_ADDR_V4MAPPED(&saP->sa_in6.sin6_addr) && + strncmp(str, "::ffff:", 7) == 0) + { + /* Elide IPv6ish prefix for IPv4 addresses. */ + + (void)strcpy(str, &str[7]); + } + + return str; + +#else /* CONFIG_NET_IPv6 */ + + return inet_ntoa(saP->sin_addr); + +#endif +} + +/* Read to requested buffer, accounting for interruptions and EOF */ + +int httpd_read(int fd, const void *buf, size_t nbytes) +{ + ssize_t nread; + int ntotal; + + ntotal = 0; + do + { + nread = read(fd, (char*)buf + ntotal, nbytes - ntotal); + if (nread < 0) + { + if (errno == EAGAIN) + { + usleep(100000); /* 100MS */ + } + else if (errno != EINTR) + { + ndbg("Error sending: %d\n", errno); + return nread; + } + } + else + { + ntotal += nread; + } + } + while (ntotal < nbytes && nread != 0); + return ntotal; +} + +/* Write the requested buffer completely, accounting for interruptions */ + +int httpd_write(int fd, const void *buf, size_t nbytes) +{ + ssize_t nwritten; + int ntotal; + + ntotal = 0; + do + { + nwritten = write(fd, (char*)buf + ntotal, nbytes - ntotal); + if (nwritten < 0) + { + if (errno == EAGAIN) + { + usleep(100000); /* 100MS */ + } + else if (errno != EINTR) + { + ndbg("Error sending: %d\n", errno); + return nwritten; + } + } + else + { + ntotal += nwritten; + } + } + while (ntotal < nbytes); + return ntotal; +} + +#endif /* CONFIG_THTTPD */ + diff --git a/apps/netutils/thttpd/libhttpd.h b/apps/netutils/thttpd/libhttpd.h new file mode 100644 index 000000000..f2e39e04d --- /dev/null +++ b/apps/netutils/thttpd/libhttpd.h @@ -0,0 +1,342 @@ +/**************************************************************************** + * netutils/thttpd/libhttpd.h + * HTTP Protocol Library Definitions + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_LIBHTTPD_H +#define __NETUTILS_THTTPD_LIBHTTPD_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <stdint.h> +#include <stdbool.h> +#include <netinet/in.h> +#include <arpa/inet.h> + +#include <time.h> + +#include "config.h" +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* A few convenient defines. */ + +#ifndef MAX +# define MAX(a,b) ((a) > (b) ? (a) : (b)) +#endif +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/* Enable special instrumentation to track down "400 Bad Request" problems */ + +#undef CONFIG_THTTPD_BADREQUEST /* Define to enable "Bad Request" instrumentation */ + +#ifdef CONFIG_THTTPD_BADREQUEST +# if !defined(CONFIG_DEBUG_VERBOSE) || !defined(CONFIG_DEBUG_NET) +# undef CONFIG_THTTPD_BADREQUEST +# else +# define BADREQUEST(s) nvdbg("Bad Request: \"%s\"\n", s) +# endif +#endif + +#ifndef CONFIG_THTTPD_BADREQUEST +# undef BADREQUEST +# define BADREQUEST(s) +#endif + +/* Enable special instrumentation to track down "501 Not Implemented" problems */ + +#undef CONFIG_THTTPD_NOTIMPLEMENTED /* Define to enable "Not Implemented" instrumentation */ + +#ifdef CONFIG_THTTPD_NOTIMPLEMENTED +# if !defined(CONFIG_DEBUG_VERBOSE) || !defined(CONFIG_DEBUG_NET) +# undef CONFIG_THTTPD_NOTIMPLEMENTED +# else +# define NOTIMPLEMENTED(s) nvdbg("Not Implemented: \"%s\"\n", s) +# endif +#endif + +#ifndef CONFIG_THTTPD_NOTIMPLEMENTED +# undef NOTIMPLEMENTED +# define NOTIMPLEMENTED(s) +#endif + +/* Enable special instrumentation to track down "500 Internal Error" problems */ + +#undef CONFIG_THTTPD_INTERNALERROR /* Define to enable "Internal Error" instrumentation */ + +#ifdef CONFIG_THTTPD_INTERNALERROR +# if !defined(CONFIG_DEBUG_VERBOSE) || !defined(CONFIG_DEBUG_NET) +# undef CONFIG_THTTPD_INTERNALERROR +# else +# define INTERNALERROR(s) nvdbg("Internal Error: \"%s\"\n", s) +# endif +#endif + +#ifndef CONFIG_THTTPD_INTERNALERROR +# undef INTERNALERROR +# define INTERNALERROR(s) +#endif + +/* Methods */ + +#define METHOD_UNKNOWN 0 +#define METHOD_GET 1 +#define METHOD_HEAD 2 +#define METHOD_POST 3 + +/* States for checked_state. */ + +#define CHST_FIRSTWORD 0 +#define CHST_FIRSTWS 1 +#define CHST_SECONDWORD 2 +#define CHST_SECONDWS 3 +#define CHST_THIRDWORD 4 +#define CHST_THIRDWS 5 +#define CHST_LINE 6 +#define CHST_LF 7 +#define CHST_CR 8 +#define CHST_CRLF 9 +#define CHST_CRLFCR 10 +#define CHST_BOGUS 11 + +#define GC_FAIL 0 +#define GC_OK 1 +#define GC_NO_MORE 2 + +#define GR_NO_REQUEST 0 +#define GR_GOT_REQUEST 1 +#define GR_BAD_REQUEST 2 + +/**************************************************************************** + * Public Type Definitions + ****************************************************************************/ + +/* A multi-family sockaddr. */ + +#ifdef CONFIG_NET_IPv6 +typedef struct sockaddr_in6 httpd_sockaddr; +#else +typedef struct sockaddr_in httpd_sockaddr; +#endif + +/* A server. */ + +typedef struct +{ + char *hostname; + int cgi_count; + int listen_fd; +} httpd_server; + +/* A connection. */ + +typedef struct +{ + int initialized; + httpd_server *hs; + httpd_sockaddr client_addr; + char *read_buf; + size_t read_size, read_idx, checked_idx; + int checked_state; + int method; + off_t bytes_to_send; + off_t bytes_sent; + char *encodedurl; + char *decodedurl; + char *protocol; + char *origfilename; + char *expnfilename; + char *encodings; + char *pathinfo; + char *query; + char *referer; + char *useragent; + char *accept; + char *accepte; + char *acceptl; + char *cookie; + char *contenttype; + char *reqhost; + char *hdrhost; + char *hostdir; + char *authorization; + char *remoteuser; + size_t maxdecodedurl, maxorigfilename, maxexpnfilename, maxencodings, + maxpathinfo, maxquery, maxaccept, maxaccepte, maxreqhost, maxhostdir, + maxremoteuser, maxresponse; +#ifdef CONFIG_THTTPD_TILDE_MAP2 + char *altdir; + size_t maxaltdir; +#endif + time_t if_modified_since, range_if; + size_t contentlength; + char *type; /* not malloc()ed */ +#ifdef CONFIG_THTTPD_VHOST + char *vhostname; /* not malloc()ed */ +#endif + bool mime_flag; + bool one_one; /* HTTP/1.1 or better */ + bool got_range; + bool tildemapped; /* this connection got tilde-mapped */ + bool keep_alive; + bool should_linger; + int conn_fd; /* Connection to the client */ + int file_fd; /* Descriptor for open, outgoing file */ + off_t range_start; /* File range start from Range= */ + off_t range_end; /* File range end from Range= */ + struct stat sb; + + /* This is the I/O buffer that is used to buffer portions of outgoing files */ + + uint16_t buflen; /* Index to first valid data in buffer */ + uint8_t buffer[CONFIG_THTTPD_IOBUFFERSIZE]; +} httpd_conn; + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/* Initializes. Does the socket(), bind(), and listen(). Returns an + * httpd_server* which includes a socket fd that you can select() on. + * Return (httpd_server*) 0 on error. + */ + +extern FAR httpd_server *httpd_initialize(FAR httpd_sockaddr *sa); + +/* Call to unlisten/close socket(s) listening for new connections. */ + +extern void httpd_unlisten(httpd_server *hs); + +/* Call to shut down. */ + +extern void httpd_terminate(httpd_server *hs); + +/* When a listen fd is ready to read, call this. It does the accept() and + * returns an httpd_conn* which includes the fd to read the request from and + * write the response to. Returns an indication of whether the accept() + * failed, succeeded, or if there were no more connections to accept. + * + * In order to minimize malloc()s, the caller passes in the httpd_conn. + * The caller is also responsible for setting initialized to zero before the + * first call using each different httpd_conn. + */ + +extern int httpd_get_conn(httpd_server *hs, int listen_fd, httpd_conn *hc); + +/* Checks whether the data in hc->read_buf constitutes a complete request + * yet. The caller reads data into hc->read_buf[hc->read_idx] and advances + * hc->read_idx. This routine checks what has been read so far, using + * hc->checked_idx and hc->checked_state to keep track, and returns an + * indication of whether there is no complete request yet, there is a + * complete request, or there won't be a valid request due to a syntax error. + */ + +extern int httpd_got_request(httpd_conn *hc); + +/* Parses the request in hc->read_buf. Fills in lots of fields in hc, + * like the URL and the various headers. + * + * Returns -1 on error. + */ + +extern int httpd_parse_request(httpd_conn *hc); + +/* Starts sending data back to the client. In some cases (directories, + * CGI programs), finishes sending by itself - in those cases, hc->file_fd + * is negative. If there is more data to be sent, then hc->file_fd is a file + * stream for the file to send. If you don't have a current timeval + * handy just pass in 0. + * + * Returns -1 on error. + */ + +extern int httpd_start_request(httpd_conn *hc, struct timeval *nowP); + +/* Actually sends any buffered response text. */ + +extern void httpd_write_response(httpd_conn *hc); + +/* Call this to close down a connection and free the data. */ + +extern void httpd_close_conn(httpd_conn *hc); + +/* Call this to de-initialize a connection struct and *really* free the + * mallocced strings. + */ + +extern void httpd_destroy_conn(httpd_conn *hc); + +/* Send an error message back to the client. */ + +extern void httpd_send_err(httpd_conn *hc, int status, const char *title, + const char *extraheads, const char *form, const char *arg); + +/* Generate a string representation of a method number. */ + +extern const char *httpd_method_str(int method); + +/* Format a network socket to a string representation. */ + +extern char *httpd_ntoa(httpd_sockaddr * saP); + +/* Set NDELAY mode on a socket. */ + +extern void httpd_set_ndelay(int fd); + +/* Clear NDELAY mode on a socket. */ + +extern void httpd_clear_ndelay(int fd); + +/* Read to requested buffer, accounting for interruptions and EOF */ + +extern int httpd_read(int fd, const void *buf, size_t nbytes); + +/* Write the buffer completely, accounting for interruptions */ + +extern int httpd_write(int fd, const void *buf, size_t nbytes); + +#endif /* CONFIG_THTTPD */ +#endif /* __NETUTILS_THTTPD_LIBHTTPD_H */ + diff --git a/apps/netutils/thttpd/mime_types.h b/apps/netutils/thttpd/mime_types.h new file mode 100644 index 000000000..cd0c514a8 --- /dev/null +++ b/apps/netutils/thttpd/mime_types.h @@ -0,0 +1,279 @@ +/**************************************************************************** + * netutils/thttpd/mime_types.h + * Provides mappings between filename extensions and MIME types and encodings. + * + * Based on mime_encodings.txt and mime_types.txt by Jef Poskanser which + * contained no copyright information. + * + * Copyright (C) 2007-2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_MIME_TYPES_H +#define __NETUTILS_THTTPD_MIME_TYPES_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <sys/types.h> + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct mime_entry +{ + char *ext; + size_t ext_len; + char *val; + size_t val_len; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* A list of file extensions followed by the corresponding MIME encoding. + * Extensions not found in the table proceed to the mime_types table. + * Must be ordered by extension so to support binary searches. + */ + +static struct mime_entry enc_tab[] = +{ + { "Z", 0, "compress", 0 }, + { "gz", 0, "gzip", 0 }, + { "uu", 0, "x-uuencode", 0 }, +}; +static const int n_enc_tab = sizeof(enc_tab) / sizeof(*enc_tab); + +/* A list of file extensions followed by the corresponding MIME type. + * Extensions not found in the table are returned as text/plain. + * Must be ordered by extension so to support binary searches. + */ + +static struct mime_entry typ_tab[] = +{ + { "a", 0, "application/octet-stream", 0 }, + { "aab", 0, "application/x-authorware-bin", 0 }, + { "aam", 0, "application/x-authorware-map", 0 }, + { "aas", 0, "application/x-authorware-seg", 0 }, + { "ai", 0, "application/postscript", 0 }, + { "aif", 0, "audio/x-aiff", 0 }, + { "aifc", 0, "audio/x-aiff", 0 }, + { "aiff", 0, "audio/x-aiff", 0 }, + { "asc", 0, "text/plain", 0 }, + { "asf", 0, "video/x-ms-asf", 0 }, + { "asx", 0, "video/x-ms-asf", 0 }, + { "au", 0, "audio/basic", 0 }, + { "avi", 0, "video/x-msvideo", 0 }, + { "bcpio", 0, "application/x-bcpio", 0 }, + { "bin", 0, "application/octet-stream", 0 }, + { "bmp", 0, "image/bmp", 0 }, + { "cdf", 0, "application/x-netcdf", 0 }, + { "class", 0, "application/x-java-vm", 0 }, + { "cpio", 0, "application/x-cpio", 0 }, + { "cpt", 0, "application/mac-compactpro", 0 }, + { "crl", 0, "application/x-pkcs7-crl", 0 }, + { "crt", 0, "application/x-x509-ca-cert", 0 }, + { "csh", 0, "application/x-csh", 0 }, + { "css", 0, "text/css", 0 }, + { "dcr", 0, "application/x-director", 0 }, + { "dir", 0, "application/x-director", 0 }, + { "djv", 0, "image/vnd.djvu", 0 }, + { "djvu", 0, "image/vnd.djvu", 0 }, + { "dll", 0, "application/octet-stream", 0 }, + { "dms", 0, "application/octet-stream", 0 }, + { "doc", 0, "application/msword", 0 }, + { "dtd", 0, "text/xml", 0 }, + { "dump", 0, "application/octet-stream", 0 }, + { "dvi", 0, "application/x-dvi", 0 }, + { "dxr", 0, "application/x-director", 0 }, + { "eps", 0, "application/postscript", 0 }, + { "etx", 0, "text/x-setext", 0 }, + { "exe", 0, "application/octet-stream", 0 }, + { "ez", 0, "application/andrew-inset", 0 }, + { "fgd", 0, "application/x-director", 0 }, + { "fh", 0, "image/x-freehand", 0 }, + { "fh4", 0, "image/x-freehand", 0 }, + { "fh5", 0, "image/x-freehand", 0 }, + { "fh7", 0, "image/x-freehand", 0 }, + { "fhc", 0, "image/x-freehand", 0 }, + { "gif", 0, "image/gif", 0 }, + { "gtar", 0, "application/x-gtar", 0 }, + { "hdf", 0, "application/x-hdf", 0 }, + { "hqx", 0, "application/mac-binhex40", 0 }, + { "htm", 0, "text/html; charset=%s", 0 }, + { "html", 0, "text/html; charset=%s", 0 }, + { "ice", 0, "x-conference/x-cooltalk", 0 }, + { "ief", 0, "image/ief", 0 }, + { "iges", 0, "model/iges", 0 }, + { "igs", 0, "model/iges", 0 }, + { "iv", 0, "application/x-inventor", 0 }, + { "jar", 0, "application/x-java-archive", 0 }, + { "jfif", 0, "image/jpeg", 0 }, + { "jpe", 0, "image/jpeg", 0 }, + { "jpeg", 0, "image/jpeg", 0 }, + { "jpg", 0, "image/jpeg", 0 }, + { "js", 0, "application/x-javascript", 0 }, + { "kar", 0, "audio/midi", 0 }, + { "latex", 0, "application/x-latex", 0 }, + { "lha", 0, "application/octet-stream", 0 }, + { "lzh", 0, "application/octet-stream", 0 }, + { "m3u", 0, "audio/x-mpegurl", 0 }, + { "man", 0, "application/x-troff-man", 0 }, + { "mathml", 0, "application/mathml+xml", 0 }, + { "me", 0, "application/x-troff-me", 0 }, + { "mesh", 0, "model/mesh", 0 }, + { "mid", 0, "audio/midi", 0 }, + { "midi", 0, "audio/midi", 0 }, + { "mif", 0, "application/vnd.mif", 0 }, + { "mime", 0, "message/rfc822", 0 }, + { "mml", 0, "application/mathml+xml", 0 }, + { "mov", 0, "video/quicktime", 0 }, + { "movie", 0, "video/x-sgi-movie", 0 }, + { "mp2", 0, "audio/mpeg", 0 }, + { "mp3", 0, "audio/mpeg", 0 }, + { "mp4", 0, "video/mp4", 0 }, + { "mpe", 0, "video/mpeg", 0 }, + { "mpeg", 0, "video/mpeg", 0 }, + { "mpg", 0, "video/mpeg", 0 }, + { "mpga", 0, "audio/mpeg", 0 }, + { "ms", 0, "application/x-troff-ms", 0 }, + { "msh", 0, "model/mesh", 0 }, + { "mv", 0, "video/x-sgi-movie", 0 }, + { "mxu", 0, "video/vnd.mpegurl", 0 }, + { "nc", 0, "application/x-netcdf", 0 }, + { "o", 0, "application/octet-stream", 0 }, + { "oda", 0, "application/oda", 0 }, + { "ogg", 0, "application/x-ogg", 0 }, + { "pac", 0, "application/x-ns-proxy-autoconfig", 0 }, + { "pbm", 0, "image/x-portable-bitmap", 0 }, + { "pdb", 0, "chemical/x-pdb", 0 }, + { "pdf", 0, "application/pdf", 0 }, + { "pgm", 0, "image/x-portable-graymap", 0 }, + { "pgn", 0, "application/x-chess-pgn", 0 }, + { "png", 0, "image/png", 0 }, + { "pnm", 0, "image/x-portable-anymap", 0 }, + { "ppm", 0, "image/x-portable-pixmap", 0 }, + { "ppt", 0, "application/vnd.ms-powerpoint", 0 }, + { "ps", 0, "application/postscript", 0 }, + { "qt", 0, "video/quicktime", 0 }, + { "ra", 0, "audio/x-realaudio", 0 }, + { "ram", 0, "audio/x-pn-realaudio", 0 }, + { "ras", 0, "image/x-cmu-raster", 0 }, + { "rdf", 0, "application/rdf+xml", 0 }, + { "rgb", 0, "image/x-rgb", 0 }, + { "rm", 0, "audio/x-pn-realaudio", 0 }, + { "roff", 0, "application/x-troff", 0 }, + { "rpm", 0, "audio/x-pn-realaudio-plugin", 0 }, + { "rss", 0, "application/rss+xml", 0 }, + { "rtf", 0, "text/rtf", 0 }, + { "rtx", 0, "text/richtext", 0 }, + { "sgm", 0, "text/sgml", 0 }, + { "sgml", 0, "text/sgml", 0 }, + { "sh", 0, "application/x-sh", 0 }, + { "shar", 0, "application/x-shar", 0 }, + { "silo", 0, "model/mesh", 0 }, + { "sit", 0, "application/x-stuffit", 0 }, + { "skd", 0, "application/x-koan", 0 }, + { "skm", 0, "application/x-koan", 0 }, + { "skp", 0, "application/x-koan", 0 }, + { "skt", 0, "application/x-koan", 0 }, + { "smi", 0, "application/smil", 0 }, + { "smil", 0, "application/smil", 0 }, + { "snd", 0, "audio/basic", 0 }, + { "so", 0, "application/octet-stream", 0 }, + { "spl", 0, "application/x-futuresplash", 0 }, + { "src", 0, "application/x-wais-source", 0 }, + { "stc", 0, "application/vnd.sun.xml.calc.template", 0 }, + { "std", 0, "application/vnd.sun.xml.draw.template", 0 }, + { "sti", 0, "application/vnd.sun.xml.impress.template", 0 }, + { "stw", 0, "application/vnd.sun.xml.writer.template", 0 }, + { "sv4cpio", 0, "application/x-sv4cpio", 0 }, + { "sv4crc", 0, "application/x-sv4crc", 0 }, + { "svg", 0, "image/svg+xml", 0 }, + { "svgz", 0, "image/svg+xml", 0 }, + { "swf", 0, "application/x-shockwave-flash", 0 }, + { "sxc", 0, "application/vnd.sun.xml.calc", 0 }, + { "sxd", 0, "application/vnd.sun.xml.draw", 0 }, + { "sxg", 0, "application/vnd.sun.xml.writer.global", 0 }, + { "sxi", 0, "application/vnd.sun.xml.impress", 0 }, + { "sxm", 0, "application/vnd.sun.xml.math", 0 }, + { "sxw", 0, "application/vnd.sun.xml.writer", 0 }, + { "t", 0, "application/x-troff", 0 }, + { "tar", 0, "application/x-tar", 0 }, + { "tcl", 0, "application/x-tcl", 0 }, + { "tex", 0, "application/x-tex", 0 }, + { "texi", 0, "application/x-texinfo", 0 }, + { "texinfo", 0, "application/x-texinfo", 0 }, + { "tif", 0, "image/tiff", 0 }, + { "tiff", 0, "image/tiff", 0 }, + { "tr", 0, "application/x-troff", 0 }, + { "tsp", 0, "application/dsptype", 0 }, + { "tsv", 0, "text/tab-separated-values", 0 }, + { "txt", 0, "text/plain; charset=%s", 0 }, + { "ustar", 0, "application/x-ustar", 0 }, + { "vcd", 0, "application/x-cdlink", 0 }, + { "vrml", 0, "model/vrml", 0 }, + { "vx", 0, "video/x-rad-screenplay", 0 }, + { "wav", 0, "audio/x-wav", 0 }, + { "wax", 0, "audio/x-ms-wax", 0 }, + { "wbmp", 0, "image/vnd.wap.wbmp", 0 }, + { "wbxml", 0, "application/vnd.wap.wbxml", 0 }, + { "wm", 0, "video/x-ms-wm", 0 }, + { "wma", 0, "audio/x-ms-wma", 0 }, + { "wmd", 0, "application/x-ms-wmd", 0 }, + { "wml", 0, "text/vnd.wap.wml", 0 }, + { "wmlc", 0, "application/vnd.wap.wmlc", 0 }, + { "wmls", 0, "text/vnd.wap.wmlscript", 0 }, + { "wmlsc", 0, "application/vnd.wap.wmlscriptc", 0 }, + { "wmv", 0, "video/x-ms-wmv", 0 }, + { "wmx", 0, "video/x-ms-wmx", 0 }, + { "wmz", 0, "application/x-ms-wmz", 0 }, + { "wrl", 0, "model/vrml", 0 }, + { "wsrc", 0, "application/x-wais-source", 0 }, + { "wvx", 0, "video/x-ms-wvx", 0 }, + { "xbm", 0, "image/x-xbitmap", 0 }, + { "xht", 0, "application/xhtml+xml", 0 }, + { "xhtml", 0, "application/xhtml+xml", 0 }, + { "xls", 0, "application/vnd.ms-excel", 0 }, + { "xml", 0, "text/xml", 0 }, + { "xpm", 0, "image/x-xpixmap", 0 }, + { "xsl", 0, "text/xml", 0 }, + { "xwd", 0, "image/x-xwindowdump", 0 }, + { "xyz", 0, "chemical/x-xyz", 0 }, + { "zip", 0, "application/zip", 0 }, +}; +static const int n_typ_tab = sizeof(typ_tab) / sizeof(*typ_tab); + +#endif /* __NETUTILS_THTTPD_MIME_TYPES_H */ + diff --git a/apps/netutils/thttpd/tdate_parse.c b/apps/netutils/thttpd/tdate_parse.c new file mode 100644 index 000000000..d9ace1b41 --- /dev/null +++ b/apps/netutils/thttpd/tdate_parse.c @@ -0,0 +1,341 @@ +/**************************************************************************** + * netutils/thttpd/timers.c + * Parse string dates into internal form, stripped-down version + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <ctype.h> +#include <time.h> +#include <debug.h> + +#include "tdate_parse.h" + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +#undef TDATE_PARSE_WORKS /* tdate_parse() doesn't work */ +#undef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct strlong +{ + char *s; + long l; +}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ +static void pound_case(char *str) +{ + for (; *str != '\0'; ++str) + { + if (isupper((int)*str)) + { + *str = tolower((int)*str); + } + } +} +#endif + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ +static int strlong_compare(const void *v1, const void *v2) +{ + return strcmp(((struct strlong *)v1)->s, ((struct strlong *)v2)->s); +} +#endif + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ +static int strlong_search(char *str, struct strlong *tab, int n, long *lP) +{ + int i, h, l, r; + + l = 0; + h = n - 1; + for (;;) + { + i = (h + l) / 2; + r = strcmp(str, tab[i].s); + if (r < 0) + { + h = i - 1; + } + else if (r > 0) + { + l = i + 1; + } + else + { + *lP = tab[i].l; + return 1; + } + + if (h < l) + { + return 0; + } + } +} +#endif + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ +static int scan_wday(char *str_wday, long *tm_wdayP) +{ + static struct strlong wday_tab[] = { + {"sun", 0}, {"sunday", 0}, + {"mon", 1}, {"monday", 1}, + {"tue", 2}, {"tuesday", 2}, + {"wed", 3}, {"wednesday", 3}, + {"thu", 4}, {"thursday", 4}, + {"fri", 5}, {"friday", 5}, + {"sat", 6}, {"saturday", 6}, + }; + static int sorted = 0; + + if (!sorted) + { + (void)qsort(wday_tab, sizeof(wday_tab) / sizeof(struct strlong), + sizeof(struct strlong), strlong_compare); + sorted = 1; + } + pound_case(str_wday); + return strlong_search(str_wday, wday_tab, + sizeof(wday_tab) / sizeof(struct strlong), tm_wdayP); +} +#endif /* Day of week not yet supported by NuttX */ + +#ifdef TDATE_PARSE_WORKS +static int scan_mon(char *str_mon, long *tm_monP) +{ + static struct strlong mon_tab[] = { + {"jan", 0}, {"january", 0}, + {"feb", 1}, {"february", 1}, + {"mar", 2}, {"march", 2}, + {"apr", 3}, {"april", 3}, + {"may", 4}, + {"jun", 5}, {"june", 5}, + {"jul", 6}, {"july", 6}, + {"aug", 7}, {"august", 7}, + {"sep", 8}, {"september", 8}, + {"oct", 9}, {"october", 9}, + {"nov", 10}, {"november", 10}, + {"dec", 11}, {"december", 11}, + }; + static int sorted = 0; + + if (!sorted) + { + (void)qsort(mon_tab, sizeof(mon_tab) / sizeof(struct strlong), + sizeof(struct strlong), strlong_compare); + sorted = 1; + } + pound_case(str_mon); + return strlong_search(str_mon, mon_tab, + sizeof(mon_tab) / sizeof(struct strlong), tm_monP); +} +#endif +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +time_t tdate_parse(char *str) +{ +#ifdef TDATE_PARSE_WORKS /* REVISIT -- doesn't work */ + struct tm tm; + char *cp; + char str_mon[32]; + int tm_year; + int tm_mday; + int tm_hour; + int tm_min; + int tm_sec; + long tm_mon; +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ + char str_wday[32]; + long tm_wday; +#endif + + nvdbg("str: \"%s\"\n", str); + + /* Initialize. */ + + (void)memset((char *)&tm, 0, sizeof(struct tm)); + + /* Skip initial whitespace ourselves - sscanf is clumsy at this. */ + + for (cp = str; *cp == ' ' || *cp == '\t'; ++cp) + { + continue; + } + + /* And do the sscanfs. WARNING: you can add more formats here, but be + * careful! You can easily screw up the parsing of existing formats when + * you add new ones. The order is important. */ + + /* DD-mth-YY HH:MM:SS GMT */ + if (sscanf(cp, "%d-%400[a-zA-Z]-%d %d:%d:%d GMT", + &tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, + &tm_sec) == 6 && scan_mon(str_mon, &tm_mon)) + { + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + } + + /* DD mth YY HH:MM:SS GMT */ + else if (sscanf(cp, "%d %400[a-zA-Z] %d %d:%d:%d GMT", + &tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, + &tm_sec) == 6 && scan_mon(str_mon, &tm_mon)) + { + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + } + + /* HH:MM:SS GMT DD-mth-YY */ + else if (sscanf(cp, "%d:%d:%d GMT %d-%400[a-zA-Z]-%d", + &tm_hour, &tm_min, &tm_sec, &tm_mday, str_mon, + &tm_year) == 6 && scan_mon(str_mon, &tm_mon)) + { + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + } + + /* HH:MM:SS GMT DD mth YY */ + else if (sscanf(cp, "%d:%d:%d GMT %d %400[a-zA-Z] %d", + &tm_hour, &tm_min, &tm_sec, &tm_mday, str_mon, + &tm_year) == 6 && scan_mon(str_mon, &tm_mon)) + { + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + } + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ + /* wdy, DD-mth-YY HH:MM:SS GMT */ + else if (sscanf(cp, "%400[a-zA-Z], %d-%400[a-zA-Z]-%d %d:%d:%d GMT", + str_wday, &tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, + &tm_sec) == 7 && + scan_wday(str_wday, &tm_wday) && scan_mon(str_mon, &tm_mon)) + { + tm.tm_wday = tm_wday; + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + } +#endif /* Day of week not yet supported by NuttX */ + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ + /* wdy, DD mth YY HH:MM:SS GMT */ + else if (sscanf(cp, "%400[a-zA-Z], %d %400[a-zA-Z] %d %d:%d:%d GMT", + str_wday, &tm_mday, str_mon, &tm_year, &tm_hour, &tm_min, + &tm_sec) == 7 && + scan_wday(str_wday, &tm_wday) && scan_mon(str_mon, &tm_mon)) + { + tm.tm_wday = tm_wday; + tm.tm_mday = tm_mday; + tm.tm_mon = tm_mon; + tm.tm_year = tm_year; + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + } +#endif /* Day of week not yet supported by NuttX */ + +#ifdef HAVE_DAY_OF_WEEK /* Day of week not yet supported by NuttX */ + /* wdy mth DD HH:MM:SS GMT YY */ + else if (sscanf(cp, "%400[a-zA-Z] %400[a-zA-Z] %d %d:%d:%d GMT %d", + str_wday, str_mon, &tm_mday, &tm_hour, &tm_min, &tm_sec, + &tm_year) == 7 && + scan_wday(str_wday, &tm_wday) && scan_mon(str_mon, &tm_mon)) + { + tm.tm_wday = tm_wday; + tm.tm_mon = tm_mon; + tm.tm_mday = tm_mday; + tm.tm_hour = tm_hour; + tm.tm_min = tm_min; + tm.tm_sec = tm_sec; + tm.tm_year = tm_year; + } +#endif /* Day of week not yet supported by NuttX */ + else + { + return (time_t) - 1; + } + + if (tm.tm_year > 1900) + { + tm.tm_year -= 1900; + } + else if (tm.tm_year < 70) + { + tm.tm_year += 100; + } + + return mktime(&tm); +#else + return 0; // for now +#endif +} + diff --git a/apps/netutils/thttpd/tdate_parse.h b/apps/netutils/thttpd/tdate_parse.h new file mode 100644 index 000000000..301d5467a --- /dev/null +++ b/apps/netutils/thttpd/tdate_parse.h @@ -0,0 +1,41 @@ +/**************************************************************************** + * netutils/thttpd/fdwatch.h + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in THTTPD: + * + * Copyright © 1995 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_TDATE_PARSE_H +#define __NETUTILS_TDATE_PARSE_H + +extern time_t tdate_parse(char *str); + +#endif /* __NETUTILS_TDATE_PARSE_H */ diff --git a/apps/netutils/thttpd/thttpd.c b/apps/netutils/thttpd/thttpd.c new file mode 100644 index 000000000..3b49c0141 --- /dev/null +++ b/apps/netutils/thttpd/thttpd.c @@ -0,0 +1,861 @@ +/**************************************************************************** + * netutils/thttpd/thttpd.c + * Tiny HTTP Server + * + * Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/time.h> + +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <fcntl.h> +#include <signal.h> +#include <errno.h> +#include <debug.h> + +#include <nuttx/compiler.h> +#include <nuttx/symtab.h> +#include <apps/netutils/thttpd.h> + +#include "config.h" +#include "fdwatch.h" +#include "libhttpd.h" +#include "thttpd_alloc.h" +#include "thttpd_strings.h" +#include "timers.h" + +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifndef MAXPATHLEN +# define MAXPATHLEN 64 +#endif + +/* The connection states */ + +#define CNST_FREE 0 +#define CNST_READING 1 +#define CNST_SENDING 2 +#define CNST_LINGERING 3 + +#define SPARE_FDS 2 +#define AVAILABLE_FDS (CONFIG_NSOCKET_DESCRIPTORS - SPARE_FDS) + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct connect_s +{ + struct connect_s *next; + int conn_state; + httpd_conn *hc; + time_t active_at; + Timer *wakeup_timer; + Timer *linger_timer; + off_t end_offset; /* The final offset+1 of the file to send */ + off_t offset; /* The current offset into the file to send */ + bool eof; /* Set true when length==0 read from file */ +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static httpd_server *hs; +static struct connect_s *free_connections; +static struct connect_s *connects; +static struct fdwatch_s *fw; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void shut_down(void); +static int handle_newconnect(struct timeval *tv, int listen_fd); +static void handle_read(struct connect_s *conn, struct timeval *tv); +static void handle_send(struct connect_s *conn, struct timeval *tv); +static void handle_linger(struct connect_s *conn, struct timeval *tv); +static void finish_connection(struct connect_s *conn, struct timeval *tv); +static void clear_connection(struct connect_s *conn, struct timeval *tv); +static void really_clear_connection(struct connect_s *conn); +static void idle(ClientData client_data, struct timeval *nowP); +static void linger_clear_connection(ClientData client_data, struct timeval *nowP); +static void occasional(ClientData client_data, struct timeval *nowP); + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static void shut_down(void) +{ + int cnum; + + for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum) + { + if (connects[cnum].conn_state != CNST_FREE) + { + httpd_close_conn(connects[cnum].hc); + } + + if (connects[cnum].hc != NULL) + { + httpd_destroy_conn(connects[cnum].hc); + httpd_free((void *)connects[cnum].hc); + connects[cnum].hc = NULL; + } + } + + if (hs) + { + httpd_server *ths = hs; + hs = NULL; + if (ths->listen_fd != -1) + { + fdwatch_del_fd(fw, ths->listen_fd); + } + httpd_terminate(ths); + } + + tmr_destroy(); + httpd_free((void *)connects); +} + +static int handle_newconnect(struct timeval *tv, int listen_fd) +{ + struct connect_s *conn; + ClientData client_data; + + /* This loops until the accept() fails, trying to start new connections as + * fast as possible so we don't overrun the listen queue. + */ + + nvdbg("New connection(s) on listen_fd %d\n", listen_fd); + for (;;) + { + /* Get the next free connection from the free list */ + + conn = free_connections; + + /* Are there any free connections? */ + + if (!conn) + { + /* Out of connection slots. Run the timers, then the existing + * connections, and maybe we'll free up a slot by the time we get + * back here. + */ + + ndbg("No free connections\n"); + tmr_run(tv); + return -1; + } + + /* Make the httpd_conn if necessary */ + + if (!conn->hc) + { + conn->hc = NEW(httpd_conn, 1); + if (conn->hc == NULL) + { + ndbg("out of memory allocating an httpd_conn\n"); + exit(1); + } + + conn->hc->initialized = 0; + } + + /* Get the connection */ + + switch (httpd_get_conn(hs, listen_fd, conn->hc)) + { + /* Some error happened. Run the timers, then the existing + * connections. Maybe the error will clear. + */ + + case GC_FAIL: + tmr_run(tv); + return -1; + + /* No more connections to accept for now */ + + case GC_NO_MORE: + return 0; + + default: + break; + } + + nvdbg("New connection fd %d\n", conn->hc->conn_fd); + + /* Remove the connection entry from the free list */ + + conn->conn_state = CNST_READING; + free_connections = conn->next; + conn->next = NULL; + + client_data.p = conn; + conn->active_at = tv->tv_sec; + conn->wakeup_timer = NULL; + conn->linger_timer = NULL; + conn->offset = 0; + + /* Set the connection file descriptor to no-delay mode */ + + httpd_set_ndelay(conn->hc->conn_fd); + fdwatch_add_fd(fw, conn->hc->conn_fd, conn); + } +} + +static void handle_read(struct connect_s *conn, struct timeval *tv) +{ + ClientData client_data; + httpd_conn *hc = conn->hc; + off_t actual; + int sz; + + /* Is there room in our buffer to read more bytes? */ + + if (hc->read_idx >= hc->read_size) + { + if (hc->read_size > CONFIG_THTTPD_MAXREALLOC) + { + BADREQUEST("MAXREALLOC"); + goto errout_with_400; + } + httpd_realloc_str(&hc->read_buf, &hc->read_size, hc->read_size + CONFIG_THTTPD_REALLOCINCR); + } + + /* Read some more bytes */ + + sz = read(hc->conn_fd, &(hc->read_buf[hc->read_idx]), hc->read_size - hc->read_idx); + if (sz == 0) + { + BADREQUEST("EOF"); + goto errout_with_400; + } + + if (sz < 0) + { + /* Ignore EINTR and EAGAIN. Also ignore EWOULDBLOCK. At first glance + * you would think that connections returned by fdwatch as readable + * should never give an EWOULDBLOCK; however, this apparently can + * happen if a packet gets garbled. + */ + + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) + { + return; + } + + ndbg("read(fd=%d) failed: %d\n", hc->conn_fd, errno); + BADREQUEST("read"); + goto errout_with_400; + } + + hc->read_idx += sz; + conn->active_at = tv->tv_sec; + + /* Do we have a complete request yet? */ + + switch (httpd_got_request(hc)) + { + case GR_NO_REQUEST: + return; + case GR_BAD_REQUEST: + BADREQUEST("httpd_got_request"); + goto errout_with_400; + } + + /* Yes. Try parsing and resolving it */ + + if (httpd_parse_request(hc) < 0) + { + goto errout_with_connection; + } + + /* Start the connection going */ + + if (httpd_start_request(hc, tv) < 0) + { + /* Something went wrong. Close down the connection */ + + goto errout_with_connection; + } + + /* Set up the file offsets to read */ + + conn->eof = false; + if (hc->got_range) + { + conn->offset = hc->range_start; + conn->end_offset = hc->range_end + 1; + } + else + { + conn->offset = 0; + if (hc->bytes_to_send < 0) + { + conn->end_offset = 0; + } + else + { + conn->end_offset = hc->bytes_to_send; + } + } + + /* Check if it's already handled */ + + if (hc->file_fd < 0) + { + /* No file descriptor means someone else is handling it */ + + conn->offset = hc->bytes_sent; + goto errout_with_connection; + } + + if (conn->offset >= conn->end_offset) + { + /* There's nothing to send */ + + goto errout_with_connection; + } + + /* Seek to the offset of the next byte to send */ + + actual = lseek(hc->file_fd, conn->offset, SEEK_SET); + if (actual != conn->offset) + { + ndbg("fseek to %d failed: offset=%d errno=%d\n", conn->offset, actual, errno); + BADREQUEST("lseek"); + goto errout_with_400; + } + + /* We have a valid connection and a file to send to it */ + + conn->conn_state = CNST_SENDING; + client_data.p = conn; + fdwatch_del_fd(fw, hc->conn_fd); + return; + +errout_with_400: + BADREQUEST("errout"); + httpd_send_err(hc, 400, httpd_err400title, "", httpd_err400form, ""); + +errout_with_connection: + finish_connection(conn, tv); + return; +} + +static inline int read_buffer(struct connect_s *conn) +{ + httpd_conn *hc = conn->hc; + ssize_t nread = 0; + + if (hc->buflen < CONFIG_THTTPD_IOBUFFERSIZE && !conn->eof) + { + nread = read(hc->file_fd, &hc->buffer[hc->buflen], + CONFIG_THTTPD_IOBUFFERSIZE - hc->buflen); + if (nread == 0) + { + /* Reading zero bytes means we are at the end of file */ + + conn->end_offset = conn->offset; + conn->eof = true; + } + else if (nread > 0) + { + hc->buflen += nread; + } + } + return nread; +} + +static void handle_send(struct connect_s *conn, struct timeval *tv) +{ + httpd_conn *hc = conn->hc; + int nwritten; + int nread; + + /* Read until the entire file is sent -- this could take awhile!! */ + + while (conn->offset < conn->end_offset) + { + nvdbg("offset: %d end_offset: %d bytes_sent: %d\n", + conn->offset, conn->end_offset, conn->hc->bytes_sent); + + /* Fill the rest of the response buffer with file data */ + + nread = read_buffer(conn); + if (nread < 0) + { + ndbg("File read error: %d\n", errno); + goto errout_clear_connection; + } + nvdbg("Read %d bytes, buflen %d\n", nread, hc->buflen); + + /* Send the buffer */ + + if (hc->buflen > 0) + { + /* httpd_write does not return until all bytes have been sent + * (or an error occurs). + */ + + nwritten = httpd_write(hc->conn_fd, hc->buffer, hc->buflen); + if (nwritten < 0) + { + ndbg("Error sending %s: %d\n", hc->encodedurl, errno); + goto errout_clear_connection; + } + + /* We wrote one full buffer of data (httpd_write does not + * return until the full buffer is written (or an error occurs). + */ + + conn->active_at = tv->tv_sec; + hc->buflen = 0; + + /* And update how much of the file we wrote */ + + conn->offset += nwritten; + conn->hc->bytes_sent += nwritten; + nvdbg("Wrote %d bytes\n", nwritten); + } + } + + /* The file transfer is complete -- finish the connection */ + + nvdbg("Finish connection\n"); + finish_connection(conn, tv); + return; + +errout_clear_connection: + ndbg("Clear connection\n"); + clear_connection(conn, tv); + return; +} + +static void handle_linger(struct connect_s *conn, struct timeval *tv) +{ + httpd_conn *hc = conn->hc; + int ret; + + /* In lingering-close mode we just read and ignore bytes. An error or EOF + * ends things, otherwise we go until a timeout + */ + + ret = read(conn->hc->conn_fd, hc->buffer, CONFIG_THTTPD_IOBUFFERSIZE); + if (ret < 0 && (errno == EINTR || errno == EAGAIN)) + { + return; + } + + if (ret <= 0) + { + really_clear_connection(conn); + } +} + +static void finish_connection(struct connect_s *conn, struct timeval *tv) +{ + /* If we haven't actually sent the buffered response yet, do so now */ + + httpd_write_response(conn->hc); + + /* And clear */ + + clear_connection(conn, tv); +} + +static void clear_connection(struct connect_s *conn, struct timeval *tv) +{ + ClientData client_data; + + if (conn->wakeup_timer != NULL) + { + tmr_cancel(conn->wakeup_timer); + conn->wakeup_timer = 0; + } + + /* This is our version of Apache's lingering_close() routine, which is + * their version of the often-broken SO_LINGER socket option. For why + * this is necessary, see http://www.apache.org/docs/misc/fin_wait_2.html + * What we do is delay the actual closing for a few seconds, while reading + * any bytes that come over the connection. However, we don't want to do + * this unless it's necessary, because it ties up a connection slot and + * file descriptor which means our maximum connection-handling rateis + * lower. So, elsewhere we set a flag when we detect the few + * circumstances that make a lingering close necessary. If the flag isn't + * set we do the real close now. + */ + + if (conn->conn_state == CNST_LINGERING) + { + /* If we were already lingering, shut down for real */ + + tmr_cancel(conn->linger_timer); + conn->linger_timer = NULL; + conn->hc->should_linger = false; + } + else if (conn->hc->should_linger) + { + fdwatch_del_fd(fw, conn->hc->conn_fd); + conn->conn_state = CNST_LINGERING; + fdwatch_add_fd(fw, conn->hc->conn_fd, conn); + client_data.p = conn; + + conn->linger_timer = tmr_create(tv, linger_clear_connection, client_data, + CONFIG_THTTPD_LINGER_MSEC, 0); + if (conn->linger_timer != NULL) + { + return; + } + ndbg("tmr_create(linger_clear_connection) failed\n"); + } + + /* Either we are done lingering, we shouldn't linger, or we failed to setup the linger */ + + really_clear_connection(conn); +} + +static void really_clear_connection(struct connect_s *conn) +{ + fdwatch_del_fd(fw, conn->hc->conn_fd); + httpd_close_conn(conn->hc); + if (conn->linger_timer != NULL) + { + tmr_cancel(conn->linger_timer); + conn->linger_timer = 0; + } + + /* Put the connection structure back on the free list */ + + conn->conn_state = CNST_FREE; + conn->next = free_connections; + free_connections = conn; +} + +static void idle(ClientData client_data, struct timeval *nowP) +{ + int cnum; + struct connect_s *conn; + + for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum) + { + conn = &connects[cnum]; + switch (conn->conn_state) + { + case CNST_READING: + if (nowP->tv_sec - conn->active_at >= CONFIG_THTTPD_IDLE_READ_LIMIT_SEC) + { + ndbg("%s connection timed out reading\n", httpd_ntoa(&conn->hc->client_addr)); + httpd_send_err(conn->hc, 408, httpd_err408title, "", + httpd_err408form, ""); + finish_connection(conn, nowP); + } + break; + + case CNST_SENDING: + if (nowP->tv_sec - conn->active_at >= CONFIG_THTTPD_IDLE_SEND_LIMIT_SEC) + { + ndbg("%s connection timed out sending\n", httpd_ntoa(&conn->hc->client_addr)); + clear_connection(conn, nowP); + } + break; + } + } +} + +static void linger_clear_connection(ClientData client_data, struct timeval *nowP) +{ + struct connect_s *conn; + + nvdbg("Clear connection\n"); + conn = (struct connect_s *) client_data.p; + conn->linger_timer = NULL; + really_clear_connection(conn); +} + +static void occasional(ClientData client_data, struct timeval *nowP) +{ + tmr_cleanup(); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Function: thttpd_main + * + * Description: + * This function is the entrypoint into the THTTPD server. It does not + * return. It may be called, the normal mechanism for starting the server + * is: + * + * 1) Set is g_thttpdsymtab and g_thttpdnsymbols. The user is required + * to provide a symbol table to use for binding CGI programs (if CGI + * is enabled. See examples/nxflat and examples/thttpd for examples of + * how such a symbol table may be created. + * 2) Call task_create() to start thttpd_main() + * + ****************************************************************************/ + +int thttpd_main(int argc, char **argv) +{ + int num_ready; + int cnum; + FAR struct connect_s *conn; + FAR httpd_conn *hc; + httpd_sockaddr sa; + struct timeval tv; +#ifdef CONFIG_THTTPD_DIR + int ret; +#endif + + nvdbg("THTTPD started\n"); + + /* Setup host address */ + +#ifdef CONFIG_NET_IPv6 +# error "IPv6 support not yet implemented" +#else + sa.sin_family = AF_INET; + sa.sin_port = HTONS(CONFIG_THTTPD_PORT); + sa.sin_addr.s_addr = HTONL(CONFIG_THTTPD_IPADDR); +#endif + + /* Initialize the fdwatch package to handle all of the configured + * socket descriptors + */ + + fw = fdwatch_initialize(CONFIG_NSOCKET_DESCRIPTORS); + if (!fw) + { + ndbg("fdwatch initialization failure\n"); + exit(1); + } + + /* Switch directories again if requested */ + +#ifdef CONFIG_THTTPD_DATADIR + if (chdir(CONFIG_THTTPD_DATADIR) < 0) + { + ndbg("chdir to %s: %d\n", CONFIG_THTTPD_DATADIR, errno); + exit(1); + } +#endif + + /* Initialize the timer package */ + + tmr_init(); + + /* Initialize the HTTP layer */ + + nvdbg("Calling httpd_initialize()\n"); + hs = httpd_initialize(&sa); + if (!hs) + { + ndbg("httpd_initialize() failed\n"); + exit(1); + } + + /* Set up the occasional timer */ + + if (tmr_create(NULL, occasional, JunkClientData, CONFIG_THTTPD_OCCASIONAL_MSEC * 1000L, 1) == NULL) + { + ndbg("tmr_create(occasional) failed\n"); + exit(1); + } + + /* Set up the idle timer */ + + if (tmr_create(NULL, idle, JunkClientData, 5 * 1000L, 1) == NULL) + { + ndbg("tmr_create(idle) failed\n"); + exit(1); + + } + + /* Initialize our connections table */ + + connects = NEW(struct connect_s, AVAILABLE_FDS); + if (connects == NULL) + { + ndbg("Out of memory allocating a struct connect_s\n"); + exit(1); + } + + for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum) + { + connects[cnum].conn_state = CNST_FREE; + connects[cnum].next = &connects[cnum + 1]; + connects[cnum].hc = NULL; + } + + connects[AVAILABLE_FDS-1].next = NULL; /* End of link list */ + free_connections = connects; /* Beginning of the link list */ + + if (hs != NULL) + { + if (hs->listen_fd != -1) + { + fdwatch_add_fd(fw, hs->listen_fd, NULL); + } + } + + /* Main loop */ + + nvdbg("Entering the main loop\n"); + (void)gettimeofday(&tv, NULL); + for(;;) + { + /* Do the fd watch */ + + num_ready = fdwatch(fw, tmr_mstimeout(&tv)); + if (num_ready < 0) + { + if (errno == EINTR || errno == EAGAIN) + { + /* Not errors... try again */ + + continue; + } + + ndbg("fdwatch failed: %d\n", errno); + exit(1); + } + + (void)gettimeofday(&tv, NULL); + + if (num_ready == 0) + { + /* No fd's are ready - run the timers */ + + tmr_run(&tv); + continue; + } + + /* Is it a new connection? */ + + if (fdwatch_check_fd(fw, hs->listen_fd)) + { + if (!handle_newconnect(&tv, hs->listen_fd)) + { + /* Go around the loop and do another fdwatch, rather than + * dropping through and processing existing connections. New + * connections always get priority. + */ + + continue; + } + } + + /* Find the connections that need servicing */ + + while ((conn = (struct connect_s*)fdwatch_get_next_client_data(fw)) != (struct connect_s*)-1) + { + if (conn) + { + hc = conn->hc; + if (fdwatch_check_fd(fw, hc->conn_fd)) + { + nvdbg("Handle conn_state %d\n", conn->conn_state); + switch (conn->conn_state) + { + case CNST_READING: + { + handle_read(conn, &tv); + + /* If a GET request was received and a file is ready to + * be sent, then fall through to send the file. + */ + + if (conn->conn_state != CNST_SENDING) + { + break; + } + } + + case CNST_SENDING: + { + /* Send a file -- this really should be performed on a + * separate thread to keep the serve from locking up during + * the write. + */ + + handle_send(conn, &tv); + } + break; + + case CNST_LINGERING: + { + /* Linger close the connection */ + + handle_linger(conn, &tv); + } + break; + } + } + } + } + tmr_run(&tv); + } + + /* The main loop terminated */ + + shut_down(); + ndbg("Exiting\n"); + exit(0); +} + +#endif /* CONFIG_THTTPD */ + diff --git a/apps/netutils/thttpd/thttpd_alloc.c b/apps/netutils/thttpd/thttpd_alloc.c new file mode 100755 index 000000000..71c71397b --- /dev/null +++ b/apps/netutils/thttpd/thttpd_alloc.c @@ -0,0 +1,199 @@ +/**************************************************************************** + * netutils/thttpd/thttpd_alloc.c + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <stdlib.h> +#include <debug.h> +#include <errno.h> + +#include "config.h" +#include "thttpd_alloc.h" + +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifndef MAX +# define MAX(a,b) ((a) > (b) ? (a) : (b)) +#endif + +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +#ifdef CONFIG_THTTPD_MEMDEBUG +static int g_nallocations = 0; +static int g_nfreed = 0; +static size_t g_allocated = 0; +#endif + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/* Generate debugging statistics */ + +#ifdef CONFIG_THTTPD_MEMDEBUG +void httpd_memstats(void) +{ + static struct mallinfo mm; + + ndbg("%d allocations (%lu bytes), %d freed\n", g_nallocations, (unsigned long)g_allocated, g_nfreed); + + /* Get the current memory usage */ + +#ifdef CONFIG_CAN_PASS_STRUCTS + mm = mallinfo(); +#else + (void)mallinfo(&mm); +#endif + ndbg("arena: %08x ordblks: %08x mxordblk: %08x uordblks: %08x fordblks: %08x\n", + mm.arena, mm.ordblks, mm.mxordblk, mm.uordblks, mm.fordblks); +} +#endif + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +#ifdef CONFIG_THTTPD_MEMDEBUG +FAR void *httpd_malloc(size_t nbytes) +{ + void *ptr = malloc(nbytes); + if (!ptr) + { + ndbg("Allocation of %d bytes failed\n", nbytes); + } + else + { + nvdbg("Allocated %d bytes at %p\n", nbytes, ptr); + g_nallocations++; + g_allocated += nbytes; + } + httpd_memstats(); + return ptr; +} +#endif + +#ifdef CONFIG_THTTPD_MEMDEBUG +FAR void *httpd_realloc(FAR void *oldptr, size_t oldsize, size_t newsize) +{ + void *ptr = realloc(oldptr, newsize); + if (!ptr) + { + ndbg("Re-allocation from %d to %d bytes failed\n", + oldsize, newsize); + } + else + { + nvdbg("Re-allocated form %d to %d bytes (from %p to %p)\n", + oldsize, newsize, oldptr, ptr); + g_allocated += (newsize - oldsize); + } + httpd_memstats(); + return ptr; +} +#endif + +#ifdef CONFIG_THTTPD_MEMDEBUG +void httpd_free(FAR void *ptr) +{ + free(ptr); + g_nfreed++; + nvdbg("Freed memory at %p\n", ptr); + httpd_memstats(); +} +#endif + +#ifdef CONFIG_THTTPD_MEMDEBUG +FAR char *httpd_strdup(const char *str) +{ + FAR char *newstr = strdup(str); + if (!newstr) + { + ndbg("strdup of %s failed\n", str); + } + else + { + nvdbg("strdup'ed %s\n", str); + g_nallocations++; + g_allocated += (strlen(str)+1); + } + httpd_memstats(); + return newstr; +} +#endif + +/* Helpers to implement dynamically allocated strings */ + +void httpd_realloc_str(char **pstr, size_t *maxsize, size_t size) +{ + size_t oldsize; + if (*maxsize == 0) + { + *maxsize = MAX(CONFIG_THTTPD_MINSTRSIZE, size + CONFIG_THTTPD_REALLOCINCR); + *pstr = NEW(char, *maxsize + 1); + } + else if (size > *maxsize) + { + oldsize = *maxsize; + *maxsize = MAX(oldsize * 2, size * 5 / 4); + *pstr = httpd_realloc(*pstr, oldsize + 1, *maxsize + 1); + } + else + { + return; + } + + if (!*pstr) + { + ndbg("out of memory reallocating a string to %d bytes\n", *maxsize); + exit(1); + } +} + +#endif /* CONFIG_THTTPD */ diff --git a/apps/netutils/thttpd/thttpd_alloc.h b/apps/netutils/thttpd/thttpd_alloc.h new file mode 100755 index 000000000..1f24bc2e9 --- /dev/null +++ b/apps/netutils/thttpd/thttpd_alloc.h @@ -0,0 +1,78 @@ +/**************************************************************************** + * netutils/thttpd/thttpd_alloc.h + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_HTTDP_ALLOC_H +#define __NETUTILS_THTTPD_HTTDP_ALLOC_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <stdlib.h> +#include <string.h> +#include "config.h" + +#ifdef CONFIG_THTTPD + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/* Allows all memory management calls to be intercepted */ + +#ifdef CONFIG_THTTPD_MEMDEBUG +extern FAR void *httpd_malloc(size_t nbytes); +extern FAR void *httpd_realloc(FAR void *oldptr, size_t oldsize, size_t newsize); +extern void httpd_free(FAR void *ptr); +extern FAR char *httpd_strdup(const char *str); +#else +# define httpd_malloc(n) malloc(n) +# define httpd_realloc(p,o,n) realloc(p,n) +# define httpd_free(p) free(p) +# define httpd_strdup(s) strdup(s) +#endif + +/* Helpers to support allocations in multiples of a type size */ + +#define NEW(t,n) ((t*)httpd_malloc(sizeof(t)*(n))) +#define RENEW(p,t,o,n) ((t*)httpd_realloc((void*)p, sizeof(t)*(o), sizeof(t)*(n))) + +/* Helpers to implement dynamically allocated strings */ + +extern void httpd_realloc_str(char **pstr, size_t *maxsizeP, size_t size); + +#endif /* CONFIG_THTTPD */ +#endif /* __NETUTILS_THTTPD_HTTDP_ALLOC_H */ diff --git a/apps/netutils/thttpd/thttpd_cgi.c b/apps/netutils/thttpd/thttpd_cgi.c new file mode 100755 index 000000000..ee126795a --- /dev/null +++ b/apps/netutils/thttpd/thttpd_cgi.c @@ -0,0 +1,1080 @@ +/**************************************************************************** + * netutils/thttpd/thttpd_cgi.c + * CGI support + * + * Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file libhttpd.c in the original THTTPD package: + * + * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/stat.h> +#include <stdint.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <signal.h> +#include <libgen.h> +#include <errno.h> +#include <debug.h> + +#include <nuttx/symtab.h> +#include <nuttx/binfmt.h> +#include <apps/netutils/thttpd.h> + +#include "config.h" +#include "libhttpd.h" +#include "thttpd_alloc.h" +#include "thttpd_strings.h" +#include "timers.h" +#include "fdwatch.h" + +#if defined(CONFIG_THTTPD) && defined(CONFIG_THTTPD_CGI_PATTERN) + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* CONFIG_THTTPD_CGIDUMP will dump the contents of each transfer to and from the CGI task. */ + +#ifdef CONFIG_THTTPD_CGIDUMP +# define cgi_dumpbuffer(m,a,n) lib_dumpbuffer(m,(FAR const uint8_t*)a,n) +#else +# define cgi_dumpbuffer(m,a,n) +#endif + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +enum cgi_outbuffer_e +{ + CGI_OUTBUFFER_READHEADER = 0, /* Reading header from HTTP client */ + CGI_OUTBUFFER_HEADERREAD, /* Header has been read */ + CGI_OUTBUFFER_HEADERSENT, /* Header has been sent to the CGI program */ + CGI_OUTBUFFER_READDATA, /* Transferring data from CGI to client */ + CGI_OUTBUFFER_DONE, /* Finished */ +}; + +struct cgi_outbuffer_s +{ + enum cgi_outbuffer_e state; /* State of the transfer */ + char *buffer; /* Allocated I/O buffer */ + size_t size; /* Size of the allocation */ + size_t len; /* Amount of valid data in the allocated buffer */ +}; + +struct cgi_inbuffer_s +{ + int contentlength; /* Size of content to send to CGI task */ + int nbytes; /* Number of bytes sent */ + char buffer[CONFIG_THTTPD_CGIINBUFFERSIZE]; /* Fixed size input buffer */ +}; + +struct cgi_conn_s +{ + /* Descriptors */ + + int connfd; /* Socket connect to CGI client */ + int rdfd; /* Pipe read fd */ + int wrfd; /* Pipe write fd */ + + /* Buffering */ + + struct cgi_outbuffer_s outbuf; /* Dynamically sized output buffer */ + struct cgi_inbuffer_s inbuf; /* Fixed size input buffer */ +}; + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void create_environment(httpd_conn *hc); +static char **make_argp(httpd_conn *hc); +static inline int cgi_interpose_input(struct cgi_conn_s *cc); +static inline int cgi_interpose_output(struct cgi_conn_s *cc); +static int cgi_child(int argc, char **argv); + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/* Used to hold off the main task until the CGI tasks have been configured */ + +static sem_t g_cgisem; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/* semaphore helpers */ + +static inline void cgi_semtake(void) +{ + while (sem_wait(&g_cgisem) != 0) + { + /* The only case that an error should occr here is if the wait was\ + * awakened by a signal. + */ + + ASSERT(*get_errno_ptr() == EINTR); + } +} + +static inline void cgi_semgive(void) +{ + sem_post(&g_cgisem); +} + +/* Set up environment variables. Be real careful here to avoid + * letting malicious clients overrun a buffer. We don't have + * to worry about freeing stuff since we're a sub-task. + */ + +static void create_environment(httpd_conn *hc) +{ + char *cp; + char buf[256]; + + setenv("PATH", CONFIG_THTTPD_CGI_PATH, TRUE); +#ifdef CGI_LD_LIBRARY_PATH + setenv("LD_LIBRARY_PATH", CGI_LD_LIBRARY_PATH, TRUE); +#endif /* CGI_LD_LIBRARY_PATH */ + + setenv("SERVER_SOFTWARE", CONFIG_THTTPD_SERVER_SOFTWARE, TRUE); + + /* If vhosting, use that server-name here. */ +#ifdef CONFIG_THTTPD_VHOST + if (hc->vhostname) + { + cp = hc->vhostname; + } + else +#endif + { + cp = hc->hs->hostname; + } + + if (cp) + { + setenv("SERVER_NAME", cp, TRUE); + } + + setenv("GATEWAY_INTERFACE", "CGI/1.1", TRUE); + setenv("SERVER_PROTOCOL", hc->protocol, TRUE); + + (void)snprintf(buf, sizeof(buf), "%d", (int)CONFIG_THTTPD_PORT); + setenv("SERVER_PORT", buf, TRUE); + + setenv("REQUEST_METHOD", httpd_method_str(hc->method), TRUE); + + if (hc->pathinfo[0] != '\0') + { + char *cp2; + size_t l; + + (void)snprintf(buf, sizeof(buf), "/%s", hc->pathinfo); + setenv("PATH_INFO", buf, TRUE); + + l = strlen(httpd_root) + strlen(hc->pathinfo) + 1; + cp2 = NEW(char, l); + if (cp2) + { + (void)snprintf(cp2, l, "%s%s", httpd_root, hc->pathinfo); + setenv("PATH_TRANSLATED", cp2, TRUE); + } + } + + (void)snprintf(buf, sizeof(buf), "/%s",strcmp(hc->origfilename, ".") == 0 ? "" : hc->origfilename); + setenv("SCRIPT_NAME", buf, TRUE); + + if (hc->query[0] != '\0') + { + setenv("QUERY_STRING", hc->query, TRUE); + } + + setenv("REMOTE_ADDR", httpd_ntoa(&hc->client_addr), TRUE); + if (hc->referer[0] != '\0') + { + setenv("HTTP_REFERER", hc->referer, TRUE); + } + + if (hc->useragent[0] != '\0') + { + setenv("HTTP_USER_AGENT", hc->useragent, TRUE); + } + + if (hc->accept[0] != '\0') + { + setenv("HTTP_ACCEPT", hc->accept, TRUE); + } + + if (hc->accepte[0] != '\0') + { + setenv("HTTP_ACCEPT_ENCODING", hc->accepte, TRUE); + } + + if (hc->acceptl[0] != '\0') + { + setenv("HTTP_ACCEPT_LANGUAGE", hc->acceptl, TRUE); + } + + if (hc->cookie[0] != '\0') + { + setenv("HTTP_COOKIE", hc->cookie, TRUE); + } + + if (hc->contenttype[0] != '\0') + { + setenv("CONTENT_TYPE", hc->contenttype, TRUE); + } + + if (hc->hdrhost[0] != '\0') + { + setenv("HTTP_HOST", hc->hdrhost, TRUE); + } + + if (hc->contentlength != -1) + { + (void)snprintf(buf, sizeof(buf), "%lu", (unsigned long)hc->contentlength); + setenv("CONTENT_LENGTH", buf, TRUE); + } + + if (hc->remoteuser[0] != '\0') + { + setenv("REMOTE_USER", hc->remoteuser, TRUE); + } + + if (hc->authorization[0] != '\0') + { + setenv("AUTH_TYPE", "Basic", TRUE); + } + + /* We only support Basic auth at the moment. */ + + if (getenv("TZ") != NULL) + { + setenv("TZ", getenv("TZ"), TRUE); + } + + setenv("CGI_PATTERN", CONFIG_THTTPD_CGI_PATTERN, TRUE); +} + +/* Set up argument vector */ + +static FAR char **make_argp(httpd_conn *hc) +{ + FAR char **argp; + int argn; + char *cp1; + char *cp2; + + /* By allocating an arg slot for every character in the query, plus one + * for the filename and one for the NULL, we are guaranteed to have + * enough. We could actually use strlen/2. + */ + + argp = NEW(char *, strlen(hc->query) + 2); + if (!argp) + { + return NULL; + } + + argp[0] = strrchr(hc->expnfilename, '/'); + if (argp[0]) + { + ++argp[0]; + } + else + { + argp[0] = hc->expnfilename; + } + argn = 1; + + /* According to the CGI spec at http://hoohoo.ncsa.uiuc.edu/cgi/cl.html, + * "The server should search the query information for a non-encoded = + * character to determine if the command line is to be used, if it finds + * one, the command line is not to be used." + */ + + if (strchr(hc->query, '=') == NULL) + { + for (cp1 = cp2 = hc->query; *cp2 != '\0'; ++cp2) + { + if (*cp2 == '+') + { + *cp2 = '\0'; + httpd_strdecode(cp1, cp1); + argp[argn++] = cp1; + cp1 = cp2 + 1; + } + } + + if (cp2 != cp1) + { + httpd_strdecode(cp1, cp1); + argp[argn++] = cp1; + } + } + + argp[argn] = NULL; + return argp; +} + +/* Data is available from the client socket. This routine is used only for POST + * requests. It reads the data from the client and sends it to the child thread. + */ + +static inline int cgi_interpose_input(struct cgi_conn_s *cc) +{ + ssize_t nbytes_read; + ssize_t nbytes_written; + + nllvdbg("nbytes: %d contentlength: %d\n", cc->inbuf.nbytes, cc->inbuf.contentlength); + if (cc->inbuf.nbytes < cc->inbuf.contentlength) + { + do + { + nbytes_read = read(cc->connfd, cc->inbuf.buffer, + MIN(CONFIG_THTTPD_CGIINBUFFERSIZE, cc->inbuf.contentlength - cc->inbuf.nbytes)); + nllvdbg("nbytes_read: %d\n", nbytes_read); + if (nbytes_read < 0) + { + if (errno != EINTR) + { + nlldbg("read failed: %d\n", errno); + return 1; + } + } + } + while (nbytes_read < 0); + + if (nbytes_read > 0) + { + nbytes_written = httpd_write(cc->wrfd, cc->inbuf.buffer, nbytes_read); + nllvdbg("nbytes_written: %d\n", nbytes_written); + if (nbytes_written != nbytes_read) + { + nlldbg("httpd_write failed\n"); + return 1; + } + cgi_dumpbuffer("Sent to CGI:", cc->inbuf.buffer, nbytes_written); + } + + cc->inbuf.nbytes += nbytes_read; + } + + if (cc->inbuf.nbytes >= cc->inbuf.contentlength) + { + /* Special hack to deal with broken browsers that send a LF or CRLF + * after POST data, causing TCP resets - we just read and discard up + * to 2 bytes. Unfortunately this doesn't fix the problem for CGIs + * which avoid the interposer task due to their POST data being + * short. Creating an interposer task for all POST CGIs is + * unacceptably expensive. The eventual fix will come when interposing + * gets integrated into the main loop as a tasklet instead of a task. + */ + + /* Turn on no-delay mode in case we previously cleared it. */ + + httpd_set_ndelay(cc->connfd); + + /* And read up to 2 bytes. */ + + (void)read(cc->connfd, cc->inbuf.buffer, CONFIG_THTTPD_CGIINBUFFERSIZE); + return 1; + } + return 0; +} + +/* This routine is used for parsed-header CGIs. The idea here is that the + * CGI can return special headers such as "Status:" and "Location:" which + * change the return status of the response. Since the return status has to + * be the very first line written out, we have to accumulate all the headers + * and check for the special ones before writing the status. Then we write + * out the saved headers and proceed to echo the rest of the response. + */ + +static inline int cgi_interpose_output(struct cgi_conn_s *cc) +{ + ssize_t nbytes_read; + char *br = NULL; + int status; + const char *title; + char *cp; + + /* Make sure the connection is in blocking mode. It should already be + * blocking, but we might as well be sure. + */ + + httpd_clear_ndelay(cc->connfd); + + /* Loop while there are things we can do without waiting for more input */ + + nllvdbg("state: %d\n", cc->outbuf.state); + switch (cc->outbuf.state) + { + case CGI_OUTBUFFER_READHEADER: + { + /* Slurp in all headers as they become available from the client. */ + + do + { + /* Read until we successfully read data or until an error occurs. + * EAGAIN is not an error, but it is still cause to return. + */ + + nbytes_read = read(cc->rdfd, cc->inbuf.buffer, CONFIG_THTTPD_CGIINBUFFERSIZE); + nllvdbg("Read %d bytes from fd %d\n", nbytes_read, cc->rdfd); + + if (nbytes_read < 0) + { + if (errno != EINTR) + { + if (errno != EAGAIN) + { + nlldbg("read: %d\n", errno); + } + return 1; + } + } + else + { + cgi_dumpbuffer("Received from CGI:", cc->inbuf.buffer, nbytes_read); + } + } + while (nbytes_read < 0); + + /* Check for end-of-file */ + + if (nbytes_read <= 0) + { + nllvdbg("End-of-file\n"); + br = &(cc->outbuf.buffer[cc->outbuf.len]); + cc->outbuf.state = CGI_OUTBUFFER_HEADERREAD; + } + else + { + /* Accumulate more header data */ + + httpd_realloc_str(&cc->outbuf.buffer, &cc->outbuf.size, cc->outbuf.len + nbytes_read); + (void)memcpy(&(cc->outbuf.buffer[cc->outbuf.len]), cc->inbuf.buffer, nbytes_read); + cc->outbuf.len += nbytes_read; + cc->outbuf.buffer[cc->outbuf.len] = '\0'; + nllvdbg("Header bytes accumulated: %d\n", cc->outbuf.len); + + /* Check for end of header */ + + if ((br = strstr(cc->outbuf.buffer, "\r\n\r\n")) != NULL || + (br = strstr(cc->outbuf.buffer, "\012\012")) != NULL) + { + nllvdbg("End-of-header\n"); + cc->outbuf.state = CGI_OUTBUFFER_HEADERREAD; + } + else + { + /* All of the headers have not yet been read ... Return. We + * will be called again when more data is available in the pipe + * connected to the CGI task. + */ + + return 0; + } + } + } + + /* Otherwise, fall through and parse status in the HTTP headers */ + + case CGI_OUTBUFFER_HEADERREAD: + { + /* If there were no headers, bail. */ + + if (cc->outbuf.buffer[0] == '\0') + { + cc->outbuf.state = CGI_OUTBUFFER_DONE; + return 1; + } + + /* Figure out the status. Look for a Status: or Location: header; else if + * there's an HTTP header line, get it from there; else default to 200. + */ + + status = 200; + if (strncmp(cc->outbuf.buffer, "HTTP/", 5) == 0) + { + cp = cc->outbuf.buffer; + cp += strcspn(cp, " \t"); + status = atoi(cp); + } + + if ((cp = strstr(cc->outbuf.buffer, "Status:")) != NULL && + cp < br && (cp == cc->outbuf.buffer || *(cp - 1) == '\012')) + { + cp += 7; + cp += strspn(cp, " \t"); + status = atoi(cp); + } + + if ((cp = strstr(cc->outbuf.buffer, "Location:")) != NULL && + cp < br && (cp == cc->outbuf.buffer || *(cp - 1) == '\012')) + { + status = 302; + } + + /* Write the status line. */ + + nllvdbg("Status: %d\n", status); + switch (status) + { + case 200: + title = ok200title; + break; + + case 302: + title = err302title; + break; + + case 304: + title = err304title; + break; + + case 400: + BADREQUEST("status"); + title = httpd_err400title; + break; + +#ifdef CONFIG_THTTPD_AUTH_FILE + case 401: + title = err401title; + break; +#endif + + case 403: + title = err403title; + break; + + case 404: + title = err404title; + break; + + case 408: + title = httpd_err408title; + break; + + case 500: + INTERNALERROR("status"); + title = err500title; + break; + + case 501: + NOTIMPLEMENTED("status"); + title = err501title; + break; + + case 503: + title = httpd_err503title; + break; + + default: + title = "Something"; + break; + } + + (void)snprintf(cc->inbuf.buffer, CONFIG_THTTPD_CGIINBUFFERSIZE, "HTTP/1.0 %d %s\r\n", status, title); + (void)httpd_write(cc->connfd, cc->inbuf.buffer, strlen(cc->inbuf.buffer)); + + /* Write the saved cc->outbuf.buffer to the client. */ + + (void)httpd_write(cc->connfd, cc->outbuf.buffer, cc->outbuf.len); + } + + /* Then set up to read the data following the header from the CGI program and + * pass it back to the client. We return now; we will be called again when + * data is available on the pipe. + */ + + cc->outbuf.state = CGI_OUTBUFFER_READDATA; + return 0; + + case CGI_OUTBUFFER_READDATA: + { + /* Read data from the pipe. */ + + do + { + /* Read until we successfully read data or until an error occurs. + * EAGAIN is not an error, but it is still cause to return. + */ + + nbytes_read = read(cc->rdfd, cc->inbuf.buffer, CONFIG_THTTPD_CGIINBUFFERSIZE); + nllvdbg("Read %d bytes from fd %d\n", nbytes_read, cc->rdfd); + + if (nbytes_read < 0) + { + if (errno != EINTR) + { + if (errno != EAGAIN) + { + nlldbg("read: %d\n", errno); + } + return 1; + } + } + else + { + cgi_dumpbuffer("Received from CGI:", cc->inbuf.buffer, nbytes_read); + } + } + while (nbytes_read < 0); + + /* Check for end of file */ + + if (nbytes_read == 0) + { + nllvdbg("End-of-file\n"); + cc->outbuf.state = CGI_OUTBUFFER_DONE; + return 1; + } + else + { + /* Forward the data from the CGI program to the client */ + + (void)httpd_write(cc->connfd, cc->inbuf.buffer, nbytes_read); + } + } + break; + + case CGI_OUTBUFFER_DONE: + default: + return 1; + } + return 0; +} + +/* CGI child task. */ + +static int cgi_child(int argc, char **argv) +{ + FAR httpd_conn *hc = (FAR httpd_conn*)strtoul(argv[1], NULL, 16); +#if CONFIG_THTTPD_CGI_TIMELIMIT > 0 + ClientData client_data; +#endif + FAR char **argp; + FAR struct cgi_conn_s *cc; + FAR struct fdwatch_s *fw; + FAR char *directory; + FAR char *dupname; + bool indone; + bool outdone; + int child; + int pipefd[2]; + int nbytes; + int fd; + int ret; + int err = 1; + + /* Use low-level debug out (because the low-level output may survive closing + * all file descriptors + */ + + nllvdbg("Started: %s\n", argv[1]); + + /* Allocate memory and initialize memory for interposing */ + + cc = (FAR struct cgi_conn_s*)httpd_malloc(sizeof(struct cgi_conn_s)); + if (!cc) + { + nlldbg("cgi_conn allocation failed\n"); + close(hc->conn_fd); + goto errout; + } + + cc->connfd = hc->conn_fd; + cc->wrfd = -1; + cc->rdfd = -1; + memset(&cc->outbuf, 0, sizeof(struct cgi_outbuffer_s)); + + /* Update all of the environment variable settings, these will be inherited + * by the CGI task. + */ + + create_environment(hc); + + /* Make the argument vector. */ + + argp = make_argp(hc); + + /* Close all file descriptors EXCEPT for stdin, stdout, stderr and + * hc->conn_fd. We'll keep stderr open for error reporting; stdin and + * stdout will be closed later by dup2(). Keeping stdin and stdout open + * now prevents re-use of fd=0 and 1 by pipe(). + */ + + nllvdbg("Closing descriptors\n"); + for (fd = 3; fd < (CONFIG_NFILE_DESCRIPTORS + CONFIG_NSOCKET_DESCRIPTORS); fd++) + { + /* Keep hc->conn_fd open for obvious reasons */ + + if (fd != hc->conn_fd) + { + close(fd); + } + } + + /* Create pipes that will be interposed between the CGI task's stdin or + * stdout and the socket. + * + * Setup up the STDIN pipe - a pipe to transfer data received on the + * socket to the CGI program. + */ + + nllvdbg("Create STDIN pipe\n"); + ret = pipe(pipefd); + if (ret < 0) + { + nlldbg("STDIN pipe: %d\n", errno); + goto errout_with_cgiconn; + } + else + { + /* Then map the receiving end the pipe to stdin, save the sending end, and + * closing the original receiving end + */ + + ret = dup2(pipefd[0], 0); + + cc->wrfd = pipefd[1]; + close(pipefd[0]); + + if (ret < 0) + { + nlldbg("STDIN dup2: %d\n", errno); + goto errout_with_descriptors; + } + } + + /* Set up the STDOUT pipe - a pipe to transfer data received from the CGI program + * to the client. + */ + + if (ret == 0) + { + nllvdbg("Create STDOUT pipe\n"); + ret = pipe(pipefd); + if (ret < 0) + { + nlldbg("STDOUT pipe: %d\n", errno); + goto errout_with_descriptors; + } + else + { + /* Then map the sending end the pipe to stdout, save the receiving end, and + * closing the original sending end + */ + + ret = dup2(pipefd[1], 1); + + cc->rdfd = pipefd[0]; + close(pipefd[1]); + + if (ret < 0) + { + nlldbg("STDOUT dup2: %d\n", errno); + goto errout_with_descriptors; + } + } + } + + /* chdir to the directory containing the binary. This isn't in the CGI 1.1 + * spec, but it's what other HTTP servers do. + */ + + dupname = httpd_strdup(hc->expnfilename); + if (dupname) + { + directory = dirname(dupname); + if (directory) + { + (void)chdir(directory); /* ignore errors */ + } + httpd_free(dupname); + } + + /* Allocate memory for output buffering */ + + httpd_realloc_str(&cc->outbuf.buffer, &cc->outbuf.size, CONFIG_THTTPD_CGIOUTBUFFERSIZE); + if (!cc->outbuf.buffer) + { + nlldbg("hdr allocation failed\n"); + goto errout_with_descriptors; + } + + /* Create fdwatch structures */ + + fw = fdwatch_initialize(2); + if (!fw) + { + nlldbg("fdwatch allocation failed\n"); + goto errout_with_outbuffer; + } + + /* Run the CGI program. */ + + nllvdbg("Starting CGI: %s\n", hc->expnfilename); + child = exec(hc->expnfilename, (FAR const char **)argp, g_thttpdsymtab, g_thttpdnsymbols); + if (child < 0) + { + /* Something went wrong. */ + + nlldbg("execve %s: %d\n", hc->expnfilename, errno); + goto errout_with_watch; + } + + /* Schedule a kill for the child task in case it runs too long. */ + +#if CONFIG_THTTPD_CGI_TIMELIMIT > 0 + client_data.i = child; + if (tmr_create(NULL, cgi_kill, client_data, CONFIG_THTTPD_CGI_TIMELIMIT * 1000L, 0) == NULL) + { + nlldbg("tmr_create(cgi_kill child) failed\n"); + goto errout_with_watch; + } +#endif + + /* Add the read descriptors to the watch */ + + fdwatch_add_fd(fw, cc->connfd, NULL); + fdwatch_add_fd(fw, cc->rdfd, NULL); + + /* Send any data that is already buffer to the CGI task */ + + nbytes = hc->read_idx - hc->checked_idx; + nllvdbg("nbytes: %d contentlength: %d\n", nbytes, hc->contentlength); + if (nbytes > 0) + { + if (httpd_write(cc->wrfd, &(hc->read_buf[hc->checked_idx]), nbytes) != nbytes) + { + nlldbg("httpd_write failed\n"); + return 1; + } + } + + cc->inbuf.contentlength = hc->contentlength; + cc->inbuf.nbytes = nbytes; + + /* Then perform the interposition */ + + indone = false; + outdone = false; + + nllvdbg("Interposing\n"); + cgi_semgive(); /* Not safe to reference hc after this point */ + do + { + (void)fdwatch(fw, 1000); + + /* Check for incoming data from the remote client to the CGI task */ + + if (!indone && fdwatch_check_fd(fw, cc->connfd)) + { + /* Transfer data from the client to the CGI program (POST) */ + + nllvdbg("Interpose input\n"); + indone = cgi_interpose_input(cc); + if (indone) + { + fdwatch_del_fd(fw, cc->connfd); + } + } + + /* Check for outgoing data from the CGI task to the remote client */ + + if (fdwatch_check_fd(fw, cc->rdfd)) + { + /* Handle receipt of headers and CGI program response (GET) */ + + nllvdbg("Interpose output\n"); + outdone = cgi_interpose_output(cc); + } + + /* No outgoing data... is the child task still running? Use kill() + * kill() with signal number == 0 does not actually send a signal, but + * can be used to check if the target task exists. If the task exists + * but is hung, then you might enable CONFIG_THTTPD_CGI_TIMELIMIT to + * kill the task. However, killing the task could cause other problems + * (consider resetting the microprocessor instead). + */ + + else if (kill(child, 0) != 0) + { + nllvdbg("CGI no longer running: %d\n", errno); + outdone = true; + } + } + while (!outdone); + err = 0; + + /* Get rid of watch structures */ + +errout_with_watch: + fdwatch_uninitialize(fw); + + /* Free output buffer memory */ + +errout_with_outbuffer: + httpd_free(cc->outbuf.buffer); + + /* Close all descriptors */ + +errout_with_descriptors: + close(cc->wrfd); + close(cc->rdfd); + +errout_with_cgiconn: + close(cc->connfd); + httpd_free(cc); + +errout: + nllvdbg("Return %d\n", err); + if (err != 0) + { + INTERNALERROR("errout"); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + httpd_write_response(hc); + cgi_semgive(); + } + return err; +} + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +int cgi(httpd_conn *hc) +{ + char arg[16]; + char *argv[1]; + pid_t child; + int retval = ERROR; + + /* Set up a semaphore to hold off the make THTTPD thread until the CGI + * threads are configured (basically until the file descriptors are all + * dup'ed and can be closed by the main thread). + */ + + sem_init(&g_cgisem, 0, 0); + + if (hc->method == METHOD_GET || hc->method == METHOD_POST) + { +#ifdef CONFIG_THTTPD_CGILIMIT + if (hc->hs->cgi_count >= CONFIG_THTTPD_CGILIMIT) + { + httpd_send_err(hc, 503, httpd_err503title, "", httpd_err503form, + hc->encodedurl); + goto errout_with_sem; + } +#endif + ++hc->hs->cgi_count; + httpd_clear_ndelay(hc->conn_fd); + + /* Start the child task. We use a trampoline task here so that we can + * safely muck with the file descriptors before actually started the CGI + * task. + */ + + snprintf(arg, 16, "%p", hc); /* task_create doesn't handle binary arguments. */ + argv[0] = arg; + +#ifndef CONFIG_CUSTOM_STACK + child = task_create("CGI child", CONFIG_THTTPD_CGI_PRIORITY, + CONFIG_THTTPD_CGI_STACKSIZE, + (main_t)cgi_child, (const char **)argv); +#else + child = task_create("CGI child", CONFIG_THTTPD_CGI_PRIORITY, + (main_t)cgi_child, (const char **)argv); +#endif + if (child < 0) + { + ndbg("task_create: %d\n", errno); + INTERNALERROR("task_create"); + httpd_send_err(hc, 500, err500title, "", err500form, hc->encodedurl); + goto errout_with_sem; + } + + ndbg("Started CGI task %d for file '%s'\n", child, hc->expnfilename); + + /* Wait for the CGI threads to become initialized */ + + cgi_semtake(); + + hc->bytes_sent = CONFIG_THTTPD_CGI_BYTECOUNT; + hc->should_linger = false; + } + else + { + NOTIMPLEMENTED("CGI"); + httpd_send_err(hc, 501, err501title, "", err501form, httpd_method_str(hc->method)); + goto errout_with_sem; + } + + /* Successfully started */ + + retval = OK; + +errout_with_sem: + sem_destroy(&g_cgisem); + return retval; +} + +#if CONFIG_THTTPD_CGI_TIMELIMIT > 0 +static void cgi_kill(ClientData client_data, struct timeval *nowP) +{ + pid_t pid = (pid_t)client_data.i; + + /* task_delete() is a very evil API. It can leave memory stranded! */ + + nlldbg("Killing CGI child: %d\n", pid); + if (task_delete(pid) != 0) + { + nlldbg("task_delete() failed: %d\n", errno); + } +} +#endif + +#endif /* CONFIG_THTTPD && CONFIG_THTTPD_CGI_PATTERN */ + diff --git a/apps/netutils/thttpd/thttpd_cgi.h b/apps/netutils/thttpd/thttpd_cgi.h new file mode 100755 index 000000000..2d98e25ec --- /dev/null +++ b/apps/netutils/thttpd/thttpd_cgi.h @@ -0,0 +1,61 @@ +/****************************************************************************
+ * netutils/thttpd/thttpd_cgi.h
+ * CGI support
+ *
+ * Copyright (C) 2009 Gregory Nutt. All rights reserved.
+ * Author: Gregory Nutt <spudmonkey@racsa.co.cr>
+ *
+ * Derived from the file libhttpd.c in the original THTTPD package:
+ *
+ * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ ****************************************************************************/
+
+#ifndef __HTTPD_CGI_H
+#define __HTTPD_CGI_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include "config.h"
+#include "libhttpd.h"
+
+#if defined(CONFIG_THTTPD) && defined(CONFIG_THTTPD_CGI_PATTERN)
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+extern int cgi(httpd_conn *hc);
+#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
+static void cgi_kill(ClientData client_data, struct timeval *now);
+#endif
+
+#endif /* CONFIG_THTTPD && CONFIG_THTTPD_CGI_PATTERN */
+#endif /* __HTTPD_CGI_H */
diff --git a/apps/netutils/thttpd/thttpd_strings.c b/apps/netutils/thttpd/thttpd_strings.c new file mode 100755 index 000000000..82836ee99 --- /dev/null +++ b/apps/netutils/thttpd/thttpd_strings.c @@ -0,0 +1,179 @@ +/****************************************************************************
+ * netutils/thttpd/thttpd_strings.c
+ * HTTP strings
+ *
+ * Copyright (C) 2009 Gregory Nutt. All rights reserved.
+ * Author: Gregory Nutt <spudmonkey@racsa.co.cr>
+ *
+ * Derived from the file of the same name in the original THTTPD package:
+ *
+ * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <stdio.h>
+#include <string.h>
+#include <ctype.h>
+
+#include "config.h"
+#include "thttpd_strings.h"
+
+#ifdef CONFIG_THTTPD
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+/* This is the 'root' of the Filesystem as seen by the HTTP client */
+
+const char httpd_root[] = CONFIG_THTTPD_PATH;
+
+/* HTPP status */
+
+const char ok200title[] = "OK";
+const char ok206title[] = "Partial Content";
+
+const char err302title[] = "Found";
+const char err302form[] = "The actual URL is '%s'.\n";
+
+const char err304title[] = "Not Modified";
+
+const char httpd_err400title[] = "Bad Request";
+const char httpd_err400form[] = "Your request has bad syntax or is inherently impossible to satisfy.\n";
+
+#ifdef CONFIG_THTTPD_AUTH_FILE
+const char err401title[] = "Unauthorized";
+const char err401form[] = "Authorization required for the URL '%s'.\n";
+#endif
+
+const char err403title[] = "Forbidden";
+#ifndef EXPLICIT_ERROR_PAGES
+const char err403form[] = "You do not have permission to get URL '%s' from this server.\n";
+#endif
+
+const char err404title[] = "Not Found";
+const char err404form[] = "The requested URL '%s' was not found on this server.\n";
+
+const char httpd_err408title[] = "Request Timeout";
+const char httpd_err408form[] = "No request appeared within a reasonable time period.\n";
+
+const char err500title[] = "Internal Error";
+const char err500form[] = "There was an unusual problem serving the requested URL '%s'.\n";
+
+const char err501title[] = "Not Implemented";
+const char err501form[] = "The requested method '%s' is not implemented by this server.\n";
+
+const char httpd_err503title[] = "Service Temporarily Overloaded";
+const char httpd_err503form[] = "The requested URL '%s' is temporarily overloaded. Please try again later.\n";
+
+/* HTML strings */
+
+const char html_crlf[] = "\r\n";
+const char html_html[] = "<HTML>\r\n";
+const char html_endhtml[] = "</HTML>\r\n";
+const char html_hdtitle[] = "<HEAD><TITLE>";
+const char html_titlehd[] = "</TITLE></HEAD>\r\n";
+const char html_body[] = "<BODY BGCOLOR=\"#99cc99\" TEXT=\"#000000\" LINK=\"#2020ff\" VLINK=\"#4040cc\">\r\n";
+const char html_endbody[] = "</BODY>\r\n";
+const char html_hdr2[] = "<H2>";
+const char html_endhdr2[] = "</H2>";
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+static int hexit(char nibble)
+{
+ if (nibble >= '0' && nibble <= '9')
+ {
+ return nibble - '0';
+ }
+ else if (nibble >= 'a' && nibble <= 'f')
+ {
+ return nibble - 'a' + 10;
+ }
+ else if (nibble >= 'A' && nibble <= 'F')
+ {
+ return nibble - 'A' + 10;
+ }
+ return 0;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/* Copies and decodes a string. It's ok for from and to to be the same string. */
+
+void httpd_strdecode(char *to, char *from)
+{
+ for (; *from != '\0'; ++to, ++from)
+ {
+ if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2]))
+ {
+ *to = hexit(from[1]) * 16 + hexit(from[2]);
+ from += 2;
+ }
+ else
+ {
+ *to = *from;
+ }
+ }
+ *to = '\0';
+}
+
+/* Copies and encodes a string. */
+
+#ifdef CONFIG_THTTPD_GENERATE_INDICES
+static void httpd_strencode(char *to, int tosize, char *from)
+{
+ int tolen;
+
+ for (tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from)
+ {
+ if (isalnum(*from) || strchr("/_.-~", *from) != NULL)
+ {
+ *to = *from;
+ ++to;
+ ++tolen;
+ }
+ else
+ {
+ (void)sprintf(to, "%%%02x", (int)*from & 0xff);
+ to += 3;
+ tolen += 3;
+ }
+ }
+ *to = '\0';
+}
+#endif /* CONFIG_THTTPD_GENERATE_INDICES */
+#endif /* CONFIG_THTTPD */
diff --git a/apps/netutils/thttpd/thttpd_strings.h b/apps/netutils/thttpd/thttpd_strings.h new file mode 100755 index 000000000..5bbaf7948 --- /dev/null +++ b/apps/netutils/thttpd/thttpd_strings.h @@ -0,0 +1,123 @@ +/****************************************************************************
+ * netutils/thttpd/thttpd_strings.h
+ * HTTP strings
+ *
+ * Copyright (C) 2009 Gregory Nutt. All rights reserved.
+ * Author: Gregory Nutt <spudmonkey@racsa.co.cr>
+ *
+ * Derived from the file of the same name in the original THTTPD package:
+ *
+ * Copyright © 1995,1998,1999,2000,2001 by Jef Poskanzer <jef@mail.acme.com>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ ****************************************************************************/
+
+#ifndef __NETUTILS_THTTPD_THTTPD_STRINGS_H
+#define __NETUTILS_THTTPD_THTTPD_STRINGS_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include "config.h"
+
+#ifdef CONFIG_THTTPD
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+/* This is the 'root' of the Filesystem as seen by the HTTP client */
+
+extern const char httpd_root[];
+
+/* HTPP status */
+
+extern const char ok200title[];
+extern const char ok206title[];
+
+extern const char err302title[];
+extern const char err302form[];
+
+extern const char err304title[];
+
+extern const char httpd_err400title[];
+extern const char httpd_err400form[];
+
+#ifdef CONFIG_THTTPD_AUTH_FILE
+extern const char err401title[];
+extern const char err401form[];
+#endif
+
+extern const char err403title[];
+#ifndef EXPLICIT_ERROR_PAGES
+extern const char err403form[];
+#endif
+
+extern const char err404title[];
+extern const char err404form[];
+
+extern const char httpd_err408title[];
+extern const char httpd_err408form[];
+
+extern const char err500title[];
+extern const char err500form[];
+
+extern const char err501title[];
+extern const char err501form[];
+
+extern const char httpd_err503title[];
+extern const char httpd_err503form[];
+
+/* HTML strings */
+
+extern const char html_crlf[];
+extern const char html_html[];
+extern const char html_endhtml[];
+extern const char html_hdtitle[];
+extern const char html_titlehd[];
+extern const char html_body[];
+extern const char html_endbody[];
+extern const char html_hdr2[];
+extern const char html_endhdr2[];
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/* Copies and decodes a string. It's ok for from and to to be the same string. */
+
+extern void httpd_strdecode(char *to, char *from);
+
+/* Copies and encodes a string. */
+
+#ifdef CONFIG_THTTPD_GENERATE_INDICES
+extern void httpd_strencode(char *to, int tosize, char *from);
+#endif
+
+#endif /* CONFIG_THTTPD */
+#endif /* __NETUTILS_THTTPD_THTTPD_STRINGS_H */
diff --git a/apps/netutils/thttpd/timers.c b/apps/netutils/thttpd/timers.c new file mode 100644 index 000000000..8edd7b21b --- /dev/null +++ b/apps/netutils/thttpd/timers.c @@ -0,0 +1,365 @@ +/**************************************************************************** + * netutils/thttpd/timers.c + * Simple Timer Routines + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in the original THTTPD package: + * + * Copyright © 1995,1998,2000 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <sys/time.h> + +#include <stdlib.h> +#include <stdio.h> +#include <debug.h> + +#include "thttpd_alloc.h" +#include "timers.h" + +/**************************************************************************** + * Pre-Processor Definitons + ****************************************************************************/ + +#define HASH_SIZE 67 + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static Timer *timers[HASH_SIZE]; +static Timer *free_timers; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +ClientData JunkClientData; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static unsigned int hash(Timer *tmr) +{ + /* We can hash on the trigger time, even though it can change over the + * life of a timer via the periodic bit. + * This is because both of those guys call l_resort(), which * recomputes + * the hash and moves the timer to the appropriate list. + */ + + return ((unsigned int)tmr->time.tv_sec ^ + (unsigned int)tmr->time.tv_usec) % HASH_SIZE; +} + +static void l_add(Timer *tmr) +{ + int h = tmr->hash; + register Timer *tmr2; + register Timer *tmr2prev; + + tmr2 = timers[h]; + if (tmr2 == NULL) + { + /* The list is empty. */ + timers[h] = tmr; + tmr->prev = tmr->next = NULL; + } + else + { + if (tmr->time.tv_sec < tmr2->time.tv_sec || + (tmr->time.tv_sec == tmr2->time.tv_sec && + tmr->time.tv_usec <= tmr2->time.tv_usec)) + { + /* The new timer goes at the head of the list. */ + + timers[h] = tmr; + tmr->prev = NULL; + tmr->next = tmr2; + tmr2->prev = tmr; + } + else + { + /* Walk the list to find the insertion point. */ + + for (tmr2prev = tmr2, tmr2 = tmr2->next; tmr2 != NULL; + tmr2prev = tmr2, tmr2 = tmr2->next) + { + if (tmr->time.tv_sec < tmr2->time.tv_sec || + (tmr->time.tv_sec == tmr2->time.tv_sec && + tmr->time.tv_usec <= tmr2->time.tv_usec)) + { + /* Found it. */ + tmr2prev->next = tmr; + tmr->prev = tmr2prev; + tmr->next = tmr2; + tmr2->prev = tmr; + return; + } + } + + /* Oops, got to the end of the list. Add to tail. */ + + tmr2prev->next = tmr; + tmr->prev = tmr2prev; + tmr->next = NULL; + } + } +} + +static void l_remove(Timer *tmr) +{ + int h = tmr->hash; + + if (tmr->prev == NULL) + { + timers[h] = tmr->next; + } + else + { + tmr->prev->next = tmr->next; + } + + if (tmr->next != NULL) + { + tmr->next->prev = tmr->prev; + } +} + +static void l_resort(Timer *tmr) +{ + /* Remove the timer from its old list. */ + + l_remove(tmr); + + /* Recompute the hash. */ + + tmr->hash = hash(tmr); + + /* And add it back in to its new list, sorted correctly. */ + + l_add(tmr); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +void tmr_init(void) +{ + int h; + + for (h = 0; h < HASH_SIZE; ++h) + { + timers[h] = NULL; + } + + free_timers = NULL; +} + +Timer *tmr_create(struct timeval *now, TimerProc *timer_proc, + ClientData client_data, long msecs, int periodic) +{ + Timer *tmr; + + if (free_timers != NULL) + { + tmr = free_timers; + free_timers = tmr->next; + } + else + { + tmr = (Timer*)httpd_malloc(sizeof(Timer)); + if (!tmr) + { + return NULL; + } + } + + tmr->timer_proc = timer_proc; + tmr->client_data = client_data; + tmr->msecs = msecs; + tmr->periodic = periodic; + + if (now != NULL) + { + tmr->time = *now; + } + else + { + (void)gettimeofday(&tmr->time, NULL); + } + + tmr->time.tv_sec += msecs / 1000L; + tmr->time.tv_usec += (msecs % 1000L) * 1000L; + if (tmr->time.tv_usec >= 1000000L) + { + tmr->time.tv_sec += tmr->time.tv_usec / 1000000L; + tmr->time.tv_usec %= 1000000L; + } + tmr->hash = hash(tmr); + + /* Add the new timer to the proper active list. */ + + l_add(tmr); + return tmr; +} + +long tmr_mstimeout(struct timeval *now) +{ + int h; + int gotone; + long msecs, m; + register Timer *tmr; + + gotone = 0; + msecs = 0; + + /* Since the lists are sorted, we only need to look at the * first timer on + * each one. + */ + + for (h = 0; h < HASH_SIZE; ++h) + { + tmr = timers[h]; + if (tmr != NULL) + { + m = (tmr->time.tv_sec - now->tv_sec) * 1000L + + (tmr->time.tv_usec - now->tv_usec) / 1000L; + if (!gotone) + { + msecs = m; + gotone = 1; + } + else if (m < msecs) + { + msecs = m; + } + } + } + + if (!gotone) + { + return INFTIM; + } + + if (msecs <= 0) + { + msecs = 0; + } + + return msecs; +} + +void tmr_run(struct timeval *now) +{ + int h; + Timer *tmr; + Timer *next; + + for (h = 0; h < HASH_SIZE; ++h) + { + for (tmr = timers[h]; tmr != NULL; tmr = next) + { + next = tmr->next; + + /* Since the lists are sorted, as soon as we find a timer * that isn'tmr + * ready yet, we can go on to the next list + */ + + if (tmr->time.tv_sec > now->tv_sec || + (tmr->time.tv_sec == now->tv_sec && tmr->time.tv_usec > now->tv_usec)) + { + break; + } + + (tmr->timer_proc)(tmr->client_data, now); + if (tmr->periodic) + { + /* Reschedule. */ + + tmr->time.tv_sec += tmr->msecs / 1000L; + tmr->time.tv_usec += (tmr->msecs % 1000L) * 1000L; + if (tmr->time.tv_usec >= 1000000L) + { + tmr->time.tv_sec += tmr->time.tv_usec / 1000000L; + tmr->time.tv_usec %= 1000000L; + } + l_resort(tmr); + } + else + { + tmr_cancel(tmr); + } + } + } +} + +void tmr_cancel(Timer *tmr) +{ + /* Remove it from its active list. */ + + l_remove(tmr); + + /* And put it on the free list. */ + + tmr->next = free_timers; + free_timers = tmr; + tmr->prev = NULL; +} + +void tmr_cleanup(void) +{ + Timer *tmr; + + while (free_timers != NULL) + { + tmr = free_timers; + free_timers = tmr->next; + httpd_free((void*)tmr); + } +} + +void tmr_destroy(void) +{ + int h; + + for (h = 0; h < HASH_SIZE; ++h) + { + while (timers[h] != NULL) + { + tmr_cancel(timers[h]); + } + } + tmr_cleanup(); +} diff --git a/apps/netutils/thttpd/timers.h b/apps/netutils/thttpd/timers.h new file mode 100644 index 000000000..2d28d3558 --- /dev/null +++ b/apps/netutils/thttpd/timers.h @@ -0,0 +1,136 @@ +/**************************************************************************** + * netutils/thttpd/timers.h + * Header file for THTTPD timers package + * + * Copyright (C) 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Derived from the file of the same name in THTTPD: + * + * Copyright © 1995,1998,1999,2000 by Jef Poskanzer <jef@mail.acme.com>. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __NETUTILS_THTTPD_TIMERS_H +#define __NETUTILS_THTTPD_TIMERS_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <time.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifndef INFTIM +# define INFTIM -1 +#endif + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +/* ClientData is a random value that tags along with a timer. The client + * can use it for whatever, and it gets passed to the callback when the + * timer triggers. + */ + +typedef union +{ + void *p; + int i; + long l; +} ClientData; + +/* The TimerProc gets called when the timer expires. It gets passed + * the ClientData associated with the timer, and a timeval in case + * it wants to schedule another timer. + */ + +typedef void TimerProc(ClientData client_data, struct timeval *nowP); + +/* The Timer struct. */ + +typedef struct TimerStruct +{ + TimerProc *timer_proc; + ClientData client_data; + long msecs; + int periodic; + struct timeval time; + struct TimerStruct *prev; + struct TimerStruct *next; + int hash; +} Timer; + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +extern ClientData JunkClientData; /* For use when you don't care */ + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +/* Initialize the timer package. */ + +extern void tmr_init(void); + +/* Set up a timer, either periodic or one-shot. Returns (Timer*) 0 on errors. */ + +extern Timer *tmr_create(struct timeval *nowP, TimerProc * timer_proc, + ClientData client_data, long msecs, int periodic); + +/* Returns a timeout in milliseconds indicating how long until the next timer + * triggers. You can just put the call to this routine right in your poll(). + * Returns INFTIM (-1) if no timers are pending. + */ + +extern long tmr_mstimeout(struct timeval *nowP); + +/* Run the list of timers. Your main program needs to call this every so often. */ + +extern void tmr_run(struct timeval *nowP); + +/* Deschedule a timer. Note that non-periodic timers are automatically + * descheduled when they run, so you don't have to call this on them. + */ + +extern void tmr_cancel(Timer *timer); + +/* Clean up the timers package, freeing any unused storage. */ + +extern void tmr_cleanup(void); + +/* Cancel all timers and free storage, usually in preparation for exitting. */ + +extern void tmr_destroy(void); + +#endif /* __NETUTILS_THTTPD_TIMERS_H */ + diff --git a/apps/netutils/uiplib/Makefile b/apps/netutils/uiplib/Makefile new file mode 100644 index 000000000..ef6c65156 --- /dev/null +++ b/apps/netutils/uiplib/Makefile @@ -0,0 +1,103 @@ +############################################################################ +# apps/netutils/uiplib/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# UIP Library + +ASRCS = +CSRCS = uiplib.c uip_sethostaddr.c uip_gethostaddr.c uip_setdraddr.c \ + uip_setnetmask.c uip_parsehttpurl.c uip_server.c + +# No MAC address support for SLIP (Ethernet only) + +ifneq ($(CONFIG_NET_SLIP),y) +CSRCS += uip_setmacaddr.c uip_getmacaddr.c +endif + +# IGMP support + +ifeq ($(CONFIG_NET_IGMP),y) +CSRCS += uip_ipmsfilter.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/uiplib/uip_gethostaddr.c b/apps/netutils/uiplib/uip_gethostaddr.c new file mode 100644 index 000000000..0de639d6c --- /dev/null +++ b/apps/netutils/uiplib/uip_gethostaddr.c @@ -0,0 +1,106 @@ +/**************************************************************************** + * netutils/uiplib/uip_gethostaddr.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> + +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_gethostaddr + * + * Description: + * Get the network driver IP address + * + * Parameters: + * ifname The name of the interface to use + * ipaddr The location to return the IP address + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +#ifdef CONFIG_NET_IPv6 +int uip_gethostaddr(const char *ifname, struct in6_addr *addr) +#else +int uip_gethostaddr(const char *ifname, struct in_addr *addr) +#endif +{ + int ret = ERROR; + if (ifname && addr) + { + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; + strncpy(req.ifr_name, ifname, IFNAMSIZ); + ret = ioctl(sockfd, SIOCGIFADDR, (unsigned long)&req); + if (!ret) + { +#ifdef CONFIG_NET_IPv6 +#error "req.ifr_addr.s_addr not big enough for IPv6 address" + memcpy(addr, &req.ifr_addr, sizeof(struct in6_addr)); +#else + memcpy(addr, &req.ifr_addr, sizeof(struct in_addr)); +#endif + } + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uip_getmacaddr.c b/apps/netutils/uiplib/uip_getmacaddr.c new file mode 100644 index 000000000..c99bc7a7d --- /dev/null +++ b/apps/netutils/uiplib/uip_getmacaddr.c @@ -0,0 +1,104 @@ +/**************************************************************************** + * netutils/uiplib/uip_getmacaddr.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <stdint.h> +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_getmacaddr + * + * Description: + * Get the network driver IP address + * + * Parameters: + * ifname The name of the interface to use + * macaddr The location to return the MAC address + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +int uip_getmacaddr(const char *ifname, uint8_t *macaddr) +{ + int ret = ERROR; + if (ifname && macaddr) + { + /* Get a socket (only so that we get access to the INET subsystem) */ + + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; + memset (&req, 0, sizeof(struct ifreq)); + + /* Put the driver name into the request */ + + strncpy(req.ifr_name, ifname, IFNAMSIZ); + + /* Perform the ioctl to get the MAC address */ + + ret = ioctl(sockfd, SIOCGIFHWADDR, (unsigned long)&req); + if (!ret) + { + /* Return the MAC address */ + + memcpy(macaddr, &req.ifr_hwaddr.sa_data, IFHWADDRLEN); + } + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uip_ipmsfilter.c b/apps/netutils/uiplib/uip_ipmsfilter.c new file mode 100755 index 000000000..ccae4a680 --- /dev/null +++ b/apps/netutils/uiplib/uip_ipmsfilter.c @@ -0,0 +1,116 @@ +/**************************************************************************** + * netutils/uiplib/uip_setmultiaddr.c + * + * Copyright (C) 2010-2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <stdint.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> +#include <debug.h> + +#include <netinet/in.h> +#include <sys/sockio.h> + +#include <apps/netutils/uiplib.h> +#include <apps/netutils/ipmsfilter.h> + +#ifdef CONFIG_NET_IGMP + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: ipmsfilter + * + * Description: + * Add or remove an IP address from a multicast filter set. + * + * Parameters: + * ifname The name of the interface to use, size must less than IMSFNAMSIZ + * multiaddr Multicast group address to add/remove (network byte order) + * fmode MCAST_INCLUDE: Add multicast address + * MCAST_EXCLUDE: Remove multicast address + * + * Return: + * 0 on sucess; Negated errno on failure + * + ****************************************************************************/ + +int ipmsfilter(FAR const char *ifname, FAR const struct in_addr *multiaddr, + uint32_t fmode) +{ + int ret = ERROR; + + nvdbg("ifname: %s muliaddr: %08x fmode: %ld\n", ifname, *multiaddr, fmode); + if (ifname && multiaddr) + { + /* Get a socket (only so that we get access to the INET subsystem) */ + + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ip_msfilter imsf; + + /* Put the driver name into the request */ + + strncpy(imsf.imsf_name, ifname, IMSFNAMSIZ); + + /* Put the new address into the request */ + + imsf.imsf_multiaddr.s_addr = multiaddr->s_addr; + + /* Perforom the ioctl to set the MAC address */ + + imsf.imsf_fmode = fmode; + ret = ioctl(sockfd, SIOCSIPMSFILTER, (unsigned long)&imsf); + close(sockfd); + } + } + return ret; +} + +#endif /* CONFIG_NET_IGM */ diff --git a/apps/netutils/uiplib/uip_parsehttpurl.c b/apps/netutils/uiplib/uip_parsehttpurl.c new file mode 100644 index 000000000..bda5502b7 --- /dev/null +++ b/apps/netutils/uiplib/uip_parsehttpurl.c @@ -0,0 +1,149 @@ +/**************************************************************************** + * netutils/uiplib/uip_parsehttpurl.c + * + * Copyright (C) 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + *****************************************************************************/ + +/**************************************************************************** + * Included Files + *****************************************************************************/ + +#include <nuttx/config.h> + +#include <stdint.h> +#include <string.h> +#include <errno.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Private Data + *****************************************************************************/ + +const char g_http[] = "http://"; +#define HTTPLEN 7 + +/**************************************************************************** + * Public Functions + *****************************************************************************/ + +/**************************************************************************** + * Name: uip_parsehttpurl + ****************************************************************************/ + +int uip_parsehttpurl(const char *url, uint16_t *port, + char *hostname, int hostlen, + char *filename, int namelen) +{ + const char *src = url; + char *dest; + int bytesleft; + int ret = OK; + + /* A valid HTTP URL must begin with http:// if it does not, we will assume + * that it is a file name only, but still return an error. wget() depends + * on this strange behavior. + */ + + if (strncmp(src, g_http, HTTPLEN) != 0) + { + ret = -EINVAL; + } + else + { + /* Skip over the http:// */ + + src += HTTPLEN; + + /* Concatenate the hostname following http:// and up to the termnator */ + + dest = hostname; + bytesleft = hostlen; + while (*src != '\0' && *src != '/' && *src != ' ' && *src != ':') + { + /* Make sure that there is space for another character in the hostname. + * (reserving space for the null terminator) + */ + + if (bytesleft > 1) + { + *dest++ = *src++; + bytesleft--; + } + else + { + ret = -E2BIG; + } + } + *dest = '\0'; + + /* Check if the hostname is following by a port number */ + + if (*src == ':') + { + uint16_t accum = 0; + src++; /* Skip over the colon */ + + while (*src >= '0' && *src <= '9') + { + accum = 10*accum + *src - '0'; + src++; + } + *port = accum; + } + } + + /* The rest of the line is the file name */ + + if (*src == '\0' || *src == ' ') + { + ret = -ENOENT; + } + + /* Make sure the file name starts with exactly one '/' */ + + dest = filename; + bytesleft = namelen; + while (*src == '/') + { + src++; + } + *dest++ = '/'; + bytesleft--; + + /* The copy the rest of the file name to the user buffer */ + + strncpy(dest, src, namelen); + filename[namelen-1] = '\0'; + return ret; +} + diff --git a/apps/netutils/uiplib/uip_server.c b/apps/netutils/uiplib/uip_server.c new file mode 100644 index 000000000..f58f063de --- /dev/null +++ b/apps/netutils/uiplib/uip_server.c @@ -0,0 +1,184 @@ +/**************************************************************************** + * netutils/uiplib/uip_server.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name Gregory Nutt nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <stdint.h> +#include <stdio.h> +#include <unistd.h> +#include <pthread.h> +#include <errno.h> +#include <debug.h> +#include <netinet/in.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_server + * + * Description: + * Implement basic server logic + * + * Parameters: + * portno The port to listen on (in network byte order) + * handler The entrypoint of the task to spawn when a new connection is + * accepted. + * stacksize The stack size needed by the spawned task + * + * Return: + * Does not return unless an error occurs. + * + ****************************************************************************/ + +void uip_server(uint16_t portno, pthread_startroutine_t handler, int stacksize) +{ + struct sockaddr_in myaddr; +#ifdef CONFIG_NET_HAVE_SOLINGER + struct linger ling; +#endif + pthread_t child; + pthread_attr_t attr; + socklen_t addrlen; + int listensd; + int acceptsd; +#ifdef CONFIG_NET_HAVE_REUSEADDR + int optval; +#endif + + /* Create a new TCP socket to use to listen for connections */ + + listensd = socket(PF_INET, SOCK_STREAM, 0); + if (listensd < 0) + { + ndbg("socket failure: %d\n", errno); + return; + } + + /* Set socket to reuse address */ + +#ifdef CONFIG_NET_HAVE_REUSEADDR + optval = 1; + if (setsockopt(listensd, SOL_SOCKET, SO_REUSEADDR, (void*)&optval, sizeof(int)) < 0) + { + ndbg("setsockopt SO_REUSEADDR failure: %d\n", errno); + goto errout_with_socket; + } +#endif + + /* Bind the socket to a local address */ + + myaddr.sin_family = AF_INET; + myaddr.sin_port = portno; + myaddr.sin_addr.s_addr = INADDR_ANY; + + if (bind(listensd, (struct sockaddr*)&myaddr, sizeof(struct sockaddr_in)) < 0) + { + ndbg("bind failure: %d\n", errno); + goto errout_with_socket; + } + + /* Listen for connections on the bound TCP socket */ + + if (listen(listensd, 5) < 0) + { + ndbg("listen failure %d\n", errno); + goto errout_with_socket; + } + + /* Begin accepting connections */ + + nvdbg("Accepting connections on port %d\n", ntohs(portno)); + for (;;) + { + addrlen = sizeof(struct sockaddr_in); + acceptsd = accept(listensd, (struct sockaddr*)&myaddr, &addrlen); + if (acceptsd < 0) + { + ndbg("accept failure: %d\n", errno); + break;; + } + nvdbg("Connection accepted -- spawning sd=%d\n", acceptsd); + + /* Configure to "linger" until all data is sent when the socket is closed */ + +#ifdef CONFIG_NET_HAVE_SOLINGER + ling.l_onoff = 1; + ling.l_linger = 30; /* timeout is seconds */ + if (setsockopt(acceptsd, SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger)) < 0) + { + close(acceptsd); + ndbg("setsockopt SO_LINGER failure: %d\n", errno); + break;; + } +#endif + + /* Create a thread to handle the connection. The socket descriptor is + * provided in as the single argument to the new thread. + */ + + (void)pthread_attr_init(&attr); + (void)pthread_attr_setstacksize(&attr, stacksize); + + if (pthread_create(&child, &attr, handler, (void*)acceptsd) != 0) + { + close(acceptsd); + ndbg("create_create failed\n"); + break; + } + + /* We don't care when/how the child thread exits so detach from it now + * in order to avoid memory leaks. + */ + + (void)pthread_detach(child); + } + +errout_with_socket: + close(listensd); +} diff --git a/apps/netutils/uiplib/uip_setdraddr.c b/apps/netutils/uiplib/uip_setdraddr.c new file mode 100644 index 000000000..79eac5b97 --- /dev/null +++ b/apps/netutils/uiplib/uip_setdraddr.c @@ -0,0 +1,117 @@ +/**************************************************************************** + * netutils/uiplib/uip_setdraddr.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> + +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_setdraddr + * + * Description: + * Set the default router IP address + * + * Parameters: + * ifname The name of the interface to use + * ipaddr The address to set + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +#ifdef CONFIG_NET_IPv6 +int uip_setdraddr(const char *ifname, const struct in6_addr *addr) +#else +int uip_setdraddr(const char *ifname, const struct in_addr *addr) +#endif +{ + int ret = ERROR; + if (ifname && addr) + { + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; +#ifdef CONFIG_NET_IPv6 + struct sockaddr_in6 *inaddr; +#else + struct sockaddr_in *inaddr; +#endif + /* Add the device name to the request */ + + strncpy(req.ifr_name, ifname, IFNAMSIZ); + + /* Add the INET address to the request */ + +#ifdef CONFIG_NET_IPv6 +#error "req.ifr_addr.s_addr not big enough for IPv6 address" + inaddr = (struct sockaddr_in6 *)&req.ifr_addr; + inaddr->sin_family = AF_INET6; + inaddr->sin_port = 0; + memcpy(&inaddr->sin6_addr, addr, sizeof(struct in6_addr)); +#else + inaddr = (struct sockaddr_in *)&req.ifr_addr; + inaddr->sin_family = AF_INET; + inaddr->sin_port = 0; + memcpy(&inaddr->sin_addr, addr, sizeof(struct in_addr)); +#endif + ret = ioctl(sockfd, SIOCSIFDSTADDR, (unsigned long)&req); + close(sockfd); + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uip_sethostaddr.c b/apps/netutils/uiplib/uip_sethostaddr.c new file mode 100644 index 000000000..ccc7526b9 --- /dev/null +++ b/apps/netutils/uiplib/uip_sethostaddr.c @@ -0,0 +1,117 @@ +/**************************************************************************** + * netutils/uiplib/uip_sethostaddr.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> + +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_sethostaddr + * + * Description: + * Set the network driver IP address + * + * Parameters: + * ifname The name of the interface to use + * ipaddr The address to set + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +#ifdef CONFIG_NET_IPv6 +int uip_sethostaddr(const char *ifname, const struct in6_addr *addr) +#else +int uip_sethostaddr(const char *ifname, const struct in_addr *addr) +#endif +{ + int ret = ERROR; + if (ifname && addr) + { + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; +#ifdef CONFIG_NET_IPv6 + struct sockaddr_in6 *inaddr; +#else + struct sockaddr_in *inaddr; +#endif + /* Add the device name to the request */ + + strncpy(req.ifr_name, ifname, IFNAMSIZ); + + /* Add the INET address to the request */ + +#ifdef CONFIG_NET_IPv6 +#error "req.ifr_addr.s_addr not big enough for IPv6 address" + inaddr = (struct sockaddr_in6 *)&req.ifr_addr; + inaddr->sin_family = AF_INET6; + inaddr->sin_port = 0; + memcpy(&inaddr->sin6_addr, addr, sizeof(struct in6_addr)); +#else + inaddr = (struct sockaddr_in *)&req.ifr_addr; + inaddr->sin_family = AF_INET; + inaddr->sin_port = 0; + memcpy(&inaddr->sin_addr, addr, sizeof(struct in_addr)); +#endif + ret = ioctl(sockfd, SIOCSIFADDR, (unsigned long)&req); + close(sockfd); + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uip_setmacaddr.c b/apps/netutils/uiplib/uip_setmacaddr.c new file mode 100644 index 000000000..28188b7f8 --- /dev/null +++ b/apps/netutils/uiplib/uip_setmacaddr.c @@ -0,0 +1,114 @@ +/**************************************************************************** + * netutils/uiplib/uip_setmacaddr.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <stdint.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifdef CONFIG_NET_IPv6 +# define AF_INETX AF_INET6 +#else +# define AF_INETX AF_INET +#endif + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_setmacaddr + * + * Description: + * Set the network driver MAC address + * + * Parameters: + * ifname The name of the interface to use + * macaddr MAC address to set, size must be IFHWADDRLEN + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +int uip_setmacaddr(const char *ifname, const uint8_t *macaddr) +{ + int ret = ERROR; + if (ifname && macaddr) + { + /* Get a socket (only so that we get access to the INET subsystem) */ + + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; + + /* Put the driver name into the request */ + + strncpy(req.ifr_name, ifname, IFNAMSIZ); + + /* Put the new MAC address into the request */ + + req.ifr_hwaddr.sa_family = AF_INETX; + memcpy(&req.ifr_hwaddr.sa_data, macaddr, IFHWADDRLEN); + + /* Perforom the ioctl to set the MAC address */ + + ret = ioctl(sockfd, SIOCSIFHWADDR, (unsigned long)&req); + close(sockfd); + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uip_setnetmask.c b/apps/netutils/uiplib/uip_setnetmask.c new file mode 100644 index 000000000..2cdc38474 --- /dev/null +++ b/apps/netutils/uiplib/uip_setnetmask.c @@ -0,0 +1,116 @@ +/**************************************************************************** + * netutils/uiplib/uip_setnetmask.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#if defined(CONFIG_NET) && CONFIG_NSOCKET_DESCRIPTORS > 0 + +#include <sys/socket.h> +#include <sys/ioctl.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#include <netinet/in.h> +#include <net/if.h> + +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Global Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: uip_setnetmask + * + * Description: + * Set the netmask + * + * Parameters: + * ifname The name of the interface to use + * ipaddr The address to set + * + * Return: + * 0 on sucess; -1 on failure + * + ****************************************************************************/ + +#ifdef CONFIG_NET_IPv6 +int uip_setnetmask(const char *ifname, const struct in6_addr *addr) +#else +int uip_setnetmask(const char *ifname, const struct in_addr *addr) +#endif +{ + int ret = ERROR; + if (ifname && addr) + { + int sockfd = socket(PF_INET, UIPLIB_SOCK_IOCTL, 0); + if (sockfd >= 0) + { + struct ifreq req; +#ifdef CONFIG_NET_IPv6 + struct sockaddr_in6 *inaddr; +#else + struct sockaddr_in *inaddr; +#endif + /* Add the device name to the request */ + + strncpy(req.ifr_name, ifname, IFNAMSIZ); + + /* Add the INET address to the request */ + +#ifdef CONFIG_NET_IPv6 +#error "req.ifr_addr.s_addr not big enough for IPv6 address" + inaddr = (struct sockaddr_in6 *)&req.ifr_addr; + inaddr->sin_family = AF_INET6; + inaddr->sin_port = 0; + memcpy(&inaddr->sin6_addr, addr, sizeof(struct in6_addr)); +#else + inaddr = (struct sockaddr_in *)&req.ifr_addr; + inaddr->sin_family = AF_INET; + inaddr->sin_port = 0; + memcpy(&inaddr->sin_addr, addr, sizeof(struct in_addr)); +#endif + ret = ioctl(sockfd, SIOCSIFNETMASK, (unsigned long)&req); + close(sockfd); + } + } + return ret; +} + +#endif /* CONFIG_NET && CONFIG_NSOCKET_DESCRIPTORS */ diff --git a/apps/netutils/uiplib/uiplib.c b/apps/netutils/uiplib/uiplib.c new file mode 100644 index 000000000..99f716f5c --- /dev/null +++ b/apps/netutils/uiplib/uiplib.c @@ -0,0 +1,95 @@ +/**************************************************************************** + * netutils/uiplib/uiplib.c + * Various uIP library functions. + * + * Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2004, Adam Dunkels and the 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stdint.h> +#include <stdbool.h> + +#include <net/uip/uip.h> +#include <apps/netutils/uiplib.h> + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +bool uiplib_ipaddrconv(const char *addrstr, uint8_t *ipaddr) +{ + unsigned char tmp; + char c; + unsigned char i; + unsigned char j; + + tmp = 0; + + for (i = 0; i < 4; ++i) + { + j = 0; + do + { + c = *addrstr; + ++j; + if (j > 4) + { + return false; + } + if (c == '.' || c == 0) + { + *ipaddr = tmp; + ++ipaddr; + tmp = 0; + } + else if(c >= '0' && c <= '9') + { + tmp = (tmp * 10) + (c - '0'); + } + else + { + return false; + } + ++addrstr; + } + while(c != '.' && c != 0); + } + return true; +} diff --git a/apps/netutils/webclient/Makefile b/apps/netutils/webclient/Makefile new file mode 100644 index 000000000..597b0c5c3 --- /dev/null +++ b/apps/netutils/webclient/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/webclient/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# Web client library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_TCP),y) +CSRCS = webclient.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/webclient/webclient.c b/apps/netutils/webclient/webclient.c new file mode 100644 index 000000000..2c5108a4a --- /dev/null +++ b/apps/netutils/webclient/webclient.c @@ -0,0 +1,583 @@ +/**************************************************************************** + * netutils/webclient/webclient.c + * Implementation of the HTTP client. + * + * Copyright (C) 2007, 2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@dunkels.com> + * Copyright (c) 2002, Adam Dunkels. + * 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 example shows a HTTP client that is able to download web pages + * and files from web servers. It requires a number of callback + * functions to be implemented by the module that utilizes the code: + * webclient_datahandler(). + */ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#ifndef CONFIG_WEBCLIENT_HOST +# include <nuttx/config.h> +# include <nuttx/compiler.h> +# include <debug.h> +#endif + +#include <sys/socket.h> +#include <stdint.h> +#include <stdbool.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> + +#ifdef CONFIG_HAVE_GETHOSTBYNAME +# include <netdb.h> +#else +# include <apps/netutils/resolv.h> +#endif + +#include <arpa/inet.h> +#include <netinet/in.h> +#include <apps/netutils/uiplib.h> +#include <apps/netutils/webclient.h> + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +#define WEBCLIENT_TIMEOUT 100 + +#define WEBCLIENT_STATE_STATUSLINE 0 +#define WEBCLIENT_STATE_HEADERS 1 +#define WEBCLIENT_STATE_DATA 2 +#define WEBCLIENT_STATE_CLOSE 3 + +#define HTTPSTATUS_NONE 0 +#define HTTPSTATUS_OK 1 +#define HTTPSTATUS_MOVED 2 +#define HTTPSTATUS_ERROR 3 + +#define ISO_nl 0x0a +#define ISO_cr 0x0d +#define ISO_space 0x20 + +/**************************************************************************** + * Private Types + ****************************************************************************/ + +struct wget_s +{ + /* Internal status */ + + uint8_t state; + uint8_t httpstatus; + + uint16_t port; /* The port number to use in the connection */ + + /* These describe the just-received buffer of data */ + + FAR char *buffer; /* user-provided buffer */ + int buflen; /* Length of the user provided buffer */ + int offset; /* Offset to the beginning of interesting data */ + int datend; /* Offset+1 to the last valid byte of data in the buffer */ + + /* Buffer HTTP header data and parse line at a time */ + + char line[CONFIG_WEBCLIENT_MAXHTTPLINE]; + int ndx; + +#ifdef CONFIG_WEBCLIENT_GETMIMETYPE + char mimetype[CONFIG_WEBCLIENT_MAXMIMESIZE]; +#endif + char hostname[CONFIG_WEBCLIENT_MAXHOSTNAME]; + char filename[CONFIG_WEBCLIENT_MAXFILENAME]; +}; + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static const char g_http10[] = "HTTP/1.0"; +static const char g_http11[] = "HTTP/1.1"; +#ifdef CONFIG_WEBCLIENT_GETMIMETYPE +static const char g_httpcontenttype[] = "content-type: "; +#endif +static const char g_httphost[] = "host: "; +static const char g_httplocation[] = "location: "; +static const char g_httpget[] = "GET "; + +static const char g_httpuseragentfields[] = + "Connection: close\r\n" + "User-Agent: NuttX/0.4.x (; http://www.nuttx.org/)\r\n\r\n"; + +static const char g_http200[] = "200 "; +static const char g_http301[] = "301 "; +static const char g_http302[] = "302 "; + +static const char g_httpcrnl[] = "\r\n"; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: wget_strcpy + ****************************************************************************/ + +static char *wget_strcpy(char *dest, const char *src) +{ + int len = strlen(src); + memcpy(dest, src, len); + dest[len] = '\0'; + return dest + len; +} + +/**************************************************************************** + * Name: wget_resolvehost + ****************************************************************************/ + +static inline int wget_resolvehost(const char *hostname, in_addr_t *ipaddr) +{ +#ifdef CONFIG_HAVE_GETHOSTBYNAME + + struct hostent *he; + + nvdbg("Getting address of %s\n", hostname); + he = gethostbyname(hostname); + if (!he) + { + ndbg("gethostbyname failed: %d\n", h_errno); + return ERROR; + } + + nvdbg("Using IP address %04x%04x\n", (uint16_t)he->h_addr[1], (uint16_t)he->h_addr[0]); + memcpy(ipaddr, he->h_addr, sizeof(in_addr_t)); + return OK; + +#else + +# ifdef CONFIG_NET_IPv6 + struct sockaddr_in6 addr; +# else + struct sockaddr_in addr; +# endif + + /* First check if the host is an IP address. */ + + if (!uiplib_ipaddrconv(hostname, (uint8_t*)ipaddr)) + { + /* 'host' does not point to a valid address string. Try to resolve + * the host name to an IP address. + */ + + if (resolv_query(hostname, &addr) < 0) + { + /* Needs to set the errno here */ + + return ERROR; + } + + /* Save the host address -- Needs fixed for IPv6 */ + + *ipaddr = addr.sin_addr.s_addr; + } + return OK; + +#endif +} + +/**************************************************************************** + * Name: wget_parsestatus + ****************************************************************************/ + +static inline int wget_parsestatus(struct wget_s *ws) +{ + int offset; + int ndx; + char *dest; + + offset = ws->offset; + ndx = ws->ndx; + + while (offset < ws->datend) + { + ws->line[ndx] = ws->buffer[offset]; + if (ws->line[ndx] == ISO_nl) + { + ws->line[ndx] = '\0'; + if ((strncmp(ws->line, g_http10, strlen(g_http10)) == 0) || + (strncmp(ws->line, g_http11, strlen(g_http11)) == 0)) + { + dest = &(ws->line[9]); + ws->httpstatus = HTTPSTATUS_NONE; + + /* Check for 200 OK */ + + if (strncmp(dest, g_http200, strlen(g_http200)) == 0) + { + ws->httpstatus = HTTPSTATUS_OK; + } + + /* Check for 301 Moved permanently or 302 Found. Location: header line + * will contain the new location. + */ + + else if (strncmp(dest, g_http301, strlen(g_http301)) == 0 || + strncmp(dest, g_http302, strlen(g_http302)) == 0) + { + + ws->httpstatus = HTTPSTATUS_MOVED; + } + } + else + { + return - ECONNABORTED; + } + + /* We're done parsing the status line, so start parsing the HTTP headers. */ + + ws->state = WEBCLIENT_STATE_HEADERS; + break; + } + else + { + offset++; + ndx++; + } + } + + ws->offset = offset; + ws->ndx = ndx; + return OK; +} + +/**************************************************************************** + * Name: wget_parsestatus + ****************************************************************************/ + +static inline int wget_parseheaders(struct wget_s *ws) +{ + int offset; + int ndx; + + offset = ws->offset; + ndx = ws->ndx; + + while (offset < ws->datend) + { + ws->line[ndx] = ws->buffer[offset]; + if (ws->line[ndx] == ISO_nl) + { + /* We have an entire HTTP header line in s.line, so + * we parse it. + */ + + if (ndx > 0) /* Should always be true */ + { + if (ws->line[0] == ISO_cr) + { + /* This was the last header line (i.e., and empty "\r\n"), so + * we are done with the headers and proceed with the actual + * data. + */ + + ws->state = WEBCLIENT_STATE_DATA; + goto exit; + } + + /* Truncate the trailing \r\n */ + + ws->line[ndx-1] = '\0'; + + /* Check for specific HTTP header fields. */ + +#ifdef CONFIG_WEBCLIENT_GETMIMETYPE + if (strncasecmp(ws->line, g_httpcontenttype, strlen(g_httpcontenttype)) == 0) + { + /* Found Content-type field. */ + + char *dest = strchr(ws->line, ';'); + if (dest != NULL) + { + *dest = 0; + } + strncpy(ws->mimetype, ws->line + strlen(g_httpcontenttype), sizeof(ws->mimetype)); + } + else +#endif + if (strncasecmp(ws->line, g_httplocation, strlen(g_httplocation)) == 0) + { + /* Parse the new HTTP host and filename from the URL. Note that + * the return value is ignored. In the event of failure, we + * retain the current location. + */ + + (void)uip_parsehttpurl(ws->line + strlen(g_httplocation), &ws->port, + ws->hostname, CONFIG_WEBCLIENT_MAXHOSTNAME, + ws->filename, CONFIG_WEBCLIENT_MAXFILENAME); + nvdbg("New hostname='%s' filename='%s'\n", ws->hostname, ws->filename); + } + } + + /* We're done parsing this line, so we reset the index to the start + * of the next line. + */ + + ndx = 0; + } + else + { + ndx++; + } + offset++; + } + +exit: + ws->offset = offset; + ws->ndx = ndx; + return OK; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: wget + * + * Description: + * Obtain the requested file from an HTTP server using the GET method. + * + * Note: If the function is passed a host name, it must already be in + * the resolver cache in order for the function to connect to the web + * server. It is therefore up to the calling module to implement the + * resolver calls and the signal handler used for reporting a resolv + * query answer. + * + * Input Parameters + * url - A pointer to a string containing either the full URL to + * the file to get (e.g., http://www.nutt.org/index.html, or + * http://192.168.23.1:80/index.html). + * buffer - A user provided buffer to receive the file data (also + * used for the outgoing GET request + * buflen - The size of the user provided buffer + * callback - As data is obtained from the host, this function is + * to dispose of each block of file data as it is received. + * + * Returned Value: + * 0: if the GET operation completed successfully; + * -1: On a failure with errno set appropriately + * + ****************************************************************************/ + +int wget(FAR const char *url, FAR char *buffer, int buflen, + wget_callback_t callback, FAR void *arg) +{ + struct sockaddr_in server; + struct wget_s ws; + bool redirected; + char *dest; + int sockfd; + int len; + int ret = OK; + + /* Initialize the state structure */ + + memset(&ws, 0, sizeof(struct wget_s)); + ws.buffer = buffer; + ws.buflen = buflen; + ws.port = 80; + + /* Parse the hostname (with optional port number) and filename from the URL */ + + ret = uip_parsehttpurl(url, &ws.port, + ws.hostname, CONFIG_WEBCLIENT_MAXHOSTNAME, + ws.filename, CONFIG_WEBCLIENT_MAXFILENAME); + if (ret != 0) + { + ndbg("Malformed HTTP URL: %s\n", url); + errno = -ret; + return ERROR; + } + nvdbg("hostname='%s' filename='%s'\n", ws.hostname, ws.filename); + + /* The following sequence may repeat indefinitely if we are redirected */ + + do + { + /* Re-initialize portions of the state structure that could have + * been left from the previous time through the loop and should not + * persist with the new connection. + */ + + ws.httpstatus = HTTPSTATUS_NONE; + ws.offset = 0; + ws.datend = 0; + ws.ndx = 0; + + /* Create a socket */ + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd < 0) + { + /* socket failed. It will set the errno appropriately */ + + ndbg("socket failed: %d\n", errno); + return ERROR; + } + + /* Get the server adddress from the host name */ + + server.sin_family = AF_INET; + server.sin_port = htons(ws.port); + ret = wget_resolvehost(ws.hostname, &server.sin_addr.s_addr); + if (ret < 0) + { + /* Could not resolve host (or malformed IP address) */ + + ndbg("Failed to resolve hostname\n"); + ret = -EHOSTUNREACH; + goto errout_with_errno; + } + + /* Connect to server. First we have to set some fields in the + * 'server' address structure. The system will assign me an arbitrary + * local port that is not in use. + */ + + ret = connect(sockfd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)); + if (ret < 0) + { + ndbg("connect failed: %d\n", errno); + goto errout; + } + + /* Send the GET request */ + + dest = ws.buffer; + dest = wget_strcpy(dest, g_httpget); + dest = wget_strcpy(dest, ws.filename); + *dest++ = ISO_space; + dest = wget_strcpy(dest, g_http10); + dest = wget_strcpy(dest, g_httpcrnl); + dest = wget_strcpy(dest, g_httphost); + dest = wget_strcpy(dest, ws.hostname); + dest = wget_strcpy(dest, g_httpcrnl); + dest = wget_strcpy(dest, g_httpuseragentfields); + len = dest - buffer; + + ret = send(sockfd, buffer, len, 0); + if (ret < 0) + { + ndbg("send failed: %d\n", errno); + goto errout; + } + + /* Now loop to get the file sent in response to the GET. This + * loop continues until either we read the end of file (nbytes == 0) + * or until we detect that we have been redirected. + */ + + ws.state = WEBCLIENT_STATE_STATUSLINE; + redirected = false; + for(;;) + { + ws.datend = recv(sockfd, ws.buffer, ws.buflen, 0); + if (ws.datend < 0) + { + ndbg("recv failed: %d\n", errno); + ret = ws.datend; + goto errout_with_errno; + } + else if (ret == 0) + { + close(sockfd); + break; + } + + /* Handle initial parsing of the status line */ + + ws.offset = 0; + if (ws.state == WEBCLIENT_STATE_STATUSLINE) + { + ret = wget_parsestatus(&ws); + if (ret < 0) + { + goto errout_with_errno; + } + } + + /* Parse the HTTP data */ + + if (ws.state == WEBCLIENT_STATE_HEADERS) + { + ret = wget_parseheaders(&ws); + if (ret < 0) + { + goto errout_with_errno; + } + } + + /* Dispose of the data payload */ + + if (ws.state == WEBCLIENT_STATE_DATA) + { + if (ws.httpstatus != HTTPSTATUS_MOVED) + { + /* Let the client decide what to do with the received file */ + + callback(&ws.buffer, ws.offset, ws.datend, &buflen, arg); + } + else + { + redirected = true; + close(sockfd); + break; + } + } + } + } + while (redirected); + return OK; + +errout_with_errno: + errno = -ret; +errout: + close(sockfd); + return ERROR; +} diff --git a/apps/netutils/webserver/Makefile b/apps/netutils/webserver/Makefile new file mode 100644 index 000000000..5072e7782 --- /dev/null +++ b/apps/netutils/webserver/Makefile @@ -0,0 +1,94 @@ +############################################################################ +# apps/netutils/webserver/Makefile +# +# Copyright (C) 2011 Gregory Nutt. All rights reserved. +# Author: Gregory Nutt <spudmonkey@racsa.co.cr> +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# 3. Neither the name NuttX nor the names of its contributors may be +# used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. +# +############################################################################ + +-include $(TOPDIR)/.config +-include $(TOPDIR)/Make.defs +include $(APPDIR)/Make.defs + +# Web server library + +ASRCS = +CSRCS = + +ifeq ($(CONFIG_NET_TCP),y) +CSRCS = httpd.c httpd_fs.c httpd_cgi.c +endif + +AOBJS = $(ASRCS:.S=$(OBJEXT)) +COBJS = $(CSRCS:.c=$(OBJEXT)) + +SRCS = $(ASRCS) $(CSRCS) +OBJS = $(AOBJS) $(COBJS) + +BIN = ../../libapps$(LIBEXT) + +ROOTDEPPATH = --dep-path . + +# Common build + +VPATH = + +all: .built + +$(AOBJS): %$(OBJEXT): %.S + $(call ASSEMBLE, $<, $@) + +$(COBJS): %$(OBJEXT): %.c + $(call COMPILE, $<, $@) + +$(BIN): $(OBJS) + @( for obj in $(OBJS) ; do \ + $(call ARCHIVE, $@, $${obj}); \ + done ; ) + @touch .built + +.built: $(BIN) + +.depend: Makefile $(SRCS) + @$(MKDEP) $(ROOTDEPPATH) \ + $(CC) -- $(CFLAGS) -- $(SRCS) >Make.dep + @touch $@ + +# Register application +depend: .depend + +clean: + @rm -f $(BIN) *.o *~ .*.swp .built + $(call CLEAN) + +distclean: clean + @rm -f Make.dep .depend + +-include Make.dep diff --git a/apps/netutils/webserver/httpd.c b/apps/netutils/webserver/httpd.c new file mode 100644 index 000000000..9322b58dc --- /dev/null +++ b/apps/netutils/webserver/httpd.c @@ -0,0 +1,498 @@ +/**************************************************************************** + * netutils/webserver/httpd.c + * httpd Web server + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * This is a leverage of similar logic from uIP: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2004, Adam Dunkels. + * All rights reserved. + * + * The uIP web server is a very simplistic implementation of an HTTP + * server. It can serve web pages and files from a read-only ROM + * filesystem, and provides a very small scripting language. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> + +#include <sys/types.h> +#include <sys/socket.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <string.h> +#include <pthread.h> +#include <errno.h> +#include <debug.h> + +#include <net/uip/uip.h> +#include <apps/netutils/uiplib.h> +#include <apps/netutils/httpd.h> + +#include "httpd.h" +#include "httpd_cgi.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#define ISO_nl 0x0a +#define ISO_space 0x20 +#define ISO_bang 0x21 +#define ISO_percent 0x25 +#define ISO_period 0x2e +#define ISO_slash 0x2f +#define ISO_colon 0x3a + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +static const char g_httpcontenttypebinary[] = "Content-type: application/octet-stream\r\n\r\n"; +static const char g_httpcontenttypecss[] = "Content-type: text/css\r\n\r\n"; +static const char g_httpcontenttypegif[] = "Content-type: image/gif\r\n\r\n"; +static const char g_httpcontenttypehtml[] = "Content-type: text/html\r\n\r\n"; +static const char g_httpcontenttypejpg[] = "Content-type: image/jpeg\r\n\r\n"; +static const char g_httpcontenttypeplain[] = "Content-type: text/plain\r\n\r\n"; +static const char g_httpcontenttypepng[] = "Content-type: image/png\r\n\r\n"; + +static const char g_httpextensionhtml[] = ".html"; +static const char g_httpextensionshtml[] = ".shtml"; +static const char g_httpextensioncss[] = ".css"; +static const char g_httpextensionpng[] = ".png"; +static const char g_httpextensiongif[] = ".gif"; +static const char g_httpextensionjpg[] = ".jpg"; + +static const char g_http404path[] = "/404.html"; +static const char g_httpindexpath[] = "/index.html"; + +static const char g_httpcmdget[] = "GET "; + +static const char g_httpheader200[] = + "HTTP/1.0 200 OK\r\n" + "Server: uIP/1.0 http://www.sics.se/~adam/uip/\r\n" + "Connection: close\r\n"; + +static const char g_httpheader404[] = + "HTTP/1.0 404 Not found\r\n" + "Server: uIP/1.0 http://www.sics.se/~adam/uip/\r\n" + "Connection: close\r\n"; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_HTTPD_DUMPBUFFER +static void httpd_dumpbuffer(FAR const char *msg, FAR const char *buffer, unsigned int nbytes) +{ + /* CONFIG_DEBUG, CONFIG_DEBUG_VERBOSE, and CONFIG_DEBUG_NET have to be + * defined or the following does nothing. + */ + + nvdbgdumpbuffer(msg, (FAR const uint8_t*)buffer, nbytes); +} +#else +# define httpd_dumpbuffer(msg,buffer,nbytes) +#endif + +#ifdef CONFIG_NETUTILS_HTTPD_DUMPPSTATE +static void httpd_dumppstate(struct httpd_state *pstate, const char *msg) +{ +#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_VERBOSE) && defined(CONFIG_DEBUG_NET) + nvdbg("[%d] pstate(%p): [%s]\n", pstate->ht_sockfd, pstate, msg); + nvdbg(" filename: [%s]\n", pstate->ht_filename); + nvdbg(" htfile len: %d\n", pstate->ht_file.len); + nvdbg(" sockfd: %d\n", pstate->ht_sockfd); + nvdbg(" scriptptr: %p\n", pstate->ht_scriptptr); + nvdbg(" scriptlen: %d\n", pstate->ht_scriptlen); + nvdbg(" sndlen: %d\n", pstate->ht_sndlen); +#endif +} +#else +# define httpd_dumppstate(pstate, msg) +#endif + +static void next_scriptstate(struct httpd_state *pstate) +{ + char *p; + p = strchr(pstate->ht_scriptptr, ISO_nl) + 1; + pstate->ht_scriptlen -= (unsigned short)(p - pstate->ht_scriptptr); + pstate->ht_scriptptr = p; +} + +static int handle_script(struct httpd_state *pstate) +{ + int len; + char *ptr; + + while (pstate->ht_file.len > 0) + { + /* Check if we should start executing a script */ + + if (*pstate->ht_file.data == ISO_percent && *(pstate->ht_file.data + 1) == ISO_bang) + { + pstate->ht_scriptptr = pstate->ht_file.data + 3; + pstate->ht_scriptlen = pstate->ht_file.len - 3; + if (*(pstate->ht_scriptptr - 1) == ISO_colon) + { + httpd_fs_open(pstate->ht_scriptptr + 1, &pstate->ht_file); + send(pstate->ht_sockfd, pstate->ht_file.data, pstate->ht_file.len, 0); + } + else + { + httpd_cgi(pstate->ht_scriptptr)(pstate, pstate->ht_scriptptr); + } + next_scriptstate(pstate); + + /* The script is over, so we reset the pointers and continue + * sending the rest of the file + */ + + pstate->ht_file.data = pstate->ht_scriptptr; + pstate->ht_file.len = pstate->ht_scriptlen; + } + else + { + /* See if we find the start of script marker in the block of HTML + * to be sent + */ + + if (pstate->ht_file.len > HTTPD_IOBUFFER_SIZE) + { + len = HTTPD_IOBUFFER_SIZE; + } + else + { + len = pstate->ht_file.len; + } + + if (*pstate->ht_file.data == ISO_percent) + { + ptr = strchr(pstate->ht_file.data + 1, ISO_percent); + } + else + { + ptr = strchr(pstate->ht_file.data, ISO_percent); + } + + if (ptr != NULL && ptr != pstate->ht_file.data) + { + len = (int)(ptr - pstate->ht_file.data); + if (len >= HTTPD_IOBUFFER_SIZE) + { + len = HTTPD_IOBUFFER_SIZE; + } + } + send(pstate->ht_sockfd, pstate->ht_file.data, len, 0); + pstate->ht_file.data += len; + pstate->ht_file.len -= len; + } + } + return OK; +} + +static int httpd_addchunk(struct httpd_state *pstate, const char *buffer, int len) +{ + int newlen; + int chunklen; + int ret; + + do + { + /* Determine the size of the next chunk so that it fits into the buffer */ + + newlen = pstate->ht_sndlen + len; + if (newlen > HTTPD_IOBUFFER_SIZE) + { + newlen = HTTPD_IOBUFFER_SIZE; + chunklen = HTTPD_IOBUFFER_SIZE - pstate->ht_sndlen; + } + else + { + chunklen = len; + } + nvdbg("[%d] sndlen=%d len=%d newlen=%d chunklen=%d\n", + pstate->ht_sockfd, pstate->ht_sndlen, len, newlen, chunklen); + + /* Copy that chunk into the send buffer */ + + memcpy(&pstate->ht_buffer[pstate->ht_sndlen], buffer, chunklen); + + if (newlen >= HTTPD_IOBUFFER_SIZE) + { + /* The buffer is full.. Send what we have and reset to send again */ + + httpd_dumpbuffer("Outgoing buffer", pstate->ht_buffer, newlen); + ret = send(pstate->ht_sockfd, pstate->ht_buffer, newlen, 0); + if (ret < 0) + { + return ret; + } + + newlen = 0; + } + + pstate->ht_sndlen = newlen; + len -= chunklen; + buffer += chunklen; + } + while (len > 0); + return OK; +} + +static int send_headers(struct httpd_state *pstate, const char *statushdr, int len) +{ + char *ptr; + int ret; + + ret = httpd_addchunk(pstate, statushdr, len); + if (ret < 0) + { + return ret; + } + + ptr = strrchr(pstate->ht_filename, ISO_period); + if (ptr == NULL) + { + ret = httpd_addchunk(pstate, g_httpcontenttypebinary, strlen(g_httpcontenttypebinary)); + } + else if (strncmp(g_httpextensionhtml, ptr, strlen(g_httpextensionhtml)) == 0 || + strncmp(g_httpextensionshtml, ptr, strlen(g_httpextensionshtml)) == 0) + { + ret = httpd_addchunk(pstate, g_httpcontenttypehtml, strlen(g_httpcontenttypehtml)); + } + else if (strncmp(g_httpextensioncss, ptr, strlen(g_httpextensioncss)) == 0) + { + ret = httpd_addchunk(pstate, g_httpcontenttypecss, strlen(g_httpcontenttypecss)); + } + else if (strncmp(g_httpextensionpng, ptr, strlen(g_httpextensionpng)) == 0) + { + ret = httpd_addchunk(pstate, g_httpcontenttypepng, strlen(g_httpcontenttypepng)); + } + else if (strncmp(g_httpextensiongif, ptr, strlen(g_httpextensiongif)) == 0) + { + ret = httpd_addchunk(pstate, g_httpcontenttypegif, strlen(g_httpcontenttypegif)); + } + else if (strncmp(g_httpextensionjpg, ptr, strlen(g_httpextensionjpg)) == 0) + { + ret = httpd_addchunk(pstate, g_httpcontenttypejpg, strlen(g_httpcontenttypejpg)); + } + else + { + ret = httpd_addchunk(pstate, g_httpcontenttypeplain, strlen(g_httpcontenttypeplain)); + } + + return ret; +} + +static int httpd_sendfile(struct httpd_state *pstate) +{ + char *ptr; + int ret = ERROR; + + pstate->ht_sndlen = 0; + + nvdbg("[%d] sending file '%s'\n", pstate->ht_sockfd, pstate->ht_filename); + if (!httpd_fs_open(pstate->ht_filename, &pstate->ht_file)) + { + ndbg("[%d] '%s' not found\n", pstate->ht_sockfd, pstate->ht_filename); + memcpy(pstate->ht_filename, g_http404path, strlen(g_http404path)); + httpd_fs_open(g_http404path, &pstate->ht_file); + if (send_headers(pstate, g_httpheader404, strlen(g_httpheader404)) == OK) + { + ret = httpd_addchunk(pstate, pstate->ht_file.data, pstate->ht_file.len); + } + } + else + { + if (send_headers(pstate, g_httpheader200, strlen(g_httpheader200)) == OK) + { + ptr = strchr(pstate->ht_filename, ISO_period); + if (ptr != NULL && + strncmp(ptr, g_httpextensionshtml, strlen(g_httpextensionshtml)) == 0) + { + ret = handle_script(pstate); + } + else + { + ret = httpd_addchunk(pstate, pstate->ht_file.data, pstate->ht_file.len); + } + } + } + + /* Send anything remaining in the buffer */ + + if (ret == OK && pstate->ht_sndlen > 0) + { + httpd_dumpbuffer("Outgoing buffer", pstate->ht_buffer, pstate->ht_sndlen); + if (send(pstate->ht_sockfd, pstate->ht_buffer, pstate->ht_sndlen, 0) < 0) + { + ret = ERROR; + } + } + + return ret; +} + +static inline int httpd_cmd(struct httpd_state *pstate) +{ + ssize_t recvlen; + int i; + + /* Get the next HTTP command. We will handle only GET */ + + recvlen = recv(pstate->ht_sockfd, pstate->ht_buffer, HTTPD_IOBUFFER_SIZE, 0); + if (recvlen < 0) + { + ndbg("[%d] recv failed: %d\n", pstate->ht_sockfd, errno); + return ERROR; + } + httpd_dumpbuffer("Incoming buffer", pstate->ht_buffer, recvlen); + + /* We will handle only GET */ + + if (strncmp(pstate->ht_buffer, g_httpcmdget, strlen(g_httpcmdget)) != 0) + { + ndbg("[%d] Unsupported command\n", pstate->ht_sockfd); + return ERROR; + } + + /* Get the name of the file to provide */ + + if (pstate->ht_buffer[4] != ISO_slash) + { + ndbg("[%d] Missing path\n", pstate->ht_sockfd); + return ERROR; + } + else if (pstate->ht_buffer[5] == ISO_space) + { + strncpy(pstate->ht_filename, g_httpindexpath, strlen(g_httpindexpath)); + } + else + { + for (i = 0; + i < (HTTPD_MAX_FILENAME-1) && pstate->ht_buffer[i+4] != ISO_space; + i++) + { + pstate->ht_filename[i] = pstate->ht_buffer[i+4]; + } + pstate->ht_filename[i]='\0'; + } + nvdbg("[%d] Filename: %s\n", pstate->ht_sockfd, pstate->ht_filename); + + /* Then send the file */ + + return httpd_sendfile(pstate); +} + +/**************************************************************************** + * Name: httpd_handler + * + * Description: + * Each time a new connection to port 80 is made, a new thread is created + * that begins at this entry point. There should be exactly one argument + * and it should be the socket descriptor (+1). + * + ****************************************************************************/ + +static void *httpd_handler(void *arg) +{ + struct httpd_state *pstate = (struct httpd_state *)malloc(sizeof(struct httpd_state)); + int sockfd = (int)arg; + int ret = ERROR; + + nvdbg("[%d] Started\n", sockfd); + + /* Verify that the state structure was successfully allocated */ + + if (pstate) + { + /* Re-initialize the thread state structure */ + + memset(pstate, 0, sizeof(struct httpd_state)); + pstate->ht_sockfd = sockfd; + + /* Then handle the next httpd command */ + + ret = httpd_cmd(pstate); + + /* End of command processing -- Clean up and exit */ + + free(pstate); + } + + /* Exit the task */ + + nvdbg("[%d] Exitting\n", sockfd); + close(sockfd); + return NULL; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ +/**************************************************************************** + * Name: httpd_listen + * + * Description: + * This is the main processing thread for the webserver. It never returns + * unless an error occurs + * + ****************************************************************************/ + +int httpd_listen(void) +{ + /* Execute httpd_handler on each connection to port 80 */ + + uip_server(HTONS(80), httpd_handler, CONFIG_NETUTILS_HTTPDSTACKSIZE); + + /* uip_server only returns on errors */ + + return ERROR; +} + +/**************************************************************************** + * Name: httpd_init + * + * Description: + * This function initializes the web server and should be called at system + * boot-up. + * + ****************************************************************************/ + +void httpd_init(void) +{ +} diff --git a/apps/netutils/webserver/httpd.h b/apps/netutils/webserver/httpd.h new file mode 100644 index 000000000..52073765c --- /dev/null +++ b/apps/netutils/webserver/httpd.h @@ -0,0 +1,118 @@ +/**************************************************************************** + * netutils/webserver/httpd.h + * + * Copyright (C) 2007, 2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2001-2005, Adam Dunkels. + * 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. + * + ****************************************************************************/ + +#ifndef _NETUTILS_WEBSERVER_HTTPD_H +#define _NETUTILS_WEBSERVER_HTTPD_H + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <nuttx/config.h> +#include <stdint.h> +#include <net/uip/uip.h> +#include <net/uip/uipopt.h> + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/* As threads are created to handle each request, a stack must be allocated + * for the thread. Use a default if the user provided no stacksize. + */ + +#ifndef CONFIG_NETUTILS_HTTPDSTACKSIZE +# define CONFIG_NETUTILS_HTTPDSTACKSIZE 4096 +#endif + +#undef CONFIG_NETUTILS_HTTPDFSSTATS +#define CONFIG_NETUTILS_HTTPDFSSTATS 1 + +#ifndef CONFIG_NET_STATISTICS +# undef CONFIG_NETUTILS_HTTPDNETSTATS +#endif + +/* For efficiency reasons, the size of the IO buffer should be a multiple + * of the TCP MSS value. Also, the current design requires that the IO + * buffer be sufficiently large to contain the entire GET request. + */ + +#define HTTPD_IOBUFFER_SIZE (3*UIP_TCP_MSS) + +/* this is the maximum size of a file path */ + +#define HTTPD_MAX_FILENAME 20 + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +struct httpd_fs_file +{ + char *data; + int len; +}; + +struct httpd_state +{ + char ht_buffer[HTTPD_IOBUFFER_SIZE]; /* recv()/send() buffer */ + char ht_filename[HTTPD_MAX_FILENAME]; /* filename from GET command */ + struct httpd_fs_file ht_file; /* Fake file data to send */ + int ht_sockfd; /* The socket descriptor from accept() */ + char *ht_scriptptr; + uint16_t ht_scriptlen; + uint16_t ht_sndlen; +}; + +/**************************************************************************** + * Public Function Prototypes + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_HTTPDFSSTATS +#if CONFIG_NETUTILS_HTTPDFSSTATS == 1 +extern uint16_t httpd_fs_count(char *name); +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ + +/* file must be allocated by caller and will be filled in by the function. */ + +int httpd_fs_open(const char *name, struct httpd_fs_file *file); +void httpd_fs_init(void); + +#endif /* _NETUTILS_WEBSERVER_HTTPD_H */ diff --git a/apps/netutils/webserver/httpd_cgi.c b/apps/netutils/webserver/httpd_cgi.c new file mode 100644 index 000000000..967ef9b9c --- /dev/null +++ b/apps/netutils/webserver/httpd_cgi.c @@ -0,0 +1,170 @@ +/**************************************************************************** + * httpd_cgi.c + * Web server script interface + * Author: Adam Dunkels <adam@sics.se> + * + * Copyright (c) 2001-2006, Adam Dunkels. + * 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. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stdio.h> +#include <string.h> +#include <sys/socket.h> + +#include <nuttx/compiler.h> + +#include <net/uip/uip.h> +#include <apps/netutils/httpd.h> + +#include "httpd_cgi.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Function Prototypes + ****************************************************************************/ + +static void nullfunction(struct httpd_state *pstate, char *ptr); +#ifdef CONFIG_NETUTILS_HTTPDNETSTATS +static void net_stats(struct httpd_state *pstate, char *ptr); +#endif + +#ifdef CONFIG_NETUTILS_HTTPDFILESTATS +static void file_stats(struct httpd_state *pstate, char *ptr); +#endif + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_HTTPDFILESTATS +HTTPD_CGI_CALL(file, "file-stats", file_stats); +#endif +#ifdef CONFIG_NETUTILS_HTTPDNETSTATS +HTTPD_CGI_CALL(net, "net-stats", net_stats); +#endif + +static const struct httpd_cgi_call *calls[] = +{ +#ifdef CONFIG_NETUTILS_HTTPDFILESTATS + &file, +#endif +#ifdef CONFIG_NETUTILS_HTTPDNETSTATS + &net, +#endif + NULL +}; + +static const char closed[] = /* "CLOSED",*/ + {0x43, 0x4c, 0x4f, 0x53, 0x45, 0x44, 0}; +static const char syn_rcvd[] = /* "SYN-RCVD",*/ + {0x53, 0x59, 0x4e, 0x2d, 0x52, 0x43, 0x56, 0x44, 0}; +static const char syn_sent[] = /* "SYN-SENT",*/ + {0x53, 0x59, 0x4e, 0x2d, 0x53, 0x45, 0x4e, 0x54, 0}; +static const char established[] = /* "ESTABLISHED",*/ + {0x45, 0x53, 0x54, 0x41, 0x42, 0x4c, 0x49, 0x53, 0x48, 0x45, 0x44, 0}; +static const char fin_wait_1[] = /* "FIN-WAIT-1",*/ + {0x46, 0x49, 0x4e, 0x2d, 0x57, 0x41, 0x49, 0x54, 0x2d, 0x31, 0}; +static const char fin_wait_2[] = /* "FIN-WAIT-2",*/ + {0x46, 0x49, 0x4e, 0x2d, 0x57, 0x41, 0x49, 0x54, 0x2d, 0x32, 0}; +static const char closing[] = /* "CLOSING",*/ + {0x43, 0x4c, 0x4f, 0x53, 0x49, 0x4e, 0x47, 0}; +static const char time_wait[] = /* "TIME-WAIT,"*/ + {0x54, 0x49, 0x4d, 0x45, 0x2d, 0x57, 0x41, 0x49, 0x54, 0}; +static const char last_ack[] = /* "LAST-ACK"*/ + {0x4c, 0x41, 0x53, 0x54, 0x2d, 0x41, 0x43, 0x4b, 0}; + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: nullfunction + ****************************************************************************/ + +static void nullfunction(struct httpd_state *pstate, char *ptr) +{ +} + +/**************************************************************************** + * Name: net_stats + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_HTTPDNETSTATS +static void net_stats(struct httpd_state *pstate, char *ptr) +{ + char buffer[16]; + int i; + + for (i = 0; i < sizeof(uip_stat) / sizeof(uip_stats_t); i++) + { + snprintf(buffer, 16, "%5u\n", ((uip_stats_t *)&uip_stat)[i]); + send(pstate->ht_sockfd, buffer, strlen(buffer), 0); + } +} +#endif + +/**************************************************************************** + * Name: file_stats + ****************************************************************************/ + +#ifdef CONFIG_NETUTILS_HTTPDFILESTATS +static void file_stats(struct httpd_state *pstate, char *ptr) +{ + char buffer[16]; + char *pcount = strchr(ptr, ' ') + 1; + snprintf(buffer, 16, "%5u", httpd_fs_count(pcount)); + (void)send(pstate->ht_sockfd, buffer, strlen(buffer), 0); +} +#endif + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +httpd_cgifunction httpd_cgi(char *name) +{ + const struct httpd_cgi_call **f; + + /* Find the matching name in the table, return the function. */ + + for(f = calls; *f != NULL; ++f) + { + if(strncmp((*f)->name, name, strlen((*f)->name)) == 0) + { + return (*f)->function; + } + } + return nullfunction; +} diff --git a/apps/netutils/webserver/httpd_cgi.h b/apps/netutils/webserver/httpd_cgi.h new file mode 100644 index 000000000..9547bca33 --- /dev/null +++ b/apps/netutils/webserver/httpd_cgi.h @@ -0,0 +1,69 @@ +/* httpd_cgi.h + * Web server script interface header file + * Author: Adam Dunkels <adam@sics.se> + * + * Copyright (c) 2001, Adam Dunkels. + * 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. + */ + +#ifndef __HTTPD_CGI_H__ +#define __HTTPD_CGI_H__ + +#include <apps/netutils/httpd.h> + +#include "httpd.h" + +typedef void (*httpd_cgifunction)(struct httpd_state *, char *); + +httpd_cgifunction httpd_cgi(char *name); + +struct httpd_cgi_call +{ + const char *name; + httpd_cgifunction function; +}; + +/** + * \brief HTTPD CGI function declaration + * \param name The C variable name of the function + * \param str The string name of the function, used in the script file + * \param function A pointer to the function that implements it + * + * This macro is used for declaring a HTTPD CGI + * function. This function is then added to the list of + * HTTPD CGI functions with the httpd_cgi_add() function. + * + * \hideinitializer + */ +#define HTTPD_CGI_CALL(name, str, function) \ +static void function(struct httpd_state *, char *); \ +static const struct httpd_cgi_call name = {str, function} + +void httpd_cgi_init(void); +#endif /* __HTTPD_CGI_H__ */ + +/** @} */ diff --git a/apps/netutils/webserver/httpd_fs.c b/apps/netutils/webserver/httpd_fs.c new file mode 100644 index 000000000..731f19498 --- /dev/null +++ b/apps/netutils/webserver/httpd_fs.c @@ -0,0 +1,155 @@ +/**************************************************************************** + * netutils/webserver/httpd_fs.c + * + * Copyright (C) 2007-2009, 2011 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Header Files + ****************************************************************************/ + +#include <stdint.h> + +#include <apps/netutils/httpd.h> + +#include "httpd.h" +#include "httpd_fsdata.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +#ifndef NULL +#define NULL 0 +#endif /* NULL */ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +#include "httpd_fsdata.c" + +#if CONFIG_NETUTILS_HTTPDFSSTATS +static uint16_t count[HTTPD_FS_NUMFILES]; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +static uint8_t httpd_fs_strcmp(const char *str1, const char *str2) +{ + int i; + + i = 0; + for (;;) + { + if (str2[i] == 0 || str1[i] == '\r' || str1[i] == '\n') + { + return 0; + } + + if (str1[i] != str2[i]) + { + return 1; + } + + i++; + } +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int httpd_fs_open(const char *name, struct httpd_fs_file *file) +{ +#if CONFIG_NETUTILS_HTTPDFSSTATS + uint16_t i = 0; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ + struct httpd_fsdata_file_noconst *f; + + for(f = (struct httpd_fsdata_file_noconst *)HTTPD_FS_ROOT; + f != NULL; + f = (struct httpd_fsdata_file_noconst *)f->next) + { + if (httpd_fs_strcmp(name, f->name) == 0) + { + file->data = f->data; + file->len = f->len; +#if CONFIG_NETUTILS_HTTPDFSSTATS + ++count[i]; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ + return 1; + } +#if CONFIG_NETUTILS_HTTPDFSSTATS + ++i; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ + } + return 0; +} + +void httpd_fs_init(void) +{ +#if CONFIG_NETUTILS_HTTPDFSSTATS + uint16_t i; + for(i = 0; i < HTTPD_FS_NUMFILES; i++) + { + count[i] = 0; + } +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +} + +#if CONFIG_NETUTILS_HTTPDFSSTATS +uint16_t httpd_fs_count(char *name) +{ + struct httpd_fsdata_file_noconst *f; + uint16_t i; + + i = 0; + for(f = (struct httpd_fsdata_file_noconst *)HTTPD_FS_ROOT; + f != NULL; + f = (struct httpd_fsdata_file_noconst *)f->next) + { + if (httpd_fs_strcmp(name, f->name) == 0) + { + return count[i]; + } + ++i; + } + return 0; +} +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ diff --git a/apps/netutils/webserver/httpd_fsdata.c b/apps/netutils/webserver/httpd_fsdata.c new file mode 100644 index 000000000..c9cd8a20c --- /dev/null +++ b/apps/netutils/webserver/httpd_fsdata.c @@ -0,0 +1,614 @@ +static const unsigned char data_processes_shtml[] = +{ + /* /processes.shtml */ + + 0x2f, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3c, 0x68, 0x31, + 0x3e, 0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x70, 0x72, + 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, 0x73, 0x3c, 0x2f, 0x68, + 0x31, 0x3e, 0x3c, 0x62, 0x72, 0x3e, 0x3c, 0x74, 0x61, 0x62, + 0x6c, 0x65, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, + 0x31, 0x30, 0x30, 0x25, 0x22, 0x3e, 0x0a, 0x3c, 0x74, 0x72, + 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x49, 0x44, 0x3c, 0x2f, 0x74, + 0x68, 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x4e, 0x61, 0x6d, 0x65, + 0x3c, 0x2f, 0x74, 0x68, 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x50, + 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x3c, 0x2f, 0x74, + 0x68, 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x50, 0x6f, 0x6c, 0x6c, + 0x20, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x3c, 0x2f, + 0x74, 0x68, 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x20, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, + 0x3c, 0x2f, 0x74, 0x68, 0x3e, 0x3c, 0x74, 0x68, 0x3e, 0x50, + 0x72, 0x6f, 0x63, 0x73, 0x74, 0x61, 0x74, 0x65, 0x3c, 0x2f, + 0x74, 0x68, 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x25, + 0x21, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x65, + 0x73, 0x0a, 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x66, 0x6f, 0x6f, + 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0 +}; + +static const unsigned char data_404_html[] = +{ + /* /404.html */ + + 0x2f, 0x34, 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a, 0x20, 0x20, 0x3c, + 0x62, 0x6f, 0x64, 0x79, 0x20, 0x62, 0x67, 0x63, 0x6f, 0x6c, + 0x6f, 0x72, 0x3d, 0x22, 0x77, 0x68, 0x69, 0x74, 0x65, 0x22, + 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x63, 0x65, 0x6e, + 0x74, 0x65, 0x72, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x3c, 0x68, 0x31, 0x3e, 0x34, 0x30, 0x34, 0x20, 0x2d, + 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x20, + 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x3c, 0x2f, 0x68, 0x31, 0x3e, + 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x68, 0x33, + 0x3e, 0x47, 0x6f, 0x20, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, + 0x66, 0x3d, 0x22, 0x2f, 0x22, 0x3e, 0x68, 0x65, 0x72, 0x65, + 0x3c, 0x2f, 0x61, 0x3e, 0x20, 0x69, 0x6e, 0x73, 0x74, 0x65, + 0x61, 0x64, 0x2e, 0x3c, 0x2f, 0x68, 0x33, 0x3e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x63, 0x65, 0x6e, 0x74, 0x65, + 0x72, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x62, 0x6f, 0x64, + 0x79, 0x3e, 0x0a, 0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e, + 0 +}; + +static const unsigned char data_files_shtml[] = +{ + /* /files.shtml */ + + 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3c, 0x68, 0x31, + 0x3e, 0x46, 0x69, 0x6c, 0x65, 0x20, 0x73, 0x74, 0x61, 0x74, + 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x3c, 0x2f, 0x68, 0x31, + 0x3e, 0x0a, 0x3c, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3e, + 0x0a, 0x3c, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x77, 0x69, + 0x64, 0x74, 0x68, 0x3d, 0x22, 0x33, 0x30, 0x30, 0x22, 0x3e, + 0x0a, 0x3c, 0x74, 0x72, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, + 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x69, + 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x22, + 0x3e, 0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, + 0x6d, 0x6c, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x0a, 0x3c, 0x74, 0x64, 0x3e, 0x25, 0x21, 0x20, 0x66, + 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, + 0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, + 0x6c, 0x0a, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, 0x74, 0x64, + 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, 0x72, 0x63, 0x3d, + 0x22, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, 0x70, 0x6e, 0x67, + 0x22, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3d, 0x31, + 0x30, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x25, 0x21, + 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, 0x61, 0x74, + 0x73, 0x20, 0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, + 0x74, 0x6d, 0x6c, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, 0x74, 0x72, + 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, + 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x73, + 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x2f, 0x66, + 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, + 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x0a, + 0x3c, 0x74, 0x64, 0x3e, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, + 0x65, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x66, + 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, + 0x0a, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, 0x74, 0x64, 0x3e, + 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, 0x72, 0x63, 0x3d, 0x22, + 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x22, + 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3d, 0x31, 0x30, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x25, 0x21, 0x20, + 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, + 0x20, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, + 0x74, 0x6d, 0x6c, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, 0x74, 0x72, + 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, + 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x74, 0x63, 0x70, 0x2e, 0x73, + 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x2f, 0x74, 0x63, 0x70, + 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x3c, 0x2f, 0x61, 0x3e, + 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x0a, 0x3c, 0x74, 0x64, 0x3e, + 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, + 0x61, 0x74, 0x73, 0x20, 0x2f, 0x74, 0x63, 0x70, 0x2e, 0x73, + 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3c, 0x2f, 0x74, 0x64, 0x3e, + 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, + 0x72, 0x63, 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, + 0x70, 0x6e, 0x67, 0x22, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x3d, 0x31, 0x30, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, + 0x3d, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, + 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x74, 0x63, 0x70, 0x2e, + 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, + 0x74, 0x64, 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, + 0x74, 0x72, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x73, 0x74, 0x61, + 0x74, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, + 0x2f, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, 0x73, 0x68, 0x74, + 0x6d, 0x6c, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x0a, 0x3c, 0x74, 0x64, 0x3e, 0x25, 0x21, 0x20, 0x66, + 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, + 0x2f, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, 0x73, 0x68, 0x74, + 0x6d, 0x6c, 0x0a, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, 0x74, + 0x64, 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, 0x72, 0x63, + 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, 0x70, 0x6e, + 0x67, 0x22, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x3d, + 0x31, 0x30, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x25, + 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, 0x61, + 0x74, 0x73, 0x20, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, + 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, + 0x74, 0x64, 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, + 0x74, 0x72, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x73, 0x74, 0x79, + 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x22, 0x3e, 0x2f, 0x73, + 0x74, 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x3c, 0x2f, + 0x61, 0x3e, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x0a, 0x3c, 0x74, + 0x64, 0x3e, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, + 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x73, 0x74, 0x79, + 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x0a, 0x3c, 0x2f, 0x74, + 0x64, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x69, 0x6d, 0x67, + 0x20, 0x73, 0x72, 0x63, 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, + 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x22, 0x20, 0x68, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x3d, 0x31, 0x30, 0x20, 0x77, 0x69, 0x64, + 0x74, 0x68, 0x3d, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, + 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x73, 0x74, + 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x0a, 0x3e, 0x20, + 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, + 0x0a, 0x3c, 0x74, 0x72, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, + 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x34, + 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x2f, + 0x34, 0x30, 0x34, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x3c, 0x2f, + 0x61, 0x3e, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x0a, 0x3c, 0x74, + 0x64, 0x3e, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, + 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x34, 0x30, 0x34, + 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, + 0x73, 0x72, 0x63, 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, 0x65, + 0x2e, 0x70, 0x6e, 0x67, 0x22, 0x20, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x3d, 0x31, 0x30, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3d, 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, + 0x73, 0x74, 0x61, 0x74, 0x73, 0x20, 0x2f, 0x34, 0x30, 0x34, + 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, + 0x74, 0x64, 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, + 0x74, 0x72, 0x3e, 0x3c, 0x74, 0x64, 0x3e, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, + 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x22, 0x3e, 0x2f, 0x66, 0x61, + 0x64, 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x3c, 0x2f, 0x61, 0x3e, + 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x0a, 0x3c, 0x74, 0x64, 0x3e, + 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, + 0x61, 0x74, 0x73, 0x20, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, + 0x70, 0x6e, 0x67, 0x0a, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, + 0x74, 0x64, 0x3e, 0x3c, 0x69, 0x6d, 0x67, 0x20, 0x73, 0x72, + 0x63, 0x3d, 0x22, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, 0x70, + 0x6e, 0x67, 0x22, 0x20, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x3d, 0x31, 0x30, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, + 0x25, 0x21, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x2d, 0x73, 0x74, + 0x61, 0x74, 0x73, 0x20, 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, + 0x70, 0x6e, 0x67, 0x0a, 0x3e, 0x20, 0x3c, 0x2f, 0x74, 0x64, + 0x3e, 0x3c, 0x2f, 0x74, 0x72, 0x3e, 0x0a, 0x3c, 0x2f, 0x74, + 0x61, 0x62, 0x6c, 0x65, 0x3e, 0x0a, 0x3c, 0x2f, 0x63, 0x65, + 0x6e, 0x74, 0x65, 0x72, 0x3e, 0x0a, 0x25, 0x21, 0x3a, 0x20, + 0x2f, 0x66, 0x6f, 0x6f, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, + 0x6d, 0x6c, 0x0a, 0 +}; + +static const unsigned char data_footer_html[] = +{ + /* /footer.html */ + + 0x2f, 0x66, 0x6f, 0x6f, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x20, 0x20, 0x3c, 0x2f, 0x62, 0x6f, 0x64, 0x79, 0x3e, 0x0a, + 0x3c, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0 +}; + +static const unsigned char data_header_html[] = +{ + /* /header.html */ + + 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, + 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x50, 0x55, 0x42, 0x4c, 0x49, + 0x43, 0x20, 0x22, 0x2d, 0x2f, 0x2f, 0x57, 0x33, 0x43, 0x2f, + 0x2f, 0x44, 0x54, 0x44, 0x20, 0x48, 0x54, 0x4d, 0x4c, 0x20, + 0x34, 0x2e, 0x30, 0x31, 0x20, 0x54, 0x72, 0x61, 0x6e, 0x73, + 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x2f, 0x2f, 0x45, + 0x4e, 0x22, 0x20, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, + 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, + 0x67, 0x2f, 0x54, 0x52, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x34, + 0x2f, 0x6c, 0x6f, 0x6f, 0x73, 0x65, 0x2e, 0x64, 0x74, 0x64, + 0x22, 0x3e, 0x0a, 0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x68, 0x65, 0x61, 0x64, 0x3e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, + 0x57, 0x65, 0x6c, 0x63, 0x6f, 0x6d, 0x65, 0x20, 0x74, 0x6f, + 0x20, 0x74, 0x68, 0x65, 0x20, 0x75, 0x49, 0x50, 0x20, 0x77, + 0x65, 0x62, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x21, + 0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x72, + 0x65, 0x6c, 0x3d, 0x22, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x73, + 0x68, 0x65, 0x65, 0x74, 0x22, 0x20, 0x74, 0x79, 0x70, 0x65, + 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x63, 0x73, 0x73, + 0x22, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x73, 0x74, + 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x22, 0x3e, 0x20, + 0x20, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x68, 0x65, 0x61, 0x64, + 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x20, + 0x62, 0x67, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3d, 0x22, 0x23, + 0x66, 0x66, 0x66, 0x65, 0x65, 0x63, 0x22, 0x20, 0x74, 0x65, + 0x78, 0x74, 0x3d, 0x22, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x22, + 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, + 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, + 0x75, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, + 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, + 0x6e, 0x75, 0x62, 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x22, 0x3e, 0x46, + 0x72, 0x6f, 0x6e, 0x74, 0x20, 0x70, 0x61, 0x67, 0x65, 0x3c, + 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, + 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, 0x75, 0x62, 0x6f, + 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, + 0x3d, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, + 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x46, 0x69, 0x6c, 0x65, 0x20, + 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, + 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, + 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, + 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, 0x75, 0x62, + 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, + 0x66, 0x3d, 0x22, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, 0x73, + 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x4e, 0x65, 0x74, 0x77, + 0x6f, 0x72, 0x6b, 0x20, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, + 0x74, 0x69, 0x63, 0x73, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, + 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, + 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, + 0x65, 0x6e, 0x75, 0x62, 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, + 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x74, 0x63, 0x70, + 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x4e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x0a, 0x20, 0x20, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3c, + 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x62, 0x72, 0x3e, 0x0a, 0x20, 0x20, 0x3c, + 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x0a, 0x20, + 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, + 0x73, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x22, 0x3e, 0x0a, 0 +}; + +static const unsigned char data_index_html[] = +{ + /* /index.html */ + + 0x2f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x3c, 0x21, 0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45, 0x20, + 0x48, 0x54, 0x4d, 0x4c, 0x20, 0x50, 0x55, 0x42, 0x4c, 0x49, + 0x43, 0x20, 0x22, 0x2d, 0x2f, 0x2f, 0x57, 0x33, 0x43, 0x2f, + 0x2f, 0x44, 0x54, 0x44, 0x20, 0x48, 0x54, 0x4d, 0x4c, 0x20, + 0x34, 0x2e, 0x30, 0x31, 0x20, 0x54, 0x72, 0x61, 0x6e, 0x73, + 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c, 0x2f, 0x2f, 0x45, + 0x4e, 0x22, 0x20, 0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, + 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x77, 0x33, 0x2e, 0x6f, 0x72, + 0x67, 0x2f, 0x54, 0x52, 0x2f, 0x68, 0x74, 0x6d, 0x6c, 0x34, + 0x2f, 0x6c, 0x6f, 0x6f, 0x73, 0x65, 0x2e, 0x64, 0x74, 0x64, + 0x22, 0x3e, 0x0a, 0x3c, 0x68, 0x74, 0x6d, 0x6c, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x68, 0x65, 0x61, 0x64, 0x3e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x3c, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, + 0x57, 0x65, 0x6c, 0x63, 0x6f, 0x6d, 0x65, 0x20, 0x74, 0x6f, + 0x20, 0x74, 0x68, 0x65, 0x20, 0x75, 0x49, 0x50, 0x20, 0x77, + 0x65, 0x62, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x21, + 0x3c, 0x2f, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x3e, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x3c, 0x6c, 0x69, 0x6e, 0x6b, 0x20, 0x72, + 0x65, 0x6c, 0x3d, 0x22, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x73, + 0x68, 0x65, 0x65, 0x74, 0x22, 0x20, 0x74, 0x79, 0x70, 0x65, + 0x3d, 0x22, 0x74, 0x65, 0x78, 0x74, 0x2f, 0x63, 0x73, 0x73, + 0x22, 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x73, 0x74, + 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0x22, 0x3e, 0x20, + 0x20, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x68, 0x65, 0x61, 0x64, + 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x62, 0x6f, 0x64, 0x79, 0x20, + 0x62, 0x67, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3d, 0x22, 0x23, + 0x66, 0x66, 0x66, 0x65, 0x65, 0x63, 0x22, 0x20, 0x74, 0x65, + 0x78, 0x74, 0x3d, 0x22, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x22, + 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, + 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, + 0x75, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, + 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, + 0x6e, 0x75, 0x62, 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x2f, 0x22, 0x3e, 0x46, + 0x72, 0x6f, 0x6e, 0x74, 0x20, 0x70, 0x61, 0x67, 0x65, 0x3c, + 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, + 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, 0x75, 0x62, 0x6f, + 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, 0x66, + 0x3d, 0x22, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x2e, 0x73, 0x68, + 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x46, 0x69, 0x6c, 0x65, 0x20, + 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, + 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, + 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, + 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, 0x65, 0x6e, 0x75, 0x62, + 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, 0x20, 0x68, 0x72, 0x65, + 0x66, 0x3d, 0x22, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, 0x73, + 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x4e, 0x65, 0x74, 0x77, + 0x6f, 0x72, 0x6b, 0x20, 0x73, 0x74, 0x61, 0x74, 0x69, 0x73, + 0x74, 0x69, 0x63, 0x73, 0x3c, 0x2f, 0x61, 0x3e, 0x3c, 0x2f, + 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x64, 0x69, + 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, 0x22, 0x6d, + 0x65, 0x6e, 0x75, 0x62, 0x6f, 0x78, 0x22, 0x3e, 0x3c, 0x61, + 0x20, 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x74, 0x63, 0x70, + 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0x22, 0x3e, 0x4e, 0x65, + 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x0a, 0x20, 0x20, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x3c, + 0x2f, 0x61, 0x3e, 0x3c, 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, + 0x20, 0x20, 0x3c, 0x62, 0x72, 0x3e, 0x0a, 0x20, 0x20, 0x3c, + 0x2f, 0x64, 0x69, 0x76, 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x3c, + 0x64, 0x69, 0x76, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x3d, + 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x22, 0x3e, 0x0a, 0x20, 0x20, 0x3c, 0x70, + 0x3e, 0x0a, 0x20, 0x20, 0x54, 0x68, 0x65, 0x73, 0x65, 0x20, + 0x77, 0x65, 0x62, 0x20, 0x70, 0x61, 0x67, 0x65, 0x73, 0x20, + 0x61, 0x72, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, + 0x20, 0x62, 0x79, 0x20, 0x61, 0x20, 0x73, 0x6d, 0x61, 0x6c, + 0x6c, 0x20, 0x77, 0x65, 0x62, 0x20, 0x73, 0x65, 0x72, 0x76, + 0x65, 0x72, 0x20, 0x72, 0x75, 0x6e, 0x6e, 0x69, 0x6e, 0x67, + 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x6f, 0x70, 0x20, 0x6f, 0x66, + 0x0a, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x3c, 0x61, 0x20, + 0x68, 0x72, 0x65, 0x66, 0x3d, 0x22, 0x68, 0x74, 0x74, 0x70, + 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x69, 0x63, + 0x73, 0x2e, 0x73, 0x65, 0x2f, 0x7e, 0x61, 0x64, 0x61, 0x6d, + 0x2f, 0x75, 0x69, 0x70, 0x2f, 0x22, 0x3e, 0x75, 0x49, 0x50, + 0x20, 0x65, 0x6d, 0x62, 0x65, 0x64, 0x64, 0x65, 0x64, 0x20, + 0x54, 0x43, 0x50, 0x2f, 0x49, 0x50, 0x0a, 0x20, 0x20, 0x73, + 0x74, 0x61, 0x63, 0x6b, 0x3c, 0x2f, 0x61, 0x3e, 0x2e, 0x0a, + 0x20, 0x20, 0x3c, 0x2f, 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x3c, + 0x70, 0x3e, 0x0a, 0x20, 0x20, 0x43, 0x6c, 0x69, 0x63, 0x6b, + 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x69, + 0x6e, 0x6b, 0x73, 0x20, 0x61, 0x62, 0x6f, 0x76, 0x65, 0x20, + 0x66, 0x6f, 0x72, 0x20, 0x77, 0x65, 0x62, 0x20, 0x73, 0x65, + 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x74, 0x61, 0x74, 0x69, + 0x73, 0x74, 0x69, 0x63, 0x73, 0x2e, 0x0a, 0x20, 0x20, 0x3c, + 0x2f, 0x70, 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x62, + 0x6f, 0x64, 0x79, 0x3e, 0x0a, 0x3c, 0x2f, 0x68, 0x74, 0x6d, + 0x6c, 0x3e, 0x0a, 0 +}; + +static const unsigned char data_style_css[] = +{ + /* /style.css */ + + 0x2f, 0x73, 0x74, 0x79, 0x6c, 0x65, 0x2e, 0x63, 0x73, 0x73, 0, + 0x68, 0x31, 0x20, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x74, 0x65, + 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0a, 0x20, 0x20, + 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, + 0x31, 0x34, 0x70, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x66, 0x6f, + 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, + 0x61, 0x72, 0x69, 0x61, 0x6c, 0x2c, 0x68, 0x65, 0x6c, 0x76, + 0x65, 0x74, 0x69, 0x63, 0x61, 0x3b, 0x0a, 0x20, 0x20, 0x66, + 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x3a, 0x62, 0x6f, 0x6c, 0x64, 0x3b, 0x0a, 0x20, 0x20, 0x70, + 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x31, 0x30, 0x70, + 0x78, 0x3b, 0x20, 0x0a, 0x7d, 0x0a, 0x0a, 0x62, 0x6f, 0x64, + 0x79, 0x0a, 0x7b, 0x0a, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, + 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, + 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x66, 0x66, 0x66, 0x65, + 0x65, 0x63, 0x3b, 0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, + 0x72, 0x3a, 0x62, 0x6c, 0x61, 0x63, 0x6b, 0x3b, 0x0a, 0x0a, + 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, + 0x65, 0x3a, 0x38, 0x70, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x66, + 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, + 0x3a, 0x61, 0x72, 0x69, 0x61, 0x6c, 0x2c, 0x68, 0x65, 0x6c, + 0x76, 0x65, 0x74, 0x69, 0x63, 0x61, 0x3b, 0x0a, 0x7d, 0x0a, + 0x0a, 0x2e, 0x6d, 0x65, 0x6e, 0x75, 0x0a, 0x7b, 0x0a, 0x20, + 0x20, 0x6d, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x34, + 0x70, 0x78, 0x3b, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3a, 0x36, 0x30, 0x25, 0x3b, 0x0a, 0x0a, 0x20, 0x20, + 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x32, 0x70, + 0x78, 0x3b, 0x0a, 0x09, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, + 0x64, 0x65, 0x72, 0x3a, 0x20, 0x73, 0x6f, 0x6c, 0x69, 0x64, + 0x20, 0x31, 0x70, 0x78, 0x3b, 0x0a, 0x20, 0x20, 0x62, 0x61, + 0x63, 0x6b, 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, + 0x6f, 0x6c, 0x6f, 0x72, 0x3a, 0x20, 0x23, 0x66, 0x66, 0x66, + 0x63, 0x64, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x74, 0x65, 0x78, + 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x6c, 0x65, + 0x66, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x66, + 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x39, + 0x70, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, + 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x61, 0x72, + 0x69, 0x61, 0x6c, 0x2c, 0x68, 0x65, 0x6c, 0x76, 0x65, 0x74, + 0x69, 0x63, 0x61, 0x3b, 0x20, 0x20, 0x0a, 0x7d, 0x0a, 0x0a, + 0x64, 0x69, 0x76, 0x2e, 0x6d, 0x65, 0x6e, 0x75, 0x62, 0x6f, + 0x78, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, + 0x68, 0x3a, 0x20, 0x32, 0x35, 0x25, 0x3b, 0x0a, 0x20, 0x20, + 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x3a, 0x20, 0x30, 0x3b, + 0x0a, 0x20, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x3a, 0x20, + 0x6c, 0x65, 0x66, 0x74, 0x3b, 0x0a, 0x74, 0x65, 0x78, 0x74, + 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, 0x20, 0x63, 0x65, + 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x2e, + 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x62, 0x6c, 0x6f, + 0x63, 0x6b, 0x0a, 0x7b, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x6d, + 0x61, 0x72, 0x67, 0x69, 0x6e, 0x3a, 0x20, 0x34, 0x70, 0x78, + 0x3b, 0x0a, 0x20, 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3a, + 0x36, 0x30, 0x25, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x70, 0x61, + 0x64, 0x64, 0x69, 0x6e, 0x67, 0x3a, 0x32, 0x70, 0x78, 0x3b, + 0x0a, 0x0a, 0x20, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, + 0x3a, 0x20, 0x31, 0x70, 0x78, 0x20, 0x64, 0x6f, 0x74, 0x74, + 0x65, 0x64, 0x3b, 0x0a, 0x20, 0x20, 0x62, 0x61, 0x63, 0x6b, + 0x67, 0x72, 0x6f, 0x75, 0x6e, 0x64, 0x2d, 0x63, 0x6f, 0x6c, + 0x6f, 0x72, 0x3a, 0x20, 0x77, 0x68, 0x69, 0x74, 0x65, 0x3b, + 0x0a, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, + 0x69, 0x7a, 0x65, 0x3a, 0x38, 0x70, 0x74, 0x3b, 0x0a, 0x20, + 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, + 0x6c, 0x79, 0x3a, 0x61, 0x72, 0x69, 0x61, 0x6c, 0x2c, 0x68, + 0x65, 0x6c, 0x76, 0x65, 0x74, 0x69, 0x63, 0x61, 0x3b, 0x20, + 0x20, 0x0a, 0x0a, 0x7d, 0x0a, 0x0a, 0x70, 0x2e, 0x69, 0x6e, + 0x74, 0x72, 0x6f, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x6d, 0x61, + 0x72, 0x67, 0x69, 0x6e, 0x2d, 0x6c, 0x65, 0x66, 0x74, 0x3a, + 0x32, 0x30, 0x70, 0x78, 0x3b, 0x0a, 0x20, 0x20, 0x6d, 0x61, + 0x72, 0x67, 0x69, 0x6e, 0x2d, 0x72, 0x69, 0x67, 0x68, 0x74, + 0x3a, 0x32, 0x30, 0x70, 0x78, 0x3b, 0x0a, 0x0a, 0x20, 0x20, + 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, + 0x31, 0x30, 0x70, 0x74, 0x3b, 0x0a, 0x2f, 0x2a, 0x20, 0x20, + 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x77, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x3a, 0x62, 0x6f, 0x6c, 0x64, 0x3b, 0x20, 0x2a, 0x2f, + 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, 0x61, + 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x61, 0x72, 0x69, 0x61, 0x6c, + 0x2c, 0x68, 0x65, 0x6c, 0x76, 0x65, 0x74, 0x69, 0x63, 0x61, + 0x3b, 0x20, 0x20, 0x0a, 0x7d, 0x0a, 0x0a, 0x70, 0x2e, 0x63, + 0x6c, 0x69, 0x6e, 0x6b, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x66, + 0x6f, 0x6e, 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x31, + 0x32, 0x70, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, + 0x74, 0x2d, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x63, + 0x6f, 0x75, 0x72, 0x69, 0x65, 0x72, 0x2c, 0x6d, 0x6f, 0x6e, + 0x6f, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3b, 0x20, 0x20, 0x0a, + 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, + 0x67, 0x6e, 0x3a, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, + 0x0a, 0x7d, 0x0a, 0x0a, 0x70, 0x2e, 0x63, 0x6c, 0x69, 0x6e, + 0x6b, 0x39, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, + 0x74, 0x2d, 0x73, 0x69, 0x7a, 0x65, 0x3a, 0x39, 0x70, 0x74, + 0x3b, 0x0a, 0x20, 0x20, 0x66, 0x6f, 0x6e, 0x74, 0x2d, 0x66, + 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x3a, 0x63, 0x6f, 0x75, 0x72, + 0x69, 0x65, 0x72, 0x2c, 0x6d, 0x6f, 0x6e, 0x6f, 0x73, 0x70, + 0x61, 0x63, 0x65, 0x3b, 0x20, 0x20, 0x0a, 0x20, 0x20, 0x74, + 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, 0x67, 0x6e, 0x3a, + 0x63, 0x65, 0x6e, 0x74, 0x65, 0x72, 0x3b, 0x0a, 0x7d, 0x0a, + 0x0a, 0x0a, 0x70, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x70, 0x61, + 0x64, 0x64, 0x69, 0x6e, 0x67, 0x2d, 0x6c, 0x65, 0x66, 0x74, + 0x3a, 0x31, 0x30, 0x70, 0x78, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, + 0x70, 0x2e, 0x72, 0x69, 0x67, 0x68, 0x74, 0x0a, 0x7b, 0x0a, + 0x20, 0x20, 0x74, 0x65, 0x78, 0x74, 0x2d, 0x61, 0x6c, 0x69, + 0x67, 0x6e, 0x3a, 0x72, 0x69, 0x67, 0x68, 0x74, 0x3b, 0x20, + 0x0a, 0x7d, 0x0a, 0x0a, 0 +}; + +static const unsigned char data_fade_png[] = +{ + /* /fade.png */ + + 0x2f, 0x66, 0x61, 0x64, 0x65, 0x2e, 0x70, 0x6e, 0x67, 0x00, + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, + 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x04, + 0x00, 0x00, 0x00, 0x0a, 0x08, 0x02, 0x00, 0x00, 0x00, 0x1c, + 0x99, 0x68, 0x59, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, + 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, + 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, + 0x4d, 0x45, 0x07, 0xd6, 0x06, 0x08, 0x14, 0x1b, 0x39, 0xaf, + 0x5b, 0xc0, 0xe3, 0x00, 0x00, 0x00, 0x1d, 0x74, 0x45, 0x58, + 0x74, 0x43, 0x6f, 0x6d, 0x6d, 0x65, 0x6e, 0x74, 0x00, 0x43, + 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, + 0x68, 0x20, 0x54, 0x68, 0x65, 0x20, 0x47, 0x49, 0x4d, 0x50, + 0xef, 0x64, 0x25, 0x6e, 0x00, 0x00, 0x00, 0x3a, 0x49, 0x44, + 0x41, 0x54, 0x08, 0xd7, 0x75, 0x8c, 0x31, 0x12, 0x00, 0x10, + 0x10, 0xc4, 0x2e, 0x37, 0x9e, 0x40, 0x65, 0xfd, 0xff, 0x83, + 0xf4, 0x0a, 0x1c, 0x8d, 0x54, 0x9b, 0xc9, 0xcc, 0x9a, 0x3d, + 0x90, 0x73, 0x71, 0x67, 0x91, 0xd4, 0x74, 0x36, 0xa9, 0x55, + 0x01, 0xf8, 0x29, 0x58, 0xc8, 0xbf, 0x48, 0xc4, 0x81, 0x74, + 0x0b, 0xa3, 0x0f, 0x7c, 0xdb, 0x04, 0xe8, 0x40, 0x05, 0xdf, + 0xa1, 0xf3, 0xfc, 0x73, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, + 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, 0 +}; + +static const unsigned char data_stats_shtml[] = +{ + /* /stats.shtml */ + + 0x2f, 0x73, 0x74, 0x61, 0x74, 0x73, 0x2e, 0x73, 0x68, 0x74, 0x6d, 0x6c, 0, + 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, + 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x0a, 0x3c, 0x68, 0x31, + 0x3e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x73, + 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x3c, + 0x2f, 0x68, 0x31, 0x3e, 0x0a, 0x3c, 0x63, 0x65, 0x6e, 0x74, + 0x65, 0x72, 0x3e, 0x0a, 0x3c, 0x74, 0x61, 0x62, 0x6c, 0x65, + 0x20, 0x77, 0x69, 0x64, 0x74, 0x68, 0x3d, 0x22, 0x33, 0x30, + 0x30, 0x22, 0x20, 0x62, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x3d, + 0x22, 0x30, 0x22, 0x3e, 0x0a, 0x3c, 0x74, 0x72, 0x3e, 0x3c, + 0x74, 0x64, 0x3e, 0x3c, 0x70, 0x72, 0x65, 0x3e, 0x0a, 0x49, + 0x50, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, + 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, + 0x73, 0x65, 0x6e, 0x74, 0x0a, 0x09, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, 0x64, + 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x0a, 0x49, 0x50, 0x20, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x73, 0x20, 0x20, 0x20, 0x20, + 0x49, 0x50, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x2f, 0x68, 0x65, 0x61, 0x64, 0x65, 0x72, 0x20, 0x6c, 0x65, + 0x6e, 0x67, 0x74, 0x68, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x50, + 0x20, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x2c, 0x20, 0x68, + 0x69, 0x67, 0x68, 0x20, 0x62, 0x79, 0x74, 0x65, 0x0a, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x49, 0x50, 0x20, 0x6c, 0x65, 0x6e, 0x67, 0x74, + 0x68, 0x2c, 0x20, 0x6c, 0x6f, 0x77, 0x20, 0x62, 0x79, 0x74, + 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x50, 0x20, 0x66, 0x72, + 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x48, 0x65, 0x61, 0x64, 0x65, 0x72, 0x20, 0x63, 0x68, + 0x65, 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x57, 0x72, 0x6f, 0x6e, 0x67, 0x20, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x63, 0x6f, 0x6c, 0x0a, 0x49, 0x43, 0x4d, 0x50, 0x09, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, + 0x74, 0x73, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, + 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, + 0x74, 0x73, 0x20, 0x73, 0x65, 0x6e, 0x74, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, 0x64, + 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x54, 0x79, 0x70, 0x65, 0x20, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x73, 0x0a, 0x54, 0x43, 0x50, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, + 0x74, 0x73, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, + 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, + 0x74, 0x73, 0x20, 0x73, 0x65, 0x6e, 0x74, 0x0a, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x50, 0x61, 0x63, 0x6b, 0x65, 0x74, 0x73, 0x20, 0x64, + 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x43, 0x68, 0x65, 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x20, 0x65, + 0x72, 0x72, 0x6f, 0x72, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x44, + 0x61, 0x74, 0x61, 0x20, 0x70, 0x61, 0x63, 0x6b, 0x65, 0x74, + 0x73, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, 0x75, 0x74, 0x20, + 0x41, 0x43, 0x4b, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x52, 0x65, + 0x73, 0x65, 0x74, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x52, 0x65, + 0x74, 0x72, 0x61, 0x6e, 0x73, 0x6d, 0x69, 0x73, 0x73, 0x69, + 0x6f, 0x6e, 0x73, 0x0a, 0x09, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x4e, 0x6f, 0x20, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x76, 0x61, 0x6c, 0x69, 0x61, + 0x62, 0x6c, 0x65, 0x0a, 0x09, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, + 0x20, 0x61, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x73, 0x20, + 0x74, 0x6f, 0x20, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x64, 0x20, + 0x70, 0x6f, 0x72, 0x74, 0x73, 0x0a, 0x3c, 0x2f, 0x70, 0x72, + 0x65, 0x3e, 0x3c, 0x2f, 0x74, 0x64, 0x3e, 0x3c, 0x74, 0x64, + 0x3e, 0x3c, 0x70, 0x72, 0x65, 0x3e, 0x25, 0x21, 0x20, 0x6e, + 0x65, 0x74, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x73, 0x0a, 0x3c, + 0x2f, 0x70, 0x72, 0x65, 0x3e, 0x3c, 0x2f, 0x74, 0x61, 0x62, + 0x6c, 0x65, 0x3e, 0x0a, 0x3c, 0x2f, 0x63, 0x65, 0x6e, 0x74, + 0x65, 0x72, 0x3e, 0x0a, 0x25, 0x21, 0x3a, 0x20, 0x2f, 0x66, + 0x6f, 0x6f, 0x74, 0x65, 0x72, 0x2e, 0x68, 0x74, 0x6d, 0x6c, + 0x0a, 0 +}; + +const struct httpd_fsdata_file file_processes_shtml[] = + {{NULL, data_processes_shtml, data_processes_shtml + 17, sizeof(data_processes_shtml) - 18}}; + +const struct httpd_fsdata_file file_404_html[] = + {{file_processes_shtml, data_404_html, data_404_html + 10, sizeof(data_404_html) - 11}}; + +const struct httpd_fsdata_file file_files_shtml[] = + {{file_404_html, data_files_shtml, data_files_shtml + 13, sizeof(data_files_shtml) - 14}}; + +const struct httpd_fsdata_file file_footer_html[] = + {{file_files_shtml, data_footer_html, data_footer_html + 13, sizeof(data_footer_html) - 14}}; + +const struct httpd_fsdata_file file_header_html[] = + {{file_footer_html, data_header_html, data_header_html + 13, sizeof(data_header_html) - 14}}; + +const struct httpd_fsdata_file file_index_html[] = + {{file_header_html, data_index_html, data_index_html + 12, sizeof(data_index_html) - 13}}; + +const struct httpd_fsdata_file file_style_css[] = + {{file_index_html, data_style_css, data_style_css + 11, sizeof(data_style_css) - 12}}; + +const struct httpd_fsdata_file file_fade_png[] = + {{file_style_css, data_fade_png, data_fade_png + 10, sizeof(data_fade_png) - 11}}; + +const struct httpd_fsdata_file file_stats_shtml[] = + {{file_fade_png, data_stats_shtml, data_stats_shtml + 13, sizeof(data_stats_shtml) - 14}}; + +#define HTTPD_FS_ROOT file_stats_shtml +#define HTTPD_FS_NUMFILES 10 diff --git a/apps/netutils/webserver/httpd_fsdata.h b/apps/netutils/webserver/httpd_fsdata.h new file mode 100644 index 000000000..d0a69affa --- /dev/null +++ b/apps/netutils/webserver/httpd_fsdata.h @@ -0,0 +1,79 @@ +/**************************************************************************** + * netutils/webserver/httpd_fsdata.h + * + * Copyright (C) 2007-2009 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt <spudmonkey@racsa.co.cr> + * + * Based on uIP which also has a BSD style license: + * + * Author: Adam Dunkels <adam@sics.se> + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + ****************************************************************************/ + +#ifndef __HTTPD_FSDATA_H__ +#define __HTTPD_FSDATA_H__ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include <stdint.h> +#include <net/uip/uip.h> + +/**************************************************************************** + * Public Types + ****************************************************************************/ + +struct httpd_fsdata_file +{ + const struct httpd_fsdata_file *next; + FAR const uint8_t *name; + FAR const uint8_t *data; + int len; +#ifdef CONFIG_NETUTILS_HTTPDFSSTATS +#if CONFIG_NETUTILS_HTTPDFSSTATS == 1 + uint16_t count; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +}; + +struct httpd_fsdata_file_noconst +{ + FAR struct httpd_fsdata_file *next; + FAR char *name; + FAR char *data; + int len; +#ifdef CONFIG_NETUTILS_HTTPDFSSTATS +#if CONFIG_NETUTILS_HTTPDFSSTATS == 1 + uint16_t count; +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +#endif /* CONFIG_NETUTILS_HTTPDFSSTATS */ +}; + +#endif /* __HTTPD_FSDATA_H__ */ diff --git a/apps/netutils/webserver/makefsdata b/apps/netutils/webserver/makefsdata new file mode 100755 index 000000000..71b6bd344 --- /dev/null +++ b/apps/netutils/webserver/makefsdata @@ -0,0 +1,75 @@ +#!/usr/bin/perl + +open(OUTPUT, "> httpd-fsdata.c"); + +chdir("httpd-fs"); + +opendir(DIR, "."); +@files = grep { !/^\./ && !/(CVS|~)/ } readdir(DIR); +closedir(DIR); + +foreach $file (@files) { + + if(-d $file && $file !~ /^\./) { + print "Processing directory $file\n"; + opendir(DIR, $file); + @newfiles = grep { !/^\./ && !/(CVS|~)/ } readdir(DIR); + closedir(DIR); + printf "Adding files @newfiles\n"; + @files = (@files, map { $_ = "$file/$_" } @newfiles); + next; + } +} + +foreach $file (@files) { + if(-f $file) { + + print "Adding file $file\n"; + + open(FILE, $file) || die "Could not open file $file\n"; + + $file =~ s-^-/-; + $fvar = $file; + $fvar =~ s-/-_-g; + $fvar =~ s-\.-_-g; + # for AVR, add PROGMEM here + print(OUTPUT "static const unsigned char data".$fvar."[] =\n"); + print(OUTPUT "{\n /* $file */\n\n "); + for($j = 0; $j < length($file); $j++) { + printf(OUTPUT "%#02x, ", unpack("C", substr($file, $j, 1))); + } + printf(OUTPUT "0x00,\n "); + + $i = 0; + while(read(FILE, $data, 1)) { + printf(OUTPUT "%#02x, ", unpack("C", $data)); + $i++; + if($i == 10) { + print(OUTPUT "\n"); + $i = 0; + print(OUTPUT " "); + } + } + print(OUTPUT "0x00\n};\n\n"); + close(FILE); + push(@fvars, $fvar); + push(@pfiles, $file); + } +} + +for($i = 0; $i < @fvars; $i++) { + $file = $pfiles[$i]; + $fvar = $fvars[$i]; + + if($i == 0) { + $prevfile = "NULL"; + } else { + $prevfile = "file" . $fvars[$i - 1]; + } + print(OUTPUT "const struct httpd_fsdata_file file".$fvar."[] = {{$prevfile, data$fvar, "); + print(OUTPUT "data$fvar + ". (length($file) + 1) .", "); + print(OUTPUT "sizeof(data$fvar) - ". (length($file) + 1) ."}};\n\n"); +} + +print(OUTPUT "#define HTTPD_FS_ROOT file$fvars[$i - 1]\n\n"); +print(OUTPUT "#define HTTPD_FS_NUMFILES $i\n"); |