http hsa: support multiple listeners for http tps
[vpp.git] / src / plugins / http / http.c
1 /*
2  * Copyright (c) 2022 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 <http/http.h>
17 #include <vnet/session/session.h>
18 #include <http/http_timer.h>
19
20 static http_main_t http_main;
21
22 #define HTTP_FIFO_THRESH (16 << 10)
23
24 const char *http_status_code_str[] = {
25 #define _(c, s, str) str,
26   foreach_http_status_code
27 #undef _
28 };
29
30 const char *http_content_type_str[] = {
31 #define _(s, str) str,
32   foreach_http_content_type
33 #undef _
34 };
35
36 const http_buffer_type_t msg_to_buf_type[] = {
37   [HTTP_MSG_DATA_INLINE] = HTTP_BUFFER_FIFO,
38   [HTTP_MSG_DATA_PTR] = HTTP_BUFFER_PTR,
39 };
40
41 static inline http_worker_t *
42 http_worker_get (u32 thread_index)
43 {
44   return &http_main.wrk[thread_index];
45 }
46
47 static inline u32
48 http_conn_alloc_w_thread (u32 thread_index)
49 {
50   http_worker_t *wrk = http_worker_get (thread_index);
51   http_conn_t *hc;
52
53   pool_get_zero (wrk->conn_pool, hc);
54   hc->c_thread_index = thread_index;
55   hc->h_hc_index = hc - wrk->conn_pool;
56   hc->h_pa_session_handle = SESSION_INVALID_HANDLE;
57   hc->h_tc_session_handle = SESSION_INVALID_HANDLE;
58   return hc->h_hc_index;
59 }
60
61 static inline http_conn_t *
62 http_conn_get_w_thread (u32 hc_index, u32 thread_index)
63 {
64   http_worker_t *wrk = http_worker_get (thread_index);
65   return pool_elt_at_index (wrk->conn_pool, hc_index);
66 }
67
68 void
69 http_conn_free (http_conn_t *hc)
70 {
71   http_worker_t *wrk = http_worker_get (hc->c_thread_index);
72   pool_put (wrk->conn_pool, hc);
73 }
74
75 static u32
76 http_listener_alloc (void)
77 {
78   http_main_t *hm = &http_main;
79   http_conn_t *lhc;
80
81   pool_get_zero (hm->listener_pool, lhc);
82   lhc->c_c_index = lhc - hm->listener_pool;
83   return lhc->c_c_index;
84 }
85
86 http_conn_t *
87 http_listener_get (u32 lhc_index)
88 {
89   return pool_elt_at_index (http_main.listener_pool, lhc_index);
90 }
91
92 void
93 http_listener_free (http_conn_t *lhc)
94 {
95   http_main_t *hm = &http_main;
96
97   if (CLIB_DEBUG)
98     memset (lhc, 0xfc, sizeof (*lhc));
99   pool_put (hm->listener_pool, lhc);
100 }
101
102 void
103 http_disconnect_transport (http_conn_t *hc)
104 {
105   vnet_disconnect_args_t a = {
106     .handle = hc->h_tc_session_handle,
107     .app_index = http_main.app_index,
108   };
109
110   hc->state = HTTP_CONN_STATE_CLOSED;
111
112   if (vnet_disconnect_session (&a))
113     clib_warning ("disconnect returned");
114 }
115
116 static void
117 http_conn_timeout_cb (void *hc_handlep)
118 {
119   http_conn_t *hc;
120   uword hs_handle;
121
122   hs_handle = pointer_to_uword (hc_handlep);
123   hc = http_conn_get_w_thread (hs_handle & 0x00FFFFFF, hs_handle >> 24);
124
125   HTTP_DBG (1, "terminate thread %d index %d hs %llx", hs_handle >> 24,
126             hs_handle & 0x00FFFFFF, hc);
127   if (!hc)
128     return;
129
130   hc->timer_handle = ~0;
131   session_transport_closing_notify (&hc->connection);
132   http_disconnect_transport (hc);
133 }
134
135 int
136 http_ts_accept_callback (session_t *ts)
137 {
138   session_t *ts_listener, *as, *asl;
139   app_worker_t *app_wrk;
140   http_conn_t *lhc, *hc;
141   u32 hc_index, thresh;
142   int rv;
143
144   ts_listener = listen_session_get_from_handle (ts->listener_handle);
145   lhc = http_listener_get (ts_listener->opaque);
146
147   hc_index = http_conn_alloc_w_thread (ts->thread_index);
148   hc = http_conn_get_w_thread (hc_index, ts->thread_index);
149   clib_memcpy_fast (hc, lhc, sizeof (*lhc));
150   hc->c_thread_index = vlib_get_thread_index ();
151   hc->h_hc_index = hc_index;
152
153   hc->h_tc_session_handle = session_handle (ts);
154   hc->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
155
156   hc->state = HTTP_CONN_STATE_ESTABLISHED;
157   hc->req_state = HTTP_REQ_STATE_WAIT_METHOD;
158
159   ts->session_state = SESSION_STATE_READY;
160   ts->opaque = hc_index;
161
162   /*
163    * Alloc session and initialize
164    */
165   as = session_alloc (hc->c_thread_index);
166   as->session_state = SESSION_STATE_CREATED;
167   hc->c_s_index = as->session_index;
168
169   as->app_wrk_index = hc->h_pa_wrk_index;
170   as->connection_index = hc->c_c_index;
171   as->session_state = SESSION_STATE_ACCEPTING;
172
173   asl = listen_session_get_from_handle (lhc->h_pa_session_handle);
174   as->session_type = asl->session_type;
175   as->listener_handle = lhc->h_pa_session_handle;
176
177   /*
178    * Init session fifos and notify app
179    */
180   if ((rv = app_worker_init_accepted (as)))
181     {
182       HTTP_DBG (1, "failed to allocate fifos");
183       session_free (as);
184       return rv;
185     }
186
187   hc->h_pa_session_handle = session_handle (as);
188   hc->h_pa_wrk_index = as->app_wrk_index;
189   app_wrk = app_worker_get (as->app_wrk_index);
190
191   HTTP_DBG (1, "Accepted on listener %u new connection [%u]%x",
192             ts_listener->opaque, vlib_get_thread_index (), hc_index);
193
194   if ((rv = app_worker_accept_notify (app_wrk, as)))
195     {
196       HTTP_DBG (0, "app accept returned");
197       session_free (as);
198       return rv;
199     }
200
201   /* Avoid enqueuing small chunks of data on transport tx notifications. If
202    * the fifo is small (under 16K) we set the threshold to it's size, meaning
203    * a notification will be given when the fifo empties.
204    */
205   ts = session_get_from_handle (hc->h_tc_session_handle);
206   thresh = clib_min (svm_fifo_size (ts->tx_fifo), HTTP_FIFO_THRESH);
207   svm_fifo_set_deq_thresh (ts->tx_fifo, thresh);
208
209   http_conn_timer_start (hc);
210
211   return 0;
212 }
213
214 static int
215 http_ts_connected_callback (u32 http_app_index, u32 hc_index, session_t *ts,
216                             session_error_t err)
217 {
218   clib_warning ("not supported");
219   return 0;
220 }
221
222 static void
223 http_ts_disconnect_callback (session_t *ts)
224 {
225   http_conn_t *hc;
226
227   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
228
229   if (hc->state < HTTP_CONN_STATE_TRANSPORT_CLOSED)
230     hc->state = HTTP_CONN_STATE_TRANSPORT_CLOSED;
231
232   if (!svm_fifo_max_dequeue_cons (ts->rx_fifo))
233     session_transport_closing_notify (&hc->connection);
234 }
235
236 static void
237 http_ts_reset_callback (session_t *ts)
238 {
239   http_conn_t *ctx;
240
241   ctx = http_conn_get_w_thread (ts->opaque, ts->thread_index);
242
243   if (ctx->state < HTTP_CONN_STATE_TRANSPORT_CLOSED)
244     ctx->state = HTTP_CONN_STATE_TRANSPORT_CLOSED;
245
246   if (!svm_fifo_max_dequeue_cons (ts->rx_fifo))
247     session_transport_reset_notify (&ctx->connection);
248 }
249
250 /**
251  * http error boilerplate
252  */
253 static const char *http_error_template = "HTTP/1.1 %s\r\n"
254                                          "Date: %U GMT\r\n"
255                                          "Content-Type: text/html\r\n"
256                                          "Connection: close\r\n"
257                                          "Pragma: no-cache\r\n"
258                                          "Content-Length: 0\r\n\r\n";
259
260 /**
261  * http response boilerplate
262  */
263 static const char *http_response_template = "HTTP/1.1 200 OK\r\n"
264                                             "Date: %U GMT\r\n"
265                                             "Expires: %U GMT\r\n"
266                                             "Server: VPP Static\r\n"
267                                             "Content-Type: %s\r\n"
268                                             "Content-Length: %lu\r\n\r\n";
269
270 static u32
271 send_data (http_conn_t *hc, u8 *data, u32 length, u32 offset)
272 {
273   const u32 max_burst = 64 << 10;
274   session_t *ts;
275   u32 to_send;
276   int sent;
277
278   ts = session_get_from_handle (hc->h_tc_session_handle);
279
280   to_send = clib_min (length - offset, max_burst);
281   sent = svm_fifo_enqueue (ts->tx_fifo, to_send, data + offset);
282
283   if (sent <= 0)
284     return offset;
285
286   if (svm_fifo_set_event (ts->tx_fifo))
287     session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX);
288
289   return (offset + sent);
290 }
291
292 static void
293 send_error (http_conn_t *hc, http_status_code_t ec)
294 {
295   http_main_t *hm = &http_main;
296   u8 *data;
297   f64 now;
298
299   if (ec >= HTTP_N_STATUS)
300     ec = HTTP_STATUS_INTERNAL_ERROR;
301
302   now = clib_timebase_now (&hm->timebase);
303   data = format (0, http_error_template, http_status_code_str[ec],
304                  format_clib_timebase_time, now);
305   send_data (hc, data, vec_len (data), 0);
306   vec_free (data);
307 }
308
309 static int
310 read_request (http_conn_t *hc)
311 {
312   u32 max_deq, cursize;
313   session_t *ts;
314   int n_read;
315
316   ts = session_get_from_handle (hc->h_tc_session_handle);
317
318   cursize = vec_len (hc->rx_buf);
319   max_deq = svm_fifo_max_dequeue (ts->rx_fifo);
320   if (PREDICT_FALSE (max_deq == 0))
321     return -1;
322
323   vec_validate (hc->rx_buf, cursize + max_deq - 1);
324   n_read = svm_fifo_dequeue (ts->rx_fifo, max_deq, hc->rx_buf + cursize);
325   ASSERT (n_read == max_deq);
326
327   if (svm_fifo_is_empty (ts->rx_fifo))
328     svm_fifo_unset_event (ts->rx_fifo);
329
330   _vec_len (hc->rx_buf) = cursize + n_read;
331   return 0;
332 }
333
334 static int
335 v_find_index (u8 *vec, u32 offset, char *str)
336 {
337   int start_index = offset;
338   u32 slen = (u32) strnlen_s_inline (str, 8);
339   u32 vlen = vec_len (vec);
340
341   ASSERT (slen > 0);
342
343   if (vlen <= slen)
344     return -1;
345
346   for (; start_index < (vlen - slen); start_index++)
347     {
348       if (!memcmp (vec + start_index, str, slen))
349         return start_index;
350     }
351
352   return -1;
353 }
354
355 /**
356  * waiting for request method from peer - parse request method and data
357  */
358 static int
359 state_wait_method (http_conn_t *hc, transport_send_params_t *sp)
360 {
361   http_status_code_t ec;
362   app_worker_t *app_wrk;
363   http_msg_t msg;
364   session_t *as;
365   int i, rv;
366   u32 len;
367   u8 *buf;
368
369   rv = read_request (hc);
370
371   /* Nothing yet, wait for data or timer expire */
372   if (rv)
373     return 0;
374
375   if (vec_len (hc->rx_buf) < 8)
376     {
377       ec = HTTP_STATUS_BAD_REQUEST;
378       goto error;
379     }
380
381   if ((i = v_find_index (hc->rx_buf, 0, "GET ")) >= 0)
382     {
383       hc->method = HTTP_REQ_GET;
384       hc->rx_buf_offset = i + 5;
385
386       i = v_find_index (hc->rx_buf, hc->rx_buf_offset, "HTTP");
387       if (i < 0)
388         {
389           ec = HTTP_STATUS_BAD_REQUEST;
390           goto error;
391         }
392
393       len = i - hc->rx_buf_offset - 1;
394     }
395   else if ((i = v_find_index (hc->rx_buf, 0, "POST ")) >= 0)
396     {
397       hc->method = HTTP_REQ_POST;
398       hc->rx_buf_offset = i + 6;
399       len = vec_len (hc->rx_buf) - hc->rx_buf_offset - 1;
400     }
401   else
402     {
403       HTTP_DBG (0, "Unknown http method");
404       ec = HTTP_STATUS_METHOD_NOT_ALLOWED;
405       goto error;
406     }
407
408   buf = &hc->rx_buf[hc->rx_buf_offset];
409
410   msg.type = HTTP_MSG_REQUEST;
411   msg.method_type = hc->method;
412   msg.content_type = HTTP_CONTENT_TEXT_HTML;
413   msg.data.type = HTTP_MSG_DATA_INLINE;
414   msg.data.len = len;
415
416   svm_fifo_seg_t segs[2] = { { (u8 *) &msg, sizeof (msg) }, { buf, len } };
417
418   as = session_get_from_handle (hc->h_pa_session_handle);
419   rv = svm_fifo_enqueue_segments (as->rx_fifo, segs, 2, 0 /* allow partial */);
420   if (rv < 0 || rv != sizeof (msg) + len)
421     {
422       clib_warning ("failed app enqueue");
423       /* This should not happen as we only handle 1 request per session,
424        * and fifo is allocated, but going forward we should consider
425        * rescheduling */
426       return -1;
427     }
428
429   vec_free (hc->rx_buf);
430   hc->req_state = HTTP_REQ_STATE_WAIT_APP;
431
432   app_wrk = app_worker_get_if_valid (as->app_wrk_index);
433   app_worker_lock_and_send_event (app_wrk, as, SESSION_IO_EVT_RX);
434
435   return 0;
436
437 error:
438
439   send_error (hc, ec);
440   session_transport_closing_notify (&hc->connection);
441   http_disconnect_transport (hc);
442
443   return -1;
444 }
445
446 /**
447  * waiting for data from app
448  */
449 static int
450 state_wait_app (http_conn_t *hc, transport_send_params_t *sp)
451 {
452   http_main_t *hm = &http_main;
453   http_status_code_t ec;
454   http_msg_t msg;
455   session_t *as;
456   u8 *header;
457   u32 offset;
458   f64 now;
459   int rv;
460
461   as = session_get_from_handle (hc->h_pa_session_handle);
462
463   rv = svm_fifo_dequeue (as->tx_fifo, sizeof (msg), (u8 *) &msg);
464   ASSERT (rv == sizeof (msg));
465
466   if (msg.type != HTTP_MSG_REPLY || msg.data.type > HTTP_MSG_DATA_PTR)
467     {
468       clib_warning ("unexpected msg type from app %u", msg.type);
469       ec = HTTP_STATUS_INTERNAL_ERROR;
470       goto error;
471     }
472
473   if (msg.code != HTTP_STATUS_OK)
474     {
475       ec = msg.code;
476       goto error;
477     }
478
479   http_buffer_init (&hc->tx_buf, msg_to_buf_type[msg.data.type], as->tx_fifo,
480                     msg.data.len);
481
482   /*
483    * Add headers. For now:
484    * - current time
485    * - expiration time
486    * - content type
487    * - data length
488    */
489   now = clib_timebase_now (&hm->timebase);
490   header = format (0, http_response_template,
491                    /* Date */
492                    format_clib_timebase_time, now,
493                    /* Expires */
494                    format_clib_timebase_time, now + 600.0,
495                    /* Content type */
496                    http_content_type_str[msg.content_type],
497                    /* Length */
498                    msg.data.len);
499
500   offset = send_data (hc, header, vec_len (header), 0);
501   if (offset != vec_len (header))
502     {
503       clib_warning ("couldn't send response header!");
504       ec = HTTP_STATUS_INTERNAL_ERROR;
505       goto error;
506     }
507   vec_free (header);
508
509   /* Start sending the actual data */
510   hc->req_state = HTTP_REQ_STATE_SEND_MORE_DATA;
511
512   ASSERT (sp->max_burst_size >= offset);
513   sp->max_burst_size -= offset;
514
515   return 1;
516
517 error:
518
519   send_error (hc, ec);
520   hc->req_state = HTTP_REQ_STATE_WAIT_METHOD;
521   session_transport_closing_notify (&hc->connection);
522   http_disconnect_transport (hc);
523
524   /* stop state machine processing */
525   return 0;
526 }
527
528 static int
529 state_send_more_data (http_conn_t *hc, transport_send_params_t *sp)
530 {
531   u32 max_send = 64 << 10, n_segs;
532   http_buffer_t *hb = &hc->tx_buf;
533   svm_fifo_seg_t *seg;
534   session_t *ts;
535   int sent = 0;
536
537   max_send = clib_min (max_send, sp->max_burst_size);
538   ts = session_get_from_handle (hc->h_tc_session_handle);
539   if ((seg = http_buffer_get_segs (hb, max_send, &n_segs)))
540     sent = svm_fifo_enqueue_segments (ts->tx_fifo, seg, n_segs,
541                                       1 /* allow partial */);
542
543   if (sent > 0)
544     {
545       /* Ask scheduler to notify app of deq event if needed */
546       sp->bytes_dequeued += http_buffer_drain (hb, sent);
547       sp->max_burst_size -= sent;
548     }
549
550   /* Not finished sending all data */
551   if (!http_buffer_is_drained (hb))
552     {
553       if (sent && svm_fifo_set_event (ts->tx_fifo))
554         session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX);
555
556       if (svm_fifo_max_enqueue (ts->tx_fifo) < HTTP_FIFO_THRESH)
557         {
558           /* Deschedule http session and wait for deq notification if
559            * underlying ts tx fifo almost full */
560           svm_fifo_add_want_deq_ntf (ts->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
561           transport_connection_deschedule (&hc->connection);
562           sp->flags |= TRANSPORT_SND_F_DESCHED;
563         }
564     }
565   else
566     {
567       if (sent && svm_fifo_set_event (ts->tx_fifo))
568         session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX_FLUSH);
569
570       /* Finished transaction, back to HTTP_REQ_STATE_WAIT_METHOD */
571       hc->req_state = HTTP_REQ_STATE_WAIT_METHOD;
572       http_buffer_free (&hc->tx_buf);
573     }
574
575   return 0;
576 }
577
578 typedef int (*http_sm_handler) (http_conn_t *, transport_send_params_t *sp);
579
580 static http_sm_handler req_state_funcs[HTTP_REQ_N_STATES] = {
581   /* Waiting for GET, POST, etc. */
582   state_wait_method,
583   /* Wait for data from app */
584   state_wait_app,
585   /* Send more data */
586   state_send_more_data,
587 };
588
589 static void
590 http_req_run_state_machine (http_conn_t *hc, transport_send_params_t *sp)
591 {
592   int rv;
593
594   do
595     {
596       rv = req_state_funcs[hc->req_state](hc, sp);
597       if (rv < 0)
598         return;
599     }
600   while (rv);
601
602   /* Reset the session expiration timer */
603   http_conn_timer_update (hc);
604 }
605
606 static int
607 http_ts_rx_callback (session_t *ts)
608 {
609   http_conn_t *hc;
610
611   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
612
613   if (hc->req_state != HTTP_REQ_STATE_WAIT_METHOD)
614     {
615       clib_warning ("tcp data in req state %u", hc->req_state);
616       return 0;
617     }
618
619   http_req_run_state_machine (hc, 0);
620
621   if (hc->state == HTTP_CONN_STATE_TRANSPORT_CLOSED)
622     {
623       if (!svm_fifo_max_dequeue_cons (ts->rx_fifo))
624         session_transport_closing_notify (&hc->connection);
625     }
626   return 0;
627 }
628
629 int
630 http_ts_builtin_tx_callback (session_t *ts)
631 {
632   http_conn_t *hc;
633
634   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
635   transport_connection_reschedule (&hc->connection);
636
637   return 0;
638 }
639
640 static void
641 http_ts_cleanup_callback (session_t *ts, session_cleanup_ntf_t ntf)
642 {
643   http_conn_t *hc;
644
645   if (ntf == SESSION_CLEANUP_TRANSPORT)
646     return;
647
648   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
649   if (!hc)
650     {
651       clib_warning ("no http connection for %u", ts->session_index);
652       return;
653     }
654
655   vec_free (hc->rx_buf);
656
657   http_buffer_free (&hc->tx_buf);
658   http_conn_timer_stop (hc);
659
660   session_transport_delete_notify (&hc->connection);
661   http_conn_free (hc);
662 }
663
664 int
665 http_add_segment_callback (u32 client_index, u64 segment_handle)
666 {
667   /* No-op for builtin */
668   return 0;
669 }
670
671 int
672 http_del_segment_callback (u32 client_index, u64 segment_handle)
673 {
674   return 0;
675 }
676
677 static session_cb_vft_t http_app_cb_vft = {
678   .session_accept_callback = http_ts_accept_callback,
679   .session_disconnect_callback = http_ts_disconnect_callback,
680   .session_connected_callback = http_ts_connected_callback,
681   .session_reset_callback = http_ts_reset_callback,
682   .session_cleanup_callback = http_ts_cleanup_callback,
683   .add_segment_callback = http_add_segment_callback,
684   .del_segment_callback = http_del_segment_callback,
685   .builtin_app_rx_callback = http_ts_rx_callback,
686   .builtin_app_tx_callback = http_ts_builtin_tx_callback,
687 };
688
689 static clib_error_t *
690 http_transport_enable (vlib_main_t *vm, u8 is_en)
691 {
692   vnet_app_detach_args_t _da, *da = &_da;
693   vnet_app_attach_args_t _a, *a = &_a;
694   u64 options[APP_OPTIONS_N_OPTIONS];
695   http_main_t *hm = &http_main;
696
697   if (!is_en)
698     {
699       da->app_index = hm->app_index;
700       da->api_client_index = APP_INVALID_INDEX;
701       vnet_application_detach (da);
702       return 0;
703     }
704
705   vec_validate (hm->wrk, vlib_num_workers ());
706
707   clib_memset (a, 0, sizeof (*a));
708   clib_memset (options, 0, sizeof (options));
709
710   a->session_cb_vft = &http_app_cb_vft;
711   a->api_client_index = APP_INVALID_INDEX;
712   a->options = options;
713   a->name = format (0, "http");
714   a->options[APP_OPTIONS_SEGMENT_SIZE] = hm->first_seg_size;
715   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = hm->add_seg_size;
716   a->options[APP_OPTIONS_RX_FIFO_SIZE] = hm->fifo_size;
717   a->options[APP_OPTIONS_TX_FIFO_SIZE] = hm->fifo_size;
718   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
719   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
720   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
721
722   if (vnet_application_attach (a))
723     return clib_error_return (0, "failed to attach http app");
724
725   hm->app_index = a->app_index;
726   vec_free (a->name);
727
728   clib_timebase_init (&hm->timebase, 0 /* GMT */, CLIB_TIMEBASE_DAYLIGHT_NONE,
729                       &vm->clib_time /* share the system clock */);
730
731   http_timers_init (vm, http_conn_timeout_cb);
732
733   return 0;
734 }
735
736 static int
737 http_transport_connect (transport_endpoint_cfg_t *tep)
738 {
739   return -1;
740 }
741
742 static u32
743 http_start_listen (u32 app_listener_index, transport_endpoint_cfg_t *tep)
744 {
745   vnet_listen_args_t _args = {}, *args = &_args;
746   session_t *ts_listener, *app_listener;
747   http_main_t *hm = &http_main;
748   session_endpoint_cfg_t *sep;
749   app_worker_t *app_wrk;
750   transport_proto_t tp;
751   app_listener_t *al;
752   application_t *app;
753   http_conn_t *lhc;
754   u32 lhc_index;
755
756   sep = (session_endpoint_cfg_t *) tep;
757
758   app_wrk = app_worker_get (sep->app_wrk_index);
759   app = application_get (app_wrk->app_index);
760
761   args->app_index = hm->app_index;
762   args->sep_ext = *sep;
763   args->sep_ext.ns_index = app->ns_index;
764   tp = sep->ext_cfg ? TRANSPORT_PROTO_TLS : TRANSPORT_PROTO_TCP;
765   args->sep_ext.transport_proto = tp;
766
767   if (vnet_listen (args))
768     return SESSION_INVALID_INDEX;
769
770   lhc_index = http_listener_alloc ();
771   lhc = http_listener_get (lhc_index);
772
773   /* Grab transport connection listener and link to http listener */
774   lhc->h_tc_session_handle = args->handle;
775   al = app_listener_get_w_handle (lhc->h_tc_session_handle);
776   ts_listener = app_listener_get_session (al);
777   ts_listener->opaque = lhc_index;
778
779   /* Grab application listener and link to http listener */
780   app_listener = listen_session_get (app_listener_index);
781   lhc->h_pa_wrk_index = sep->app_wrk_index;
782   lhc->h_pa_session_handle = listen_session_get_handle (app_listener);
783   lhc->c_s_index = app_listener_index;
784   lhc->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
785
786   return lhc_index;
787 }
788
789 static u32
790 http_stop_listen (u32 listener_index)
791 {
792   http_conn_t *lhc;
793   int rv;
794
795   lhc = http_listener_get (listener_index);
796
797   vnet_unlisten_args_t a = {
798     .handle = lhc->h_tc_session_handle,
799     .app_index = http_main.app_index,
800     .wrk_map_index = 0 /* default wrk */
801   };
802
803   if ((rv = vnet_unlisten (&a)))
804     clib_warning ("unlisten returned %d", rv);
805
806   http_listener_free (lhc);
807
808   return 0;
809 }
810
811 static void
812 http_transport_close (u32 hc_index, u32 thread_index)
813 {
814   session_t *as;
815   http_conn_t *hc;
816
817   HTTP_DBG (1, "App disconnecting %x", hc_index);
818
819   hc = http_conn_get_w_thread (hc_index, thread_index);
820   as = session_get_from_handle (hc->h_pa_session_handle);
821
822   /* Nothing more to send, confirm close */
823   if (!svm_fifo_max_dequeue_cons (as->tx_fifo))
824     {
825       session_transport_closed_notify (&hc->connection);
826       http_disconnect_transport (hc);
827     }
828   else
829     {
830       /* Wait for all data to be written to ts */
831       hc->state = HTTP_CONN_STATE_APP_CLOSED;
832     }
833 }
834
835 static transport_connection_t *
836 http_transport_get_connection (u32 hc_index, u32 thread_index)
837 {
838   http_conn_t *hc = http_conn_get_w_thread (hc_index, thread_index);
839   return &hc->connection;
840 }
841
842 static transport_connection_t *
843 http_transport_get_listener (u32 listener_index)
844 {
845   http_conn_t *lhc = http_listener_get (listener_index);
846   return &lhc->connection;
847 }
848
849 static int
850 http_app_tx_callback (void *session, transport_send_params_t *sp)
851 {
852   session_t *as = (session_t *) session;
853   u32 max_burst_sz, sent;
854   http_conn_t *hc;
855
856   hc = http_conn_get_w_thread (as->connection_index, as->thread_index);
857   if (hc->req_state < HTTP_REQ_STATE_WAIT_APP)
858     {
859       clib_warning ("app data in req state %u", hc->req_state);
860       return 0;
861     }
862
863   max_burst_sz = sp->max_burst_size * TRANSPORT_PACER_MIN_MSS;
864   sp->max_burst_size = max_burst_sz;
865
866   http_req_run_state_machine (hc, sp);
867
868   if (hc->state == HTTP_CONN_STATE_CLOSED)
869     {
870       if (!svm_fifo_max_dequeue_cons (as->rx_fifo))
871         http_disconnect_transport (hc);
872     }
873
874   sent = max_burst_sz - sp->max_burst_size;
875
876   return sent > 0 ? clib_max (sent / TRANSPORT_PACER_MIN_MSS, 1) : 0;
877 }
878
879 static void
880 http_transport_get_endpoint (u32 hc_index, u32 thread_index,
881                              transport_endpoint_t *tep, u8 is_lcl)
882 {
883   http_conn_t *hc = http_conn_get_w_thread (hc_index, thread_index);
884   session_t *ts;
885
886   ts = session_get_from_handle (hc->h_tc_session_handle);
887   session_get_endpoint (ts, tep, is_lcl);
888 }
889
890 static u8 *
891 format_http_connection (u8 *s, va_list *args)
892 {
893   http_conn_t *hc = va_arg (*args, http_conn_t *);
894   session_t *ts;
895
896   ts = session_get_from_handle (hc->h_tc_session_handle);
897   s = format (s, "[%d:%d][H] app_wrk %u ts %d:%d", hc->c_thread_index,
898               hc->c_s_index, hc->h_pa_wrk_index, ts->thread_index,
899               ts->session_index);
900
901   return s;
902 }
903
904 static u8 *
905 format_http_listener (u8 *s, va_list *args)
906 {
907   http_conn_t *lhc = va_arg (*args, http_conn_t *);
908   app_listener_t *al;
909   session_t *lts;
910
911   al = app_listener_get_w_handle (lhc->h_tc_session_handle);
912   lts = app_listener_get_session (al);
913   s = format (s, "[%d:%d][H] app_wrk %u ts %d:%d", lhc->c_thread_index,
914               lhc->c_s_index, lhc->h_pa_wrk_index, lts->thread_index,
915               lts->session_index);
916
917   return s;
918 }
919
920 static u8 *
921 format_http_conn_state (u8 *s, va_list *args)
922 {
923   http_conn_t *hc = va_arg (*args, http_conn_t *);
924
925   switch (hc->state)
926     {
927     case HTTP_CONN_STATE_LISTEN:
928       s = format (s, "LISTEN");
929       break;
930     case HTTP_CONN_STATE_CONNECTING:
931       s = format (s, "CONNECTING");
932       break;
933     case HTTP_CONN_STATE_ESTABLISHED:
934       s = format (s, "ESTABLISHED");
935       break;
936     case HTTP_CONN_STATE_TRANSPORT_CLOSED:
937       s = format (s, "TRANSPORT_CLOSED");
938       break;
939     case HTTP_CONN_STATE_APP_CLOSED:
940       s = format (s, "APP_CLOSED");
941       break;
942     case HTTP_CONN_STATE_CLOSED:
943       s = format (s, "CLOSED");
944       break;
945     }
946
947   return s;
948 }
949
950 static u8 *
951 format_http_transport_connection (u8 *s, va_list *args)
952 {
953   u32 tc_index = va_arg (*args, u32);
954   u32 thread_index = va_arg (*args, u32);
955   u32 verbose = va_arg (*args, u32);
956   http_conn_t *hc;
957
958   hc = http_conn_get_w_thread (tc_index, thread_index);
959
960   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_http_connection, hc);
961   if (verbose)
962     {
963       s =
964         format (s, "%-" SESSION_CLI_STATE_LEN "U", format_http_conn_state, hc);
965       if (verbose > 1)
966         s = format (s, "\n");
967     }
968
969   return s;
970 }
971
972 static u8 *
973 format_http_transport_listener (u8 *s, va_list *args)
974 {
975   u32 tc_index = va_arg (*args, u32);
976   u32 __clib_unused thread_index = va_arg (*args, u32);
977   u32 __clib_unused verbose = va_arg (*args, u32);
978   http_conn_t *lhc = http_listener_get (tc_index);
979
980   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_http_listener, lhc);
981   if (verbose)
982     s =
983       format (s, "%-" SESSION_CLI_STATE_LEN "U", format_http_conn_state, lhc);
984   return s;
985 }
986
987 static const transport_proto_vft_t http_proto = {
988   .enable = http_transport_enable,
989   .connect = http_transport_connect,
990   .start_listen = http_start_listen,
991   .stop_listen = http_stop_listen,
992   .close = http_transport_close,
993   .custom_tx = http_app_tx_callback,
994   .get_connection = http_transport_get_connection,
995   .get_listener = http_transport_get_listener,
996   .get_transport_endpoint = http_transport_get_endpoint,
997   .format_connection = format_http_transport_connection,
998   .format_listener = format_http_transport_listener,
999   .transport_options = {
1000     .name = "http",
1001     .short_name = "H",
1002     .tx_type = TRANSPORT_TX_INTERNAL,
1003     .service_type = TRANSPORT_SERVICE_APP,
1004   },
1005 };
1006
1007 static clib_error_t *
1008 http_transport_init (vlib_main_t *vm)
1009 {
1010   http_main_t *hm = &http_main;
1011
1012   transport_register_protocol (TRANSPORT_PROTO_HTTP, &http_proto,
1013                                FIB_PROTOCOL_IP4, ~0);
1014   transport_register_protocol (TRANSPORT_PROTO_HTTP, &http_proto,
1015                                FIB_PROTOCOL_IP6, ~0);
1016
1017   /* Default values, configurable via startup conf */
1018   hm->add_seg_size = 256 << 20;
1019   hm->first_seg_size = 32 << 20;
1020   hm->fifo_size = 512 << 10;
1021
1022   return 0;
1023 }
1024
1025 VLIB_INIT_FUNCTION (http_transport_init);
1026
1027 static clib_error_t *
1028 http_config_fn (vlib_main_t *vm, unformat_input_t *input)
1029 {
1030   http_main_t *hm = &http_main;
1031   uword mem_sz;
1032
1033   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1034     {
1035       if (unformat (input, "first-segment-size %U", unformat_memory_size,
1036                     &mem_sz))
1037         {
1038           hm->first_seg_size = clib_max (mem_sz, 1 << 20);
1039           if (hm->first_seg_size != mem_sz)
1040             clib_warning ("first seg size too small %u", mem_sz);
1041         }
1042       else if (unformat (input, "add-segment-size %U", unformat_memory_size,
1043                          &mem_sz))
1044         {
1045           hm->add_seg_size = clib_max (mem_sz, 1 << 20);
1046           if (hm->add_seg_size != mem_sz)
1047             clib_warning ("add seg size too small %u", mem_sz);
1048         }
1049       else if (unformat (input, "fifo-size %U", unformat_memory_size, &mem_sz))
1050         {
1051           hm->fifo_size = clib_clamp (mem_sz, 4 << 10, 2 << 30);
1052           if (hm->fifo_size != mem_sz)
1053             clib_warning ("invalid fifo size %lu", mem_sz);
1054         }
1055       else
1056         return clib_error_return (0, "unknown input `%U'",
1057                                   format_unformat_error, input);
1058     }
1059   return 0;
1060 }
1061
1062 VLIB_EARLY_CONFIG_FUNCTION (http_config_fn, "http");
1063
1064 VLIB_PLUGIN_REGISTER () = {
1065   .version = VPP_BUILD_VER,
1066   .description = "Hypertext Transfer Protocol (HTTP)",
1067   .default_disabled = 0,
1068 };
1069
1070 /*
1071  * fd.io coding-style-patch-verification: ON
1072  *
1073  * Local Variables:
1074  * eval: (c-set-style "gnu")
1075  * End:
1076  */