-
Notifications
You must be signed in to change notification settings - Fork 790
/
HttpSM.cc
8190 lines (7127 loc) · 296 KB
/
HttpSM.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @file
HTTP state machine
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "../ProxyTransaction.h"
#include "HttpSM.h"
#include "HttpTransact.h"
#include "HttpTransactHeaders.h"
#include "ProxyConfig.h"
#include "Http1ServerSession.h"
#include "HttpDebugNames.h"
#include "HttpSessionManager.h"
#include "P_Cache.h"
#include "P_Net.h"
#include "StatPages.h"
#include "Log.h"
#include "LogAccess.h"
#include "PluginVC.h"
#include "ReverseProxy.h"
#include "RemapProcessor.h"
#include "Transform.h"
#include "P_SSLConfig.h"
#include "P_SSLSNI.h"
#include "HttpPages.h"
#include "IPAllow.h"
#include "tscore/I_Layout.h"
#include "tscore/bwf_std_format.h"
#include "ts/sdt.h"
#include <openssl/ossl_typ.h>
#include <openssl/ssl.h>
#include <algorithm>
#include <atomic>
#include <logging/Log.h>
#define DEFAULT_RESPONSE_BUFFER_SIZE_INDEX 6 // 8K
#define DEFAULT_REQUEST_BUFFER_SIZE_INDEX 6 // 8K
#define MIN_CONFIG_BUFFER_SIZE_INDEX 5 // 4K
#define hsm_release_assert(EX) \
{ \
if (!(EX)) { \
this->dump_state_on_assert(); \
_ink_assert(#EX, __FILE__, __LINE__); \
} \
}
/*
* Comment this off if you don't
* want httpSM to use new_empty_MIOBuffer(..) call
*/
#define USE_NEW_EMPTY_MIOBUFFER
extern int cache_config_read_while_writer;
// We have a debugging list that can use to find stuck
// state machines
DList(HttpSM, debug_link) debug_sm_list;
ink_mutex debug_sm_list_mutex;
static const int sub_header_size = sizeof("Content-type: ") - 1 + 2 + sizeof("Content-range: bytes ") - 1 + 4;
static const int boundary_size = 2 + sizeof("RANGE_SEPARATOR") - 1 + 2;
static const char *str_100_continue_response = "HTTP/1.1 100 Continue\r\n\r\n";
static const int len_100_continue_response = strlen(str_100_continue_response);
// Handy typedef for short (single line) message generation.
using lbw = ts::LocalBufferWriter<256>;
namespace
{
/// Update the milestone state given the milestones and timer.
inline void
milestone_update_api_time(TransactionMilestones &milestones, ink_hrtime &api_timer)
{
// Bit of funkiness - we set @a api_timer to be the negative value when we're tracking
// non-active API time. In that case we need to make a note of it and flip the value back
// to positive.
if (api_timer) {
ink_hrtime delta;
bool active = api_timer >= 0;
if (!active) {
api_timer = -api_timer;
}
delta = Thread::get_hrtime_updated() - api_timer;
api_timer = 0;
// Zero or negative time is a problem because we want to signal *something* happened
// vs. no API activity at all. This can happen due to graininess or real time
// clock adjustment.
if (delta <= 0) {
delta = 1;
}
if (0 == milestones[TS_MILESTONE_PLUGIN_TOTAL]) {
milestones[TS_MILESTONE_PLUGIN_TOTAL] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_TOTAL] += delta;
if (active) {
if (0 == milestones[TS_MILESTONE_PLUGIN_ACTIVE]) {
milestones[TS_MILESTONE_PLUGIN_ACTIVE] = milestones[TS_MILESTONE_SM_START];
}
milestones[TS_MILESTONE_PLUGIN_ACTIVE] += delta;
}
}
}
// Unique state machine identifier
std::atomic<int64_t> next_sm_id(0);
} // namespace
ClassAllocator<HttpSM> httpSMAllocator("httpSMAllocator");
HttpVCTable::HttpVCTable(HttpSM *mysm)
{
memset(&vc_table, 0, sizeof(vc_table));
sm = mysm;
}
HttpVCTableEntry *
HttpVCTable::new_entry()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == nullptr) {
vc_table[i].sm = sm;
return vc_table + i;
}
}
ink_release_assert(0);
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VConnection *vc)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc == vc) {
return vc_table + i;
}
}
return nullptr;
}
HttpVCTableEntry *
HttpVCTable::find_entry(VIO *vio)
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].read_vio == vio || vc_table[i].write_vio == vio) {
ink_assert(vc_table[i].vc != nullptr);
return vc_table + i;
}
}
return nullptr;
}
// bool HttpVCTable::remove_entry(HttpVCEntry* e)
//
// Deallocates all buffers from the associated
// entry and re-initializes it's other fields
// for reuse
//
void
HttpVCTable::remove_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc == nullptr || e->in_tunnel);
e->vc = nullptr;
e->eos = false;
if (e->read_buffer) {
free_MIOBuffer(e->read_buffer);
e->read_buffer = nullptr;
}
if (e->write_buffer) {
free_MIOBuffer(e->write_buffer);
e->write_buffer = nullptr;
}
// Cannot reach in to checkout the netvc
// for remaining I/O operations because the netvc
// may have been deleted at this point and the pointer
// could be stale.
e->read_vio = nullptr;
e->write_vio = nullptr;
e->vc_handler = nullptr;
e->vc_type = HTTP_UNKNOWN;
e->in_tunnel = false;
}
// bool HttpVCTable::cleanup_entry(HttpVCEntry* e)
//
// Closes the associate vc for the entry,
// and the call remove_entry
//
void
HttpVCTable::cleanup_entry(HttpVCTableEntry *e)
{
ink_assert(e->vc);
if (e->in_tunnel == false) {
// Update stats
switch (e->vc_type) {
case HTTP_UA_VC:
// proxy.process.http.current_client_transactions is decremented in HttpSM::destroy
break;
default:
// This covers:
// HTTP_UNKNOWN, HTTP_SERVER_VC, HTTP_TRANSFORM_VC, HTTP_CACHE_READ_VC,
// HTTP_CACHE_WRITE_VC, HTTP_RAW_SERVER_VC
break;
}
e->vc->do_io_close();
e->vc = nullptr;
}
remove_entry(e);
}
void
HttpVCTable::cleanup_all()
{
for (int i = 0; i < vc_table_max_entries; i++) {
if (vc_table[i].vc != nullptr) {
cleanup_entry(vc_table + i);
}
}
}
#define SMDebug(tag, ...) SpecificDebug(debug_on, tag, __VA_ARGS__)
#define REMEMBER(e, r) \
{ \
history.push_back(MakeSourceLocation(), e, r); \
}
#ifdef STATE_ENTER
#undef STATE_ENTER
#endif
#define STATE_ENTER(state_name, event) \
{ \
/*ink_assert (magic == HTTP_SM_MAGIC_ALIVE); */ REMEMBER(event, reentrancy_count); \
SMDebug("http", "[%" PRId64 "] [%s, %s]", sm_id, #state_name, HttpDebugNames::get_event_name(event)); \
}
#define HTTP_SM_SET_DEFAULT_HANDLER(_h) \
{ \
REMEMBER(NO_EVENT, reentrancy_count); \
default_handler = _h; \
}
/*
* Helper functions to ensure that the parallel
* API set timeouts are set consistenly with the records.config settings
*/
void
HttpSM::set_server_netvc_inactivity_timeout(NetVConnection *netvc)
{
if (netvc) {
if (t_state.api_txn_no_activity_timeout_value != -1) {
netvc->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_no_activity_timeout_value));
} else {
netvc->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_out));
}
}
}
void
HttpSM::set_server_netvc_active_timeout(NetVConnection *netvc)
{
if (netvc) {
if (t_state.api_txn_active_timeout_value != -1) {
netvc->set_active_timeout(HRTIME_MSECONDS(t_state.api_txn_active_timeout_value));
} else {
netvc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_out));
}
}
}
void
HttpSM::set_server_netvc_connect_timeout(NetVConnection *netvc)
{
if (netvc) {
if (t_state.api_txn_connect_timeout_value != -1) {
netvc->set_inactivity_timeout(HRTIME_MSECONDS(t_state.api_txn_connect_timeout_value));
} else {
int connect_timeout;
if (t_state.method == HTTP_WKSIDX_POST || t_state.method == HTTP_WKSIDX_PUT) {
connect_timeout = t_state.txn_conf->post_connect_attempts_timeout;
} else if (t_state.current.server == &t_state.parent_info) {
connect_timeout = t_state.txn_conf->parent_connect_timeout;
} else {
connect_timeout = t_state.txn_conf->connect_attempts_timeout;
}
netvc->set_inactivity_timeout(HRTIME_SECONDS(connect_timeout));
}
}
}
HttpSM::HttpSM() : Continuation(nullptr), vc_table(this) {}
void
HttpSM::cleanup()
{
t_state.destroy();
api_hooks.clear();
http_parser_clear(&http_parser);
HttpConfig::release(t_state.http_config_param);
m_remap->release();
mutex.clear();
tunnel.mutex.clear();
cache_sm.mutex.clear();
transform_cache_sm.mutex.clear();
magic = HTTP_SM_MAGIC_DEAD;
debug_on = false;
}
void
HttpSM::destroy()
{
cleanup();
httpSMAllocator.free(this);
}
void
HttpSM::init(bool from_early_data)
{
milestones[TS_MILESTONE_SM_START] = Thread::get_hrtime();
_from_early_data = from_early_data;
magic = HTTP_SM_MAGIC_ALIVE;
// Unique state machine identifier
sm_id = next_sm_id++;
t_state.state_machine_id = sm_id;
t_state.state_machine = this;
t_state.http_config_param = HttpConfig::acquire();
// Acquire a lease on the global remap / rewrite table (stupid global name ...)
m_remap = rewrite_table->acquire();
// Simply point to the global config for the time being, no need to copy this
// entire struct if nothing is going to change it.
t_state.txn_conf = &t_state.http_config_param->oride;
t_state.init();
http_parser_init(&http_parser);
// Added to skip dns if the document is in cache. DNS will be forced if there is a ip based ACL in
// cache control or parent.config or if the doc_in_cache_skip_dns is disabled or if http caching is disabled
// TODO: This probably doesn't honor this as a per-transaction overridable config.
t_state.force_dns = (ip_rule_in_CacheControlTable() || t_state.parent_params->parent_table->ipMatch ||
!(t_state.txn_conf->doc_in_cache_skip_dns) || !(t_state.txn_conf->cache_http));
SET_HANDLER(&HttpSM::main_handler);
// Remember where this SM is running so it gets returned correctly
this->setThreadAffinity(this_ethread());
#ifdef USE_HTTP_DEBUG_LISTS
ink_mutex_acquire(&debug_sm_list_mutex);
debug_sm_list.push(this);
ink_mutex_release(&debug_sm_list_mutex);
#endif
}
void
HttpSM::set_ua_half_close_flag()
{
ua_txn->set_half_close_flag(true);
}
inline int
HttpSM::do_api_callout()
{
if (hooks_set) {
return do_api_callout_internal();
} else {
handle_api_return();
return 0;
}
}
int
HttpSM::state_add_to_list(int event, void * /* data ATS_UNUSED */)
{
// The list if for stat pages and general debugging
// The config variable exists mostly to allow us to
// measure an performance drop during benchmark runs
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_add_to_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = (static_cast<unsigned int>(sm_id) % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
// the client_vc`s timeout events can be triggered, so we should not
// reschedule the http_sm when the lock is not acquired.
// FIXME: the sm_list may miss some http_sms when the lock contention
if (lock.is_locked()) {
HttpSMList[bucket].sm_list.push(this);
}
}
t_state.api_next_action = HttpTransact::SM_ACTION_API_SM_START;
if (do_api_callout() < 0) {
// Didn't get the hook continuation lock. Clear the read and wait for next event
if (ua_entry->read_vio) {
// Seems like ua_entry->read_vio->disable(); should work, but that was
// not sufficient to stop the state machine from processing IO events until the
// TXN_START hooks had completed
ua_entry->read_vio = ua_entry->vc->do_io_read(nullptr, 0, nullptr);
}
return EVENT_CONT;
}
return EVENT_DONE;
}
int
HttpSM::state_remove_from_list(int event, void * /* data ATS_UNUSED */)
{
// The config parameters are guaranteed not change
// across the life of a transaction so it safe to
// check the config here and use it determine
// whether we need to strip ourselves off of the
// state page list
if (t_state.http_config_param->enable_http_info) {
STATE_ENTER(&HttpSM::state_remove_from_list, event);
ink_assert(event == EVENT_NONE || event == EVENT_INTERVAL);
int bucket = (static_cast<unsigned int>(sm_id) % HTTP_LIST_BUCKETS);
MUTEX_TRY_LOCK(lock, HttpSMList[bucket].mutex, mutex->thread_holding);
if (!lock.is_locked()) {
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::state_remove_from_list);
mutex->thread_holding->schedule_in(this, HTTP_LIST_RETRY);
return EVENT_DONE;
}
HttpSMList[bucket].sm_list.remove(this);
}
return this->kill_this_async_hook(EVENT_NONE, nullptr);
}
int
HttpSM::kill_this_async_hook(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */)
{
// In the base HttpSM, we don't have anything to
// do here. subclasses can override this function
// to do their own asynchronous cleanup
// So We're now ready to finish off the state machine
terminate_sm = true;
kill_this_async_done = true;
return EVENT_DONE;
}
void
HttpSM::start_sub_sm()
{
tunnel.init(this, mutex);
cache_sm.init(this, mutex);
transform_cache_sm.init(this, mutex);
}
void
HttpSM::attach_client_session(ProxyTransaction *client_vc, IOBufferReader *buffer_reader)
{
milestones[TS_MILESTONE_UA_BEGIN] = Thread::get_hrtime();
ink_assert(client_vc != nullptr);
NetVConnection *netvc = client_vc->get_netvc();
if (!netvc) {
return;
}
ua_txn = client_vc;
// It seems to be possible that the ua_txn pointer will go stale before log entries for this HTTP transaction are
// generated. Therefore, collect information that may be needed for logging from the ua_txn object at this point.
//
_client_transaction_id = ua_txn->get_transaction_id();
_client_transaction_priority_weight = ua_txn->get_transaction_priority_weight();
_client_transaction_priority_dependence = ua_txn->get_transaction_priority_dependence();
{
auto p = ua_txn->get_proxy_ssn();
if (p) {
_client_connection_id = p->connection_id();
}
}
// Collect log & stats information. We've already verified that the netvc is !nullptr above,
// and netvc == ua_txn->get_netvc().
SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc);
is_internal = netvc->get_is_internal_request();
mptcp_state = netvc->get_mptcp_state();
client_tcp_reused = !(ua_txn->is_first_transaction());
if (ssl_vc != nullptr) {
client_connection_is_ssl = true;
client_ssl_reused = ssl_vc->getSSLSessionCacheHit();
const char *protocol = ssl_vc->getSSLProtocol();
client_sec_protocol = protocol ? protocol : "-";
const char *cipher = ssl_vc->getSSLCipherSuite();
client_cipher_suite = cipher ? cipher : "-";
const char *curve = ssl_vc->getSSLCurve();
client_curve = curve ? curve : "-";
if (!client_tcp_reused) {
// Copy along the TLS handshake timings
milestones[TS_MILESTONE_TLS_HANDSHAKE_START] = ssl_vc->sslHandshakeBeginTime;
milestones[TS_MILESTONE_TLS_HANDSHAKE_END] = ssl_vc->sslHandshakeEndTime;
}
}
const char *protocol_str = client_vc->get_protocol_string();
client_protocol = protocol_str ? protocol_str : "-";
ink_release_assert(ua_txn->get_half_close_flag() == false);
mutex = client_vc->mutex;
if (ua_txn->debug()) {
debug_on = true;
}
t_state.setup_per_txn_configs();
ink_assert(ua_txn->get_proxy_ssn());
ink_assert(ua_txn->get_proxy_ssn()->accept_options);
// default the upstream IP style host resolution order from inbound
t_state.my_txn_conf().host_res_data.order = ua_txn->get_proxy_ssn()->accept_options->host_res_preference;
start_sub_sm();
// Allocate a user agent entry in the state machine's
// vc table
ua_entry = vc_table.new_entry();
ua_entry->vc = client_vc;
ua_entry->vc_type = HTTP_UA_VC;
ats_ip_copy(&t_state.client_info.src_addr, netvc->get_remote_addr());
ats_ip_copy(&t_state.client_info.dst_addr, netvc->get_local_addr());
t_state.client_info.is_transparent = netvc->get_is_transparent();
t_state.client_info.port_attribute = static_cast<HttpProxyPort::TransportType>(netvc->attributes);
// Record api hook set state
hooks_set = client_vc->has_hooks();
// Setup for parsing the header
ua_buffer_reader = buffer_reader;
ua_entry->vc_handler = &HttpSM::state_read_client_request_header;
t_state.hdr_info.client_request.destroy();
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
// Prepare raw reader which will live until we are sure this is HTTP indeed
if (is_transparent_passthrough_allowed() || (ssl_vc && ssl_vc->decrypt_tunnel())) {
ua_raw_buffer_reader = buffer_reader->clone();
}
// We first need to run the transaction start hook. Since
// this hook maybe asynchronous, we need to disable IO on
// client but set the continuation to be the state machine
// so if we get an timeout events the sm handles them
ua_entry->read_vio = client_vc->do_io_read(this, 0, buffer_reader->mbuf);
ua_entry->write_vio = client_vc->do_io_write(this, 0, nullptr);
/////////////////////////
// set up timeouts //
/////////////////////////
client_vc->set_inactivity_timeout(HRTIME_SECONDS(t_state.http_config_param->accept_no_activity_timeout));
client_vc->set_active_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_active_timeout_in));
++reentrancy_count;
// Add our state sm to the sm list
state_add_to_list(EVENT_NONE, nullptr);
// This is another external entry point and it is possible for the state machine to get terminated
// while down the call chain from @c state_add_to_list. So we need to use the reentrancy_count to
// prevent cleanup there and do it here as we return to the external caller.
if (terminate_sm == true && reentrancy_count == 1) {
kill_this();
} else {
--reentrancy_count;
ink_assert(reentrancy_count >= 0);
}
}
void
HttpSM::setup_client_read_request_header()
{
ink_assert(ua_entry->vc_handler == &HttpSM::state_read_client_request_header);
ua_entry->read_vio = ua_txn->do_io_read(this, INT64_MAX, ua_buffer_reader->mbuf);
// The header may already be in the buffer if this
// a request from a keep-alive connection
handleEvent(VC_EVENT_READ_READY, ua_entry->read_vio);
}
void
HttpSM::setup_blind_tunnel_port()
{
NetVConnection *netvc = ua_txn->get_netvc();
ink_release_assert(netvc);
int host_len;
if (SSLNetVConnection *ssl_vc = dynamic_cast<SSLNetVConnection *>(netvc)) {
if (!t_state.hdr_info.client_request.url_get()->host_get(&host_len)) {
// the URL object has not been created in the start of the transaction. Hence, we need to create the URL here
URL u;
t_state.hdr_info.client_request.create(HTTP_TYPE_REQUEST);
t_state.hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
t_state.hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
t_state.hdr_info.client_request.url_set(&u);
if (ssl_vc->has_tunnel_destination()) {
const char *tunnel_host = ssl_vc->get_tunnel_host();
t_state.hdr_info.client_request.url_get()->host_set(tunnel_host, strlen(tunnel_host));
if (ssl_vc->get_tunnel_port() > 0) {
t_state.hdr_info.client_request.url_get()->port_set(ssl_vc->get_tunnel_port());
} else {
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
} else {
t_state.hdr_info.client_request.url_get()->host_set(ssl_vc->get_server_name(), strlen(ssl_vc->get_server_name()));
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
}
} else {
char new_host[INET6_ADDRSTRLEN];
ats_ip_ntop(netvc->get_local_addr(), new_host, sizeof(new_host));
t_state.hdr_info.client_request.url_get()->host_set(new_host, strlen(new_host));
t_state.hdr_info.client_request.url_get()->port_set(netvc->get_local_port());
}
call_transact_and_set_next_state(HttpTransact::HandleBlindTunnel);
}
int
HttpSM::state_read_client_request_header(int event, void *data)
{
STATE_ENTER(&HttpSM::state_read_client_request_header, event);
ink_assert(ua_entry->read_vio == (VIO *)data);
ink_assert(server_entry == nullptr);
ink_assert(server_session == nullptr);
int bytes_used = 0;
ink_assert(ua_entry->eos == false);
NetVConnection *netvc = ua_txn->get_netvc();
if (!netvc && event != VC_EVENT_EOS) {
return 0;
}
switch (event) {
case VC_EVENT_READ_READY:
case VC_EVENT_READ_COMPLETE:
// More data to parse
break;
case VC_EVENT_EOS:
ua_entry->eos = true;
if ((client_request_hdr_bytes > 0) && is_transparent_passthrough_allowed() && (ua_raw_buffer_reader != nullptr)) {
break;
}
// Fall through
case VC_EVENT_ERROR:
case VC_EVENT_INACTIVITY_TIMEOUT:
case VC_EVENT_ACTIVE_TIMEOUT:
// The user agent is hosed. Close it &
// bail on the state machine
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
return 0;
}
// Reset the inactivity timeout if this is the first
// time we've been called. The timeout had been set to
// the accept timeout by the ProxyTransaction
//
if ((ua_buffer_reader->read_avail() > 0) && (client_request_hdr_bytes == 0)) {
milestones[TS_MILESTONE_UA_FIRST_READ] = Thread::get_hrtime();
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
}
/////////////////////
// tokenize header //
/////////////////////
ParseResult state = t_state.hdr_info.client_request.parse_req(
&http_parser, ua_buffer_reader, &bytes_used, ua_entry->eos, t_state.http_config_param->strict_uri_parsing,
t_state.http_config_param->http_request_line_max_size, t_state.http_config_param->http_hdr_field_max_size);
client_request_hdr_bytes += bytes_used;
// Check to see if we are over the hdr size limit
if (client_request_hdr_bytes > t_state.txn_conf->request_hdr_max_size) {
SMDebug("http", "client header bytes were over max header size; treating as a bad request");
state = PARSE_RESULT_ERROR;
}
// We need to handle EOS as well as READ_READY because the client
// may have sent all of the data already followed by a FIN and that
// should be OK.
if (ua_raw_buffer_reader != nullptr) {
bool do_blind_tunnel = false;
// If we had a parse error and we're done reading data
// blind tunnel
if ((event == VC_EVENT_READ_READY || event == VC_EVENT_EOS) && state == PARSE_RESULT_ERROR) {
do_blind_tunnel = true;
// If we had a GET request that has data after the
// get request, do blind tunnel
} else if (state == PARSE_RESULT_DONE && t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_GET &&
ua_buffer_reader->read_avail() > 0 && !t_state.hdr_info.client_request.is_keep_alive_set()) {
do_blind_tunnel = true;
}
if (do_blind_tunnel) {
SMDebug("http", "[%" PRId64 "] first request on connection failed parsing, switching to passthrough.", sm_id);
t_state.transparent_passthrough = true;
http_parser_clear(&http_parser);
// Turn off read eventing until we get the
// blind tunnel infrastructure set up
if (netvc) {
netvc->do_io_read(nullptr, 0, nullptr);
}
/* establish blind tunnel */
setup_blind_tunnel_port();
// Setting half close means we will send the FIN when we've written all of the data.
if (event == VC_EVENT_EOS) {
this->set_ua_half_close_flag();
t_state.client_info.keep_alive = HTTP_NO_KEEPALIVE;
}
return 0;
}
}
// Check to see if we are done parsing the header
if (state != PARSE_RESULT_CONT || ua_entry->eos || (state == PARSE_RESULT_CONT && event == VC_EVENT_READ_COMPLETE)) {
if (ua_raw_buffer_reader != nullptr) {
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
http_parser_clear(&http_parser);
ua_entry->vc_handler = &HttpSM::state_watch_for_client_abort;
milestones[TS_MILESTONE_UA_READ_HEADER_DONE] = Thread::get_hrtime();
}
switch (state) {
case PARSE_RESULT_ERROR:
SMDebug("http", "[%" PRId64 "] error parsing client request header", sm_id);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
(bytes_used > t_state.http_config_param->http_request_line_max_size) ?
t_state.http_return_code = HTTP_STATUS_REQUEST_URI_TOO_LONG :
t_state.http_return_code = HTTP_STATUS_NONE;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
case PARSE_RESULT_CONT:
if (ua_entry->eos) {
SMDebug("http_seq", "[%" PRId64 "] EOS before client request parsing finished", sm_id);
set_ua_abort(HttpTransact::ABORTED, event);
// Disable further I/O on the client
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
call_transact_and_set_next_state(HttpTransact::BadRequest);
break;
} else if (event == VC_EVENT_READ_COMPLETE) {
SMDebug("http_parse", "[%" PRId64 "] VC_EVENT_READ_COMPLETE and PARSE CONT state", sm_id);
break;
} else {
if (is_transparent_passthrough_allowed() && ua_raw_buffer_reader != nullptr &&
ua_raw_buffer_reader->get_current_block()->write_avail() <= 0) {
// Disable passthrough regardless of eventual parsing failure or success -- otherwise
// we either have to consume some data or risk blocking the writer.
ua_raw_buffer_reader->dealloc();
ua_raw_buffer_reader = nullptr;
}
ua_entry->read_vio->reenable();
return VC_EVENT_CONT;
}
case PARSE_RESULT_DONE:
SMDebug("http", "[%" PRId64 "] done parsing client request header", sm_id);
if (_from_early_data) {
// Only allow early data for safe methods defined in RFC7231 Section 4.2.1.
// https://tools.ietf.org/html/rfc7231#section-4.2.1
SMDebug("ssl_early_data", "%d", t_state.hdr_info.client_request.method_get_wksidx());
if (!HttpTransactHeaders::is_method_safe(t_state.hdr_info.client_request.method_get_wksidx())) {
SMDebug("http", "client request was from early data but is NOT safe");
call_transact_and_set_next_state(HttpTransact::TooEarly);
return 0;
} else if (!SSLConfigParams::server_allow_early_data_params &&
(t_state.hdr_info.client_request.m_http->u.req.m_url_impl->m_len_params > 0 ||
t_state.hdr_info.client_request.m_http->u.req.m_url_impl->m_len_query > 0)) {
SMDebug("http", "client request was from early data but HAS parameters");
call_transact_and_set_next_state(HttpTransact::TooEarly);
return 0;
}
t_state.hdr_info.client_request.mark_early_data();
}
ua_txn->set_session_active();
if (t_state.hdr_info.client_request.version_get() == HTTPVersion(1, 1) &&
(t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_POST ||
t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_PUT) &&
t_state.http_config_param->send_100_continue_response) {
int len = 0;
const char *expect = t_state.hdr_info.client_request.value_get(MIME_FIELD_EXPECT, MIME_LEN_EXPECT, &len);
// When receive an "Expect: 100-continue" request from client, ATS sends a "100 Continue" response to client
// immediately, before receive the real response from original server.
if ((len == HTTP_LEN_100_CONTINUE) && (strncasecmp(expect, HTTP_VALUE_100_CONTINUE, HTTP_LEN_100_CONTINUE) == 0)) {
int64_t alloc_index = buffer_size_to_index(len_100_continue_response);
if (ua_entry->write_buffer) {
free_MIOBuffer(ua_entry->write_buffer);
ua_entry->write_buffer = nullptr;
}
ua_entry->write_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = ua_entry->write_buffer->alloc_reader();
t_state.hdr_info.client_request.m_100_continue_required = true;
SMDebug("http_seq", "send 100 Continue response to client");
int64_t nbytes = ua_entry->write_buffer->write(str_100_continue_response, len_100_continue_response);
ua_entry->write_vio = ua_txn->do_io_write(this, nbytes, buf_start);
}
}
if (t_state.hdr_info.client_request.method_get_wksidx() == HTTP_WKSIDX_TRACE ||
(t_state.hdr_info.client_request.get_content_length() == 0 &&
t_state.client_info.transfer_encoding != HttpTransact::CHUNKED_ENCODING)) {
// Enable further IO to watch for client aborts
ua_entry->read_vio->reenable();
} else {
// Disable further I/O on the client since there could
// be body that we are tunneling POST/PUT/CONNECT or
// extension methods and we can't issue another
// another IO later for the body with a different buffer
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
call_transact_and_set_next_state(HttpTransact::ModifyRequest);
break;
default:
ink_assert(!"not reached");
}
return 0;
}
void
HttpSM::wait_for_full_body()
{
is_waiting_for_full_body = true;
HTTP_SM_SET_DEFAULT_HANDLER(&HttpSM::tunnel_handler_post);
bool chunked = (t_state.client_info.transfer_encoding == HttpTransact::CHUNKED_ENCODING);
int64_t alloc_index;
HttpTunnelProducer *p = nullptr;
// content length is undefined, use default buffer size
if (t_state.hdr_info.request_content_length == HTTP_UNDEFINED_CL) {
alloc_index = static_cast<int>(t_state.txn_conf->default_buffer_size_index);
if (alloc_index < MIN_CONFIG_BUFFER_SIZE_INDEX || alloc_index > MAX_BUFFER_SIZE_INDEX) {
alloc_index = DEFAULT_REQUEST_BUFFER_SIZE_INDEX;
}
} else {
alloc_index = buffer_size_to_index(t_state.hdr_info.request_content_length);
}
MIOBuffer *post_buffer = new_MIOBuffer(alloc_index);
IOBufferReader *buf_start = post_buffer->alloc_reader();
this->_postbuf.init(post_buffer->clone_reader(buf_start));
// Note: Many browsers, Netscape and IE included send two extra
// bytes (CRLF) at the end of the post. We just ignore those
// bytes since the sending them is not spec
// Next order of business if copy the remaining data from the
// header buffer into new buffer
int64_t post_bytes = chunked ? INT64_MAX : t_state.hdr_info.request_content_length;
client_request_body_bytes = post_buffer->write(ua_buffer_reader, chunked ? ua_buffer_reader->read_avail() : post_bytes);
ua_buffer_reader->consume(client_request_body_bytes);
p = tunnel.add_producer(ua_entry->vc, post_bytes, buf_start, &HttpSM::tunnel_handler_post_ua, HT_BUFFER_READ, "ua post buffer");
if (chunked) {
tunnel.set_producer_chunking_action(p, 0, TCA_PASSTHRU_CHUNKED_CONTENT);
}
ua_entry->in_tunnel = true;
ua_txn->set_inactivity_timeout(HRTIME_SECONDS(t_state.txn_conf->transaction_no_activity_timeout_in));
tunnel.tunnel_run(p);
}
int
HttpSM::state_watch_for_client_abort(int event, void *data)
{
STATE_ENTER(&HttpSM::state_watch_for_client_abort, event);
ink_assert(ua_entry->read_vio == (VIO *)data || ua_entry->write_vio == (VIO *)data);
ink_assert(ua_entry->vc == ua_txn);
switch (event) {
/* EOS means that the client has initiated the connection shut down.
* Only half close the client connection so ATS can read additional
* data that may still be sent from the server and send it to the
* client.
*/
case VC_EVENT_EOS: {
// We got an early EOS.
NetVConnection *netvc = ua_txn->get_netvc();
if (ua_txn->allow_half_open()) {
if (netvc) {
netvc->do_io_shutdown(IO_SHUTDOWN_READ);
}
ua_entry->eos = true;
} else {
ua_txn->do_io_close();
ua_buffer_reader = nullptr;
vc_table.cleanup_entry(ua_entry);
ua_entry = nullptr;
tunnel.kill_tunnel();
terminate_sm = true; // Just die already, the requester is gone
set_ua_abort(HttpTransact::ABORTED, event);
}
break;
}
case VC_EVENT_ERROR:
case VC_EVENT_ACTIVE_TIMEOUT:
case VC_EVENT_INACTIVITY_TIMEOUT: {
if (tunnel.is_tunnel_active()) {
// Check to see if the user agent is part of the tunnel.
// If so forward the event to the tunnel. Otherwise,
// kill the tunnel and fallthrough to the case
// where the tunnel is not active
HttpTunnelConsumer *c = tunnel.get_consumer(ua_txn);
if (c && c->alive) {
SMDebug("http",
"[%" PRId64 "] [watch_for_client_abort] "
"forwarding event %s to tunnel",
sm_id, HttpDebugNames::get_event_name(event));
tunnel.handleEvent(event, c->write_vio);
return 0;
} else {
tunnel.kill_tunnel();
}
}
// Disable further I/O on the client
if (ua_entry->read_vio) {
ua_entry->read_vio->nbytes = ua_entry->read_vio->ndone;
}
mark_server_down_on_client_abort();
milestones[TS_MILESTONE_UA_CLOSE] = Thread::get_hrtime();
set_ua_abort(HttpTransact::ABORTED, event);
terminate_sm = true;
break;
}
case VC_EVENT_READ_COMPLETE:
// XXX Work around for TS-1233.
case VC_EVENT_READ_READY:
// Ignore. Could be a pipelined request. We'll get to it
// when we finish the current transaction
break;
case VC_EVENT_WRITE_READY:
// 100-continue handler
ink_assert(t_state.hdr_info.client_request.m_100_continue_required);