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