Add some utility to manage query strings.
[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
69 /**
70  * Get key value from tokenized buffer
71  */
72 int http_getValue(char *tolenized_buf, size_t tolenized_buf_len, const char *key, char *value, size_t len)
73 {
74         if (!tolenized_buf || !key || !value)
75                 return -1;
76
77         char *p = tolenized_buf;
78         size_t value_len = 0;
79
80         memset(value, 0, len);
81
82         for (size_t i = 0; i < tolenized_buf_len; i++)
83         {
84                 if (!strcmp(key, p))
85                 {
86                         /* skip key */
87                         size_t jump = strlen(p) + 1;
88                         p += jump;
89
90                         value_len = strlen(p);
91                         if (value_len >= len)
92                                 return -1;
93
94                         strcpy(value, p);
95                         break;
96                 }
97                 /* jump to next pair */
98                 p += strlen(p) + 1;
99         }
100
101         return value_len;
102 }
103
104 /**
105  * tokenize a buffer
106  */
107 int http_tokenizeGetRequest(char *raw_buf, size_t raw_len)
108 {
109         size_t token = 0;
110
111     for(size_t i = 0; (i < raw_len) && raw_buf; i++)
112         {
113                 if (raw_buf[i] == '&')
114                 {
115                         token++;
116                         raw_buf[i] = '\0';
117                 }
118
119                 if (raw_buf[i] == '=')
120                         raw_buf[i] = '\0';
121     }
122
123     return token + 1;
124 }
125
126 static char http_hexToAscii(char first, char second)
127 {
128         char hex[5], *stop;
129         hex[0] = '0';
130         hex[1] = 'x';
131         hex[2] = first;
132         hex[3] = second;
133         hex[4] = 0;
134         return strtol(hex, &stop, 16);
135 }
136
137 void http_decodeUri(const char *raw_buf, size_t raw_len, char *decodec_buf, size_t len)
138 {
139         char value;
140         for (size_t i = 0; i < raw_len; i++)
141         {
142                 if (!len)
143                         return;
144
145                 if (raw_buf[i] == '%')
146                 {
147                         if (i + 2 < raw_len)
148                         {
149                                 /* convert hex value after % */
150                                 value = http_hexToAscii(raw_buf[i + 1], raw_buf[i + 2]);
151                                 if (value)
152                                 {
153                                         *decodec_buf++ = value;
154                                         len--;
155                                         i += 2;
156                                         continue;
157                                 }
158                         }
159                 }
160                 *decodec_buf++ = raw_buf[i];
161                 len--;
162         }
163 }
164
165 void http_getPageName(const char *recv_buf, size_t recv_len, char *page_name, size_t len)
166 {
167         int i = 0;
168         bool str_ok = false;
169         const char *p = recv_buf;
170         if (p && (recv_len > sizeof("GET /")))
171         {
172                 if (*p++ == 'G' &&
173                         *p++ == 'E' && *p++ == 'T')
174                         {
175                                 str_ok = true;
176                                 /* skip the space and "/" */
177                                 p += 2;
178                         }
179         }
180
181         if (str_ok)
182         {
183                 while ((size_t)i < recv_len)
184                 {
185                         char ch = *(p++);
186                         if (ch == ' ' || ch == '\t' || ch == '\n')
187                                 break;
188                         if((size_t)i == len - 1)
189                                 break;
190                         page_name[i++] = ch;
191                 }
192         }
193
194         page_name[i] = '\0';
195 }
196
197 INLINE const char *get_ext(const char *name)
198 {
199         const char *ext = strstr(name, ".");
200         if(ext && (ext + 1))
201                 return (ext + 1);
202
203         return NULL;
204 }
205
206
207 /**
208  * Send on \param client socket
209  * the 200 Ok http header
210  */
211 void http_sendOk(struct netconn *client)
212 {
213         netconn_write(client, http_html_hdr_200, sizeof(http_html_hdr_200) - 1, NETCONN_NOCOPY);
214 }
215
216
217 /**
218  * Send on \param client socket
219  * the 404 File not found http header
220  */
221 void http_sendFileNotFound(struct netconn *client)
222 {
223         netconn_write(client, http_html_hdr_404, sizeof(http_html_hdr_404) - 1, NETCONN_NOCOPY);
224 }
225
226 /**
227  * Send on \param client socket
228  * the 500 internal server error http header
229  */
230 void http_sendInternalErr(struct netconn *client)
231 {
232         netconn_write(client, http_html_hdr_500, sizeof(http_html_hdr_500) - 1, NETCONN_NOCOPY);
233 }
234
235 static http_handler_t cgi_search(const char *name,  HttpCGI *table)
236 {
237         if (!table)
238                 return NULL;
239
240         int i = 0;
241         const char *ext = get_ext(name);
242         LOG_INFO("EXT %s\n", ext);
243         while(table[i].name)
244         {
245                 if (ext && table[i].type == CGI_MATCH_EXT)
246                 {
247                         LOG_INFO("Match all ext %s\n", ext);
248                         if (!strcmp(table[i].name, ext))
249                                 break;
250                 }
251                 else if (table[i].type == CGI_MATCH_NAME)
252                 {
253                         LOG_INFO("Match all name %s\n", name);
254                         if (strstr(name, table[i].name) != NULL)
255                                 break;
256                 }
257                 else /* (table[i].type == CGI_MATCH_WORD) */
258                 {
259                         LOG_INFO("Match all word %s\n", name);
260                         if (!strcmp(table[i].name, name))
261                                 break;
262                 }
263
264                 i++;
265         }
266
267         return table[i].handler;
268 }
269
270 static char req_string[80];
271
272 /**
273  * Http polling function.
274  *
275  * Call this functions to process each client connections.
276  *
277  */
278 void http_poll(struct netconn *server)
279 {
280         struct netconn *client;
281         struct netbuf *rx_buf_conn;
282         char *rx_buf;
283         uint16_t len;
284
285         client = netconn_accept(server);
286         if (!client)
287                 return;
288
289         rx_buf_conn = netconn_recv(client);
290         if (rx_buf_conn)
291         {
292                 netbuf_data(rx_buf_conn, (void **)&rx_buf, &len);
293                 if (rx_buf)
294                 {
295                         memset(req_string, 0, sizeof(req_string));
296                         http_getPageName(rx_buf, len, req_string, sizeof(req_string));
297
298                         LOG_INFO("Search %s\n", req_string);
299                         if (req_string[0] == '\0')
300                                 strcpy(req_string, HTTP_DEFAULT_PAGE);
301
302                         http_handler_t cgi = cgi_search(req_string, cgi_table);
303                         if (cgi)
304                         {
305                                 if (cgi(client, req_string, rx_buf, len) < 0)
306                                 {
307                                         LOG_ERR("Internal server error\n");
308                                         http_sendInternalErr(client);
309                                         netconn_write(client, http_server_error, http_server_error_len - 1, NETCONN_NOCOPY);
310                                 }
311                         }
312                         else
313                         {
314                                 http_callback(client, req_string, rx_buf, len);
315                         }
316                 }
317                 netconn_close(client);
318                 netbuf_delete(rx_buf_conn);
319         }
320         netconn_delete(client);
321 }
322
323 /**
324  * Init the http server.
325  *
326  * The simply http server call for each client request the default_callback function. The
327  * user should define this callback to manage the client request, i.e. reading site's page
328  * from SD card. The user can define the cgi_table, where associate one callback to the user string.
329  * In this way the user could filter some client request and redirect they to custom callback, i.e.
330  * the client could request status of the device only loading the particular page name.
331  *
332  * \param default_callback fuction that server call for all request, that does'nt match cgi table.
333  * \param table of callcack to call when client request a particular page.
334  */
335 void http_init(http_handler_t default_callback, struct HttpCGI *table)
336 {
337         ASSERT(default_callback);
338
339         cgi_table = table;
340         http_callback = default_callback;
341 }
342