HTTP Server library for Mbed OS-5. A fork of Henry Leinen's [[https://os.mbed.com/users/leihen/code/HTTPServer/]] library.

Dependents:   STM32F407VET6_HTTPServer

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers HTTPServer.h Source File

HTTPServer.h

00001 /* HTTPServer.cpp */
00002 /*
00003 Copyright (c) 2013 Henry Leinen (henry[dot]leinen [at] online [dot] de)
00004  
00005 Permission is hereby granted, free of charge, to any person obtaining a copy
00006 of this software and associated documentation files (the "Software"), to deal
00007 in the Software without restriction, including without limitation the rights
00008 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00009 copies of the Software, and to permit persons to whom the Software is
00010 furnished to do so, subject to the following conditions:
00011  
00012 The above copyright notice and this permission notice shall be included in
00013 all copies or substantial portions of the Software.
00014  
00015 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00016 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00017 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00018 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00019 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00020 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
00021 THE SOFTWARE.
00022 */
00023 #ifndef __HTTPSERVER_H__
00024 #define __HTTPSERVER_H__
00025 #include "mbed.h"
00026 #include "EthernetInterface.h"
00027 #include "HTTPConnection.h"
00028 #include "HTTPRequestHandler.h"
00029 
00030 #include <map>
00031 using std::map;
00032 #include <string>
00033 using std::string;
00034 
00035 #include <TCPSocket.h>
00036 
00037 /** Typedefinition for a handler function
00038 */
00039 typedef void (*HTTPRequestHandlerFunction)(HTTPConnection::HTTPMessage&, TCPSocket*);
00040 
00041 
00042 /** Class HTTPServer for use with <a href="http://mbed.org/users/samux/code/WiflyInterface/">WiflyInterface</a>.
00043 * This class is a simple implementation of an HTTP Server for use with the WiFly interface.
00044 * The class will listen for incoming connections on the (configurable) HTTP port. For each 
00045 * incoming connection, one request will be processed. 
00046 * After instantiating this class, add all required handlers using the \c addHandler function,
00047 * replace the default error handler using \c addErrorHandler if needed and call the \c start
00048 * method to initialize the class.
00049 * You need to continuously poll for any new incoming connections after one request has been
00050 * served using the \c poll member function.
00051 *
00052 * \b Example:
00053 * @code
00054 * #include "mbed.h"
00055 * #include "HTTPServer.h"
00056 * #include "LocalFileSystem.h"
00057 *
00058 * LocalFileSystem local("local"); 
00059 *
00060 * void main(void)
00061 * {
00062 *     HTTPServer svr;
00063 *     svr.mount("/local/", "/");
00064 *     svr.addHandler<HTTPFsRequestHandler>( "/" );
00065 *     svr.start();
00066 *     while(1)
00067 *     {
00068 *         if (svr.poll() < 0)
00069 *             exit(0);
00070 *     }
00071 * }
00072 * @endcode
00073 *
00074 * An alternate approach e.g. if you need to perform additional tasks using the EthernetInterface
00075 * there is the possibility to provide the EthernetInterface object in an initialized and connected
00076 * state. __NOTE: You should choose this scenario for compatibility reasons.___
00077 *
00078 * \b Example2:
00079 * @code
00080 * #include "mbed.h"
00081 * #include "HTTPServer.h"
00082 * #include "EthernetInterface.h"
00083 * #include "LocalFileSystem.h"
00084 *
00085 * LocalFileSystem local("local");
00086 * EthernetInterface eth;
00087 *
00088 * void main(void)
00089 * {
00090 *     HTTPServer svr;
00091 *     //    Initialize the ethernet interface
00092 *     if (eth.init() != 0) {
00093 *         printf("Initialization of EthernetInterface failed !");
00094 *         exit(0);
00095 *     }
00096 *     //    Connect using DHCP
00097 *     if (eth.connect() !=0) {
00098 *         printf("Failed to connect using DHCP !");
00099 *         exit(0);
00100 *     }
00101 *     
00102 *     // Moint the local file system and provide a handler for 'root'.
00103 *     svr.mount("/local/", "/");
00104 *     svr.addHandler<HTTPFsRequestHandler>( "/" );
00105 *     // Start the server on port 80, providing our own ethernet interface object.
00106 *     svr.start(80, &eth);
00107 *     while(1)
00108 *     {
00109 *         if (svr.poll() < 0)
00110 *             exit(0);
00111 *     }
00112 * }
00113 * @endcode
00114 *     
00115 */
00116 class HTTPServer
00117 {
00118         TCPSocket               m_Svr;
00119         bool                    m_bServerListening;
00120         EthernetInterface*      m_pEthernet;
00121        
00122     public:
00123         /** Constructor for HTTPServer objects.
00124         */
00125         HTTPServer();
00126         
00127         /** Destructor for HTTPServer objects.
00128         */
00129         ~HTTPServer();
00130 
00131         /**
00132         * Structure which will allow to order the stored handlers according to their associated path.
00133         */
00134         struct handlersComp //Used to order handlers in the right way
00135         {
00136             bool operator() (const string& handler1, const string& handler2) const
00137             {
00138                 //The first handler is longer than the second one
00139                 if (handler1.length() > handler2.length())
00140                     return true; //Returns true if handler1 is to appear before handler2
00141                 else if (handler1.length() < handler2.length())
00142                     return false;
00143                 else //To avoid the == case, sort now by address
00144                     return ((&handler1)>(&handler2));
00145             }
00146         };
00147 
00148         /**
00149         * Adds a request handler to the handlers list. You will have to use one of the existing implementations.
00150         * With each handler a \c uri or \c path is associated. Whenever a request is received the server will
00151         * walk through all registered handlers and check which \c path is matching.
00152         * @param T : class which will be instanciated to serve these requests for the associated \b path.
00153         * @param path : request uri starting with this \c path will be served using this handler.
00154         */
00155         template<typename T>
00156         void addHandler(const char* path)
00157         { m_lpHandlers[path] = &T::create; }
00158     
00159         /**
00160         * Replaces the standard error Handler. The error Handler will be called everytime a request is not
00161         * matching any of the registered \c paths or \c uris.
00162         * @param hdlFunc: User specified handler function which will be used in error conditions.
00163         */
00164         void addErrorHandler(HTTPRequestHandlerFunction hdlFunc)
00165         { m_pErrorHandler = hdlFunc!=NULL ?hdlFunc : StdErrorHandler; }    
00166 
00167         /** Binds server to a specific port and starts listening. This member prepares the internal variables and the server socket
00168         * and terminates after successfull initialization
00169         * @param port : port on which to listen for incoming connections
00170         * @param pEthernet : a pointer to an existing EthernetInterface object or NULL if the HTTPServer shall allocate the object. _Please note that for compatibility reasons
00171         * your should consider to create the EthernetInterface as a static variable. Otherwise the the object will be created on the heap._
00172         * @returns : false if an unrecoverable error occured or if the ethernet interface was not set or not initialized correctly, or true if everything was ok.
00173         */
00174         bool start(int port = 80, EthernetInterface* pEthernet = NULL);
00175         
00176         /** Performs the regular polling of the server component. Needs to be called cyclically.
00177         * The function will internally check whether new connections are requested by a client and will also poll all existing client connections.
00178         * @param blocking : if true, 
00179         * @returns -1 if there was a problem. If 0 is returned, the latest request was served successfully and the server is
00180         * ready for processing the next request. Simply call \c poll as long as you want to serve new incoming requests.
00181         */
00182         int poll(bool blocking = true);
00183         
00184     private:
00185         
00186         /** The standard error handler function.
00187         * @param msg : Request message data.
00188         * @param tcp : Socket to be used for responding.
00189         */
00190         static void StdErrorHandler(HTTPConnection::HTTPMessage& msg, TCPSocket* tcp);
00191         
00192         /** Internal function which processes a request and which will try to find the matching handler function
00193         * for the given request. Please note that the function will search through the list of handlers, iterating
00194         * from longest to shortest \c paths. If the registered \c path is a subset of the request the associated
00195         * handler is considered as being a match.
00196         * @param msg : Request message data. Contains the requested logical \c uri. 
00197         * @param tcp : Socket to be used for communication with the client.
00198         */
00199         void HandleRequest(HTTPConnection::HTTPMessage& msg, TCPSocket* tcp);
00200     
00201         /** Map of handler objects. Can be any object derived from \ref HTTPRequestHeader. Use the \ref addHandler function
00202         * to register new handler objects.
00203         */
00204         map<string, HTTPRequestHandler* (*)(const char*, const char*, HTTPConnection::HTTPMessage&, TCPSocket*), handlersComp>   m_lpHandlers;
00205         HTTPRequestHandlerFunction m_pErrorHandler;
00206         
00207  };
00208  
00209  #endif //__HTTPSERVER_H__