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