http: return more than url to server app
[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 #define CONTENT_LEN_STR  "Content-Length: "
24
25 /* HTTP state machine result */
26 typedef enum http_sm_result_t_
27 {
28   HTTP_SM_STOP = 0,
29   HTTP_SM_CONTINUE = 1,
30   HTTP_SM_ERROR = -1,
31 } http_sm_result_t;
32
33 const char *http_status_code_str[] = {
34 #define _(c, s, str) str,
35   foreach_http_status_code
36 #undef _
37 };
38
39 const char *http_content_type_str[] = {
40 #define _(s, ext, str) str,
41   foreach_http_content_type
42 #undef _
43 };
44
45 const http_buffer_type_t msg_to_buf_type[] = {
46   [HTTP_MSG_DATA_INLINE] = HTTP_BUFFER_FIFO,
47   [HTTP_MSG_DATA_PTR] = HTTP_BUFFER_PTR,
48 };
49
50 u8 *
51 format_http_state (u8 *s, va_list *va)
52 {
53   http_state_t state = va_arg (*va, http_state_t);
54
55   switch (state)
56     {
57     case HTTP_STATE_IDLE:
58       return format (s, "idle");
59     case HTTP_STATE_WAIT_APP_METHOD:
60       return format (s, "wait app method");
61     case HTTP_STATE_WAIT_SERVER_REPLY:
62       return format (s, "wait server reply");
63     case HTTP_STATE_CLIENT_IO_MORE_DATA:
64       return format (s, "client io more data");
65     case HTTP_STATE_WAIT_CLIENT_METHOD:
66       return format (s, "wait client method");
67     case HTTP_STATE_WAIT_APP_REPLY:
68       return format (s, "wait app reply");
69     case HTTP_STATE_APP_IO_MORE_DATA:
70       return format (s, "app io more data");
71     default:
72       break;
73     }
74   return format (s, "unknown");
75 }
76
77 #define http_state_change(_hc, _state)                                        \
78   do                                                                          \
79     {                                                                         \
80       HTTP_DBG (1, "changing http state %U -> %U", format_http_state,         \
81                 (_hc)->http_state, format_http_state, _state);                \
82       (_hc)->http_state = _state;                                             \
83     }                                                                         \
84   while (0)
85
86 static inline int
87 http_state_is_tx_valid (http_conn_t *hc)
88 {
89   http_state_t state = hc->http_state;
90   return (state == HTTP_STATE_APP_IO_MORE_DATA ||
91           state == HTTP_STATE_CLIENT_IO_MORE_DATA ||
92           state == HTTP_STATE_WAIT_APP_REPLY ||
93           state == HTTP_STATE_WAIT_APP_METHOD);
94 }
95
96 static inline http_worker_t *
97 http_worker_get (u32 thread_index)
98 {
99   return &http_main.wrk[thread_index];
100 }
101
102 static inline u32
103 http_conn_alloc_w_thread (u32 thread_index)
104 {
105   http_worker_t *wrk = http_worker_get (thread_index);
106   http_conn_t *hc;
107
108   pool_get_aligned_safe (wrk->conn_pool, hc, CLIB_CACHE_LINE_BYTES);
109   clib_memset (hc, 0, sizeof (*hc));
110   hc->c_thread_index = thread_index;
111   hc->h_hc_index = hc - wrk->conn_pool;
112   hc->h_pa_session_handle = SESSION_INVALID_HANDLE;
113   hc->h_tc_session_handle = SESSION_INVALID_HANDLE;
114   return hc->h_hc_index;
115 }
116
117 static inline http_conn_t *
118 http_conn_get_w_thread (u32 hc_index, u32 thread_index)
119 {
120   http_worker_t *wrk = http_worker_get (thread_index);
121   return pool_elt_at_index (wrk->conn_pool, hc_index);
122 }
123
124 void
125 http_conn_free (http_conn_t *hc)
126 {
127   http_worker_t *wrk = http_worker_get (hc->c_thread_index);
128   pool_put (wrk->conn_pool, hc);
129 }
130
131 static u32
132 http_listener_alloc (void)
133 {
134   http_main_t *hm = &http_main;
135   http_conn_t *lhc;
136
137   pool_get_zero (hm->listener_pool, lhc);
138   lhc->c_c_index = lhc - hm->listener_pool;
139   return lhc->c_c_index;
140 }
141
142 http_conn_t *
143 http_listener_get (u32 lhc_index)
144 {
145   return pool_elt_at_index (http_main.listener_pool, lhc_index);
146 }
147
148 void
149 http_listener_free (http_conn_t *lhc)
150 {
151   http_main_t *hm = &http_main;
152
153   vec_free (lhc->app_name);
154   if (CLIB_DEBUG)
155     memset (lhc, 0xfc, sizeof (*lhc));
156   pool_put (hm->listener_pool, lhc);
157 }
158
159 void
160 http_disconnect_transport (http_conn_t *hc)
161 {
162   vnet_disconnect_args_t a = {
163     .handle = hc->h_tc_session_handle,
164     .app_index = http_main.app_index,
165   };
166
167   hc->state = HTTP_CONN_STATE_CLOSED;
168
169   if (vnet_disconnect_session (&a))
170     clib_warning ("disconnect returned");
171 }
172
173 static void
174 http_conn_timeout_cb (void *hc_handlep)
175 {
176   http_conn_t *hc;
177   uword hs_handle;
178
179   hs_handle = pointer_to_uword (hc_handlep);
180   hc = http_conn_get_w_thread (hs_handle & 0x00FFFFFF, hs_handle >> 24);
181
182   HTTP_DBG (1, "terminate thread %d index %d hs %llx", hs_handle >> 24,
183             hs_handle & 0x00FFFFFF, hc);
184   if (!hc)
185     return;
186
187   hc->timer_handle = ~0;
188   session_transport_closing_notify (&hc->connection);
189   http_disconnect_transport (hc);
190 }
191
192 int
193 http_ts_accept_callback (session_t *ts)
194 {
195   session_t *ts_listener, *as, *asl;
196   app_worker_t *app_wrk;
197   http_conn_t *lhc, *hc;
198   u32 hc_index, thresh;
199   int rv;
200
201   ts_listener = listen_session_get_from_handle (ts->listener_handle);
202   lhc = http_listener_get (ts_listener->opaque);
203
204   hc_index = http_conn_alloc_w_thread (ts->thread_index);
205   hc = http_conn_get_w_thread (hc_index, ts->thread_index);
206   clib_memcpy_fast (hc, lhc, sizeof (*lhc));
207   hc->c_thread_index = ts->thread_index;
208   hc->h_hc_index = hc_index;
209
210   hc->h_tc_session_handle = session_handle (ts);
211   hc->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
212
213   hc->state = HTTP_CONN_STATE_ESTABLISHED;
214   http_state_change (hc, HTTP_STATE_WAIT_CLIENT_METHOD);
215
216   ts->session_state = SESSION_STATE_READY;
217   ts->opaque = hc_index;
218
219   /*
220    * Alloc session and initialize
221    */
222   as = session_alloc (hc->c_thread_index);
223   hc->c_s_index = as->session_index;
224
225   as->app_wrk_index = hc->h_pa_wrk_index;
226   as->connection_index = hc->c_c_index;
227   as->session_state = SESSION_STATE_ACCEPTING;
228
229   asl = listen_session_get_from_handle (lhc->h_pa_session_handle);
230   as->session_type = asl->session_type;
231   as->listener_handle = lhc->h_pa_session_handle;
232
233   /*
234    * Init session fifos and notify app
235    */
236   if ((rv = app_worker_init_accepted (as)))
237     {
238       HTTP_DBG (1, "failed to allocate fifos");
239       session_free (as);
240       return rv;
241     }
242
243   hc->h_pa_session_handle = session_handle (as);
244   hc->h_pa_wrk_index = as->app_wrk_index;
245   app_wrk = app_worker_get (as->app_wrk_index);
246
247   HTTP_DBG (1, "Accepted on listener %u new connection [%u]%x",
248             ts_listener->opaque, vlib_get_thread_index (), hc_index);
249
250   if ((rv = app_worker_accept_notify (app_wrk, as)))
251     {
252       HTTP_DBG (0, "app accept returned");
253       session_free (as);
254       return rv;
255     }
256
257   /* Avoid enqueuing small chunks of data on transport tx notifications. If
258    * the fifo is small (under 16K) we set the threshold to it's size, meaning
259    * a notification will be given when the fifo empties.
260    */
261   ts = session_get_from_handle (hc->h_tc_session_handle);
262   thresh = clib_min (svm_fifo_size (ts->tx_fifo), HTTP_FIFO_THRESH);
263   svm_fifo_set_deq_thresh (ts->tx_fifo, thresh);
264
265   http_conn_timer_start (hc);
266
267   return 0;
268 }
269
270 static int
271 http_ts_connected_callback (u32 http_app_index, u32 ho_hc_index, session_t *ts,
272                             session_error_t err)
273 {
274   u32 new_hc_index;
275   session_t *as;
276   http_conn_t *hc, *ho_hc;
277   app_worker_t *app_wrk;
278   int rv;
279
280   ho_hc = http_conn_get_w_thread (ho_hc_index, 0);
281   ASSERT (ho_hc->state == HTTP_CONN_STATE_CONNECTING);
282
283   if (err)
284     {
285       clib_warning ("half-open hc index %d, error: %U", ho_hc_index,
286                     format_session_error, err);
287       app_wrk = app_worker_get_if_valid (ho_hc->h_pa_wrk_index);
288       if (app_wrk)
289         app_worker_connect_notify (app_wrk, 0, err, ho_hc->h_pa_app_api_ctx);
290       return 0;
291     }
292
293   new_hc_index = http_conn_alloc_w_thread (ts->thread_index);
294   hc = http_conn_get_w_thread (new_hc_index, ts->thread_index);
295
296   clib_memcpy_fast (hc, ho_hc, sizeof (*hc));
297
298   hc->c_thread_index = ts->thread_index;
299   hc->h_tc_session_handle = session_handle (ts);
300   hc->c_c_index = new_hc_index;
301   hc->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
302   hc->state = HTTP_CONN_STATE_ESTABLISHED;
303   http_state_change (hc, HTTP_STATE_WAIT_APP_METHOD);
304
305   ts->session_state = SESSION_STATE_READY;
306   ts->opaque = new_hc_index;
307
308   /* allocate app session and initialize */
309
310   as = session_alloc (hc->c_thread_index);
311   hc->c_s_index = as->session_index;
312   as->connection_index = hc->c_c_index;
313   as->app_wrk_index = hc->h_pa_wrk_index;
314   as->session_state = SESSION_STATE_READY;
315   as->opaque = hc->h_pa_app_api_ctx;
316   as->session_type = session_type_from_proto_and_ip (
317     TRANSPORT_PROTO_HTTP, session_type_is_ip4 (ts->session_type));
318
319   HTTP_DBG (1, "half-open hc index %d,  hc index %d", ho_hc_index,
320             new_hc_index);
321
322   app_wrk = app_worker_get (hc->h_pa_wrk_index);
323   if (!app_wrk)
324     {
325       clib_warning ("no app worker");
326       return -1;
327     }
328
329   if ((rv = app_worker_init_connected (app_wrk, as)))
330     {
331       HTTP_DBG (1, "failed to allocate fifos");
332       session_free (as);
333       return rv;
334     }
335   app_worker_connect_notify (app_wrk, as, err, hc->h_pa_app_api_ctx);
336   hc->h_pa_session_handle = session_handle (as);
337   http_conn_timer_start (hc);
338
339   return 0;
340 }
341
342 static void
343 http_ts_disconnect_callback (session_t *ts)
344 {
345   http_conn_t *hc;
346
347   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
348
349   if (hc->state < HTTP_CONN_STATE_TRANSPORT_CLOSED)
350     hc->state = HTTP_CONN_STATE_TRANSPORT_CLOSED;
351
352   /* Nothing more to rx, propagate to app */
353   if (!svm_fifo_max_dequeue_cons (ts->rx_fifo))
354     session_transport_closing_notify (&hc->connection);
355 }
356
357 static void
358 http_ts_reset_callback (session_t *ts)
359 {
360   http_conn_t *hc;
361
362   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
363
364   hc->state = HTTP_CONN_STATE_CLOSED;
365   http_buffer_free (&hc->tx_buf);
366   http_state_change (hc, HTTP_STATE_WAIT_CLIENT_METHOD);
367   session_transport_reset_notify (&hc->connection);
368
369   http_disconnect_transport (hc);
370 }
371
372 /**
373  * http error boilerplate
374  */
375 static const char *http_error_template = "HTTP/1.1 %s\r\n"
376                                          "Date: %U GMT\r\n"
377                                          "Content-Type: text/html\r\n"
378                                          "Connection: close\r\n"
379                                          "Pragma: no-cache\r\n"
380                                          "Content-Length: 0\r\n\r\n";
381
382 static const char *http_redirect_template = "HTTP/1.1 %s\r\n";
383
384 /**
385  * http response boilerplate
386  */
387 static const char *http_response_template = "HTTP/1.1 %s\r\n"
388                                             "Date: %U GMT\r\n"
389                                             "Expires: %U GMT\r\n"
390                                             "Server: %s\r\n"
391                                             "Content-Type: %s\r\n"
392                                             "Content-Length: %lu\r\n\r\n";
393
394 static const char *http_request_template = "GET %s HTTP/1.1\r\n"
395                                            "User-Agent: %s\r\n"
396                                            "Accept: */*\r\n\r\n";
397
398 static u32
399 http_send_data (http_conn_t *hc, u8 *data, u32 length, u32 offset)
400 {
401   const u32 max_burst = 64 << 10;
402   session_t *ts;
403   u32 to_send;
404   int sent;
405
406   ts = session_get_from_handle (hc->h_tc_session_handle);
407
408   to_send = clib_min (length - offset, max_burst);
409   sent = svm_fifo_enqueue (ts->tx_fifo, to_send, data + offset);
410
411   if (sent <= 0)
412     return offset;
413
414   if (svm_fifo_set_event (ts->tx_fifo))
415     session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX);
416
417   return (offset + sent);
418 }
419
420 static void
421 http_send_error (http_conn_t *hc, http_status_code_t ec)
422 {
423   http_main_t *hm = &http_main;
424   u8 *data;
425   f64 now;
426
427   if (ec >= HTTP_N_STATUS)
428     ec = HTTP_STATUS_INTERNAL_ERROR;
429
430   now = clib_timebase_now (&hm->timebase);
431   data = format (0, http_error_template, http_status_code_str[ec],
432                  format_clib_timebase_time, now);
433   http_send_data (hc, data, vec_len (data), 0);
434   vec_free (data);
435 }
436
437 static int
438 http_read_message (http_conn_t *hc)
439 {
440   u32 max_deq, cursize;
441   session_t *ts;
442   int n_read;
443
444   ts = session_get_from_handle (hc->h_tc_session_handle);
445
446   cursize = vec_len (hc->rx_buf);
447   max_deq = svm_fifo_max_dequeue (ts->rx_fifo);
448   if (PREDICT_FALSE (max_deq == 0))
449     return -1;
450
451   vec_validate (hc->rx_buf, cursize + max_deq - 1);
452   n_read = svm_fifo_dequeue (ts->rx_fifo, max_deq, hc->rx_buf + cursize);
453   ASSERT (n_read == max_deq);
454
455   if (svm_fifo_is_empty (ts->rx_fifo))
456     svm_fifo_unset_event (ts->rx_fifo);
457
458   vec_set_len (hc->rx_buf, cursize + n_read);
459   return 0;
460 }
461
462 /**
463  * @brief Find the first occurrence of the string in the vector.
464  *
465  * @param vec The vector to be scanned.
466  * @param offset Search offset in the vector.
467  * @param num Maximum number of characters to be searched if non-zero.
468  * @param str The string to be searched.
469  *
470  * @return @c -1 if the string is not found within the vector; index otherwise.
471  */
472 static inline int
473 v_find_index (u8 *vec, u32 offset, u32 num, char *str)
474 {
475   int start_index = offset;
476   u32 slen = (u32) strnlen_s_inline (str, 16);
477   u32 vlen = vec_len (vec);
478
479   ASSERT (slen > 0);
480
481   if (vlen <= slen)
482     return -1;
483
484   int end_index = vlen - slen;
485   if (num)
486     {
487       if (num < slen)
488         return -1;
489       end_index = clib_min (end_index, offset + num - slen);
490     }
491
492   for (; start_index <= end_index; start_index++)
493     {
494       if (!memcmp (vec + start_index, str, slen))
495         return start_index;
496     }
497
498   return -1;
499 }
500
501 static void
502 http_identify_optional_query (http_conn_t *hc)
503 {
504   u32 pos = vec_search (hc->rx_buf, '?');
505   if (~0 != pos)
506     {
507       hc->target_query_offset = pos + 1;
508       hc->target_query_len =
509         hc->target_path_offset + hc->target_path_len - hc->target_query_offset;
510       hc->target_path_len = hc->target_path_len - hc->target_query_len - 1;
511     }
512 }
513
514 static int
515 http_get_target_form (http_conn_t *hc)
516 {
517   int i;
518
519   /* "*" */
520   if ((hc->rx_buf[hc->target_path_offset] == '*') &&
521       (hc->target_path_len == 1))
522     {
523       hc->target_form = HTTP_TARGET_ASTERISK_FORM;
524       return 0;
525     }
526
527   /* 1*( "/" segment ) [ "?" query ] */
528   if (hc->rx_buf[hc->target_path_offset] == '/')
529     {
530       /* drop leading slash */
531       hc->target_path_len--;
532       hc->target_path_offset++;
533       hc->target_form = HTTP_TARGET_ORIGIN_FORM;
534       http_identify_optional_query (hc);
535       return 0;
536     }
537
538   /* scheme "://" host [ ":" port ] *( "/" segment ) [ "?" query ] */
539   i = v_find_index (hc->rx_buf, hc->target_path_offset, hc->target_path_len,
540                     "://");
541   if (i > 0)
542     {
543       hc->target_form = HTTP_TARGET_ABSOLUTE_FORM;
544       http_identify_optional_query (hc);
545       return 0;
546     }
547
548   /* host ":" port */
549   for (i = hc->target_path_offset;
550        i < (hc->target_path_offset + hc->target_path_len); i++)
551     {
552       if ((hc->rx_buf[i] == ':') && (isdigit (hc->rx_buf[i + 1])))
553         {
554           hc->target_form = HTTP_TARGET_AUTHORITY_FORM;
555           return 0;
556         }
557     }
558
559   return -1;
560 }
561
562 static int
563 http_parse_request_line (http_conn_t *hc, http_status_code_t *ec)
564 {
565   int i, target_len;
566   u32 next_line_offset;
567
568   /* request-line = method SP request-target SP HTTP-version CRLF */
569   i = v_find_index (hc->rx_buf, 0, 0, "\r\n");
570   if (i < 0)
571     {
572       clib_warning ("request line incomplete");
573       *ec = HTTP_STATUS_BAD_REQUEST;
574       return -1;
575     }
576   HTTP_DBG (0, "request line length: %d", i);
577   next_line_offset = i + 2;
578
579   /* there should be at least one more CRLF */
580   if (vec_len (hc->rx_buf) < (next_line_offset + 2))
581     {
582       clib_warning ("malformed message, too short");
583       *ec = HTTP_STATUS_BAD_REQUEST;
584       return -1;
585     }
586
587   /* parse method */
588   if ((i = v_find_index (hc->rx_buf, 0, next_line_offset, "GET ")) >= 0)
589     {
590       HTTP_DBG (0, "GET method");
591       hc->method = HTTP_REQ_GET;
592       hc->target_path_offset = i + 4;
593     }
594   else if ((i = v_find_index (hc->rx_buf, 0, next_line_offset, "POST ")) >= 0)
595     {
596       HTTP_DBG (0, "POST method");
597       hc->method = HTTP_REQ_POST;
598       hc->target_path_offset = i + 5;
599     }
600   else
601     {
602       clib_warning ("method not implemented: %8v", hc->rx_buf);
603       *ec = HTTP_STATUS_NOT_IMPLEMENTED;
604       return -1;
605     }
606
607   /* find version */
608   i = v_find_index (hc->rx_buf, next_line_offset - 11, 11, " HTTP/");
609   if (i < 0)
610     {
611       clib_warning ("HTTP version not present");
612       *ec = HTTP_STATUS_BAD_REQUEST;
613       return -1;
614     }
615   /* verify major version */
616   if (isdigit (hc->rx_buf[i + 6]))
617     {
618       if (hc->rx_buf[i + 6] != '1')
619         {
620           clib_warning ("HTTP major version '%c' not supported",
621                         hc->rx_buf[i + 6]);
622           *ec = HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED;
623           return -1;
624         }
625     }
626   else
627     {
628       clib_warning ("HTTP major version '%c' is not digit", hc->rx_buf[i + 6]);
629       *ec = HTTP_STATUS_BAD_REQUEST;
630       return -1;
631     }
632
633   /* parse request-target */
634   target_len = i - hc->target_path_offset;
635   if (target_len < 1)
636     {
637       clib_warning ("request-target not present");
638       *ec = HTTP_STATUS_BAD_REQUEST;
639       return -1;
640     }
641   hc->target_path_len = target_len;
642   hc->target_query_offset = 0;
643   hc->target_query_len = 0;
644   if (http_get_target_form (hc))
645     {
646       clib_warning ("invalid target");
647       *ec = HTTP_STATUS_BAD_REQUEST;
648       return -1;
649     }
650   HTTP_DBG (0, "request-target path length: %u", hc->target_path_len);
651   HTTP_DBG (0, "request-target path offset: %u", hc->target_path_offset);
652   HTTP_DBG (0, "request-target query length: %u", hc->target_query_len);
653   HTTP_DBG (0, "request-target query offset: %u", hc->target_query_offset);
654
655   /* set buffer offset to nex line start */
656   hc->rx_buf_offset = next_line_offset;
657
658   return 0;
659 }
660
661 static int
662 http_identify_headers (http_conn_t *hc, http_status_code_t *ec)
663 {
664   int i;
665
666   /* check if we have any header */
667   if ((hc->rx_buf[hc->rx_buf_offset] == '\r') &&
668       (hc->rx_buf[hc->rx_buf_offset + 1] == '\n'))
669     {
670       /* just another CRLF -> no headers */
671       HTTP_DBG (0, "no headers");
672       hc->headers_len = 0;
673       return 0;
674     }
675
676   /* find empty line indicating end of header section */
677   i = v_find_index (hc->rx_buf, hc->rx_buf_offset, 0, "\r\n\r\n");
678   if (i < 0)
679     {
680       clib_warning ("cannot find header section end");
681       *ec = HTTP_STATUS_BAD_REQUEST;
682       return -1;
683     }
684   hc->headers_offset = hc->rx_buf_offset;
685   hc->headers_len = i - hc->rx_buf_offset + 2;
686   HTTP_DBG (0, "headers length: %u", hc->headers_len);
687   HTTP_DBG (0, "headers offset: %u", hc->headers_offset);
688
689   return 0;
690 }
691
692 static int
693 http_identify_message_body (http_conn_t *hc, http_status_code_t *ec)
694 {
695   unformat_input_t input;
696   int i, len;
697   u8 *line;
698
699   hc->body_len = 0;
700
701   if (hc->headers_len == 0)
702     {
703       HTTP_DBG (0, "no header, no message-body");
704       return 0;
705     }
706
707   /* TODO check for chunked transfer coding */
708
709   /* try to find Content-Length header */
710   i = v_find_index (hc->rx_buf, hc->headers_offset, hc->headers_len,
711                     "Content-Length:");
712   if (i < 0)
713     {
714       HTTP_DBG (0, "Content-Length header not present, no message-body");
715       return 0;
716     }
717   hc->rx_buf_offset = i + 15;
718
719   i = v_find_index (hc->rx_buf, hc->rx_buf_offset, hc->headers_len, "\r\n");
720   if (i < 0)
721     {
722       clib_warning ("end of line missing");
723       *ec = HTTP_STATUS_BAD_REQUEST;
724       return -1;
725     }
726   len = i - hc->rx_buf_offset;
727   if (len < 1)
728     {
729       clib_warning ("invalid header, content length value missing");
730       *ec = HTTP_STATUS_BAD_REQUEST;
731       return -1;
732     }
733
734   line = vec_new (u8, len);
735   clib_memcpy (line, hc->rx_buf + hc->rx_buf_offset, len);
736   HTTP_DBG (0, "%v", line);
737
738   unformat_init_vector (&input, line);
739   if (!unformat (&input, "%lu", &hc->body_len))
740     {
741       clib_warning ("failed to unformat content length value");
742       *ec = HTTP_STATUS_BAD_REQUEST;
743       return -1;
744     }
745   unformat_free (&input);
746
747   hc->body_offset = hc->headers_offset + hc->headers_len + 2;
748   HTTP_DBG (0, "body length: %u", hc->body_len);
749   HTTP_DBG (0, "body offset: %u", hc->body_offset);
750
751   return 0;
752 }
753
754 static int
755 http_parse_header (http_conn_t *hc, int *content_length)
756 {
757   unformat_input_t input;
758   int i, len;
759   u8 *line;
760
761   i = v_find_index (hc->rx_buf, hc->rx_buf_offset, 0, CONTENT_LEN_STR);
762   if (i < 0)
763     {
764       clib_warning ("cannot find '%s' in the header!", CONTENT_LEN_STR);
765       return -1;
766     }
767
768   hc->rx_buf_offset = i;
769
770   i = v_find_index (hc->rx_buf, hc->rx_buf_offset, 0, "\n");
771   if (i < 0)
772     {
773       clib_warning ("end of line missing; incomplete data");
774       return -1;
775     }
776
777   len = i - hc->rx_buf_offset;
778   line = vec_new (u8, len);
779   clib_memcpy (line, hc->rx_buf + hc->rx_buf_offset, len);
780
781   unformat_init_vector (&input, line);
782   if (!unformat (&input, CONTENT_LEN_STR "%d", content_length))
783     {
784       clib_warning ("failed to unformat content length!");
785       return -1;
786     }
787   unformat_free (&input);
788
789   /* skip rest of the header */
790   hc->rx_buf_offset += len;
791   i = v_find_index (hc->rx_buf, hc->rx_buf_offset, 0, "<html>");
792   if (i < 0)
793     {
794       clib_warning ("<html> tag not found");
795       return -1;
796     }
797   hc->rx_buf_offset = i;
798
799   return 0;
800 }
801
802 static http_sm_result_t
803 http_state_wait_server_reply (http_conn_t *hc, transport_send_params_t *sp)
804 {
805   int i, rv, content_length;
806   http_msg_t msg = {};
807   app_worker_t *app_wrk;
808   session_t *as;
809
810   rv = http_read_message (hc);
811
812   /* Nothing yet, wait for data or timer expire */
813   if (rv)
814     {
815       HTTP_DBG (1, "no data to deq");
816       return HTTP_SM_STOP;
817     }
818
819   if (vec_len (hc->rx_buf) < 8)
820     {
821       clib_warning ("response buffer too short");
822       goto error;
823     }
824
825   if ((i = v_find_index (hc->rx_buf, 0, 0, "200 OK")) >= 0)
826     {
827       msg.type = HTTP_MSG_REPLY;
828       msg.content_type = HTTP_CONTENT_TEXT_HTML;
829       msg.code = HTTP_STATUS_OK;
830       msg.data.type = HTTP_MSG_DATA_INLINE;
831       msg.data.len = 0;
832
833       rv = http_parse_header (hc, &content_length);
834       if (rv)
835         {
836           clib_warning ("failed to parse http reply");
837           goto error;
838         }
839       msg.data.len = content_length;
840       u32 dlen = vec_len (hc->rx_buf) - hc->rx_buf_offset;
841       as = session_get_from_handle (hc->h_pa_session_handle);
842       svm_fifo_seg_t segs[2] = { { (u8 *) &msg, sizeof (msg) },
843                                  { &hc->rx_buf[hc->rx_buf_offset], dlen } };
844
845       rv = svm_fifo_enqueue_segments (as->rx_fifo, segs, 2,
846                                       0 /* allow partial */);
847       if (rv < 0)
848         {
849           clib_warning ("error enqueue");
850           return HTTP_SM_ERROR;
851         }
852
853       hc->rx_buf_offset += dlen;
854       hc->to_recv = content_length - dlen;
855
856       if (hc->rx_buf_offset == vec_len (hc->rx_buf))
857         {
858           vec_reset_length (hc->rx_buf);
859           hc->rx_buf_offset = 0;
860         }
861
862       if (hc->to_recv == 0)
863         {
864           hc->rx_buf_offset = 0;
865           vec_reset_length (hc->rx_buf);
866           http_state_change (hc, HTTP_STATE_WAIT_APP_METHOD);
867         }
868       else
869         {
870           http_state_change (hc, HTTP_STATE_CLIENT_IO_MORE_DATA);
871         }
872
873       app_wrk = app_worker_get_if_valid (as->app_wrk_index);
874       if (app_wrk)
875         app_worker_rx_notify (app_wrk, as);
876       return HTTP_SM_STOP;
877     }
878   else
879     {
880       clib_warning ("Unknown http method %v", hc->rx_buf);
881       goto error;
882     }
883
884 error:
885   session_transport_closing_notify (&hc->connection);
886   session_transport_closed_notify (&hc->connection);
887   http_disconnect_transport (hc);
888   return HTTP_SM_ERROR;
889 }
890
891 static http_sm_result_t
892 http_state_wait_client_method (http_conn_t *hc, transport_send_params_t *sp)
893 {
894   http_status_code_t ec;
895   app_worker_t *app_wrk;
896   http_msg_t msg;
897   session_t *as;
898   int rv;
899   u32 len;
900
901   rv = http_read_message (hc);
902
903   /* Nothing yet, wait for data or timer expire */
904   if (rv)
905     return HTTP_SM_STOP;
906
907   HTTP_DBG (0, "%v", hc->rx_buf);
908
909   if (vec_len (hc->rx_buf) < 8)
910     {
911       ec = HTTP_STATUS_BAD_REQUEST;
912       goto error;
913     }
914
915   rv = http_parse_request_line (hc, &ec);
916   if (rv)
917     goto error;
918
919   rv = http_identify_headers (hc, &ec);
920   if (rv)
921     goto error;
922
923   rv = http_identify_message_body (hc, &ec);
924   if (rv)
925     goto error;
926
927   len = vec_len (hc->rx_buf);
928
929   msg.type = HTTP_MSG_REQUEST;
930   msg.method_type = hc->method;
931   msg.content_type = HTTP_CONTENT_TEXT_HTML;
932   msg.data.type = HTTP_MSG_DATA_INLINE;
933   msg.data.len = len;
934   msg.data.target_form = hc->target_form;
935   msg.data.target_path_offset = hc->target_path_offset;
936   msg.data.target_path_len = hc->target_path_len;
937   msg.data.target_query_offset = hc->target_query_offset;
938   msg.data.target_query_len = hc->target_query_len;
939   msg.data.headers_offset = hc->headers_offset;
940   msg.data.headers_len = hc->headers_len;
941   msg.data.body_offset = hc->body_offset;
942   msg.data.body_len = hc->body_len;
943
944   svm_fifo_seg_t segs[2] = { { (u8 *) &msg, sizeof (msg) },
945                              { hc->rx_buf, len } };
946
947   as = session_get_from_handle (hc->h_pa_session_handle);
948   rv = svm_fifo_enqueue_segments (as->rx_fifo, segs, 2, 0 /* allow partial */);
949   if (rv < 0 || rv != sizeof (msg) + len)
950     {
951       clib_warning ("failed app enqueue");
952       /* This should not happen as we only handle 1 request per session,
953        * and fifo is allocated, but going forward we should consider
954        * rescheduling */
955       return HTTP_SM_ERROR;
956     }
957
958   vec_free (hc->rx_buf);
959   http_state_change (hc, HTTP_STATE_WAIT_APP_REPLY);
960
961   app_wrk = app_worker_get_if_valid (as->app_wrk_index);
962   if (app_wrk)
963     app_worker_rx_notify (app_wrk, as);
964
965   return HTTP_SM_STOP;
966
967 error:
968
969   http_send_error (hc, ec);
970   session_transport_closing_notify (&hc->connection);
971   http_disconnect_transport (hc);
972
973   return HTTP_SM_ERROR;
974 }
975
976 static http_sm_result_t
977 http_state_wait_app_reply (http_conn_t *hc, transport_send_params_t *sp)
978 {
979   http_main_t *hm = &http_main;
980   u8 *header;
981   u32 offset;
982   f64 now;
983   session_t *as;
984   http_status_code_t sc;
985   http_msg_t msg;
986   int rv;
987
988   as = session_get_from_handle (hc->h_pa_session_handle);
989
990   rv = svm_fifo_dequeue (as->tx_fifo, sizeof (msg), (u8 *) &msg);
991   ASSERT (rv == sizeof (msg));
992
993   if (msg.data.type > HTTP_MSG_DATA_PTR)
994     {
995       clib_warning ("no data");
996       sc = HTTP_STATUS_INTERNAL_ERROR;
997       goto error;
998     }
999
1000   if (msg.type != HTTP_MSG_REPLY)
1001     {
1002       clib_warning ("unexpected message type %d", msg.type);
1003       sc = HTTP_STATUS_INTERNAL_ERROR;
1004       goto error;
1005     }
1006
1007   http_buffer_init (&hc->tx_buf, msg_to_buf_type[msg.data.type], as->tx_fifo,
1008                     msg.data.len);
1009
1010   /*
1011    * Add headers. For now:
1012    * - current time
1013    * - expiration time
1014    * - server name
1015    * - content type
1016    * - data length
1017    */
1018   now = clib_timebase_now (&hm->timebase);
1019
1020   switch (msg.code)
1021     {
1022     case HTTP_STATUS_NOT_FOUND:
1023     case HTTP_STATUS_METHOD_NOT_ALLOWED:
1024     case HTTP_STATUS_BAD_REQUEST:
1025     case HTTP_STATUS_INTERNAL_ERROR:
1026     case HTTP_STATUS_FORBIDDEN:
1027     case HTTP_STATUS_OK:
1028       header =
1029         format (0, http_response_template, http_status_code_str[msg.code],
1030                 /* Date */
1031                 format_clib_timebase_time, now,
1032                 /* Expires */
1033                 format_clib_timebase_time, now + 600.0,
1034                 /* Server */
1035                 hc->app_name,
1036                 /* Content type */
1037                 http_content_type_str[msg.content_type],
1038                 /* Length */
1039                 msg.data.len);
1040       break;
1041     case HTTP_STATUS_MOVED:
1042       header =
1043         format (0, http_redirect_template, http_status_code_str[msg.code]);
1044       /* Location: http(s)://new-place already queued up as data */
1045       break;
1046     default:
1047       clib_warning ("unsupported status code: %d", msg.code);
1048       return HTTP_SM_ERROR;
1049     }
1050
1051   offset = http_send_data (hc, header, vec_len (header), 0);
1052   if (offset != vec_len (header))
1053     {
1054       clib_warning ("couldn't send response header!");
1055       sc = HTTP_STATUS_INTERNAL_ERROR;
1056       vec_free (header);
1057       goto error;
1058     }
1059   vec_free (header);
1060
1061   /* Start sending the actual data */
1062   http_state_change (hc, HTTP_STATE_APP_IO_MORE_DATA);
1063
1064   ASSERT (sp->max_burst_size >= offset);
1065   sp->max_burst_size -= offset;
1066   return HTTP_SM_CONTINUE;
1067
1068 error:
1069   clib_warning ("unexpected msg type from app %u", msg.type);
1070   http_send_error (hc, sc);
1071   http_state_change (hc, HTTP_STATE_WAIT_CLIENT_METHOD);
1072   session_transport_closing_notify (&hc->connection);
1073   http_disconnect_transport (hc);
1074   return HTTP_SM_STOP;
1075 }
1076
1077 static http_sm_result_t
1078 http_state_wait_app_method (http_conn_t *hc, transport_send_params_t *sp)
1079 {
1080   http_msg_t msg;
1081   session_t *as;
1082   u8 *buf = 0, *request;
1083   u32 offset;
1084   int rv;
1085
1086   as = session_get_from_handle (hc->h_pa_session_handle);
1087
1088   rv = svm_fifo_dequeue (as->tx_fifo, sizeof (msg), (u8 *) &msg);
1089   ASSERT (rv == sizeof (msg));
1090
1091   if (msg.data.type > HTTP_MSG_DATA_PTR)
1092     {
1093       clib_warning ("no data");
1094       goto error;
1095     }
1096
1097   if (msg.type != HTTP_MSG_REQUEST)
1098     {
1099       clib_warning ("unexpected message type %d", msg.type);
1100       goto error;
1101     }
1102
1103   /* currently we support only GET method */
1104   if (msg.method_type != HTTP_REQ_GET)
1105     {
1106       clib_warning ("unsupported method %d", msg.method_type);
1107       goto error;
1108     }
1109
1110   vec_validate (buf, msg.data.len - 1);
1111   rv = svm_fifo_dequeue (as->tx_fifo, msg.data.len, buf);
1112   ASSERT (rv == msg.data.len);
1113
1114   request = format (0, http_request_template, buf, hc->app_name);
1115   offset = http_send_data (hc, request, vec_len (request), 0);
1116   if (offset != vec_len (request))
1117     {
1118       clib_warning ("sending request failed!");
1119       goto error;
1120     }
1121
1122   http_state_change (hc, HTTP_STATE_WAIT_SERVER_REPLY);
1123
1124   vec_free (buf);
1125   vec_free (request);
1126
1127   return HTTP_SM_STOP;
1128
1129 error:
1130   svm_fifo_dequeue_drop_all (as->tx_fifo);
1131   session_transport_closing_notify (&hc->connection);
1132   session_transport_closed_notify (&hc->connection);
1133   http_disconnect_transport (hc);
1134   return HTTP_SM_ERROR;
1135 }
1136
1137 static http_sm_result_t
1138 http_state_client_io_more_data (http_conn_t *hc, transport_send_params_t *sp)
1139 {
1140   session_t *as, *ts;
1141   app_worker_t *app_wrk;
1142   svm_fifo_seg_t _seg, *seg = &_seg;
1143   u32 max_len, max_deq, max_enq, n_segs = 1;
1144   int rv, len;
1145
1146   as = session_get_from_handle (hc->h_pa_session_handle);
1147   ts = session_get_from_handle (hc->h_tc_session_handle);
1148
1149   max_deq = svm_fifo_max_dequeue (ts->rx_fifo);
1150   if (max_deq == 0)
1151     {
1152       HTTP_DBG (1, "no data to deq");
1153       return HTTP_SM_STOP;
1154     }
1155
1156   max_enq = svm_fifo_max_enqueue (as->rx_fifo);
1157   if (max_enq == 0)
1158     {
1159       HTTP_DBG (1, "app's rx fifo full");
1160       svm_fifo_add_want_deq_ntf (as->rx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
1161       return HTTP_SM_STOP;
1162     }
1163
1164   max_len = clib_min (max_enq, max_deq);
1165   len = svm_fifo_segments (ts->rx_fifo, 0, seg, &n_segs, max_len);
1166   if (len < 0)
1167     {
1168       HTTP_DBG (1, "svm_fifo_segments() len %d", len);
1169       return HTTP_SM_STOP;
1170     }
1171
1172   rv = svm_fifo_enqueue_segments (as->rx_fifo, seg, 1, 0 /* allow partial */);
1173   if (rv < 0)
1174     {
1175       clib_warning ("data enqueue failed, rv: %d", rv);
1176       return HTTP_SM_ERROR;
1177     }
1178
1179   svm_fifo_dequeue_drop (ts->rx_fifo, rv);
1180   if (rv > hc->to_recv)
1181     {
1182       clib_warning ("http protocol error: received more data than expected");
1183       session_transport_closing_notify (&hc->connection);
1184       http_disconnect_transport (hc);
1185       http_state_change (hc, HTTP_STATE_WAIT_APP_METHOD);
1186       return HTTP_SM_ERROR;
1187     }
1188   hc->to_recv -= rv;
1189   HTTP_DBG (1, "drained %d from ts; remains %d", rv, hc->to_recv);
1190
1191   if (hc->to_recv == 0)
1192     {
1193       hc->rx_buf_offset = 0;
1194       vec_reset_length (hc->rx_buf);
1195       http_state_change (hc, HTTP_STATE_WAIT_APP_METHOD);
1196     }
1197
1198   app_wrk = app_worker_get_if_valid (as->app_wrk_index);
1199   if (app_wrk)
1200     app_worker_rx_notify (app_wrk, as);
1201
1202   if (svm_fifo_max_dequeue_cons (ts->rx_fifo))
1203     session_enqueue_notify (ts);
1204
1205   return HTTP_SM_STOP;
1206 }
1207
1208 static http_sm_result_t
1209 http_state_app_io_more_data (http_conn_t *hc, transport_send_params_t *sp)
1210 {
1211   u32 max_send = 64 << 10, n_segs;
1212   http_buffer_t *hb = &hc->tx_buf;
1213   svm_fifo_seg_t *seg;
1214   session_t *ts;
1215   int sent = 0;
1216
1217   max_send = clib_min (max_send, sp->max_burst_size);
1218   ts = session_get_from_handle (hc->h_tc_session_handle);
1219   if ((seg = http_buffer_get_segs (hb, max_send, &n_segs)))
1220     sent = svm_fifo_enqueue_segments (ts->tx_fifo, seg, n_segs,
1221                                       1 /* allow partial */);
1222
1223   if (sent > 0)
1224     {
1225       /* Ask scheduler to notify app of deq event if needed */
1226       sp->bytes_dequeued += http_buffer_drain (hb, sent);
1227       sp->max_burst_size -= sent;
1228     }
1229
1230   /* Not finished sending all data */
1231   if (!http_buffer_is_drained (hb))
1232     {
1233       if (sent && svm_fifo_set_event (ts->tx_fifo))
1234         session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX);
1235
1236       if (svm_fifo_max_enqueue (ts->tx_fifo) < HTTP_FIFO_THRESH)
1237         {
1238           /* Deschedule http session and wait for deq notification if
1239            * underlying ts tx fifo almost full */
1240           svm_fifo_add_want_deq_ntf (ts->tx_fifo, SVM_FIFO_WANT_DEQ_NOTIF);
1241           transport_connection_deschedule (&hc->connection);
1242           sp->flags |= TRANSPORT_SND_F_DESCHED;
1243         }
1244     }
1245   else
1246     {
1247       if (sent && svm_fifo_set_event (ts->tx_fifo))
1248         session_send_io_evt_to_thread (ts->tx_fifo, SESSION_IO_EVT_TX_FLUSH);
1249
1250       /* Finished transaction, back to HTTP_STATE_WAIT_METHOD */
1251       http_state_change (hc, HTTP_STATE_WAIT_CLIENT_METHOD);
1252       http_buffer_free (&hc->tx_buf);
1253     }
1254
1255   return HTTP_SM_STOP;
1256 }
1257
1258 typedef http_sm_result_t (*http_sm_handler) (http_conn_t *,
1259                                              transport_send_params_t *sp);
1260
1261 static http_sm_handler state_funcs[HTTP_N_STATES] = {
1262   0, /* idle state */
1263   http_state_wait_app_method,
1264   http_state_wait_client_method,
1265   http_state_wait_server_reply,
1266   http_state_wait_app_reply,
1267   http_state_client_io_more_data,
1268   http_state_app_io_more_data,
1269 };
1270
1271 static void
1272 http_req_run_state_machine (http_conn_t *hc, transport_send_params_t *sp)
1273 {
1274   http_sm_result_t res;
1275
1276   do
1277     {
1278       res = state_funcs[hc->http_state](hc, sp);
1279       if (res == HTTP_SM_ERROR)
1280         {
1281           HTTP_DBG (1, "error in state machine %d", res);
1282           return;
1283         }
1284     }
1285   while (res == HTTP_SM_CONTINUE);
1286
1287   /* Reset the session expiration timer */
1288   http_conn_timer_update (hc);
1289 }
1290
1291 static int
1292 http_ts_rx_callback (session_t *ts)
1293 {
1294   http_conn_t *hc;
1295
1296   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
1297   if (!hc)
1298     {
1299       clib_warning ("http connection not found (ts %d)", ts->opaque);
1300       return -1;
1301     }
1302
1303   if (hc->state == HTTP_CONN_STATE_CLOSED)
1304     {
1305       svm_fifo_dequeue_drop_all (ts->tx_fifo);
1306       return 0;
1307     }
1308
1309   http_req_run_state_machine (hc, 0);
1310
1311   if (hc->state == HTTP_CONN_STATE_TRANSPORT_CLOSED)
1312     {
1313       if (!svm_fifo_max_dequeue_cons (ts->rx_fifo))
1314         session_transport_closing_notify (&hc->connection);
1315     }
1316   return 0;
1317 }
1318
1319 int
1320 http_ts_builtin_tx_callback (session_t *ts)
1321 {
1322   http_conn_t *hc;
1323
1324   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
1325   transport_connection_reschedule (&hc->connection);
1326
1327   return 0;
1328 }
1329
1330 static void
1331 http_ts_cleanup_callback (session_t *ts, session_cleanup_ntf_t ntf)
1332 {
1333   http_conn_t *hc;
1334
1335   if (ntf == SESSION_CLEANUP_TRANSPORT)
1336     return;
1337
1338   hc = http_conn_get_w_thread (ts->opaque, ts->thread_index);
1339   if (!hc)
1340     {
1341       clib_warning ("no http connection for %u", ts->session_index);
1342       return;
1343     }
1344
1345   vec_free (hc->rx_buf);
1346
1347   http_buffer_free (&hc->tx_buf);
1348   http_conn_timer_stop (hc);
1349
1350   session_transport_delete_notify (&hc->connection);
1351   http_conn_free (hc);
1352 }
1353
1354 int
1355 http_add_segment_callback (u32 client_index, u64 segment_handle)
1356 {
1357   /* No-op for builtin */
1358   return 0;
1359 }
1360
1361 int
1362 http_del_segment_callback (u32 client_index, u64 segment_handle)
1363 {
1364   return 0;
1365 }
1366
1367 static session_cb_vft_t http_app_cb_vft = {
1368   .session_accept_callback = http_ts_accept_callback,
1369   .session_disconnect_callback = http_ts_disconnect_callback,
1370   .session_connected_callback = http_ts_connected_callback,
1371   .session_reset_callback = http_ts_reset_callback,
1372   .session_cleanup_callback = http_ts_cleanup_callback,
1373   .add_segment_callback = http_add_segment_callback,
1374   .del_segment_callback = http_del_segment_callback,
1375   .builtin_app_rx_callback = http_ts_rx_callback,
1376   .builtin_app_tx_callback = http_ts_builtin_tx_callback,
1377 };
1378
1379 static clib_error_t *
1380 http_transport_enable (vlib_main_t *vm, u8 is_en)
1381 {
1382   vnet_app_detach_args_t _da, *da = &_da;
1383   vnet_app_attach_args_t _a, *a = &_a;
1384   u64 options[APP_OPTIONS_N_OPTIONS];
1385   http_main_t *hm = &http_main;
1386
1387   if (!is_en)
1388     {
1389       da->app_index = hm->app_index;
1390       da->api_client_index = APP_INVALID_INDEX;
1391       vnet_application_detach (da);
1392       return 0;
1393     }
1394
1395   vec_validate (hm->wrk, vlib_num_workers ());
1396
1397   clib_memset (a, 0, sizeof (*a));
1398   clib_memset (options, 0, sizeof (options));
1399
1400   a->session_cb_vft = &http_app_cb_vft;
1401   a->api_client_index = APP_INVALID_INDEX;
1402   a->options = options;
1403   a->name = format (0, "http");
1404   a->options[APP_OPTIONS_SEGMENT_SIZE] = hm->first_seg_size;
1405   a->options[APP_OPTIONS_ADD_SEGMENT_SIZE] = hm->add_seg_size;
1406   a->options[APP_OPTIONS_RX_FIFO_SIZE] = hm->fifo_size;
1407   a->options[APP_OPTIONS_TX_FIFO_SIZE] = hm->fifo_size;
1408   a->options[APP_OPTIONS_FLAGS] = APP_OPTIONS_FLAGS_IS_BUILTIN;
1409   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE;
1410   a->options[APP_OPTIONS_FLAGS] |= APP_OPTIONS_FLAGS_IS_TRANSPORT_APP;
1411
1412   if (vnet_application_attach (a))
1413     return clib_error_return (0, "failed to attach http app");
1414
1415   hm->app_index = a->app_index;
1416   vec_free (a->name);
1417
1418   clib_timebase_init (&hm->timebase, 0 /* GMT */, CLIB_TIMEBASE_DAYLIGHT_NONE,
1419                       &vm->clib_time /* share the system clock */);
1420
1421   http_timers_init (vm, http_conn_timeout_cb);
1422
1423   return 0;
1424 }
1425
1426 static int
1427 http_transport_connect (transport_endpoint_cfg_t *tep)
1428 {
1429   vnet_connect_args_t _cargs, *cargs = &_cargs;
1430   http_main_t *hm = &http_main;
1431   session_endpoint_cfg_t *sep = (session_endpoint_cfg_t *) tep;
1432   application_t *app;
1433   http_conn_t *hc;
1434   int error;
1435   u32 hc_index;
1436   app_worker_t *app_wrk = app_worker_get (sep->app_wrk_index);
1437
1438   clib_memset (cargs, 0, sizeof (*cargs));
1439   clib_memcpy (&cargs->sep_ext, sep, sizeof (session_endpoint_cfg_t));
1440   cargs->sep.transport_proto = TRANSPORT_PROTO_TCP;
1441   cargs->app_index = hm->app_index;
1442   app = application_get (app_wrk->app_index);
1443   cargs->sep_ext.ns_index = app->ns_index;
1444
1445   hc_index = http_conn_alloc_w_thread (0 /* ts->thread_index */);
1446   hc = http_conn_get_w_thread (hc_index, 0);
1447   hc->h_pa_wrk_index = sep->app_wrk_index;
1448   hc->h_pa_app_api_ctx = sep->opaque;
1449   hc->state = HTTP_CONN_STATE_CONNECTING;
1450   cargs->api_context = hc_index;
1451
1452   if (vec_len (app->name))
1453     hc->app_name = vec_dup (app->name);
1454   else
1455     hc->app_name = format (0, "VPP HTTP client");
1456
1457   HTTP_DBG (1, "hc ho_index %x", hc_index);
1458
1459   if ((error = vnet_connect (cargs)))
1460     return error;
1461
1462   return 0;
1463 }
1464
1465 static u32
1466 http_start_listen (u32 app_listener_index, transport_endpoint_cfg_t *tep)
1467 {
1468   vnet_listen_args_t _args = {}, *args = &_args;
1469   session_t *ts_listener, *app_listener;
1470   http_main_t *hm = &http_main;
1471   session_endpoint_cfg_t *sep;
1472   app_worker_t *app_wrk;
1473   transport_proto_t tp;
1474   app_listener_t *al;
1475   application_t *app;
1476   http_conn_t *lhc;
1477   u32 lhc_index;
1478
1479   sep = (session_endpoint_cfg_t *) tep;
1480
1481   app_wrk = app_worker_get (sep->app_wrk_index);
1482   app = application_get (app_wrk->app_index);
1483
1484   args->app_index = hm->app_index;
1485   args->sep_ext = *sep;
1486   args->sep_ext.ns_index = app->ns_index;
1487   tp = sep->ext_cfg ? TRANSPORT_PROTO_TLS : TRANSPORT_PROTO_TCP;
1488   args->sep_ext.transport_proto = tp;
1489
1490   if (vnet_listen (args))
1491     return SESSION_INVALID_INDEX;
1492
1493   lhc_index = http_listener_alloc ();
1494   lhc = http_listener_get (lhc_index);
1495
1496   /* Grab transport connection listener and link to http listener */
1497   lhc->h_tc_session_handle = args->handle;
1498   al = app_listener_get_w_handle (lhc->h_tc_session_handle);
1499   ts_listener = app_listener_get_session (al);
1500   ts_listener->opaque = lhc_index;
1501
1502   /* Grab application listener and link to http listener */
1503   app_listener = listen_session_get (app_listener_index);
1504   lhc->h_pa_wrk_index = sep->app_wrk_index;
1505   lhc->h_pa_session_handle = listen_session_get_handle (app_listener);
1506   lhc->c_s_index = app_listener_index;
1507   lhc->c_flags |= TRANSPORT_CONNECTION_F_NO_LOOKUP;
1508
1509   if (vec_len (app->name))
1510     lhc->app_name = vec_dup (app->name);
1511   else
1512     lhc->app_name = format (0, "VPP server app");
1513
1514   return lhc_index;
1515 }
1516
1517 static u32
1518 http_stop_listen (u32 listener_index)
1519 {
1520   http_conn_t *lhc;
1521   int rv;
1522
1523   lhc = http_listener_get (listener_index);
1524
1525   vnet_unlisten_args_t a = {
1526     .handle = lhc->h_tc_session_handle,
1527     .app_index = http_main.app_index,
1528     .wrk_map_index = 0 /* default wrk */
1529   };
1530
1531   if ((rv = vnet_unlisten (&a)))
1532     clib_warning ("unlisten returned %d", rv);
1533
1534   http_listener_free (lhc);
1535
1536   return 0;
1537 }
1538
1539 static void
1540 http_transport_close (u32 hc_index, u32 thread_index)
1541 {
1542   session_t *as;
1543   http_conn_t *hc;
1544
1545   HTTP_DBG (1, "App disconnecting %x", hc_index);
1546
1547   hc = http_conn_get_w_thread (hc_index, thread_index);
1548   if (hc->state == HTTP_CONN_STATE_CONNECTING)
1549     {
1550       hc->state = HTTP_CONN_STATE_APP_CLOSED;
1551       http_disconnect_transport (hc);
1552       return;
1553     }
1554   else if (hc->state == HTTP_CONN_STATE_CLOSED)
1555     {
1556       HTTP_DBG (1, "nothing to do, already closed");
1557       return;
1558     }
1559   as = session_get_from_handle (hc->h_pa_session_handle);
1560
1561   /* Nothing more to send, confirm close */
1562   if (!svm_fifo_max_dequeue_cons (as->tx_fifo))
1563     {
1564       session_transport_closed_notify (&hc->connection);
1565       http_disconnect_transport (hc);
1566     }
1567   else
1568     {
1569       /* Wait for all data to be written to ts */
1570       hc->state = HTTP_CONN_STATE_APP_CLOSED;
1571     }
1572 }
1573
1574 static transport_connection_t *
1575 http_transport_get_connection (u32 hc_index, u32 thread_index)
1576 {
1577   http_conn_t *hc = http_conn_get_w_thread (hc_index, thread_index);
1578   return &hc->connection;
1579 }
1580
1581 static transport_connection_t *
1582 http_transport_get_listener (u32 listener_index)
1583 {
1584   http_conn_t *lhc = http_listener_get (listener_index);
1585   return &lhc->connection;
1586 }
1587
1588 static int
1589 http_app_tx_callback (void *session, transport_send_params_t *sp)
1590 {
1591   session_t *as = (session_t *) session;
1592   u32 max_burst_sz, sent;
1593   http_conn_t *hc;
1594
1595   HTTP_DBG (1, "app session conn index %x", as->connection_index);
1596
1597   hc = http_conn_get_w_thread (as->connection_index, as->thread_index);
1598   if (!http_state_is_tx_valid (hc))
1599     {
1600       if (hc->state != HTTP_CONN_STATE_CLOSED)
1601         clib_warning ("app data req state '%U' session state %u",
1602                       format_http_state, hc->http_state, hc->state);
1603       svm_fifo_dequeue_drop_all (as->tx_fifo);
1604       return 0;
1605     }
1606
1607   max_burst_sz = sp->max_burst_size * TRANSPORT_PACER_MIN_MSS;
1608   sp->max_burst_size = max_burst_sz;
1609
1610   http_req_run_state_machine (hc, sp);
1611
1612   if (hc->state == HTTP_CONN_STATE_APP_CLOSED)
1613     {
1614       if (!svm_fifo_max_dequeue_cons (as->tx_fifo))
1615         http_disconnect_transport (hc);
1616     }
1617
1618   sent = max_burst_sz - sp->max_burst_size;
1619
1620   return sent > 0 ? clib_max (sent / TRANSPORT_PACER_MIN_MSS, 1) : 0;
1621 }
1622
1623 static void
1624 http_transport_get_endpoint (u32 hc_index, u32 thread_index,
1625                              transport_endpoint_t *tep, u8 is_lcl)
1626 {
1627   http_conn_t *hc = http_conn_get_w_thread (hc_index, thread_index);
1628   session_t *ts;
1629
1630   ts = session_get_from_handle (hc->h_tc_session_handle);
1631   session_get_endpoint (ts, tep, is_lcl);
1632 }
1633
1634 static u8 *
1635 format_http_connection (u8 *s, va_list *args)
1636 {
1637   http_conn_t *hc = va_arg (*args, http_conn_t *);
1638   session_t *ts;
1639
1640   ts = session_get_from_handle (hc->h_tc_session_handle);
1641   s = format (s, "[%d:%d][H] app_wrk %u ts %d:%d", hc->c_thread_index,
1642               hc->c_s_index, hc->h_pa_wrk_index, ts->thread_index,
1643               ts->session_index);
1644
1645   return s;
1646 }
1647
1648 static u8 *
1649 format_http_listener (u8 *s, va_list *args)
1650 {
1651   http_conn_t *lhc = va_arg (*args, http_conn_t *);
1652   app_listener_t *al;
1653   session_t *lts;
1654
1655   al = app_listener_get_w_handle (lhc->h_tc_session_handle);
1656   lts = app_listener_get_session (al);
1657   s = format (s, "[%d:%d][H] app_wrk %u ts %d:%d", lhc->c_thread_index,
1658               lhc->c_s_index, lhc->h_pa_wrk_index, lts->thread_index,
1659               lts->session_index);
1660
1661   return s;
1662 }
1663
1664 static u8 *
1665 format_http_conn_state (u8 *s, va_list *args)
1666 {
1667   http_conn_t *hc = va_arg (*args, http_conn_t *);
1668
1669   switch (hc->state)
1670     {
1671     case HTTP_CONN_STATE_LISTEN:
1672       s = format (s, "LISTEN");
1673       break;
1674     case HTTP_CONN_STATE_CONNECTING:
1675       s = format (s, "CONNECTING");
1676       break;
1677     case HTTP_CONN_STATE_ESTABLISHED:
1678       s = format (s, "ESTABLISHED");
1679       break;
1680     case HTTP_CONN_STATE_TRANSPORT_CLOSED:
1681       s = format (s, "TRANSPORT_CLOSED");
1682       break;
1683     case HTTP_CONN_STATE_APP_CLOSED:
1684       s = format (s, "APP_CLOSED");
1685       break;
1686     case HTTP_CONN_STATE_CLOSED:
1687       s = format (s, "CLOSED");
1688       break;
1689     }
1690
1691   return s;
1692 }
1693
1694 static u8 *
1695 format_http_transport_connection (u8 *s, va_list *args)
1696 {
1697   u32 tc_index = va_arg (*args, u32);
1698   u32 thread_index = va_arg (*args, u32);
1699   u32 verbose = va_arg (*args, u32);
1700   http_conn_t *hc;
1701
1702   hc = http_conn_get_w_thread (tc_index, thread_index);
1703
1704   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_http_connection, hc);
1705   if (verbose)
1706     {
1707       s =
1708         format (s, "%-" SESSION_CLI_STATE_LEN "U", format_http_conn_state, hc);
1709       if (verbose > 1)
1710         s = format (s, "\n");
1711     }
1712
1713   return s;
1714 }
1715
1716 static u8 *
1717 format_http_transport_listener (u8 *s, va_list *args)
1718 {
1719   u32 tc_index = va_arg (*args, u32);
1720   u32 __clib_unused thread_index = va_arg (*args, u32);
1721   u32 __clib_unused verbose = va_arg (*args, u32);
1722   http_conn_t *lhc = http_listener_get (tc_index);
1723
1724   s = format (s, "%-" SESSION_CLI_ID_LEN "U", format_http_listener, lhc);
1725   if (verbose)
1726     s =
1727       format (s, "%-" SESSION_CLI_STATE_LEN "U", format_http_conn_state, lhc);
1728   return s;
1729 }
1730
1731 static const transport_proto_vft_t http_proto = {
1732   .enable = http_transport_enable,
1733   .connect = http_transport_connect,
1734   .start_listen = http_start_listen,
1735   .stop_listen = http_stop_listen,
1736   .close = http_transport_close,
1737   .custom_tx = http_app_tx_callback,
1738   .get_connection = http_transport_get_connection,
1739   .get_listener = http_transport_get_listener,
1740   .get_transport_endpoint = http_transport_get_endpoint,
1741   .format_connection = format_http_transport_connection,
1742   .format_listener = format_http_transport_listener,
1743   .transport_options = {
1744     .name = "http",
1745     .short_name = "H",
1746     .tx_type = TRANSPORT_TX_INTERNAL,
1747     .service_type = TRANSPORT_SERVICE_APP,
1748   },
1749 };
1750
1751 static clib_error_t *
1752 http_transport_init (vlib_main_t *vm)
1753 {
1754   http_main_t *hm = &http_main;
1755
1756   transport_register_protocol (TRANSPORT_PROTO_HTTP, &http_proto,
1757                                FIB_PROTOCOL_IP4, ~0);
1758   transport_register_protocol (TRANSPORT_PROTO_HTTP, &http_proto,
1759                                FIB_PROTOCOL_IP6, ~0);
1760
1761   /* Default values, configurable via startup conf */
1762   hm->add_seg_size = 256 << 20;
1763   hm->first_seg_size = 32 << 20;
1764   hm->fifo_size = 512 << 10;
1765
1766   return 0;
1767 }
1768
1769 VLIB_INIT_FUNCTION (http_transport_init);
1770
1771 static clib_error_t *
1772 http_config_fn (vlib_main_t *vm, unformat_input_t *input)
1773 {
1774   http_main_t *hm = &http_main;
1775   uword mem_sz;
1776
1777   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1778     {
1779       if (unformat (input, "first-segment-size %U", unformat_memory_size,
1780                     &mem_sz))
1781         {
1782           hm->first_seg_size = clib_max (mem_sz, 1 << 20);
1783           if (hm->first_seg_size != mem_sz)
1784             clib_warning ("first seg size too small %u", mem_sz);
1785         }
1786       else if (unformat (input, "add-segment-size %U", unformat_memory_size,
1787                          &mem_sz))
1788         {
1789           hm->add_seg_size = clib_max (mem_sz, 1 << 20);
1790           if (hm->add_seg_size != mem_sz)
1791             clib_warning ("add seg size too small %u", mem_sz);
1792         }
1793       else if (unformat (input, "fifo-size %U", unformat_memory_size, &mem_sz))
1794         {
1795           hm->fifo_size = clib_clamp (mem_sz, 4 << 10, 2 << 30);
1796           if (hm->fifo_size != mem_sz)
1797             clib_warning ("invalid fifo size %lu", mem_sz);
1798         }
1799       else
1800         return clib_error_return (0, "unknown input `%U'",
1801                                   format_unformat_error, input);
1802     }
1803   return 0;
1804 }
1805
1806 VLIB_CONFIG_FUNCTION (http_config_fn, "http");
1807
1808 VLIB_PLUGIN_REGISTER () = {
1809   .version = VPP_BUILD_VER,
1810   .description = "Hypertext Transfer Protocol (HTTP)",
1811   .default_disabled = 0,
1812 };
1813
1814 /*
1815  * fd.io coding-style-patch-verification: ON
1816  *
1817  * Local Variables:
1818  * eval: (c-set-style "gnu")
1819  * End:
1820  */