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