First commit
[anna.git] / include / anna / http / Transport.hpp
1 // ANNA - Anna is Not 'N' Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
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
16 // distribution.
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.
20 //
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.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_http_Transport_hpp
38 #define anna_http_Transport_hpp
39
40 #include <anna/core/DataBlock.hpp>
41
42 #include <anna/comm/Transport.hpp>
43 #include <anna/comm/TransportFactory.hpp>
44 #include <anna/comm/TransportFactoryImpl.hpp>
45
46 #include <anna/http/internal/Tokenizer.hpp>
47 #include <anna/http/Message.hpp>
48
49 namespace anna {
50
51 namespace http {
52
53 class EncodedBlock;
54
55 namespace parser {
56 class Abstract;
57 }
58
59 /**
60    Clase generica para definir la capa de transporte del protocolo HTTP.
61
62    \see Transport.
63 */
64 class Transport : public comm::Transport {
65 public:
66   /**
67    * Constructor.
68    * Sólo debería usarse en caso de tener que usar el método #externalDecode.
69    */
70   Transport();
71
72   /**
73      Devuelve la longitud del cuerpo del mensaje asociado.
74      \return la longitud del cuerpo del mensaje asociado.
75      \warning Exclusivamente de uso interno.
76   */
77   int getContentLength() const throw() { return a_contentLength; }
78
79   /**
80      Devuelve el mensaje de entrada asociado.
81      \return La instancia del mensaje de entrada asociado.
82      \warning Exclusivamente de uso interno.
83   */
84   http::Message* getInputMessage() throw(RuntimeException);
85
86   /**
87      Establece la longitud del cuerpo del mensaje asociado.
88      \param contentLength Longitud del cuerpo del mensaje asociado.
89      \warning Exclusivamente de uso interno.
90   */
91   void setContentLength(const int contentLength) throw(RuntimeException) { a_contentLength = contentLength; }
92
93   /**
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.
97   */
98   void setBodyOffset(const int bodyOffset) throw(RuntimeException) { a_bodyOffset = bodyOffset; }
99
100   /**
101      Metodo que inicializa el estado de esta capa de transporte. Se invoca
102      directamente por el nucleo cuando sea necesario.
103   */
104   void clear() throw();
105
106   /**
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.
113    */
114   const http::Message* externalDecode(const char* buffer, const int length) throw(RuntimeException);
115
116   /**
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.
120      \internal
121   */
122   http::Message* allocateInputMessage(const Message::Type::_v type) throw(RuntimeException);
123
124   /**
125    * Devuelve el bloque de datos codificados asociados a esta instancia.
126    * \warning Exclusivamente uso interno.
127    */
128   EncodedBlock* getEncodedBlock() throw();
129
130   /**
131      Separa el token recibido como parametro en distintos componentes basicos, usando
132      como separadores los caracteres de espacios, tabs, etc.
133
134      \param token Token sobre el que deseamos aplicar la separacion.
135
136      \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
137   */
138   const Tokenizer& split(const Token& token) throw(RuntimeException);
139
140   /**
141      Separa el token recibido como parametro en distintos componentes basicos.
142
143      \param token Token sobre el que deseamos aplicar la separacion.
144      \param separator Separador usado para detectar los tokens. No puede ser NULL:
145
146      \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
147   */
148   const Tokenizer& split(const Token& token, const char* separator) throw(RuntimeException);
149
150   /**
151      Separa el token recibido como parametro en distintos componentes basicos.
152
153      \param token Token sobre el que deseamos aplicar la separacion.
154      \param separator Separador usado para detectar los tokens.
155
156      \return Una instancia del Tokenizer con el que poder recorrer todos los componentes.
157   */
158   const Tokenizer& split(const Token& token, const char separator) throw(RuntimeException);
159
160   /**
161      Devuelve el literal que identifica de esta clase.
162      \return el literal que identifica de esta clase.
163   */
164   static const char* className() throw() { return "anna::http::Transport"; }
165
166   /**
167      Devuelve el gestor de capas de transporte asociado a esta clase.
168      \return El gestor de capas de transporte asociado a esta clase.
169   */
170   static comm::TransportFactory& getFactory() throw() { return st_factory; }
171
172 private:
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;
187   int a_contentLength;
188   int a_bodyOffset;
189   DataBlock a_result;
190   bool a_haveToClear;
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;
197
198   static comm::TransportFactoryImpl <http::Transport> st_factory;
199
200   void setParserState(const parser::Abstract* parser) throw(RuntimeException);
201
202   int calculeSize(const DataBlock&) throw(RuntimeException);
203   const comm::Message* decode(const DataBlock&) throw(RuntimeException);
204   const DataBlock& code(comm::Message&) throw(RuntimeException);
205
206   /*
207      static const Token* tryRequest (const Tokenizer&) throw ();
208      static const Token* tryResponse (const Tokenizer&) throw ();
209   */
210   friend class anna::Allocator <http::Transport>;
211   friend class parser::Abstract;
212 };
213
214 }
215 }
216 #endif
217