-
Notifications
You must be signed in to change notification settings - Fork 779
/
HttpTransact.cc
9166 lines (8183 loc) · 372 KB
/
HttpTransact.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
A brief file description
@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 "ts/ink_platform.h"
#include <strings.h>
#include <math.h>
#include "HttpTransact.h"
#include "HttpTransactHeaders.h"
#include "HttpSM.h"
#include "HttpCacheSM.h" //Added to get the scope of HttpCacheSM object - YTS Team, yamsat
#include "HttpDebugNames.h"
#include "time.h"
#include "ts/ParseRules.h"
#include "HTTP.h"
#include "HdrUtils.h"
#include "logging/Log.h"
#include "logging/LogUtils.h"
#include "Error.h"
#include "CacheControl.h"
#include "ControlMatcher.h"
#include "ReverseProxy.h"
#include "HttpBodyFactory.h"
#include "StatPages.h"
#include "../IPAllow.h"
#include "I_Machine.h"
static char range_type[] = "multipart/byteranges; boundary=RANGE_SEPARATOR";
#define RANGE_NUMBERS_LENGTH 60
#define TRANSACT_REMEMBER(_s, _e, _d) \
{ \
HttpSM *sm = (_s)->state_machine; \
sm->history[sm->history_pos % HISTORY_SIZE].file = __FILE__; \
sm->history[sm->history_pos % HISTORY_SIZE].line = __LINE__; \
sm->history[sm->history_pos % HISTORY_SIZE].event = _e; \
sm->history[sm->history_pos % HISTORY_SIZE].data = (void *)_d; \
sm->history_pos += 1; \
}
#define DebugTxn(tag, fmt, ...) \
DebugSpecific((s->state_machine->debug_on), tag, "[%" PRId64 "] " fmt, s->state_machine->sm_id, ##__VA_ARGS__)
extern HttpBodyFactory *body_factory;
inline static bool
is_localhost(const char *name, int len)
{
static const char local[] = "127.0.0.1";
return (len == (sizeof(local) - 1)) && (memcmp(name, local, len) == 0);
}
inline static void
simple_or_unavailable_server_retry(HttpTransact::State *s)
{
HTTP_RELEASE_ASSERT(!s->parent_result.parent_is_proxy());
// reponse is from a parent origin server.
HTTPStatus server_response = http_hdr_status_get(s->hdr_info.server_response.m_http);
DebugTxn("http_trans", "[simple_or_unavailabe_server_retry] server_response = %d, simple_retry_attempts: %d, numParents:%d ",
server_response, s->current.simple_retry_attempts, s->parent_params->numParents(&s->parent_result));
// simple retry is enabled, 0x1
if ((s->parent_result.retry_type() & PARENT_RETRY_SIMPLE) &&
s->current.simple_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_SIMPLE) &&
server_response == HTTP_STATUS_NOT_FOUND) {
DebugTxn("parent_select", "RECEIVED A SIMPLE RETRY RESPONSE");
if (s->current.simple_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_SIMPLE;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_SIMPLE: retried all parents, send response to client.");
return;
}
}
// unavailable server retry is enabled 0x2
else if ((s->parent_result.retry_type() & PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->current.unavailable_server_retry_attempts < s->parent_result.max_retries(PARENT_RETRY_UNAVAILABLE_SERVER) &&
s->parent_result.response_is_retryable(server_response)) {
DebugTxn("parent_select", "RECEIVED A PARENT_RETRY_UNAVAILABLE_SERVER RESPONSE");
if (s->current.unavailable_server_retry_attempts < s->parent_params->numParents(&s->parent_result)) {
s->current.state = HttpTransact::PARENT_ORIGIN_RETRY;
s->current.retry_type = PARENT_RETRY_UNAVAILABLE_SERVER;
return;
} else {
DebugTxn("http_trans", "PARENT_RETRY_UNAVAILABLE_SERVER: retried all parents, send error to client.");
return;
}
}
}
inline static bool
is_request_conditional(HTTPHdr *header)
{
uint64_t mask = (MIME_PRESENCE_IF_UNMODIFIED_SINCE | MIME_PRESENCE_IF_MODIFIED_SINCE | MIME_PRESENCE_IF_RANGE |
MIME_PRESENCE_IF_MATCH | MIME_PRESENCE_IF_NONE_MATCH);
return (header->presence(mask) &&
(header->method_get_wksidx() == HTTP_WKSIDX_GET || header->method_get_wksidx() == HTTP_WKSIDX_HEAD));
}
static inline bool
is_port_in_range(int port, HttpConfigPortRange *pr)
{
while (pr) {
if (pr->low == -1) {
return true;
} else if ((pr->low <= port) && (pr->high >= port)) {
return true;
}
pr = pr->next;
}
return false;
}
inline static void
update_cache_control_information_from_config(HttpTransact::State *s)
{
getCacheControl(&s->cache_control, &s->request_data, s->txn_conf);
s->cache_info.directives.does_config_permit_lookup &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_config_permit_storing &= (s->cache_control.never_cache == false);
s->cache_info.directives.does_client_permit_storing =
HttpTransact::does_client_request_permit_storing(&s->cache_control, &s->hdr_info.client_request);
s->cache_info.directives.does_client_permit_lookup = HttpTransact::does_client_request_permit_cached_response(
s->txn_conf, &s->cache_control, &s->hdr_info.client_request, s->via_string);
s->cache_info.directives.does_client_permit_dns_storing =
HttpTransact::does_client_request_permit_dns_caching(&s->cache_control, &s->hdr_info.client_request);
if (s->client_info.http_version == HTTPVersion(0, 9)) {
s->cache_info.directives.does_client_permit_lookup = false;
s->cache_info.directives.does_client_permit_storing = false;
}
// Less than 0 means it wasn't overridden, so leave it alone.
if (s->cache_control.cache_responses_to_cookies >= 0) {
s->txn_conf->cache_responses_to_cookies = s->cache_control.cache_responses_to_cookies;
}
}
inline bool
HttpTransact::is_server_negative_cached(State *s)
{
if (s->host_db_info.app.http_data.last_failure != 0 &&
s->host_db_info.app.http_data.last_failure + s->txn_conf->down_server_timeout > s->client_request_time) {
return true;
} else {
// Make sure some nasty clock skew has not happened
// Use the server timeout to set an upperbound as to how far in the
// future we should tolerate bogus last failure times. This sets
// the upper bound to the time that we would ever consider a server
// down to 2*down_server_timeout
if (s->client_request_time + s->txn_conf->down_server_timeout < s->host_db_info.app.http_data.last_failure) {
s->host_db_info.app.http_data.last_failure = 0;
ink_assert(!"extreme clock skew");
return true;
}
return false;
}
}
inline static void
update_current_info(HttpTransact::CurrentInfo *into, HttpTransact::ConnectionAttributes *from, HttpTransact::LookingUp_t who,
int attempts)
{
into->request_to = who;
into->server = from;
into->attempts = attempts;
}
inline static void
update_dns_info(HttpTransact::DNSLookupInfo *dns, HttpTransact::CurrentInfo *from, int attempts, Arena * /* arena ATS_UNUSED */)
{
dns->looking_up = from->request_to;
dns->lookup_name = from->server->name;
dns->attempts = attempts;
}
inline static HTTPHdr *
find_appropriate_cached_resp(HttpTransact::State *s)
{
HTTPHdr *c_resp = NULL;
if (s->cache_info.object_store.valid()) {
c_resp = s->cache_info.object_store.response_get();
if (c_resp != NULL && c_resp->valid()) {
return c_resp;
}
}
ink_assert(s->cache_info.object_read != NULL);
return s->cache_info.object_read->response_get();
}
int response_cacheable_indicated_by_cc(HTTPHdr *response);
inline static bool
is_negative_caching_appropriate(HttpTransact::State *s)
{
if (!s->txn_conf->negative_caching_enabled || !s->hdr_info.server_response.valid()) {
return false;
}
switch (s->hdr_info.server_response.status_get()) {
case HTTP_STATUS_NO_CONTENT:
case HTTP_STATUS_USE_PROXY:
case HTTP_STATUS_BAD_REQUEST:
case HTTP_STATUS_FORBIDDEN:
case HTTP_STATUS_NOT_FOUND:
case HTTP_STATUS_METHOD_NOT_ALLOWED:
case HTTP_STATUS_REQUEST_URI_TOO_LONG:
case HTTP_STATUS_INTERNAL_SERVER_ERROR:
case HTTP_STATUS_NOT_IMPLEMENTED:
case HTTP_STATUS_BAD_GATEWAY:
case HTTP_STATUS_SERVICE_UNAVAILABLE:
case HTTP_STATUS_GATEWAY_TIMEOUT:
return true;
default:
break;
}
return false;
}
inline static HttpTransact::LookingUp_t
find_server_and_update_current_info(HttpTransact::State *s)
{
int host_len;
const char *host = s->hdr_info.client_request.host_get(&host_len);
if (is_localhost(host, host_len)) {
// Do not forward requests to local_host onto a parent.
// I just wanted to do this for cop heartbeats, someone else
// wanted it for all requests to local_host.
s->parent_result.result = PARENT_DIRECT;
} else if (s->method == HTTP_WKSIDX_CONNECT && s->http_config_param->disable_ssl_parenting) {
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else if (s->txn_conf->uncacheable_requests_bypass_parent && s->http_config_param->no_dns_forward_to_parent == 0 &&
!HttpTransact::is_request_cache_lookupable(s)) {
// request not lookupable and cacheable, so bypass parent if the parent is not an origin server.
// Note that the configuration of the proxy as well as the request
// itself affects the result of is_request_cache_lookupable();
// we are assuming both child and parent have similar configuration
// with respect to whether a request is cacheable or not.
// For example, the cache_urls_that_look_dynamic variable.
s->parent_params->findParent(&s->request_data, &s->parent_result);
if (!s->parent_result.is_some() || s->parent_result.is_api_result() || s->parent_result.parent_is_proxy()) {
DebugTxn("http_trans", "request not cacheable, so bypass parent");
s->parent_result.result = PARENT_DIRECT;
}
} else {
switch (s->parent_result.result) {
case PARENT_UNDEFINED:
s->parent_params->findParent(&s->request_data, &s->parent_result);
break;
case PARENT_SPECIFIED:
s->parent_params->nextParent(&s->request_data, &s->parent_result);
// Hack!
// We already have a parent that failed, if we are now told
// to go the origin server, we can only obey this if we
// dns'ed the origin server
if (s->parent_result.result == PARENT_DIRECT && s->http_config_param->no_dns_forward_to_parent != 0) {
ink_assert(!s->server_info.dst_addr.isValid());
s->parent_result.result = PARENT_FAIL;
}
break;
case PARENT_FAIL:
// Check to see if should bypass the parent and go direct
// We can only do this if
// 1) the config permitted us to dns the origin server
// 2) the config permits us
// 3) the parent was not set from API
if (s->http_config_param->no_dns_forward_to_parent == 0 && s->parent_result.bypass_ok() &&
s->parent_result.parent_is_proxy() && !s->parent_params->apiParentExists(&s->request_data)) {
s->parent_result.result = PARENT_DIRECT;
}
break;
default:
ink_assert(0);
// FALL THROUGH
case PARENT_DIRECT:
// // if we have already decided to go direct
// // dont bother calling nextParent.
// // do nothing here, guy.
break;
}
}
switch (s->parent_result.result) {
case PARENT_SPECIFIED:
s->parent_info.name = s->arena.str_store(s->parent_result.hostname, strlen(s->parent_result.hostname));
update_current_info(&s->current, &s->parent_info, HttpTransact::PARENT_PROXY, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::PARENT_PROXY);
s->next_hop_scheme = URL_WKSIDX_HTTP;
return HttpTransact::PARENT_PROXY;
case PARENT_FAIL:
// No more parents - need to return an error message
s->current.request_to = HttpTransact::HOST_NONE;
return HttpTransact::HOST_NONE;
case PARENT_DIRECT:
/* fall through */
default:
update_current_info(&s->current, &s->server_info, HttpTransact::ORIGIN_SERVER, (s->current.attempts)++);
update_dns_info(&s->dns_info, &s->current, 0, &s->arena);
ink_assert(s->dns_info.looking_up == HttpTransact::ORIGIN_SERVER);
s->next_hop_scheme = s->scheme;
return HttpTransact::ORIGIN_SERVER;
}
}
inline static bool
do_cookies_prevent_caching(int cookies_conf, HTTPHdr *request, HTTPHdr *response, HTTPHdr *cached_request = NULL)
{
enum CookiesConfig {
COOKIES_CACHE_NONE = 0, // do not cache any responses to cookies
COOKIES_CACHE_ALL = 1, // cache for any content-type (ignore cookies)
COOKIES_CACHE_IMAGES = 2, // cache only for image types
COOKIES_CACHE_ALL_BUT_TEXT = 3, // cache for all but text content-types
COOKIES_CACHE_ALL_BUT_TEXT_EXT = 4 // cache for all but text content-types except with OS response
// without "Set-Cookie" or with "Cache-Control: public"
};
const char *content_type = NULL;
int str_len;
#ifdef DEBUG
ink_assert(request->type_get() == HTTP_TYPE_REQUEST);
ink_assert(response->type_get() == HTTP_TYPE_RESPONSE);
if (cached_request) {
ink_assert(cached_request->type_get() == HTTP_TYPE_REQUEST);
}
#endif
// Can cache all regardless of cookie header - just ignore all cookie headers
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL) {
return false;
}
// It is considered that Set-Cookie headers can be safely ignored
// for non text content types if Cache-Control private is not set.
// This enables a bigger hit rate, which currently outweighs the risk of
// breaking origin servers that truly intend to set a cookie with other
// objects such as images.
// At this time, it is believed that only advertisers do this, and that
// customers won't care about it.
// If the response does not have a Set-Cookie header and
// the response does not have a Cookie header and
// the object is not cached or the request does not have a Cookie header
// then cookies do not prevent caching.
if (!response->presence(MIME_PRESENCE_SET_COOKIE) && !request->presence(MIME_PRESENCE_COOKIE) &&
(cached_request == NULL || !cached_request->presence(MIME_PRESENCE_COOKIE))) {
return false;
}
// Do not cache if cookies option is COOKIES_CACHE_NONE
// and a Cookie is detected
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_NONE) {
return true;
}
// All other options depend on the Content-Type
content_type = response->value_get(MIME_FIELD_CONTENT_TYPE, MIME_LEN_CONTENT_TYPE, &str_len);
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_IMAGES) {
if (content_type && str_len >= 5 && memcmp(content_type, "image", 5) == 0) {
// Images can be cached
return false;
}
return true; // do not cache if COOKIES_CACHE_IMAGES && content_type != "image"
}
// COOKIES_CACHE_ALL_BUT_TEXT || COOKIES_CACHE_ALL_BUT_TEXT_EXT
// Note: if the configuration is bad, we consider
// COOKIES_CACHE_ALL_BUT_TEXT to be the default
if (content_type && str_len >= 4 && memcmp(content_type, "text", 4) == 0) { // content type - "text"
// Text objects cannot be cached unless the option is
// COOKIES_CACHE_ALL_BUT_TEXT_EXT.
// Furthermore, if there is a Set-Cookie header, then
// Cache-Control must be set.
if ((CookiesConfig)cookies_conf == COOKIES_CACHE_ALL_BUT_TEXT_EXT &&
((!response->presence(MIME_PRESENCE_SET_COOKIE)) || response->is_cache_control_set(HTTP_VALUE_PUBLIC))) {
return false;
}
return true;
}
return false; // Non text objects can be cached
}
inline static bool
does_method_require_cache_copy_deletion(const HttpConfigParams *http_config_param, const int method)
{
return ((method != HTTP_WKSIDX_GET) &&
(method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
(http_config_param->cache_post_method != 1 && method == HTTP_WKSIDX_POST)));
}
inline static bool
does_method_effect_cache(int method)
{
return ((method == HTTP_WKSIDX_GET || method == HTTP_WKSIDX_DELETE || method == HTTP_WKSIDX_PURGE || method == HTTP_WKSIDX_PUT ||
method == HTTP_WKSIDX_POST));
}
inline static HttpTransact::StateMachineAction_t
how_to_open_connection(HttpTransact::State *s)
{
ink_assert((s->pending_work == NULL) || (s->current.request_to == HttpTransact::PARENT_PROXY));
// Originally we returned which type of server to open
// Now, however, we may want to issue a cache
// operation first in order to lock the cache
// entry to prevent multiple origin server requests
// for the same document.
// The cache operation that we actually issue, of
// course, depends on the specified "cache_action".
// If there is no cache-action to be issued, just
// connect to the server.
switch (s->cache_info.action) {
case HttpTransact::CACHE_PREPARE_TO_DELETE:
case HttpTransact::CACHE_PREPARE_TO_UPDATE:
case HttpTransact::CACHE_PREPARE_TO_WRITE:
s->transact_return_point = HttpTransact::handle_cache_write_lock;
return HttpTransact::SM_ACTION_CACHE_ISSUE_WRITE;
default:
// This covers:
// CACHE_DO_UNDEFINED, CACHE_DO_NO_ACTION, CACHE_DO_DELETE,
// CACHE_DO_LOOKUP, CACHE_DO_REPLACE, CACHE_DO_SERVE,
// CACHE_DO_SERVE_AND_DELETE, CACHE_DO_SERVE_AND_UPDATE,
// CACHE_DO_UPDATE, CACHE_DO_WRITE, TOTAL_CACHE_ACTION_TYPES
break;
}
if (s->method == HTTP_WKSIDX_CONNECT && s->parent_result.result != PARENT_SPECIFIED) {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN;
} else {
s->cdn_saved_next_action = HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN;
}
// In the following, if url_remap_mode == 2 (URL_REMAP_FOR_OS)
// then do remapping for requests to OS's.
// Whether there is CDN remapping or not, goto SM_ACTION_DNS_LOOKUP;
// after that, it'll goto ORIGIN_SERVER_(RAW_)OPEN as needed.
if ((url_remap_mode == HttpTransact::URL_REMAP_FOR_OS) && (s->current.request_to == HttpTransact::ORIGIN_SERVER) &&
!s->cdn_remap_complete) {
DebugTxn("cdn", "*** START CDN Remapping *** CDN mode = %d", url_remap_mode);
char *remap_redirect = NULL;
int host_len;
const char *host;
// We need to copy the client request into the server request. Why? BUGBUG
s->hdr_info.server_request.url_set(s->hdr_info.client_request.url_get());
// TODO yeah, not sure everything here is correct with redirects
// This probably doesn't work properly, since request_url_remap() is broken.
if (request_url_remap(s, &s->hdr_info.server_request, &remap_redirect)) {
ink_assert(!remap_redirect); // should not redirect in this code
HttpTransact::initialize_state_variables_for_origin_server(s, &s->hdr_info.server_request, true);
DebugTxn("cdn", "Converting proxy request to server request");
// Check whether a Host header field is missing from a 1.0 or 1.1 request.
if (/*outgoing_version != HTTPVersion(0,9) && */
!s->hdr_info.server_request.presence(MIME_PRESENCE_HOST)) {
URL *url = s->hdr_info.server_request.url_get();
host = url->host_get(&host_len);
// Add a ':port' to the HOST header if the request is not going
// to the default port.
int port = url->port_get();
if (port != url_canonicalize_port(URL_TYPE_HTTP, 0)) {
char *buf = (char *)alloca(host_len + 15);
memcpy(buf, host, host_len);
host_len += snprintf(buf + host_len, 15, ":%d", port);
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, buf, host_len);
} else {
s->hdr_info.server_request.value_set(MIME_FIELD_HOST, MIME_LEN_HOST, host, host_len);
}
ats_free(remap_redirect); // This apparently shouldn't happen...
}
// Stripping out the host name from the URL
if (s->current.server == &s->server_info && s->next_hop_scheme == URL_WKSIDX_HTTP) {
DebugTxn("cdn", "Removing host name from URL");
HttpTransactHeaders::remove_host_name_from_url(&s->hdr_info.server_request);
}
} // the URL was remapped
if (is_debug_tag_set("cdn")) {
char *d_url = s->hdr_info.server_request.url_get()->string_get(NULL);
if (d_url) {
DebugTxn("cdn", "URL: %s", d_url);
}
char *d_hst = (char *)s->hdr_info.server_request.value_get(MIME_FIELD_HOST, MIME_LEN_HOST, &host_len);
if (d_hst) {
DebugTxn("cdn", "Host Hdr: %s", d_hst);
}
ats_free(d_url);
}
s->cdn_remap_complete = true; // It doesn't matter if there was an actual remap or not
s->transact_return_point = HttpTransact::OSDNSLookup;
ink_assert(s->next_action);
ink_assert(s->cdn_saved_next_action);
return HttpTransact::SM_ACTION_DNS_LOOKUP;
}
if (!s->already_downgraded) { // false unless downgraded previously (possibly due to HTTP 505)
(&s->hdr_info.server_request)->version_set(HTTPVersion(1, 1));
HttpTransactHeaders::convert_request(s->current.server->http_version, &s->hdr_info.server_request);
}
ink_assert(s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_OPEN ||
s->cdn_saved_next_action == HttpTransact::SM_ACTION_ORIGIN_SERVER_RAW_OPEN);
return s->cdn_saved_next_action;
}
/*****************************************************************************
*****************************************************************************
**** ****
**** HttpTransact State Machine Handlers ****
**** ****
**** What follow from here on are the state machine handlers - the code ****
**** which is called from HttpSM::set_next_state to specify ****
**** what action the state machine needs to execute next. These ftns ****
**** take as input just the state and set the next_action variable. ****
*****************************************************************************
*****************************************************************************/
void
HttpTransact::BadRequest(State *s)
{
DebugTxn("http_trans", "[BadRequest]"
"parser marked request bad");
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Invalid HTTP Request", "request#syntax_error", NULL);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
void
HttpTransact::HandleBlindTunnel(State *s)
{
bool inbound_transparent_p = s->state_machine->ua_session->get_netvc()->get_is_transparent();
URL u;
// IpEndpoint dest_addr;
// ip_text_buffer new_host;
DebugTxn("http_trans", "[HttpTransact::HandleBlindTunnel]");
// We've received a request on a port which we blind forward
// For logging purposes we create a fake request
s->hdr_info.client_request.create(HTTP_TYPE_REQUEST);
s->hdr_info.client_request.method_set(HTTP_METHOD_CONNECT, HTTP_LEN_CONNECT);
s->hdr_info.client_request.url_create(&u);
u.scheme_set(URL_SCHEME_TUNNEL, URL_LEN_TUNNEL);
s->hdr_info.client_request.url_set(&u);
// We set the version to 0.9 because once we know where we are going
// this blind ssl tunnel is indistinguishable from a "CONNECT 0.9"
// except for the need to suppression error messages
HTTPVersion ver(0, 9);
s->hdr_info.client_request.version_set(ver);
char new_host[INET6_ADDRSTRLEN];
ats_ip_ntop(s->state_machine->ua_session->get_netvc()->get_local_addr(), new_host, sizeof(new_host));
s->hdr_info.client_request.url_get()->host_set(new_host, strlen(new_host));
s->hdr_info.client_request.url_get()->port_set(s->state_machine->ua_session->get_netvc()->get_local_port());
// Initialize the state vars necessary to sending error responses
bootstrap_state_variables_from_request(s, &s->hdr_info.client_request);
if (is_debug_tag_set("http_trans")) {
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
DebugTxn("http_trans", "[HandleBlindTunnel] destination set to %.*s:%d", host_len, host,
s->hdr_info.client_request.url_get()->port_get());
}
// Now we need to run the url remapping engine to find the where
// this request really goes since we were sent was bound for
// machine we are running on
// Do request_url_remap only if url_remap_mode != URL_REMAP_FOR_OS.
bool url_remap_success = false;
char *remap_redirect = NULL;
if (s->transparent_passthrough) {
url_remap_success = true;
} else if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
// TODO: take a look at this
// This probably doesn't work properly, since request_url_remap() is broken.
url_remap_success = request_url_remap(s, &s->hdr_info.client_request, &remap_redirect);
}
// We must have mapping or we will self loop since the this
// request was addressed to us to begin with. Remap directs
// are something used in the normal reverse proxy and if we
// get them here they indicate a very bad misconfiguration!
if (!(inbound_transparent_p || url_remap_success) || remap_redirect != NULL) {
// The error message we send back will be suppressed so
// the only important thing in selecting the error is what
// status code it gets logged as
build_error_response(s, HTTP_STATUS_INTERNAL_SERVER_ERROR, "Port Forwarding Error", "default", NULL);
int host_len;
const char *host = s->hdr_info.client_request.url_get()->host_get(&host_len);
Log::error("Forwarded port error: request with destination %.*s:%d "
"does not have a mapping",
host_len, host, s->hdr_info.client_request.url_get()->port_get());
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
}
// Set the mode to tunnel so that we don't lookup the cache
s->current.mode = TUNNELLING_PROXY;
// Let the request work it's way through the code and
// we grab it again after the raw connection has been opened
HandleRequest(s);
}
bool
HttpTransact::perform_accept_encoding_filtering(State *s)
{
HttpUserAgent_RegxEntry *uae;
HTTPHdr *client_request;
MIMEField *accept_field;
MIMEField *usragent_field;
char tmp_ua_buf[1024], *c;
char const *u_agent = NULL;
int u_agent_len = 0;
bool retcode = false;
bool ua_match = false;
client_request = &s->hdr_info.client_request;
// Make sense to check Accept-Encoding if UserAgent is present (and matches)
if ((usragent_field = client_request->field_find(MIME_FIELD_USER_AGENT, MIME_LEN_USER_AGENT)) != 0 &&
(u_agent = usragent_field->value_get(&u_agent_len)) != 0 && u_agent_len > 0) {
if (u_agent_len >= (int)sizeof(tmp_ua_buf)) {
u_agent_len = (int)(sizeof(tmp_ua_buf) - 1);
}
memcpy(tmp_ua_buf, u_agent, u_agent_len);
tmp_ua_buf[u_agent_len] = '\0';
// TODO: Do we really want to do these hardcoded checks still?
// Check hardcoded case MSIE>6 & Mozilla>4
if ((c = strstr(tmp_ua_buf, "MSIE")) != NULL) {
if (c[5] >= '7' && c[5] <= '9') {
return false; // Don't change anything for IE > 6
}
ua_match = true;
} else if (!strncasecmp(tmp_ua_buf, "mozilla", 7)) {
if (tmp_ua_buf[8] >= '5' && tmp_ua_buf[8] <= '9') {
return false; // Don't change anything for Mozilla > 4
}
ua_match = true;
}
// Check custom filters
if (!ua_match && HttpConfig::user_agent_list) {
for (uae = HttpConfig::user_agent_list; uae && !ua_match; uae = uae->next) {
switch (uae->stype) {
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_CASE: /* .substring, .string */
if (u_agent_len >= uae->user_agent_str_size && !memcmp(tmp_ua_buf, uae->user_agent_str, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_SUBSTR_NCASE: /* .substring_ncase, .string_ncase */
if (u_agent_len >= uae->user_agent_str_size && !strncasecmp(uae->user_agent_str, tmp_ua_buf, uae->user_agent_str_size)) {
ua_match = true;
}
break;
case HttpUserAgent_RegxEntry::STRTYPE_REGEXP: /* .regexp POSIX regular expression */
if (uae->regx_valid && !pcre_exec(uae->regx, NULL, tmp_ua_buf, u_agent_len, 0, 0, NULL, 0)) {
ua_match = true;
}
break;
default: /* unknown type in the structure - bad initialization - impossible bug! */
/* I can use ink_error() here since we should shutdown TS immediately */
ink_error("[HttpTransact::perform_accept_encoding_filtering] - get unknown User-Agent string type - bad initialization");
};
}
}
/* If we have correct User-Agent header ....
Just set Accept-Encoding: identity or .... do nothing because
"If no Accept-Encoding field is present in a request, the server MAY assume that the client
will accept any content coding. In this case, if "identity" is one of the available content-codings,
then the server SHOULD use the "identity" content-coding, unless it has additional information that
a different content-coding is meaningful to the client." */
if (ua_match) {
DebugTxn("http_trans", "HttpTransact::ModifyRequest, insert identity Accept-Encoding");
accept_field = client_request->field_find(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (!accept_field) {
accept_field = client_request->field_create(MIME_FIELD_ACCEPT_ENCODING, MIME_LEN_ACCEPT_ENCODING);
if (accept_field) {
client_request->field_attach(accept_field);
}
}
if (accept_field) {
client_request->field_value_set(accept_field, HTTP_VALUE_IDENTITY, HTTP_LEN_IDENTITY);
}
}
retcode = true;
} // end of 'user-agent'
return retcode;
}
void
HttpTransact::StartRemapRequest(State *s)
{
if (s->api_skip_all_remapping) {
DebugTxn("http_trans", "API request to skip remapping");
s->hdr_info.client_request.set_url_target_from_host_field();
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_POST_REMAP_SKIP, HttpTransact::HandleRequest);
}
DebugTxn("http_trans", "START HttpTransact::StartRemapRequest");
/**
* Check for URL remappings before checking request
* validity or initializing state variables since
* the remappings can insert or change the destination
* host, port and protocol.
**/
HTTPHdr *incoming_request = &s->hdr_info.client_request;
URL *url = incoming_request->url_get();
int host_len, path_len;
const char *host = url->host_get(&host_len);
const char *path = url->path_get(&path_len);
const int port = url->port_get();
const char syntxt[] = "synthetic.txt";
s->cop_test_page = is_localhost(host, host_len) && ((path_len == sizeof(syntxt) - 1) && (memcmp(path, syntxt, path_len) == 0)) &&
port == s->http_config_param->synthetic_port && s->method == HTTP_WKSIDX_GET &&
s->orig_scheme == URL_WKSIDX_HTTP && ats_ip4_addr_cast(&s->client_info.dst_addr.sa) == htonl(INADDR_LOOPBACK);
//////////////////////////////////////////////////////////////////
// FIX: this logic seems awfully convoluted and hard to follow; //
// seems like we could come up with a more elegant and //
// comprehensible design that generalized things //
//////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// run the remap url-rewriting engine: //
// //
// * the variable <url_remap_success> is set true if //
// the url was rewritten //
// //
// * the variable <remap_redirect> is set to non-NULL if there //
// is a URL provided that the proxy is supposed to redirect //
// requesters of a particular URL to. //
/////////////////////////////////////////////////////////////////
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans")) {
DebugTxn("http_trans", "Before Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
if (url_remap_mode == URL_REMAP_DEFAULT || url_remap_mode == URL_REMAP_ALL) {
if (s->http_config_param->referer_filter_enabled) {
s->filter_mask = URL_REMAP_FILTER_REFERER;
if (s->http_config_param->referer_format_redirect) {
s->filter_mask |= URL_REMAP_FILTER_REDIRECT_FMT;
}
}
}
DebugTxn("http_trans", "END HttpTransact::StartRemapRequest");
TRANSACT_RETURN(SM_ACTION_API_PRE_REMAP, HttpTransact::PerformRemap);
}
void
HttpTransact::PerformRemap(State *s)
{
DebugTxn("http_trans", "Inside PerformRemap");
TRANSACT_RETURN(SM_ACTION_REMAP_REQUEST, HttpTransact::EndRemapRequest);
}
void
HttpTransact::EndRemapRequest(State *s)
{
DebugTxn("http_trans", "START HttpTransact::EndRemapRequest");
HTTPHdr *incoming_request = &s->hdr_info.client_request;
int method = incoming_request->method_get_wksidx();
int host_len;
const char *host = incoming_request->host_get(&host_len);
DebugTxn("http_trans", "EndRemapRequest host is %.*s", host_len, host);
////////////////////////////////////////////////////////////////
// if we got back a URL to redirect to, vector the user there //
////////////////////////////////////////////////////////////////
if (s->remap_redirect != NULL) {
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (s->http_return_code == HTTP_STATUS_MOVED_PERMANENTLY) {
build_error_response(s, HTTP_STATUS_MOVED_PERMANENTLY, "Redirect", "redirect#moved_permanently", NULL);
} else {
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect", "redirect#moved_temporarily", NULL);
}
ats_free(s->remap_redirect);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////
// Quick HTTP filtering (primary key: http method) //
/////////////////////////////////////////////////////
process_quick_http_filter(s, method);
/////////////////////////////////////////////////////////////////////////
// We must close this connection if client_connection_enabled == false //
/////////////////////////////////////////////////////////////////////////
if (!s->client_connection_enabled) {
build_error_response(s, HTTP_STATUS_FORBIDDEN, "Access Denied", "access#denied", NULL);
s->reverse_proxy = false;
goto done;
}
/////////////////////////////////////////////////////////////////
// Check if remap plugin set HTTP return code and return body //
/////////////////////////////////////////////////////////////////
if (s->http_return_code != HTTP_STATUS_NONE) {
build_error_response(s, s->http_return_code, NULL, NULL, s->internal_msg_buffer_size ? s->internal_msg_buffer : NULL);
s->reverse_proxy = false;
goto done;
}
///////////////////////////////////////////////////////////////
// if no mapping was found, handle the cases where: //
// //
// (1) reverse proxy is on, and no URL host (server request) //
// (2) no mappings are found, but mappings strictly required //
///////////////////////////////////////////////////////////////
if (!s->url_remap_success) {
/**
* It's better to test redirect rules just after url_remap failed
* Or those successfully remapped rules might be redirected
**/
if (handleIfRedirect(s)) {
DebugTxn("http_trans", "END HttpTransact::RemapRequest");
TRANSACT_RETURN(SM_ACTION_INTERNAL_CACHE_NOOP, NULL);
}
if (!s->http_config_param->url_remap_required && !incoming_request->is_target_in_url()) {
s->hdr_info.client_request.set_url_target_from_host_field();
}
/////////////////////////////////////////////////////////
// check for: (1) reverse proxy is on, and no URL host //
/////////////////////////////////////////////////////////
if (s->http_config_param->reverse_proxy_enabled && !s->client_info.is_transparent && !incoming_request->is_target_in_url()) {
/////////////////////////////////////////////////////////
// the url mapping failed, reverse proxy was enabled,
// and the request contains no host:
//
// * if there is an explanatory redirect, send there.
// * if there was no host, send "no host" error.
// * if there was a host, say "not found".
/////////////////////////////////////////////////////////
char *redirect_url = s->http_config_param->reverse_proxy_no_host_redirect;
int redirect_url_len = s->http_config_param->reverse_proxy_no_host_redirect_len;
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
if (redirect_url) { /* there is a redirect url */
build_error_response(s, HTTP_STATUS_MOVED_TEMPORARILY, "Redirect For Explanation", "request#no_host", NULL);
s->hdr_info.client_response.value_set(MIME_FIELD_LOCATION, MIME_LEN_LOCATION, redirect_url, redirect_url_len);
// socket when there is no host. Need to handle DNS failure elsewhere.
} else if (host == NULL) { /* no host */
build_error_response(s, HTTP_STATUS_BAD_REQUEST, "Host Header Required", "request#no_host", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
} else {
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found on Accelerator", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
}
s->reverse_proxy = false;
goto done;
} else if (s->http_config_param->url_remap_required && !s->cop_test_page) {
///////////////////////////////////////////////////////
// the url mapping failed, but mappings are strictly //
// required (except for synthetic cop accesses), so //
// return an error message. //
///////////////////////////////////////////////////////
SET_VIA_STRING(VIA_DETAIL_TUNNEL, VIA_DETAIL_TUNNEL_NO_FORWARD);
build_error_response(s, HTTP_STATUS_NOT_FOUND, "Not Found", "urlrouting#no_mapping", NULL);
s->squid_codes.log_code = SQUID_LOG_ERR_INVALID_URL;
s->reverse_proxy = false;
goto done;
}
} else {
if (s->http_config_param->reverse_proxy_enabled) {
s->req_flavor = REQ_FLAVOR_REVPROXY;
}
}
s->reverse_proxy = true;
s->server_info.is_transparent = s->state_machine->ua_session ? s->state_machine->ua_session->is_outbound_transparent() : false;
done:
// We now set the active-timeout again, since it might have been changed as part of the remap rules.
if (s->state_machine->ua_session) {
s->state_machine->ua_session->get_netvc()->set_active_timeout(HRTIME_SECONDS(s->txn_conf->transaction_active_timeout_in));
}
if (is_debug_tag_set("http_chdr_describe") || is_debug_tag_set("http_trans") || is_debug_tag_set("url_rewrite")) {
DebugTxn("http_trans", "After Remapping:");
obj_describe(s->hdr_info.client_request.m_http, 1);
}
/*
if s->reverse_proxy == false, we can assume remapping failed in some way
-however-
If an API setup a tunnel to fake the origin or proxy's response we will
continue to handle the request (as this was likely the plugin author's intent)
otherwise, 502/404 the request right now. /eric
*/
if (!s->reverse_proxy && s->state_machine->plugin_tunnel_type == HTTP_NO_PLUGIN_TUNNEL) {
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
HTTP_INCREMENT_DYN_STAT(http_invalid_client_requests_stat);
TRANSACT_RETURN(SM_ACTION_SEND_ERROR_CACHE_NOOP, NULL);
} else {
s->hdr_info.client_response.destroy(); // release the underlying memory.
s->hdr_info.client_response.clear(); // clear the pointers.
DebugTxn("http_trans", "END HttpTransact::EndRemapRequest");
if (s->is_upgrade_request && s->post_remap_upgrade_return_point) {
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, s->post_remap_upgrade_return_point);
}
TRANSACT_RETURN(SM_ACTION_API_POST_REMAP, HttpTransact::HandleRequest);
}
ink_assert(!"not reached");
}
bool
HttpTransact::handle_upgrade_request(State *s)
{
// Quickest way to determine that this is defintely not an upgrade.
/* RFC 6455 The method of the request MUST be GET, and the HTTP version MUST
be at least 1.1. */
if (!s->hdr_info.client_request.presence(MIME_PRESENCE_UPGRADE) ||
!s->hdr_info.client_request.presence(MIME_PRESENCE_CONNECTION) || s->method != HTTP_WKSIDX_GET ||
s->hdr_info.client_request.version_get() < HTTPVersion(1, 1)) {
return false;
}
MIMEField *upgrade_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_UPGRADE, MIME_LEN_UPGRADE);
MIMEField *connection_hdr = s->hdr_info.client_request.field_find(MIME_FIELD_CONNECTION, MIME_LEN_CONNECTION);
StrList connection_hdr_vals;
const char *upgrade_hdr_val = NULL;
int upgrade_hdr_val_len = 0;
if (!upgrade_hdr || !connection_hdr || connection_hdr->value_get_comma_list(&connection_hdr_vals) == 0 ||
(upgrade_hdr_val = upgrade_hdr->value_get(&upgrade_hdr_val_len)) == NULL) {
DebugTxn("http_trans_upgrade", "Transaction wasn't a valid upgrade request, proceeding as a normal HTTP request.");
return false;
}
/*
* In order for this request to be treated as a normal upgrade request we must have a Connection: Upgrade header