Minor fix.
[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 static struct { const char *key; const char *content; } http_content_type[] =
62 {
63         {"",    "Content-type: application/json\r\n\r\n"},
64         {"htm", "Content-type: text/html\r\n\r\n"},
65         {"css", "Content-type: text/css\r\n\r\n"},
66         {"js",  "Content-type: text/javascript\r\n\r\n"},
67         {"png", "Content-type: image/png\r\n\r\n"},
68         {"jpg", "Content-type: image/jpeg\r\n\r\n"},
69         {"gif", "Content-type: image/gif\r\n\r\n"},
70         {"txt", "Content-type: text/plain\r\n\r\n"},
71 };
72
73 static const char http_html_hdr_200[] = "HTTP/1.0 200 OK\r\n";
74 static const char http_html_hdr_404[] = "HTTP/1.0 404 Not Found\r\n";
75 static const char http_html_hdr_500[] = "HTTP/1.0 500 Internal Server Error\r\n";
76
77 static HttpCGI *cgi_table;
78 static http_handler_t http_callback;
79 static char decoded_str[80];
80
81 /**
82  * Get key value from tokenized buffer
83  */
84 int http_getValue(char *tolenized_buf, size_t tolenized_buf_len, const char *key, char *value, size_t len)
85 {
86         if (!tolenized_buf || !key || !value)
87                 return -1;
88
89         char *p = tolenized_buf;
90         size_t value_len = 0;
91
92         memset(value, 0, len);
93
94         for (size_t i = 0; i < tolenized_buf_len; i++)
95         {
96                 size_t token_len = strlen(p);
97                 http_decodeUrl(p, token_len, decoded_str, sizeof(decoded_str));
98
99                 if (!strcmp(key, decoded_str))
100                 {
101                         /* skip key */
102                         p += token_len + 1;
103
104                         value_len = http_decodeUrl(p, strlen(p), decoded_str, sizeof(decoded_str));
105
106                         if (value_len >= len)
107                                 return -1;
108
109                         strcpy(value, decoded_str);
110                         return value_len;
111                 }
112                 /* jump to next pair */
113                 p += token_len + 1;
114         }
115
116         return -1;
117 }
118
119 /**
120  * tokenize a buffer
121  */
122 int http_tokenizeGetRequest(char *raw_buf, size_t raw_len)
123 {
124         size_t token = 0;
125
126     for(size_t i = 0; (i < raw_len) && raw_buf; i++)
127         {
128                 if (raw_buf[i] == '&')
129                 {
130                         token++;
131                         raw_buf[i] = '\0';
132                 }
133
134                 if (raw_buf[i] == '=')
135                         raw_buf[i] = '\0';
136     }
137
138     return token + 1;
139 }
140
141 static char http_hexToAscii(char first, char second)
142 {
143         char hex[5], *stop;
144         hex[0] = '0';
145         hex[1] = 'x';
146         hex[2] = first;
147         hex[3] = second;
148         hex[4] = 0;
149         return strtol(hex, &stop, 16);
150 }
151
152 size_t http_decodeUrl(const char *raw_buf, size_t raw_len, char *decodec_buf, size_t len)
153 {
154         ASSERT(decodec_buf);
155
156         char value;
157         size_t i;
158         memset(decodec_buf, 0, len);
159
160         for (i = 0; i < raw_len; i++)
161         {
162                 if (len <= 1)
163                         return i;
164
165                 if (raw_buf[i] == '%')
166                 {
167                         if (i + 2 < raw_len)
168                         {
169                                 /* convert hex value after % */
170                                 value = http_hexToAscii(raw_buf[i + 1], raw_buf[i + 2]);
171                                 if (value)
172                                 {
173                                         *decodec_buf++ = value;
174                                         len--;
175                                         /* decoded two digit of hex value, go to next value*/
176                                         i += 2;
177                                         continue;
178                                 }
179                         }
180                 }
181
182                 /* Manage special case of '+', that it should be convert in space */
183                 *decodec_buf++ = (raw_buf[i] == '+' ? ' ' : raw_buf[i]);
184                 len--;
185         }
186
187         return i;
188 }
189
190 void http_getPageName(const char *recv_buf, size_t recv_len, char *page_name, size_t len)
191 {
192         int i = 0;
193         bool str_ok = false;
194         const char *p = recv_buf;
195         if (p && (recv_len > sizeof("GET /")))
196         {
197                 if (*p++ == 'G' && *p++ == 'E' && *p++ == 'T')
198                 {
199                         str_ok = true;
200                         /* skip the space and "/" */
201                         p += 2;
202                 }
203         }
204
205         if (str_ok)
206         {
207                 while ((size_t)i < recv_len)
208                 {
209                         char ch = *(p++);
210                         if (ch == ' ' || ch == '\t' || ch == '\n')
211                                 break;
212                         if((size_t)i == len - 1)
213                                 break;
214                         page_name[i++] = ch;
215                 }
216         }
217
218         page_name[i] = '\0';
219 }
220
221 INLINE const char *get_ext(const char *name)
222 {
223         const char *ext = strstr(name, ".");
224         if(ext != NULL && ext[1] != '\0')
225                 return (ext + 1);
226
227         return NULL;
228 }
229
230 int http_searchContentType(const char *name)
231 {
232         if (!name)
233                 return 0;
234
235         const char *ext = get_ext(name);
236         LOG_INFO("Ext: %s\n", !ext ? "none" : ext);
237
238         if (!ext)
239                 return 0;
240
241         if (!strcmp(ext, "ico"))
242                 return HTTP_CONTENT_JPEG;
243
244         for (int i = 0; i < HTTP_CONTENT_CNT; i++)
245         {
246                 if (!strcmp(ext, http_content_type[i].key))
247                         return i;
248         }
249
250         return 0;
251 }
252
253
254 /**
255  * Send on \param client socket the 200 Ok http header with
256  * select \param content_type
257  */
258 void http_sendOk(struct netconn *client, int content_type)
259 {
260         ASSERT(content_type < HTTP_CONTENT_CNT);
261
262         netconn_write(client, http_html_hdr_200, sizeof(http_html_hdr_200) - 1, NETCONN_NOCOPY);
263         netconn_write(client, http_content_type[content_type].content,
264                         strlen(http_content_type[content_type].content), NETCONN_NOCOPY);
265 }
266
267
268 /**
269  * Send on \param client socket the 404 File not found http header with
270  * select \param content_type
271  */
272 void http_sendFileNotFound(struct netconn *client, int content_type)
273 {
274         ASSERT(content_type < HTTP_CONTENT_CNT);
275
276         netconn_write(client, http_html_hdr_404, sizeof(http_html_hdr_404) - 1, NETCONN_NOCOPY);
277         netconn_write(client, http_content_type[content_type].content,
278                         strlen(http_content_type[content_type].content), NETCONN_NOCOPY);
279 }
280
281 /**
282  * Send on \param client socket the 500 internal server error http header with
283  * select \param content_type
284  */
285 void http_sendInternalErr(struct netconn *client, int content_type)
286 {
287         ASSERT(content_type < HTTP_CONTENT_CNT);
288
289         netconn_write(client, http_html_hdr_500, sizeof(http_html_hdr_500) - 1, NETCONN_NOCOPY);
290         netconn_write(client, http_content_type[content_type].content,
291                         strlen(http_content_type[content_type].content), NETCONN_NOCOPY);
292 }
293
294 static http_handler_t cgi_search(const char *name,  HttpCGI *table)
295 {
296         if (!table)
297                 return NULL;
298
299         int i = 0;
300         const char *ext = get_ext(name);
301
302         while(table[i].name)
303         {
304                 if (ext && table[i].type == CGI_MATCH_EXT)
305                 {
306
307                         if (!strcmp(table[i].name, ext))
308                         {
309                                 LOG_INFO("Match ext: %s\n", ext);
310                                 break;
311                         }
312                 }
313                 else if (table[i].type == CGI_MATCH_NAME)
314                 {
315
316                         if (strstr(name, table[i].name) != NULL)
317                         {
318                                 LOG_INFO("Match string: %s\n", name);
319                                 break;
320                         }
321                 }
322                 else /* (table[i].type == CGI_MATCH_WORD) */
323                 {
324
325                         if (!strcmp(table[i].name, name))
326                         {
327                                 LOG_INFO("Word match: %s\n", name);
328                                 break;
329                         }
330                 }
331
332                 i++;
333         }
334
335         return table[i].handler;
336 }
337
338 static char req_string[80];
339
340 /**
341  * Http polling function.
342  *
343  * Call this functions to process each client connections.
344  *
345  */
346 void http_poll(struct netconn *server)
347 {
348         struct netconn *client;
349         struct netbuf *rx_buf_conn;
350         char *rx_buf;
351         uint16_t len;
352
353         client = netconn_accept(server);
354         if (!client)
355                 return;
356
357         rx_buf_conn = netconn_recv(client);
358         if (rx_buf_conn)
359         {
360                 netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
361                 if (rx_buf)
362                 {
363                         memset(req_string, 0, sizeof(req_string));
364                         http_getPageName(rx_buf, len, req_string, sizeof(req_string));
365
366                         if (req_string[0] == '\0')
367                                 strcpy(req_string, HTTP_DEFAULT_PAGE);
368
369                         http_handler_t cgi = cgi_search(req_string, cgi_table);
370                         if (cgi)
371                         {
372                                 if (cgi(client, req_string, rx_buf, len) < 0)
373                                 {
374                                         LOG_ERR("Internal server error\n");
375                                         http_sendInternalErr(client, HTTP_CONTENT_HTML);
376                                         netconn_write(client, http_server_error, http_server_error_len - 1, NETCONN_NOCOPY);
377                                 }
378                         }
379                         else
380                         {
381                                 http_callback(client, req_string, rx_buf, len);
382                         }
383                 }
384                 netconn_close(client);
385                 netbuf_delete(rx_buf_conn);
386         }
387         netconn_delete(client);
388 }
389
390 /**
391  * Init the http server.
392  *
393  * The simply http server call for each client request the default_callback function. The
394  * user should define this callback to manage the client request, i.e. reading site's page
395  * from SD card. The user can define the cgi_table, where associate one callback to the user string.
396  * In this way the user could filter some client request and redirect they to custom callback, i.e.
397  * the client could request status of the device only loading the particular page name.
398  *
399  * \param default_callback fuction that server call for all request, that does'nt match cgi table.
400  * \param table of callcack to call when client request a particular page.
401  */
402 void http_init(http_handler_t default_callback, struct HttpCGI *table)
403 {
404         ASSERT(default_callback);
405
406         cgi_table = table;
407         http_callback = default_callback;
408 }
409