aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/http/io/chunk.cpp
blob: 1bdc0fbf4941eadafaca57946db64a9231552652 (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
#include "chunk.h"

#include "headers.h"

#include <util/string/cast.h>
#include <util/generic/utility.h>
#include <util/generic/yexception.h>

static inline size_t ParseHex(const TString& s) {
    if (s.empty()) {
        ythrow yexception() << "can not parse chunk length(empty string)";
    }

    size_t ret = 0;

    for (TString::const_iterator c = s.begin(); c != s.end(); ++c) {
        const char ch = *c;

        if (ch >= '0' && ch <= '9') {
            ret *= 16;
            ret += ch - '0';
        } else if (ch >= 'a' && ch <= 'f') {
            ret *= 16;
            ret += 10 + ch - 'a';
        } else if (ch >= 'A' && ch <= 'F') {
            ret *= 16;
            ret += 10 + ch - 'A';
        } else if (ch == ';') {
            break;
        } else if (isspace(ch)) {
            continue;
        } else {
            ythrow yexception() << "can not parse chunk length(" << s.data() << ")";
        }
    }

    return ret;
}

static inline char* ToHex(size_t len, char* buf) {
    do {
        const size_t val = len % 16;

        *--buf = (val < 10) ? (val + '0') : (val - 10 + 'a');
        len /= 16;
    } while (len);

    return buf;
}

class TChunkedInput::TImpl {
public:
    inline TImpl(IInputStream* slave, TMaybe<THttpHeaders>* trailers)
        : Slave_(slave)
        , Trailers_(trailers)
        , Pending_(0)
        , LastChunkReaded_(false)
    {
        if (Trailers_) {
            Trailers_->Clear();
        }
    }

    inline ~TImpl() {
    }

    inline size_t Read(void* buf, size_t len) {
        return Perform(len, [this, buf](size_t toRead) { return Slave_->Read(buf, toRead); }); 
    } 
 
    inline size_t Skip(size_t len) { 
        return Perform(len, [this](size_t toSkip) { return Slave_->Skip(toSkip); }); 
    } 
 
private: 
    template <class Operation>
    inline size_t Perform(size_t len, const Operation& operation) { 
        if (!HavePendingData()) {
            return 0;
        }

        const size_t toProcess = Min(Pending_, len); 

        if (toProcess) { 
            const size_t processed = operation(toProcess); 

            if (!processed) { 
                ythrow yexception() << "malformed http chunk";
            }

            Pending_ -= processed; 

            return processed; 
        }

        return 0;
    }

    inline bool HavePendingData() {
        if (LastChunkReaded_) {
            return false;
        }

        if (!Pending_) {
            if (!ProceedToNextChunk()) {
                return false;
            }
        }

        return true;
    }

    inline bool ProceedToNextChunk() {
        TString len(Slave_->ReadLine());

        if (len.empty()) {
            /*
             * skip crlf from previous chunk
             */

            len = Slave_->ReadLine();
        }

        Pending_ = ParseHex(len);

        if (Pending_) {
            return true;
        }

        if (Trailers_) {
            Trailers_->ConstructInPlace(Slave_);
        }
        LastChunkReaded_ = true;

        return false;
    }

private:
    IInputStream* Slave_;
    TMaybe<THttpHeaders>* Trailers_;
    size_t Pending_;
    bool LastChunkReaded_;
};

TChunkedInput::TChunkedInput(IInputStream* slave, TMaybe<THttpHeaders>* trailers)
    : Impl_(new TImpl(slave, trailers))
{
}

TChunkedInput::~TChunkedInput() {
}

size_t TChunkedInput::DoRead(void* buf, size_t len) {
    return Impl_->Read(buf, len);
}

size_t TChunkedInput::DoSkip(size_t len) { 
    return Impl_->Skip(len); 
} 
 
class TChunkedOutput::TImpl {
    typedef IOutputStream::TPart TPart;

public:
    inline TImpl(IOutputStream* slave)
        : Slave_(slave)
    {
    }

    inline ~TImpl() {
    }

    inline void Write(const void* buf, size_t len) {
        const char* ptr = (const char*)buf;

        while (len) {
            const size_t portion = Min<size_t>(len, 1024 * 16);

            WriteImpl(ptr, portion);

            ptr += portion;
            len -= portion;
        }
    }

    inline void WriteImpl(const void* buf, size_t len) {
        char tmp[32];
        char* e = tmp + sizeof(tmp);
        char* b = ToHex(len, e);

        const TPart parts[] = {
            TPart(b, e - b),
            TPart::CrLf(),
            TPart(buf, len),
            TPart::CrLf(),
        };

        Slave_->Write(parts, sizeof(parts) / sizeof(*parts));
    }

    inline void Flush() {
        Slave_->Flush();
    }

    inline void Finish() {
        Slave_->Write("0\r\n\r\n", 5);

        Flush();
    }

private:
    IOutputStream* Slave_;
};

TChunkedOutput::TChunkedOutput(IOutputStream* slave)
    : Impl_(new TImpl(slave))
{
}

TChunkedOutput::~TChunkedOutput() {
    try {
        Finish();
    } catch (...) {
    }
}

void TChunkedOutput::DoWrite(const void* buf, size_t len) {
    if (Impl_.Get()) {
        Impl_->Write(buf, len);
    } else {
        ythrow yexception() << "can not write to finished stream";
    }
}

void TChunkedOutput::DoFlush() {
    if (Impl_.Get()) {
        Impl_->Flush();
    }
}

void TChunkedOutput::DoFinish() {
    if (Impl_.Get()) {
        Impl_->Finish();
        Impl_.Destroy();
    }
}