1 // ANNA - Anna is Not 'N' Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // https://bitbucket.org/testillano/anna
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
37 #ifndef anna_http_Transport_hpp
38 #define anna_http_Transport_hpp
40 #include <anna/core/DataBlock.hpp>
42 #include <anna/comm/Transport.hpp>
43 #include <anna/comm/TransportFactory.hpp>
44 #include <anna/comm/TransportFactoryImpl.hpp>
46 #include <anna/http/internal/Tokenizer.hpp>
47 #include <anna/http/Message.hpp>
60 Clase generica para definir la capa de transporte del protocolo HTTP.
64 class Transport : public comm::Transport {
68 * Sólo debería usarse en caso de tener que usar el método #externalDecode.
73 Devuelve la longitud del cuerpo del mensaje asociado.
74 \return la longitud del cuerpo del mensaje asociado.
75 \warning Exclusivamente de uso interno.
77 int getContentLength() const throw() { return a_contentLength; }
80 Devuelve el mensaje de entrada asociado.
81 \return La instancia del mensaje de entrada asociado.
82 \warning Exclusivamente de uso interno.
84 http::Message* getInputMessage() throw(RuntimeException);
87 Establece la longitud del cuerpo del mensaje asociado.
88 \param contentLength Longitud del cuerpo del mensaje asociado.
89 \warning Exclusivamente de uso interno.
91 void setContentLength(const int contentLength) throw(RuntimeException) { a_contentLength = contentLength; }
94 Establece la posicion donde comienza el cuerpo del mensaje asociado.
95 \param bodyOffset Posicion donde comienza el cuerpor del mensaje.
96 \warning Exclusivamente de uso interno.
98 void setBodyOffset(const int bodyOffset) throw(RuntimeException) { a_bodyOffset = bodyOffset; }
101 Metodo que inicializa el estado de esta capa de transporte. Se invoca
102 directamente por el nucleo cuando sea necesario.
104 void clear() throw();
107 * Permite obtener una instancia de anna::http::Message correspondiente al búfer recibido como parámetro.
108 * \param buffer Espacio de memoria que contiene el mensaje HTTP a interpretar.
109 * \param length Longitud del búfer.
110 * \Warning Al ser invocado desde el exterior de la plataforma no hay ninguna sección crítica que la
111 * proteja, porque lo que si se invoca en modo MT desde varios thread habrá que establecer las secciones
112 * críticas necesarias para que sólo un thread pueda acceder a este método.
114 const http::Message* externalDecode(const char* buffer, const int length) throw(RuntimeException);
117 Instancia un mensaje HTTP de entrada del tipo determinado por \em type.
118 \param type Tipo de mensaje HTTP detectado en la entrada.
119 \return La instancia del mensaje creado.
122 http::Message* allocateInputMessage(const Message::Type::_v type) throw(RuntimeException);
125 * Devuelve el bloque de datos codificados asociados a esta instancia.
126 * \warning Exclusivamente uso interno.
128 EncodedBlock* getEncodedBlock() throw();
131 Separa el token recibido como parametro en distintos componentes basicos, usando
132 como separadores los caracteres de espacios, tabs, etc.
134 \param token Token sobre el que deseamos aplicar la separacion.
136 \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
138 const Tokenizer& split(const Token& token) throw(RuntimeException);
141 Separa el token recibido como parametro en distintos componentes basicos.
143 \param token Token sobre el que deseamos aplicar la separacion.
144 \param separator Separador usado para detectar los tokens. No puede ser NULL:
146 \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
148 const Tokenizer& split(const Token& token, const char* separator) throw(RuntimeException);
151 Separa el token recibido como parametro en distintos componentes basicos.
153 \param token Token sobre el que deseamos aplicar la separacion.
154 \param separator Separador usado para detectar los tokens.
156 \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
158 const Tokenizer& split(const Token& token, const char separator) throw(RuntimeException);
161 Devuelve el literal que identifica de esta clase.
162 \return el literal que identifica de esta clase.
164 static const char* className() throw() { return "anna::http::Transport"; }
167 Devuelve el gestor de capas de transporte asociado a esta clase.
168 \return El gestor de capas de transporte asociado a esta clase.
170 static comm::TransportFactory& getFactory() throw() { return st_factory; }
173 //-------------------------------------------------------------------------------------
174 // - a_parser: Analizador del mensaje HTTP. Realiza un analisis en profundidad para
175 // interpretar el contenido del mensaje.
176 // - a_contentLenth: Tamaño indicado por la etiqueta HTTP Content-length.
177 // - a_bodyOffset: Indica el desplazamiento que hay que aplicar en http::Transport::decode
178 // para direccionar el contenido del mensaje HTTP.
179 // - a_result: El decode nos obliga a devolver un DataBlock => devolvemos el
180 // a_inputMessage que nos dara la direccion al http::Message al invocar a
181 // DataBlock::getData.
182 // - a_haveToClear: Indica si el metodo calculeSize debe iniciar el estado de la instancia.
183 // - a_inputMessage: Instancia del mensaje obtenida al realizar el analisis detallado
184 // del ultimo mensaje recibido.
185 //--------------------------------------------------------------------------------------
186 const parser::Abstract* a_parser;
191 http::Message* a_inputMessage;
192 Tokenizer a_fullScope;
193 Tokenizer a_lineScope;
194 EncodedBlock* a_encodedBlock;
195 int a_lastChunkedByte;
196 const DataBlock* a_fullMessage;
198 static comm::TransportFactoryImpl <http::Transport> st_factory;
200 void setParserState(const parser::Abstract* parser) throw(RuntimeException);
202 int calculeSize(const DataBlock&) throw(RuntimeException);
203 const comm::Message* decode(const DataBlock&) throw(RuntimeException);
204 const DataBlock& code(comm::Message&) throw(RuntimeException);
207 static const Token* tryRequest (const Tokenizer&) throw ();
208 static const Token* tryResponse (const Tokenizer&) throw ();
210 friend class anna::Allocator <http::Transport>;
211 friend class parser::Abstract;