streamproxy.cpp 16.4 KB
Newer Older
1
2
/* Copyright (C) 2017-2018 J.F.Dockes
 *   This program is free software; you can redistribute it and/or modify
3
4
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation; either version 2.1 of the License, or
5
6
7
8
9
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU Lesser General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU Lesser General Public License
13
14
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
Jean-Francois Dockes's avatar
Jean-Francois Dockes committed
15
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16
17
18
 */

#include "streamproxy.h"
19
#include "netfetch.h"
20
21
22
#ifdef MDU_INCLUDE_LOG
#include MDU_INCLUDE_LOG
#else
23
#include "log.h"
24
#endif
25
#include "smallut.h"
26
#include "chrono.h"
27

28
#include <fcntl.h>
29

Jean-Francois Dockes's avatar
shared    
Jean-Francois Dockes committed
30
#include <microhttpd.h>
31

32
#if MHD_VERSION <= 0x00097000
Jean-Francois Dockes's avatar
shared    
Jean-Francois Dockes committed
33
#define MHD_Result int
34
35
#endif

36
37
38
39
40
41
42
43
#include <mutex>
#include <condition_variable>
#include <unordered_map>

using namespace std;

class ContentReader {
public:
44
45
46
    ContentReader(std::unique_ptr<NetFetch> ftchr, int cfd)
        : fetcher(std::move(ftchr)), connfd(cfd) {
        
47
48
49
50
51
52
53
54
55
        // Set a timeout on the client side, so that connections can
        // be cleaned-up in a timely fashion if we stop providing
        // data. This is mostly for the versions of mpd which read the
        // top of the file then restart: the first connection would
        // never be cleaned up because it was waiting on the queue
        // which was not sending data (at least in the spotify case)
        // because the proxy was used for the second request.
        queue.set_take_timeout(
            std::chrono::milliseconds(std::chrono::seconds(10)));
56
57
    }

58
59
    ~ContentReader() {
        LOGDEB1("ContentReader::~ContentReader\n");
60
        // This should not be necessary but see comments in
61
        // tstcurlfetch code
62
        fetcher = std::unique_ptr<NetFetch>();
63
64
65
    }
    ssize_t contentRead(uint64_t pos, char *buf, size_t max);

66
    std::unique_ptr<NetFetch> fetcher;
67
68
    BufXChange<ABuffer*> queue{"crqueue"};
    bool normalEOS{false};
69
70
71
72
    // Used for experimentations in killing the connection
    int connfd{-1};
    int killafterms{-1};
    Chrono chron;
73
74
75
76
77
78
79
80
81
82
83
84
85
86
};


ssize_t ContentReader::contentRead(uint64_t pos, char *obuf, size_t max)
{
    LOGDEB1("ContentReader::contentRead: pos "<<pos << " max " << max << endl);
    if (normalEOS) {
        LOGDEB1("ContentReader::contentRead: return EOS\n");
        return MHD_CONTENT_READER_END_OF_STREAM;
    }
    size_t totcnt = 0;
    ABuffer *abuf;
    while (totcnt < max) {
        if (!queue.take(&abuf)) {
87
88
89
90
            NetFetch::FetchStatus code;
            int httpcode;
            fetcher->fetchDone(&code, &httpcode);
            LOGDEB("Reader: queue take failed code " << code <<
91
                   " httpcode " << httpcode << endl);
92
            if (code == NetFetch::FETCH_RETRYABLE) {
93
94
95
96
97
                LOGINF("Reader: retrying at " << pos+totcnt << endl);
                fetcher->reset();
                fetcher->start(&queue, pos+totcnt);
                return 0;
            }
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
            LOGDEB("ContentReader::contentRead: return ERROR\n");
            return MHD_CONTENT_READER_END_WITH_ERROR;
        }
        LOGDEB1("ContentReader::contentRead: got buffer with " <<
                abuf->bytes << " bytes\n");
        if (abuf->bytes == 0) {
            normalEOS = true;
            if (totcnt == 0) {
                LOGDEB1("ContentReader::contentRead: return EOS\n");
                return MHD_CONTENT_READER_END_OF_STREAM;
            } else {
                // Copied data, we will return eostream on next call.
                break;
            }
        }
        size_t tocopy = MIN(max-totcnt, abuf->bytes - abuf->curoffs);
        memcpy(obuf + totcnt, abuf->buf + abuf->curoffs, tocopy);
        totcnt += tocopy;
        abuf->curoffs += tocopy;
        if (abuf->curoffs >= abuf->bytes) {
            queue.recycle(abuf);
        } else {
            queue.untake(abuf);
        }
    }
123
124
125
126
127
128
129
130
131
132
133
    if (killafterms > 0 && connfd >= 0) {
        if (chron.millis() > killafterms) {
            int fd = open("/dev/null", 0);
            if (fd < 0) {
                abort();
            }
            dup2(fd, connfd);
            close(fd);
            connfd = -1;
        }
    }
134
135
136
137
138
139
140
141
142
143
144
145
146
147
    LOGDEB1("ContentReader::contentRead: return " << totcnt << endl);
    return totcnt;
}

static ssize_t content_reader_cb(void *cls, uint64_t pos, char *buf, size_t max)
{
    ContentReader *reader = static_cast<ContentReader*>(cls);
    if (reader) {
        return reader->contentRead(pos, buf, max);
    } else {
        return -1;
    }
}

148
149
150
151
152
153
154
155
void content_reader_free_callback(void *cls)
{
    LOGDEB("content_reader_free_callback\n");
    if (cls) {
        ContentReader *reader = static_cast<ContentReader*>(cls);
        delete reader;
    }
}
156
157
158
159
160
161
162

class StreamProxy::Internal {
public:
    Internal(int listenport, UrlTransFunc urlt);
    ~Internal();
    bool startMHD();

163
    MHD_Result answerConn(
164
165
166
167
168
169
170
171
172
173
174
175
        struct MHD_Connection *connection, const char *url, 
        const char *method, const char *version, 
        const char *upload_data, size_t *upload_data_size,
        void **con_cls);

    void requestCompleted(
        struct MHD_Connection *conn,
        void **con_cls, enum MHD_RequestTerminationCode toe);

    int listenport{-1};
    UrlTransFunc urltrans;
    struct MHD_Daemon *mhd{nullptr};
176
    int killafterms{-1};
177
178
179
180
181
182
183
184
};


StreamProxy::StreamProxy(int listenport,UrlTransFunc urltrans)
    : m(new Internal(listenport, urltrans))
{
}

185
186
187
188
189
void StreamProxy::setKillAfterMs(int ms)
{
    m->killafterms = ms;
}

190
191
192
StreamProxy::~StreamProxy()
{
}
193

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
StreamProxy::Internal::~Internal()
{
    LOGDEB("StreamProxy::Internal::~Internal()\n");
    if (mhd) {
        MHD_stop_daemon(mhd);
        mhd = nullptr;
    }
}

StreamProxy::Internal::Internal(int _listenport, UrlTransFunc _urltrans)
    : listenport(_listenport), urltrans(_urltrans)
{
    startMHD();
}


210
static MHD_Result answer_to_connection(
211
212
213
214
215
216
217
218
219
220
221
    void *cls, struct MHD_Connection *conn, 
    const char *url, const char *method, const char *version, 
    const char *upload_data, size_t *upload_data_size,
    void **con_cls)
{
    StreamProxy::Internal *internal = static_cast<StreamProxy::Internal*>(cls);
    
    if (internal) {
        return internal->answerConn(
            conn, url, method, version, upload_data, upload_data_size, con_cls);
    } else {
222
        return MHD_NO;
223
224
225
    }
}

226
#undef PRINT_KEYS
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#ifdef PRINT_KEYS
static vector<CharFlags> valueKind {
    {MHD_RESPONSE_HEADER_KIND, "Response header"},
    {MHD_HEADER_KIND, "HTTP header"},
    {MHD_COOKIE_KIND, "Cookies"},
    {MHD_POSTDATA_KIND, "POST data"},
    {MHD_GET_ARGUMENT_KIND, "GET (URI) arguments"},
    {MHD_FOOTER_KIND, "HTTP footer"},
        };

static int print_out_key (void *cls, enum MHD_ValueKind kind, 
                          const char *key, const char *value)
{
    LOGDEB(valToString(valueKind, kind) << ": " << key << " -> " <<
           value << endl);
    return MHD_YES;
}
#endif /* PRINT_KEYS */

246
247
static MHD_Result mapvalues_cb(void *cls, enum MHD_ValueKind kind, 
                               const char *key, const char *value)
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
{
    unordered_map<string,string> *mp = (unordered_map<string,string> *)cls;
    if (mp) {
        (*mp)[key] = value;
    }
    return MHD_YES;
}

// Parse range header. 
static bool parseRanges(
    const string& ranges, vector<pair<int64_t, int64_t>>& oranges)
{
    oranges.clear();
    string::size_type pos = ranges.find("bytes=");
    if (pos == string::npos) {
        return false;
    }
    pos += 6;
    bool done = false;
    while(!done) {
        string::size_type dash = ranges.find('-', pos);
        if (dash == string::npos) {
            return false;
        }
        string::size_type comma = ranges.find(',', pos);
        string firstPart = ranges.substr(pos, dash-pos);
        int64_t start = firstPart.empty() ? 0 : atoll(firstPart.c_str());
        string secondPart = ranges.substr(dash+1, comma != string::npos ? 
                                          comma-dash-1 : string::npos);
        int64_t fin = secondPart.empty() ? -1 : atoll(secondPart.c_str());
        pair<int64_t, int64_t> nrange(start,fin);
        oranges.push_back(nrange);
        if (comma != string::npos) {
            pos = comma + 1;
        }
        done = comma == string::npos;
    }
    return true;
}

static bool processRange(struct MHD_Connection *mhdconn, uint64_t& offset)
{
    const char* rangeh =
        MHD_lookup_connection_value(mhdconn, MHD_HEADER_KIND, "range");
292
293
294
295
    if (!rangeh) {
        LOGDEB1("NO RANGE\n");
        return true;
    }
296
    vector<pair<int64_t, int64_t> > ranges;
297
    if (parseRanges(rangeh, ranges) && ranges.size()) {
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        if (ranges[0].second != -1 || ranges.size() > 1) {
            LOGERR("AProxy::mhdAnswerConn: unsupported range: " <<
                   rangeh << "\n");
            struct MHD_Response *response = 
                MHD_create_response_from_buffer(0,0,MHD_RESPMEM_PERSISTENT);
            MHD_queue_response(mhdconn, 416, response);
            MHD_destroy_response(response);
            return false;
        } else {
            offset = (uint64_t)ranges[0].first;
            LOGDEB("AProxy::mhdAnswerConn: accept xx- range, offset "
                   << offset << endl);
        }
    }
    return true;
}

315
MHD_Result StreamProxy::Internal::answerConn(
316
317
318
319
320
    struct MHD_Connection *mhdconn, const char *_url,
    const char *method, const char *version, 
    const char *upload_data, size_t *upload_data_size,
    void **con_cls)
{
321
    LOGDEB1("answerConn con_cls " << *con_cls << "\n");
322
323
    NetFetch::FetchStatus fetchcode;
    int httpcode;
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

    if (nullptr == *con_cls) {
        uint64_t offset = 0;
        // First call, look at headers, method etc.
#ifdef PRINT_KEYS
        MHD_get_connection_values(mhdconn,MHD_HEADER_KIND,&print_out_key,0);
#endif
        if (strcmp("GET", method) && strcmp("HEAD", method)) {
            LOGERR("StreamProxy::answerConn: method is not GET or HEAD\n");
            return MHD_NO;
        }
        if (!processRange(mhdconn, offset)) {
            return MHD_NO;
        }

        // Compute destination url
        unordered_map<string,string>querydata;
        MHD_get_connection_values(mhdconn, MHD_GET_ARGUMENT_KIND,
                                  &mapvalues_cb, &querydata);
343
344
345

        // Request the method (redirect or proxy), and the fetcher if
        // we are proxying.
346
        string url(_url);
347
348
349
        std::unique_ptr<NetFetch> fetcher;
        UrlTransReturn ret = urltrans(url, querydata, fetcher);
        
350
351
352
353
354
355
356
357
358
359
        if (ret == Error) {
            return MHD_NO;
        } else if (ret == Redirect) {
            struct MHD_Response *response =
                MHD_create_response_from_buffer(0, 0, MHD_RESPMEM_PERSISTENT);
            if (nullptr == response ) {
                LOGERR("StreamProxy::answerConn: can't create redirect\n");
                return MHD_NO;
            }
            MHD_add_response_header (response, "Location", url.c_str());
360
            MHD_Result ret = MHD_queue_response(mhdconn, 302, response);
361
362
363
364
            MHD_destroy_response(response);
            return ret;
        }

365
366
367
        // The connection fd thing is strictly for debug/diag: faking
        // a connection loss so that the client side can exercise the
        // retry code.
368
369
370
371
372
373
374
375
        int cfd{-1};
        const union MHD_ConnectionInfo *cinf =
            MHD_get_connection_info(mhdconn, MHD_CONNECTION_INFO_CONNECTION_FD);
        if (nullptr == cinf) {
            LOGERR("StreamProxy::answerConn: can't get connection fd\n");
        } else {
            cfd = cinf->connect_fd;
        }
376

377
        // Create/Start the fetch transaction.
378
379
        LOGDEB0("StreamProxy::answerConn: starting fetch for " << url << endl);
        auto reader = new ContentReader(std::move(fetcher), cfd);
380
381
382
383
        if (killafterms > 0) {
            reader->killafterms = killafterms;
            killafterms = -1;
        }
384
385
        reader->fetcher->start(&reader->queue, offset);
        *con_cls = reader;
386

387
        LOGDEB1("StreamProxy::answerConn: returning after 1st call\n");
388
389
390
391
        return MHD_YES;
        // End first call
    }

392
    // Second call for this request (*con_cls is set)
393
394
395
396
    ContentReader *reader = (ContentReader*)*con_cls;
    
    if (!reader->fetcher->waitForHeaders()) {
        LOGDEB("StreamProxy::answerConn: waitForHeaders error\n");
397
        reader->fetcher->fetchDone(&fetchcode, &httpcode);
398
399
400
        int code = httpcode ? httpcode : MHD_HTTP_INTERNAL_SERVER_ERROR;
        struct MHD_Response *response =
            MHD_create_response_from_buffer(0, 0, MHD_RESPMEM_PERSISTENT);
401
        MHD_Result ret = MHD_queue_response(mhdconn, code, response);
402
403
404
405
406
        MHD_destroy_response(response);
        LOGINF("StreamProxy::answerConn (1): return with http code: " <<
               code << endl);
        return ret;
    }
407
    LOGDEB1("StreamProxy::answerConn: waitForHeaders done\n");
408
409
410
411
412
413
414
415
416
417
418
419

    string cl;
    uint64_t size = MHD_SIZE_UNKNOWN;
    if (reader->fetcher->headerValue("content-length", cl) && !cl.empty()) {
        LOGDEB1("mhdAnswerConn: header content-length: " << cl << endl);
        size  = (uint64_t)atoll(cl.c_str());
    }
    // Build a data response.
    // the block size seems to be flatly ignored by libmicrohttpd
    // Any random value would probably work the same
    struct MHD_Response *response = 
        MHD_create_response_from_callback(size, 4096,
420
421
                                          content_reader_cb, reader,
                                          content_reader_free_callback);
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
    if (response == NULL) {
        LOGERR("mhdAnswerConn: answer: could not create response" << endl);
        return MHD_NO;
    }

    MHD_add_response_header (response, "Accept-Ranges", "bytes");
    if (!cl.empty()) {
        MHD_add_response_header(response, "Content-Length", cl.c_str());
    }
    string ct;
    if (reader->fetcher->headerValue("content-type", ct) && !ct.empty()) {
        LOGDEB1("mhdAnswerConn: header content-type: " << ct << endl);
        MHD_add_response_header(response, "Content-Type", ct.c_str());
    }

    int code = MHD_HTTP_OK;
438
439
    LOGDEB1("StreamProxy::answerConn: calling fetchDone\n");
    if (reader->fetcher->fetchDone(&fetchcode, &httpcode)) {
440
441
        code = httpcode ? httpcode : MHD_HTTP_INTERNAL_SERVER_ERROR;
    }
442
    MHD_Result ret = MHD_queue_response(mhdconn, code, response);
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
    MHD_destroy_response(response);
    return ret;
}

static void
request_completed_callback(
    void *cls, struct MHD_Connection *conn,
    void **con_cls, enum MHD_RequestTerminationCode toe)
{
    // We get this even if the answer callback returned MHD_NO
    // (e.g. for a second connection). check con_cls and do nothing if
    // it's not set.
    if (cls && *con_cls) {
        StreamProxy::Internal *internal =
            static_cast<StreamProxy::Internal*>(cls);
        return internal->requestCompleted(conn, con_cls, toe);
    }
}

static vector<CharFlags> completionStatus {
    {MHD_REQUEST_TERMINATED_COMPLETED_OK,
            "MHD_REQUEST_TERMINATED_COMPLETED_OK", ""},
    {MHD_REQUEST_TERMINATED_WITH_ERROR,
            "MHD_REQUEST_TERMINATED_WITH_ERROR", ""},
    {MHD_REQUEST_TERMINATED_TIMEOUT_REACHED,
            "MHD_REQUEST_TERMINATED_TIMEOUT_REACHED", ""},
    {MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN,
            "MHD_REQUEST_TERMINATED_DAEMON_SHUTDOWN", ""},
    {MHD_REQUEST_TERMINATED_READ_ERROR,
            "MHD_REQUEST_TERMINATED_READ_ERROR", ""},
    {MHD_REQUEST_TERMINATED_CLIENT_ABORT,
            "MHD_REQUEST_TERMINATED_CLIENT_ABORT", ""},
        };

void StreamProxy::Internal::requestCompleted(
    struct MHD_Connection *conn,
    void **con_cls, enum MHD_RequestTerminationCode toe)
{
    LOGDEB("StreamProxy::requestCompleted: status " <<
482
483
484
           valToString(completionStatus, toe) << " *con_cls "<<*con_cls << endl);
    // The content reader was supposedly deleted by the content_reader_free
    // callback...
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
}

bool StreamProxy::Internal::startMHD()
{
    mhd = MHD_start_daemon(
        MHD_USE_THREAD_PER_CONNECTION|MHD_USE_SELECT_INTERNALLY|MHD_USE_DEBUG,
        listenport, 
        /* Accept policy callback and arg */
        nullptr, nullptr, 
        /* handler and arg */
        &answer_to_connection, this,
        MHD_OPTION_NOTIFY_COMPLETED, request_completed_callback, this,
        MHD_OPTION_END);

    if (nullptr == mhd) {
        LOGERR("Aproxy: MHD_start_daemon failed\n");
        return false;
    }

    return true;
}