Blame view

trunk/src/app/srs_app_http.cpp 25.8 KB
1 2 3
/*
The MIT License (MIT)
4
Copyright (c) 2013-2014 winlin
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
24
#include <srs_app_http.hpp>
25
26
#ifdef SRS_AUTO_HTTP_PARSER
27
winlin authored
28 29
#include <stdlib.h>
30 31
using namespace std;
32
#include <srs_kernel_error.hpp>
33
#include <srs_kernel_log.hpp>
34
#include <srs_app_st_socket.hpp>
winlin authored
35 36
#include <srs_app_http_api.hpp>
#include <srs_app_http_conn.hpp>
37
#include <srs_app_json.hpp>
38
#include <srs_kernel_utility.hpp>
winlin authored
39 40 41

#define SRS_DEFAULT_HTTP_PORT 80
winlin authored
42 43
#define SRS_HTTP_HEADER_BUFFER 1024
winlin authored
44 45 46 47 48 49 50
// for http parser macros
#define SRS_CONSTS_HTTP_OPTIONS HTTP_OPTIONS
#define SRS_CONSTS_HTTP_GET HTTP_GET
#define SRS_CONSTS_HTTP_POST HTTP_POST
#define SRS_CONSTS_HTTP_PUT HTTP_PUT
#define SRS_CONSTS_HTTP_DELETE HTTP_DELETE
51 52 53 54 55 56 57 58
bool srs_path_equals(const char* expect, const char* path, int nb_path)
{
    int size = strlen(expect);
    
    if (size != nb_path) {
        return false;
    }
    
59 60
    bool equals = !memcmp(expect, path, size);
    return equals;
61 62
}
63 64 65 66 67 68 69
bool srs_path_like(const char* expect, const char* path, int nb_path)
{
    int size = strlen(expect);
    bool equals = !strncmp(expect, path, srs_min(size, nb_path));
    return equals;
}
70 71 72 73 74
SrsHttpHandlerMatch::SrsHttpHandlerMatch()
{
    handler = NULL;
}
winlin authored
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
SrsHttpHandler::SrsHttpHandler()
{
}

SrsHttpHandler::~SrsHttpHandler()
{
    std::vector<SrsHttpHandler*>::iterator it;
    for (it = handlers.begin(); it != handlers.end(); ++it) {
        SrsHttpHandler* handler = *it;
        srs_freep(handler);
    }
    handlers.clear();
}

int SrsHttpHandler::initialize()
{
    int ret = ERROR_SUCCESS;
    return ret;
}
95
bool SrsHttpHandler::can_handle(const char* /*path*/, int /*length*/, const char** /*pchild*/)
winlin authored
96 97 98 99
{
    return false;
}
100
int SrsHttpHandler::process_request(SrsStSocket* skt, SrsHttpMessage* req)
101
{
winlin authored
102
    if (req->method() == SRS_CONSTS_HTTP_OPTIONS) {
103
        req->set_requires_crossdomain(true);
104 105
        return res_options(skt);
    }
106 107 108 109 110 111

    int status_code;
    std::string reason_phrase;
    if (!is_handler_valid(req, status_code, reason_phrase)) {
        std::stringstream ss;
        
winlin authored
112 113 114 115 116 117 118 119
        ss << __SRS_JOBJECT_START
            << __SRS_JFIELD_ERROR(ERROR_HTTP_HANDLER_INVALID) << __SRS_JFIELD_CONT
            << __SRS_JFIELD_ORG("data", __SRS_JOBJECT_START)
                << __SRS_JFIELD_ORG("status_code", status_code) << __SRS_JFIELD_CONT
                << __SRS_JFIELD_STR("reason_phrase", reason_phrase) << __SRS_JFIELD_CONT
                << __SRS_JFIELD_STR("url", req->url())
            << __SRS_JOBJECT_END
            << __SRS_JOBJECT_END;
120
        
121
        return res_error(skt, req, status_code, reason_phrase, ss.str());
122
    }
123 124 125 126
    
    return do_process_request(skt, req);
}
127
bool SrsHttpHandler::is_handler_valid(SrsHttpMessage* req, int& status_code, string& reason_phrase) 
128 129
{
    if (!req->match()->unmatched_url.empty()) {
winlin authored
130 131
        status_code = SRS_CONSTS_HTTP_NotFound;
        reason_phrase = SRS_CONSTS_HTTP_NotFound_str;
132 133 134 135 136 137 138
        
        return false;
    }
    
    return true;
}
139
int SrsHttpHandler::do_process_request(SrsStSocket* /*skt*/, SrsHttpMessage* /*req*/)
winlin authored
140 141 142 143 144
{
    int ret = ERROR_SUCCESS;
    return ret;
}
145
int SrsHttpHandler::response_error(SrsStSocket* skt, SrsHttpMessage* req, int code, string desc)
146 147
{
    std::stringstream ss;
winlin authored
148 149 150 151
    ss << __SRS_JOBJECT_START
        << __SRS_JFIELD_ERROR(code) << __SRS_JFIELD_CONT
        << __SRS_JFIELD_STR("desc", desc)
        << __SRS_JOBJECT_END;
152 153 154 155
    
    return res_json(skt, req, ss.str());
}
156
int SrsHttpHandler::best_match(const char* path, int length, SrsHttpHandlerMatch** ppmatch)
winlin authored
157 158 159
{
    int ret = ERROR_SUCCESS;
    
160 161 162 163
    SrsHttpHandler* handler = NULL;
    const char* match_start = NULL;
    int match_length = 0;
    
winlin authored
164 165 166 167 168 169 170 171
    for (;;) {
        // ensure cur is not NULL.
        // ensure p not NULL and has bytes to parse.
        if (!path || length <= 0) {
            break;
        }
        
        const char* p = NULL;
winlin authored
172
        for (p = path + 1; p - path < length && *p != SRS_CONSTS_HTTP_PATH_SEP; p++) {
winlin authored
173 174 175
        }
        
        // whether the handler can handler the node.
176 177
        const char* pchild = p;
        if (!can_handle(path, p - path, &pchild)) {
winlin authored
178 179 180
            break;
        }
        
181
        // save current handler, it's ok for current handler atleast.
182 183 184
        handler = this;
        match_start = path;
        match_length = p - path;
winlin authored
185
        
186
        // find the best matched child handler.
winlin authored
187 188
        std::vector<SrsHttpHandler*>::iterator it;
        for (it = handlers.begin(); it != handlers.end(); ++it) {
189
            SrsHttpHandler* h = *it;
190 191
            
            // matched, donot search more.
192
            if (h->best_match(pchild, length - (pchild - path), ppmatch) == ERROR_SUCCESS) {
winlin authored
193 194 195 196 197 198 199 200
                break;
            }
        }
        
        // whatever, donot loop.
        break;
    }
    
201 202 203 204 205 206 207
    // if already matched by child, return.
    if (*ppmatch) {
        return ret;
    }
    
    // not matched, error.
    if (handler == NULL) {
winlin authored
208 209 210 211
        ret = ERROR_HTTP_HANDLER_MATCH_URL;
        return ret;
    }
    
212 213 214 215 216
    // matched by this handler.
    *ppmatch = new SrsHttpHandlerMatch();
    (*ppmatch)->handler = handler;
    (*ppmatch)->matched_url.append(match_start, match_length);
    
217 218 219 220 221
    int unmatch_length = length - match_length;
    if (unmatch_length > 0) {
        (*ppmatch)->unmatched_url.append(match_start + match_length, unmatch_length);
    }
    
winlin authored
222 223 224
    return ret;
}
225
SrsHttpHandler* SrsHttpHandler::res_status_line(stringstream& ss)
226
{
winlin authored
227 228
    ss << "HTTP/1.1 200 OK " << __SRS_CRLF
       << "Server: "RTMP_SIG_SRS_KEY"/"RTMP_SIG_SRS_VERSION"" << __SRS_CRLF;
229 230 231
    return this;
}
232
SrsHttpHandler* SrsHttpHandler::res_status_line_error(stringstream& ss, int code, string reason_phrase)
233
{
winlin authored
234 235
    ss << "HTTP/1.1 " << code << " " << reason_phrase << __SRS_CRLF
       << "Server: SRS/"RTMP_SIG_SRS_VERSION"" << __SRS_CRLF;
236 237 238
    return this;
}
239
SrsHttpHandler* SrsHttpHandler::res_content_type(stringstream& ss)
240
{
winlin authored
241 242
    ss << "Content-Type: text/html;charset=utf-8" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
243 244 245
    return this;
}
246
SrsHttpHandler* SrsHttpHandler::res_content_type_xml(stringstream& ss)
247
{
winlin authored
248 249
    ss << "Content-Type: text/xml;charset=utf-8" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
250 251 252
    return this;
}
253
SrsHttpHandler* SrsHttpHandler::res_content_type_javascript(stringstream& ss)
254
{
winlin authored
255 256
    ss << "Content-Type: text/javascript" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
257 258 259
    return this;
}
260
SrsHttpHandler* SrsHttpHandler::res_content_type_swf(stringstream& ss)
261
{
winlin authored
262 263
    ss << "Content-Type: application/x-shockwave-flash" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
264 265 266
    return this;
}
267
SrsHttpHandler* SrsHttpHandler::res_content_type_css(stringstream& ss)
268
{
winlin authored
269 270
    ss << "Content-Type: text/css;charset=utf-8" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
271 272 273
    return this;
}
274 275
SrsHttpHandler* SrsHttpHandler::res_content_type_ico(stringstream& ss)
{
winlin authored
276 277
    ss << "Content-Type: image/x-icon" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
278 279 280 281
    return this;
}

SrsHttpHandler* SrsHttpHandler::res_content_type_json(stringstream& ss)
282
{
winlin authored
283 284
    ss << "Content-Type: application/json;charset=utf-8" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
285 286 287
    return this;
}
288
SrsHttpHandler* SrsHttpHandler::res_content_type_m3u8(stringstream& ss)
289
{
winlin authored
290 291
    ss << "Content-Type: application/x-mpegURL;charset=utf-8" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
292 293 294
    return this;
}
295
SrsHttpHandler* SrsHttpHandler::res_content_type_mpegts(stringstream& ss)
296
{
winlin authored
297 298
    ss << "Content-Type: video/MP2T" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
299 300 301
    return this;
}
302 303
SrsHttpHandler* SrsHttpHandler::res_content_type_flv(stringstream& ss)
{
winlin authored
304 305
    ss << "Content-Type: video/x-flv" << __SRS_CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __SRS_CRLF;
306 307 308
    return this;
}
309
SrsHttpHandler* SrsHttpHandler::res_content_length(stringstream& ss, int64_t length)
310
{
winlin authored
311
    ss << "Content-Length: "<< length << __SRS_CRLF;
312 313 314
    return this;
}
315
SrsHttpHandler* SrsHttpHandler::res_enable_crossdomain(stringstream& ss)
316
{
winlin authored
317
    ss << "Access-Control-Allow-Origin: *" << __SRS_CRLF
318
        << "Access-Control-Allow-Methods: "
winlin authored
319
        << "GET, POST, HEAD, PUT, DELETE" << __SRS_CRLF
320
        << "Access-Control-Allow-Headers: "
winlin authored
321
        << "Cache-Control,X-Proxy-Authorization,X-Requested-With,Content-Type" << __SRS_CRLF;
322 323 324
    return this;
}
325
SrsHttpHandler* SrsHttpHandler::res_header_eof(stringstream& ss)
326
{
winlin authored
327
    ss << __SRS_CRLF;
328 329 330
    return this;
}
331
SrsHttpHandler* SrsHttpHandler::res_body(stringstream& ss, string body)
332 333 334 335 336
{
    ss << body;
    return this;
}
337
int SrsHttpHandler::res_flush(SrsStSocket* skt, stringstream& ss)
338
{
339
    return skt->write((void*)ss.str().c_str(), ss.str().length(), NULL);
340 341
}
342
int SrsHttpHandler::res_options(SrsStSocket* skt)
343 344 345 346 347 348 349 350 351 352
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type(ss)
        ->res_content_length(ss, 0)->res_enable_crossdomain(ss)
        ->res_header_eof(ss);
    
    return res_flush(skt, ss);
}
353
int SrsHttpHandler::res_text(SrsStSocket* skt, SrsHttpMessage* req, string body)
354 355 356 357
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type(ss)
358 359 360 361 362 363 364
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
365 366 367 368 369
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
370
int SrsHttpHandler::res_xml(SrsStSocket* skt, SrsHttpMessage* req, string body)
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_xml(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
387
int SrsHttpHandler::res_javascript(SrsStSocket* skt, SrsHttpMessage* req, string body)
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_javascript(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
404
int SrsHttpHandler::res_swf(SrsStSocket* skt, SrsHttpMessage* req, string body)
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_swf(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
421
int SrsHttpHandler::res_css(SrsStSocket* skt, SrsHttpMessage* req, string body)
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_css(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
438
int SrsHttpHandler::res_ico(SrsStSocket* skt, SrsHttpMessage* req, string body)
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_ico(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
455
int SrsHttpHandler::res_m3u8(SrsStSocket* skt, SrsHttpMessage* req, string body)
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_m3u8(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
472
int SrsHttpHandler::res_mpegts(SrsStSocket* skt, SrsHttpMessage* req, string body)
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_mpegts(ss)
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
489
int SrsHttpHandler::res_json(SrsStSocket* skt, SrsHttpMessage* req, string json)
490 491 492 493
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_json(ss)
494 495 496 497 498 499 500
        ->res_content_length(ss, (int)json.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
501 502 503 504 505
        ->res_body(ss, json);
    
    return res_flush(skt, ss);
}
506
int SrsHttpHandler::res_error(SrsStSocket* skt, SrsHttpMessage* req, int code, string reason_phrase, string body)
507 508 509
{
    std::stringstream ss;
510
    res_status_line_error(ss, code, reason_phrase)->res_content_type_json(ss)
511 512 513 514 515 516 517
        ->res_content_length(ss, (int)body.length());
        
    if (req->requires_crossdomain()) {
        res_enable_crossdomain(ss);
    }
    
    res_header_eof(ss)
518 519 520 521 522
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
winlin authored
523
#ifdef SRS_AUTO_HTTP_API
winlin authored
524 525 526 527
SrsHttpHandler* SrsHttpHandler::create_http_api()
{
    return new SrsApiRoot();
}
winlin authored
528
#endif
winlin authored
529
winlin authored
530
#ifdef SRS_AUTO_HTTP_SERVER
winlin authored
531 532
SrsHttpHandler* SrsHttpHandler::create_http_stream()
{
winlin authored
533
    return new SrsHttpRoot();
winlin authored
534
}
winlin authored
535
#endif
536
537 538
SrsHttpMessage::SrsHttpMessage()
{
539 540
    _body = new SrsBuffer();
    _state = SrsHttpParseStateInit;
541 542
    _uri = new SrsHttpUri();
    _match = NULL;
543
    _requires_crossdomain = false;
winlin authored
544
    _http_ts_send_buffer = new char[__SRS_HTTP_TS_SEND_BUFFER_SIZE];
545 546 547 548
}

SrsHttpMessage::~SrsHttpMessage()
{
549
    srs_freep(_body);
550 551
    srs_freep(_uri);
    srs_freep(_match);
552
    srs_freep(_http_ts_send_buffer);
553 554 555 556 557
}

char* SrsHttpMessage::http_ts_send_buffer()
{
    return _http_ts_send_buffer;
558 559 560 561
}

void SrsHttpMessage::reset()
{
562
    _state = SrsHttpParseStateInit;
563
    _body->erase(_body->length());
564
    _url = "";
565 566
}
567 568
int SrsHttpMessage::parse_uri()
{
569 570 571 572 573 574 575 576 577 578 579 580 581 582
    // filter url according to HTTP specification.
    
    // remove the duplicated slash.
    std::string filtered_url = srs_string_replace(_url, "//", "/");
    
    // remove the last / to match resource.
    filtered_url = srs_string_trim_end(filtered_url, "/");
    
    // if empty, use root.
    if (filtered_url.empty()) {
        filtered_url = "/";
    }
    
    return _uri->initialize(filtered_url);
583 584
}
585 586
bool SrsHttpMessage::is_complete()
{
587 588 589 590 591 592 593 594
    return _state == SrsHttpParseStateComplete;
}

u_int8_t SrsHttpMessage::method()
{
    return (u_int8_t)_header.method;
}
winlin authored
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
string SrsHttpMessage::method_str()
{
    if (is_http_get()) {
        return "GET";
    }
    if (is_http_put()) {
        return "PUT";
    }
    if (is_http_post()) {
        return "POST";
    }
    if (is_http_delete()) {
        return "DELETE";
    }
    if (is_http_options()) {
        return "OPTIONS";
    }
    
    return "OTHER";
}
616 617
bool SrsHttpMessage::is_http_get()
{
winlin authored
618
    return _header.method == SRS_CONSTS_HTTP_GET;
619 620 621 622
}

bool SrsHttpMessage::is_http_put()
{
winlin authored
623
    return _header.method == SRS_CONSTS_HTTP_PUT;
624 625 626 627
}

bool SrsHttpMessage::is_http_post()
{
winlin authored
628
    return _header.method == SRS_CONSTS_HTTP_POST;
629 630 631 632
}

bool SrsHttpMessage::is_http_delete()
{
winlin authored
633
    return _header.method == SRS_CONSTS_HTTP_DELETE;
634 635
}
winlin authored
636 637
bool SrsHttpMessage::is_http_options()
{
winlin authored
638
    return _header.method == SRS_CONSTS_HTTP_OPTIONS;
winlin authored
639 640
}
641 642 643 644 645 646 647 648 649 650 651 652
string SrsHttpMessage::uri()
{
    std::string uri = _uri->get_schema();
    if (uri.empty()) {
        uri += "http://";
    }
    
    uri += host();
    uri += path();
    return uri;
}
653 654
string SrsHttpMessage::url()
{
655 656 657
    return _uri->get_url();
}
658 659 660 661 662
string SrsHttpMessage::host()
{
    return get_request_header("Host");
}
663 664 665 666 667 668 669 670
string SrsHttpMessage::path()
{
    return _uri->get_path();
}

string SrsHttpMessage::query()
{
    return _uri->get_query();
671 672 673 674 675 676
}

string SrsHttpMessage::body()
{
    std::string b;
    
677 678
    if (_body && _body->length() > 0) {
        b.append(_body->bytes(), _body->length());
679 680 681 682 683
    }
    
    return b;
}
684 685
char* SrsHttpMessage::body_raw()
{
686
    return _body? _body->bytes() : NULL;
687 688
}
689 690
int64_t SrsHttpMessage::body_size()
{
691
    return (int64_t)_body->length();
692 693 694 695 696 697 698
}

int64_t SrsHttpMessage::content_length()
{
    return _header.content_length;
}
699 700 701 702 703
SrsHttpHandlerMatch* SrsHttpMessage::match()
{
    return _match;
}
704 705 706 707 708
bool SrsHttpMessage::requires_crossdomain()
{
    return _requires_crossdomain;
}
709
void SrsHttpMessage::set_url(string url)
710 711 712 713 714 715 716 717 718 719 720 721 722 723
{
    _url = url;
}

void SrsHttpMessage::set_state(SrsHttpParseState state)
{
    _state = state;
}

void SrsHttpMessage::set_header(http_parser* header)
{
    memcpy(&_header, header, sizeof(http_parser));
}
724 725 726 727 728 729
void SrsHttpMessage::set_match(SrsHttpHandlerMatch* match)
{
    srs_freep(_match);
    _match = match;
}
730 731 732 733 734
void SrsHttpMessage::set_requires_crossdomain(bool requires_crossdomain)
{
    _requires_crossdomain = requires_crossdomain;
}
735 736 737
void SrsHttpMessage::append_body(const char* body, int length)
{
    _body->append(body, length);
738 739
}
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
string SrsHttpMessage::query_get(string key)
{
    std::string q = query();
    size_t pos = std::string::npos;
    
    // must format as key=value&...&keyN=valueN
    if ((pos = key.find("=")) != key.length() - 1) {
        key = key + "=";
    }
    
    if ((pos = q.find(key)) == std::string::npos) {
        return "";
    }
    
    std::string v = q.substr(pos + key.length());
    if ((pos = v.find("&")) != std::string::npos) {
        v = v.substr(0, pos);
    }
    
    return v;
}
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
int SrsHttpMessage::request_header_count()
{
    return (int)headers.size();
}

string SrsHttpMessage::request_header_key_at(int index)
{
    srs_assert(index < request_header_count());
    SrsHttpHeaderField item = headers[index];
    return item.first;
}

string SrsHttpMessage::request_header_value_at(int index)
{
    srs_assert(index < request_header_count());
    SrsHttpHeaderField item = headers[index];
    return item.second;
}

void SrsHttpMessage::set_request_header(string key, string value)
{
    headers.push_back(std::make_pair(key, value));
}

string SrsHttpMessage::get_request_header(string name)
{
    std::vector<SrsHttpHeaderField>::iterator it;
    
    for (it = headers.begin(); it != headers.end(); ++it) {
        SrsHttpHeaderField& elem = *it;
        std::string key = elem.first;
        std::string value = elem.second;
        if (key == name) {
            return value;
        }
    }
    
    return "";
}
802 803
SrsHttpParser::SrsHttpParser()
{
804
    msg = NULL;
805 806 807 808
}

SrsHttpParser::~SrsHttpParser()
{
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
    srs_freep(msg);
}

int SrsHttpParser::initialize(enum http_parser_type type)
{
    int ret = ERROR_SUCCESS;
    
    memset(&settings, 0, sizeof(settings));
    settings.on_message_begin = on_message_begin;
    settings.on_url = on_url;
    settings.on_header_field = on_header_field;
    settings.on_header_value = on_header_value;
    settings.on_headers_complete = on_headers_complete;
    settings.on_body = on_body;
    settings.on_message_complete = on_message_complete;
    
    http_parser_init(&parser, type);
    // callback object ptr.
    parser.data = (void*)this;
    
    return ret;
}
832
int SrsHttpParser::parse_message(SrsStSocket* skt, SrsHttpMessage** ppmsg)
833 834 835 836 837 838 839 840 841
{
    *ppmsg = NULL;
    
    int ret = ERROR_SUCCESS;

    // the msg must be always NULL
    srs_assert(msg == NULL);
    msg = new SrsHttpMessage();
    
842 843 844
    // reset request data.
    filed_name = "";
    
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    // reset response header.
    msg->reset();
    
    // do parse
    if ((ret = parse_message_imp(skt)) != ERROR_SUCCESS) {
        if (!srs_is_client_gracefully_close(ret)) {
            srs_error("parse http msg failed. ret=%d", ret);
        }
        srs_freep(msg);
        return ret;
    }
    
    // parse ok, return the msg.
    *ppmsg = msg;
    msg = NULL;
    
    return ret;
}
864
int SrsHttpParser::parse_message_imp(SrsStSocket* skt)
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
{
    int ret = ERROR_SUCCESS;
    
    // the msg should never be NULL
    srs_assert(msg != NULL);
    
    // parser header.
    char buf[SRS_HTTP_HEADER_BUFFER];
    for (;;) {
        ssize_t nread;
        if ((ret = skt->read(buf, (size_t)sizeof(buf), &nread)) != ERROR_SUCCESS) {
            if (!srs_is_client_gracefully_close(ret)) {
                srs_error("read body from server failed. ret=%d", ret);
            }
            return ret;
        }
        
        ssize_t nparsed = http_parser_execute(&parser, &settings, buf, nread);
        srs_info("read_size=%d, nparsed=%d", (int)nread, (int)nparsed);

        // check header size.
        if (msg->is_complete()) {
            return ret;
        }
        
        if (nparsed != nread) {
            ret = ERROR_HTTP_PARSE_HEADER;
            srs_error("parse response error, parsed(%d)!=read(%d), ret=%d", (int)nparsed, (int)nread, ret);
            return ret;
        }
    }

    return ret;
}

int SrsHttpParser::on_message_begin(http_parser* parser)
{
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    obj->msg->set_state(SrsHttpParseStateStart);
    
    srs_info("***MESSAGE BEGIN***");
    
    return 0;
}

int SrsHttpParser::on_headers_complete(http_parser* parser)
{
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    obj->msg->set_header(parser);
    
    srs_info("***HEADERS COMPLETE***");
    
    // see http_parser.c:1570, return 1 to skip body.
    return 0;
}

int SrsHttpParser::on_message_complete(http_parser* parser)
{
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    // save the parser when header parse completed.
    obj->msg->set_state(SrsHttpParseStateComplete);
    
    srs_info("***MESSAGE COMPLETE***\n");
    
    return 0;
}

int SrsHttpParser::on_url(http_parser* parser, const char* at, size_t length)
{
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    
    if (length > 0) {
        std::string url;
        
        url.append(at, (int)length);
        
        obj->msg->set_url(url);
    }
    
    srs_info("Method: %d, Url: %.*s", parser->method, (int)length, at);
    
    return 0;
}
949
int SrsHttpParser::on_header_field(http_parser* parser, const char* at, size_t length)
950
{
951 952 953 954 955 956 957
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    
    if (length > 0) {
        srs_assert(obj);
        obj->filed_name.append(at, (int)length);
    }
    
958 959 960 961
    srs_info("Header field: %.*s", (int)length, at);
    return 0;
}
962
int SrsHttpParser::on_header_value(http_parser* parser, const char* at, size_t length)
963
{
964 965 966 967 968 969 970 971 972 973 974 975 976
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    
    if (length > 0) {
        srs_assert(obj);
        srs_assert(obj->msg);
        
        std::string field_value;
        field_value.append(at, (int)length);

        obj->msg->set_request_header(obj->filed_name, field_value);
        obj->filed_name = "";
    }
    
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    srs_info("Header value: %.*s", (int)length, at);
    return 0;
}

int SrsHttpParser::on_body(http_parser* parser, const char* at, size_t length)
{
    SrsHttpParser* obj = (SrsHttpParser*)parser->data;
    
    if (length > 0) {
        srs_assert(obj);
        srs_assert(obj->msg);
        
        obj->msg->append_body(at, (int)length);
    }
    
    srs_info("Body: %.*s", (int)length, at);

    return 0;
995
}
996
winlin authored
997 998
SrsHttpUri::SrsHttpUri()
{
999
    port = SRS_DEFAULT_HTTP_PORT;
winlin authored
1000 1001 1002 1003 1004 1005
}

SrsHttpUri::~SrsHttpUri()
{
}
1006
int SrsHttpUri::initialize(string _url)
winlin authored
1007
{
1008
    int ret = ERROR_SUCCESS;
winlin authored
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    
    url = _url;
    const char* purl = url.c_str();
    
    http_parser_url hp_u;
    if((ret = http_parser_parse_url(purl, url.length(), 0, &hp_u)) != 0){
        int code = ret;
        ret = ERROR_HTTP_PARSE_URI;
        
        srs_error("parse url %s failed, code=%d, ret=%d", purl, code, ret);
        return ret;
    }
    
1022
    std::string field = get_uri_field(url, &hp_u, UF_SCHEMA);
winlin authored
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    if(!field.empty()){
        schema = field;
    }
    
    host = get_uri_field(url, &hp_u, UF_HOST);
    
    field = get_uri_field(url, &hp_u, UF_PORT);
    if(!field.empty()){
        port = atoi(field.c_str());
    }
    
    path = get_uri_field(url, &hp_u, UF_PATH);
    srs_info("parse url %s success", purl);
    
1037
    query = get_uri_field(url, &hp_u, UF_QUERY);
1038
    srs_info("parse query %s success", query.c_str());
1039
    
1040
    return ret;
winlin authored
1041 1042 1043 1044
}

const char* SrsHttpUri::get_url()
{
1045
    return url.data();
winlin authored
1046 1047 1048 1049
}

const char* SrsHttpUri::get_schema()
{
1050
    return schema.data();
winlin authored
1051 1052 1053 1054
}

const char* SrsHttpUri::get_host()
{
1055
    return host.data();
winlin authored
1056 1057 1058 1059 1060 1061 1062
}

int SrsHttpUri::get_port()
{
    return port;
}
1063 1064
const char* SrsHttpUri::get_path()
{
1065 1066 1067 1068 1069
    return path.data();
}

const char* SrsHttpUri::get_query()
{
1070
    return query.data();
1071 1072
}
1073
string SrsHttpUri::get_uri_field(string uri, http_parser_url* hp_u, http_parser_url_fields field)
winlin authored
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
{
    if((hp_u->field_set & (1 << field)) == 0){
        return "";
    }
    
    srs_verbose("uri field matched, off=%d, len=%d, value=%.*s", 
        hp_u->field_data[field].off, 
        hp_u->field_data[field].len, 
        hp_u->field_data[field].len, 
        uri.c_str() + hp_u->field_data[field].off);
    
    int offset = hp_u->field_data[field].off;
    int len = hp_u->field_data[field].len;
    
    return uri.substr(offset, len);
}
1091
#endif
1092