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/tw_timer_2t_1w_2048sl.h>
21 #include <vppinfra/unix.h>
22 #include <sys/types.h>
25 #include <http_static/http_static.h>
26 #include <vppinfra/bihash_vec8_8.h>
28 #include <vppinfra/bihash_template.c>
31 Simple Static http server, sufficient to
32 serve .html / .css / .js content.
34 /*? %%clicmd:group_label Static HTTP Server %% ?*/
36 /** \brief Session States
41 /** Session is closed */
43 /** Session is established */
44 HTTP_STATE_ESTABLISHED,
45 /** Session has sent an OK response */
47 /** Session has sent an HTML response */
48 HTTP_STATE_SEND_MORE_DATA,
49 /** Number of states */
51 } http_session_state_t;
58 } state_machine_called_from_t;
61 /** \brief Application session
65 CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
66 /** Base class instance variables */
67 #define _(type, name) type name;
68 foreach_app_session_field
70 /** rx thread index */
74 /** vpp session index, handle */
75 u32 vpp_session_index;
76 u64 vpp_session_handle;
77 /** Timeout timer handle */
79 /** Fully-resolved file path */
81 /** File data, a vector */
83 /** Current data send offset */
85 /** File cache pool index */
87 /** state machine called from... */
88 state_machine_called_from_t called_from;
91 /** \brief In-memory file data cache entry
95 /** Name of the file */
97 /** Contents of the file, as a u8 * vector */
99 /** Last time the cache entry was used */
101 /** Cache LRU links */
104 /** Reference count, so we don't recycle while referenced */
108 /** \brief Main data structure
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;
120 /** Enable debug messages */
123 /** vpp message/event queue */
124 svm_msg_q_t **vpp_queue;
126 /** Unified file data cache pool */
127 file_data_cache_t *cache_pool;
128 /** Hash table which maps file name to file data */
129 BVT (clib_bihash) name_to_data;
131 /** Current cache size */
133 /** Max cache size in bytes */
135 /** Number of cache evictions */
138 /** Cache LRU listheads */
142 /** root path to be served */
145 /** Server's event queue */
146 svm_queue_t *vl_input_queue;
148 /** API client handle */
151 /** Application index */
154 /** Process node index for event scheduling */
157 /** Session cleanup timer wheel */
158 tw_timer_wheel_2t_1w_2048sl_t tw;
159 clib_spinlock_t tw_lock;
161 /** Time base, so we can generate browser cache control http spew */
162 clib_timebase_t timebase;
164 /** Number of preallocated fifos, usually 0 */
166 /** Private segment size, usually 0 */
167 u32 private_segment_size;
168 /** Size of the allocated rx, tx fifos, roughly 8K or so */
170 /** The bind URI, defaults to tcp://0.0.0.0/80 */
172 vlib_main_t *vlib_main;
173 } http_static_server_main_t;
175 http_static_server_main_t http_static_server_main;
177 /** \brief Format the called-from enum
181 format_state_machine_called_from (u8 * s, va_list * args)
183 state_machine_called_from_t cf =
184 va_arg (*args, state_machine_called_from_t);
185 char *which = "bogus!";
195 case CALLED_FROM_TIMER:
196 which = "from timer";
203 s = format (s, "%s", which);
208 /** \brief Acquire reader lock on the sessions pools
211 http_static_server_sessions_reader_lock (void)
213 clib_rwlock_reader_lock (&http_static_server_main.sessions_lock);
216 /** \brief Drop reader lock on the sessions pools
219 http_static_server_sessions_reader_unlock (void)
221 clib_rwlock_reader_unlock (&http_static_server_main.sessions_lock);
224 /** \brief Acquire writer lock on the sessions pools
227 http_static_server_sessions_writer_lock (void)
229 clib_rwlock_writer_lock (&http_static_server_main.sessions_lock);
232 /** \brief Drop writer lock on the sessions pools
235 http_static_server_sessions_writer_unlock (void)
237 clib_rwlock_writer_unlock (&http_static_server_main.sessions_lock);
240 /** \brief Allocate an http session
242 static http_session_t *
243 http_static_server_session_alloc (u32 thread_index)
245 http_static_server_main_t *hsm = &http_static_server_main;
247 pool_get (hsm->sessions[thread_index], hs);
248 memset (hs, 0, sizeof (*hs));
249 hs->session_index = hs - hsm->sessions[thread_index];
250 hs->thread_index = thread_index;
251 hs->timer_handle = ~0;
252 hs->cache_pool_index = ~0;
256 /** \brief Get an http session by index
258 static http_session_t *
259 http_static_server_session_get (u32 thread_index, u32 hs_index)
261 http_static_server_main_t *hsm = &http_static_server_main;
262 if (pool_is_free_index (hsm->sessions[thread_index], hs_index))
264 return pool_elt_at_index (hsm->sessions[thread_index], hs_index);
267 /** \brief Free an http session
270 http_static_server_session_free (http_session_t * hs)
272 http_static_server_main_t *hsm = &http_static_server_main;
273 pool_put (hsm->sessions[hs->thread_index], hs);
275 memset (hs, 0xfa, sizeof (*hs));
278 /** \brief add a session to the vpp < -- > http session index map
281 http_static_server_session_lookup_add (u32 thread_index, u32 s_index,
284 http_static_server_main_t *hsm = &http_static_server_main;
285 vec_validate (hsm->session_to_http_session[thread_index], s_index);
286 hsm->session_to_http_session[thread_index][s_index] = hs_index;
289 /** \brief Remove a session from the vpp < -- > http session index map
292 http_static_server_session_lookup_del (u32 thread_index, u32 s_index)
294 http_static_server_main_t *hsm = &http_static_server_main;
295 hsm->session_to_http_session[thread_index][s_index] = ~0;
298 /** \brief lookup a session in the vpp < -- > http session index map
301 static http_session_t *
302 http_static_server_session_lookup (u32 thread_index, u32 s_index)
304 http_static_server_main_t *hsm = &http_static_server_main;
307 if (s_index < vec_len (hsm->session_to_http_session[thread_index]))
309 hs_index = hsm->session_to_http_session[thread_index][s_index];
310 return http_static_server_session_get (thread_index, hs_index);
315 /** \brief Start a session cleanup timer
318 http_static_server_session_timer_start (http_session_t * hs)
321 hs_handle = hs->thread_index << 24 | hs->session_index;
322 clib_spinlock_lock (&http_static_server_main.tw_lock);
323 hs->timer_handle = tw_timer_start_2t_1w_2048sl (&http_static_server_main.tw,
325 clib_spinlock_unlock (&http_static_server_main.tw_lock);
328 /** \brief stop a session cleanup timer
331 http_static_server_session_timer_stop (http_session_t * hs)
333 if (hs->timer_handle == ~0)
335 clib_spinlock_lock (&http_static_server_main.tw_lock);
336 tw_timer_stop_2t_1w_2048sl (&http_static_server_main.tw, hs->timer_handle);
337 clib_spinlock_unlock (&http_static_server_main.tw_lock);
340 /** \brief Detach cache entry from session
344 http_static_server_detach_cache_entry (http_session_t * hs)
346 http_static_server_main_t *hsm = &http_static_server_main;
347 file_data_cache_t *ep;
350 * Decrement cache pool entry reference count
351 * Note that if e.g. a file lookup fails, the cache pool index
354 if (hs->cache_pool_index != ~0)
356 ep = pool_elt_at_index (hsm->cache_pool, hs->cache_pool_index);
358 if (hsm->debug_level > 1)
359 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
362 hs->cache_pool_index = ~0;
368 /** \brief clean up a session
372 http_static_server_session_cleanup (http_session_t * hs)
377 http_static_server_detach_cache_entry (hs);
379 http_static_server_session_lookup_del (hs->thread_index,
380 hs->vpp_session_index);
381 vec_free (hs->rx_buf);
382 http_static_server_session_timer_stop (hs);
383 http_static_server_session_free (hs);
386 /** \brief Disconnect a session
390 http_static_server_session_disconnect (http_session_t * hs)
392 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
393 a->handle = hs->vpp_session_handle;
394 a->app_index = http_static_server_main.app_index;
395 vnet_disconnect_session (a);
399 /** \brief http error boilerplate
401 static const char *http_error_template =
404 "Content-Type: text/html\r\n"
405 "Connection: close\r\n"
406 "Pragma: no-cache\r\n"
407 "Content-Length: 0\r\n\r\n";
409 /** \brief http response boilerplate
411 static const char *http_response_template =
413 "Expires: %U GMT\r\n"
414 "Server: VPP Static\r\n"
415 "Content-Type: text/%s\r\n"
416 "Content-Length: %d\r\n\r\n";
420 /** \brief send http data
421 @param hs - http session
422 @param data - the data vector to transmit
423 @param offset - transmit offset for this operation
424 @return offset for next transmit operation, may be unchanged w/ full fifo
428 static_send_data (http_session_t * hs, u8 * data, u32 length, u32 offset)
431 http_static_server_main_t *hsm = &http_static_server_main;
433 bytes_to_send = length - offset;
435 while (bytes_to_send > 0)
439 actual_transfer = svm_fifo_enqueue
440 (hs->tx_fifo, bytes_to_send, data + offset);
442 /* Made any progress? */
443 if (actual_transfer <= 0)
445 if (hsm->debug_level > 0 && bytes_to_send > 0)
446 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
451 offset += actual_transfer;
452 bytes_to_send -= actual_transfer;
454 if (hsm->debug_level && bytes_to_send > 0)
455 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
457 if (svm_fifo_set_event (hs->tx_fifo))
458 session_send_io_evt_to_thread (hs->tx_fifo,
459 SESSION_IO_EVT_TX_FLUSH);
467 /** \brief Send an http error string
468 @param hs - the http session
469 @param str - the error string, e.g. "404 Not Found"
472 send_error (http_session_t * hs, char *str)
474 http_static_server_main_t *hsm = &http_static_server_main;
478 now = clib_timebase_now (&hsm->timebase);
479 data = format (0, http_error_template, str, format_clib_timebase_time, now);
480 static_send_data (hs, data, vec_len (data), 0);
484 /** \brief Retrieve data from the application layer
487 session_rx_request (http_session_t * hs)
489 u32 max_dequeue, cursize;
492 cursize = vec_len (hs->rx_buf);
493 max_dequeue = svm_fifo_max_dequeue (hs->rx_fifo);
494 if (PREDICT_FALSE (max_dequeue == 0))
497 vec_validate (hs->rx_buf, cursize + max_dequeue - 1);
498 n_read = app_recv_stream_raw (hs->rx_fifo, hs->rx_buf + cursize,
499 max_dequeue, 0, 0 /* peek */ );
500 ASSERT (n_read == max_dequeue);
501 if (svm_fifo_is_empty (hs->rx_fifo))
502 svm_fifo_unset_event (hs->rx_fifo);
504 _vec_len (hs->rx_buf) = cursize + n_read;
508 /** \brief Sanity-check the forward and reverse LRU lists
511 lru_validate (http_static_server_main_t * hsm)
517 file_data_cache_t *ep;
519 last_timestamp = 1e70;
520 for (i = 1, index = hsm->first_index; index != ~0;)
522 ep = pool_elt_at_index (hsm->cache_pool, index);
523 index = ep->next_index;
524 /* Timestamps should be smaller (older) as we walk the fwd list */
525 if (ep->last_used > last_timestamp)
527 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
528 ep - hsm->cache_pool, i,
529 ep->last_used, last_timestamp);
531 last_timestamp = ep->last_used;
535 last_timestamp = 0.0;
536 for (i = 1, index = hsm->last_index; index != ~0;)
538 ep = pool_elt_at_index (hsm->cache_pool, index);
539 index = ep->prev_index;
540 /* Timestamps should be larger (newer) as we walk the rev list */
541 if (ep->last_used < last_timestamp)
543 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
544 ep - hsm->cache_pool, i,
545 ep->last_used, last_timestamp);
547 last_timestamp = ep->last_used;
553 /** \brief Remove a data cache entry from the LRU lists
556 lru_remove (http_static_server_main_t * hsm, file_data_cache_t * ep)
558 file_data_cache_t *next_ep, *prev_ep;
563 ep_index = ep - hsm->cache_pool;
565 /* Deal with list heads */
566 if (ep_index == hsm->first_index)
567 hsm->first_index = ep->next_index;
568 if (ep_index == hsm->last_index)
569 hsm->last_index = ep->prev_index;
572 if (ep->next_index != ~0)
574 next_ep = pool_elt_at_index (hsm->cache_pool, ep->next_index);
575 next_ep->prev_index = ep->prev_index;
578 if (ep->prev_index != ~0)
580 prev_ep = pool_elt_at_index (hsm->cache_pool, ep->prev_index);
581 prev_ep->next_index = ep->next_index;
586 /** \brief Add an entry to the LRU lists, tag w/ supplied timestamp
590 lru_add (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
592 file_data_cache_t *next_ep;
597 ep_index = ep - hsm->cache_pool;
600 * Re-add at the head of the forward LRU list,
601 * tail of the reverse LRU list
603 if (hsm->first_index != ~0)
605 next_ep = pool_elt_at_index (hsm->cache_pool, hsm->first_index);
606 next_ep->prev_index = ep_index;
611 /* ep now the new head of the LRU forward list */
612 ep->next_index = hsm->first_index;
613 hsm->first_index = ep_index;
615 /* single session case: also the tail of the reverse LRU list */
616 if (hsm->last_index == ~0)
617 hsm->last_index = ep_index;
623 /** \brief Remove and re-add a cache entry from/to the LRU lists
627 lru_update (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
629 lru_remove (hsm, ep);
630 lru_add (hsm, ep, now);
633 /** \brief Session-layer (main) data rx callback.
634 Parse the http request, and reply to it.
635 Future extensions might include POST processing, active content, etc.
638 /* svm_fifo_add_want_deq_ntf (tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL)
639 get shoulder-tap when transport dequeues something, set in
642 /** \brief closed state - should never really get here
645 state_closed (session_t * s, http_session_t * hs,
646 state_machine_called_from_t cf)
648 clib_warning ("WARNING: http session %d, called from %U",
649 hs->session_index, format_state_machine_called_from, cf);
654 close_session (http_session_t * hs)
656 http_static_server_session_disconnect (hs);
657 http_static_server_session_cleanup (hs);
660 /** \brief established state - waiting for GET, POST, etc.
663 state_established (session_t * s, http_session_t * hs,
664 state_machine_called_from_t cf)
666 http_static_server_main_t *hsm = &http_static_server_main;
671 struct stat _sb, *sb = &_sb;
674 /* Read data from the sessison layer */
675 rv = session_rx_request (hs);
677 /* No data? Odd, but stay in this state and await further instructions */
681 /* Process the client request */
682 request = hs->rx_buf;
683 request_len = vec_len (request);
684 if (vec_len (request) < 7)
686 send_error (hs, "400 Bad Request");
691 /* We only handle GET requests at the moment */
692 for (i = 0; i < request_len - 4; i++)
694 if (request[i] == 'G' &&
695 request[i + 1] == 'E' &&
696 request[i + 2] == 'T' && request[i + 3] == ' ')
699 if (hsm->debug_level > 1)
700 clib_warning ("Unknown http method");
702 send_error (hs, "405 Method Not Allowed");
709 vec_delete (request, i + 5, 0);
711 /* Lose stuff to the right of the path */
712 for (i = 0; i < vec_len (request); i++)
714 if (request[i] == ' ' || request[i] == '?')
722 * Now we can construct the file to open
723 * Browsers are capable of sporadically including a leading '/'
725 if (request[0] == '/')
726 path = format (0, "%s%s%c", hsm->www_root, request, 0);
728 path = format (0, "%s/%s%c", hsm->www_root, request, 0);
730 if (hsm->debug_level > 0)
731 clib_warning ("GET '%s'", path);
733 /* Try to find the file. 2x special cases to find index.html */
734 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
735 || sb->st_size < 20 /* file too small */
736 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
738 u32 save_length = vec_len (path) - 1;
739 /* Try appending "index.html"... */
740 _vec_len (path) -= 1;
741 path = format (path, "index.html%c", 0);
742 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
743 || sb->st_size < 20 /* file too small */
744 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
746 _vec_len (path) = save_length;
747 path = format (path, "/index.html%c", 0);
749 /* Send a redirect, otherwise the browser will confuse itself */
750 if (stat ((char *) path, sb) < 0 /* cant even stat the file */
751 || sb->st_size < 20 /* file too small */
752 || (sb->st_mode & S_IFMT) != S_IFREG /* not a regular file */ )
755 send_error (hs, "404 Not Found");
761 transport_endpoint_t endpoint;
762 transport_proto_t proto;
768 * To make this bit work correctly, we need to know our local
769 * IP address, etc. and send it in the redirect...
773 vec_delete (path, vec_len (hsm->www_root) - 1, 0);
775 session_get_endpoint (s, &endpoint, 1 /* is_local */ );
777 local_port = clib_net_to_host_u16 (endpoint.port);
779 proto = session_type_transport_proto (s->session_type);
781 if ((proto == TRANSPORT_PROTO_TCP && local_port != 80)
782 || (proto == TRANSPORT_PROTO_TLS && local_port != 443))
785 port_str = format (0, ":%u", (u32) local_port);
788 redirect = format (0, "HTTP/1.1 301 Moved Permanently\r\n"
789 "Location: http%s://%U%s%s\r\n\r\n",
790 proto == TRANSPORT_PROTO_TLS ? "s" : "",
791 format_ip46_address, &endpoint.ip,
793 print_port ? port_str : (u8 *) "", path);
794 if (hsm->debug_level > 0)
795 clib_warning ("redirect: %s", redirect);
799 static_send_data (hs, redirect, vec_len (redirect), 0);
800 hs->session_state = HTTP_STATE_CLOSED;
810 /* find or read the file if we haven't done so yet. */
813 BVT (clib_bihash_kv) kv;
814 file_data_cache_t *dp;
818 /* First, try the cache */
819 kv.key = (u64) hs->path;
820 if (BV (clib_bihash_search) (&hsm->name_to_data, &kv, &kv) == 0)
822 if (hsm->debug_level > 1)
823 clib_warning ("lookup '%s' returned %lld", kv.key, kv.value);
825 /* found the data.. */
826 dp = pool_elt_at_index (hsm->cache_pool, kv.value);
828 /* Update the cache entry, mark it in-use */
829 lru_update (hsm, dp, vlib_time_now (hsm->vlib_main));
830 hs->cache_pool_index = dp - hsm->cache_pool;
832 if (hsm->debug_level > 1)
833 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
838 if (hsm->debug_level > 1)
839 clib_warning ("lookup '%s' failed", kv.key, kv.value);
840 /* Need to recycle one (or more cache) entries? */
841 if (hsm->cache_size > hsm->cache_limit)
843 int free_index = hsm->last_index;
845 while (free_index != ~0)
848 dp = pool_elt_at_index (hsm->cache_pool, free_index);
849 free_index = dp->prev_index;
850 /* Which could be in use... */
853 if (hsm->debug_level > 1)
854 clib_warning ("index %d in use refcnt %d",
855 dp - hsm->cache_pool, dp->inuse);
858 kv.key = (u64) (dp->filename);
860 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
861 0 /* is_add */ ) < 0)
863 clib_warning ("LRU delete '%s' FAILED!", dp->filename);
865 else if (hsm->debug_level > 1)
866 clib_warning ("LRU delete '%s' ok", dp->filename);
868 lru_remove (hsm, dp);
869 hsm->cache_size -= vec_len (dp->data);
870 hsm->cache_evictions++;
871 vec_free (dp->filename);
873 if (hsm->debug_level > 1)
874 clib_warning ("pool put index %d", dp - hsm->cache_pool);
875 pool_put (hsm->cache_pool, dp);
876 if (hsm->cache_size < hsm->cache_limit)
882 error = clib_file_contents ((char *) (hs->path), &hs->data);
885 clib_warning ("Error reading '%s'", hs->path);
886 clib_error_report (error);
891 /* Create a cache entry for it */
892 pool_get (hsm->cache_pool, dp);
893 memset (dp, 0, sizeof (*dp));
894 dp->filename = vec_dup (hs->path);
896 hs->cache_pool_index = dp - hsm->cache_pool;
898 if (hsm->debug_level > 1)
899 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
901 lru_add (hsm, dp, vlib_time_now (hsm->vlib_main));
902 kv.key = (u64) vec_dup (hs->path);
903 kv.value = dp - hsm->cache_pool;
904 /* Add to the lookup table */
905 if (hsm->debug_level > 1)
906 clib_warning ("add '%s' value %lld", kv.key, kv.value);
908 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
909 1 /* is_add */ ) < 0)
911 clib_warning ("BUG: add failed!");
913 hsm->cache_size += vec_len (dp->data);
917 /* send 200 OK first */
918 static_send_data (hs, (u8 *) "HTTP/1.1 200 OK\r\n", 17, 0);
919 hs->session_state = HTTP_STATE_OK_SENT;
924 state_send_more_data (session_t * s, http_session_t * hs,
925 state_machine_called_from_t cf)
928 /* Start sending data */
929 hs->data_offset = static_send_data (hs, hs->data, vec_len (hs->data),
933 if (hs->data_offset < vec_len (hs->data))
935 /* No: ask for a shoulder-tap when the tx fifo has space */
936 svm_fifo_add_want_deq_ntf (hs->tx_fifo,
937 SVM_FIFO_WANT_DEQ_NOTIF_IF_FULL);
938 hs->session_state = HTTP_STATE_SEND_MORE_DATA;
941 /* Finished with this transaction, back to HTTP_STATE_ESTABLISHED */
943 /* Let go of the file cache entry */
944 http_static_server_detach_cache_entry (hs);
945 hs->session_state = HTTP_STATE_ESTABLISHED;
950 state_sent_ok (session_t * s, http_session_t * hs,
951 state_machine_called_from_t cf)
953 http_static_server_main_t *hsm = &http_static_server_main;
960 /* What kind of dog food are we serving? */
961 suffix = (char *) (hs->path + vec_len (hs->path) - 1);
962 while (*suffix != '.')
966 if (!clib_strcmp (suffix, "css"))
968 else if (!clib_strcmp (suffix, "js"))
969 http_type = "javascript";
974 clib_warning ("BUG: hs->data not set for session %d",
981 * Send an http response, which needs the current time,
982 * the expiration time, and the data length
984 now = clib_timebase_now (&hsm->timebase);
985 http_response = format (0, http_response_template,
987 format_clib_timebase_time, now,
989 format_clib_timebase_time, now + 600.0,
990 http_type, vec_len (hs->data));
991 offset = static_send_data (hs, http_response, vec_len (http_response), 0);
992 if (offset != vec_len (http_response))
994 clib_warning ("BUG: couldn't send response header!");
998 vec_free (http_response);
1000 /* Send data from the beginning... */
1001 hs->data_offset = 0;
1002 hs->session_state = HTTP_STATE_SEND_MORE_DATA;
1006 static void *state_funcs[HTTP_STATE_N_STATES] = {
1008 /* Waiting for GET, POST, etc. */
1012 /* Send more data */
1013 state_send_more_data,
1017 http_static_server_rx_tx_callback (session_t * s,
1018 state_machine_called_from_t cf)
1021 int (*fp) (session_t *, http_session_t *, state_machine_called_from_t);
1024 /* Acquire a reader lock on the session table */
1025 http_static_server_sessions_reader_lock ();
1026 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1030 clib_warning ("No http session for thread %d session_index %d",
1031 s->thread_index, s->session_index);
1032 http_static_server_sessions_reader_unlock ();
1036 /* Execute state machine for this session */
1039 fp = state_funcs[hs->session_state];
1040 rv = (*fp) (s, hs, cf);
1044 /* Reset the session expiration timer */
1045 http_static_server_session_timer_stop (hs);
1046 http_static_server_session_timer_start (hs);
1048 http_static_server_sessions_reader_unlock ();
1053 http_static_server_rx_callback (session_t * s)
1055 return http_static_server_rx_tx_callback (s, CALLED_FROM_RX);
1059 http_static_server_tx_callback (session_t * s)
1061 return http_static_server_rx_tx_callback (s, CALLED_FROM_TX);
1065 /** \brief Session accept callback
1069 http_static_server_session_accept_callback (session_t * s)
1071 http_static_server_main_t *hsm = &http_static_server_main;
1074 hsm->vpp_queue[s->thread_index] =
1075 session_main_get_vpp_event_queue (s->thread_index);
1077 http_static_server_sessions_writer_lock ();
1079 hs = http_static_server_session_alloc (s->thread_index);
1080 http_static_server_session_lookup_add (s->thread_index, s->session_index,
1082 hs->rx_fifo = s->rx_fifo;
1083 hs->tx_fifo = s->tx_fifo;
1084 hs->vpp_session_index = s->session_index;
1085 hs->vpp_session_handle = session_handle (s);
1086 hs->session_state = HTTP_STATE_ESTABLISHED;
1087 http_static_server_session_timer_start (hs);
1089 http_static_server_sessions_writer_unlock ();
1091 s->session_state = SESSION_STATE_READY;
1095 /** \brief Session disconnect callback
1099 http_static_server_session_disconnect_callback (session_t * s)
1101 http_static_server_main_t *hsm = &http_static_server_main;
1102 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1105 http_static_server_sessions_writer_lock ();
1107 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1108 http_static_server_session_cleanup (hs);
1110 http_static_server_sessions_writer_unlock ();
1112 a->handle = session_handle (s);
1113 a->app_index = hsm->app_index;
1114 vnet_disconnect_session (a);
1117 /** \brief Session reset callback
1121 http_static_server_session_reset_callback (session_t * s)
1123 http_static_server_main_t *hsm = &http_static_server_main;
1124 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1127 http_static_server_sessions_writer_lock ();
1129 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1130 http_static_server_session_cleanup (hs);
1132 http_static_server_sessions_writer_unlock ();
1134 a->handle = session_handle (s);
1135 a->app_index = hsm->app_index;
1136 vnet_disconnect_session (a);
1140 http_static_server_session_connected_callback (u32 app_index, u32 api_context,
1141 session_t * s, u8 is_fail)
1143 clib_warning ("called...");
1148 http_static_server_add_segment_callback (u32 client_index, u64 segment_handle)
1150 clib_warning ("called...");
1154 /** \brief Session-layer virtual function table
1156 static session_cb_vft_t http_static_server_session_cb_vft = {
1157 .session_accept_callback = http_static_server_session_accept_callback,
1158 .session_disconnect_callback =
1159 http_static_server_session_disconnect_callback,
1160 .session_connected_callback = http_static_server_session_connected_callback,
1161 .add_segment_callback = http_static_server_add_segment_callback,
1162 .builtin_app_rx_callback = http_static_server_rx_callback,
1163 .builtin_app_tx_callback = http_static_server_tx_callback,
1164 .session_reset_callback = http_static_server_session_reset_callback
1168 http_static_server_attach ()
1170 vnet_app_add_tls_cert_args_t _a_cert, *a_cert = &_a_cert;
1171 vnet_app_add_tls_key_args_t _a_key, *a_key = &_a_key;
1172 http_static_server_main_t *hsm = &http_static_server_main;
1173 u64 options[APP_OPTIONS_N_OPTIONS];
1174 vnet_app_attach_args_t _a, *a = &_a;
1175 u32 segment_size = 128 << 20;
1177 clib_memset (a, 0, sizeof (*a));
1178 clib_memset (options, 0, sizeof (options));
1180 if (hsm->private_segment_size)
1181 segment_size = hsm->private_segment_size;
1183 a->api_client_index = ~0;
1184 a->name = format (0, "test_http_static_server");
1185 a->session_cb_vft = &http_static_server_session_cb_vft;
1186 a->options = options;
1187 a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
1188 a->options[APP_OPTIONS_RX_FIFO_SIZE] =
1189 hsm->fifo_size ? hsm->fifo_size : 8 << 10;
1190 a->options[APP_OPTIONS_TX_FIFO_SIZE] =
1191 hsm->fifo_size ? hsm->fifo_size : 32 << 10;
1192 a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1193 a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = hsm->prealloc_fifos;
1194 a->options[APP_OPTIONS_TLS_ENGINE] = TLS_ENGINE_OPENSSL;
1196 if (vnet_application_attach (a))
1199 clib_warning ("failed to attach server");
1203 hsm->app_index = a->app_index;
1205 clib_memset (a_cert, 0, sizeof (*a_cert));
1206 a_cert->app_index = a->app_index;
1207 vec_validate (a_cert->cert, test_srv_crt_rsa_len);
1208 clib_memcpy_fast (a_cert->cert, test_srv_crt_rsa, test_srv_crt_rsa_len);
1209 vnet_app_add_tls_cert (a_cert);
1211 clib_memset (a_key, 0, sizeof (*a_key));
1212 a_key->app_index = a->app_index;
1213 vec_validate (a_key->key, test_srv_key_rsa_len);
1214 clib_memcpy_fast (a_key->key, test_srv_key_rsa, test_srv_key_rsa_len);
1215 vnet_app_add_tls_key (a_key);
1221 http_static_server_listen ()
1223 http_static_server_main_t *hsm = &http_static_server_main;
1224 vnet_listen_args_t _a, *a = &_a;
1225 clib_memset (a, 0, sizeof (*a));
1226 a->app_index = hsm->app_index;
1227 a->uri = "tcp://0.0.0.0/80";
1229 a->uri = (char *) hsm->uri;
1230 return vnet_bind_uri (a);
1234 http_static_server_session_cleanup_cb (void *hs_handlep)
1236 http_static_server_main_t *hsm = &http_static_server_main;
1239 hs_handle = pointer_to_uword (hs_handlep);
1241 http_static_server_session_get (hs_handle >> 24, hs_handle & 0x00FFFFFF);
1243 if (hsm->debug_level > 1)
1244 clib_warning ("terminate thread %d index %d hs %llx",
1245 hs_handle >> 24, hs_handle & 0x00FFFFFF, hs);
1248 hs->timer_handle = ~0;
1249 http_static_server_session_disconnect (hs);
1250 http_static_server_session_cleanup (hs);
1253 /** \brief Expired session timer-wheel callback
1256 http_expired_timers_dispatch (u32 * expired_timers)
1261 for (i = 0; i < vec_len (expired_timers); i++)
1263 /* Get session handle. The first bit is the timer id */
1264 hs_handle = expired_timers[i] & 0x7FFFFFFF;
1265 session_send_rpc_evt_to_thread (hs_handle >> 24,
1266 http_static_server_session_cleanup_cb,
1267 uword_to_pointer (hs_handle, void *));
1271 /** \brief Timer-wheel expiration process
1274 http_static_server_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
1277 http_static_server_main_t *hsm = &http_static_server_main;
1278 f64 now, timeout = 1.0;
1279 uword *event_data = 0;
1280 uword __clib_unused event_type;
1284 vlib_process_wait_for_event_or_clock (vm, timeout);
1285 now = vlib_time_now (vm);
1286 event_type = vlib_process_get_events (vm, (uword **) & event_data);
1289 clib_spinlock_lock (&http_static_server_main.tw_lock);
1290 tw_timer_expire_timers_2t_1w_2048sl (&hsm->tw, now);
1291 clib_spinlock_unlock (&http_static_server_main.tw_lock);
1293 vec_reset_length (event_data);
1299 VLIB_REGISTER_NODE (http_static_server_process_node) =
1301 .function = http_static_server_process,
1302 .type = VLIB_NODE_TYPE_PROCESS,
1303 .name = "static-http-server-process",
1304 .state = VLIB_NODE_STATE_DISABLED,
1309 http_static_server_create (vlib_main_t * vm)
1311 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1312 http_static_server_main_t *hsm = &http_static_server_main;
1316 num_threads = 1 /* main thread */ + vtm->n_threads;
1317 vec_validate (hsm->vpp_queue, num_threads - 1);
1318 vec_validate (hsm->sessions, num_threads - 1);
1319 vec_validate (hsm->session_to_http_session, num_threads - 1);
1321 clib_rwlock_init (&hsm->sessions_lock);
1322 clib_spinlock_init (&hsm->tw_lock);
1324 if (http_static_server_attach ())
1326 clib_warning ("failed to attach server");
1329 if (http_static_server_listen ())
1331 clib_warning ("failed to start listening");
1335 /* Init path-to-cache hash table */
1336 BV (clib_bihash_init) (&hsm->name_to_data, "http cache", 128, 32 << 20);
1338 /* Init timer wheel and process */
1339 tw_timer_wheel_init_2t_1w_2048sl (&hsm->tw, http_expired_timers_dispatch,
1340 1.0 /* timer interval */ , ~0);
1341 vlib_node_set_state (vm, http_static_server_process_node.index,
1342 VLIB_NODE_STATE_POLLING);
1343 n = vlib_get_node (vm, http_static_server_process_node.index);
1344 vlib_start_process (vm, n->runtime_index);
1349 /** \brief API helper function for vl_api_http_static_enable_t messages
1352 http_static_server_enable_api (u32 fifo_size, u32 cache_limit,
1354 u32 private_segment_size,
1355 u8 * www_root, u8 * uri)
1357 http_static_server_main_t *hsm = &http_static_server_main;
1360 hsm->fifo_size = fifo_size;
1361 hsm->cache_limit = cache_limit;
1362 hsm->prealloc_fifos = prealloc_fifos;
1363 hsm->private_segment_size = private_segment_size;
1364 hsm->www_root = format (0, "%s%c", www_root, 0);
1365 hsm->uri = format (0, "%s%c", uri, 0);
1367 if (vec_len (hsm->www_root) < 2)
1368 return VNET_API_ERROR_INVALID_VALUE;
1370 if (hsm->my_client_index != ~0)
1371 return VNET_API_ERROR_APP_ALREADY_ATTACHED;
1373 vnet_session_enable_disable (hsm->vlib_main, 1 /* turn on TCP, etc. */ );
1375 rv = http_static_server_create (hsm->vlib_main);
1381 vec_free (hsm->www_root);
1382 vec_free (hsm->uri);
1383 return VNET_API_ERROR_INIT_FAILED;
1388 static clib_error_t *
1389 http_static_server_create_command_fn (vlib_main_t * vm,
1390 unformat_input_t * input,
1391 vlib_cli_command_t * cmd)
1393 http_static_server_main_t *hsm = &http_static_server_main;
1394 unformat_input_t _line_input, *line_input = &_line_input;
1399 hsm->prealloc_fifos = 0;
1400 hsm->private_segment_size = 0;
1402 /* 10mb cache limit, before LRU occurs */
1403 hsm->cache_limit = 10 << 20;
1405 /* Get a line of input. */
1406 if (!unformat_user (input, unformat_line_input, line_input))
1409 while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1411 if (unformat (line_input, "www-root %s", &www_root))
1414 if (unformat (line_input, "prealloc-fifos %d", &hsm->prealloc_fifos))
1416 else if (unformat (line_input, "private-segment-size %U",
1417 unformat_memory_size, &seg_size))
1419 if (seg_size >= 0x100000000ULL)
1421 vlib_cli_output (vm, "private segment size %llu, too large",
1425 hsm->private_segment_size = seg_size;
1427 else if (unformat (line_input, "fifo-size %d", &hsm->fifo_size))
1428 hsm->fifo_size <<= 10;
1429 else if (unformat (line_input, "cache-size %U", unformat_memory_size,
1432 if (hsm->cache_limit < (128 << 10))
1434 return clib_error_return (0,
1435 "cache-size must be at least 128kb");
1439 else if (unformat (line_input, "uri %s", &hsm->uri))
1441 else if (unformat (line_input, "debug %d", &hsm->debug_level))
1443 else if (unformat (line_input, "debug"))
1444 hsm->debug_level = 1;
1446 return clib_error_return (0, "unknown input `%U'",
1447 format_unformat_error, line_input);
1449 unformat_free (line_input);
1454 return clib_error_return (0, "Must specify www-root <path>");
1457 if (hsm->my_client_index != (u32) ~ 0)
1459 vec_free (www_root);
1460 return clib_error_return (0, "http server already running...");
1463 hsm->www_root = www_root;
1465 vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
1467 rv = http_static_server_create (vm);
1473 vec_free (hsm->www_root);
1474 return clib_error_return (0, "server_create returned %d", rv);
1480 * Enable the static http server
1483 * This command enables the static http server. Only the www-root
1484 * parameter is required
1486 * http static server www-root /tmp/www uri tcp://0.0.0.0/80 cache-size 2m
1488 * @cliexcmd{http static server www-root <path> [prealloc-fios <nn>]
1489 * [private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]}
1492 VLIB_CLI_COMMAND (http_static_server_create_command, static) =
1494 .path = "http static server",
1495 .short_help = "http static server www-root <path> [prealloc-fifos <nn>]\n"
1496 "[private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]\n"
1498 .function = http_static_server_create_command_fn,
1502 /** \brief format a file cache entry
1505 format_hsm_cache_entry (u8 * s, va_list * args)
1507 file_data_cache_t *ep = va_arg (*args, file_data_cache_t *);
1508 f64 now = va_arg (*args, f64);
1513 s = format (s, "%40s%12s%20s", "File", "Size", "Age");
1516 s = format (s, "%40s%12lld%20.2f", ep->filename, vec_len (ep->data),
1517 now - ep->last_used);
1522 format_http_session_state (u8 * s, va_list * args)
1524 http_session_state_t state = va_arg (*args, http_session_state_t);
1525 char *state_string = "bogus!";
1529 case HTTP_STATE_CLOSED:
1530 state_string = "closed";
1532 case HTTP_STATE_ESTABLISHED:
1533 state_string = "established";
1535 case HTTP_STATE_OK_SENT:
1536 state_string = "ok sent";
1538 case HTTP_STATE_SEND_MORE_DATA:
1539 state_string = "send more data";
1545 return format (s, "%s", state_string);
1549 format_http_session (u8 * s, va_list * args)
1551 http_session_t *hs = va_arg (*args, http_session_t *);
1552 int verbose = va_arg (*args, int);
1554 s = format (s, "[%d]: state %U", hs->session_index,
1555 format_http_session_state, hs->session_state);
1558 s = format (s, "\n path %s, data length %u, data_offset %u",
1559 hs->path ? hs->path : (u8 *) "[none]",
1560 vec_len (hs->data), hs->data_offset);
1565 static clib_error_t *
1566 http_show_static_server_command_fn (vlib_main_t * vm,
1567 unformat_input_t * input,
1568 vlib_cli_command_t * cmd)
1570 http_static_server_main_t *hsm = &http_static_server_main;
1571 file_data_cache_t *ep, **entries = 0;
1574 int show_sessions = 0;
1578 if (hsm->www_root == 0)
1579 return clib_error_return (0, "Static server disabled");
1581 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1583 if (unformat (input, "verbose %d", &verbose))
1585 else if (unformat (input, "verbose"))
1587 else if (unformat (input, "cache"))
1589 else if (unformat (input, "sessions"))
1595 if ((show_cache + show_sessions) == 0)
1596 return clib_error_return (0, "specify one or more of cache, sessions");
1603 (vm, "www_root %s, cache size %lld bytes, limit %lld bytes, "
1605 hsm->www_root, hsm->cache_size, hsm->cache_limit,
1606 hsm->cache_evictions);
1610 now = vlib_time_now (vm);
1612 vlib_cli_output (vm, "%U", format_hsm_cache_entry, 0 /* header */ ,
1615 for (index = hsm->first_index; index != ~0;)
1617 ep = pool_elt_at_index (hsm->cache_pool, index);
1618 index = ep->next_index;
1619 vlib_cli_output (vm, "%U", format_hsm_cache_entry, ep, now);
1622 vlib_cli_output (vm, "%40s%12lld", "Total Size", hsm->cache_size);
1629 u32 *session_indices = 0;
1633 http_static_server_sessions_reader_lock ();
1635 for (i = 0; i < vec_len (hsm->sessions); i++)
1638 pool_foreach (hs, hsm->sessions[i],
1640 vec_add1 (session_indices, hs - hsm->sessions[i]);
1644 for (j = 0; j < vec_len (session_indices); j++)
1646 vlib_cli_output (vm, "%U", format_http_session,
1648 (hsm->sessions[i], session_indices[j]),
1651 vec_reset_length (session_indices);
1653 http_static_server_sessions_reader_unlock ();
1654 vec_free (session_indices);
1660 * Display static http server cache statistics
1663 * This command shows the contents of the static http server cache
1665 * show http static server
1667 * @cliexcmd{show http static server sessions cache [verbose [nn]]}
1670 VLIB_CLI_COMMAND (http_show_static_server_command, static) =
1672 .path = "show http static server",
1673 .short_help = "show http static server sessions cache [verbose [<nn>]]",
1674 .function = http_show_static_server_command_fn,
1678 static clib_error_t *
1679 http_static_server_main_init (vlib_main_t * vm)
1681 http_static_server_main_t *hsm = &http_static_server_main;
1683 hsm->my_client_index = ~0;
1684 hsm->vlib_main = vm;
1685 hsm->first_index = hsm->last_index = ~0;
1687 clib_timebase_init (&hsm->timebase, 0 /* GMT */ ,
1688 CLIB_TIMEBASE_DAYLIGHT_NONE);
1693 VLIB_INIT_FUNCTION (http_static_server_main_init);
1696 * fd.io coding-style-patch-verification: ON
1699 * eval: (c-set-style "gnu")