ce4e09addbc418af5e4d850c3a9c97fffaa93901
[vpp.git] / src / plugins / hs_apps / http_server.c
1 /*
2 * Copyright (c) 2017-2019 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <vnet/vnet.h>
17 #include <vnet/session/application.h>
18 #include <vnet/session/application_interface.h>
19 #include <vnet/session/session.h>
20 #include <vppinfra/tw_timer_2t_1w_2048sl.h>
21
22 typedef enum
23 {
24   EVENT_WAKEUP = 1,
25 } http_process_event_t;
26
27 typedef struct
28 {
29   u32 hs_index;
30   u32 thread_index;
31   u64 node_index;
32 } http_server_args;
33
34 typedef enum
35 {
36   HTTP_STATE_CLOSED,
37   HTTP_STATE_ESTABLISHED,
38   HTTP_STATE_OK_SENT,
39 } http_session_state_t;
40 typedef struct
41 {
42   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
43 #define _(type, name) type name;
44   foreach_app_session_field
45 #undef _
46   u32 thread_index;
47   u8 *rx_buf;
48   u32 vpp_session_index;
49   u64 vpp_session_handle;
50   u32 timer_handle;
51 } http_session_t;
52
53 typedef struct
54 {
55   http_session_t **sessions;
56   clib_rwlock_t sessions_lock;
57   u32 **session_to_http_session;
58
59   svm_msg_q_t **vpp_queue;
60
61   uword *handler_by_get_request;
62
63   u32 *free_http_cli_process_node_indices;
64
65   /* Sever's event queue */
66   svm_queue_t *vl_input_queue;
67
68   /* API client handle */
69   u32 my_client_index;
70
71   u32 app_index;
72
73   /* process node index for evnt scheduling */
74   u32 node_index;
75
76   tw_timer_wheel_2t_1w_2048sl_t tw;
77   clib_spinlock_t tw_lock;
78
79   u32 prealloc_fifos;
80   u32 private_segment_size;
81   u32 fifo_size;
82   u8 *uri;
83   u32 is_static;
84   vlib_main_t *vlib_main;
85 } http_server_main_t;
86
87 http_server_main_t http_server_main;
88
89 static void
90 http_server_sessions_reader_lock (void)
91 {
92   clib_rwlock_reader_lock (&http_server_main.sessions_lock);
93 }
94
95 static void
96 http_server_sessions_reader_unlock (void)
97 {
98   clib_rwlock_reader_unlock (&http_server_main.sessions_lock);
99 }
100
101 static void
102 http_server_sessions_writer_lock (void)
103 {
104   clib_rwlock_writer_lock (&http_server_main.sessions_lock);
105 }
106
107 static void
108 http_server_sessions_writer_unlock (void)
109 {
110   clib_rwlock_writer_unlock (&http_server_main.sessions_lock);
111 }
112
113 static http_session_t *
114 http_server_session_alloc (u32 thread_index)
115 {
116   http_server_main_t *hsm = &http_server_main;
117   http_session_t *hs;
118   pool_get (hsm->sessions[thread_index], hs);
119   memset (hs, 0, sizeof (*hs));
120   hs->session_index = hs - hsm->sessions[thread_index];
121   hs->thread_index = thread_index;
122   hs->timer_handle = ~0;
123   return hs;
124 }
125
126 static http_session_t *
127 http_server_session_get (u32 thread_index, u32 hs_index)
128 {
129   http_server_main_t *hsm = &http_server_main;
130   if (pool_is_free_index (hsm->sessions[thread_index], hs_index))
131     return 0;
132   return pool_elt_at_index (hsm->sessions[thread_index], hs_index);
133 }
134
135 static void
136 http_server_session_free (http_session_t * hs)
137 {
138   http_server_main_t *hsm = &http_server_main;
139   u32 thread = hs->thread_index;
140   if (CLIB_DEBUG)
141     memset (hs, 0xfa, sizeof (*hs));
142   pool_put (hsm->sessions[thread], hs);
143 }
144
145 static void
146 http_server_session_lookup_add (u32 thread_index, u32 s_index, u32 hs_index)
147 {
148   http_server_main_t *hsm = &http_server_main;
149   vec_validate (hsm->session_to_http_session[thread_index], s_index);
150   hsm->session_to_http_session[thread_index][s_index] = hs_index;
151 }
152
153 static void
154 http_server_session_lookup_del (u32 thread_index, u32 s_index)
155 {
156   http_server_main_t *hsm = &http_server_main;
157   hsm->session_to_http_session[thread_index][s_index] = ~0;
158 }
159
160 static http_session_t *
161 http_server_session_lookup (u32 thread_index, u32 s_index)
162 {
163   http_server_main_t *hsm = &http_server_main;
164   u32 hs_index;
165
166   if (s_index < vec_len (hsm->session_to_http_session[thread_index]))
167     {
168       hs_index = hsm->session_to_http_session[thread_index][s_index];
169       return http_server_session_get (thread_index, hs_index);
170     }
171   return 0;
172 }
173
174
175 static void
176 http_server_session_timer_start (http_session_t * hs)
177 {
178   u32 hs_handle;
179   hs_handle = hs->thread_index << 24 | hs->session_index;
180   clib_spinlock_lock (&http_server_main.tw_lock);
181   hs->timer_handle = tw_timer_start_2t_1w_2048sl (&http_server_main.tw,
182                                                   hs_handle, 0, 60);
183   clib_spinlock_unlock (&http_server_main.tw_lock);
184 }
185
186 static void
187 http_server_session_timer_stop (http_session_t * hs)
188 {
189   if (hs->timer_handle == ~0)
190     return;
191   clib_spinlock_lock (&http_server_main.tw_lock);
192   tw_timer_stop_2t_1w_2048sl (&http_server_main.tw, hs->timer_handle);
193   clib_spinlock_unlock (&http_server_main.tw_lock);
194 }
195
196 static void
197 http_server_session_disconnect (http_session_t * hs)
198 {
199   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
200   a->handle = hs->vpp_session_handle;
201   a->app_index = http_server_main.app_index;
202   vnet_disconnect_session (a);
203 }
204
205 static void
206 http_process_free (http_server_args * args)
207 {
208   vlib_node_runtime_t *rt;
209   vlib_main_t *vm = &vlib_global_main;
210   http_server_main_t *hsm = &http_server_main;
211   vlib_node_t *n;
212   u32 node_index;
213   http_server_args **save_args;
214
215   node_index = args->node_index;
216   ASSERT (node_index != 0);
217
218   n = vlib_get_node (vm, node_index);
219   rt = vlib_node_get_runtime (vm, n->index);
220   save_args = vlib_node_get_runtime_data (vm, n->index);
221
222   /* Reset process session pointer */
223   clib_mem_free (*save_args);
224   *save_args = 0;
225
226   /* Turn off the process node */
227   vlib_node_set_state (vm, rt->node_index, VLIB_NODE_STATE_DISABLED);
228
229   /* add node index to the freelist */
230   vec_add1 (hsm->free_http_cli_process_node_indices, node_index);
231 }
232
233 /* *INDENT-OFF* */
234 static const char *http_ok =
235     "HTTP/1.1 200 OK\r\n";
236
237 static const char *http_response =
238     "Content-Type: text/html\r\n"
239     "Expires: Mon, 11 Jan 1970 10:10:10 GMT\r\n"
240     "Connection: close \r\n"
241     "Pragma: no-cache\r\n"
242     "Content-Length: %d\r\n\r\n%v";
243
244 static const char *http_error_template =
245     "HTTP/1.1 %s\r\n"
246     "Content-Type: text/html\r\n"
247     "Expires: Mon, 11 Jan 1970 10:10:10 GMT\r\n"
248     "Connection: close\r\n"
249     "Pragma: no-cache\r\n"
250     "Content-Length: 0\r\n\r\n";
251
252 /* Header, including incantation to suppress favicon.ico requests */
253 static const char *html_header_template =
254     "<html><head><title>%v</title></head>"
255     "<link rel=\"icon\" href=\"data:,\">"
256     "<body><pre>";
257
258 static const char *html_footer =
259     "</pre></body></html>\r\n";
260
261 static const char *html_header_static =
262     "<html><head><title>static reply</title></head>"
263     "<link rel=\"icon\" href=\"data:,\">"
264     "<body><pre>hello</pre></body></html>\r\n";
265 /* *INDENT-ON* */
266
267 static u8 *static_http;
268 static u8 *static_ok;
269
270 static void
271 http_cli_output (uword arg, u8 * buffer, uword buffer_bytes)
272 {
273   u8 **output_vecp = (u8 **) arg;
274   u8 *output_vec;
275   u32 offset;
276
277   output_vec = *output_vecp;
278
279   offset = vec_len (output_vec);
280   vec_validate (output_vec, offset + buffer_bytes - 1);
281   clib_memcpy_fast (output_vec + offset, buffer, buffer_bytes);
282
283   *output_vecp = output_vec;
284 }
285
286 void
287 send_data (http_session_t * hs, u8 * data)
288 {
289   http_server_main_t *hsm = &http_server_main;
290   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
291   vlib_main_t *vm = vlib_get_main ();
292   f64 last_sent_timer = vlib_time_now (vm);
293   u32 offset, bytes_to_send;
294   f64 delay = 10e-3;
295
296   bytes_to_send = vec_len (data);
297   offset = 0;
298
299   while (bytes_to_send > 0)
300     {
301       int actual_transfer;
302
303       actual_transfer = svm_fifo_enqueue
304         (hs->tx_fifo, bytes_to_send, data + offset);
305
306       /* Made any progress? */
307       if (actual_transfer <= 0)
308         {
309           http_server_sessions_reader_unlock ();
310           vlib_process_suspend (vm, delay);
311           http_server_sessions_reader_lock ();
312
313           /* 10s deadman timer */
314           if (vlib_time_now (vm) > last_sent_timer + 10.0)
315             {
316               a->handle = hs->vpp_session_handle;
317               a->app_index = hsm->app_index;
318               vnet_disconnect_session (a);
319               break;
320             }
321           /* Exponential backoff, within reason */
322           if (delay < 1.0)
323             delay = delay * 2.0;
324         }
325       else
326         {
327           last_sent_timer = vlib_time_now (vm);
328           offset += actual_transfer;
329           bytes_to_send -= actual_transfer;
330
331           if (svm_fifo_set_event (hs->tx_fifo))
332             session_send_io_evt_to_thread (hs->tx_fifo,
333                                            SESSION_IO_EVT_TX_FLUSH);
334           delay = 10e-3;
335         }
336     }
337 }
338
339 static void
340 send_error (http_session_t * hs, char *str)
341 {
342   u8 *data;
343
344   data = format (0, http_error_template, str);
345   send_data (hs, data);
346   vec_free (data);
347 }
348
349 static uword
350 http_cli_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
351                   vlib_frame_t * f)
352 {
353   u8 *request = 0, *reply = 0, *http = 0, *html = 0;
354   http_server_main_t *hsm = &http_server_main;
355   http_server_args **save_args;
356   http_server_args *args;
357   unformat_input_t input;
358   http_session_t *hs;
359   int i;
360
361   save_args = vlib_node_get_runtime_data (hsm->vlib_main, rt->node_index);
362   args = *save_args;
363
364   http_server_sessions_reader_lock ();
365
366   hs = http_server_session_get (args->thread_index, args->hs_index);
367   ASSERT (hs);
368
369   request = hs->rx_buf;
370   if (vec_len (request) < 7)
371     {
372       send_error (hs, "400 Bad Request");
373       goto out;
374     }
375
376   for (i = 0; i < vec_len (request) - 4; i++)
377     {
378       if (request[i] == 'G' &&
379           request[i + 1] == 'E' &&
380           request[i + 2] == 'T' && request[i + 3] == ' ')
381         goto found;
382     }
383 bad_request:
384   send_error (hs, "400 Bad Request");
385   goto out;
386
387 found:
388   /* Lose "GET " */
389   vec_delete (request, i + 5, 0);
390
391   /* Replace slashes with spaces, stop at the end of the path */
392   i = 0;
393   while (1)
394     {
395       if (request[i] == '/')
396         request[i] = ' ';
397       else if (request[i] == ' ')
398         {
399           /* vlib_cli_input is vector-based, no need for a NULL */
400           _vec_len (request) = i;
401           break;
402         }
403       i++;
404       /* Should never happen */
405       if (i == vec_len (request))
406         goto bad_request;
407     }
408
409   /* Generate the html header */
410   html = format (0, html_header_template, request /* title */ );
411
412   /* Run the command */
413   unformat_init_vector (&input, vec_dup (request));
414   vlib_cli_input (vm, &input, http_cli_output, (uword) & reply);
415   unformat_free (&input);
416   request = 0;
417
418   /* Generate the html page */
419   html = format (html, "%v", reply);
420   html = format (html, html_footer);
421   /* And the http reply */
422   http = format (0, http_ok);
423   http = format (http, http_response, vec_len (html), html);
424
425   /* Send it */
426   send_data (hs, http);
427
428 out:
429   /* Cleanup */
430   http_server_sessions_reader_unlock ();
431   vec_free (reply);
432   vec_free (html);
433   vec_free (http);
434
435   http_process_free (args);
436   return (0);
437 }
438
439 static void
440 alloc_http_process (http_server_args * args)
441 {
442   char *name;
443   vlib_node_t *n;
444   http_server_main_t *hsm = &http_server_main;
445   vlib_main_t *vm = hsm->vlib_main;
446   uword l = vec_len (hsm->free_http_cli_process_node_indices);
447   http_server_args **save_args;
448
449   if (vec_len (hsm->free_http_cli_process_node_indices) > 0)
450     {
451       n = vlib_get_node (vm, hsm->free_http_cli_process_node_indices[l - 1]);
452       vlib_node_set_state (vm, n->index, VLIB_NODE_STATE_POLLING);
453       _vec_len (hsm->free_http_cli_process_node_indices) = l - 1;
454     }
455   else
456     {
457       static vlib_node_registration_t r = {
458         .function = http_cli_process,
459         .type = VLIB_NODE_TYPE_PROCESS,
460         .process_log2_n_stack_bytes = 16,
461         .runtime_data_bytes = sizeof (void *),
462       };
463
464       name = (char *) format (0, "http-cli-%d", l);
465       r.name = name;
466       vlib_register_node (vm, &r);
467       vec_free (name);
468
469       n = vlib_get_node (vm, r.index);
470     }
471
472   /* Save the node index in the args. It won't be zero. */
473   args->node_index = n->index;
474
475   /* Save the args (pointer) in the node runtime */
476   save_args = vlib_node_get_runtime_data (vm, n->index);
477   *save_args = clib_mem_alloc (sizeof (*args));
478   clib_memcpy_fast (*save_args, args, sizeof (*args));
479
480   vlib_start_process (vm, n->runtime_index);
481 }
482
483 static void
484 alloc_http_process_callback (void *cb_args)
485 {
486   alloc_http_process ((http_server_args *) cb_args);
487 }
488
489 static int
490 session_rx_request (http_session_t * hs)
491 {
492   u32 max_dequeue, cursize;
493   int n_read;
494
495   cursize = vec_len (hs->rx_buf);
496   max_dequeue = svm_fifo_max_dequeue_cons (hs->rx_fifo);
497   if (PREDICT_FALSE (max_dequeue == 0))
498     return -1;
499
500   vec_validate (hs->rx_buf, cursize + max_dequeue - 1);
501   n_read = app_recv_stream_raw (hs->rx_fifo, hs->rx_buf + cursize,
502                                 max_dequeue, 0, 0 /* peek */ );
503   ASSERT (n_read == max_dequeue);
504   if (svm_fifo_is_empty_cons (hs->rx_fifo))
505     svm_fifo_unset_event (hs->rx_fifo);
506
507   _vec_len (hs->rx_buf) = cursize + n_read;
508   return 0;
509 }
510
511 static int
512 http_server_rx_callback (session_t * s)
513 {
514   http_server_args args;
515   http_session_t *hs;
516   int rv;
517
518   http_server_sessions_reader_lock ();
519
520   hs = http_server_session_lookup (s->thread_index, s->session_index);
521   if (!hs || hs->session_state != HTTP_STATE_ESTABLISHED)
522     return -1;
523
524   rv = session_rx_request (hs);
525   if (rv)
526     return rv;
527
528   /* send the command to a new/recycled vlib process */
529   args.hs_index = hs->session_index;
530   args.thread_index = hs->thread_index;
531
532   http_server_sessions_reader_unlock ();
533
534   /* Send RPC request to main thread */
535   if (vlib_get_thread_index () != 0)
536     vlib_rpc_call_main_thread (alloc_http_process_callback, (u8 *) & args,
537                                sizeof (args));
538   else
539     alloc_http_process (&args);
540   return 0;
541 }
542
543 static int
544 http_server_rx_callback_static (session_t * s)
545 {
546   http_session_t *hs;
547   u32 request_len;
548   u8 *request = 0;
549   int i, rv;
550
551   hs = http_server_session_lookup (s->thread_index, s->session_index);
552   if (!hs || hs->session_state == HTTP_STATE_CLOSED)
553     return 0;
554
555   /* ok 200 was sent */
556   if (hs->session_state == HTTP_STATE_OK_SENT)
557     goto send_data;
558
559   rv = session_rx_request (hs);
560   if (rv)
561     goto wait_for_data;
562
563   request = hs->rx_buf;
564   request_len = vec_len (request);
565   if (vec_len (request) < 7)
566     {
567       send_error (hs, "400 Bad Request");
568       goto close_session;
569     }
570
571   for (i = 0; i < request_len - 4; i++)
572     {
573       if (request[i] == 'G' &&
574           request[i + 1] == 'E' &&
575           request[i + 2] == 'T' && request[i + 3] == ' ')
576         goto find_end;
577     }
578   send_error (hs, "400 Bad Request");
579   goto close_session;
580
581 find_end:
582
583   /* check for the end sequence: /r/n/r/n */
584   if (request[request_len - 1] != 0xa || request[request_len - 3] != 0xa
585       || request[request_len - 2] != 0xd || request[request_len - 4] != 0xd)
586     goto wait_for_data;
587
588   /* send 200 OK first */
589   send_data (hs, static_ok);
590   hs->session_state = HTTP_STATE_OK_SENT;
591   goto postpone;
592
593 send_data:
594   send_data (hs, static_http);
595
596 close_session:
597   http_server_session_disconnect (hs);
598   return 0;
599
600 postpone:
601   (void) svm_fifo_set_event (hs->rx_fifo);
602   session_send_io_evt_to_thread (hs->rx_fifo, SESSION_IO_EVT_BUILTIN_RX);
603   return 0;
604
605 wait_for_data:
606   return 0;
607 }
608
609 static int
610 http_server_session_accept_callback (session_t * s)
611 {
612   http_server_main_t *hsm = &http_server_main;
613   http_session_t *hs;
614
615   hsm->vpp_queue[s->thread_index] =
616     session_main_get_vpp_event_queue (s->thread_index);
617
618   if (!hsm->is_static)
619     http_server_sessions_writer_lock ();
620
621   hs = http_server_session_alloc (s->thread_index);
622   http_server_session_lookup_add (s->thread_index, s->session_index,
623                                   hs->session_index);
624   hs->rx_fifo = s->rx_fifo;
625   hs->tx_fifo = s->tx_fifo;
626   hs->vpp_session_index = s->session_index;
627   hs->vpp_session_handle = session_handle (s);
628   hs->session_state = HTTP_STATE_ESTABLISHED;
629   http_server_session_timer_start (hs);
630
631   if (!hsm->is_static)
632     http_server_sessions_writer_unlock ();
633
634   s->session_state = SESSION_STATE_READY;
635   return 0;
636 }
637
638 static void
639 http_server_session_disconnect_callback (session_t * s)
640 {
641   http_server_main_t *hsm = &http_server_main;
642   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
643
644   a->handle = session_handle (s);
645   a->app_index = hsm->app_index;
646   vnet_disconnect_session (a);
647 }
648
649 static void
650 http_server_session_reset_callback (session_t * s)
651 {
652   http_server_main_t *hsm = &http_server_main;
653   vnet_disconnect_args_t _a = { 0 }, *a = &_a;
654
655   a->handle = session_handle (s);
656   a->app_index = hsm->app_index;
657   vnet_disconnect_session (a);
658 }
659
660 static int
661 http_server_session_connected_callback (u32 app_index, u32 api_context,
662                                         session_t * s, session_error_t err)
663 {
664   clib_warning ("called...");
665   return -1;
666 }
667
668 static int
669 http_server_add_segment_callback (u32 client_index, u64 segment_handle)
670 {
671   clib_warning ("called...");
672   return -1;
673 }
674
675 static void
676 http_server_cleanup_callback (session_t * s, session_cleanup_ntf_t ntf)
677 {
678   http_server_main_t *hsm = &http_server_main;
679   http_session_t *hs;
680
681   if (ntf == SESSION_CLEANUP_TRANSPORT)
682     return;
683
684   if (!hsm->is_static)
685     http_server_sessions_writer_lock ();
686
687   hs = http_server_session_lookup (s->thread_index, s->session_index);
688   if (!hs)
689     goto done;
690
691   http_server_session_lookup_del (hs->thread_index, hs->vpp_session_index);
692   vec_free (hs->rx_buf);
693   http_server_session_timer_stop (hs);
694   http_server_session_free (hs);
695
696 done:
697
698   if (!hsm->is_static)
699     http_server_sessions_writer_unlock ();
700 }
701
702 static session_cb_vft_t http_server_session_cb_vft = {
703   .session_accept_callback = http_server_session_accept_callback,
704   .session_disconnect_callback = http_server_session_disconnect_callback,
705   .session_connected_callback = http_server_session_connected_callback,
706   .add_segment_callback = http_server_add_segment_callback,
707   .builtin_app_rx_callback = http_server_rx_callback,
708   .session_reset_callback = http_server_session_reset_callback,
709   .session_cleanup_callback = http_server_cleanup_callback,
710 };
711
712 static int
713 http_server_attach ()
714 {
715   vnet_app_add_tls_cert_args_t _a_cert, *a_cert = &_a_cert;
716   vnet_app_add_tls_key_args_t _a_key, *a_key = &_a_key;
717   http_server_main_t *hsm = &http_server_main;
718   u64 options[APP_OPTIONS_N_OPTIONS];
719   vnet_app_attach_args_t _a, *a = &_a;
720   u32 segment_size = 128 << 20;
721
722   clib_memset (a, 0, sizeof (*a));
723   clib_memset (options, 0, sizeof (options));
724
725   if (hsm->private_segment_size)
726     segment_size = hsm->private_segment_size;
727
728   a->api_client_index = ~0;
729   a->name = format (0, "test_http_server");
730   a->session_cb_vft = &http_server_session_cb_vft;
731   a->options = options;
732   a->options[APP_OPTIONS_SEGMENT_SIZE] = segment_size;
733   a->options[APP_OPTIONS_RX_FIFO_SIZE] =
734     hsm->fifo_size ? hsm->fifo_size : 8 << 10;
735   a->options[APP_OPTIONS_TX_FIFO_SIZE] =
736     hsm->fifo_size ? hsm->fifo_size : 32 << 10;
737   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
738   a->options[APP_OPTIONS_PREALLOC_FIFO_PAIRS] = hsm->prealloc_fifos;
739
740   if (vnet_application_attach (a))
741     {
742       vec_free (a->name);
743       clib_warning ("failed to attach server");
744       return -1;
745     }
746   vec_free (a->name);
747   hsm->app_index = a->app_index;
748
749   clib_memset (a_cert, 0, sizeof (*a_cert));
750   a_cert->app_index = a->app_index;
751   vec_validate (a_cert->cert, test_srv_crt_rsa_len);
752   clib_memcpy_fast (a_cert->cert, test_srv_crt_rsa, test_srv_crt_rsa_len);
753   vnet_app_add_tls_cert (a_cert);
754
755   clib_memset (a_key, 0, sizeof (*a_key));
756   a_key->app_index = a->app_index;
757   vec_validate (a_key->key, test_srv_key_rsa_len);
758   clib_memcpy_fast (a_key->key, test_srv_key_rsa, test_srv_key_rsa_len);
759   vnet_app_add_tls_key (a_key);
760
761   return 0;
762 }
763
764 static int
765 http_server_listen ()
766 {
767   http_server_main_t *hsm = &http_server_main;
768   vnet_listen_args_t _a, *a = &_a;
769   clib_memset (a, 0, sizeof (*a));
770   a->app_index = hsm->app_index;
771   a->uri = "tcp://0.0.0.0/80";
772   if (hsm->uri)
773     a->uri = (char *) hsm->uri;
774   return vnet_bind_uri (a);
775 }
776
777 static void
778 http_server_session_close_cb (void *hs_handlep)
779 {
780   http_session_t *hs;
781   uword hs_handle;
782   hs_handle = pointer_to_uword (hs_handlep);
783   hs = http_server_session_get (hs_handle >> 24, hs_handle & 0x00FFFFFF);
784   if (!hs)
785     return;
786   hs->timer_handle = ~0;
787   http_server_session_disconnect (hs);
788 }
789
790 static void
791 http_expired_timers_dispatch (u32 * expired_timers)
792 {
793   u32 hs_handle;
794   int i;
795
796   for (i = 0; i < vec_len (expired_timers); i++)
797     {
798       /* Get session handle. The first bit is the timer id */
799       hs_handle = expired_timers[i] & 0x7FFFFFFF;
800       session_send_rpc_evt_to_thread (hs_handle >> 24,
801                                       http_server_session_close_cb,
802                                       uword_to_pointer (hs_handle, void *));
803     }
804 }
805
806 static uword
807 http_server_process (vlib_main_t * vm, vlib_node_runtime_t * rt,
808                      vlib_frame_t * f)
809 {
810   http_server_main_t *hsm = &http_server_main;
811   f64 now, timeout = 1.0;
812   uword *event_data = 0;
813   uword __clib_unused event_type;
814
815   while (1)
816     {
817       vlib_process_wait_for_event_or_clock (vm, timeout);
818       now = vlib_time_now (vm);
819       event_type = vlib_process_get_events (vm, (uword **) & event_data);
820
821       /* expire timers */
822       clib_spinlock_lock (&http_server_main.tw_lock);
823       tw_timer_expire_timers_2t_1w_2048sl (&hsm->tw, now);
824       clib_spinlock_unlock (&http_server_main.tw_lock);
825
826       vec_reset_length (event_data);
827     }
828   return 0;
829 }
830
831 /* *INDENT-OFF* */
832 VLIB_REGISTER_NODE (http_server_process_node) =
833 {
834   .function = http_server_process,
835   .type = VLIB_NODE_TYPE_PROCESS,
836   .name = "http-server-process",
837   .state = VLIB_NODE_STATE_DISABLED,
838 };
839 /* *INDENT-ON* */
840
841 static int
842 http_server_create (vlib_main_t * vm)
843 {
844   vlib_thread_main_t *vtm = vlib_get_thread_main ();
845   http_server_main_t *hsm = &http_server_main;
846   u32 num_threads;
847   vlib_node_t *n;
848
849   num_threads = 1 /* main thread */  + vtm->n_threads;
850   vec_validate (hsm->vpp_queue, num_threads - 1);
851   vec_validate (hsm->sessions, num_threads - 1);
852   vec_validate (hsm->session_to_http_session, num_threads - 1);
853
854   clib_rwlock_init (&hsm->sessions_lock);
855   clib_spinlock_init (&hsm->tw_lock);
856
857   if (http_server_attach ())
858     {
859       clib_warning ("failed to attach server");
860       return -1;
861     }
862   if (http_server_listen ())
863     {
864       clib_warning ("failed to start listening");
865       return -1;
866     }
867
868   /* Init timer wheel and process */
869   tw_timer_wheel_init_2t_1w_2048sl (&hsm->tw, http_expired_timers_dispatch,
870                                     1 /* timer interval */ , ~0);
871   vlib_node_set_state (vm, http_server_process_node.index,
872                        VLIB_NODE_STATE_POLLING);
873   n = vlib_get_node (vm, http_server_process_node.index);
874   vlib_start_process (vm, n->runtime_index);
875
876   return 0;
877 }
878
879 static clib_error_t *
880 http_server_create_command_fn (vlib_main_t * vm,
881                                unformat_input_t * input,
882                                vlib_cli_command_t * cmd)
883 {
884   http_server_main_t *hsm = &http_server_main;
885   unformat_input_t _line_input, *line_input = &_line_input;
886   u64 seg_size;
887   u8 *html;
888   int rv;
889
890   hsm->prealloc_fifos = 0;
891   hsm->private_segment_size = 0;
892   hsm->fifo_size = 0;
893   hsm->is_static = 0;
894
895   /* Get a line of input. */
896   if (!unformat_user (input, unformat_line_input, line_input))
897     goto start_server;
898
899   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
900     {
901       if (unformat (line_input, "static"))
902         hsm->is_static = 1;
903       else
904         if (unformat (line_input, "prealloc-fifos %d", &hsm->prealloc_fifos))
905         ;
906       else if (unformat (line_input, "private-segment-size %U",
907                          unformat_memory_size, &seg_size))
908         {
909           if (seg_size >= 0x100000000ULL)
910             {
911               vlib_cli_output (vm, "private segment size %llu, too large",
912                                seg_size);
913               return 0;
914             }
915           hsm->private_segment_size = seg_size;
916         }
917       else if (unformat (line_input, "fifo-size %d", &hsm->fifo_size))
918         hsm->fifo_size <<= 10;
919       else if (unformat (line_input, "uri %s", &hsm->uri))
920         ;
921       else
922         return clib_error_return (0, "unknown input `%U'",
923                                   format_unformat_error, line_input);
924     }
925   unformat_free (line_input);
926
927 start_server:
928
929   if (hsm->my_client_index != (u32) ~ 0)
930     return clib_error_return (0, "test http server is already running");
931
932   vnet_session_enable_disable (vm, 1 /* turn on TCP, etc. */ );
933
934   if (hsm->is_static)
935     {
936       http_server_session_cb_vft.builtin_app_rx_callback =
937         http_server_rx_callback_static;
938       html = format (0, html_header_static);
939       static_http = format (0, http_response, vec_len (html), html);
940       static_ok = format (0, http_ok);
941     }
942   rv = http_server_create (vm);
943   switch (rv)
944     {
945     case 0:
946       break;
947     default:
948       return clib_error_return (0, "server_create returned %d", rv);
949     }
950   return 0;
951 }
952
953 /* *INDENT-OFF* */
954 VLIB_CLI_COMMAND (http_server_create_command, static) =
955 {
956   .path = "test http server",
957   .short_help = "test http server",
958   .function = http_server_create_command_fn,
959 };
960 /* *INDENT-ON* */
961
962 static clib_error_t *
963 http_server_main_init (vlib_main_t * vm)
964 {
965   http_server_main_t *hsm = &http_server_main;
966
967   hsm->my_client_index = ~0;
968   hsm->vlib_main = vm;
969   return 0;
970 }
971
972 VLIB_INIT_FUNCTION (http_server_main_init);
973
974 /*
975 * fd.io coding-style-patch-verification: ON
976 *
977 * Local Variables:
978 * eval: (c-set-style "gnu")
979 * End:
980 */