-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathats_pagespeed.cc
1340 lines (1185 loc) · 48.4 KB
/
ats_pagespeed.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.
*/
// TODO(oschaaf): remove what isn't used
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <limits.h>
#include <netinet/in.h>
#include <stdint.h>
#include <sys/inotify.h>
#include <unistd.h>
#include <ts/ts.h>
#include <vector>
#include <set>
#include "ats_pagespeed.h"
#include "ats_config.h"
#include "ats_header_utils.h"
#include "ats_rewrite_options.h"
#include "ats_log_message_handler.h"
#include "ats_base_fetch.h"
#include "ats_resource_intercept.h"
#include "ats_beacon_intercept.h"
#include "ats_process_context.h"
#include "ats_rewrite_driver_factory.h"
#include "ats_rewrite_options.h"
#include "ats_server_context.h"
#include "ats_request_context.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/cache_url_async_fetcher.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/public/global_constants.h"
#include "net/instaweb/public/version.h"
#include "net/instaweb/rewriter/public/experiment_matcher.h"
#include "net/instaweb/rewriter/public/experiment_util.h"
#include "net/instaweb/rewriter/public/process_context.h"
#include "net/instaweb/rewriter/public/resource_fetch.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/rewriter/public/rewrite_options.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/rewriter/public/rewrite_stats.h"
#include "net/instaweb/rewriter/public/static_asset_manager.h"
#include "net/instaweb/util/public/fallback_property_page.h"
#include "pagespeed/automatic/proxy_fetch.h"
#include "pagespeed/kernel/base/google_message_handler.h"
#include "pagespeed/kernel/base/null_message_handler.h"
#include "pagespeed/kernel/base/posix_timer.h"
#include "pagespeed/kernel/base/stack_buffer.h"
#include "pagespeed/kernel/base/stdio_file_system.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_writer.h"
#include "pagespeed/kernel/base/time_util.h"
#include "pagespeed/kernel/http/content_type.h"
#include "pagespeed/kernel/http/google_url.h"
#include "pagespeed/kernel/http/query_params.h"
#include "pagespeed/kernel/html/html_keywords.h"
#include "pagespeed/kernel/thread/pthread_shared_mem.h"
#include "pagespeed/kernel/util/gzip_inflater.h"
#include "pagespeed/kernel/util/statistics_logger.h"
#include "pagespeed/system/in_place_resource_recorder.h"
#include "pagespeed/system/system_caches.h"
#include "pagespeed/system/system_request_context.h"
#include "pagespeed/system/system_rewrite_options.h"
#include "pagespeed/system/system_server_context.h"
#include "pagespeed/system/system_thread_system.h"
#include <dirent.h>
#ifndef INT64_MIN
#define INT64_MAX (9223372036854775807LL)
#endif
using namespace net_instaweb;
static AtsProcessContext *ats_process_context;
static const char *DEBUG_TAG = "ats_pagespeed_transform";
static int TXN_INDEX_ARG;
static int TXN_INDEX_OWNED_ARG;
static int TXN_INDEX_OWNED_ARG_SET;
static int TXN_INDEX_OWNED_ARG_UNSET;
TSMutex config_mutex = TSMutexCreate();
AtsConfig *config = NULL;
TransformCtx *
get_transaction_context(TSHttpTxn txnp)
{
return (TransformCtx *)TSHttpTxnArgGet(txnp, TXN_INDEX_ARG);
}
static TransformCtx *
ats_ctx_alloc()
{
TransformCtx *ctx;
ctx = (TransformCtx *)TSmalloc(sizeof(TransformCtx));
ctx->downstream_vio = NULL;
ctx->downstream_buffer = NULL;
ctx->downstream_length = 0;
ctx->state = transform_state_initialized;
ctx->base_fetch = NULL;
ctx->proxy_fetch = NULL;
ctx->inflater = NULL;
ctx->url_string = NULL;
ctx->gurl = NULL;
ctx->write_pending = false;
ctx->fetch_done = false;
ctx->resource_request = false;
ctx->beacon_request = false;
ctx->transform_added = false;
ctx->mps_user_agent = false;
ctx->user_agent = NULL;
ctx->server_context = NULL;
ctx->html_rewrite = false;
ctx->request_method = NULL;
ctx->alive = 0xaaaa;
ctx->options = NULL;
ctx->to_host = NULL;
ctx->in_place = false;
ctx->driver = NULL;
ctx->record_in_place = false;
ctx->recorder = NULL;
ctx->ipro_response_headers = NULL;
ctx->serve_in_place = false;
return ctx;
}
void
ats_ctx_destroy(TransformCtx *ctx)
{
TSReleaseAssert(ctx);
CHECK(ctx->alive == 0xaaaa) << "Already dead!";
ctx->alive = 0xbbbb;
if (ctx->base_fetch != NULL) {
ctx->base_fetch->Release();
ctx->base_fetch = NULL;
}
if (ctx->proxy_fetch != NULL) {
ctx->proxy_fetch->Done(false /* failure */);
ctx->proxy_fetch = NULL;
}
if (ctx->inflater != NULL) {
delete ctx->inflater;
ctx->inflater = NULL;
}
if (ctx->downstream_buffer) {
TSIOBufferDestroy(ctx->downstream_buffer);
}
if (ctx->url_string != NULL) {
delete ctx->url_string;
ctx->url_string = NULL;
}
if (ctx->gurl != NULL) {
delete ctx->gurl;
ctx->gurl = NULL;
}
if (ctx->user_agent != NULL) {
delete ctx->user_agent;
ctx->user_agent = NULL;
}
ctx->request_method = NULL;
if (ctx->options != NULL) {
delete ctx->options;
ctx->options = NULL;
}
if (ctx->to_host != NULL) {
delete ctx->to_host;
ctx->to_host = NULL;
}
if (ctx->driver != NULL) {
ctx->driver->Cleanup();
ctx->driver = NULL;
}
if (ctx->recorder != NULL) {
ctx->recorder->Fail();
ctx->recorder->DoneAndSetHeaders(NULL,false); // Deletes recorder.
ctx->recorder = NULL;
}
if (ctx->ipro_response_headers != NULL) {
delete ctx->ipro_response_headers;
ctx->ipro_response_headers = NULL;
}
TSfree(ctx);
}
// Wrapper around GetQueryOptions()
RewriteOptions *
ps_determine_request_options(const RewriteOptions *domain_options, /* may be null */
RequestHeaders *request_headers, ResponseHeaders *response_headers, RequestContextPtr request_context,
ServerContext *server_context, GoogleUrl *url, GoogleString *pagespeed_query_params,
GoogleString *pagespeed_option_cookies)
{
// Sets option from request headers and url.
RewriteQuery rewrite_query;
if (!server_context->GetQueryOptions(request_context, domain_options, url, request_headers, response_headers, &rewrite_query)) {
// Failed to parse query params or request headers. Treat this as if there
// were no query params given.
TSError("[ats_pagespeed] ps_route request: parsing headers or query params failed.");
return NULL;
}
*pagespeed_query_params = rewrite_query.pagespeed_query_params().ToEscapedString();
*pagespeed_option_cookies = rewrite_query.pagespeed_option_cookies().ToEscapedString();
// Will be NULL if there aren't any options set with query params or in
// headers.
return rewrite_query.ReleaseOptions();
}
// There are many sources of options:
// - the request (query parameters, headers, and cookies)
// - location block
// - global server options
// - experiment framework
// Consider them all, returning appropriate options for this request, of which
// the caller takes ownership. If the only applicable options are global,
// set options to NULL so we can use server_context->global_options().
bool
ps_determine_options(ServerContext *server_context, RequestHeaders *request_headers, ResponseHeaders *response_headers,
RewriteOptions **options, RequestContextPtr request_context, GoogleUrl *url,
GoogleString *pagespeed_query_params, GoogleString *pagespeed_option_cookies, bool html_rewrite)
{
// Global options for this server. Never null.
RewriteOptions *global_options = server_context->global_options();
// TODO(oschaaf): we don't have directory_options right now. But if we did,
// we'd need to take them into account here.
RewriteOptions *directory_options = NULL;
// Request-specific options, nearly always null. If set they need to be
// rebased on the directory options or the global options.
// TODO(oschaaf): domain options..
RewriteOptions *request_options =
ps_determine_request_options(NULL /*domain options*/, request_headers, response_headers, request_context, server_context, url,
pagespeed_query_params, pagespeed_option_cookies);
// Because the caller takes ownership of any options we return, the only
// situation in which we can avoid allocating a new RewriteOptions is if the
// global options are ok as are.
if (directory_options == NULL && request_options == NULL && !global_options->running_experiment()) {
return true;
}
// Start with directory options if we have them, otherwise request options.
if (directory_options != NULL) {
//*options = directory_options->Clone();
// OS: HACK! TODO!
*options = global_options->Clone();
(*options)->Merge(*directory_options);
} else {
*options = global_options->Clone();
}
// Modify our options in response to request options or experiment settings,
// if we need to. If there are request options then ignore the experiment
// because we don't want experiments to be contaminated with unexpected
// settings.
if (request_options != NULL) {
(*options)->Merge(*request_options);
delete request_options;
}
// TODO(oschaaf): experiments
/*else if ((*options)->running_experiment()) {
bool ok = ps_set_experiment_state_and_cookie(
r, request_headers, *options, url->Host());
if (!ok) {
delete *options;
*options = NULL;
return false;
}
}*/
return true;
}
void
handle_send_response_headers(TSHttpTxn txnp)
{
TransformCtx *ctx = get_transaction_context(txnp);
// TODO(oschaaf): Fix the response headers!!
bool is_owned = TSHttpTxnArgGet(txnp, TXN_INDEX_OWNED_ARG) == &TXN_INDEX_OWNED_ARG_SET;
if (!is_owned) {
return;
}
CHECK(ctx->alive == 0xaaaa) << "Already dead !";
if (ctx->html_rewrite) {
TSMBuffer bufp = NULL;
TSMLoc hdr_loc = NULL;
if (ctx->base_fetch == NULL) {
// TODO(oschaaf): figure out when this happens.
return;
}
if (TSHttpTxnClientRespGet(txnp, &bufp, &hdr_loc) == TS_SUCCESS) {
ResponseHeaders *pagespeed_headers = ctx->base_fetch->response_headers();
for (int i = 0; i < pagespeed_headers->NumAttributes(); i++) {
const GoogleString &name_gs = pagespeed_headers->Name(i);
const GoogleString &value_gs = pagespeed_headers->Value(i);
// We should avoid touching these fields, as ATS will drop keepalive when we do.
if (StringCaseEqual(name_gs, "Connection") || StringCaseEqual(name_gs, "Transfer-Encoding")) {
continue;
}
TSMLoc field_loc = TSMimeHdrFieldFind(bufp, hdr_loc, name_gs.data(), name_gs.size());
if (field_loc != NULL) {
TSMimeHdrFieldValuesClear(bufp, hdr_loc, field_loc);
TSMimeHdrFieldValueStringInsert(bufp, hdr_loc, field_loc, -1, value_gs.data(), value_gs.size());
} else if (TSMimeHdrFieldCreate(bufp, hdr_loc, &field_loc) == TS_SUCCESS) {
if (TSMimeHdrFieldNameSet(bufp, hdr_loc, field_loc, name_gs.data(), name_gs.size()) == TS_SUCCESS) {
TSMimeHdrFieldValueStringInsert(bufp, hdr_loc, field_loc, -1, value_gs.data(), value_gs.size());
TSMimeHdrFieldAppend(bufp, hdr_loc, field_loc);
} else {
CHECK(false) << "Field name set failure";
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
} else {
CHECK(false) << "Field create failure";
}
}
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
} else {
DCHECK(false) << "Could not get response headers?!";
}
}
}
static void
copy_response_headers_to_psol(TSMBuffer bufp, TSMLoc hdr_loc, ResponseHeaders *psol_headers)
{
int n_mime_headers = TSMimeHdrFieldsCount(bufp, hdr_loc);
TSMLoc field_loc;
const char *name, *value;
int name_len, value_len;
GoogleString header;
for (int i = 0; i < n_mime_headers; ++i) {
field_loc = TSMimeHdrFieldGet(bufp, hdr_loc, i);
if (!field_loc) {
TSDebug(DEBUG_TAG, "[%s] Error while obtaining header field #%d", __FUNCTION__, i);
continue;
}
name = TSMimeHdrFieldNameGet(bufp, hdr_loc, field_loc, &name_len);
StringPiece s_name(name, name_len);
int n_field_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
for (int j = 0; j < n_field_values; ++j) {
value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, j, &value_len);
if (NULL == value || !value_len) {
TSDebug(DEBUG_TAG, "[%s] Error while getting value #%d of header [%.*s]", __FUNCTION__, j, name_len, name);
} else {
StringPiece s_value(value, value_len);
psol_headers->Add(s_name, s_value);
// TSDebug(DEBUG_TAG, "Add response header [%.*s:%.*s]",name_len, name, value_len, value);
}
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
}
}
void
copy_request_headers_to_psol(TSMBuffer bufp, TSMLoc hdr_loc, RequestHeaders *psol_headers)
{
int n_mime_headers = TSMimeHdrFieldsCount(bufp, hdr_loc);
TSMLoc field_loc;
const char *name, *value;
int name_len, value_len;
GoogleString header;
for (int i = 0; i < n_mime_headers; ++i) {
field_loc = TSMimeHdrFieldGet(bufp, hdr_loc, i);
if (!field_loc) {
TSDebug(DEBUG_TAG, "[%s] Error while obtaining header field #%d", __FUNCTION__, i);
continue;
}
name = TSMimeHdrFieldNameGet(bufp, hdr_loc, field_loc, &name_len);
StringPiece s_name(name, name_len);
int n_field_values = TSMimeHdrFieldValuesCount(bufp, hdr_loc, field_loc);
for (int j = 0; j < n_field_values; ++j) {
value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, j, &value_len);
if (NULL == value || !value_len) {
TSDebug(DEBUG_TAG, "[%s] Error while getting value #%d of header [%.*s]", __FUNCTION__, j, name_len, name);
} else {
StringPiece s_value(value, value_len);
psol_headers->Add(s_name, s_value);
// TSDebug(DEBUG_TAG, "Add request header [%.*s:%.*s]",name_len, name, value_len, value);
}
}
TSHandleMLocRelease(bufp, hdr_loc, field_loc);
}
}
// TODO(oschaaf): this is not sustainable when we get more
// configuration options like this.
bool
get_override_expiry(const StringPiece &host)
{
TSMutexLock(config_mutex);
AtsHostConfig *hc = config->Find(host.data(), host.size());
TSMutexUnlock(config_mutex);
return hc->override_expiry();
}
AtsRewriteOptions *
get_host_options(const StringPiece &host, ServerContext *server_context)
{
TSMutexLock(config_mutex);
AtsRewriteOptions *r = (AtsRewriteOptions *)server_context->global_options()->Clone();
AtsHostConfig *hc = config->Find(host.data(), host.size());
if (hc->options() != NULL) {
// We return a clone here to avoid having to thing about
// configuration reloads and outstanding options
hc->options()->ClearSignatureWithCaution();
r->Merge(*hc->options());
}
TSMutexUnlock(config_mutex);
return r;
}
std::string
get_remapped_host(TSHttpTxn txn)
{
TSMBuffer server_req_buf;
TSMLoc server_req_loc;
std::string to_host;
if (TSHttpTxnServerReqGet(txn, &server_req_buf, &server_req_loc) == TS_SUCCESS ||
TSHttpTxnCachedReqGet(txn, &server_req_buf, &server_req_loc) == TS_SUCCESS) {
to_host = get_header(server_req_buf, server_req_loc, "Host");
TSHandleMLocRelease(server_req_buf, TS_NULL_MLOC, server_req_loc);
} else {
fprintf(stderr, "@@@@@@@ FAILED \n");
}
return to_host;
}
static void
ats_transform_init(TSCont contp, TransformCtx *ctx)
{
// prepare the downstream for transforming
TSVConn downstream_conn;
TSMBuffer bufp;
TSMLoc hdr_loc;
TSMBuffer reqp;
TSMLoc req_hdr_loc;
ctx->state = transform_state_output;
// TODO: check cleanup flow
if (TSHttpTxnTransformRespGet(ctx->txn, &bufp, &hdr_loc) != TS_SUCCESS) {
TSError("[ats_pagespeed] TSHttpTxnTransformRespGet failed");
return;
}
if (TSHttpTxnClientReqGet(ctx->txn, &reqp, &req_hdr_loc) != TS_SUCCESS) {
TSError("[ats_pagespeed] TSHttpTxnClientReqGet failed");
return;
}
AtsServerContext *server_context = ats_process_context->server_context();
if (server_context->IsPagespeedResource(*ctx->gurl)) {
CHECK(false) << "PageSpeed resource should not get here!";
}
downstream_conn = TSTransformOutputVConnGet(contp);
ctx->downstream_buffer = TSIOBufferCreate();
ctx->downstream_vio = TSVConnWrite(downstream_conn, contp, TSIOBufferReaderAlloc(ctx->downstream_buffer), INT64_MAX);
if (ctx->recorder != NULL) {
TSHandleMLocRelease(reqp, TS_NULL_MLOC, req_hdr_loc);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
return;
}
// TODO(oschaaf): fix host/ip(?)
AtsRequestContext *system_request_context =
new AtsRequestContext(server_context->thread_system()->NewMutex(), server_context->timer(), "www.foo.com", 80, "127.0.0.1", ctx->txn);
RequestContextPtr rptr(system_request_context);
// Clean up existing base fetch
if (ctx->base_fetch)
{
ctx->base_fetch->Release();
ctx->base_fetch->Release();
}
ctx->base_fetch = new AtsBaseFetch(server_context, rptr, ctx->downstream_vio, ctx->downstream_buffer, false);
ResponseHeaders response_headers;
RequestHeaders *request_headers = new RequestHeaders();
ctx->base_fetch->SetRequestHeadersTakingOwnership(request_headers);
copy_request_headers_to_psol(reqp, req_hdr_loc, request_headers);
TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);
copy_response_headers_to_psol(bufp, hdr_loc, &response_headers);
std::string host = ctx->gurl->HostAndPort().as_string();
RewriteOptions *options = NULL;
if (host.size() > 0) {
options = get_host_options(host.c_str(), server_context);
if (options != NULL) {
server_context->message_handler()->Message(kInfo, "request options found \r\n");
}
}
if (options == NULL) {
options = server_context->global_options()->Clone();
}
server_context->message_handler()->Message(kInfo, "request options:\r\n[%s]", options->OptionsToString().c_str());
/*
RewriteOptions* options = NULL;
GoogleString pagespeed_query_params;
GoogleString pagespeed_option_cookies;
bool ok = ps_determine_options(server_context,
ctx->base_fetch->request_headers(),
&response_headers,
&options,
rptr,
ctx->gurl,
&pagespeed_query_params,
&pagespeed_option_cookies,
true);
*/
// TODO(oschaaf): use the determined option/query params
// Take ownership of custom_options.
net_instaweb::scoped_ptr<RewriteOptions> custom_options(options);
/*
if (!ok) {
TSError("Failure while determining request options for psol");
options = server_context->global_options();
} else {
// ps_determine_options modified url, removing any ModPagespeedFoo=Bar query
// parameters. Keep url_string in sync with url.
ctx->gurl->Spec().CopyToString(ctx->url_string);
}*/
RewriteDriver *driver;
if (custom_options.get() == NULL) {
driver = server_context->NewRewriteDriver(ctx->base_fetch->request_context());
} else {
driver = server_context->NewCustomRewriteDriver(custom_options.release(), ctx->base_fetch->request_context());
}
rptr->set_options(driver->options()->ComputeHttpOptions());
// TODO(oschaaf): http version
ctx->base_fetch->response_headers()->set_status_code(status);
copy_response_headers_to_psol(bufp, hdr_loc, ctx->base_fetch->response_headers());
ctx->base_fetch->response_headers()->ComputeCaching();
driver->SetRequestHeaders(*request_headers);
// driver->set_pagespeed_query_params(pagespeed_query_params);
// driver->set_pagespeed_option_cookies(pagespeed_option_cookies);
ProxyFetchPropertyCallbackCollector* property_callback =
ProxyFetchFactory::InitiatePropertyCacheLookup(
false /* is_resource_fetch */,
*ctx->gurl,
server_context,
options,
ctx->base_fetch);
ctx->proxy_fetch = ats_process_context->proxy_fetch_factory()->CreateNewProxyFetch(
*(ctx->url_string), ctx->base_fetch, driver, property_callback, NULL /* original_content_fetch */);
ctx->proxy_fetch->set_trusted_input(true);
TSHandleMLocRelease(reqp, TS_NULL_MLOC, req_hdr_loc);
TSHandleMLocRelease(bufp, TS_NULL_MLOC, hdr_loc);
}
static void
ats_transform_one(TransformCtx *ctx, TSIOBufferReader upstream_reader, int amount)
{
TSDebug("ats_pagespeed", "transform_one()");
TSIOBufferBlock downstream_blkp;
const char *upstream_buffer;
int64_t upstream_length;
while (amount > 0) {
downstream_blkp = TSIOBufferReaderStart(upstream_reader);
if (!downstream_blkp) {
TSError("[ats_pagespeed] Couldn't get from IOBufferBlock");
return;
}
upstream_buffer = TSIOBufferBlockReadStart(downstream_blkp, upstream_reader, &upstream_length);
if (!upstream_buffer) {
TSError("[ats_pagespeed] Couldn't get from TSIOBufferBlockReadStart");
return;
}
if (upstream_length > amount) {
upstream_length = amount;
}
TSDebug("ats_pagespeed", "transform!");
// TODO(oschaaf): use at least the message handler from the server conrtext here?
if (ctx->inflater == NULL) {
if (ctx->recorder != NULL) {
ctx->recorder->Write(StringPiece((char *)upstream_buffer, upstream_length), ats_process_context->message_handler());
} else {
ctx->proxy_fetch->Write(StringPiece((char *)upstream_buffer, upstream_length), ats_process_context->message_handler());
}
} else {
char buf[net_instaweb::kStackBufferSize];
ctx->inflater->SetInput((char *)upstream_buffer, upstream_length);
while (ctx->inflater->HasUnconsumedInput()) {
int num_inflated_bytes = ctx->inflater->InflateBytes(buf, net_instaweb::kStackBufferSize);
if (num_inflated_bytes < 0) {
TSError("[ats_pagespeed] Corrupted inflation");
} else if (num_inflated_bytes > 0) {
if (ctx->recorder != NULL) {
ctx->recorder->Write(StringPiece(buf, num_inflated_bytes), ats_process_context->message_handler());
} else {
ctx->proxy_fetch->Write(StringPiece(buf, num_inflated_bytes), ats_process_context->message_handler());
}
}
}
}
// ctx->proxy_fetch->Flush(NULL);
TSIOBufferReaderConsume(upstream_reader, upstream_length);
amount -= upstream_length;
}
// TODO(oschaaf): get the output from the base fetch, and send it downstream.
// This would require proper locking around the base fetch buffer
// We could also have a look at directly writing to the traffic server buffers
}
static void
ats_transform_finish(TransformCtx *ctx)
{
if (ctx->state == transform_state_output) {
ctx->state = transform_state_finished;
if (ctx->recorder != NULL) {
TSDebug("ats_pagespeed", "ipro recording finished");
TSDebug("ats_pagespeed", "%s", ctx->ipro_response_headers->ToString().c_str());
//TODO(kspoelstra): we've always finished our resource successfully, right? right?
ctx->recorder->DoneAndSetHeaders(ctx->ipro_response_headers,true);
ctx->recorder = NULL;
} else {
TSDebug("ats_pagespeed", "proxy fetch finished");
ctx->proxy_fetch->Done(true);
ctx->proxy_fetch = NULL;
}
}
}
static void
ats_transform_do(TSCont contp)
{
TSVIO upstream_vio;
TransformCtx *ctx;
int64_t upstream_todo;
int64_t upstream_avail;
int64_t downstream_bytes_written;
ctx = (TransformCtx *)TSContDataGet(contp);
if (ctx->state == transform_state_initialized) {
ats_transform_init(contp, ctx);
}
upstream_vio = TSVConnWriteVIOGet(contp);
downstream_bytes_written = ctx->downstream_length;
if (!TSVIOBufferGet(upstream_vio)) {
ats_transform_finish(ctx);
return;
}
upstream_todo = TSVIONTodoGet(upstream_vio);
if (upstream_todo > 0) {
upstream_avail = TSIOBufferReaderAvail(TSVIOReaderGet(upstream_vio));
if (upstream_todo > upstream_avail) {
upstream_todo = upstream_avail;
}
if (upstream_todo > 0) {
if (ctx->recorder != NULL) {
ctx->downstream_length += upstream_todo;
TSIOBufferCopy(TSVIOBufferGet(ctx->downstream_vio), TSVIOReaderGet(upstream_vio), upstream_todo, 0);
}
ats_transform_one(ctx, TSVIOReaderGet(upstream_vio), upstream_todo);
TSVIONDoneSet(upstream_vio, TSVIONDoneGet(upstream_vio) + upstream_todo);
}
}
if (TSVIONTodoGet(upstream_vio) > 0) {
if (upstream_todo > 0) {
if (ctx->downstream_length > downstream_bytes_written) {
TSVIOReenable(ctx->downstream_vio);
}
TSContCall(TSVIOContGet(upstream_vio), TS_EVENT_VCONN_WRITE_READY, upstream_vio);
}
} else {
// When not recording, the base fetch will re-enable from the PSOL callback.
if (ctx->recorder != NULL) {
TSVIONBytesSet(ctx->downstream_vio, ctx->downstream_length);
TSVIOReenable(ctx->downstream_vio);
}
ats_transform_finish(ctx);
TSContCall(TSVIOContGet(upstream_vio), TS_EVENT_VCONN_WRITE_COMPLETE, upstream_vio);
}
}
static int
ats_pagespeed_transform(TSCont contp, TSEvent event, void * /* edata ATS_UNUSED */)
{
TSDebug("ats_pagespeed", "ats_pagespeed_transform()");
if (TSVConnClosedGet(contp)) {
// ats_ctx_destroy((TransformCtx*)TSContDataGet(contp));
TSContDestroy(contp);
return 0;
} else {
switch (event) {
case TS_EVENT_ERROR: {
fprintf(stderr, "ats speed transform event: [%d] TS EVENT ERROR?!\n", event);
TSVIO upstream_vio = TSVConnWriteVIOGet(contp);
TSContCall(TSVIOContGet(upstream_vio), TS_EVENT_ERROR, upstream_vio);
} break;
case TS_EVENT_VCONN_WRITE_COMPLETE:
TSVConnShutdown(TSTransformOutputVConnGet(contp), 0, 1);
break;
case TS_EVENT_VCONN_WRITE_READY:
ats_transform_do(contp);
break;
case TS_EVENT_IMMEDIATE:
ats_transform_do(contp);
break;
default:
DCHECK(false) << "unknown event: " << event;
ats_transform_do(contp);
break;
}
}
return 0;
}
static void
ats_pagespeed_transform_add(TSHttpTxn txnp)
{
TransformCtx *ctx = get_transaction_context(txnp);
CHECK(ctx);
if (ctx->transform_added) { // Happens with a stale cache hit
TSDebug("ats_pagespeed", "transform not added due to already being added");
return;
} else {
TSDebug("ats_pagespeed", "transform added");
ctx->transform_added = true;
}
TSHttpTxnUntransformedRespCache(txnp, ctx->recorder == NULL ? 1 : 0);
TSHttpTxnTransformedRespCache(txnp, 0);
TSVConn connp;
connp = TSTransformCreate(ats_pagespeed_transform, txnp);
TSContDataSet(connp, ctx);
TSHttpTxnHookAdd(txnp, TS_HTTP_RESPONSE_TRANSFORM_HOOK, connp);
}
const std::string get_txn_url(TSHttpTxn txnp)
{
int url_length = -1;
const char *url = TSHttpTxnEffectiveUrlStringGet(txnp, &url_length);
if (!url || url_length <= 0) {
return "";
} else {
int port = 0;
const sockaddr *sockaddr = TSHttpTxnIncomingAddrGet(txnp);
if (sockaddr->sa_family == AF_INET)
port = ((struct sockaddr_in *) sockaddr)->sin_port;
else
port = ((struct sockaddr_in6 *) sockaddr)->sin6_port;
port = ntohs(port);
std::string s_url = std::string(url, url_length);
TSfree((void *)url);
unsigned int urlpos = s_url.find("/", 8);
if (port!=0 && s_url.size() > 8 &&
((port != 443 && s_url.at(5) == ':') ||
(port != 80 && s_url.at(4) == ':'))) {
std::string s_port = IntegerToString(port);
if (urlpos != std::string::npos) {
if (s_url.compare(urlpos - (s_port.length()), s_port.length(), s_port) != 0) {
s_url = s_url.substr(0, urlpos) + ":" + s_port + s_url.substr(urlpos);
}
} else {
if (s_url.compare(s_url.length() - (s_port.length()), s_port.length(), s_port) != 0) {
s_url = s_url + ":" + s_port;
}
}
}
return s_url;
}
}
void
handle_read_request_header(TSHttpTxn txnp)
{
TSMBuffer reqp = NULL;
TSMLoc hdr_loc = NULL;
TransformCtx *ctx = ats_ctx_alloc();
ctx->txn = txnp;
TSHttpTxnArgSet(txnp, TXN_INDEX_ARG, (void *)ctx);
TSHttpTxnArgSet(txnp, TXN_INDEX_OWNED_ARG, &TXN_INDEX_OWNED_ARG_SET);
if (TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc) == TS_SUCCESS) {
const std::string s_url=get_txn_url(txnp);
if (s_url=="") {
DCHECK(false) << "Could not get url!";
} else {
GoogleUrl gurl(s_url);
ctx->url_string = new GoogleString(s_url);
ctx->gurl = new GoogleUrl(*(ctx->url_string));
if (!ctx->gurl->IsWebValid()) {
TSDebug("ats_pagespeed", "URL != WebValid(): %s", ctx->url_string->c_str());
} else {
const char *method;
int method_len;
method = TSHttpHdrMethodGet(reqp, hdr_loc, &method_len);
bool head_or_get = method == TS_HTTP_METHOD_GET || method == TS_HTTP_METHOD_HEAD;
ctx->request_method = method;
GoogleString user_agent = get_header(reqp, hdr_loc, "User-Agent");
ctx->user_agent = new GoogleString(user_agent);
ctx->server_context = ats_process_context->server_context();
TSDebug("ats_pagespeed", "static asset prefix: %s",
((AtsRewriteDriverFactory *)ctx->server_context->factory())->static_asset_prefix().c_str());
if (user_agent.find(kModPagespeedSubrequestUserAgent) != user_agent.npos) {
ctx->mps_user_agent = true;
}
if (ats_process_context->server_context()->IsPagespeedResource(gurl)) {
if (head_or_get && !ctx->mps_user_agent) {
ctx->resource_request = true;
TSHttpTxnArgSet(txnp, TXN_INDEX_OWNED_ARG, &TXN_INDEX_OWNED_ARG_UNSET);
}
} else if (ctx->gurl->PathSansLeaf() ==
((AtsRewriteDriverFactory *)ctx->server_context->factory())->static_asset_prefix()) {
ctx->resource_request = true;
TSHttpTxnArgSet(txnp, TXN_INDEX_OWNED_ARG, &TXN_INDEX_OWNED_ARG_UNSET);
} else if (StringCaseEqual(gurl.PathSansQuery(), "/ats_pagespeed_beacon")) {
ctx->beacon_request = true;
TSHttpTxnArgSet(txnp, TXN_INDEX_OWNED_ARG, &TXN_INDEX_OWNED_ARG_UNSET);
hook_beacon_intercept(txnp);
} else {
AtsServerContext *server_context = ctx->server_context;
// TODO(oschaaf): fix host/ip(?)
AtsRequestContext *system_request_context = new AtsRequestContext(
server_context->thread_system()->NewMutex(), server_context->timer(), "www.foo.com", 80, "127.0.0.1", txnp);
RequestContextPtr rptr(system_request_context);
// TSHttpStatus status = TSHttpHdrStatusGet(bufp, hdr_loc);
// TODO(oschaaf): http version
// ctx->base_fetch->response_headers()->set_status_code(status);
// copy_response_headers_to_psol(bufp, hdr_loc, ctx->base_fetch->response_headers());
// ctx->base_fetch->response_headers()->ComputeCaching();
std::string host = ctx->gurl->HostAndPort().as_string();
// request_headers->Lookup1(HttpAttributes::kHost);
RewriteOptions *options = NULL;
if (host.size() > 0) {
options = get_host_options(host.c_str(), server_context);
}
if (options == NULL) {
options = server_context->global_options()->Clone();
}
// GoogleString pagespeed_query_params;
// GoogleString pagespeed_option_cookies;
// bool ok = ps_determine_options(server_context,
// ctx->base_fetch->request_headers(),
// NULL /*ResponseHeaders* */,
// &options,
// rptr,
// ctx->gurl,
// &pagespeed_query_params,
// &pagespeed_option_cookies,
// false /*html rewrite*/);
// Take ownership of custom_options.
net_instaweb::scoped_ptr<RewriteOptions> custom_options(options);
// ps_determine_options modified url, removing any ModPagespeedFoo=Bar query
// parameters. Keep url_string in sync with url.
// ctx->gurl->Spec().CopyToString(ctx->url_string);
rptr->set_options(options->ComputeHttpOptions());
if (options->in_place_rewriting_enabled() && options->enabled() && options->IsAllowed(ctx->gurl->Spec())) {
ctx->base_fetch = new AtsBaseFetch(server_context, rptr, ctx->downstream_vio, ctx->downstream_buffer, false);
RequestHeaders *request_headers = new RequestHeaders();
ctx->base_fetch->SetRequestHeadersTakingOwnership(request_headers);
copy_request_headers_to_psol(reqp, hdr_loc, request_headers);
RewriteDriver *driver;
if (custom_options.get() == NULL) {
driver = server_context->NewRewriteDriver(ctx->base_fetch->request_context());
} else {
driver = server_context->NewCustomRewriteDriver(custom_options.release(), ctx->base_fetch->request_context());
}
driver->SetRequestHeaders(*ctx->base_fetch->request_headers());
// driver->set_pagespeed_query_params(pagespeed_query_params);
// driver->set_pagespeed_option_cookies(pagespeed_option_cookies);
ctx->driver = driver;
ctx->server_context->message_handler()->Message(kInfo, "Trying to serve rewritten resource in-place: %s",
ctx->url_string->c_str());
ctx->in_place = true;
ctx->base_fetch->set_handle_error(false);
ctx->base_fetch->set_is_ipro(true);
// ctx->driver->FetchInPlaceResource(
// *ctx->gurl, false /* proxy_mode */, ctx->base_fetch);
}
}
}
} // gurl->IsWebValid() == true
TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc);
} else {
DCHECK(false) << "Could not get client request header\n";
}
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
}
bool
cache_hit(TSHttpTxn txnp)
{
int obj_status;
if (TSHttpTxnCacheLookupStatusGet(txnp, &obj_status) == TS_ERROR) {
// TODO(oschaaf): log warning
return false;
}
return obj_status == TS_CACHE_LOOKUP_HIT_FRESH;
}
static int
transform_plugin(TSCont contp, TSEvent event, void *edata)
{
TSHttpTxn txn = (TSHttpTxn)edata;
CHECK(event == TS_EVENT_HTTP_READ_RESPONSE_HDR || event == TS_EVENT_HTTP_READ_CACHE_HDR ||
event == TS_EVENT_HTTP_SEND_REQUEST_HDR || event == TS_EVENT_HTTP_READ_REQUEST_HDR || event == TS_EVENT_HTTP_TXN_CLOSE ||
event == TS_EVENT_HTTP_SEND_RESPONSE_HDR)
<< "Invalid transform event";
if (event != TS_EVENT_HTTP_READ_REQUEST_HDR) {
// Bail if an intercept is running
bool is_owned = TSHttpTxnArgGet(txn, TXN_INDEX_OWNED_ARG) == &TXN_INDEX_OWNED_ARG_SET;
if (!is_owned) {
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return 0;
}
}
if (event == TS_EVENT_HTTP_SEND_RESPONSE_HDR) {
handle_send_response_headers(txn);
TSHttpTxnReenable(txn, TS_EVENT_HTTP_CONTINUE);
return 0;
}
if (event == TS_EVENT_HTTP_TXN_CLOSE) {
TransformCtx *ctx = get_transaction_context(txn);
// if (ctx != NULL && !ctx->resource_request && !ctx->beacon_request && !ctx->html_rewrite) {
// For intercepted requests like beacons and resource requests, we don't own the
// ctx here - the interceptor does.