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 /** vpp message/event queue */
121 svm_msg_q_t **vpp_queue;
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;
128 /** Current cache size */
130 /** Max cache size in bytes */
132 /** Number of cache evictions */
135 /** Cache LRU listheads */
139 /** root path to be served */
142 /** Server's event queue */
143 svm_queue_t *vl_input_queue;
145 /** API client handle */
148 /** Application index */
151 /** Process node index for event scheduling */
154 /** Session cleanup timer wheel */
155 tw_timer_wheel_2t_1w_2048sl_t tw;
156 clib_spinlock_t tw_lock;
158 /** Time base, so we can generate browser cache control http spew */
159 clib_timebase_t timebase;
161 /** Number of preallocated fifos, usually 0 */
163 /** Private segment size, usually 0 */
164 u32 private_segment_size;
165 /** Size of the allocated rx, tx fifos, roughly 8K or so */
167 /** The bind URI, defaults to tcp://0.0.0.0/80 */
169 vlib_main_t *vlib_main;
170 } http_static_server_main_t;
172 http_static_server_main_t http_static_server_main;
174 /** \brief Format the called-from enum
178 format_state_machine_called_from (u8 * s, va_list * args)
180 state_machine_called_from_t cf =
181 va_arg (*args, state_machine_called_from_t);
182 char *which = "bogus!";
192 case CALLED_FROM_TIMER:
193 which = "from timer";
200 s = format (s, "%s", which);
205 /** \brief Acquire reader lock on the sessions pools
208 http_static_server_sessions_reader_lock (void)
210 clib_rwlock_reader_lock (&http_static_server_main.sessions_lock);
213 /** \brief Drop reader lock on the sessions pools
216 http_static_server_sessions_reader_unlock (void)
218 clib_rwlock_reader_unlock (&http_static_server_main.sessions_lock);
221 /** \brief Acquire writer lock on the sessions pools
224 http_static_server_sessions_writer_lock (void)
226 clib_rwlock_writer_lock (&http_static_server_main.sessions_lock);
229 /** \brief Drop writer lock on the sessions pools
232 http_static_server_sessions_writer_unlock (void)
234 clib_rwlock_writer_unlock (&http_static_server_main.sessions_lock);
237 /** \brief Allocate an http session
239 static http_session_t *
240 http_static_server_session_alloc (u32 thread_index)
242 http_static_server_main_t *hsm = &http_static_server_main;
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;
253 /** \brief Get an http session by index
255 static http_session_t *
256 http_static_server_session_get (u32 thread_index, u32 hs_index)
258 http_static_server_main_t *hsm = &http_static_server_main;
259 if (pool_is_free_index (hsm->sessions[thread_index], hs_index))
261 return pool_elt_at_index (hsm->sessions[thread_index], hs_index);
264 /** \brief Free an http session
267 http_static_server_session_free (http_session_t * hs)
269 http_static_server_main_t *hsm = &http_static_server_main;
270 pool_put (hsm->sessions[hs->thread_index], hs);
272 memset (hs, 0xfa, sizeof (*hs));
275 /** \brief add a session to the vpp < -- > http session index map
278 http_static_server_session_lookup_add (u32 thread_index, u32 s_index,
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;
286 /** \brief Remove a session from the vpp < -- > http session index map
289 http_static_server_session_lookup_del (u32 thread_index, u32 s_index)
291 http_static_server_main_t *hsm = &http_static_server_main;
292 hsm->session_to_http_session[thread_index][s_index] = ~0;
295 /** \brief lookup a session in the vpp < -- > http session index map
298 static http_session_t *
299 http_static_server_session_lookup (u32 thread_index, u32 s_index)
301 http_static_server_main_t *hsm = &http_static_server_main;
304 if (s_index < vec_len (hsm->session_to_http_session[thread_index]))
306 hs_index = hsm->session_to_http_session[thread_index][s_index];
307 return http_static_server_session_get (thread_index, hs_index);
312 /** \brief Start a session cleanup timer
316 http_static_server_session_timer_start (http_session_t * hs)
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,
323 clib_spinlock_unlock (&http_static_server_main.tw_lock);
326 /** \brief stop a session cleanup timer
329 http_static_server_session_timer_stop (http_session_t * hs)
331 if (hs->timer_handle == ~0)
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);
338 /** \brief Clean up an http session
342 http_static_server_detach_cache_entry (http_session_t * hs)
344 http_static_server_main_t *hsm = &http_static_server_main;
345 file_data_cache_t *ep;
348 * Decrement cache pool entry reference count
349 * Note that if e.g. a file lookup fails, the cache pool index
352 if (hs->cache_pool_index != ~0)
354 ep = pool_elt_at_index (hsm->cache_pool, hs->cache_pool_index);
357 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
360 hs->cache_pool_index = ~0;
367 http_static_server_session_cleanup (http_session_t * hs)
372 http_static_server_detach_cache_entry (hs);
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);
381 /** \brief Disconnect a session
385 http_static_server_session_disconnect (http_session_t * hs)
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);
394 /** \brief http error boilerplate
396 static const char *http_error_template =
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";
404 /** \brief http response boilerplate
406 static const char *http_response_template =
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";
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
423 static_send_data (http_session_t * hs, u8 * data, u32 length, u32 offset)
427 bytes_to_send = length - offset;
429 while (bytes_to_send > 0)
433 actual_transfer = svm_fifo_enqueue
434 (hs->tx_fifo, bytes_to_send, data + offset);
436 /* Made any progress? */
437 if (actual_transfer <= 0)
439 if (bytes_to_send > 0)
440 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
445 offset += actual_transfer;
446 bytes_to_send -= actual_transfer;
448 if (bytes_to_send > 0)
449 clib_warning ("WARNING: still %d bytes to send", bytes_to_send);
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);
461 /** \brief Send an http error string
462 @param hs - the http session
463 @param str - the error string, e.g. "404 Not Found"
466 send_error (http_session_t * hs, char *str)
468 http_static_server_main_t *hsm = &http_static_server_main;
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);
478 /** \brief Retrieve data from the application layer
481 session_rx_request (http_session_t * hs)
483 u32 max_dequeue, cursize;
486 cursize = vec_len (hs->rx_buf);
487 max_dequeue = svm_fifo_max_dequeue (hs->rx_fifo);
488 if (PREDICT_FALSE (max_dequeue == 0))
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);
498 _vec_len (hs->rx_buf) = cursize + n_read;
502 /** \brief Sanity-check the forward and reverse LRU lists
505 lru_validate (http_static_server_main_t * hsm)
511 file_data_cache_t *ep;
513 last_timestamp = 1e70;
514 for (i = 1, index = hsm->first_index; index != ~0;)
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)
521 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
522 ep - hsm->cache_pool, i,
523 ep->last_used, last_timestamp);
525 last_timestamp = ep->last_used;
529 last_timestamp = 0.0;
530 for (i = 1, index = hsm->last_index; index != ~0;)
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)
537 clib_warning ("%d[%d]: last used %.6f, last_timestamp %.6f",
538 ep - hsm->cache_pool, i,
539 ep->last_used, last_timestamp);
541 last_timestamp = ep->last_used;
547 /** \brief Remove a data cache entry from the LRU lists
550 lru_remove (http_static_server_main_t * hsm, file_data_cache_t * ep)
552 file_data_cache_t *next_ep, *prev_ep;
557 ep_index = ep - hsm->cache_pool;
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;
566 if (ep->next_index != ~0)
568 next_ep = pool_elt_at_index (hsm->cache_pool, ep->next_index);
569 next_ep->prev_index = ep->prev_index;
572 if (ep->prev_index != ~0)
574 prev_ep = pool_elt_at_index (hsm->cache_pool, ep->prev_index);
575 prev_ep->next_index = ep->next_index;
580 /** \brief Add an entry to the LRU lists, tag w/ supplied timestamp
584 lru_add (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
586 file_data_cache_t *next_ep;
591 ep_index = ep - hsm->cache_pool;
594 * Re-add at the head of the forward LRU list,
595 * tail of the reverse LRU list
597 if (hsm->first_index != ~0)
599 next_ep = pool_elt_at_index (hsm->cache_pool, hsm->first_index);
600 next_ep->prev_index = ep_index;
605 /* ep now the new head of the LRU forward list */
606 ep->next_index = hsm->first_index;
607 hsm->first_index = ep_index;
609 /* single session case: also the tail of the reverse LRU list */
610 if (hsm->last_index == ~0)
611 hsm->last_index = ep_index;
617 /** \brief Remove and re-add a cache entry from/to the LRU lists
621 lru_update (http_static_server_main_t * hsm, file_data_cache_t * ep, f64 now)
623 lru_remove (hsm, ep);
624 lru_add (hsm, ep, now);
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.
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
636 /** \brief closed state - should never really get here
639 state_closed (session_t * s, http_session_t * hs,
640 state_machine_called_from_t cf)
642 clib_warning ("http session %d, called from %U",
643 hs->session_index, format_state_machine_called_from, cf);
648 close_session (http_session_t * hs)
650 http_static_server_session_disconnect (hs);
651 http_static_server_session_cleanup (hs);
654 /** \brief established state - waiting for GET, POST, etc.
657 state_established (session_t * s, http_session_t * hs,
658 state_machine_called_from_t cf)
660 http_static_server_main_t *hsm = &http_static_server_main;
665 struct stat _sb, *sb = &_sb;
668 /* Read data from the sessison layer */
669 rv = session_rx_request (hs);
671 /* No data? Odd, but stay in this state and await further instructions */
675 /* Process the client request */
676 request = hs->rx_buf;
677 request_len = vec_len (request);
678 if (vec_len (request) < 7)
680 send_error (hs, "400 Bad Request");
685 /* We only handle GET requests at the moment */
686 for (i = 0; i < request_len - 4; i++)
688 if (request[i] == 'G' &&
689 request[i + 1] == 'E' &&
690 request[i + 2] == 'T' && request[i + 3] == ' ')
693 send_error (hs, "405 Method Not Allowed");
700 vec_delete (request, i + 5, 0);
702 /* Lose stuff to the right of the path */
703 for (i = 0; i < vec_len (request); i++)
705 if (request[i] == ' ' || request[i] == '?')
713 * Now we can construct the file to open
714 * Browsers are capable of sporadically including a leading '/'
716 if (request[0] == '/')
717 path = format (0, "%s%s%c", hsm->www_root, request, 0);
719 path = format (0, "%s/%s%c", hsm->www_root, request, 0);
722 clib_warning ("GET '%s'", path);
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 */ )
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 */ )
737 _vec_len (path) = save_length;
738 path = format (path, "/index.html%c", 0);
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 */ )
746 send_error (hs, "404 Not Found");
752 transport_endpoint_t endpoint;
753 transport_proto_t proto;
759 * To make this bit work correctly, we need to know our local
760 * IP address, etc. and send it in the redirect...
764 vec_delete (path, vec_len (hsm->www_root) - 1, 0);
766 session_get_endpoint (s, &endpoint, 1 /* is_local */ );
768 local_port = clib_net_to_host_u16 (endpoint.port);
770 proto = session_type_transport_proto (s->session_type);
772 if ((proto == TRANSPORT_PROTO_TCP && local_port != 80)
773 || (proto == TRANSPORT_PROTO_TLS && local_port != 443))
776 port_str = format (0, ":%u", (u32) local_port);
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,
784 print_port ? port_str : (u8 *) "", path);
786 clib_warning ("redirect: %s", redirect);
790 static_send_data (hs, redirect, vec_len (redirect), 0);
791 hs->session_state = HTTP_STATE_CLOSED;
801 /* find or read the file if we haven't done so yet. */
804 BVT (clib_bihash_kv) kv;
805 file_data_cache_t *dp;
809 /* First, try the cache */
810 kv.key = (u64) hs->path;
811 if (BV (clib_bihash_search) (&hsm->name_to_data, &kv, &kv) == 0)
814 clib_warning ("lookup '%s' returned %lld", kv.key, kv.value);
816 /* found the data.. */
817 dp = pool_elt_at_index (hsm->cache_pool, kv.value);
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;
824 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
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)
834 int free_index = hsm->last_index;
836 while (free_index != ~0)
839 dp = pool_elt_at_index (hsm->cache_pool, free_index);
840 free_index = dp->prev_index;
841 /* Which could be in use... */
845 clib_warning ("index %d in use refcnt %d",
846 dp - hsm->cache_pool, dp->inuse);
849 kv.key = (u64) (dp->filename);
851 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
852 0 /* is_add */ ) < 0)
854 clib_warning ("LRU delete '%s' FAILED!", dp->filename);
857 clib_warning ("LRU delete '%s' ok", dp->filename);
859 lru_remove (hsm, dp);
860 hsm->cache_size -= vec_len (dp->data);
861 hsm->cache_evictions++;
862 vec_free (dp->filename);
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)
873 error = clib_file_contents ((char *) (hs->path), &hs->data);
876 clib_warning ("Error reading '%s'", hs->path);
877 clib_error_report (error);
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);
887 hs->cache_pool_index = dp - hsm->cache_pool;
890 clib_warning ("index %d refcnt now %d", hs->cache_pool_index,
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 */
897 clib_warning ("add '%s' value %lld", kv.key, kv.value);
899 if (BV (clib_bihash_add_del) (&hsm->name_to_data, &kv,
900 1 /* is_add */ ) < 0)
902 clib_warning ("BUG: add failed!");
904 hsm->cache_size += vec_len (dp->data);
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;
915 state_send_more_data (session_t * s, http_session_t * hs,
916 state_machine_called_from_t cf)
919 /* Start sending data */
920 hs->data_offset = static_send_data (hs, hs->data, vec_len (hs->data),
924 if (hs->data_offset < vec_len (hs->data))
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;
932 /* Finished with this transaction, back to HTTP_STATE_ESTABLISHED */
934 /* Let go of the file cache entry */
935 http_static_server_detach_cache_entry (hs);
936 hs->session_state = HTTP_STATE_ESTABLISHED;
941 state_sent_ok (session_t * s, http_session_t * hs,
942 state_machine_called_from_t cf)
944 http_static_server_main_t *hsm = &http_static_server_main;
951 /* What kind of dog food are we serving? */
952 suffix = (char *) (hs->path + vec_len (hs->path) - 1);
953 while (*suffix != '.')
957 if (!clib_strcmp (suffix, "css"))
959 else if (!clib_strcmp (suffix, "js"))
960 http_type = "javascript";
965 clib_warning ("BUG: hs->data not set for session %d",
972 * Send an http response, which needs the current time,
973 * the expiration time, and the data length
975 now = clib_timebase_now (&hsm->timebase);
976 http_response = format (0, http_response_template,
978 format_clib_timebase_time, now,
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))
985 clib_warning ("BUG: couldn't send response header!");
989 vec_free (http_response);
991 /* Send data from the beginning... */
993 hs->session_state = HTTP_STATE_SEND_MORE_DATA;
997 static void *state_funcs[HTTP_STATE_N_STATES] = {
999 /* Waiting for GET, POST, etc. */
1003 /* Send more data */
1004 state_send_more_data,
1008 http_static_server_rx_tx_callback (session_t * s,
1009 state_machine_called_from_t cf)
1012 int (*fp) (session_t *, http_session_t *, state_machine_called_from_t);
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);
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 ();
1029 fp = state_funcs[hs->session_state];
1030 rv = (*fp) (s, hs, cf);
1034 http_static_server_sessions_reader_unlock ();
1039 http_static_server_rx_callback (session_t * s)
1041 return http_static_server_rx_tx_callback (s, CALLED_FROM_RX);
1045 http_static_server_tx_callback (session_t * s)
1047 return http_static_server_rx_tx_callback (s, CALLED_FROM_TX);
1051 /** \brief Session accept callback
1055 http_static_server_session_accept_callback (session_t * s)
1057 http_static_server_main_t *hsm = &http_static_server_main;
1060 hsm->vpp_queue[s->thread_index] =
1061 session_main_get_vpp_event_queue (s->thread_index);
1063 http_static_server_sessions_writer_lock ();
1065 hs = http_static_server_session_alloc (s->thread_index);
1066 http_static_server_session_lookup_add (s->thread_index, s->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);
1075 http_static_server_sessions_writer_unlock ();
1077 s->session_state = SESSION_STATE_READY;
1081 /** \brief Session disconnect callback
1085 http_static_server_session_disconnect_callback (session_t * s)
1087 http_static_server_main_t *hsm = &http_static_server_main;
1088 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1091 http_static_server_sessions_writer_lock ();
1093 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1094 http_static_server_session_cleanup (hs);
1096 http_static_server_sessions_writer_unlock ();
1098 a->handle = session_handle (s);
1099 a->app_index = hsm->app_index;
1100 vnet_disconnect_session (a);
1103 /** \brief Session reset callback
1107 http_static_server_session_reset_callback (session_t * s)
1109 http_static_server_main_t *hsm = &http_static_server_main;
1110 vnet_disconnect_args_t _a = { 0 }, *a = &_a;
1113 http_static_server_sessions_writer_lock ();
1115 hs = http_static_server_session_lookup (s->thread_index, s->session_index);
1116 http_static_server_session_cleanup (hs);
1118 http_static_server_sessions_writer_unlock ();
1120 a->handle = session_handle (s);
1121 a->app_index = hsm->app_index;
1122 vnet_disconnect_session (a);
1126 http_static_server_session_connected_callback (u32 app_index, u32 api_context,
1127 session_t * s, u8 is_fail)
1129 clib_warning ("called...");
1134 http_static_server_add_segment_callback (u32 client_index, u64 segment_handle)
1136 clib_warning ("called...");
1140 /** \brief Session-layer virtual function table
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
1154 http_static_server_attach ()
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;
1163 clib_memset (a, 0, sizeof (*a));
1164 clib_memset (options, 0, sizeof (options));
1166 if (hsm->private_segment_size)
1167 segment_size = hsm->private_segment_size;
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;
1182 if (vnet_application_attach (a))
1185 clib_warning ("failed to attach server");
1189 hsm->app_index = a->app_index;
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);
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);
1207 http_static_server_listen ()
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";
1215 a->uri = (char *) hsm->uri;
1216 return vnet_bind_uri (a);
1220 http_static_server_session_cleanup_cb (void *hs_handlep)
1224 hs_handle = pointer_to_uword (hs_handlep);
1226 http_static_server_session_get (hs_handle >> 24, hs_handle & 0x00FFFFFF);
1229 hs->timer_handle = ~0;
1230 http_static_server_session_disconnect (hs);
1231 http_static_server_session_cleanup (hs);
1234 /** \brief Expired session timer-wheel callback
1237 http_expired_timers_dispatch (u32 * expired_timers)
1242 for (i = 0; i < vec_len (expired_timers); i++)
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 *));
1252 /** \brief Timer-wheel expiration process
1255 http_static_server_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
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;
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);
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);
1274 vec_reset_length (event_data);
1280 VLIB_REGISTER_NODE (http_static_server_process_node) =
1282 .function = http_static_server_process,
1283 .type = VLIB_NODE_TYPE_PROCESS,
1284 .name = "static-http-server-process",
1285 .state = VLIB_NODE_STATE_DISABLED,
1290 http_static_server_create (vlib_main_t * vm)
1292 vlib_thread_main_t *vtm = vlib_get_thread_main ();
1293 http_static_server_main_t *hsm = &http_static_server_main;
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);
1302 clib_rwlock_init (&hsm->sessions_lock);
1303 clib_spinlock_init (&hsm->tw_lock);
1305 if (http_static_server_attach ())
1307 clib_warning ("failed to attach server");
1310 if (http_static_server_listen ())
1312 clib_warning ("failed to start listening");
1316 /* Init path-to-cache hash table */
1317 BV (clib_bihash_init) (&hsm->name_to_data, "http cache", 128, 32 << 20);
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);
1330 /** \brief API helper function for vl_api_http_static_enable_t messages
1333 http_static_server_enable_api (u32 fifo_size, u32 cache_limit,
1335 u32 private_segment_size,
1336 u8 * www_root, u8 * uri)
1338 http_static_server_main_t *hsm = &http_static_server_main;
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);
1348 if (vec_len (hsm->www_root) < 2)
1349 return VNET_API_ERROR_INVALID_VALUE;
1351 if (hsm->my_client_index != ~0)
1352 return VNET_API_ERROR_APP_ALREADY_ATTACHED;
1354 vnet_session_enable_disable (hsm->vlib_main, 1 /* turn on TCP, etc. */ );
1356 rv = http_static_server_create (hsm->vlib_main);
1362 vec_free (hsm->www_root);
1363 vec_free (hsm->uri);
1364 return VNET_API_ERROR_INIT_FAILED;
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)
1374 http_static_server_main_t *hsm = &http_static_server_main;
1375 unformat_input_t _line_input, *line_input = &_line_input;
1380 hsm->prealloc_fifos = 0;
1381 hsm->private_segment_size = 0;
1383 /* 10mb cache limit, before LRU occurs */
1384 hsm->cache_limit = 10 << 20;
1386 /* Get a line of input. */
1387 if (!unformat_user (input, unformat_line_input, line_input))
1390 while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1392 if (unformat (line_input, "www-root %s", &www_root))
1395 if (unformat (line_input, "prealloc-fifos %d", &hsm->prealloc_fifos))
1397 else if (unformat (line_input, "private-segment-size %U",
1398 unformat_memory_size, &seg_size))
1400 if (seg_size >= 0x100000000ULL)
1402 vlib_cli_output (vm, "private segment size %llu, too large",
1406 hsm->private_segment_size = seg_size;
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,
1413 if (hsm->cache_limit < (128 << 10))
1415 return clib_error_return (0,
1416 "cache-size must be at least 128kb");
1420 else if (unformat (line_input, "uri %s", &hsm->uri))
1423 return clib_error_return (0, "unknown input `%U'",
1424 format_unformat_error, line_input);
1426 unformat_free (line_input);
1431 return clib_error_return (0, "Must specify www-root <path>");
1434 if (hsm->my_client_index != (u32) ~ 0)
1436 vec_free (www_root);
1437 return clib_error_return (0, "http server already running...");
1440 hsm->www_root = www_root;
1442 vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
1444 rv = http_static_server_create (vm);
1450 vec_free (hsm->www_root);
1451 return clib_error_return (0, "server_create returned %d", rv);
1457 * Enable the static http server
1460 * This command enables the static http server. Only the www-root
1461 * parameter is required
1463 * http static server www-root /tmp/www uri tcp://0.0.0.0/80 cache-size 2m
1465 * @cliexcmd{http static server www-root <path> [prealloc-fios <nn>]
1466 * [private-segment-size <nnMG>] [fifo-size <nbytes>] [uri <uri>]}
1469 VLIB_CLI_COMMAND (http_static_server_create_command, static) =
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,
1478 /** \brief format a file cache entry
1481 format_hsm_cache_entry (u8 * s, va_list * args)
1483 file_data_cache_t *ep = va_arg (*args, file_data_cache_t *);
1484 f64 now = va_arg (*args, f64);
1489 s = format (s, "%40s%12s%20s", "File", "Size", "Age");
1492 s = format (s, "%40s%12lld%20.2f", ep->filename, vec_len (ep->data),
1493 now - ep->last_used);
1498 format_http_session_state (u8 * s, va_list * args)
1500 http_session_state_t state = va_arg (*args, http_session_state_t);
1501 char *state_string = "bogus!";
1505 case HTTP_STATE_CLOSED:
1506 state_string = "closed";
1508 case HTTP_STATE_ESTABLISHED:
1509 state_string = "established";
1511 case HTTP_STATE_OK_SENT:
1512 state_string = "ok sent";
1514 case HTTP_STATE_SEND_MORE_DATA:
1515 state_string = "send more data";
1521 return format (s, "%s", state_string);
1525 format_http_session (u8 * s, va_list * args)
1527 http_session_t *hs = va_arg (*args, http_session_t *);
1528 int verbose = va_arg (*args, int);
1530 s = format (s, "[%d]: state %U", hs->session_index,
1531 format_http_session_state, hs->session_state);
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);
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)
1546 http_static_server_main_t *hsm = &http_static_server_main;
1547 file_data_cache_t *ep, **entries = 0;
1550 int show_sessions = 0;
1554 if (hsm->www_root == 0)
1555 return clib_error_return (0, "Static server disabled");
1557 while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1559 if (unformat (input, "verbose %d", &verbose))
1561 else if (unformat (input, "verbose"))
1563 else if (unformat (input, "cache"))
1565 else if (unformat (input, "sessions"))
1571 if ((show_cache + show_sessions) == 0)
1572 return clib_error_return (0, "specify one or more of cache, sessions");
1579 (vm, "www_root %s, cache size %lld bytes, limit %lld bytes, "
1581 hsm->www_root, hsm->cache_size, hsm->cache_limit,
1582 hsm->cache_evictions);
1586 now = vlib_time_now (vm);
1588 vlib_cli_output (vm, "%U", format_hsm_cache_entry, 0 /* header */ ,
1591 for (index = hsm->first_index; index != ~0;)
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);
1598 vlib_cli_output (vm, "%40s%12lld", "Total Size", hsm->cache_size);
1605 u32 *session_indices = 0;
1609 http_static_server_sessions_reader_lock ();
1611 for (i = 0; i < vec_len (hsm->sessions); i++)
1614 pool_foreach (hs, hsm->sessions[i],
1616 vec_add1 (session_indices, hs - hsm->sessions[i]);
1620 for (j = 0; j < vec_len (session_indices); j++)
1622 vlib_cli_output (vm, "%U", format_http_session,
1624 (hsm->sessions[i], session_indices[j]),
1627 vec_reset_length (session_indices);
1629 http_static_server_sessions_reader_unlock ();
1630 vec_free (session_indices);
1636 * Display static http server cache statistics
1639 * This command shows the contents of the static http server cache
1641 * show http static server
1643 * @cliexcmd{show http static server [verbose]}
1646 VLIB_CLI_COMMAND (http_show_static_server_command, static) =
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,
1654 static clib_error_t *
1655 http_static_server_main_init (vlib_main_t * vm)
1657 http_static_server_main_t *hsm = &http_static_server_main;
1659 hsm->my_client_index = ~0;
1660 hsm->vlib_main = vm;
1661 hsm->first_index = hsm->last_index = ~0;
1663 clib_timebase_init (&hsm->timebase, 0 /* GMT */ ,
1664 CLIB_TIMEBASE_DAYLIGHT_NONE);
1669 VLIB_INIT_FUNCTION (http_static_server_main_init);
1672 * fd.io coding-style-patch-verification: ON
1675 * eval: (c-set-style "gnu")