http_static: debug spew control, session expiration timers
[vpp.git] / src / plugins / http_static / static_server.c
1 /*
2  * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <vnet/vnet.h>
17 #include <vnet/session/application.h>
18 #include <vnet/session/application_interface.h>
19 #include <vnet/session/session.h>
20 #include <vppinfra/tw_timer_2t_1w_2048sl.h>
21 #include <vppinfra/unix.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <http_static/http_static.h>
26 #include <vppinfra/bihash_vec8_8.h>
27
28 #include <vppinfra/bihash_template.c>
29
30 /** @file
31     Simple Static http server, sufficient to
32     serve .html / .css / .js content.
33 */
34 /*? %%clicmd:group_label Static HTTP Server %% ?*/
35
36 /** \brief Session States
37  */
38
39 typedef enum
40 {
41   /** Session is closed */
42   HTTP_STATE_CLOSED,
43   /** Session is established */
44   HTTP_STATE_ESTABLISHED,
45   /** Session has sent an OK response */
46   HTTP_STATE_OK_SENT,
47   /** Session has sent an HTML response */
48   HTTP_STATE_SEND_MORE_DATA,
49   /** Number of states */
50   HTTP_STATE_N_STATES,
51 } http_session_state_t;
52
53 typedef enum
54 {
55   CALLED_FROM_RX,
56   CALLED_FROM_TX,
57   CALLED_FROM_TIMER,
58 } state_machine_called_from_t;
59
60
61 /** \brief Application session
62  */
63 typedef struct
64 {
65   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
66   /** Base class instance variables */
67 #define _(type, name) type name;
68   foreach_app_session_field
69 #undef _
70   /** rx thread index */
71   u32 thread_index;
72   /** rx buffer */
73   u8 *rx_buf;
74   /** vpp session index, handle */
75   u32 vpp_session_index;
76   u64 vpp_session_handle;
77   /** Timeout timer handle */
78   u32 timer_handle;
79   /** Fully-resolved file path */
80   u8 *path;
81   /** File data, a vector */
82   u8 *data;
83   /** Current data send offset */
84   u32 data_offset;
85   /** File cache pool index */
86   u32 cache_pool_index;
87   /** state machine called from... */
88   state_machine_called_from_t called_from;
89 } http_session_t;
90
91 /** \brief In-memory file data cache entry
92  */
93 typedef struct
94 {
95   /** Name of the file */
96   u8 *filename;
97   /** Contents of the file, as a u8 * vector */
98   u8 *data;
99   /** Last time the cache entry was used */
100   f64 last_used;
101   /** Cache LRU links */
102   u32 next_index;
103   u32 prev_index;
104   /** Reference count, so we don't recycle while referenced */
105   int inuse;
106 } file_data_cache_t;
107
108 /** \brief Main data structure
109  */
110
111 typedef struct
112 {
113   /** Per thread vector of session pools */
114   http_session_t **sessions;
115   /** Session pool reader writer lock */
116   clib_rwlock_t sessions_lock;
117   /** vpp session to http session index map */
118   u32 **session_to_http_session;
119
120   /** Enable debug messages */
121   int debug_level;
122
123   /** vpp message/event queue */
124   svm_msg_q_t **vpp_queue;
125
126   /** Unified file data cache pool */
127   file_data_cache_t *cache_pool;
128   /** Hash table which maps file name to file data */
129     BVT (clib_bihash) name_to_data;
130
131   /** Current cache size */
132   u64 cache_size;
133   /** Max cache size in bytes */
134   u64 cache_limit;
135   /** Number of cache evictions */
136   u64 cache_evictions;
137
138   /** Cache LRU listheads */
139   u32 first_index;
140   u32 last_index;
141
142   /** root path to be served */
143   u8 *www_root;
144
145   /** Server's event queue */
146   svm_queue_t *vl_input_queue;
147
148   /** API client handle */
149   u32 my_client_index;
150
151   /** Application index */
152   u32 app_index;
153
154   /** Process node index for event scheduling */
155   u32 node_index;
156
157   /** Session cleanup timer wheel */
158   tw_timer_wheel_2t_1w_2048sl_t tw;
159   clib_spinlock_t tw_lock;
160
161   /** Time base, so we can generate browser cache control http spew */
162   clib_timebase_t timebase;
163
164   /** Number of preallocated fifos, usually 0 */
165   u32 prealloc_fifos;
166   /** Private segment size, usually 0 */
167   u32 private_segment_size;
168   /** Size of the allocated rx, tx fifos, roughly 8K or so */
169   u32 fifo_size;
170   /** The bind URI, defaults to tcp://0.0.0.0/80 */
171   u8 *uri;
172   vlib_main_t *vlib_main;
173 } http_static_server_main_t;
174
175 http_static_server_main_t http_static_server_main;
176
177 /** \brief Format the called-from enum
178  */
179
180 static u8 *
181 format_state_machine_called_from (u8 * s, va_list * args)
182 {
183   state_machine_called_from_t cf =
184     va_arg (*args, state_machine_called_from_t);
185   char *which = "bogus!";
186
187   switch (cf)
188     {
189     case CALLED_FROM_RX:
190       which = "from rx";
191       break;
192     case CALLED_FROM_TX:
193       which = "from tx";
194       break;
195     case CALLED_FROM_TIMER:
196       which = "from timer";
197       break;
198
199     default:
200       break;
201     }
202
203   s = format (s, "%s", which);
204   return s;
205 }
206
207
208 /** \brief Acquire reader lock on the sessions pools
209  */
210 static void
211 http_static_server_sessions_reader_lock (void)
212 {
213   clib_rwlock_reader_lock (&http_static_server_main.sessions_lock);
214 }
215
216 /** \brief Drop reader lock on the sessions pools
217  */
218 static void
219 http_static_server_sessions_reader_unlock (void)
220 {
221   clib_rwlock_reader_unlock (&http_static_server_main.sessions_lock);
222 }
223
224 /** \brief Acquire writer lock on the sessions pools
225  */
226 static void
227 http_static_server_sessions_writer_lock (void)
228 {
229   clib_rwlock_writer_lock (&http_static_server_main.sessions_lock);
230 }
231
232 /** \brief Drop writer lock on the sessions pools
233  */
234 static void
235 http_static_server_sessions_writer_unlock (void)
236 {
237   clib_rwlock_writer_unlock (&http_static_server_main.sessions_lock);
238 }
239
240 /** \brief Allocate an http session
241  */
242 static http_session_t *
243 http_static_server_session_alloc (u32 thread_index)
244 {
245   http_static_server_main_t *hsm = &http_static_server_main;
246   http_session_t *hs;
247   pool_get (hsm->sessions[thread_index], hs);
248   memset (hs, 0, sizeof (*hs));
249   hs->session_index = hs - hsm->sessions[thread_index];
250   hs->thread_index = thread_index;
251   hs->timer_handle = ~0;
252   hs->cache_pool_index = ~0;
253   return hs;
254 }
255
256 /** \brief Get an http session by index
257  */
258 static http_session_t *
259 http_static_server_session_get (u32 thread_index, u32 hs_index)
260 {
261   http_static_server_main_t *hsm = &http_static_server_main;
262   if (pool_is_free_index (hsm->sessions[thread_index], hs_index))
263     return 0;
264   return pool_elt_at_index (hsm->sessions[thread_index], hs_index);
265 }
266
267 /** \brief Free an http session
268  */
269 static void
270 http_static_server_session_free (http_session_t * hs)
271 {
272   http_static_server_main_t *hsm = &http_static_server_main;
273   pool_put (hsm->sessions[hs->thread_index], hs);
274   if (CLIB_DEBUG)
275     memset (hs, 0xfa, sizeof (*hs));
276 }
277
278 /** \brief add a session to the vpp < -- > http session index map
279  */
280 static void
281 http_static_server_session_lookup_add (u32 thread_index, u32 s_index,
282                                        u32 hs_index)
283 {
284   http_static_server_main_t *hsm = &http_static_server_main;
285   vec_validate (hsm->session_to_http_session[thread_index], s_index);
286   hsm->session_to_http_session[thread_index][s_index] = hs_index;
287 }
288
289 /** \brief Remove a session from the vpp < -- > http session index map
290  */
291 static void
292 http_static_server_session_lookup_del (u32 thread_index, u32 s_index)
293 {
294   http_static_server_main_t *hsm = &http_static_server_main;
295   hsm->session_to_http_session[thread_index][s_index] = ~0;
296 }
297
298 /** \brief lookup a session in the vpp < -- > http session index map
299  */
300
301 static http_session_t *
302 http_static_server_session_lookup (u32 thread_index, u32 s_index)
303 {
304   http_static_server_main_t *hsm = &http_static_server_main;
305   u32 hs_index;
306
307   if (s_index < vec_len (hsm->session_to_http_session[thread_index]))
308     {
309       hs_index = hsm->session_to_http_session[thread_index][s_index];
310       return http_static_server_session_get (thread_index, hs_index);
311     }
312   return 0;
313 }
314
315 /** \brief Start a session cleanup timer
316  */
317 static void
318 http_static_server_session_timer_start (http_session_t * hs)
319 {
320   u32 hs_handle;
321   hs_handle = hs->thread_index << 24 | hs->session_index;
322   clib_spinlock_lock (&http_static_server_main.tw_lock);
323   hs->timer_handle = tw_timer_start_2t_1w_2048sl (&http_static_server_main.tw,
324                                                   hs_handle, 0, 60);
325   clib_spinlock_unlock (&http_static_server_main.tw_lock);
326 }
327
328 /** \brief stop a session cleanup timer
329  */
330 static void
331 http_static_server_session_timer_stop (http_session_t * hs)
332 {
333   if (hs->timer_handle == ~0)
334     return;
335   clib_spinlock_lock (&http_static_server_main.tw_lock);
336   tw_timer_stop_2t_1w_2048sl (&http_static_server_main.tw, hs->timer_handle);
337   clib_spinlock_unlock (&http_static_server_main.tw_lock);
338 }
339
340 /** \brief Detach cache entry from session
341  */
342
343 static void
344 http_static_server_detach_cache_entry (http_session_t * hs)
345 {
346   http_static_server_main_t *hsm = &http_static_server_main;
347   file_data_cache_t *ep;
348
349   /*
350    * Decrement cache pool entry reference count
351    * Note that if e.g. a file lookup fails, the cache pool index
352    * won't be set
353    */
354   if (hs->cache_pool_index != ~0)
355     {
356       ep = pool_elt_at_index (hsm->cache_pool, hs->cache_pool_index);
357       ep->inuse--;
358       if (hsm->debug_level > 1)
359         clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
360                       ep->inuse);
361     }
362   hs->cache_pool_index = ~0;
363   hs->data = 0;
364   hs->data_offset = 0;
365   vec_free (hs->path);
366 }
367
368 /** \brief clean up a session
369  */
370
371 static void
372 http_static_server_session_cleanup (http_session_t * hs)
373 {
374   if (!hs)
375     return;
376
377   http_static_server_detach_cache_entry (hs);
378
379   http_static_server_session_lookup_del (hs->thread_index,
380                                          hs->vpp_session_index);
381   vec_free (hs->rx_buf);
382   http_static_server_session_timer_stop (hs);
383   http_static_server_session_free (hs);
384 }
385
386 /** \brief Disconnect a session
387  */
388
389 static void
390 http_static_server_session_disconnect (http_session_t * hs)
391 {
392   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
393   a->handle = hs->vpp_session_handle;
394   a->app_index = http_static_server_main.app_index;
395   vnet_disconnect_session (a);
396 }
397
398 /* *INDENT-OFF* */
399 /** \brief http error boilerplate
400  */
401 static const char *http_error_template =
402     "HTTP/1.1 %s\r\n"
403     "Date: %U GMT\r\n"
404     "Content-Type: text/html\r\n"
405     "Connection: close\r\n"
406     "Pragma: no-cache\r\n"
407     "Content-Length: 0\r\n\r\n";
408
409 /** \brief http response boilerplate
410  */
411 static const char *http_response_template =
412     "Date: %U GMT\r\n"
413     "Expires: %U GMT\r\n"
414     "Server: VPP Static\r\n"
415     "Content-Type: text/%s\r\n"
416     "Content-Length: %d\r\n\r\n";
417
418 /* *INDENT-ON* */
419
420 /** \brief send http data
421     @param hs - http session
422     @param data - the data vector to transmit
423     @param offset - transmit offset for this operation
424     @return offset for next transmit operation, may be unchanged w/ full fifo
425 */
426
427 static u32
428 static_send_data (http_session_t * hs, u8 * data, u32 length, u32 offset)
429 {
430   u32 bytes_to_send;
431   http_static_server_main_t *hsm = &http_static_server_main;
432
433   bytes_to_send = length - offset;
434
435   while (bytes_to_send > 0)
436     {
437       int actual_transfer;
438
439       actual_transfer = svm_fifo_enqueue
440         (hs->tx_fifo, bytes_to_send, data + offset);
441
442       /* Made any progress? */
443       if (actual_transfer <= 0)
444         {
445           if (hsm->debug_level > 0 && bytes_to_send > 0)
446             clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
447           return offset;
448         }
449       else
450         {
451           offset += actual_transfer;
452           bytes_to_send -= actual_transfer;
453
454           if (hsm->debug_level && bytes_to_send > 0)
455             clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
456
457           if (svm_fifo_set_event (hs->tx_fifo))
458             session_send_io_evt_to_thread (hs->tx_fifo,
459                                            SESSION_IO_EVT_TX_FLUSH);
460           return offset;
461         }
462     }
463   /* NOTREACHED */
464   return ~0;
465 }
466
467 /** \brief Send an http error string
468     @param hs - the http session
469     @param str - the error string, e.g. "404 Not Found"
470 */
471 static void
472 send_error (http_session_t * hs, char *str)
473 {
474   http_static_server_main_t *hsm = &http_static_server_main;
475   u8 *data;
476   f64 now;
477
478   now = clib_timebase_now (&hsm->timebase);
479   data = format (0, http_error_template, str, format_clib_timebase_time, now);
480   static_send_data (hs, data, vec_len (data), 0);
481   vec_free (data);
482 }
483
484 /** \brief Retrieve data from the application layer
485  */
486 static int
487 session_rx_request (http_session_t * hs)
488 {
489   u32 max_dequeue, cursize;
490   int n_read;
491
492   cursize = vec_len (hs->rx_buf);
493   max_dequeue = svm_fifo_max_dequeue (hs->rx_fifo);
494   if (PREDICT_FALSE (max_dequeue == 0))
495     return -1;
496
497   vec_validate (hs->rx_buf, cursize + max_dequeue - 1);
498   n_read = app_recv_stream_raw (hs->rx_fifo, hs->rx_buf + cursize,
499                                 max_dequeue, 0, 0 /* peek */ );
500   ASSERT (n_read == max_dequeue);
501   if (svm_fifo_is_empty (hs->rx_fifo))
502     svm_fifo_unset_event (hs->rx_fifo);
503
504   _vec_len (hs->rx_buf) = cursize + n_read;
505   return 0;
506 }
507
508 /** \brief Sanity-check the forward and reverse LRU lists
509  */
510 static inline void
511 lru_validate (http_static_server_main_t * hsm)
512 {
513 #if CLIB_DEBUG > 0
514   f64 last_timestamp;
515   u32 index;
516   int i;
517   file_data_cache_t *ep;
518
519   last_timestamp = 1e70;
520   for (i = 1, index = hsm->first_index; index != ~0;)
521     {
522       ep = pool_elt_at_index (hsm->cache_pool, index);
523       index = ep->next_index;
524       /* Timestamps should be smaller (older) as we walk the fwd list */
525       if (ep->last_used > last_timestamp)
526         {
527           clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
528                         ep - hsm->cache_pool, i,
529                         ep->last_used, last_timestamp);
530         }
531       last_timestamp = ep->last_used;
532       i++;
533     }
534
535   last_timestamp = 0.0;
536   for (i = 1, index = hsm->last_index; index != ~0;)
537     {
538       ep = pool_elt_at_index (hsm->cache_pool, index);
539       index = ep->prev_index;
540       /* Timestamps should be larger (newer) as we walk the rev list */
541       if (ep->last_used < last_timestamp)
542         {
543           clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
544                         ep - hsm->cache_pool, i,
545                         ep->last_used, last_timestamp);
546         }
547       last_timestamp = ep->last_used;
548       i++;
549     }
550 #endif
551 }
552
553 /** \brief Remove a data cache entry from the LRU lists
554  */
555 static inline void
556 lru_remove (http_static_server_main_t * hsm, file_data_cache_t * ep)
557 {
558   file_data_cache_t *next_ep, *prev_ep;
559   u32 ep_index;
560
561   lru_validate (hsm);
562
563   ep_index = ep - hsm->cache_pool;
564
565   /* Deal with list heads */
566   if (ep_index == hsm->first_index)
567     hsm->first_index = ep->next_index;
568   if (ep_index == hsm->last_index)
569     hsm->last_index = ep->prev_index;
570
571   /* Fix next->prev */
572   if (ep->next_index != ~0)
573     {
574       next_ep = pool_elt_at_index (hsm->cache_pool, ep->next_index);
575       next_ep->prev_index = ep->prev_index;
576     }
577   /* Fix prev->next */
578   if (ep->prev_index != ~0)
579     {
580       prev_ep = pool_elt_at_index (hsm->cache_pool, ep->prev_index);
581       prev_ep->next_index = ep->next_index;
582     }
583   lru_validate (hsm);
584 }
585
586 /** \brief Add an entry to the LRU lists, tag w/ supplied timestamp
587  */
588
589 static inline void
590 lru_add (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
591 {
592   file_data_cache_t *next_ep;
593   u32 ep_index;
594
595   lru_validate (hsm);
596
597   ep_index = ep - hsm->cache_pool;
598
599   /*
600    * Re-add at the head of the forward LRU list,
601    * tail of the reverse LRU list
602    */
603   if (hsm->first_index != ~0)
604     {
605       next_ep = pool_elt_at_index (hsm->cache_pool, hsm->first_index);
606       next_ep->prev_index = ep_index;
607     }
608
609   ep->prev_index = ~0;
610
611   /* ep now the new head of the LRU forward list */
612   ep->next_index = hsm->first_index;
613   hsm->first_index = ep_index;
614
615   /* single session case: also the tail of the reverse LRU list */
616   if (hsm->last_index == ~0)
617     hsm->last_index = ep_index;
618   ep->last_used = now;
619
620   lru_validate (hsm);
621 }
622
623 /** \brief Remove and re-add a cache entry from/to the LRU lists
624  */
625
626 static inline void
627 lru_update (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
628 {
629   lru_remove (hsm, ep);
630   lru_add (hsm, ep, now);
631 }
632
633 /** \brief Session-layer (main) data rx callback.
634     Parse the http request, and reply to it.
635     Future extensions might include POST processing, active content, etc.
636 */
637
638 /* svm_fifo_add_want_deq_ntf (tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL)
639 get shoulder-tap when transport dequeues something, set in
640 xmit routine. */
641
642 /** \brief closed state - should never really get here
643  */
644 static int
645 state_closed (session_t * s, http_session_t * hs,
646               state_machine_called_from_t cf)
647 {
648   clib_warning ("WARNING: http session %d, called from %U",
649                 hs->session_index, format_state_machine_called_from, cf);
650   return 0;
651 }
652
653 static void
654 close_session (http_session_t * hs)
655 {
656   http_static_server_session_disconnect (hs);
657   http_static_server_session_cleanup (hs);
658 }
659
660 /** \brief established state - waiting for GET, POST, etc.
661  */
662 static int
663 state_established (session_t * s, http_session_t * hs,
664                    state_machine_called_from_t cf)
665 {
666   http_static_server_main_t *hsm = &http_static_server_main;
667   u32 request_len;
668   u8 *request = 0;
669   u8 *path;
670   int i, rv;
671   struct stat _sb, *sb = &_sb;
672   clib_error_t *error;
673
674   /* Read data from the sessison layer */
675   rv = session_rx_request (hs);
676
677   /* No data? Odd, but stay in this state and await further instructions */
678   if (rv)
679     return 0;
680
681   /* Process the client request */
682   request = hs->rx_buf;
683   request_len = vec_len (request);
684   if (vec_len (request) < 7)
685     {
686       send_error (hs, "400 Bad Request");
687       close_session (hs);
688       return 0;
689     }
690
691   /* We only handle GET requests at the moment */
692   for (i = 0; i < request_len - 4; i++)
693     {
694       if (request[i] == 'G' &&
695           request[i + 1] == 'E' &&
696           request[i + 2] == 'T' && request[i + 3] == ' ')
697         goto find_end;
698     }
699   if (hsm->debug_level > 1)
700     clib_warning ("Unknown http method");
701
702   send_error (hs, "405 Method Not Allowed");
703   close_session (hs);
704   return 0;
705
706 find_end:
707
708   /* Lose "GET " */
709   vec_delete (request, i + 5, 0);
710
711   /* Lose stuff to the right of the path */
712   for (i = 0; i < vec_len (request); i++)
713     {
714       if (request[i] == ' ' || request[i] == '?')
715         {
716           request[i] = 0;
717           break;
718         }
719     }
720
721   /*
722    * Now we can construct the file to open
723    * Browsers are capable of sporadically including a leading '/'
724    */
725   if (request[0] == '/')
726     path = format (0, "%s%s%c", hsm->www_root, request, 0);
727   else
728     path = format (0, "%s/%s%c", hsm->www_root, request, 0);
729
730   if (hsm->debug_level > 0)
731     clib_warning ("GET '%s'", path);
732
733   /* Try to find the file. 2x special cases to find index.html */
734   if (stat ((char *) path, sb) < 0      /* cant even stat the file */
735       || sb->st_size < 20       /* file too small */
736       || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
737     {
738       u32 save_length = vec_len (path) - 1;
739       /* Try appending "index.html"... */
740       _vec_len (path) -= 1;
741       path = format (path, "index.html%c", 0);
742       if (stat ((char *) path, sb) < 0  /* cant even stat the file */
743           || sb->st_size < 20   /* file too small */
744           || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
745         {
746           _vec_len (path) = save_length;
747           path = format (path, "/index.html%c", 0);
748
749           /* Send a redirect, otherwise the browser will confuse itself */
750           if (stat ((char *) path, sb) < 0      /* cant even stat the file */
751               || sb->st_size < 20       /* file too small */
752               || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
753             {
754               vec_free (path);
755               send_error (hs, "404 Not Found");
756               close_session (hs);
757               return 0;
758             }
759           else
760             {
761               transport_endpoint_t endpoint;
762               transport_proto_t proto;
763               u16 local_port;
764               int print_port = 0;
765               u8 *port_str = 0;
766
767               /*
768                * To make this bit work correctly, we need to know our local
769                * IP address, etc. and send it in the redirect...
770                */
771               u8 *redirect;
772
773               vec_delete (path, vec_len (hsm->www_root) - 1, 0);
774
775               session_get_endpoint (s, &endpoint, 1 /* is_local */ );
776
777               local_port = clib_net_to_host_u16 (endpoint.port);
778
779               proto = session_type_transport_proto (s->session_type);
780
781               if ((proto == TRANSPORT_PROTO_TCP && local_port != 80)
782                   || (proto == TRANSPORT_PROTO_TLS && local_port != 443))
783                 {
784                   print_port = 1;
785                   port_str = format (0, ":%u", (u32) local_port);
786                 }
787
788               redirect = format (0, "HTTP/1.1 301 Moved Permanently\r\n"
789                                  "Location: http%s://%U%s%s\r\n\r\n",
790                                  proto == TRANSPORT_PROTO_TLS ? "s" : "",
791                                  format_ip46_address, &endpoint.ip,
792                                  endpoint.is_ip4,
793                                  print_port ? port_str : (u8 *) "", path);
794               if (hsm->debug_level > 0)
795                 clib_warning ("redirect: %s", redirect);
796
797               vec_free (port_str);
798
799               static_send_data (hs, redirect, vec_len (redirect), 0);
800               hs->session_state = HTTP_STATE_CLOSED;
801               hs->path = 0;
802               vec_free (redirect);
803               vec_free (path);
804               close_session (hs);
805               return 0;
806             }
807         }
808     }
809
810   /* find or read the file if we haven't done so yet. */
811   if (hs->data == 0)
812     {
813       BVT (clib_bihash_kv) kv;
814       file_data_cache_t *dp;
815
816       hs->path = path;
817
818       /* First, try the cache */
819       kv.key = (u64) hs->path;
820       if (BV (clib_bihash_search) (&hsm->name_to_data, &kv, &kv) == 0)
821         {
822           if (hsm->debug_level > 1)
823             clib_warning ("lookup '%s' returned %lld", kv.key, kv.value);
824
825           /* found the data.. */
826           dp = pool_elt_at_index (hsm->cache_pool, kv.value);
827           hs->data = dp->data;
828           /* Update the cache entry, mark it in-use */
829           lru_update (hsm, dp, vlib_time_now (hsm->vlib_main));
830           hs->cache_pool_index = dp - hsm->cache_pool;
831           dp->inuse++;
832           if (hsm->debug_level > 1)
833             clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
834                           dp->inuse);
835         }
836       else
837         {
838           if (hsm->debug_level > 1)
839             clib_warning ("lookup '%s' failed", kv.key, kv.value);
840           /* Need to recycle one (or more cache) entries? */
841           if (hsm->cache_size > hsm->cache_limit)
842             {
843               int free_index = hsm->last_index;
844
845               while (free_index != ~0)
846                 {
847                   /* pick the LRU */
848                   dp = pool_elt_at_index (hsm->cache_pool, free_index);
849                   free_index = dp->prev_index;
850                   /* Which could be in use... */
851                   if (dp->inuse)
852                     {
853                       if (hsm->debug_level > 1)
854                         clib_warning ("index %d in use refcnt %d",
855                                       dp - hsm->cache_pool, dp->inuse);
856
857                     }
858                   kv.key = (u64) (dp->filename);
859                   kv.value = ~0ULL;
860                   if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
861                                                 0 /* is_add */ ) < 0)
862                     {
863                       clib_warning ("LRU delete '%s' FAILED!", dp->filename);
864                     }
865                   else if (hsm->debug_level > 1)
866                     clib_warning ("LRU delete '%s' ok", dp->filename);
867
868                   lru_remove (hsm, dp);
869                   hsm->cache_size -= vec_len (dp->data);
870                   hsm->cache_evictions++;
871                   vec_free (dp->filename);
872                   vec_free (dp->data);
873                   if (hsm->debug_level > 1)
874                     clib_warning ("pool put index %d", dp - hsm->cache_pool);
875                   pool_put (hsm->cache_pool, dp);
876                   if (hsm->cache_size < hsm->cache_limit)
877                     break;
878                 }
879             }
880
881           /* Read the file */
882           error = clib_file_contents ((char *) (hs->path), &hs->data);
883           if (error)
884             {
885               clib_warning ("Error reading '%s'", hs->path);
886               clib_error_report (error);
887               vec_free (hs->path);
888               close_session (hs);
889               return 0;
890             }
891           /* Create a cache entry for it */
892           pool_get (hsm->cache_pool, dp);
893           memset (dp, 0, sizeof (*dp));
894           dp->filename = vec_dup (hs->path);
895           dp->data = hs->data;
896           hs->cache_pool_index = dp - hsm->cache_pool;
897           dp->inuse++;
898           if (hsm->debug_level > 1)
899             clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
900                           dp->inuse);
901           lru_add (hsm, dp, vlib_time_now (hsm->vlib_main));
902           kv.key = (u64) vec_dup (hs->path);
903           kv.value = dp - hsm->cache_pool;
904           /* Add to the lookup table */
905           if (hsm->debug_level > 1)
906             clib_warning ("add '%s' value %lld", kv.key, kv.value);
907
908           if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
909                                         1 /* is_add */ ) < 0)
910             {
911               clib_warning ("BUG: add failed!");
912             }
913           hsm->cache_size += vec_len (dp->data);
914         }
915       hs->data_offset = 0;
916     }
917   /* send 200 OK first */
918   static_send_data (hs, (u8 *) "HTTP/1.1 200 OK\r\n", 17, 0);
919   hs->session_state = HTTP_STATE_OK_SENT;
920   return 1;
921 }
922
923 static int
924 state_send_more_data (session_t * s, http_session_t * hs,
925                       state_machine_called_from_t cf)
926 {
927
928   /* Start sending data */
929   hs->data_offset = static_send_data (hs, hs->data, vec_len (hs->data),
930                                       hs->data_offset);
931
932   /* Did we finish? */
933   if (hs->data_offset < vec_len (hs->data))
934     {
935       /* No: ask for a shoulder-tap when the tx fifo has space */
936       svm_fifo_add_want_deq_ntf (hs->tx_fifo,
937                                  SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL);
938       hs->session_state = HTTP_STATE_SEND_MORE_DATA;
939       return 0;
940     }
941   /* Finished with this transaction, back to HTTP_STATE_ESTABLISHED */
942
943   /* Let go of the file cache entry */
944   http_static_server_detach_cache_entry (hs);
945   hs->session_state = HTTP_STATE_ESTABLISHED;
946   return 0;
947 }
948
949 static int
950 state_sent_ok (session_t * s, http_session_t * hs,
951                state_machine_called_from_t cf)
952 {
953   http_static_server_main_t *hsm = &http_static_server_main;
954   char *suffix;
955   char *http_type;
956   u8 *http_response;
957   f64 now;
958   u32 offset;
959
960   /* What kind of dog food are we serving? */
961   suffix = (char *) (hs->path + vec_len (hs->path) - 1);
962   while (*suffix != '.')
963     suffix--;
964   suffix++;
965   http_type = "html";
966   if (!clib_strcmp (suffix, "css"))
967     http_type = "css";
968   else if (!clib_strcmp (suffix, "js"))
969     http_type = "javascript";
970
971
972   if (hs->data == 0)
973     {
974       clib_warning ("BUG: hs->data not set for session %d",
975                     hs->session_index);
976       close_session (hs);
977       return 0;
978     }
979
980   /*
981    * Send an http response, which needs the current time,
982    * the expiration time, and the data length
983    */
984   now = clib_timebase_now (&hsm->timebase);
985   http_response = format (0, http_response_template,
986                           /* Date */
987                           format_clib_timebase_time, now,
988                           /* Expires */
989                           format_clib_timebase_time, now + 600.0,
990                           http_type, vec_len (hs->data));
991   offset = static_send_data (hs, http_response, vec_len (http_response), 0);
992   if (offset != vec_len (http_response))
993     {
994       clib_warning ("BUG: couldn't send response header!");
995       close_session (hs);
996       return 0;
997     }
998   vec_free (http_response);
999
1000   /* Send data from the beginning... */
1001   hs->data_offset = 0;
1002   hs->session_state = HTTP_STATE_SEND_MORE_DATA;
1003   return 1;
1004 }
1005
1006 static void *state_funcs[HTTP_STATE_N_STATES] = {
1007   state_closed,
1008   /* Waiting for GET, POST, etc. */
1009   state_established,
1010   /* Sent OK */
1011   state_sent_ok,
1012   /* Send more data */
1013   state_send_more_data,
1014 };
1015
1016 static inline int
1017 http_static_server_rx_tx_callback (session_t * s,
1018                                    state_machine_called_from_t cf)
1019 {
1020   http_session_t *hs;
1021   int (*fp) (session_t *, http_session_t *, state_machine_called_from_t);
1022   int rv;
1023
1024   /* Acquire a reader lock on the session table */
1025   http_static_server_sessions_reader_lock ();
1026   hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1027
1028   if (!hs)
1029     {
1030       clib_warning ("No http session for thread %d session_index %d",
1031                     s->thread_index, s->session_index);
1032       http_static_server_sessions_reader_unlock ();
1033       return 0;
1034     }
1035
1036   /* Execute state machine for this session */
1037   do
1038     {
1039       fp = state_funcs[hs->session_state];
1040       rv = (*fp) (s, hs, cf);
1041     }
1042   while (rv);
1043
1044   /* Reset the session expiration timer */
1045   http_static_server_session_timer_stop (hs);
1046   http_static_server_session_timer_start (hs);
1047
1048   http_static_server_sessions_reader_unlock ();
1049   return 0;
1050 }
1051
1052 static int
1053 http_static_server_rx_callback (session_t * s)
1054 {
1055   return http_static_server_rx_tx_callback (s, CALLED_FROM_RX);
1056 }
1057
1058 static int
1059 http_static_server_tx_callback (session_t * s)
1060 {
1061   return http_static_server_rx_tx_callback (s, CALLED_FROM_TX);
1062 }
1063
1064
1065 /** \brief Session accept callback
1066  */
1067
1068 static int
1069 http_static_server_session_accept_callback (session_t * s)
1070 {
1071   http_static_server_main_t *hsm = &http_static_server_main;
1072   http_session_t *hs;
1073
1074   hsm->vpp_queue[s->thread_index] =
1075     session_main_get_vpp_event_queue (s->thread_index);
1076
1077   http_static_server_sessions_writer_lock ();
1078
1079   hs = http_static_server_session_alloc (s->thread_index);
1080   http_static_server_session_lookup_add (s->thread_index, s->session_index,
1081                                          hs->session_index);
1082   hs->rx_fifo = s->rx_fifo;
1083   hs->tx_fifo = s->tx_fifo;
1084   hs->vpp_session_index = s->session_index;
1085   hs->vpp_session_handle = session_handle (s);
1086   hs->session_state = HTTP_STATE_ESTABLISHED;
1087   http_static_server_session_timer_start (hs);
1088
1089   http_static_server_sessions_writer_unlock ();
1090
1091   s->session_state = SESSION_STATE_READY;
1092   return 0;
1093 }
1094
1095 /** \brief Session disconnect callback
1096  */
1097
1098 static void
1099 http_static_server_session_disconnect_callback (session_t * s)
1100 {
1101   http_static_server_main_t *hsm = &http_static_server_main;
1102   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1103   http_session_t *hs;
1104
1105   http_static_server_sessions_writer_lock ();
1106
1107   hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1108   http_static_server_session_cleanup (hs);
1109
1110   http_static_server_sessions_writer_unlock ();
1111
1112   a->handle = session_handle (s);
1113   a->app_index = hsm->app_index;
1114   vnet_disconnect_session (a);
1115 }
1116
1117 /** \brief Session reset callback
1118  */
1119
1120 static void
1121 http_static_server_session_reset_callback (session_t * s)
1122 {
1123   http_static_server_main_t *hsm = &http_static_server_main;
1124   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1125   http_session_t *hs;
1126
1127   http_static_server_sessions_writer_lock ();
1128
1129   hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1130   http_static_server_session_cleanup (hs);
1131
1132   http_static_server_sessions_writer_unlock ();
1133
1134   a->handle = session_handle (s);
1135   a->app_index = hsm->app_index;
1136   vnet_disconnect_session (a);
1137 }
1138
1139 static int
1140 http_static_server_session_connected_callback (u32 app_index, u32 api_context,
1141                                                session_t * s, u8 is_fail)
1142 {
1143   clib_warning ("called...");
1144   return -1;
1145 }
1146
1147 static int
1148 http_static_server_add_segment_callback (u32 client_index, u64 segment_handle)
1149 {
1150   clib_warning ("called...");
1151   return -1;
1152 }
1153
1154 /** \brief Session-layer virtual function table
1155  */
1156 static session_cb_vft_t http_static_server_session_cb_vft = {
1157   .session_accept_callback = http_static_server_session_accept_callback,
1158   .session_disconnect_callback =
1159     http_static_server_session_disconnect_callback,
1160   .session_connected_callback = http_static_server_session_connected_callback,
1161   .add_segment_callback = http_static_server_add_segment_callback,
1162   .builtin_app_rx_callback = http_static_server_rx_callback,
1163   .builtin_app_tx_callback = http_static_server_tx_callback,
1164   .session_reset_callback = http_static_server_session_reset_callback
1165 };
1166
1167 static int
1168 http_static_server_attach ()
1169 {
1170   vnet_app_add_tls_cert_args_t _a_cert, *a_cert = &_a_cert;
1171   vnet_app_add_tls_key_args_t _a_key, *a_key = &_a_key;
1172   http_static_server_main_t *hsm = &http_static_server_main;
1173   u64 options[APP_OPTIONS_N_OPTIONS];
1174   vnet_app_attach_args_t _a, *a = &_a;
1175   u32 segment_size = 128 << 20;
1176
1177   clib_memset (a, 0, sizeof (*a));
1178   clib_memset (options, 0, sizeof (options));
1179
1180   if (hsm->private_segment_size)
1181     segment_size = hsm->private_segment_size;
1182
1183   a->api_client_index = ~0;
1184   a->name = format (0, "test_http_static_server");
1185   a->session_cb_vft = &http_static_server_session_cb_vft;
1186   a->options = options;
1187   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1188   a->options[APP_OPTIONS_RX_FIFO_SIZE] =
1189     hsm->fifo_size ? hsm->fifo_size : 8 << 10;
1190   a->options[APP_OPTIONS_TX_FIFO_SIZE] =
1191     hsm->fifo_size ? hsm->fifo_size : 32 << 10;
1192   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1193   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = hsm->prealloc_fifos;
1194   a->options[APP_OPTIONS_TLS_ENGINE] = TLS_ENGINE_OPENSSL;
1195
1196   if (vnet_application_attach (a))
1197     {
1198       vec_free (a->name);
1199       clib_warning ("failed to attach server");
1200       return -1;
1201     }
1202   vec_free (a->name);
1203   hsm->app_index = a->app_index;
1204
1205   clib_memset (a_cert, 0, sizeof (*a_cert));
1206   a_cert->app_index = a->app_index;
1207   vec_validate (a_cert->cert, test_srv_crt_rsa_len);
1208   clib_memcpy_fast (a_cert->cert, test_srv_crt_rsa, test_srv_crt_rsa_len);
1209   vnet_app_add_tls_cert (a_cert);
1210
1211   clib_memset (a_key, 0, sizeof (*a_key));
1212   a_key->app_index = a->app_index;
1213   vec_validate (a_key->key, test_srv_key_rsa_len);
1214   clib_memcpy_fast (a_key->key, test_srv_key_rsa, test_srv_key_rsa_len);
1215   vnet_app_add_tls_key (a_key);
1216
1217   return 0;
1218 }
1219
1220 static int
1221 http_static_server_listen ()
1222 {
1223   http_static_server_main_t *hsm = &http_static_server_main;
1224   vnet_listen_args_t _a, *a = &_a;
1225   clib_memset (a, 0, sizeof (*a));
1226   a->app_index = hsm->app_index;
1227   a->uri = "tcp://0.0.0.0/80";
1228   if (hsm->uri)
1229     a->uri = (char *) hsm->uri;
1230   return vnet_bind_uri (a);
1231 }
1232
1233 static void
1234 http_static_server_session_cleanup_cb (void *hs_handlep)
1235 {
1236   http_static_server_main_t *hsm = &http_static_server_main;
1237   http_session_t *hs;
1238   uword hs_handle;
1239   hs_handle = pointer_to_uword (hs_handlep);
1240   hs =
1241     http_static_server_session_get (hs_handle >> 24, hs_handle & 0x00FFFFFF);
1242
1243   if (hsm->debug_level > 1)
1244     clib_warning ("terminate thread %d index %d hs %llx",
1245                   hs_handle >> 24, hs_handle & 0x00FFFFFF, hs);
1246   if (!hs)
1247     return;
1248   hs->timer_handle = ~0;
1249   http_static_server_session_disconnect (hs);
1250   http_static_server_session_cleanup (hs);
1251 }
1252
1253 /** \brief Expired session timer-wheel callback
1254  */
1255 static void
1256 http_expired_timers_dispatch (u32 * expired_timers)
1257 {
1258   u32 hs_handle;
1259   int i;
1260
1261   for (i = 0; i < vec_len (expired_timers); i++)
1262     {
1263       /* Get session handle. The first bit is the timer id */
1264       hs_handle = expired_timers[i] & 0x7FFFFFFF;
1265       session_send_rpc_evt_to_thread (hs_handle >> 24,
1266                                       http_static_server_session_cleanup_cb,
1267                                       uword_to_pointer (hs_handle, void *));
1268     }
1269 }
1270
1271 /** \brief Timer-wheel expiration process
1272  */
1273 static uword
1274 http_static_server_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1275                             vlib_frame_t * f)
1276 {
1277   http_static_server_main_t *hsm = &http_static_server_main;
1278   f64 now, timeout = 1.0;
1279   uword *event_data = 0;
1280   uword __clib_unused event_type;
1281
1282   while (1)
1283     {
1284       vlib_process_wait_for_event_or_clock (vm, timeout);
1285       now = vlib_time_now (vm);
1286       event_type = vlib_process_get_events (vm, (uword **) & event_data);
1287
1288       /* expire timers */
1289       clib_spinlock_lock (&http_static_server_main.tw_lock);
1290       tw_timer_expire_timers_2t_1w_2048sl (&hsm->tw, now);
1291       clib_spinlock_unlock (&http_static_server_main.tw_lock);
1292
1293       vec_reset_length (event_data);
1294     }
1295   return 0;
1296 }
1297
1298 /* *INDENT-OFF* */
1299 VLIB_REGISTER_NODE (http_static_server_process_node) =
1300 {
1301   .function = http_static_server_process,
1302   .type = VLIB_NODE_TYPE_PROCESS,
1303   .name = "static-http-server-process",
1304   .state = VLIB_NODE_STATE_DISABLED,
1305 };
1306 /* *INDENT-ON* */
1307
1308 static int
1309 http_static_server_create (vlib_main_t * vm)
1310 {
1311   vlib_thread_main_t *vtm = vlib_get_thread_main ();
1312   http_static_server_main_t *hsm = &http_static_server_main;
1313   u32 num_threads;
1314   vlib_node_t *n;
1315
1316   num_threads = 1 /* main thread */  + vtm->n_threads;
1317   vec_validate (hsm->vpp_queue, num_threads - 1);
1318   vec_validate (hsm->sessions, num_threads - 1);
1319   vec_validate (hsm->session_to_http_session, num_threads - 1);
1320
1321   clib_rwlock_init (&hsm->sessions_lock);
1322   clib_spinlock_init (&hsm->tw_lock);
1323
1324   if (http_static_server_attach ())
1325     {
1326       clib_warning ("failed to attach server");
1327       return -1;
1328     }
1329   if (http_static_server_listen ())
1330     {
1331       clib_warning ("failed to start listening");
1332       return -1;
1333     }
1334
1335   /* Init path-to-cache hash table */
1336   BV (clib_bihash_init) (&hsm->name_to_data, "http cache", 128, 32 << 20);
1337
1338   /* Init timer wheel and process */
1339   tw_timer_wheel_init_2t_1w_2048sl (&hsm->tw, http_expired_timers_dispatch,
1340                                     1.0 /* timer interval */ , ~0);
1341   vlib_node_set_state (vm, http_static_server_process_node.index,
1342                        VLIB_NODE_STATE_POLLING);
1343   n = vlib_get_node (vm, http_static_server_process_node.index);
1344   vlib_start_process (vm, n->runtime_index);
1345
1346   return 0;
1347 }
1348
1349 /** \brief API helper function for vl_api_http_static_enable_t messages
1350  */
1351 int
1352 http_static_server_enable_api (u32 fifo_size, u32 cache_limit,
1353                                u32 prealloc_fifos,
1354                                u32 private_segment_size,
1355                                u8 * www_root, u8 * uri)
1356 {
1357   http_static_server_main_t *hsm = &http_static_server_main;
1358   int rv;
1359
1360   hsm->fifo_size = fifo_size;
1361   hsm->cache_limit = cache_limit;
1362   hsm->prealloc_fifos = prealloc_fifos;
1363   hsm->private_segment_size = private_segment_size;
1364   hsm->www_root = format (0, "%s%c", www_root, 0);
1365   hsm->uri = format (0, "%s%c", uri, 0);
1366
1367   if (vec_len (hsm->www_root) < 2)
1368     return VNET_API_ERROR_INVALID_VALUE;
1369
1370   if (hsm->my_client_index != ~0)
1371     return VNET_API_ERROR_APP_ALREADY_ATTACHED;
1372
1373   vnet_session_enable_disable (hsm->vlib_main, 1 /* turn on TCP, etc. */ );
1374
1375   rv = http_static_server_create (hsm->vlib_main);
1376   switch (rv)
1377     {
1378     case 0:
1379       break;
1380     default:
1381       vec_free (hsm->www_root);
1382       vec_free (hsm->uri);
1383       return VNET_API_ERROR_INIT_FAILED;
1384     }
1385   return 0;
1386 }
1387
1388 static clib_error_t *
1389 http_static_server_create_command_fn (vlib_main_t * vm,
1390                                       unformat_input_t * input,
1391                                       vlib_cli_command_t * cmd)
1392 {
1393   http_static_server_main_t *hsm = &http_static_server_main;
1394   unformat_input_t _line_input, *line_input = &_line_input;
1395   u64 seg_size;
1396   u8 *www_root = 0;
1397   int rv;
1398
1399   hsm->prealloc_fifos = 0;
1400   hsm->private_segment_size = 0;
1401   hsm->fifo_size = 0;
1402   /* 10mb cache limit, before LRU occurs */
1403   hsm->cache_limit = 10 << 20;
1404
1405   /* Get a line of input. */
1406   if (!unformat_user (input, unformat_line_input, line_input))
1407     goto no_wwwroot;
1408
1409   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1410     {
1411       if (unformat (line_input, "www-root %s", &www_root))
1412         ;
1413       else
1414         if (unformat (line_input, "prealloc-fifos %d", &hsm->prealloc_fifos))
1415         ;
1416       else if (unformat (line_input, "private-segment-size %U",
1417                          unformat_memory_size, &seg_size))
1418         {
1419           if (seg_size >= 0x100000000ULL)
1420             {
1421               vlib_cli_output (vm, "private segment size %llu, too large",
1422                                seg_size);
1423               return 0;
1424             }
1425           hsm->private_segment_size = seg_size;
1426         }
1427       else if (unformat (line_input, "fifo-size %d", &hsm->fifo_size))
1428         hsm->fifo_size <<= 10;
1429       else if (unformat (line_input, "cache-size %U", unformat_memory_size,
1430                          &hsm->cache_limit))
1431         {
1432           if (hsm->cache_limit < (128 << 10))
1433             {
1434               return clib_error_return (0,
1435                                         "cache-size must be at least 128kb");
1436             }
1437         }
1438
1439       else if (unformat (line_input, "uri %s", &hsm->uri))
1440         ;
1441       else if (unformat (line_input, "debug %d", &hsm->debug_level))
1442         ;
1443       else if (unformat (line_input, "debug"))
1444         hsm->debug_level = 1;
1445       else
1446         return clib_error_return (0, "unknown input `%U'",
1447                                   format_unformat_error, line_input);
1448     }
1449   unformat_free (line_input);
1450
1451   if (www_root == 0)
1452     {
1453     no_wwwroot:
1454       return clib_error_return (0, "Must specify www-root <path>");
1455     }
1456
1457   if (hsm->my_client_index != (u32) ~ 0)
1458     {
1459       vec_free (www_root);
1460       return clib_error_return (0, "http server already running...");
1461     }
1462
1463   hsm->www_root = www_root;
1464
1465   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
1466
1467   rv = http_static_server_create (vm);
1468   switch (rv)
1469     {
1470     case 0:
1471       break;
1472     default:
1473       vec_free (hsm->www_root);
1474       return clib_error_return (0, "server_create returned %d", rv);
1475     }
1476   return 0;
1477 }
1478
1479 /*?
1480  * Enable the static http server
1481  *
1482  * @cliexpar
1483  * This command enables the static http server. Only the www-root
1484  * parameter is required
1485  * @clistart
1486  * http static server www-root /tmp/www uri tcp://0.0.0.0/80 cache-size 2m
1487  * @cliend
1488  * @cliexcmd{http static server www-root <path> [prealloc-fios <nn>]
1489  *   [private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]}
1490 ?*/
1491 /* *INDENT-OFF* */
1492 VLIB_CLI_COMMAND (http_static_server_create_command, static) =
1493 {
1494   .path = "http static server",
1495   .short_help = "http static server www-root <path> [prealloc-fifos <nn>]\n"
1496   "[private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]\n"
1497   "[debug [nn]]\n",
1498   .function = http_static_server_create_command_fn,
1499 };
1500 /* *INDENT-ON* */
1501
1502 /** \brief format a file cache entry
1503  */
1504 u8 *
1505 format_hsm_cache_entry (u8 * s, va_list * args)
1506 {
1507   file_data_cache_t *ep = va_arg (*args, file_data_cache_t *);
1508   f64 now = va_arg (*args, f64);
1509
1510   /* Header */
1511   if (ep == 0)
1512     {
1513       s = format (s, "%40s%12s%20s", "File", "Size", "Age");
1514       return s;
1515     }
1516   s = format (s, "%40s%12lld%20.2f", ep->filename, vec_len (ep->data),
1517               now - ep->last_used);
1518   return s;
1519 }
1520
1521 u8 *
1522 format_http_session_state (u8 * s, va_list * args)
1523 {
1524   http_session_state_t state = va_arg (*args, http_session_state_t);
1525   char *state_string = "bogus!";
1526
1527   switch (state)
1528     {
1529     case HTTP_STATE_CLOSED:
1530       state_string = "closed";
1531       break;
1532     case HTTP_STATE_ESTABLISHED:
1533       state_string = "established";
1534       break;
1535     case HTTP_STATE_OK_SENT:
1536       state_string = "ok sent";
1537       break;
1538     case HTTP_STATE_SEND_MORE_DATA:
1539       state_string = "send more data";
1540       break;
1541     default:
1542       break;
1543     }
1544
1545   return format (s, "%s", state_string);
1546 }
1547
1548 u8 *
1549 format_http_session (u8 * s, va_list * args)
1550 {
1551   http_session_t *hs = va_arg (*args, http_session_t *);
1552   int verbose = va_arg (*args, int);
1553
1554   s = format (s, "[%d]: state %U", hs->session_index,
1555               format_http_session_state, hs->session_state);
1556   if (verbose > 0)
1557     {
1558       s = format (s, "\n path %s, data length %u, data_offset %u",
1559                   hs->path ? hs->path : (u8 *) "[none]",
1560                   vec_len (hs->data), hs->data_offset);
1561     }
1562   return s;
1563 }
1564
1565 static clib_error_t *
1566 http_show_static_server_command_fn (vlib_main_t * vm,
1567                                     unformat_input_t * input,
1568                                     vlib_cli_command_t * cmd)
1569 {
1570   http_static_server_main_t *hsm = &http_static_server_main;
1571   file_data_cache_t *ep, **entries = 0;
1572   int verbose = 0;
1573   int show_cache = 0;
1574   int show_sessions = 0;
1575   u32 index;
1576   f64 now;
1577
1578   if (hsm->www_root == 0)
1579     return clib_error_return (0, "Static server disabled");
1580
1581   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1582     {
1583       if (unformat (input, "verbose %d", &verbose))
1584         ;
1585       else if (unformat (input, "verbose"))
1586         verbose = 1;
1587       else if (unformat (input, "cache"))
1588         show_cache = 1;
1589       else if (unformat (input, "sessions"))
1590         show_sessions = 1;
1591       else
1592         break;
1593     }
1594
1595   if ((show_cache + show_sessions) == 0)
1596     return clib_error_return (0, "specify one or more of cache, sessions");
1597
1598   if (show_cache)
1599     {
1600       if (verbose == 0)
1601         {
1602           vlib_cli_output
1603             (vm, "www_root %s, cache size %lld bytes, limit %lld bytes, "
1604              "evictions %lld",
1605              hsm->www_root, hsm->cache_size, hsm->cache_limit,
1606              hsm->cache_evictions);
1607           return 0;
1608         }
1609
1610       now = vlib_time_now (vm);
1611
1612       vlib_cli_output (vm, "%U", format_hsm_cache_entry, 0 /* header */ ,
1613                        now);
1614
1615       for (index = hsm->first_index; index != ~0;)
1616         {
1617           ep = pool_elt_at_index (hsm->cache_pool, index);
1618           index = ep->next_index;
1619           vlib_cli_output (vm, "%U", format_hsm_cache_entry, ep, now);
1620         }
1621
1622       vlib_cli_output (vm, "%40s%12lld", "Total Size", hsm->cache_size);
1623
1624       vec_free (entries);
1625     }
1626
1627   if (show_sessions)
1628     {
1629       u32 *session_indices = 0;
1630       http_session_t *hs;
1631       int i, j;
1632
1633       http_static_server_sessions_reader_lock ();
1634
1635       for (i = 0; i < vec_len (hsm->sessions); i++)
1636         {
1637           /* *INDENT-OFF* */
1638           pool_foreach (hs, hsm->sessions[i],
1639           ({
1640             vec_add1 (session_indices, hs - hsm->sessions[i]);
1641           }));
1642           /* *INDENT-ON* */
1643
1644           for (j = 0; j < vec_len (session_indices); j++)
1645             {
1646               vlib_cli_output (vm, "%U", format_http_session,
1647                                pool_elt_at_index
1648                                (hsm->sessions[i], session_indices[j]),
1649                                verbose);
1650             }
1651           vec_reset_length (session_indices);
1652         }
1653       http_static_server_sessions_reader_unlock ();
1654       vec_free (session_indices);
1655     }
1656   return 0;
1657 }
1658
1659 /*?
1660  * Display static http server cache statistics
1661  *
1662  * @cliexpar
1663  * This command shows the contents of the static http server cache
1664  * @clistart
1665  * show http static server
1666  * @cliend
1667  * @cliexcmd{show http static server sessions cache [verbose [nn]]}
1668 ?*/
1669 /* *INDENT-OFF* */
1670 VLIB_CLI_COMMAND (http_show_static_server_command, static) =
1671 {
1672   .path = "show http static server",
1673   .short_help = "show http static server sessions cache [verbose [<nn>]]",
1674   .function = http_show_static_server_command_fn,
1675 };
1676 /* *INDENT-ON* */
1677
1678 static clib_error_t *
1679 http_static_server_main_init (vlib_main_t * vm)
1680 {
1681   http_static_server_main_t *hsm = &http_static_server_main;
1682
1683   hsm->my_client_index = ~0;
1684   hsm->vlib_main = vm;
1685   hsm->first_index = hsm->last_index = ~0;
1686
1687   clib_timebase_init (&hsm->timebase, 0 /* GMT */ ,
1688                       CLIB_TIMEBASE_DAYLIGHT_NONE);
1689
1690   return 0;
1691 }
1692
1693 VLIB_INIT_FUNCTION (http_static_server_main_init);
1694
1695 /*
1696 * fd.io coding-style-patch-verification: ON
1697 *
1698 * Local Variables:
1699 * eval: (c-set-style "gnu")
1700 * End:
1701 */