Single instance HTTP Server using WiFly Interface.

Dependents:   WiFlyHTTPServerSample MultiThreadingHTTPServer

This is my implementation for a HTTP Server using the WiFly Interface. Please note that this is still under development.

It may still contain several bugs. I have tested it using a 1768 on an application board plus RN-XV board.

Currently there is only a FileSystem implemented. Also it is limited to GET request.

I try to extend it further so it will be more useful.

Btw, it does NOT work with RTOS, which seems not to be the Problem of my library.

Do not Forget to Import the WiFly Interface into your Project when using this library.

Change History:

REV5: - added support for basic RPC GET request functionality.

REV4: - added argument parsing from the request uri. - documentation extended and updated.

HTTPRequestHandler.cpp

Committer:
leihen
Date:
2013-06-26
Revision:
13:93ff322420b0
Parent:
12:ba81cc117fb6

File content as of revision 13:93ff322420b0:

/* HTTPRequestHandler.cpp */
#include "mbed.h"
#include "HTTPRequestHandler.h"
#include <ctype.h>
#include "Wifly.h"

//#define DEBUG
#include "debug.h"

static char buffer[128];

//const char hdrConClose[] = "Connection: Keep-Alive\r\n";

const char hdrStandard[] = "DNT: 1\r\n"
                            "MaxAge: 0\r\n"
                            "Connection: Keep-Alive\r\n"
                            "Content-Type: text/html\r\n"
                            "Server: mbed embedded\r\n"
                            "Accessible: 1\r\n"
                            "\r\n";


static int _stricmp(const char* a, const char* b)
{
    int la = strlen(a);
    int lb = strlen(b);
    for (int i = 0 ; i < min(la, lb) ; i++) {
        if (tolower((int)a[i]) != tolower((int)b[i]))
            return i;
    }
    return 0;
}


static const struct mapping_t {
    const char* key;
    const char* value;
} fileTypeMapping[]  = {
        {".gif", "Content-Type: image/gif\r\n"   },
    {".jpg", "Content-Type: image/jpeg\r\n"  },
    {".jpeg","Content-Type: image/jpeg\r\n"  },
    {".ico", "Content-Type: image/x-icon\r\n"},
    {".png", "Content-Type: image/png\r\n"   },
    {".zip", "Content-Type: image/zip\r\n"   },
    {".gz",  "Content-Type: image/gz\r\n"    },
    {".tar", "Content-Type: image/tar\r\n"   },
    {".txt", "Content-Type: plain/text\r\n"  },
    {".pdf", "Content-Type: application/pdf\r\n" },
    {".htm", "Content-Type: text/html\r\n"   },
    {".html","Content-Type: text/html\r\n"   },
    {".js", "Content-Type: text/javascript\r\n"}};
    
HTTPRequestHandler::HTTPRequestHandler(HTTPConnection::HTTPMessage& Msg)
    : msg(Msg)
{
    msg = Msg;

}

HTTPRequestHandler::~HTTPRequestHandler()
{
}

void HTTPRequestHandler::getStandardHeaders(HTTPHeaders& header, const char* fext)
{
    header.clear();
    header["DNT"] = "1";
    header["MaxAge"] = "0";
    header["Connection"] = "Keep-Alive";
    header["Server"] = "mbed Embedded";
    header["Accessible"] = "1";
    if (fext == NULL)
        header["Content-Type"] = "text/html";
    else {
        for (int i = 0 ; i < sizeof(fileTypeMapping)/sizeof(struct mapping_t) ;i++) {
            if (_stricmp(fileTypeMapping[i].key, fext) == 0) {
                header["Content-Type"] = fileTypeMapping[i].value;
                break;
            }
        }
    }
}

void HTTPRequestHandler::handleRequest()
{
    int err = 0;
    
    switch (msg.request) {
        case HTTP_RT_GET:
            INFO("Dispatching GET Request.");
            err = handleGetRequest();
            break;
            
        case HTTP_RT_POST:
            INFO("Dispatching POST request.");
            err = handlePostRequest();
            break;
            
        case HTTP_RT_PUT:
            INFO("Dispatching PUT request.");
            err = handlePutRequest();
            break;
            
        default:
            INFO("Error in handleRequest, unhandled request type.");
            err = HTTP_NotImplemented;
            break;
    }
    
    //  if any of these functions returns a negative number, call the error handler
    if (err > 0) {
        handleError(err);
    }        
}

static const char* szErrorPage = "<HTML><HEAD><META content=\"text/html\" http-equiv=Content-Type></HEAD><BODY><h1>Error %d</h1><P>HTTPServer Error<P></BODY></HTML>\r\n\r\n";

void HTTPRequestHandler::handleError(int errorCode, HTTPHeaders* header)
{
    INFO("Handling error !");
    sprintf(buffer,"HTTP/1.1 %d Error\r\n", errorCode);
    Wifly::getInstance()->sendData(buffer, strlen(buffer));
    sprintf(buffer, "Content-Length: %d\r\n", strlen(szErrorPage));
    Wifly::getInstance()->sendData(buffer, strlen(buffer));
    if (header == NULL) {
        sprintf(buffer, "Content-Type: text/html\r\nServer: mbed embedded\r\n\n\r");
        Wifly::getInstance()->sendData(buffer, strlen(buffer));
    }
    else {
        for ( map<const char*, const char*>::iterator cIter = header->begin() ; cIter != header->end() ; cIter ++) {
            Wifly::getInstance()->sendData((char*)cIter->first, strlen(cIter->first));
            Wifly::getInstance()->sendData(": ", 2);
            Wifly::getInstance()->sendData((char*)cIter->second, strlen(cIter->second));
            Wifly::getInstance()->sendData("\r\n",2);
        }
        Wifly::getInstance()->sendData("\r\n",2);
    }
    Wifly::getInstance()->sendData((char*)szErrorPage, strlen(szErrorPage));
}


void HTTPRequestHandler::startResponse(int returnCode, long nLen, HTTPHeaders* header)
{
    INFO("Starting response (%ld bytes in total)!", nLen);
    sprintf(buffer, "HTTP/1.1 %d OK\r\n", returnCode);
    Wifly::getInstance()->sendData(buffer, strlen(buffer));
    sprintf(buffer, "Content-Length: %ld\r\n", nLen);    //  Add 2 chars for the terminating CR+LF
    Wifly::getInstance()->sendData(buffer, strlen(buffer));
    if (header == NULL) {
            Wifly::getInstance()->sendData((char*)hdrStandard, strlen(hdrStandard));
    }
    else {
        for ( map<const char*, const char*>::iterator cIter = header->begin() ; cIter != header->end() ; cIter ++) {
            Wifly::getInstance()->sendData((char*)cIter->first, strlen(cIter->first));
            Wifly::getInstance()->sendData(": ", 2);
            Wifly::getInstance()->sendData((char*)cIter->second, strlen(cIter->second));
            Wifly::getInstance()->sendData("\r\n\r\n",2);
        }
        Wifly::getInstance()->sendData("\r\n", 2);
    }
    //  other content must be sent using the 'processResponse' function
}

void HTTPRequestHandler::processResponse(int nLen, char* body)
{
    INFO("Processing Response (%d bytes)!\n",nLen);
    Wifly::getInstance()->sendData(body, nLen);
}

void HTTPRequestHandler::endResponse()
{
//    INFO("Ending Response !");
//    Wifly::getInstance()->sendData("\r\n\r\n", 4);
//    Wifly::getInstance()->cmdMode();
//    Wifly::getInstance()->sendData("close\r", 6);
//    Thread::wait(250);
//    Wifly::getInstance()->exit();
}