HttpClient.cpp 9.75 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2 3 4 5 6 7 8 9
 * Copyright (c) 2016 The ZLMediaKit project authors. All Rights Reserved.
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
 */
xiongziliang committed
10

11
#include <cstdlib>
xiongziliang committed
12
#include "HttpClient.h"
xiongziliang committed
13
#include "Common/config.h"
xiongziliang committed
14

xiongziliang committed
15
namespace mediakit {
xiongziliang committed
16 17


18
HttpClient::HttpClient() {
xiongziliang committed
19
}
20 21

HttpClient::~HttpClient() {
xiongziliang committed
22
}
23 24

void HttpClient::sendRequest(const string &strUrl, float fTimeOutSec) {
25
    _aliveTicker.resetTime();
26
    _url = strUrl;
27
    auto protocol = FindField(strUrl.data(), NULL, "://");
xiongziliang committed
28 29
    uint16_t defaultPort;
    bool isHttps;
xiongziliang committed
30
    if (strcasecmp(protocol.data(), "http") == 0) {
xiongziliang committed
31 32
        defaultPort = 80;
        isHttps = false;
xiongziliang committed
33
    } else if (strcasecmp(protocol.data(), "https") == 0) {
xiongziliang committed
34 35
        defaultPort = 443;
        isHttps = true;
36
    } else {
37
        auto strErr = StrPrinter << "非法的协议:" << protocol << endl;
xiongziliang committed
38 39
        throw std::invalid_argument(strErr);
    }
40

xiongziliang committed
41 42 43 44 45 46 47 48
    auto host = FindField(strUrl.data(), "://", "/");
    if (host.empty()) {
        host = FindField(strUrl.data(), "://", NULL);
    }
    _path = FindField(strUrl.data(), host.data(), NULL);
    if (_path.empty()) {
        _path = "/";
    }
49
    uint16_t port = atoi(FindField(host.data(), ":", NULL).data());
xiongziliang committed
50 51 52 53 54 55 56
    if (port <= 0) {
        //默认端口
        port = defaultPort;
    } else {
        //服务器域名
        host = FindField(host.data(), NULL, ":");
    }
57
    _header.emplace("Host", host);
xiongziliang committed
58
    _header.emplace("Tools", SERVER_NAME);
59 60 61 62
    _header.emplace("Connection", "keep-alive");
    _header.emplace("Accept", "*/*");
    _header.emplace("Accept-Language", "zh-CN,zh;q=0.8");
    _header.emplace("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
63 64

    if (_body && _body->remainSize()) {
65 66
        _header.emplace("Content-Length", to_string(_body->remainSize()));
        _header.emplace("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xiongziliang committed
67 68 69 70 71
    }

    bool bChanged = (_lastHost != host + ":" + to_string(port)) || (_isHttps != isHttps);
    _lastHost = host + ":" + to_string(port);
    _isHttps = isHttps;
72
    _fTimeOutSec = fTimeOutSec;
73 74 75 76 77 78 79 80

    auto cookies = HttpCookieStorage::Instance().get(_lastHost,_path);
    _StrPrinter printer;
    for(auto &cookie : cookies){
        printer << cookie->getKey() << "=" << cookie->getVal() << ";";
    }
    if(!printer.empty()){
        printer.pop_back();
81
        _header.emplace("Cookie", printer);
82 83 84
    }


85
    if (!alive() || bChanged) {
86
        //InfoL << "reconnet:" << _lastHost;
87 88
        startConnect(host, port, fTimeOutSec);
    } else {
xiongziliang committed
89 90 91 92 93 94
        SockException ex;
        onConnect(ex);
    }
}


95
void HttpClient::onConnect(const SockException &ex) {
96
    _aliveTicker.resetTime();
97 98 99 100 101
    if (ex) {
        onDisconnect(ex);
        return;
    }

102
    //先假设http客户端只会接收一点点数据(只接受http头,节省内存)
103
    getSock()->setReadBuffer(std::make_shared<BufferRaw>(1 * 1024));
104

105 106 107
    _totalBodySize = 0;
    _recvedBodySize = 0;
    HttpRequestSplitter::reset();
108
    _chunkedSplitter.reset();
109

110 111
    _StrPrinter printer;
    printer << _method + " " << _path + " HTTP/1.1\r\n";
xiongziliang committed
112
    for (auto &pr : _header) {
113
        printer << pr.first + ": ";
114
        printer << pr.second + "\r\n";
xiongziliang committed
115
    }
xiongziliang committed
116
    SockSender::send(printer << "\r\n");
xiongziliang committed
117
    onFlush();
xiongziliang committed
118
}
119 120 121

void HttpClient::onRecv(const Buffer::Ptr &pBuf) {
    _aliveTicker.resetTime();
xiongziliang committed
122
    HttpRequestSplitter::input(pBuf->data(), pBuf->size());
xiongziliang committed
123 124
}

125
void HttpClient::onErr(const SockException &ex) {
126
    if (ex.getErrCode() == Err_eof && _totalBodySize < 0) {
127 128
        //如果Content-Length未指定 但服务器断开链接
        //则认为本次http请求完成
129
        onResponseCompleted_l();
130
    }
131
    onDisconnect(ex);
xiongziliang committed
132 133
}

134 135
int64_t HttpClient::onRecvHeader(const char *data, uint64_t len) {
    _parser.Parse(data);
136 137 138 139 140 141
    if(_parser.Url() == "302" || _parser.Url() == "301"){
        auto newUrl = _parser["Location"];
        if(newUrl.empty()){
            shutdown(SockException(Err_shutdown,"未找到Location字段(跳转url)"));
            return 0;
        }
142 143 144 145 146 147
        if(onRedirectUrl(newUrl,_parser.Url() == "302")){
            HttpClient::clear();
            setMethod("GET");
            HttpClient::sendRequest(newUrl,_fTimeOutSec);
            return 0;
        }
148 149
    }

xiongziliang committed
150 151
    checkCookie(_parser.getHeader());
    _totalBodySize = onResponseHeader(_parser.Url(), _parser.getHeader());
152

153 154 155
    if(!_parser["Content-Length"].empty()){
        //有Content-Length字段时忽略onResponseHeader的返回值
        _totalBodySize = atoll(_parser["Content-Length"].data());
156
    }
157

158
    if(_parser["Transfer-Encoding"] == "chunked"){
159
        //我们认为这种情况下后面应该有大量的数据过来,加大接收缓存提高性能
160
        getSock()->setReadBuffer(std::make_shared<BufferRaw>(256 * 1024));
161

162 163 164 165 166 167 168 169 170 171 172 173 174
        //如果Transfer-Encoding字段等于chunked,则认为后续的content是不限制长度的
        _totalBodySize = -1;
        _chunkedSplitter = std::make_shared<HttpChunkedSplitter>([this](const char *data,uint64_t len){
            if(len > 0){
                auto recvedBodySize = _recvedBodySize + len;
                onResponseBody(data, len, recvedBodySize, INT64_MAX);
                _recvedBodySize = recvedBodySize;
            }else{
                onResponseCompleted_l();
            }
        });
    }

175
    if(_totalBodySize == 0){
176
        //后续没content,本次http请求结束
177 178 179
        onResponseCompleted_l();
        return 0;
    }
180

181 182
    //当_totalBodySize != 0时到达这里,代表后续有content
    //虽然我们在_totalBodySize >0 时知道content的确切大小,
183 184
    //但是由于我们没必要等content接收完毕才回调onRecvContent(因为这样浪费内存并且要多次拷贝数据)
    //所以返回-1代表我们接下来分段接收content
185
    _recvedBodySize = 0;
186 187
    if(_totalBodySize > 0){
        //根据_totalBodySize设置接收缓存大小
188
        getSock()->setReadBuffer(std::make_shared<BufferRaw>(MIN(_totalBodySize + 1,256 * 1024)));
189
    }else{
190
        getSock()->setReadBuffer(std::make_shared<BufferRaw>(256 * 1024));
191 192
    }

193 194 195 196
    return -1;
}

void HttpClient::onRecvContent(const char *data, uint64_t len) {
197 198 199 200
    if(_chunkedSplitter){
        _chunkedSplitter->input(data,len);
        return;
    }
201
    auto recvedBodySize = _recvedBodySize + len;
202 203 204 205 206 207 208 209 210 211
    if(_totalBodySize < 0){
        //不限长度的content,最大支持INT64_MAX个字节
        onResponseBody(data, len, recvedBodySize, INT64_MAX);
        _recvedBodySize = recvedBodySize;
        return;
    }

    //固定长度的content
    if ( recvedBodySize < _totalBodySize ) {
        //content还未接收完毕
212 213
        onResponseBody(data, len, recvedBodySize, _totalBodySize);
        _recvedBodySize = recvedBodySize;
214 215 216 217 218 219 220 221 222
        return;
    }

    //content接收完毕
    onResponseBody(data, _totalBodySize - _recvedBodySize, _totalBodySize, _totalBodySize);
    bool biggerThanExpected = recvedBodySize > _totalBodySize;
    onResponseCompleted_l();
    if(biggerThanExpected) {
        //声明的content数据比真实的小,那么我们只截取前面部分的并断开链接
xiongziliang committed
223
        shutdown(SockException(Err_shutdown, "http response content size bigger than expected"));
224
    }
xiongziliang committed
225
}
226

xiongziliang committed
227
void HttpClient::onFlush() {
228
    _aliveTicker.resetTime();
229
    GET_CONFIG(uint32_t,sendBufSize,Http::kSendBufSize);
230
    while (_body && _body->remainSize() && !isSocketBusy()) {
231
        auto buffer = _body->readData(sendBufSize);
232
        if (!buffer) {
233 234 235
            //数据发送结束或读取数据异常
            break;
        }
236
        if (send(buffer) <= 0) {
237 238 239 240 241 242 243 244
            //发送数据失败,不需要回滚数据,因为发送前已经通过isSocketBusy()判断socket可写
            //所以发送缓存区肯定未满,该buffer肯定已经写入socket
            break;
        }
    }
}

void HttpClient::onManager() {
245
    if (_aliveTicker.elapsedTime() > 3 * 1000 && _totalBodySize < 0 && !_chunkedSplitter) {
246 247
        //如果Content-Length未指定 但接收数据超时
        //则认为本次http请求完成
248
        onResponseCompleted_l();
249 250
    }

251
    if (_fTimeOutSec > 0 && _aliveTicker.elapsedTime() > _fTimeOutSec * 1000) {
252
        //超时
xiongziliang committed
253
        shutdown(SockException(Err_timeout, "http request timeout"));
254 255 256
    }
}

257
void HttpClient::onResponseCompleted_l() {
258 259
    _totalBodySize = 0;
    _recvedBodySize = 0;
260
    onResponseCompleted();
261 262
}

263
void HttpClient::checkCookie(HttpClient::HttpHeader &headers) {
264
    //Set-Cookie: IPTV_SERVER=8E03927B-CC8C-4389-BC00-31DBA7EC7B49;expires=Sun, Sep 23 2018 15:07:31 GMT;path=/index/api/
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    for(auto it_set_cookie = headers.find("Set-Cookie") ; it_set_cookie != headers.end() ; ++it_set_cookie ){
        auto key_val = Parser::parseArgs(it_set_cookie->second,";","=");
        HttpCookie::Ptr cookie = std::make_shared<HttpCookie>();
        cookie->setHost(_lastHost);

        int index = 0;
        auto arg_vec = split(it_set_cookie->second, ";");
        for (string &key_val : arg_vec) {
            auto key = FindField(key_val.data(),NULL,"=");
            auto val = FindField(key_val.data(),"=", NULL);

            if(index++ == 0){
                cookie->setKeyVal(key,val);
                continue;
            }
280

281 282 283 284
            if(key == "path") {
                cookie->setPath(val);
                continue;
            }
285

286 287 288 289
            if(key == "expires"){
                cookie->setExpires(val,headers["Date"]);
                continue;
            }
290 291
        }

292 293
        if(!(*cookie)){
            //无效的cookie
294
            continue;
295
        }
296
        HttpCookieStorage::Instance().set(cookie);
297 298 299
    }
}

300

xiongziliang committed
301
} /* namespace mediakit */
xiongziliang committed
302