aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/http/http.cpp
blob: ef25a17a8a66904ad69bc6ac586c97fa65aa5b94 (plain) (blame)
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
#include "http.h"
#include <library/cpp/string_utils/quote/quote.h>

inline TStringBuf operator +(TStringBuf l, TStringBuf r) {
    if (l.empty()) {
        return r;
    }
    if (r.empty()) {
        return l;
    }
    if (l.end() == r.begin()) {
        return TStringBuf(l.data(), l.size() + r.size());
    }
    if (r.end() == l.begin()) {
        return TStringBuf(r.data(), l.size() + r.size());
    }
    Y_FAIL("oops");
    return TStringBuf();
}

inline TStringBuf operator +=(TStringBuf& l, TStringBuf r) {
    return l = l + r;
}

namespace NHttp {

template <> TStringBuf THttpRequest::GetName<&THttpRequest::Host>() { return "Host"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::Accept>() { return "Accept"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::Connection>() { return "Connection"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::ContentType>() { return "Content-Type"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::ContentLength>() { return "Content-Length"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::TransferEncoding>() { return "Transfer-Encoding"; }
template <> TStringBuf THttpRequest::GetName<&THttpRequest::AcceptEncoding>() { return "Accept-Encoding"; }

const TMap<TStringBuf, TStringBuf THttpRequest::*, TLessNoCase> THttpRequest::HeadersLocation = {
    { THttpRequest::GetName<&THttpRequest::Host>(), &THttpRequest::Host },
    { THttpRequest::GetName<&THttpRequest::Accept>(), &THttpRequest::Accept },
    { THttpRequest::GetName<&THttpRequest::Connection>(), &THttpRequest::Connection },
    { THttpRequest::GetName<&THttpRequest::ContentType>(), &THttpRequest::ContentType },
    { THttpRequest::GetName<&THttpRequest::ContentLength>(), &THttpRequest::ContentLength },
    { THttpRequest::GetName<&THttpRequest::TransferEncoding>(), &THttpRequest::TransferEncoding },
    { THttpRequest::GetName<&THttpRequest::AcceptEncoding>(), &THttpRequest::AcceptEncoding },
};

template <> TStringBuf THttpResponse::GetName<&THttpResponse::Connection>() { return "Connection"; }
template <> TStringBuf THttpResponse::GetName<&THttpResponse::ContentType>() { return "Content-Type"; }
template <> TStringBuf THttpResponse::GetName<&THttpResponse::ContentLength>() { return "Content-Length"; }
template <> TStringBuf THttpResponse::GetName<&THttpResponse::TransferEncoding>() { return "Transfer-Encoding"; }
template <> TStringBuf THttpResponse::GetName<&THttpResponse::LastModified>() { return "Last-Modified"; }
template <> TStringBuf THttpResponse::GetName<&THttpResponse::ContentEncoding>() { return "Content-Encoding"; }

const TMap<TStringBuf, TStringBuf THttpResponse::*, TLessNoCase> THttpResponse::HeadersLocation = {
    { THttpResponse::GetName<&THttpResponse::Connection>(), &THttpResponse::Connection },
    { THttpResponse::GetName<&THttpResponse::ContentType>(), &THttpResponse::ContentType },
    { THttpResponse::GetName<&THttpResponse::ContentLength>(), &THttpResponse::ContentLength },
    { THttpResponse::GetName<&THttpResponse::TransferEncoding>(), &THttpResponse::TransferEncoding },
    { THttpResponse::GetName<&THttpResponse::LastModified>(), &THttpResponse::LastModified },
    { THttpResponse::GetName<&THttpResponse::ContentEncoding>(), &THttpResponse::ContentEncoding }
};

void THttpRequest::Clear() {
    // a dirty little trick
    this->~THttpRequest(); // basically, do nothing
    new (this) THttpRequest(); // reset all fields
}

template <>
bool THttpParser<THttpRequest, TSocketBuffer>::HaveBody() const {
    if (!Body.empty()) {
        return true;
    }
    return (!ContentType.empty() || !ContentLength.empty() || !TransferEncoding.empty());
}

template <>
void THttpParser<THttpRequest, TSocketBuffer>::Advance(size_t len) {
    TStringBuf data(Pos(), len);
    while (!data.empty()) {
        if (Stage != EParseStage::Error) {
            LastSuccessStage = Stage;
        }
        switch (Stage) {
            case EParseStage::Method: {
                if (ProcessData(Method, data, ' ', MaxMethodSize)) {
                    Stage = EParseStage::URL;
                }
                break;
            }
            case EParseStage::URL: {
                if (ProcessData(URL, data, ' ', MaxURLSize)) {
                    Stage = EParseStage::Protocol;
                }
                break;
            }
            case EParseStage::Protocol: {
                if (ProcessData(Protocol, data, '/', MaxProtocolSize)) {
                    Stage = EParseStage::Version;
                }
                break;
            }
            case EParseStage::Version: {
                if (ProcessData(Version, data, "\r\n", MaxVersionSize)) {
                    Stage = EParseStage::Header;
                    Headers = data;
                }
                break;
            }
            case EParseStage::Header: {
                if (ProcessData(Header, data, "\r\n", MaxHeaderSize)) {
                    if (Header.empty()) {
                        if (HaveBody()) {
                            Stage = EParseStage::Body;
                        } else {
                            Stage = EParseStage::Done;
                        }
                    } else {
                        ProcessHeader(Header);
                    }
                    Headers = TStringBuf(Headers.data(), data.data() - Headers.data());
                }
                break;
            }
            case EParseStage::Body: {
                if (!ContentLength.empty()) {
                    if (ProcessData(Content, data, FromString(ContentLength))) {
                        Body = Content;
                        Stage = EParseStage::Done;
                    }
                } else if (TEqNoCase()(TransferEncoding, "chunked")) {
                    Stage = EParseStage::ChunkLength;
                } else if (TotalSize.has_value()) {
                    if (ProcessData(Content, data, GetBodySizeFromTotalSize())) {
                        Body = Content;
                        Stage = EParseStage::Done;
                    }
                } else {
                    // Invalid body encoding
                    Stage = EParseStage::Error;
                }
                break;
            }
            case EParseStage::ChunkLength: {
                if (ProcessData(Line, data, "\r\n", MaxChunkLengthSize)) {
                    if (!Line.empty()) {
                        ChunkLength = ParseHex(Line);
                        if (ChunkLength <= MaxChunkSize) {
                            ContentSize = Content.size() + ChunkLength;
                            if (ContentSize <= MaxChunkContentSize) {
                                Stage = EParseStage::ChunkData;
                                Line.Clear();
                            } else {
                                // Invalid chunk content length
                                Stage = EParseStage::Error;
                            }
                        } else {
                            // Invalid chunk length
                            Stage = EParseStage::Error;
                        }
                    } else {
                        // Invalid body encoding
                        Stage = EParseStage::Error;
                    }
                }
                break;
            }
            case EParseStage::ChunkData: {
                if (!IsError()) {
                    if (ProcessData(Content, data, ContentSize)) {
                        if (ProcessData(Line, data, 2)) {
                            if (Line == "\r\n") {
                                if (ChunkLength == 0) {
                                    Body = Content;
                                    Stage = EParseStage::Done;
                                } else {
                                    Stage = EParseStage::ChunkLength;
                                }
                                Line.Clear();
                            } else {
                                // Invalid body encoding
                                Stage = EParseStage::Error;
                            }
                        }
                    }
                }
                break;
            }

            case EParseStage::Done:
            case EParseStage::Error: {
                data.Clear();
                break;
            }
            default:
                Y_FAIL("Invalid processing sequence");
                break;
        }
    }
    TSocketBuffer::Advance(len);
}

template <>
THttpParser<THttpRequest, TSocketBuffer>::EParseStage THttpParser<THttpRequest, TSocketBuffer>::GetInitialStage() {
    return EParseStage::Method;
}

template <>
bool THttpParser<THttpResponse, TSocketBuffer>::HaveBody() const {
    if (!Body.empty()) {
        return true;
    }
    return (!Status.starts_with("1") && Status != "204" && Status != "304")
        && (!ContentType.empty() || !ContentLength.empty() || !TransferEncoding.empty());
}

template <>
THttpParser<THttpResponse, TSocketBuffer>::EParseStage THttpParser<THttpResponse, TSocketBuffer>::GetInitialStage() {
    return EParseStage::Protocol;
}

void THttpResponse::Clear() {
    // a dirty little trick
    this->~THttpResponse(); // basically, do nothing
    new (this) THttpResponse(); // reset all fields
}

template <>
void THttpParser<THttpResponse, TSocketBuffer>::Advance(size_t len) {
    TStringBuf data(Pos(), len);
    while (!data.empty()) {
        if (Stage != EParseStage::Error) {
            LastSuccessStage = Stage;
        }
        switch (Stage) {
            case EParseStage::Protocol: {
                if (ProcessData(Protocol, data, '/', MaxProtocolSize)) {
                    Stage = EParseStage::Version;
                }
                break;
            }
            case EParseStage::Version: {
                if (ProcessData(Version, data, ' ', MaxVersionSize)) {
                    Stage = EParseStage::Status;
                }
                break;
            }
            case EParseStage::Status: {
                if (ProcessData(Status, data, ' ', MaxStatusSize)) {
                    Stage = EParseStage::Message;
                }
                break;
            }
            case EParseStage::Message: {
                if (ProcessData(Message, data, "\r\n", MaxMessageSize)) {
                    Stage = EParseStage::Header;
                    Headers = TStringBuf(data.data(), size_t(0));
                }
                break;
            }
            case EParseStage::Header: {
                if (ProcessData(Header, data, "\r\n", MaxHeaderSize)) {
                    if (Header.empty()) {
                        if (HaveBody() && (ContentLength.empty() || ContentLength != "0")) {
                            Stage = EParseStage::Body;
                        } else if (TotalSize.has_value() && !data.empty()) {
                            Stage = EParseStage::Body;
                        } else {
                            Stage = EParseStage::Done;
                        }
                    } else {
                        ProcessHeader(Header);
                    }
                    Headers = TStringBuf(Headers.data(), data.data() - Headers.data());
                }
                break;
            }
            case EParseStage::Body: {
                if (!ContentLength.empty()) {
                    if (ProcessData(Body, data, FromString(ContentLength))) {
                        Stage = EParseStage::Done;
                        if (Body && ContentEncoding == "deflate") {
                            Content = DecompressDeflate(Body);
                            Body = Content;
                        }
                    }
                } else if (TEqNoCase()(TransferEncoding, "chunked")) {
                    Stage = EParseStage::ChunkLength;
                } else if (TotalSize.has_value()) {
                    if (ProcessData(Content, data, GetBodySizeFromTotalSize())) {
                        Body = Content;
                        Stage = EParseStage::Done;
                        if (Body && ContentEncoding == "deflate") {
                            Content = DecompressDeflate(Body);
                            Body = Content;
                        }
                    }
                } else {
                    // Invalid body encoding
                    Stage = EParseStage::Error;
                }
                break;
            }
            case EParseStage::ChunkLength: {
                if (ProcessData(Line, data, "\r\n", MaxChunkLengthSize)) {
                    if (!Line.empty()) {
                        ChunkLength = ParseHex(Line);
                        if (ChunkLength <= MaxChunkSize) {
                            ContentSize = Content.size() + ChunkLength;
                            if (ContentSize <= MaxChunkContentSize) {
                                Stage = EParseStage::ChunkData;
                                Line.Clear();
                            } else {
                                // Invalid chunk content length
                                Stage = EParseStage::Error;
                            }
                        } else {
                            // Invalid chunk length
                            Stage = EParseStage::Error;
                        }
                    } else {
                        // Invalid body encoding
                        Stage = EParseStage::Error;
                    }
                }
                break;
            }
            case EParseStage::ChunkData: {
                if (!IsError()) {
                    if (ProcessData(Content, data, ContentSize)) {
                        if (ProcessData(Line, data, 2)) {
                            if (Line == "\r\n") {
                                if (ChunkLength == 0) {
                                    Body = Content;
                                    Stage = EParseStage::Done;
                                    if (Body && ContentEncoding == "deflate") {
                                        Content = DecompressDeflate(Body);
                                        Body = Content;
                                    }
                                } else {
                                    Stage = EParseStage::ChunkLength;
                                }
                                Line.Clear();
                            } else {
                                // Invalid body encoding
                                Stage = EParseStage::Error;
                            }
                        }
                    }
                }
                break;
            }
            case EParseStage::Done:
            case EParseStage::Error:
                data.Clear();
                break;
            default:
                // Invalid processing sequence
                Stage = EParseStage::Error;
                break;
        }
    }
    TSocketBuffer::Advance(len);
}

template <>
void THttpParser<THttpResponse, TSocketBuffer>::ConnectionClosed() {
    if (Stage == EParseStage::Done) {
        return;
    }
    if (Stage == EParseStage::Body) {
        // ?
        Stage = EParseStage::Done;
    } else {
        LastSuccessStage = Stage;
        Stage = EParseStage::Error;
    }
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseString(TStringBuf data) {
    THttpParser<THttpResponse, TSocketBuffer> parser(data);
    THeadersBuilder headers(parser.Headers);
    if (!Endpoint->WorkerName.empty()) {
        headers.Set("X-Worker-Name", Endpoint->WorkerName);
    }
    THttpOutgoingResponsePtr response = new THttpOutgoingResponse(this);
    response->InitResponse(parser.Protocol, parser.Version, parser.Status, parser.Message);
    if (parser.HaveBody()) {
        if (parser.ContentType && !Endpoint->CompressContentTypes.empty()) {
            TStringBuf contentType = parser.ContentType.Before(';');
            Trim(contentType, ' ');
            if (Count(Endpoint->CompressContentTypes, contentType) != 0) {
                if (response->EnableCompression()) {
                    headers.Erase("Content-Length"); // we will need new length after compression
                }
            }
        }
        response->Set(headers);
        response->SetBody(parser.Body);
    } else {
        response->Set(headers);
        if (!response->ContentLength) {
            response->Set<&THttpResponse::ContentLength>("0");
        }
    }
    return response;
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseOK(TStringBuf body, TStringBuf contentType, TInstant lastModified) {
    return CreateResponse("200", "OK", contentType, body, lastModified);
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseBadRequest(TStringBuf html, TStringBuf contentType) {
    if (html.empty() && IsError()) {
        contentType = "text/plain";
        html = GetErrorText();
    }
    return CreateResponse("400", "Bad Request", contentType, html);
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseNotFound(TStringBuf html, TStringBuf contentType) {
    return CreateResponse("404", "Not Found", contentType, html);
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseServiceUnavailable(TStringBuf html, TStringBuf contentType) {
    return CreateResponse("503", "Service Unavailable", contentType, html);
}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponseGatewayTimeout(TStringBuf html, TStringBuf contentType) {
    return CreateResponse("504", "Gateway Timeout", contentType, html);
}

THttpIncomingResponse::THttpIncomingResponse(THttpOutgoingRequestPtr request)
    : Request(request)
{}

THttpOutgoingResponsePtr THttpIncomingRequest::CreateResponse(TStringBuf status, TStringBuf message, TStringBuf contentType, TStringBuf body, TInstant lastModified) {
    TStringBuf version = Version;
    if (version != "1.0" && version != "1.1") {
        version = "1.1";
    }
    THttpOutgoingResponsePtr response = new THttpOutgoingResponse(this, "HTTP", version, status, message);
    response->Set<&THttpResponse::Connection>(GetConnection());
    if (!Endpoint->WorkerName.empty()) {
        response->Set("X-Worker-Name", Endpoint->WorkerName);
    }
    if (!contentType.empty() && !body.empty()) {
        response->Set<&THttpResponse::ContentType>(contentType);
        if (!Endpoint->CompressContentTypes.empty()) {
            contentType = contentType.Before(';');
            Trim(contentType, ' ');
            if (Count(Endpoint->CompressContentTypes, contentType) != 0) {
                response->EnableCompression();
            }
        }
    }
    if (lastModified) {
        response->Set<&THttpResponse::LastModified>(lastModified.FormatGmTime("%a, %d %b %Y %H:%M:%S GMT"));
    }
    if (response->IsNeedBody() || !body.empty()) {
        if (Method == "HEAD") {
            response->Set<&THttpResponse::ContentLength>(ToString(body.size()));
        } else {
            response->SetBody(body);
        }
    }
    return response;
}

THttpIncomingRequestPtr THttpIncomingRequest::Duplicate() {
    THttpIncomingRequestPtr request = new THttpIncomingRequest(*this);
    request->Reparse();
    request->Timer.Reset();
    return request;
}

THttpIncomingResponsePtr THttpIncomingResponse::Duplicate(THttpOutgoingRequestPtr request) {
    THttpIncomingResponsePtr response = new THttpIncomingResponse(*this);
    response->Reparse();
    response->Request = request;
    return response;
}

THttpOutgoingResponsePtr THttpOutgoingResponse::Duplicate(THttpIncomingRequestPtr request) {
    THeadersBuilder headers(Headers);
    if (!request->Endpoint->WorkerName.empty()) {
        headers.Set("X-Worker-Name", request->Endpoint->WorkerName);
    }
    THttpOutgoingResponsePtr response = new THttpOutgoingResponse(request);
    response->InitResponse(Protocol, Version, Status, Message);
    if (Body) {
        if (ContentType && !request->Endpoint->CompressContentTypes.empty()) {
            TStringBuf contentType = ContentType.Before(';');
            Trim(contentType, ' ');
            if (Count(request->Endpoint->CompressContentTypes, contentType) != 0) {
                if (response->EnableCompression()) {
                    headers.Erase("Content-Length"); // we will need new length after compression
                }
            }
        }
        response->Set(headers);
        response->SetBody(Body);
    } else {
        response->Set(headers);
        if (!response->ContentLength) {
            response->Set<&THttpResponse::ContentLength>("0");
        }
    }
    return response;
}


THttpOutgoingResponsePtr THttpIncomingResponse::Reverse(THttpIncomingRequestPtr request) {
    THttpOutgoingResponsePtr response = new THttpOutgoingResponse(request);
    response->Assign(Data(), Size());
    response->Reparse();
    return response;
}

THttpOutgoingRequest::THttpOutgoingRequest(TStringBuf method, TStringBuf scheme, TStringBuf host, TStringBuf uri, TStringBuf protocol, TStringBuf version) {
    Secure = (scheme == "https");
    TString urie = UrlEscapeRet(uri);
    InitRequest(method, urie, protocol, version);
    if (host) {
        Set<&THttpRequest::Host>(host);
    }
}

THttpOutgoingRequest::THttpOutgoingRequest(TStringBuf method, TStringBuf url, TStringBuf protocol, TStringBuf version) {
    TStringBuf scheme, host, uri;
    if (!CrackURL(url, scheme, host, uri)) {
        Y_FAIL("Invalid URL specified");
    }
    if (!scheme.empty() && scheme != "http" && scheme != "https") {
        Y_FAIL("Invalid URL specified");
    }
    Secure = (scheme == "https");
    TString urie = UrlEscapeRet(uri);
    InitRequest(method, urie, protocol, version);
    if (host) {
        Set<&THttpRequest::Host>(host);
    }
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequestString(const TString& data) {
    THttpOutgoingRequestPtr request = new THttpOutgoingRequest();
    request->Assign(data.data(), data.size());
    request->Reparse();
    return request;
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequestGet(TStringBuf url) {
    return CreateRequest("GET", url);
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequestGet(TStringBuf host, TStringBuf uri) {
    return CreateHttpRequest("GET", host, uri);
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequestPost(TStringBuf url, TStringBuf contentType, TStringBuf body) {
    return CreateRequest("POST", url, contentType, body);
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequestPost(TStringBuf host, TStringBuf uri, TStringBuf contentType, TStringBuf body) {
    return CreateHttpRequest("POST", host, uri, contentType, body);
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateRequest(TStringBuf method, TStringBuf url, TStringBuf contentType, TStringBuf body) {
    THttpOutgoingRequestPtr request = new THttpOutgoingRequest(method, url, "HTTP", "1.1");
    request->Set<&THttpRequest::Accept>("*/*");
    if (!contentType.empty()) {
        request->Set<&THttpRequest::ContentType>(contentType);
        request->Set<&THttpRequest::Body>(body);
    }
    return request;
}

THttpOutgoingRequestPtr THttpOutgoingRequest::CreateHttpRequest(TStringBuf method, TStringBuf host, TStringBuf uri, TStringBuf contentType, TStringBuf body) {
    THttpOutgoingRequestPtr request = new THttpOutgoingRequest(method, "http", host, uri, "HTTP", "1.1");
    request->Set<&THttpRequest::Accept>("*/*");
    if (!contentType.empty()) {
        request->Set<&THttpRequest::ContentType>(contentType);
        request->Set<&THttpRequest::Body>(body);
    }
    return request;
}

THttpOutgoingRequestPtr THttpOutgoingRequest::Duplicate() {
    THttpOutgoingRequestPtr request = new THttpOutgoingRequest(*this);
    request->Reparse();
    return request;
}

THttpOutgoingResponse::THttpOutgoingResponse(THttpIncomingRequestPtr request)
    : Request(request)
{}

THttpOutgoingResponse::THttpOutgoingResponse(THttpIncomingRequestPtr request, TStringBuf protocol, TStringBuf version, TStringBuf status, TStringBuf message)
    : Request(request)
{
    InitResponse(protocol, version, status, message);
}

const size_t THttpConfig::BUFFER_MIN_STEP;
const TDuration THttpConfig::CONNECTION_TIMEOUT;

TUrlParameters::TUrlParameters(TStringBuf url) {
    TStringBuf base;
    TStringBuf params;
    if (url.TrySplit('?', base, params)) {
        for (TStringBuf param = params.NextTok('&'); !param.empty(); param = params.NextTok('&')) {
            TStringBuf name = param.NextTok('=');
            Parameters[name] = param;
        }
    }
}

TString TUrlParameters::operator [](TStringBuf name) const {
    TString value(Get(name));
    CGIUnescape(value);
    return value;
}

bool TUrlParameters::Has(TStringBuf name) const {
    return Parameters.count(name) != 0;
}

TStringBuf TUrlParameters::Get(TStringBuf name) const {
    auto it = Parameters.find(name);
    if (it != Parameters.end()) {
        return it->second;
    }
    return TStringBuf();
}

TString TUrlParameters::Render() const {
    TStringBuilder parameters;
    for (const std::pair<TStringBuf, TStringBuf> parameter : Parameters) {
        if (parameters.empty()) {
            parameters << '?';
        } else {
            parameters << '&';
        }
        parameters << parameter.first;
        parameters << '=';
        parameters << parameter.second;
    }
    return parameters;
}

TCookies::TCookies(TStringBuf cookie) {
    for (TStringBuf param = cookie.NextTok(';'); !param.empty(); param = cookie.NextTok(';')) {
        param.SkipPrefix(" ");
        TStringBuf name = param.NextTok('=');
        Cookies[name] = param;
    }
}

TStringBuf TCookies::operator [](TStringBuf name) const {
    return Get(name);
}

bool TCookies::Has(TStringBuf name) const {
    return Cookies.count(name) != 0;
}

TStringBuf TCookies::Get(TStringBuf name) const {
    auto it = Cookies.find(name);
    if (it != Cookies.end()) {
        return it->second;
    }
    return TStringBuf();
}

TString TCookies::Render() const {
    TStringBuilder cookies;
    for (const std::pair<TStringBuf, TStringBuf> cookie : Cookies) {
        if (!cookies.empty()) {
            cookies << ' ';
        }
        cookies << cookie.first;
        cookies << '=';
        cookies << cookie.second;
        cookies << ';';
    }
    return cookies;
}

TCookiesBuilder::TCookiesBuilder()
    :TCookies(TStringBuf())
{}

void TCookiesBuilder::Set(TStringBuf name, TStringBuf data) {
    Data.emplace_back(name, data);
    Cookies[Data.back().first] = Data.back().second;
}

THeaders::THeaders(TStringBuf headers) {
    Parse(headers);
}

size_t THeaders::Parse(TStringBuf headers) {
    auto start = headers.begin();
    for (TStringBuf param = headers.NextTok("\r\n"); !param.empty(); param = headers.NextTok("\r\n")) {
        TStringBuf name = param.NextTok(":");
        param.SkipPrefix(" ");
        Headers[name] = param;
    }
    return headers.begin() - start;
}

TStringBuf THeaders::operator [](TStringBuf name) const {
    return Get(name);
}

bool THeaders::Has(TStringBuf name) const {
    return Headers.count(name) != 0;
}

TStringBuf THeaders::Get(TStringBuf name) const {
    auto it = Headers.find(name);
    if (it != Headers.end()) {
        return it->second;
    }
    return TStringBuf();
}

TString THeaders::Render() const {
    TStringBuilder headers;
    for (const std::pair<TStringBuf, TStringBuf> header : Headers) {
        headers << header.first;
        headers << ": ";
        headers << header.second;
        headers << "\r\n";
    }
    return headers;
}

THeadersBuilder::THeadersBuilder()
    : THeaders(TStringBuf())
{}

THeadersBuilder::THeadersBuilder(TStringBuf headers)
    : THeaders(headers)
{}

THeadersBuilder::THeadersBuilder(const THeadersBuilder& builder) {
    for (const auto& pr : builder.Headers) {
        Set(pr.first, pr.second);
    }
}

void THeadersBuilder::Set(TStringBuf name, TStringBuf data) {
    Data.emplace_back(name, data);
    Headers[Data.back().first] = Data.back().second;
}

void THeadersBuilder::Erase(TStringBuf name) {
    Headers.erase(name);
}

}