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