2ea1004452f1e31ea21efeb157b39415e7af3260
[bertos.git] / bertos / net / http.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2011 Develer S.r.l. (http://www.develer.com/)
30  *
31  * -->
32  *
33  * \author Daniele Basile <asterix@develer.com>
34  *
35  * \brief Simple Http server.
36  *
37  * This simple web server read the site's pages from SD card, and manage
38  * the cases where SD is not present or page not found, using embedded pages.
39  * Quering from browser the /status page, the server return a json dictionary where are store
40  * some board status info, like board temperature, up-time, etc.
41  *
42  * notest: avr
43  */
44
45 #include "http.h"
46
47 #include "hw/hw_sd.h"
48 #include "hw/hw_http.h"
49
50 #include "cfg/cfg_http.h"
51
52 // Define logging setting (for cfg/log.h module).
53 #define LOG_LEVEL         HTTP_LOG_LEVEL
54 #define LOG_VERBOSITY     HTTP_LOG_FORMAT
55 #include <cfg/log.h>
56
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60
61
62 static const char http_html_hdr_200[] = "HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n";
63 static const char http_html_hdr_404[] = "HTTP/1.0 404 Not Found\r\nContent-type: text/html\r\n\r\n";
64 static const char http_html_hdr_500[] = "HTTP/1.0 500 Internal Server Error\r\nContent-type: text/html\r\n\r\n";
65
66 static HttpCGI *cgi_table;
67 static http_handler_t http_callback;
68 static char decoded_str[80];
69
70 /**
71  * Get key value from tokenized buffer
72  */
73 int http_getValue(char *tolenized_buf, size_t tolenized_buf_len, const char *key, char *value, size_t len)
74 {
75         if (!tolenized_buf || !key || !value)
76                 return -1;
77
78         char *p = tolenized_buf;
79         size_t value_len = 0;
80
81         memset(value, 0, len);
82
83         for (size_t i = 0; i < tolenized_buf_len; i++)
84         {
85                 size_t token_len = strlen(p);
86                 http_decodeUrl(p, token_len, decoded_str, sizeof(decoded_str));
87
88                 if (!strcmp(key, decoded_str))
89                 {
90                         /* skip key */
91                         p += token_len + 1;
92
93                         http_decodeUrl(p, strlen(p), decoded_str, sizeof(decoded_str));
94                         value_len = strlen(decoded_str);
95
96                         if (value_len >= len)
97                                 return -1;
98
99                         strcpy(value, decoded_str);
100                         break;
101                 }
102                 /* jump to next pair */
103                 p += token_len + 1;
104         }
105
106         return value_len;
107 }
108
109 /**
110  * tokenize a buffer
111  */
112 int http_tokenizeGetRequest(char *raw_buf, size_t raw_len)
113 {
114         size_t token = 0;
115
116     for(size_t i = 0; (i < raw_len) && raw_buf; i++)
117         {
118                 if (raw_buf[i] == '&')
119                 {
120                         token++;
121                         raw_buf[i] = '\0';
122                 }
123
124                 if (raw_buf[i] == '=')
125                         raw_buf[i] = '\0';
126     }
127
128     return token + 1;
129 }
130
131 static char http_hexToAscii(char first, char second)
132 {
133         char hex[5], *stop;
134         hex[0] = '0';
135         hex[1] = 'x';
136         hex[2] = first;
137         hex[3] = second;
138         hex[4] = 0;
139         return strtol(hex, &stop, 16);
140 }
141
142 void http_decodeUrl(const char *raw_buf, size_t raw_len, char *decodec_buf, size_t len)
143 {
144         ASSERT(decodec_buf);
145
146         char value;
147         memset(decodec_buf, 0, len);
148
149         for (size_t i = 0; i < raw_len; i++)
150         {
151                 if (!len)
152                         return;
153
154                 if (raw_buf[i] == '%')
155                 {
156                         if (i + 2 < raw_len)
157                         {
158                                 /* convert hex value after % */
159                                 value = http_hexToAscii(raw_buf[i + 1], raw_buf[i + 2]);
160                                 if (value)
161                                 {
162                                         *decodec_buf++ = value;
163                                         len--;
164                                         /* decoded two digit of hex value, go to next value*/
165                                         i += 2;
166                                         continue;
167                                 }
168                         }
169                 }
170
171                 /* Manage special case of '+', that it should be convert in space */
172                 *decodec_buf++ = (raw_buf[i] == '+' ? ' ' : raw_buf[i]);
173                 len--;
174         }
175 }
176
177 void http_getPageName(const char *recv_buf, size_t recv_len, char *page_name, size_t len)
178 {
179         int i = 0;
180         bool str_ok = false;
181         const char *p = recv_buf;
182         if (p && (recv_len > sizeof("GET /")))
183         {
184                 if (*p++ == 'G' && *p++ == 'E' && *p++ == 'T')
185                 {
186                         str_ok = true;
187                         /* skip the space and "/" */
188                         p += 2;
189                 }
190         }
191
192         if (str_ok)
193         {
194                 while ((size_t)i < recv_len)
195                 {
196                         char ch = *(p++);
197                         if (ch == ' ' || ch == '\t' || ch == '\n')
198                                 break;
199                         if((size_t)i == len - 1)
200                                 break;
201                         page_name[i++] = ch;
202                 }
203         }
204
205         page_name[i] = '\0';
206 }
207
208 INLINE const char *get_ext(const char *name)
209 {
210         const char *ext = strstr(name, ".");
211         if(ext && (ext + 1))
212                 return (ext + 1);
213
214         return NULL;
215 }
216
217
218 /**
219  * Send on \param client socket
220  * the 200 Ok http header
221  */
222 void http_sendOk(struct netconn *client)
223 {
224         netconn_write(client, http_html_hdr_200, sizeof(http_html_hdr_200) - 1, NETCONN_NOCOPY);
225 }
226
227
228 /**
229  * Send on \param client socket
230  * the 404 File not found http header
231  */
232 void http_sendFileNotFound(struct netconn *client)
233 {
234         netconn_write(client, http_html_hdr_404, sizeof(http_html_hdr_404) - 1, NETCONN_NOCOPY);
235 }
236
237 /**
238  * Send on \param client socket
239  * the 500 internal server error http header
240  */
241 void http_sendInternalErr(struct netconn *client)
242 {
243         netconn_write(client, http_html_hdr_500, sizeof(http_html_hdr_500) - 1, NETCONN_NOCOPY);
244 }
245
246 static http_handler_t cgi_search(const char *name,  HttpCGI *table)
247 {
248         if (!table)
249                 return NULL;
250
251         int i = 0;
252         const char *ext = get_ext(name);
253         LOG_INFO("EXT %s\n", ext);
254         while(table[i].name)
255         {
256                 if (ext && table[i].type == CGI_MATCH_EXT)
257                 {
258                         LOG_INFO("Match all ext %s\n", ext);
259                         if (!strcmp(table[i].name, ext))
260                                 break;
261                 }
262                 else if (table[i].type == CGI_MATCH_NAME)
263                 {
264                         LOG_INFO("Match all name %s\n", name);
265                         if (strstr(name, table[i].name) != NULL)
266                                 break;
267                 }
268                 else /* (table[i].type == CGI_MATCH_WORD) */
269                 {
270                         LOG_INFO("Match all word %s\n", name);
271                         if (!strcmp(table[i].name, name))
272                                 break;
273                 }
274
275                 i++;
276         }
277
278         return table[i].handler;
279 }
280
281 static char req_string[80];
282
283 /**
284  * Http polling function.
285  *
286  * Call this functions to process each client connections.
287  *
288  */
289 void http_poll(struct netconn *server)
290 {
291         struct netconn *client;
292         struct netbuf *rx_buf_conn;
293         char *rx_buf;
294         uint16_t len;
295
296         client = netconn_accept(server);
297         if (!client)
298                 return;
299
300         rx_buf_conn = netconn_recv(client);
301         if (rx_buf_conn)
302         {
303                 netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
304                 if (rx_buf)
305                 {
306                         memset(req_string, 0, sizeof(req_string));
307                         http_getPageName(rx_buf, len, req_string, sizeof(req_string));
308
309                         LOG_INFO("Search %s\n", req_string);
310                         if (req_string[0] == '\0')
311                                 strcpy(req_string, HTTP_DEFAULT_PAGE);
312
313                         http_handler_t cgi = cgi_search(req_string, cgi_table);
314                         if (cgi)
315                         {
316                                 if (cgi(client, req_string, rx_buf, len) < 0)
317                                 {
318                                         LOG_ERR("Internal server error\n");
319                                         http_sendInternalErr(client);
320                                         netconn_write(client, http_server_error, http_server_error_len - 1, NETCONN_NOCOPY);
321                                 }
322                         }
323                         else
324                         {
325                                 http_callback(client, req_string, rx_buf, len);
326                         }
327                 }
328                 netconn_close(client);
329                 netbuf_delete(rx_buf_conn);
330         }
331         netconn_delete(client);
332 }
333
334 /**
335  * Init the http server.
336  *
337  * The simply http server call for each client request the default_callback function. The
338  * user should define this callback to manage the client request, i.e. reading site's page
339  * from SD card. The user can define the cgi_table, where associate one callback to the user string.
340  * In this way the user could filter some client request and redirect they to custom callback, i.e.
341  * the client could request status of the device only loading the particular page name.
342  *
343  * \param default_callback fuction that server call for all request, that does'nt match cgi table.
344  * \param table of callcack to call when client request a particular page.
345  */
346 void http_init(http_handler_t default_callback, struct HttpCGI *table)
347 {
348         ASSERT(default_callback);
349
350         cgi_table = table;
351         http_callback = default_callback;
352 }
353