Blame view

trunk/src/app/srs_app_http.cpp 14.4 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_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_socket.hpp>
winlin authored
35 36
#include <srs_app_http_api.hpp>
#include <srs_app_http_conn.hpp>
winlin authored
37 38 39

#define SRS_DEFAULT_HTTP_PORT 80
winlin authored
40 41
#define SRS_HTTP_HEADER_BUFFER 1024
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
bool srs_path_equals(const char* expect, const char* path, int nb_path)
{
    int size = strlen(expect);
    
    if (size != nb_path) {
        return false;
    }
    
    return !memcmp(expect, path, size);
}

SrsHttpHandlerMatch::SrsHttpHandlerMatch()
{
    handler = NULL;
}
winlin authored
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
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;
}
78
bool SrsHttpHandler::can_handle(const char* /*path*/, int /*length*/, const char** /*pchild*/)
winlin authored
79 80 81 82
{
    return false;
}
83 84 85 86 87 88 89 90 91 92
int SrsHttpHandler::process_request(SrsSocket* skt, SrsHttpMessage* req)
{
    if (req->method() == HTTP_OPTIONS) {
        return res_options(skt);
    }
    
    return do_process_request(skt, req);
}

int SrsHttpHandler::do_process_request(SrsSocket* /*skt*/, SrsHttpMessage* /*req*/)
winlin authored
93 94 95 96 97
{
    int ret = ERROR_SUCCESS;
    return ret;
}
98
int SrsHttpHandler::best_match(const char* path, int length, SrsHttpHandlerMatch** ppmatch)
winlin authored
99 100 101
{
    int ret = ERROR_SUCCESS;
    
102 103 104 105
    SrsHttpHandler* handler = NULL;
    const char* match_start = NULL;
    int match_length = 0;
    
winlin authored
106 107 108 109 110 111 112 113 114 115 116 117
    for (;;) {
        // ensure cur is not NULL.
        // ensure p not NULL and has bytes to parse.
        if (!path || length <= 0) {
            break;
        }
        
        const char* p = NULL;
        for (p = path + 1; p - path < length && *p != __PATH_SEP; p++) {
        }
        
        // whether the handler can handler the node.
118 119
        const char* pchild = p;
        if (!can_handle(path, p - path, &pchild)) {
winlin authored
120 121 122
            break;
        }
        
123
        // save current handler, it's ok for current handler atleast.
124 125 126
        handler = this;
        match_start = path;
        match_length = p - path;
winlin authored
127
        
128
        // find the best matched child handler.
winlin authored
129 130
        std::vector<SrsHttpHandler*>::iterator it;
        for (it = handlers.begin(); it != handlers.end(); ++it) {
131
            SrsHttpHandler* h = *it;
132 133
            
            // matched, donot search more.
134
            if (h->best_match(pchild, length - (pchild - path), ppmatch) == ERROR_SUCCESS) {
winlin authored
135 136 137 138 139 140 141 142
                break;
            }
        }
        
        // whatever, donot loop.
        break;
    }
    
143 144 145 146 147 148 149
    // if already matched by child, return.
    if (*ppmatch) {
        return ret;
    }
    
    // not matched, error.
    if (handler == NULL) {
winlin authored
150 151 152 153
        ret = ERROR_HTTP_HANDLER_MATCH_URL;
        return ret;
    }
    
154 155 156 157 158
    // matched by this handler.
    *ppmatch = new SrsHttpHandlerMatch();
    (*ppmatch)->handler = handler;
    (*ppmatch)->matched_url.append(match_start, match_length);
    
winlin authored
159 160 161
    return ret;
}
162 163 164 165 166 167 168 169 170 171 172 173 174 175
SrsHttpHandler* SrsHttpHandler::res_status_line(std::stringstream& ss)
{
    ss << "HTTP/1.1 200 OK " << __CRLF
       << "Server: SRS/"RTMP_SIG_SRS_VERSION"" << __CRLF;
    return this;
}

SrsHttpHandler* SrsHttpHandler::res_content_type(std::stringstream& ss)
{
    ss << "Content-Type: text/html;charset=utf-8" << __CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __CRLF;
    return this;
}
176 177 178 179 180 181 182
SrsHttpHandler* SrsHttpHandler::res_content_type_json(std::stringstream& ss)
{
    ss << "Content-Type: application/json;charset=utf-8" << __CRLF
        << "Allow: DELETE, GET, HEAD, OPTIONS, POST, PUT" << __CRLF;
    return this;
}
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
SrsHttpHandler* SrsHttpHandler::res_content_length(std::stringstream& ss, int64_t length)
{
    ss << "Content-Length: "<< length << __CRLF;
    return this;
}

SrsHttpHandler* SrsHttpHandler::res_enable_crossdomain(std::stringstream& ss)
{
    ss << "Access-Control-Allow-Origin: *" << __CRLF
        << "Access-Control-Allow-Methods: "
        << "GET, POST, HEAD, PUT, DELETE" << __CRLF
        << "Access-Control-Allow-Headers: "
        << "Cache-Control,X-Proxy-Authorization,X-Requested-With,Content-Type" << __CRLF;
    return this;
}

SrsHttpHandler* SrsHttpHandler::res_header_eof(std::stringstream& ss)
{
    ss << __CRLF;
    return this;
}

SrsHttpHandler* SrsHttpHandler::res_body(std::stringstream& ss, std::string body)
{
    ss << body;
    return this;
}

int SrsHttpHandler::res_flush(SrsSocket* skt, std::stringstream& ss)
{
    return skt->write(ss.str().c_str(), ss.str().length(), NULL);
}

int SrsHttpHandler::res_options(SrsSocket* skt)
{
    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);
}

int SrsHttpHandler::res_text(SrsSocket* skt, std::string body)
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type(ss)
        ->res_content_length(ss, (int)body.length())->res_enable_crossdomain(ss)
        ->res_header_eof(ss)
        ->res_body(ss, body);
    
    return res_flush(skt, ss);
}
239 240 241 242 243 244 245 246 247 248 249 250
int SrsHttpHandler::res_json(SrsSocket* skt, std::string json)
{
    std::stringstream ss;
    
    res_status_line(ss)->res_content_type_json(ss)
        ->res_content_length(ss, (int)json.length())->res_enable_crossdomain(ss)
        ->res_header_eof(ss)
        ->res_body(ss, json);
    
    return res_flush(skt, ss);
}
winlin authored
251 252 253 254 255 256 257 258 259 260
SrsHttpHandler* SrsHttpHandler::create_http_api()
{
    return new SrsApiRoot();
}

SrsHttpHandler* SrsHttpHandler::create_http_stream()
{
    // TODO: FIXME: use http stream handler instead.
    return new SrsHttpHandler();
}
261
262 263
SrsHttpMessage::SrsHttpMessage()
{
264 265
    _body = new SrsBuffer();
    _state = SrsHttpParseStateInit;
266 267
    _uri = new SrsHttpUri();
    _match = NULL;
268 269 270 271
}

SrsHttpMessage::~SrsHttpMessage()
{
272
    srs_freep(_body);
273 274
    srs_freep(_uri);
    srs_freep(_match);
275 276 277 278
}

void SrsHttpMessage::reset()
{
279 280 281
    _state = SrsHttpParseStateInit;
    _body->clear();
    _url = "";
282 283
}
284 285 286 287 288
int SrsHttpMessage::parse_uri()
{
    return _uri->initialize(_url);
}
289 290
bool SrsHttpMessage::is_complete()
{
291 292 293 294 295 296 297 298 299 300
    return _state == SrsHttpParseStateComplete;
}

u_int8_t SrsHttpMessage::method()
{
    return (u_int8_t)_header.method;
}

string SrsHttpMessage::url()
{
301 302 303 304 305 306 307 308 309 310 311
    return _uri->get_url();
}

string SrsHttpMessage::path()
{
    return _uri->get_path();
}

string SrsHttpMessage::query()
{
    return _uri->get_query();
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
}

string SrsHttpMessage::body()
{
    std::string b;
    
    if (_body && !_body->empty()) {
        b.append(_body->bytes(), _body->size());
    }
    
    return b;
}

int64_t SrsHttpMessage::body_size()
{
    return (int64_t)_body->size();
}

int64_t SrsHttpMessage::content_length()
{
    return _header.content_length;
}
335 336 337 338 339
SrsHttpHandlerMatch* SrsHttpMessage::match()
{
    return _match;
}
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
void SrsHttpMessage::set_url(std::string url)
{
    _url = url;
}

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

void SrsHttpMessage::set_header(http_parser* header)
{
    memcpy(&_header, header, sizeof(http_parser));
}
355 356 357 358 359 360
void SrsHttpMessage::set_match(SrsHttpHandlerMatch* match)
{
    srs_freep(_match);
    _match = match;
}
361 362 363
void SrsHttpMessage::append_body(const char* body, int length)
{
    _body->append(body, length);
364 365 366 367
}

SrsHttpParser::SrsHttpParser()
{
368
    msg = NULL;
369 370 371 372
}

SrsHttpParser::~SrsHttpParser()
{
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
    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;
}

int SrsHttpParser::parse_message(SrsSocket* skt, SrsHttpMessage** ppmsg)
{
    *ppmsg = NULL;
    
    int ret = ERROR_SUCCESS;

    // the msg must be always NULL
    srs_assert(msg == NULL);
    msg = new SrsHttpMessage();
    
    // 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;
}

int SrsHttpParser::parse_message_imp(SrsSocket* skt)
{
    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;
}

int SrsHttpParser::on_header_field(http_parser* /*parser*/, const char* at, size_t length)
{
    srs_info("Header field: %.*s", (int)length, at);
    return 0;
}

int SrsHttpParser::on_header_value(http_parser* /*parser*/, const char* at, size_t length)
{
    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;
536
}
537
winlin authored
538 539
SrsHttpUri::SrsHttpUri()
{
540
    port = SRS_DEFAULT_HTTP_PORT;
winlin authored
541 542 543 544 545 546 547 548
}

SrsHttpUri::~SrsHttpUri()
{
}

int SrsHttpUri::initialize(std::string _url)
{
549
    int ret = ERROR_SUCCESS;
winlin authored
550 551 552 553 554 555 556 557 558 559 560 561 562
    
    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;
    }
    
563
    std::string field = get_uri_field(url, &hp_u, UF_SCHEMA);
winlin authored
564 565 566 567 568 569 570 571 572 573 574 575 576 577
    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);
    
578
    query = get_uri_field(url, &hp_u, UF_QUERY);
579
    srs_info("parse query %s success", query);
580
    
581
    return ret;
winlin authored
582 583 584 585
}

const char* SrsHttpUri::get_url()
{
586
    return url.data();
winlin authored
587 588 589 590
}

const char* SrsHttpUri::get_schema()
{
591
    return schema.data();
winlin authored
592 593 594 595
}

const char* SrsHttpUri::get_host()
{
596
    return host.data();
winlin authored
597 598 599 600 601 602 603
}

int SrsHttpUri::get_port()
{
    return port;
}
604 605
const char* SrsHttpUri::get_path()
{
606 607 608 609 610 611
    return path.data();
}

const char* SrsHttpUri::get_query()
{
    return path.data();
612 613
}
winlin authored
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
std::string SrsHttpUri::get_uri_field(std::string uri, http_parser_url* hp_u, http_parser_url_fields field)
{
    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);
}
632
#endif