Contiki 3.x
httpd.c
1 /*
2  * Copyright (c) 2004, Adam Dunkels.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * This file is part of the Contiki operating system.
30  *
31  * Author: Adam Dunkels <adam@sics.se>
32  *
33  */
34 
35 #include <string.h>
36 
37 #include "contiki-net.h"
38 
39 #include "webserver.h"
40 #include "httpd-fs.h"
41 #include "httpd-cgi.h"
42 #include "httpd.h"
43 #include "raven-lcd.h"
44 
45 //#include "http-strings.h"
46 #if COFFEE_FILES
47 #include "cfs-coffee-arch.h"
48 #endif /* COFFEE_FILES */
49 
50 /* DEBUGLOGIC is a convenient way to debug in a simulator without a tcp/ip connection.
51  * Break the program in the process loop and step from the entry in httpd_appcall.
52  * The input file is forced to /index.html and the output directed to TCPBUF.
53  * If cgi's are invoked define it in httpd-cgi.c as well!
54  * psock_generator_send in /core/net/psock.c must also be modified as follows:
55  * ...
56  * // Wait until all data is sent and acknowledged.
57  * if (!s->sendlen) break; //<---add this line
58  * PT_YIELD_UNTIL(&s->psockpt, uip_acked() || uip_rexmit());
59  * ...
60  */
61 #define DEBUGLOGIC 0
62 #define DEBUG 0
63 #if DEBUGLOGIC
64 struct httpd_state *sg;
65 #define uip_mss(...) 512
66 #define uip_appdata TCPBUF
67 char TCPBUF[512];
68 #endif
69 #if DEBUG
70 #include <stdio.h>
71 #if HTTPD_STRING_TYPE==PROGMEM_TYPE
72 #define PRINTF(FORMAT,args...) printf_P(PSTR(FORMAT),##args)
73 #else
74 #define PRINTF printf
75 #endif
76 #else
77 #define PRINTF(...)
78 #endif
79 
80 #ifndef WEBSERVER_CONF_CGI_CONNS
81 #define CONNS 4
82 #else
83 #define CONNS WEBSERVER_CONF_CGI_CONNS
84 #endif /* WEBSERVER_CONF_CGI_CONNS */
85 
86 #define STATE_WAITING 0
87 #define STATE_OUTPUT 1
88 
89 //#define SEND_STRING(s, str) PSOCK_SEND(s, (uint8_t *)str, (unsigned int)strlen(str))
90 MEMB(conns, struct httpd_state, CONNS);
91 
92 /* MAX_SCRIPT_NAME_LENGTH should be at least be the maximum file name length+2 for %!: includes */
93 #define MAX_SCRIPT_NAME_LENGTH 20
94 #define ISO_tab 0x09
95 #define ISO_nl 0x0a
96 #define ISO_cr 0x0d
97 #define ISO_space 0x20
98 #define ISO_bang 0x21
99 #define ISO_percent 0x25
100 #define ISO_period 0x2e
101 #define ISO_slash 0x2f
102 #define ISO_colon 0x3a
103 
104 /*---------------------------------------------------------------------------*/
105 static unsigned short
106 generate(void *state)
107 {
108  struct httpd_state *s = (struct httpd_state *)state;
109 
110  if(s->file.len > uip_mss()) {
111  s->len = uip_mss();
112  } else {
113  s->len = s->file.len;
114  }
115  httpd_fs_cpy(uip_appdata, s->file.data, s->len);
116 #if DEBUGLOGIC
117  return 0;
118 #else
119  return s->len;
120 #endif
121 }
122 /*---------------------------------------------------------------------------*/
123 static
124 PT_THREAD(send_file(struct httpd_state *s))
125 {
126  PSOCK_BEGIN(&s->sout);
127 
128  do {
129  PSOCK_GENERATOR_SEND(&s->sout, generate, s);
130  s->file.len -= s->len;
131  s->file.data += s->len;
132  } while(s->file.len > 0);
133 
134  PSOCK_END(&s->sout);
135 }
136 /*---------------------------------------------------------------------------*/
137 static
138 PT_THREAD(send_part_of_file(struct httpd_state *s))
139 {
140  PSOCK_BEGIN(&s->sout);
141 
142  static int oldfilelen, oldlen;
143  static char * olddata;
144 
145  //Store stuff that gets clobbered...
146  oldfilelen = s->file.len;
147  oldlen = s->len;
148  olddata = s->file.data;
149 
150  //How much to send
151  s->file.len = s->len;
152 
153  do {
154  PSOCK_GENERATOR_SEND(&s->sout, generate, s);
155  s->file.len -= s->len;
156  s->file.data += s->len;
157  } while(s->file.len > 0);
158 
159  s->len = oldlen;
160  s->file.len = oldfilelen;
161  s->file.data = olddata;
162 
163  PSOCK_END(&s->sout);
164 }
165 /*---------------------------------------------------------------------------*/
166 static void
167 next_scriptstate(struct httpd_state *s)
168 {
169  char *p;
170 /* Skip over any script parameters to the beginning of the next line */
171  if((p = (char *)httpd_fs_strchr(s->scriptptr, ISO_nl)) != NULL) {
172  p += 1;
173  s->scriptlen -= (unsigned short)(p - s->scriptptr);
174  s->scriptptr = p;
175  } else {
176  s->scriptlen = 0;
177  }
178 
179  /* char *p;
180  p = strchr(s->scriptptr, ISO_nl) + 1;
181  s->scriptlen -= (unsigned short)(p - s->scriptptr);
182  s->scriptptr = p;*/
183 }
184 
185 /*---------------------------------------------------------------------------*/
186 char *
187 get_scriptname(char *dest, char *fromfile)
188 {
189  uint8_t i=0,skip=1;
190  /* Extract a file or cgi name, trim leading spaces and replace termination with zero */
191  /* Returns number of characters processed up to the next non-tab or space */
192  do {
193  dest[i]=httpd_fs_getchar(fromfile++);
194  if (dest[i]==ISO_colon) {if (!skip) break;} //allow leading colons
195  else if (dest[i]==ISO_tab ) {if (skip) continue;else break;}//skip leading tabs
196  else if (dest[i]==ISO_space) {if (skip) continue;else break;}//skip leading spaces
197  else if (dest[i]==ISO_nl ) break; //nl is preferred delimiter
198  else if (dest[i]==ISO_cr ) break; //some editors insert cr
199  else if (dest[i]==0 ) break; //files are terminated with null
200  else skip=0;
201  i++;
202  } while (i<(MAX_SCRIPT_NAME_LENGTH+1));
203  fromfile--;
204  while ((dest[i]==ISO_space) || (dest[i]==ISO_tab)) dest[i]=httpd_fs_getchar(++fromfile);
205  dest[i]=0;
206  return (fromfile);
207 }
208 /*---------------------------------------------------------------------------*/
209 
210 static
211 PT_THREAD(handle_script(struct httpd_state *s))
212 {
213  /* Note script includes will attach a leading : to the filename and a trailing zero */
214  static char scriptname[MAX_SCRIPT_NAME_LENGTH+1],*pptr;
215  static uint16_t filelength;
216 
217  PT_BEGIN(&s->scriptpt);
218 
219  filelength=s->file.len;
220  while(s->file.len > 0) {
221  /* Sanity check */
222  if (s->file.len > filelength) break;
223 
224  /* Check if we should start executing a script, flagged by %! */
225  if(httpd_fs_getchar(s->file.data) == ISO_percent &&
226  httpd_fs_getchar(s->file.data + 1) == ISO_bang) {
227 
228  /* Extract name, if starts with colon include file else call cgi */
229  s->scriptptr=get_scriptname(scriptname,s->file.data+2);
230  s->scriptlen=s->file.len-(s->scriptptr-s->file.data);
231  PRINTF("httpd: Handle script named %s\n",scriptname);
232  if(scriptname[0] == ISO_colon) {
233  if (httpd_fs_open(&scriptname[1], &s->file)) {
234  PT_WAIT_THREAD(&s->scriptpt, send_file(s));
235  }
236  } else {
237  PT_WAIT_THREAD(&s->scriptpt,httpd_cgi(scriptname)(s, s->scriptptr));
238  }
239  next_scriptstate(s);
240 
241  /* Reset the pointers and continue sending the current file. */
242  s->file.data = s->scriptptr;
243  s->file.len = s->scriptlen;
244  } else {
245 
246  /* Send file up to the next potential script */
247  if(s->file.len > uip_mss()) {
248  s->len = uip_mss();
249  } else {
250  s->len = s->file.len;
251  }
252 
253  if(httpd_fs_getchar(s->file.data) == ISO_percent) {
254  pptr = (char *) httpd_fs_strchr(s->file.data + 1, ISO_percent);
255  } else {
256  pptr = (char *) httpd_fs_strchr(s->file.data, ISO_percent);
257  }
258 
259  if(pptr != NULL && pptr != s->file.data) {
260  s->len = (int)(pptr - s->file.data);
261  if(s->len >= uip_mss()) {
262  s->len = uip_mss();
263  }
264  }
265  PRINTF("httpd: Sending %u bytes from 0x%04x\n",s->file.len,(unsigned int)s->file.data);
266  PT_WAIT_THREAD(&s->scriptpt, send_part_of_file(s));
267  s->file.data += s->len;
268  s->file.len -= s->len;
269  }
270  }
271 
272  PT_END(&s->scriptpt);
273 }
274 /*---------------------------------------------------------------------------*/
275 const char httpd_http[] HTTPD_STRING_ATTR = "HTTP/1.0 ";
276 const char httpd_server[] HTTPD_STRING_ATTR = "\r\nServer: Contiki/2.0 http://www.sics.se/contiki/\r\nConnection: close\r\n";
277 static unsigned short
278 generate_status(void *sstr)
279 {
280  uint8_t slen=httpd_strlen((char *)sstr);
281  httpd_memcpy(uip_appdata, httpd_http, sizeof(httpd_http)-1);
282  httpd_memcpy(uip_appdata+sizeof(httpd_http)-1, (char *)sstr, slen);
283  slen+=sizeof(httpd_http)-1;
284  httpd_memcpy(uip_appdata+slen, httpd_server, sizeof(httpd_server)-1);
285 #if DEBUGLOGIC
286  return 0;
287 #else
288  return slen+sizeof(httpd_server)-1;
289 #endif
290 }
291 /*---------------------------------------------------------------------------*/
292 const char httpd_content[] HTTPD_STRING_ATTR = "Content-type: ";
293 const char httpd_crlf[] HTTPD_STRING_ATTR = "\r\n\r\n";
294 static unsigned short
295 generate_header(void *hstr)
296 {
297  uint8_t slen=httpd_strlen((char *)hstr);
298  httpd_memcpy(uip_appdata,httpd_content,sizeof(httpd_content)-1);
299  httpd_memcpy(uip_appdata+sizeof(httpd_content)-1, (char *)hstr, slen);
300  slen+=sizeof(httpd_content)-1;
301  httpd_memcpy(uip_appdata+slen,httpd_crlf,sizeof(httpd_crlf)-1);
302 #if DEBUGLOGIC
303  return 0;
304 #else
305  return slen+4;
306 #endif
307 }
308 /*---------------------------------------------------------------------------*/
309 const char httpd_mime_htm[] HTTPD_STRING_ATTR = "text/html";
310 const char httpd_mime_css[] HTTPD_STRING_ATTR = "text/css";
311 const char httpd_mime_png[] HTTPD_STRING_ATTR = "image/png";
312 const char httpd_mime_gif[] HTTPD_STRING_ATTR = "image/gif";
313 const char httpd_mime_jpg[] HTTPD_STRING_ATTR = "image/jpeg";
314 const char httpd_mime_txt[] HTTPD_STRING_ATTR = "text/plain";
315 const char httpd_mime_bin[] HTTPD_STRING_ATTR = "application/octet-stream";
316 const char httpd_jpg [] HTTPD_STRING_ATTR = "jpg";
317 const char httpd_shtml [] HTTPD_STRING_ATTR = ".shtml";
318 
319 static
320 PT_THREAD(send_headers(struct httpd_state *s, const char *statushdr))
321 {
322  char *ptr;
323  PSOCK_BEGIN(&s->sout);
324 
325  PSOCK_GENERATOR_SEND(&s->sout, generate_status, (char *)statushdr);
326 
327  ptr = strrchr(s->filename, ISO_period);
328  if (httpd_strncmp("4", statushdr, 1)==0) {
329  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_htm );
330  } else if(ptr == NULL) {
331  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_bin );
332  } else {
333  ptr++;
334  if(httpd_strncmp(ptr, &httpd_mime_htm[5],3)== 0 ||httpd_strncmp(ptr, &httpd_shtml[1], 4) == 0) {
335  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_htm );
336  } else if(httpd_strcmp(ptr, &httpd_mime_css[5]) == 0) {
337  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_css );
338  } else if(httpd_strcmp(ptr, &httpd_mime_png[6]) == 0) {
339  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_png );
340  } else if(httpd_strcmp(ptr, &httpd_mime_gif[6])== 0) {
341  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_gif );
342  } else if(httpd_strcmp(ptr, httpd_mime_jpg) == 0) {
343  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_jpg );
344  } else {
345  PSOCK_GENERATOR_SEND(&s->sout, generate_header, &httpd_mime_txt);
346  }
347  }
348  PSOCK_END(&s->sout);
349 }
350 /*---------------------------------------------------------------------------*/
351 const char httpd_indexfn [] HTTPD_STRING_ATTR = "/index.html";
352 const char httpd_404fn [] HTTPD_STRING_ATTR = "/404.html";
353 const char httpd_404notf [] HTTPD_STRING_ATTR = "404 Not found";
354 const char httpd_200ok [] HTTPD_STRING_ATTR = "200 OK";
355 static
356 PT_THREAD(handle_output(struct httpd_state *s))
357 {
358  char *ptr;
359 
360  PT_BEGIN(&s->outputpt);
361 #if DEBUGLOGIC
362  httpd_strcpy(s->filename,httpd_indexfn);
363 #endif
364  if(!httpd_fs_open(s->filename, &s->file)) {
365  httpd_strcpy(s->filename, httpd_404fn);
366  httpd_fs_open(s->filename, &s->file);
367  PT_WAIT_THREAD(&s->outputpt, send_headers(s, httpd_404notf));
368  PT_WAIT_THREAD(&s->outputpt, send_file(s));
369  } else {
370  PT_WAIT_THREAD(&s->outputpt, send_headers(s, httpd_200ok));
371  ptr = strchr(s->filename, ISO_period);
372  if((ptr != NULL && httpd_strncmp(ptr, httpd_shtml, 6) == 0) || httpd_strcmp(s->filename,httpd_indexfn)==0) {
373  PT_INIT(&s->scriptpt);
374  PT_WAIT_THREAD(&s->outputpt, handle_script(s));
375  } else {
376  PT_WAIT_THREAD(&s->outputpt, send_file(s));
377  }
378  }
379  PSOCK_CLOSE(&s->sout);
380  PT_END(&s->outputpt);
381 }
382 /*---------------------------------------------------------------------------*/
383 const char httpd_get[] HTTPD_STRING_ATTR = "GET ";
384 const char httpd_ref[] HTTPD_STRING_ATTR = "Referer:";
385 static
386 PT_THREAD(handle_input(struct httpd_state *s))
387 {
388 
389  PSOCK_BEGIN(&s->sin);
390 
391  PSOCK_READTO(&s->sin, ISO_space);
392 
393  if(httpd_strncmp(s->inputbuf, httpd_get, 4) != 0) {
394  PSOCK_CLOSE_EXIT(&s->sin);
395  }
396  PSOCK_READTO(&s->sin, ISO_space);
397 
398  if(s->inputbuf[0] != ISO_slash) {
399  PSOCK_CLOSE_EXIT(&s->sin);
400  }
401 
402  if(s->inputbuf[1] == ISO_space) {
403  httpd_strcpy(s->filename, httpd_indexfn);
404  } else {
405  s->inputbuf[PSOCK_DATALEN(&s->sin) - 1] = 0;
406  strncpy(s->filename, &s->inputbuf[0], sizeof(s->filename));
407 {
408  /* Look for ?, if found strip file name and send any following text to the LCD */
409  uint8_t i;
410  for (i=0;i<sizeof(s->inputbuf);i++) {
411  if (s->inputbuf[i]=='?') {
412  raven_lcd_show_text(&s->inputbuf[i]);
413  if (i<sizeof(s->filename)) s->filename[i]=0;
414  // s->inputbuf[i]=0; //allow multiple beeps with multiple ?'s
415  }
416  if (s->inputbuf[i]==0) break;
417  }
418 }
419  }
420 
421  webserver_log_file(&uip_conn->ripaddr, s->filename);
422 
423  s->state = STATE_OUTPUT;
424 
425  while(1) {
426  PSOCK_READTO(&s->sin, ISO_nl);
427 
428  if(httpd_strncmp(s->inputbuf, httpd_ref, 8) == 0) {
429  s->inputbuf[PSOCK_DATALEN(&s->sin) - 2] = 0;
430  petsciiconv_topetscii(s->inputbuf, PSOCK_DATALEN(&s->sin) - 2);
431  webserver_log(s->inputbuf);
432  }
433  }
434  PSOCK_END(&s->sin);
435 }
436 /*---------------------------------------------------------------------------*/
437 static void
438 handle_connection(struct httpd_state *s)
439 {
440 #if DEBUGLOGIC
441  handle_output(s);
442 #else
443  handle_input(s);
444  if(s->state == STATE_OUTPUT) {
445  handle_output(s);
446  }
447 #endif
448 }
449 /*---------------------------------------------------------------------------*/
450 void
451 httpd_appcall(void *state)
452 {
453 #if DEBUGLOGIC
454  struct httpd_state *s; //Enter here for debugging with output directed to TCPBUF
455  s = sg = (struct httpd_state *)memb_alloc(&conns);
456  if (1) {
457 #else
458  struct httpd_state *s = (struct httpd_state *)state;
459  if(uip_closed() || uip_aborted() || uip_timedout()) {
460  if(s != NULL) {
461  memb_free(&conns, s);
462  }
463  } else if(uip_connected()) {
464  s = (struct httpd_state *)memb_alloc(&conns);
465  if(s == NULL) {
466  uip_abort();
467  return;
468  }
469 #endif
470  tcp_markconn(uip_conn, s);
471  PSOCK_INIT(&s->sin, (uint8_t *)s->inputbuf, sizeof(s->inputbuf) - 1);
472  PSOCK_INIT(&s->sout, (uint8_t *)s->inputbuf, sizeof(s->inputbuf) - 1);
473  PT_INIT(&s->outputpt);
474  s->state = STATE_WAITING;
475  /* timer_set(&s->timer, CLOCK_SECOND * 100);*/
476  s->timer = 0;
477  handle_connection(s);
478  } else if(s != NULL) {
479  if(uip_poll()) {
480  ++s->timer;
481  if(s->timer >= 20) {
482  uip_abort();
483  memb_free(&conns, s);
484  }
485  } else {
486  s->timer = 0;
487  }
488  handle_connection(s);
489  } else {
490  uip_abort();
491  }
492 }
493 /*---------------------------------------------------------------------------*/
494 void
495 httpd_init(void)
496 {
497  tcp_listen(UIP_HTONS(80));
498  memb_init(&conns);
499  httpd_cgi_init();
500 }
501 /*---------------------------------------------------------------------------*/
#define PT_WAIT_THREAD(pt, thread)
Block and wait until a child protothread completes.
Definition: pt.h:191
#define PSOCK_READTO(psock, c)
Read data up to a specified character.
Definition: psock.h:291
void memb_init(struct memb *m)
Initialize a memory block that was declared with MEMB().
Definition: memb.c:52
#define PSOCK_CLOSE_EXIT(psock)
Close a protosocket and exit the protosocket&#39;s protothread.
Definition: psock.h:331
#define PSOCK_BEGIN(psock)
Start the protosocket protothread in a function.
Definition: psock.h:164
Representation of a uIP TCP connection.
Definition: uip.h:1336
#define uip_aborted()
Has the connection been aborted by the other end?
Definition: uip.h:781
char memb_free(struct memb *m, void *ptr)
Deallocate a memory block from a memory block previously declared with MEMB().
Definition: memb.c:79
#define uip_mss()
Get the current maximum segment size that can be sent on the current connection.
Definition: uip.h:838
void * memb_alloc(struct memb *m)
Allocate a memory block from a block of memory declared with MEMB().
Definition: memb.c:59
#define NULL
The null pointer.
#define PT_INIT(pt)
Initialize a protothread.
Definition: pt.h:79
#define uip_poll()
Is the connection being polled by uIP?
Definition: uip.h:817
#define UIP_HTONS(n)
Convert 16-bit quantity from host byte order to network byte order.
Definition: uip.h:1238
#define PT_THREAD(name_args)
Declaration of a protothread.
Definition: pt.h:99
#define uip_connected()
Has the connection just been connected?
Definition: uip.h:761
#define uip_abort()
Abort the current connection.
Definition: uip.h:682
#define PSOCK_INIT(psock, buffer, buffersize)
Initialize a protosocket.
Definition: psock.h:150
#define PSOCK_GENERATOR_SEND(psock, generator, arg)
Generate data with a function and send it.
Definition: psock.h:225
#define MEMB(name, structure, num)
Declare a memory block.
Definition: memb.h:89
#define PSOCK_CLOSE(psock)
Close a protosocket.
Definition: psock.h:241
#define PSOCK_END(psock)
Declare the end of a protosocket&#39;s protothread.
Definition: psock.h:348
#define PT_BEGIN(pt)
Declare the start of a protothread inside the C function implementing the protothread.
Definition: pt.h:114
#define uip_timedout()
Has the connection timed out?
Definition: uip.h:791
#define PT_END(pt)
Declare the end of a protothread.
Definition: pt.h:126
CCIF void tcp_listen(uint16_t port)
Open a TCP port.
#define PSOCK_DATALEN(psock)
The length of the data that was previously read.
Definition: psock.h:304
#define uip_closed()
Has the connection been closed by the other end?
Definition: uip.h:771
uip_ipaddr_t ripaddr
The IP address of the remote host.
Definition: uip.h:1337
uip_appdata
Pointer to the application data in the packet buffer.
Definition: tcp_loader.c:74