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:
7 * http://www.apache.org/licenses/LICENSE-2.0
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.
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/unix.h>
21 #include <sys/types.h>
24 #include <http_static/http_static.h>
26 #include <vppinfra/bihash_template.c>
28 /** @file static_server.c
29 * Static http server, sufficient to
30 * serve .html / .css / .js content.
32 /*? %%clicmd:group_label Static HTTP Server %% ?*/
34 http_static_server_main_t http_static_server_main;
36 /** \brief Format the called-from enum
40 format_state_machine_called_from (u8 * s, va_list * args)
42 http_state_machine_called_from_t cf =
43 va_arg (*args, http_state_machine_called_from_t);
44 char *which = "bogus!";
54 case CALLED_FROM_TIMER:
62 s = format (s, "%s", which);
67 /** \brief Acquire reader lock on the sessions pools
70 http_static_server_sessions_reader_lock (void)
72 clib_rwlock_reader_lock (&http_static_server_main.sessions_lock);
75 /** \brief Drop reader lock on the sessions pools
78 http_static_server_sessions_reader_unlock (void)
80 clib_rwlock_reader_unlock (&http_static_server_main.sessions_lock);
83 /** \brief Acquire writer lock on the sessions pools
86 http_static_server_sessions_writer_lock (void)
88 clib_rwlock_writer_lock (&http_static_server_main.sessions_lock);
91 /** \brief Drop writer lock on the sessions pools
94 http_static_server_sessions_writer_unlock (void)
96 clib_rwlock_writer_unlock (&http_static_server_main.sessions_lock);
99 /** \brief Start a session cleanup timer
102 http_static_server_session_timer_start (http_session_t * hs)
104 http_static_server_main_t *hsm = &http_static_server_main;
107 /* The session layer may fire a callback at a later date... */
108 if (!pool_is_free (hsm->sessions[hs->thread_index], hs))
110 hs_handle = hs->thread_index << 24 | hs->session_index;
111 clib_spinlock_lock (&http_static_server_main.tw_lock);
112 hs->timer_handle = tw_timer_start_2t_1w_2048sl
113 (&http_static_server_main.tw, hs_handle, 0, 60);
114 clib_spinlock_unlock (&http_static_server_main.tw_lock);
118 /** \brief stop a session cleanup timer
121 http_static_server_session_timer_stop (http_session_t * hs)
123 if (hs->timer_handle == ~0)
125 clib_spinlock_lock (&http_static_server_main.tw_lock);
126 tw_timer_stop_2t_1w_2048sl (&http_static_server_main.tw, hs->timer_handle);
127 clib_spinlock_unlock (&http_static_server_main.tw_lock);
130 /** \brief Allocate an http session
132 static http_session_t *
133 http_static_server_session_alloc (u32 thread_index)
135 http_static_server_main_t *hsm = &http_static_server_main;
137 pool_get_aligned_zero_numa (hsm->sessions[thread_index], hs,
138 0 /* not aligned */ ,
140 os_get_numa_index ());
141 hs->session_index = hs - hsm->sessions[thread_index];
142 hs->thread_index = thread_index;
143 hs->timer_handle = ~0;
144 hs->cache_pool_index = ~0;
148 /** \brief Get an http session by index
150 static http_session_t *
151 http_static_server_session_get (u32 thread_index, u32 hs_index)
153 http_static_server_main_t *hsm = &http_static_server_main;
154 if (pool_is_free_index (hsm->sessions[thread_index], hs_index))
156 return pool_elt_at_index (hsm->sessions[thread_index], hs_index);
159 /** \brief Free an http session
162 http_static_server_session_free (http_session_t * hs)
164 http_static_server_main_t *hsm = &http_static_server_main;
166 /* Make sure the timer is stopped... */
167 http_static_server_session_timer_stop (hs);
168 pool_put (hsm->sessions[hs->thread_index], hs);
172 u32 save_thread_index;
173 save_thread_index = hs->thread_index;
174 /* Poison the entry, preserve timer state and thread index */
175 memset (hs, 0xfa, sizeof (*hs));
176 hs->timer_handle = ~0;
177 hs->thread_index = save_thread_index;
181 /** \brief add a session to the vpp < -- > http session index map
184 http_static_server_session_lookup_add (u32 thread_index, u32 s_index,
187 http_static_server_main_t *hsm = &http_static_server_main;
188 vec_validate (hsm->session_to_http_session[thread_index], s_index);
189 hsm->session_to_http_session[thread_index][s_index] = hs_index;
192 /** \brief Remove a session from the vpp < -- > http session index map
195 http_static_server_session_lookup_del (u32 thread_index, u32 s_index)
197 http_static_server_main_t *hsm = &http_static_server_main;
198 hsm->session_to_http_session[thread_index][s_index] = ~0;
201 /** \brief lookup a session in the vpp < -- > http session index map
204 static http_session_t *
205 http_static_server_session_lookup (u32 thread_index, u32 s_index)
207 http_static_server_main_t *hsm = &http_static_server_main;
210 if (s_index < vec_len (hsm->session_to_http_session[thread_index]))
212 hs_index = hsm->session_to_http_session[thread_index][s_index];
213 return http_static_server_session_get (thread_index, hs_index);
218 /** \brief Detach cache entry from session
222 http_static_server_detach_cache_entry (http_session_t * hs)
224 http_static_server_main_t *hsm = &http_static_server_main;
225 file_data_cache_t *ep;
228 * Decrement cache pool entry reference count
229 * Note that if e.g. a file lookup fails, the cache pool index
232 if (hs->cache_pool_index != ~0)
234 ep = pool_elt_at_index (hsm->cache_pool, hs->cache_pool_index);
236 if (hsm->debug_level > 1)
237 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
240 hs->cache_pool_index = ~0;
249 /** \brief clean up a session
253 http_static_server_session_cleanup (http_session_t * hs)
258 http_static_server_detach_cache_entry (hs);
260 http_static_server_session_lookup_del (hs->thread_index,
261 hs->vpp_session_index);
262 vec_free (hs->rx_buf);
263 http_static_server_session_free (hs);
266 /** \brief Disconnect a session
270 http_static_server_session_disconnect (http_session_t * hs)
272 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
273 a->handle = hs->vpp_session_handle;
274 a->app_index = http_static_server_main.app_index;
275 vnet_disconnect_session (a);
279 /** \brief http error boilerplate
281 static const char *http_error_template =
284 "Content-Type: text/html\r\n"
285 "Connection: close\r\n"
286 "Pragma: no-cache\r\n"
287 "Content-Length: 0\r\n\r\n";
289 /** \brief http response boilerplate
291 static const char *http_response_template =
293 "Expires: %U GMT\r\n"
294 "Server: VPP Static\r\n"
295 "Content-Type: %s\r\n"
296 "Content-Length: %d\r\n\r\n";
300 /** \brief send http data
301 @param hs - http session
302 @param data - the data vector to transmit
303 @param length - length of data
304 @param offset - transmit offset for this operation
305 @return offset for next transmit operation, may be unchanged w/ full fifo
309 static_send_data (http_session_t * hs, u8 * data, u32 length, u32 offset)
312 http_static_server_main_t *hsm = &http_static_server_main;
314 bytes_to_send = length - offset;
316 while (bytes_to_send > 0)
320 actual_transfer = svm_fifo_enqueue
321 (hs->tx_fifo, bytes_to_send, data + offset);
323 /* Made any progress? */
324 if (actual_transfer <= 0)
326 if (hsm->debug_level > 0 && bytes_to_send > 0)
327 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
332 offset += actual_transfer;
333 bytes_to_send -= actual_transfer;
335 if (hsm->debug_level && bytes_to_send > 0)
336 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
338 if (svm_fifo_set_event (hs->tx_fifo))
339 session_send_io_evt_to_thread (hs->tx_fifo,
340 SESSION_IO_EVT_TX_FLUSH);
348 /** \brief Send an http error string
349 @param hs - the http session
350 @param str - the error string, e.g. "404 Not Found"
353 send_error (http_session_t * hs, char *str)
355 http_static_server_main_t *hsm = &http_static_server_main;
359 now = clib_timebase_now (&hsm->timebase);
360 data = format (0, http_error_template, str, format_clib_timebase_time, now);
361 static_send_data (hs, data, vec_len (data), 0);
365 /** \brief Retrieve data from the application layer
368 session_rx_request (http_session_t * hs)
370 u32 max_dequeue, cursize;
373 cursize = vec_len (hs->rx_buf);
374 max_dequeue = svm_fifo_max_dequeue (hs->rx_fifo);
375 if (PREDICT_FALSE (max_dequeue == 0))
378 vec_validate (hs->rx_buf, cursize + max_dequeue - 1);
379 n_read = app_recv_stream_raw (hs->rx_fifo, hs->rx_buf + cursize,
380 max_dequeue, 0, 0 /* peek */ );
381 ASSERT (n_read == max_dequeue);
382 if (svm_fifo_is_empty (hs->rx_fifo))
383 svm_fifo_unset_event (hs->rx_fifo);
385 _vec_len (hs->rx_buf) = cursize + n_read;
389 /** \brief Sanity-check the forward and reverse LRU lists
392 lru_validate (http_static_server_main_t * hsm)
398 file_data_cache_t *ep;
400 last_timestamp = 1e70;
401 for (i = 1, index = hsm->first_index; index != ~0;)
403 ep = pool_elt_at_index (hsm->cache_pool, index);
404 index = ep->next_index;
405 /* Timestamps should be smaller (older) as we walk the fwd list */
406 if (ep->last_used > last_timestamp)
408 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
409 ep - hsm->cache_pool, i,
410 ep->last_used, last_timestamp);
412 last_timestamp = ep->last_used;
416 last_timestamp = 0.0;
417 for (i = 1, index = hsm->last_index; index != ~0;)
419 ep = pool_elt_at_index (hsm->cache_pool, index);
420 index = ep->prev_index;
421 /* Timestamps should be larger (newer) as we walk the rev list */
422 if (ep->last_used < last_timestamp)
424 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
425 ep - hsm->cache_pool, i,
426 ep->last_used, last_timestamp);
428 last_timestamp = ep->last_used;
434 /** \brief Remove a data cache entry from the LRU lists
437 lru_remove (http_static_server_main_t * hsm, file_data_cache_t * ep)
439 file_data_cache_t *next_ep, *prev_ep;
444 ep_index = ep - hsm->cache_pool;
446 /* Deal with list heads */
447 if (ep_index == hsm->first_index)
448 hsm->first_index = ep->next_index;
449 if (ep_index == hsm->last_index)
450 hsm->last_index = ep->prev_index;
453 if (ep->next_index != ~0)
455 next_ep = pool_elt_at_index (hsm->cache_pool, ep->next_index);
456 next_ep->prev_index = ep->prev_index;
459 if (ep->prev_index != ~0)
461 prev_ep = pool_elt_at_index (hsm->cache_pool, ep->prev_index);
462 prev_ep->next_index = ep->next_index;
467 /** \brief Add an entry to the LRU lists, tag w/ supplied timestamp
471 lru_add (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
473 file_data_cache_t *next_ep;
478 ep_index = ep - hsm->cache_pool;
481 * Re-add at the head of the forward LRU list,
482 * tail of the reverse LRU list
484 if (hsm->first_index != ~0)
486 next_ep = pool_elt_at_index (hsm->cache_pool, hsm->first_index);
487 next_ep->prev_index = ep_index;
492 /* ep now the new head of the LRU forward list */
493 ep->next_index = hsm->first_index;
494 hsm->first_index = ep_index;
496 /* single session case: also the tail of the reverse LRU list */
497 if (hsm->last_index == ~0)
498 hsm->last_index = ep_index;
504 /** \brief Remove and re-add a cache entry from/to the LRU lists
508 lru_update (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
510 lru_remove (hsm, ep);
511 lru_add (hsm, ep, now);
514 /** \brief Session-layer (main) data rx callback.
515 Parse the http request, and reply to it.
516 Future extensions might include POST processing, active content, etc.
519 /* svm_fifo_add_want_deq_ntf (tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL)
520 get shoulder-tap when transport dequeues something, set in
523 /** \brief closed state - should never really get here
526 state_closed (session_t * s, http_session_t * hs,
527 http_state_machine_called_from_t cf)
529 clib_warning ("WARNING: http session %d, called from %U",
530 hs->session_index, format_state_machine_called_from, cf);
535 close_session (http_session_t * hs)
537 http_static_server_session_disconnect (hs);
538 http_static_server_session_cleanup (hs);
541 /** \brief Register a builtin GET or POST handler
543 void http_static_server_register_builtin_handler
544 (void *fp, char *url, int request_type)
546 http_static_server_main_t *hsm = &http_static_server_main;
547 uword *p, *builtin_table;
549 builtin_table = (request_type == HTTP_BUILTIN_METHOD_GET)
550 ? hsm->get_url_handlers : hsm->post_url_handlers;
552 p = hash_get_mem (builtin_table, url);
556 clib_warning ("WARNING: attempt to replace handler for %s '%s' ignored",
557 (request_type == HTTP_BUILTIN_METHOD_GET) ?
558 "GET" : "POST", url);
562 hash_set_mem (builtin_table, url, (uword) fp);
565 * Need to update the hash table pointer in http_static_server_main
566 * in case we just expanded it...
568 if (request_type == HTTP_BUILTIN_METHOD_GET)
569 hsm->get_url_handlers = builtin_table;
571 hsm->post_url_handlers = builtin_table;
575 v_find_index (u8 * vec, char *str)
578 u32 slen = (u32) strnlen_s_inline (str, 8);
579 u32 vlen = vec_len (vec);
586 for (start_index = 0; start_index < (vlen - slen); start_index++)
588 if (!memcmp (vec, str, slen))
595 /** \brief established state - waiting for GET, POST, etc.
598 state_established (session_t * s, http_session_t * hs,
599 http_state_machine_called_from_t cf)
601 http_static_server_main_t *hsm = &http_static_server_main;
605 struct stat _sb, *sb = &_sb;
607 u8 request_type = HTTP_BUILTIN_METHOD_GET;
609 uword *p, *builtin_table;
611 /* Read data from the sessison layer */
612 rv = session_rx_request (hs);
614 /* No data? Odd, but stay in this state and await further instructions */
618 /* Process the client request */
619 request = hs->rx_buf;
620 if (vec_len (request) < 8)
622 send_error (hs, "400 Bad Request");
627 if ((i = v_find_index (request, "GET ")) >= 0)
629 else if ((i = v_find_index (request, "POST ")) >= 0)
631 request_type = HTTP_BUILTIN_METHOD_POST;
635 if (hsm->debug_level > 1)
636 clib_warning ("Unknown http method");
638 send_error (hs, "405 Method Not Allowed");
644 /* Lose "GET " or "POST " */
645 vec_delete (request, i + 5 + request_type, 0);
647 /* Temporarily drop in a NULL byte for lookup purposes */
648 for (i = 0; i < vec_len (request); i++)
650 if (request[i] == ' ' || request[i] == '?')
652 save_byte = request[i];
659 * Now we can construct the file to open
660 * Browsers are capable of sporadically including a leading '/'
662 if (request[0] == '/')
663 path = format (0, "%s%s%c", hsm->www_root, request, 0);
665 path = format (0, "%s/%s%c", hsm->www_root, request, 0);
667 if (hsm->debug_level > 0)
668 clib_warning ("%s '%s'", (request_type) == HTTP_BUILTIN_METHOD_GET ?
669 "GET" : "POST", path);
671 /* Look for built-in GET / POST handlers */
672 builtin_table = (request_type == HTTP_BUILTIN_METHOD_GET) ?
673 hsm->get_url_handlers : hsm->post_url_handlers;
675 p = hash_get_mem (builtin_table, request);
678 request[i] = save_byte;
683 int (*fp) (http_builtin_method_type_t, u8 *, http_session_t *);
686 rv = (*fp) (request_type, request, hs);
689 clib_warning ("builtin handler %llx hit on %s '%s' but failed!",
690 p[0], (request_type == HTTP_BUILTIN_METHOD_GET) ?
691 "GET" : "POST", request);
692 send_error (hs, "404 Not Found");
696 vec_reset_length (hs->rx_buf);
699 vec_reset_length (hs->rx_buf);
700 /* poison request, it's not valid anymore */
702 /* The static server itself doesn't do POSTs */
703 if (request_type == HTTP_BUILTIN_METHOD_POST)
705 send_error (hs, "404 Not Found");
710 /* Try to find the file. 2x special cases to find index.html */
711 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
712 || sb->st_size < 20 /* file too small */
713 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
715 u32 save_length = vec_len (path) - 1;
716 /* Try appending "index.html"... */
717 _vec_len (path) -= 1;
718 path = format (path, "index.html%c", 0);
719 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
720 || sb->st_size < 20 /* file too small */
721 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
723 _vec_len (path) = save_length;
724 path = format (path, "/index.html%c", 0);
726 /* Send a redirect, otherwise the browser will confuse itself */
727 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
728 || sb->st_size < 20 /* file too small */
729 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
732 send_error (hs, "404 Not Found");
738 transport_endpoint_t endpoint;
739 transport_proto_t proto;
745 * To make this bit work correctly, we need to know our local
746 * IP address, etc. and send it in the redirect...
750 vec_delete (path, vec_len (hsm->www_root) - 1, 0);
752 session_get_endpoint (s, &endpoint, 1 /* is_local */ );
754 local_port = clib_net_to_host_u16 (endpoint.port);
756 proto = session_type_transport_proto (s->session_type);
758 if ((proto == TRANSPORT_PROTO_TCP && local_port != 80)
759 || (proto == TRANSPORT_PROTO_TLS && local_port != 443))
762 port_str = format (0, ":%u", (u32) local_port);
765 redirect = format (0, "HTTP/1.1 301 Moved Permanently\r\n"
766 "Location: http%s://%U%s%s\r\n\r\n",
767 proto == TRANSPORT_PROTO_TLS ? "s" : "",
768 format_ip46_address, &endpoint.ip,
770 print_port ? port_str : (u8 *) "", path);
771 if (hsm->debug_level > 0)
772 clib_warning ("redirect: %s", redirect);
776 static_send_data (hs, redirect, vec_len (redirect), 0);
777 hs->session_state = HTTP_STATE_CLOSED;
787 /* find or read the file if we haven't done so yet. */
790 BVT (clib_bihash_kv) kv;
791 file_data_cache_t *dp;
795 /* First, try the cache */
796 kv.key = (u64) hs->path;
797 if (BV (clib_bihash_search) (&hsm->name_to_data, &kv, &kv) == 0)
799 if (hsm->debug_level > 1)
800 clib_warning ("lookup '%s' returned %lld", kv.key, kv.value);
802 /* found the data.. */
803 dp = pool_elt_at_index (hsm->cache_pool, kv.value);
805 /* Update the cache entry, mark it in-use */
806 lru_update (hsm, dp, vlib_time_now (hsm->vlib_main));
807 hs->cache_pool_index = dp - hsm->cache_pool;
809 if (hsm->debug_level > 1)
810 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
815 if (hsm->debug_level > 1)
816 clib_warning ("lookup '%s' failed", kv.key, kv.value);
817 /* Need to recycle one (or more cache) entries? */
818 if (hsm->cache_size > hsm->cache_limit)
820 int free_index = hsm->last_index;
822 while (free_index != ~0)
825 dp = pool_elt_at_index (hsm->cache_pool, free_index);
826 free_index = dp->prev_index;
827 /* Which could be in use... */
830 if (hsm->debug_level > 1)
831 clib_warning ("index %d in use refcnt %d",
832 dp - hsm->cache_pool, dp->inuse);
835 kv.key = (u64) (dp->filename);
837 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
838 0 /* is_add */ ) < 0)
840 clib_warning ("LRU delete '%s' FAILED!", dp->filename);
842 else if (hsm->debug_level > 1)
843 clib_warning ("LRU delete '%s' ok", dp->filename);
845 lru_remove (hsm, dp);
846 hsm->cache_size -= vec_len (dp->data);
847 hsm->cache_evictions++;
848 vec_free (dp->filename);
850 if (hsm->debug_level > 1)
851 clib_warning ("pool put index %d", dp - hsm->cache_pool);
852 pool_put (hsm->cache_pool, dp);
853 if (hsm->cache_size < hsm->cache_limit)
859 error = clib_file_contents ((char *) (hs->path), &hs->data);
862 clib_warning ("Error reading '%s'", hs->path);
863 clib_error_report (error);
868 /* Create a cache entry for it */
869 pool_get (hsm->cache_pool, dp);
870 memset (dp, 0, sizeof (*dp));
871 dp->filename = vec_dup (hs->path);
873 hs->cache_pool_index = dp - hsm->cache_pool;
875 if (hsm->debug_level > 1)
876 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
878 lru_add (hsm, dp, vlib_time_now (hsm->vlib_main));
879 kv.key = (u64) vec_dup (hs->path);
880 kv.value = dp - hsm->cache_pool;
881 /* Add to the lookup table */
882 if (hsm->debug_level > 1)
883 clib_warning ("add '%s' value %lld", kv.key, kv.value);
885 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
886 1 /* is_add */ ) < 0)
888 clib_warning ("BUG: add failed!");
890 hsm->cache_size += vec_len (dp->data);
894 /* send 200 OK first */
896 static_send_data (hs, (u8 *) "HTTP/1.1 200 OK\r\n", 17, 0);
897 hs->session_state = HTTP_STATE_OK_SENT;
902 state_send_more_data (session_t * s, http_session_t * hs,
903 http_state_machine_called_from_t cf)
906 /* Start sending data */
907 hs->data_offset = static_send_data (hs, hs->data, vec_len (hs->data),
911 if (hs->data_offset < vec_len (hs->data))
913 /* No: ask for a shoulder-tap when the tx fifo has space */
914 svm_fifo_add_want_deq_ntf (hs->tx_fifo,
915 SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL);
916 hs->session_state = HTTP_STATE_SEND_MORE_DATA;
919 /* Finished with this transaction, back to HTTP_STATE_ESTABLISHED */
921 /* Let go of the file cache entry */
922 http_static_server_detach_cache_entry (hs);
923 hs->session_state = HTTP_STATE_ESTABLISHED;
928 state_sent_ok (session_t * s, http_session_t * hs,
929 http_state_machine_called_from_t cf)
931 http_static_server_main_t *hsm = &http_static_server_main;
938 /* What kind of dog food are we serving? */
939 suffix = (char *) (hs->path + vec_len (hs->path) - 1);
940 while ((u8 *) suffix >= hs->path && *suffix != '.')
943 http_type = "text/html";
944 if (!clib_strcmp (suffix, "css"))
945 http_type = "text/css";
946 else if (!clib_strcmp (suffix, "js"))
947 http_type = "text/javascript";
948 else if (!clib_strcmp (suffix, "json"))
949 http_type = "application/json";
953 clib_warning ("BUG: hs->data not set for session %d",
960 * Send an http response, which needs the current time,
961 * the expiration time, and the data length
963 now = clib_timebase_now (&hsm->timebase);
964 http_response = format (0, http_response_template,
966 format_clib_timebase_time, now,
968 format_clib_timebase_time, now + 600.0,
969 http_type, vec_len (hs->data));
970 offset = static_send_data (hs, http_response, vec_len (http_response), 0);
971 if (offset != vec_len (http_response))
973 clib_warning ("BUG: couldn't send response header!");
977 vec_free (http_response);
979 /* Send data from the beginning... */
981 hs->session_state = HTTP_STATE_SEND_MORE_DATA;
985 static void *state_funcs[HTTP_STATE_N_STATES] = {
987 /* Waiting for GET, POST, etc. */
992 state_send_more_data,
996 http_static_server_rx_tx_callback (session_t * s,
997 http_state_machine_called_from_t cf)
1000 int (*fp) (session_t *, http_session_t *, http_state_machine_called_from_t);
1003 /* Acquire a reader lock on the session table */
1004 http_static_server_sessions_reader_lock ();
1005 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1009 clib_warning ("No http session for thread %d session_index %d",
1010 s->thread_index, s->session_index);
1011 http_static_server_sessions_reader_unlock ();
1015 /* Execute state machine for this session */
1018 fp = state_funcs[hs->session_state];
1019 rv = (*fp) (s, hs, cf);
1021 goto session_closed;
1025 /* Reset the session expiration timer */
1026 http_static_server_session_timer_stop (hs);
1027 http_static_server_session_timer_start (hs);
1030 http_static_server_sessions_reader_unlock ();
1035 http_static_server_rx_callback (session_t * s)
1037 return http_static_server_rx_tx_callback (s, CALLED_FROM_RX);
1041 http_static_server_tx_callback (session_t * s)
1043 return http_static_server_rx_tx_callback (s, CALLED_FROM_TX);
1047 /** \brief Session accept callback
1051 http_static_server_session_accept_callback (session_t * s)
1053 http_static_server_main_t *hsm = &http_static_server_main;
1056 hsm->vpp_queue[s->thread_index] =
1057 session_main_get_vpp_event_queue (s->thread_index);
1059 http_static_server_sessions_writer_lock ();
1061 hs = http_static_server_session_alloc (s->thread_index);
1062 http_static_server_session_lookup_add (s->thread_index, s->session_index,
1064 hs->rx_fifo = s->rx_fifo;
1065 hs->tx_fifo = s->tx_fifo;
1066 hs->vpp_session_index = s->session_index;
1067 hs->vpp_session_handle = session_handle (s);
1068 hs->session_state = HTTP_STATE_ESTABLISHED;
1069 http_static_server_session_timer_start (hs);
1071 http_static_server_sessions_writer_unlock ();
1073 s->session_state = SESSION_STATE_READY;
1077 /** \brief Session disconnect callback
1081 http_static_server_session_disconnect_callback (session_t * s)
1083 http_static_server_main_t *hsm = &http_static_server_main;
1084 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1087 http_static_server_sessions_writer_lock ();
1089 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1090 http_static_server_session_cleanup (hs);
1092 http_static_server_sessions_writer_unlock ();
1094 a->handle = session_handle (s);
1095 a->app_index = hsm->app_index;
1096 vnet_disconnect_session (a);
1099 /** \brief Session reset callback
1103 http_static_server_session_reset_callback (session_t * s)
1105 http_static_server_main_t *hsm = &http_static_server_main;
1106 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1109 http_static_server_sessions_writer_lock ();
1111 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1112 http_static_server_session_cleanup (hs);
1114 http_static_server_sessions_writer_unlock ();
1116 a->handle = session_handle (s);
1117 a->app_index = hsm->app_index;
1118 vnet_disconnect_session (a);
1122 http_static_server_session_connected_callback (u32 app_index, u32 api_context,
1124 session_error_t err)
1126 clib_warning ("called...");
1131 http_static_server_add_segment_callback (u32 client_index, u64 segment_handle)
1133 clib_warning ("called...");
1137 /** \brief Session-layer virtual function table
1139 static session_cb_vft_t http_static_server_session_cb_vft = {
1140 .session_accept_callback = http_static_server_session_accept_callback,
1141 .session_disconnect_callback =
1142 http_static_server_session_disconnect_callback,
1143 .session_connected_callback = http_static_server_session_connected_callback,
1144 .add_segment_callback = http_static_server_add_segment_callback,
1145 .builtin_app_rx_callback = http_static_server_rx_callback,
1146 .builtin_app_tx_callback = http_static_server_tx_callback,
1147 .session_reset_callback = http_static_server_session_reset_callback
1151 http_static_server_attach ()
1153 vnet_app_add_tls_cert_args_t _a_cert, *a_cert = &_a_cert;
1154 vnet_app_add_tls_key_args_t _a_key, *a_key = &_a_key;
1155 http_static_server_main_t *hsm = &http_static_server_main;
1156 u64 options[APP_OPTIONS_N_OPTIONS];
1157 vnet_app_attach_args_t _a, *a = &_a;
1158 u32 segment_size = 128 << 20;
1160 clib_memset (a, 0, sizeof (*a));
1161 clib_memset (options, 0, sizeof (options));
1163 if (hsm->private_segment_size)
1164 segment_size = hsm->private_segment_size;
1166 a->api_client_index = ~0;
1167 a->name = format (0, "test_http_static_server");
1168 a->session_cb_vft = &http_static_server_session_cb_vft;
1169 a->options = options;
1170 a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1171 a->options[APP_OPTIONS_RX_FIFO_SIZE] =
1172 hsm->fifo_size ? hsm->fifo_size : 8 << 10;
1173 a->options[APP_OPTIONS_TX_FIFO_SIZE] =
1174 hsm->fifo_size ? hsm->fifo_size : 32 << 10;
1175 a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1176 a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = hsm->prealloc_fifos;
1177 a->options[APP_OPTIONS_TLS_ENGINE] = CRYPTO_ENGINE_OPENSSL;
1179 if (vnet_application_attach (a))
1182 clib_warning ("failed to attach server");
1186 hsm->app_index = a->app_index;
1188 clib_memset (a_cert, 0, sizeof (*a_cert));
1189 a_cert->app_index = a->app_index;
1190 vec_validate (a_cert->cert, test_srv_crt_rsa_len);
1191 clib_memcpy_fast (a_cert->cert, test_srv_crt_rsa, test_srv_crt_rsa_len);
1192 vnet_app_add_tls_cert (a_cert);
1194 clib_memset (a_key, 0, sizeof (*a_key));
1195 a_key->app_index = a->app_index;
1196 vec_validate (a_key->key, test_srv_key_rsa_len);
1197 clib_memcpy_fast (a_key->key, test_srv_key_rsa, test_srv_key_rsa_len);
1198 vnet_app_add_tls_key (a_key);
1204 http_static_server_listen ()
1206 http_static_server_main_t *hsm = &http_static_server_main;
1207 vnet_listen_args_t _a, *a = &_a;
1208 clib_memset (a, 0, sizeof (*a));
1209 a->app_index = hsm->app_index;
1210 a->uri = "tcp://0.0.0.0/80";
1212 a->uri = (char *) hsm->uri;
1213 return vnet_bind_uri (a);
1217 http_static_server_session_cleanup_cb (void *hs_handlep)
1219 http_static_server_main_t *hsm = &http_static_server_main;
1222 hs_handle = pointer_to_uword (hs_handlep);
1224 http_static_server_session_get (hs_handle >> 24, hs_handle & 0x00FFFFFF);
1226 if (hsm->debug_level > 1)
1227 clib_warning ("terminate thread %d index %d hs %llx",
1228 hs_handle >> 24, hs_handle & 0x00FFFFFF, hs);
1231 hs->timer_handle = ~0;
1232 http_static_server_session_disconnect (hs);
1233 http_static_server_session_cleanup (hs);
1236 /** \brief Expired session timer-wheel callback
1239 http_expired_timers_dispatch (u32 * expired_timers)
1244 for (i = 0; i < vec_len (expired_timers); i++)
1246 /* Get session handle. The first bit is the timer id */
1247 hs_handle = expired_timers[i] & 0x7FFFFFFF;
1248 session_send_rpc_evt_to_thread (hs_handle >> 24,
1249 http_static_server_session_cleanup_cb,
1250 uword_to_pointer (hs_handle, void *));
1254 /** \brief Timer-wheel expiration process
1257 http_static_server_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1260 http_static_server_main_t *hsm = &http_static_server_main;
1261 f64 now, timeout = 1.0;
1262 uword *event_data = 0;
1263 uword __clib_unused event_type;
1267 vlib_process_wait_for_event_or_clock (vm, timeout);
1268 now = vlib_time_now (vm);
1269 event_type = vlib_process_get_events (vm, (uword **) & event_data);
1272 clib_spinlock_lock (&http_static_server_main.tw_lock);
1273 tw_timer_expire_timers_2t_1w_2048sl (&hsm->tw, now);
1274 clib_spinlock_unlock (&http_static_server_main.tw_lock);
1276 vec_reset_length (event_data);
1282 VLIB_REGISTER_NODE (http_static_server_process_node) =
1284 .function = http_static_server_process,
1285 .type = VLIB_NODE_TYPE_PROCESS,
1286 .name = "static-http-server-process",
1287 .state = VLIB_NODE_STATE_DISABLED,
1292 http_static_server_create (vlib_main_t * vm)
1294 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1295 http_static_server_main_t *hsm = &http_static_server_main;
1299 num_threads = 1 /* main thread */ + vtm->n_threads;
1300 vec_validate (hsm->vpp_queue, num_threads - 1);
1301 vec_validate (hsm->sessions, num_threads - 1);
1302 vec_validate (hsm->session_to_http_session, num_threads - 1);
1304 clib_rwlock_init (&hsm->sessions_lock);
1305 clib_spinlock_init (&hsm->tw_lock);
1307 if (http_static_server_attach ())
1309 clib_warning ("failed to attach server");
1312 if (http_static_server_listen ())
1314 clib_warning ("failed to start listening");
1318 /* Init path-to-cache hash table */
1319 BV (clib_bihash_init) (&hsm->name_to_data, "http cache", 128, 32 << 20);
1321 hsm->get_url_handlers = hash_create_string (0, sizeof (uword));
1322 hsm->post_url_handlers = hash_create_string (0, sizeof (uword));
1324 /* Init timer wheel and process */
1325 tw_timer_wheel_init_2t_1w_2048sl (&hsm->tw, http_expired_timers_dispatch,
1326 1.0 /* timer interval */ , ~0);
1327 vlib_node_set_state (vm, http_static_server_process_node.index,
1328 VLIB_NODE_STATE_POLLING);
1329 n = vlib_get_node (vm, http_static_server_process_node.index);
1330 vlib_start_process (vm, n->runtime_index);
1335 /** \brief API helper function for vl_api_http_static_enable_t messages
1338 http_static_server_enable_api (u32 fifo_size, u32 cache_limit,
1340 u32 private_segment_size,
1341 u8 * www_root, u8 * uri)
1343 http_static_server_main_t *hsm = &http_static_server_main;
1346 hsm->fifo_size = fifo_size;
1347 hsm->cache_limit = cache_limit;
1348 hsm->prealloc_fifos = prealloc_fifos;
1349 hsm->private_segment_size = private_segment_size;
1350 hsm->www_root = format (0, "%s%c", www_root, 0);
1351 hsm->uri = format (0, "%s%c", uri, 0);
1353 if (vec_len (hsm->www_root) < 2)
1354 return VNET_API_ERROR_INVALID_VALUE;
1356 if (hsm->my_client_index != ~0)
1357 return VNET_API_ERROR_APP_ALREADY_ATTACHED;
1359 vnet_session_enable_disable (hsm->vlib_main, 1 /* turn on TCP, etc. */ );
1361 rv = http_static_server_create (hsm->vlib_main);
1367 vec_free (hsm->www_root);
1368 vec_free (hsm->uri);
1369 return VNET_API_ERROR_INIT_FAILED;
1374 static clib_error_t *
1375 http_static_server_create_command_fn (vlib_main_t * vm,
1376 unformat_input_t * input,
1377 vlib_cli_command_t * cmd)
1379 http_static_server_main_t *hsm = &http_static_server_main;
1380 unformat_input_t _line_input, *line_input = &_line_input;
1385 hsm->prealloc_fifos = 0;
1386 hsm->private_segment_size = 0;
1388 /* 10mb cache limit, before LRU occurs */
1389 hsm->cache_limit = 10 << 20;
1391 /* Get a line of input. */
1392 if (!unformat_user (input, unformat_line_input, line_input))
1395 while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1397 if (unformat (line_input, "www-root %s", &www_root))
1400 if (unformat (line_input, "prealloc-fifos %d", &hsm->prealloc_fifos))
1402 else if (unformat (line_input, "private-segment-size %U",
1403 unformat_memory_size, &seg_size))
1405 if (seg_size >= 0x100000000ULL)
1407 vlib_cli_output (vm, "private segment size %llu, too large",
1411 hsm->private_segment_size = seg_size;
1413 else if (unformat (line_input, "fifo-size %d", &hsm->fifo_size))
1414 hsm->fifo_size <<= 10;
1415 else if (unformat (line_input, "cache-size %U", unformat_memory_size,
1418 if (hsm->cache_limit < (128 << 10))
1420 return clib_error_return (0,
1421 "cache-size must be at least 128kb");
1425 else if (unformat (line_input, "uri %s", &hsm->uri))
1427 else if (unformat (line_input, "debug %d", &hsm->debug_level))
1429 else if (unformat (line_input, "debug"))
1430 hsm->debug_level = 1;
1432 return clib_error_return (0, "unknown input `%U'",
1433 format_unformat_error, line_input);
1435 unformat_free (line_input);
1440 return clib_error_return (0, "Must specify www-root <path>");
1443 if (hsm->my_client_index != (u32) ~ 0)
1445 vec_free (www_root);
1446 return clib_error_return (0, "http server already running...");
1449 hsm->www_root = www_root;
1451 vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
1453 rv = http_static_server_create (vm);
1459 vec_free (hsm->www_root);
1460 return clib_error_return (0, "server_create returned %d", rv);
1466 * Enable the static http server
1469 * This command enables the static http server. Only the www-root
1470 * parameter is required
1472 * http static server www-root /tmp/www uri tcp://0.0.0.0/80 cache-size 2m
1474 * @cliexcmd{http static server www-root <path> [prealloc-fios <nn>]
1475 * [private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]}
1478 VLIB_CLI_COMMAND (http_static_server_create_command, static) =
1480 .path = "http static server",
1481 .short_help = "http static server www-root <path> [prealloc-fifos <nn>]\n"
1482 "[private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]\n"
1484 .function = http_static_server_create_command_fn,
1488 /** \brief format a file cache entry
1491 format_hsm_cache_entry (u8 * s, va_list * args)
1493 file_data_cache_t *ep = va_arg (*args, file_data_cache_t *);
1494 f64 now = va_arg (*args, f64);
1499 s = format (s, "%40s%12s%20s", "File", "Size", "Age");
1502 s = format (s, "%40s%12lld%20.2f", ep->filename, vec_len (ep->data),
1503 now - ep->last_used);
1508 format_http_session_state (u8 * s, va_list * args)
1510 http_session_state_t state = va_arg (*args, http_session_state_t);
1511 char *state_string = "bogus!";
1515 case HTTP_STATE_CLOSED:
1516 state_string = "closed";
1518 case HTTP_STATE_ESTABLISHED:
1519 state_string = "established";
1521 case HTTP_STATE_OK_SENT:
1522 state_string = "ok sent";
1524 case HTTP_STATE_SEND_MORE_DATA:
1525 state_string = "send more data";
1531 return format (s, "%s", state_string);
1535 format_http_session (u8 * s, va_list * args)
1537 http_session_t *hs = va_arg (*args, http_session_t *);
1538 int verbose = va_arg (*args, int);
1540 s = format (s, "[%d]: state %U", hs->session_index,
1541 format_http_session_state, hs->session_state);
1544 s = format (s, "\n path %s, data length %u, data_offset %u",
1545 hs->path ? hs->path : (u8 *) "[none]",
1546 vec_len (hs->data), hs->data_offset);
1551 static clib_error_t *
1552 http_show_static_server_command_fn (vlib_main_t * vm,
1553 unformat_input_t * input,
1554 vlib_cli_command_t * cmd)
1556 http_static_server_main_t *hsm = &http_static_server_main;
1557 file_data_cache_t *ep, **entries = 0;
1560 int show_sessions = 0;
1564 if (hsm->www_root == 0)
1565 return clib_error_return (0, "Static server disabled");
1567 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1569 if (unformat (input, "verbose %d", &verbose))
1571 else if (unformat (input, "verbose"))
1573 else if (unformat (input, "cache"))
1575 else if (unformat (input, "sessions"))
1581 if ((show_cache + show_sessions) == 0)
1582 return clib_error_return (0, "specify one or more of cache, sessions");
1589 (vm, "www_root %s, cache size %lld bytes, limit %lld bytes, "
1591 hsm->www_root, hsm->cache_size, hsm->cache_limit,
1592 hsm->cache_evictions);
1596 now = vlib_time_now (vm);
1598 vlib_cli_output (vm, "%U", format_hsm_cache_entry, 0 /* header */ ,
1601 for (index = hsm->first_index; index != ~0;)
1603 ep = pool_elt_at_index (hsm->cache_pool, index);
1604 index = ep->next_index;
1605 vlib_cli_output (vm, "%U", format_hsm_cache_entry, ep, now);
1608 vlib_cli_output (vm, "%40s%12lld", "Total Size", hsm->cache_size);
1615 u32 *session_indices = 0;
1619 http_static_server_sessions_reader_lock ();
1621 for (i = 0; i < vec_len (hsm->sessions); i++)
1624 pool_foreach (hs, hsm->sessions[i],
1626 vec_add1 (session_indices, hs - hsm->sessions[i]);
1630 for (j = 0; j < vec_len (session_indices); j++)
1632 vlib_cli_output (vm, "%U", format_http_session,
1634 (hsm->sessions[i], session_indices[j]),
1637 vec_reset_length (session_indices);
1639 http_static_server_sessions_reader_unlock ();
1640 vec_free (session_indices);
1646 * Display static http server cache statistics
1649 * This command shows the contents of the static http server cache
1651 * show http static server
1653 * @cliexcmd{show http static server sessions cache [verbose [nn]]}
1656 VLIB_CLI_COMMAND (http_show_static_server_command, static) =
1658 .path = "show http static server",
1659 .short_help = "show http static server sessions cache [verbose [<nn>]]",
1660 .function = http_show_static_server_command_fn,
1664 static clib_error_t *
1665 http_clear_static_cache_command_fn (vlib_main_t * vm,
1666 unformat_input_t * input,
1667 vlib_cli_command_t * cmd)
1669 http_static_server_main_t *hsm = &http_static_server_main;
1670 file_data_cache_t *dp;
1673 BVT (clib_bihash_kv) kv;
1675 if (hsm->www_root == 0)
1676 return clib_error_return (0, "Static server disabled");
1678 http_static_server_sessions_reader_lock ();
1680 /* Walk the LRU list to find active entries */
1681 free_index = hsm->last_index;
1682 while (free_index != ~0)
1684 dp = pool_elt_at_index (hsm->cache_pool, free_index);
1685 free_index = dp->prev_index;
1686 /* Which could be in use... */
1690 free_index = dp->next_index;
1693 kv.key = (u64) (dp->filename);
1695 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
1696 0 /* is_add */ ) < 0)
1698 clib_warning ("BUG: cache clear delete '%s' FAILED!", dp->filename);
1701 lru_remove (hsm, dp);
1702 hsm->cache_size -= vec_len (dp->data);
1703 hsm->cache_evictions++;
1704 vec_free (dp->filename);
1705 vec_free (dp->data);
1706 if (hsm->debug_level > 1)
1707 clib_warning ("pool put index %d", dp - hsm->cache_pool);
1708 pool_put (hsm->cache_pool, dp);
1709 free_index = hsm->last_index;
1711 http_static_server_sessions_reader_unlock ();
1713 vlib_cli_output (vm, "Note: %d busy items still in cache...", busy_items);
1715 vlib_cli_output (vm, "Cache cleared...");
1720 * Clear the static http server cache, to force the server to
1721 * reload content from backing files
1724 * This command clear the static http server cache
1726 * clear http static cache
1728 * @cliexcmd{clear http static cache}
1731 VLIB_CLI_COMMAND (clear_http_static_cache_command, static) =
1733 .path = "clear http static cache",
1734 .short_help = "clear http static cache",
1735 .function = http_clear_static_cache_command_fn,
1739 static clib_error_t *
1740 http_static_server_main_init (vlib_main_t * vm)
1742 http_static_server_main_t *hsm = &http_static_server_main;
1744 hsm->my_client_index = ~0;
1745 hsm->vlib_main = vm;
1746 hsm->first_index = hsm->last_index = ~0;
1748 clib_timebase_init (&hsm->timebase, 0 /* GMT */ ,
1749 CLIB_TIMEBASE_DAYLIGHT_NONE,
1750 &vm->clib_time /* share the system clock */ );
1755 VLIB_INIT_FUNCTION (http_static_server_main_init);
1758 * fd.io coding-style-patch-verification: ON
1761 * eval: (c-set-style "gnu")