RtmpProtocol.cpp 23.7 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2
 * MIT License
xzl committed
3
 *
xiongziliang committed
4
 * Copyright (c) 2016-2019 xiongziliang <771730766@qq.com>
xiongziliang committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *
 * This file is part of ZLMediaKit(https://github.com/xiongziliang/ZLMediaKit).
 *
 * 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.
xzl committed
25 26
 */
#include "RtmpProtocol.h"
xiongzilaing committed
27
#include "Rtmp/utils.h"
xzl committed
28 29
#include "Util/util.h"
#include "Util/onceToken.h"
xiongzilaing committed
30
#include "Thread/ThreadPool.h"
xiongziliang committed
31
using namespace toolkit;
xzl committed
32

33
#ifdef ENABLE_OPENSSL
34
#include "Util/SSLBox.h"
35
#include <openssl/hmac.h>
36 37
#include <openssl/opensslv.h>

38 39
static string openssl_HMACsha256(const void *key,unsigned int key_len,
								 const void *data,unsigned int data_len){
40
	std::shared_ptr<char> out(new char[32],[](char *ptr){delete [] ptr;});
41
	unsigned int out_len;
42

43 44
#if defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10100000L)
    //openssl 1.1.0新增api,老版本api作废
45 46 47 48 49 50 51 52
	HMAC_CTX *ctx = HMAC_CTX_new();
	HMAC_CTX_reset(ctx);
	HMAC_Init_ex(ctx, key, key_len, EVP_sha256(), NULL);
	HMAC_Update(ctx, (unsigned char*)data, data_len);
	HMAC_Final(ctx, (unsigned char *)out.get(), &out_len);
	HMAC_CTX_reset(ctx);
	HMAC_CTX_free(ctx);
#else
53 54 55 56
	HMAC_CTX ctx;
	HMAC_CTX_init(&ctx);
	HMAC_Init_ex(&ctx, key, key_len, EVP_sha256(), NULL);
	HMAC_Update(&ctx, (unsigned char*)data, data_len);
57
	HMAC_Final(&ctx, (unsigned char *)out.get(), &out_len);
58
	HMAC_CTX_cleanup(&ctx);
59
#endif //defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER > 0x10100000L)
60
	return string(out.get(),out_len);
61 62 63 64 65 66 67 68 69 70 71 72 73
}
#endif //ENABLE_OPENSSL


#define C1_DIGEST_SIZE 32
#define C1_KEY_SIZE 128
#define C1_SCHEMA_SIZE 764
#define C1_HANDSHARK_SIZE (RANDOM_LEN + 8)
#define C1_FPKEY_SIZE 30
#define S1_FMS_KEY_SIZE 36
#define S2_FMS_KEY_SIZE 68
#define C1_OFFSET_SIZE 4

xiongziliang committed
74
namespace mediakit {
xzl committed
75 76

RtmpProtocol::RtmpProtocol() {
77
	_nextHandle = [this](){
xzl committed
78 79 80 81
		handle_C0C1();
	};
}
RtmpProtocol::~RtmpProtocol() {
xiongziliang committed
82
	reset();
xzl committed
83
}
xiongziliang committed
84
void RtmpProtocol::reset() {
xzl committed
85
	////////////ChunkSize////////////
86 87
	_iChunkLenIn = DEFAULT_CHUNK_LEN;
	_iChunkLenOut = DEFAULT_CHUNK_LEN;
xzl committed
88
	////////////Acknowledgement////////////
89 90 91
	_ui32ByteSent = 0;
	_ui32LastSent = 0;
	_ui32WinSize = 0;
xzl committed
92
	///////////PeerBandwidth///////////
93 94
	_ui32Bandwidth = 2500000;
	_ui8LimitType = 2;
xzl committed
95
	////////////Chunk////////////
96 97 98
	_mapChunkData.clear();
	_iNowStreamID = 0;
	_iNowChunkID = 0;
xzl committed
99
	//////////Invoke Request//////////
100
	_iReqID = 0;
xzl committed
101
	//////////Rtmp parser//////////
102 103 104
	_strRcvBuf.clear();
	_ui32StreamId = STREAM_CONTROL;
	_nextHandle = [this]() {
xzl committed
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
		handle_C0C1();
	};
}

void RtmpProtocol::sendAcknowledgement(uint32_t ui32Size) {
	std::string control;
	uint32_t stream = htonl(ui32Size);
	control.append((char *) &stream, 4);
	sendRequest(MSG_ACK, control);
}

void RtmpProtocol::sendAcknowledgementSize(uint32_t ui32Size) {
	uint32_t windowSize = htonl(ui32Size);
	std::string set_windowSize((char *) &windowSize, 4);
	sendRequest(MSG_WIN_SIZE, set_windowSize);
}

void RtmpProtocol::sendPeerBandwidth(uint32_t ui32Size) {
	uint32_t peerBandwidth = htonl(ui32Size);
	std::string set_peerBandwidth((char *) &peerBandwidth, 4);
	set_peerBandwidth.push_back((char) 0x02);
	sendRequest(MSG_SET_PEER_BW, set_peerBandwidth);
}

void RtmpProtocol::sendChunkSize(uint32_t ui32Size) {
	uint32_t len = htonl(ui32Size);
	std::string set_chunk((char *) &len, 4);
	sendRequest(MSG_SET_CHUNK, set_chunk);
133
	_iChunkLenOut = ui32Size;
xzl committed
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
}

void RtmpProtocol::sendPingRequest(uint32_t ui32TimeStamp) {
	sendUserControl(CONTROL_PING_REQUEST, ui32TimeStamp);
}

void RtmpProtocol::sendPingResponse(uint32_t ui32TimeStamp) {
	sendUserControl(CONTROL_PING_RESPONSE, ui32TimeStamp);
}

void RtmpProtocol::sendSetBufferLength(uint32_t ui32StreamId,
		uint32_t ui32Length) {
	std::string control;
	ui32StreamId = htonl(ui32StreamId);
	control.append((char *) &ui32StreamId, 4);
	ui32Length = htonl(ui32Length);
	control.append((char *) &ui32Length, 4);
	sendUserControl(CONTROL_SETBUFFER, control);
}

void RtmpProtocol::sendUserControl(uint16_t ui16EventType,
		uint32_t ui32EventData) {
	std::string control;
	uint16_t type = htons(ui16EventType);
	control.append((char *) &type, 2);
	uint32_t stream = htonl(ui32EventData);
	control.append((char *) &stream, 4);
	sendRequest(MSG_USER_CONTROL, control);
}

void RtmpProtocol::sendUserControl(uint16_t ui16EventType,
		const string& strEventData) {
	std::string control;
	uint16_t type = htons(ui16EventType);
	control.append((char *) &type, 2);
	control.append(strEventData);
	sendRequest(MSG_USER_CONTROL, control);
}

void RtmpProtocol::sendResponse(int iType, const string& str) {
174 175
	if(!_bDataStarted && (iType == MSG_DATA)){
		_bDataStarted =  true;
xiongziliang committed
176
	}
177
	sendRtmp(iType, _iNowStreamID, str, 0, _bDataStarted ? CHUNK_CLIENT_REQUEST_AFTER : CHUNK_CLIENT_REQUEST_BEFORE);
xzl committed
178 179 180 181
}

void RtmpProtocol::sendInvoke(const string& strCmd, const AMFValue& val) {
	AMFEncoder enc;
182
	enc << strCmd << ++_iReqID << val;
xzl committed
183 184 185 186
	sendRequest(MSG_CMD, enc.data());
}

void RtmpProtocol::sendRequest(int iCmd, const string& str) {
187
	sendRtmp(iCmd, _ui32StreamId, str, 0, CHUNK_SERVER_REQUEST);
xzl committed
188 189
}

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
class BufferPartial : public Buffer {
public:
    BufferPartial(const Buffer::Ptr &buffer,uint32_t offset,uint32_t size){
        _buffer = buffer;
        _data = buffer->data() + offset;
        _size = size;
    }

    ~BufferPartial(){}

    char *data() const override {
        return _data;
    }
    uint32_t size() const override{
        return _size;
    }
private:
    Buffer::Ptr _buffer;
    char *_data;
    uint32_t _size;
};

xzl committed
212
void RtmpProtocol::sendRtmp(uint8_t ui8Type, uint32_t ui32StreamId,
213 214 215
                            const std::string& strBuf, uint32_t ui32TimeStamp, int iChunkId) {
    sendRtmp(ui8Type,ui32StreamId,std::make_shared<BufferString>(strBuf),ui32TimeStamp,iChunkId);
}
xzl committed
216

217 218 219 220 221 222
void RtmpProtocol::sendRtmp(uint8_t ui8Type, uint32_t ui32StreamId,
        const Buffer::Ptr &buf, uint32_t ui32TimeStamp, int iChunkId){
    if (iChunkId < 2 || iChunkId > 63) {
        auto strErr = StrPrinter << "不支持发送该类型的块流 ID:" << iChunkId << endl;
        throw std::runtime_error(strErr);
    }
223
	//是否有扩展时间戳
224
    bool bExtStamp = ui32TimeStamp >= 0xFFFFFF;
771730766@qq.com committed
225

226 227 228 229 230 231 232 233 234 235 236 237 238
    //rtmp头
	BufferRaw::Ptr bufferHeader = obtainBuffer();
	bufferHeader->setCapacity(sizeof(RtmpHeader));
	bufferHeader->setSize(sizeof(RtmpHeader));
	//对rtmp头赋值,如果使用整形赋值,在arm android上可能由于数据对齐导致总线错误的问题
	RtmpHeader *header = (RtmpHeader*) bufferHeader->data();
    header->flags = (iChunkId & 0x3f) | (0 << 6);
    header->typeId = ui8Type;
    set_be24(header->timeStamp, bExtStamp ? 0xFFFFFF : ui32TimeStamp);
    set_be24(header->bodySize, buf->size());
    set_le32(header->streamId, ui32StreamId);
    //发送rtmp头
    onSendRawData(bufferHeader);
239

240 241
    //扩展时间戳字段
	BufferRaw::Ptr bufferExtStamp;
242
    if (bExtStamp) {
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        //生成扩展时间戳
		bufferExtStamp = obtainBuffer();
		bufferExtStamp->setCapacity(4);
		bufferExtStamp->setSize(4);
		set_be32(bufferExtStamp->data(), ui32TimeStamp);
	}

	//生成一个字节的flag,标明是什么chunkId
	BufferRaw::Ptr bufferFlags = obtainBuffer();
	bufferFlags->setCapacity(1);
	bufferFlags->setSize(1);
	bufferFlags->data()[0] = (iChunkId & 0x3f) | (3 << 6);
    
    size_t offset = 0;
	uint32_t totalSize = sizeof(RtmpHeader);
    while (offset < buf->size()) {
        if (offset) {
            onSendRawData(bufferFlags);
261 262 263 264
            totalSize += 1;
        }
        if (bExtStamp) {
            //扩展时间戳
265
            onSendRawData(bufferExtStamp);
266 267
            totalSize += 4;
        }
268 269
        size_t chunk = min(_iChunkLenOut, buf->size() - offset);
        onSendRawData(std::make_shared<BufferPartial>(buf,offset,chunk));
270
        totalSize += chunk;
271
        offset += chunk;
272 273 274 275 276 277
    }
    _ui32ByteSent += totalSize;
    if (_ui32WinSize > 0 && _ui32ByteSent - _ui32LastSent >= _ui32WinSize) {
        _ui32LastSent = _ui32ByteSent;
        sendAcknowledgement(_ui32ByteSent);
    }
xzl committed
278 279
}

280

xzl committed
281
void RtmpProtocol::onParseRtmp(const char *pcRawData, int iSize) {
282 283
	_strRcvBuf.append(pcRawData, iSize);
	auto cb = _nextHandle;
xzl committed
284 285 286 287 288 289 290
	cb();
}

////for client////
void RtmpProtocol::startClientSession(const function<void()> &callBack) {
	//发送 C0C1
	char handshake_head = HANDSHAKE_PLAINTEXT;
291
	onSendRawData(obtainBuffer(&handshake_head, 1));
292
	RtmpHandshake c1(0);
293
	onSendRawData(obtainBuffer((char *) (&c1), sizeof(c1)));
294
	_nextHandle = [this,callBack]() {
xzl committed
295 296 297 298 299
		//等待 S0+S1+S2
		handle_S0S1S2(callBack);
	};
}
void RtmpProtocol::handle_S0S1S2(const function<void()> &callBack) {
300
	if (_strRcvBuf.size() < 1 + 2 * C1_HANDSHARK_SIZE) {
xzl committed
301 302 303
		//数据不够
		return;
	}
304
	if (_strRcvBuf[0] != HANDSHAKE_PLAINTEXT) {
xzl committed
305 306 307
		throw std::runtime_error("only plaintext[0x03] handshake supported");
	}
	//发送 C2
308
	const char *pcC2 = _strRcvBuf.data() + 1;
309
	onSendRawData(obtainBuffer(pcC2, C1_HANDSHARK_SIZE));
310
	_strRcvBuf.erase(0, 1 + 2 * C1_HANDSHARK_SIZE);
xzl committed
311
	//握手结束
312
	_nextHandle = [this]() {
xzl committed
313 314 315 316 317 318 319
		//握手结束并且开始进入解析命令模式
		handle_rtmp();
	};
	callBack();
}
////for server ////
void RtmpProtocol::handle_C0C1() {
320
	if (_strRcvBuf.size() < 1 + C1_HANDSHARK_SIZE) {
xzl committed
321 322 323
		//need more data!
		return;
	}
324
	if (_strRcvBuf[0] != HANDSHAKE_PLAINTEXT) {
xzl committed
325 326
		throw std::runtime_error("only plaintext[0x03] handshake supported");
	}
xiongziliang committed
327
	if(memcmp(_strRcvBuf.data() + 5,"\x00\x00\x00\x00",4) ==0 ){
328 329 330 331 332 333 334 335 336 337 338
		//simple handsharke
		handle_C1_simple();
	}else{
#ifdef ENABLE_OPENSSL
		//complex handsharke
		handle_C1_complex();
#else
		WarnL << "未打开ENABLE_OPENSSL宏,复杂握手采用简单方式处理!";
		handle_C1_simple();
#endif//ENABLE_OPENSSL
	}
339
	_strRcvBuf.erase(0, 1 + C1_HANDSHARK_SIZE);
340 341
}
void RtmpProtocol::handle_C1_simple(){
xiongziliang committed
342
	//发送S0
343
	char handshake_head = HANDSHAKE_PLAINTEXT;
344
	onSendRawData(obtainBuffer(&handshake_head, 1));
xiongziliang committed
345
	//发送S1
346
	RtmpHandshake s1(0);
347
	onSendRawData(obtainBuffer((char *) &s1, C1_HANDSHARK_SIZE));
xiongziliang committed
348
	//发送S2
xiongziliang committed
349
	onSendRawData(obtainBuffer(_strRcvBuf.data() + 1, C1_HANDSHARK_SIZE));
xzl committed
350
	//等待C2
351
	_nextHandle = [this]() {
xzl committed
352 353 354
		handle_C2();
	};
}
355
#ifdef ENABLE_OPENSSL
356
void RtmpProtocol::handle_C1_complex(){
357
	//参考自:http://blog.csdn.net/win_lin/article/details/13006803
358
	//skip c0,time,version
359
	const char *c1_start = _strRcvBuf.data() + 1;
360 361 362 363 364 365 366 367 368 369 370 371 372 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
	const char *schema_start = c1_start + 8;
	char *digest_start;
	try{
		/* c1s1 schema0
		time: 4bytes
		version: 4bytes
		key: 764bytes
		digest: 764bytes
		 */
		auto digest = get_C1_digest((uint8_t *)schema_start + C1_SCHEMA_SIZE,&digest_start);
		string c1_joined(c1_start,C1_HANDSHARK_SIZE);
		c1_joined.erase(digest_start - c1_start , C1_DIGEST_SIZE );
		check_C1_Digest(digest,c1_joined);

		send_complex_S0S1S2(0,digest);
		InfoL << "schema0";
	}catch(std::exception &ex){
		//貌似flash从来都不用schema1
		WarnL << "try rtmp complex schema0 failed:" <<  ex.what();
		try{
			/* c1s1 schema1
			time: 4bytes
			version: 4bytes
			digest: 764bytes
			key: 764bytes
			 */
			auto digest = get_C1_digest((uint8_t *)schema_start,&digest_start);
			string c1_joined(c1_start,C1_HANDSHARK_SIZE);
			c1_joined.erase(digest_start - c1_start , C1_DIGEST_SIZE );
			check_C1_Digest(digest,c1_joined);

			send_complex_S0S1S2(1,digest);
			InfoL << "schema1";
		}catch(std::exception &ex){
			WarnL << "try rtmp complex schema1 failed:" <<  ex.what();
			handle_C1_simple();
		}
	}
}

400 401 402
#if !defined(u_int8_t)
#define u_int8_t unsigned char
#endif // !defined(u_int8_t)
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

static u_int8_t FMSKey[] = {
    0x47, 0x65, 0x6e, 0x75, 0x69, 0x6e, 0x65, 0x20,
    0x41, 0x64, 0x6f, 0x62, 0x65, 0x20, 0x46, 0x6c,
    0x61, 0x73, 0x68, 0x20, 0x4d, 0x65, 0x64, 0x69,
    0x61, 0x20, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72,
    0x20, 0x30, 0x30, 0x31, // Genuine Adobe Flash Media Server 001
    0xf0, 0xee, 0xc2, 0x4a, 0x80, 0x68, 0xbe, 0xe8,
    0x2e, 0x00, 0xd0, 0xd1, 0x02, 0x9e, 0x7e, 0x57,
    0x6e, 0xec, 0x5d, 0x2d, 0x29, 0x80, 0x6f, 0xab,
    0x93, 0xb8, 0xe6, 0x36, 0xcf, 0xeb, 0x31, 0xae
}; // 68

static u_int8_t FPKey[] = {
    0x47, 0x65, 0x6E, 0x75, 0x69, 0x6E, 0x65, 0x20,
    0x41, 0x64, 0x6F, 0x62, 0x65, 0x20, 0x46, 0x6C,
    0x61, 0x73, 0x68, 0x20, 0x50, 0x6C, 0x61, 0x79,
    0x65, 0x72, 0x20, 0x30, 0x30, 0x31, // Genuine Adobe Flash Player 001
    0xF0, 0xEE, 0xC2, 0x4A, 0x80, 0x68, 0xBE, 0xE8,
    0x2E, 0x00, 0xD0, 0xD1, 0x02, 0x9E, 0x7E, 0x57,
    0x6E, 0xEC, 0x5D, 0x2D, 0x29, 0x80, 0x6F, 0xAB,
    0x93, 0xB8, 0xE6, 0x36, 0xCF, 0xEB, 0x31, 0xAE
}; // 62
void RtmpProtocol::check_C1_Digest(const string &digest,const string &data){
	auto sha256 = openssl_HMACsha256(FPKey,C1_FPKEY_SIZE,data.data(),data.size());
	if(sha256 != digest){
429
		throw std::runtime_error("digest mismatched");
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
	}else{
		InfoL << "check rtmp complex handshark success!";
	}
}
string RtmpProtocol::get_C1_digest(const uint8_t *ptr,char **digestPos){
	/* 764bytes digest结构
	offset: 4bytes
	random-data: (offset)bytes
	digest-data: 32bytes
	random-data: (764-4-offset-32)bytes
	 */
	int offset = 0;
	for(int i=0;i<C1_OFFSET_SIZE;++i){
		offset += ptr[i];
	}
	offset %= (C1_SCHEMA_SIZE - C1_DIGEST_SIZE - C1_OFFSET_SIZE);
	*digestPos = (char *)ptr + C1_OFFSET_SIZE + offset;
	string digest(*digestPos,C1_DIGEST_SIZE);
	//DebugL << "digest offset:" << offset << ",digest:" << hexdump(digest.data(),digest.size());
	return digest;
}
string RtmpProtocol::get_C1_key(const uint8_t *ptr){
	/* 764bytes key结构
	random-data: (offset)bytes
	key-data: 128bytes
	random-data: (764-offset-128-4)bytes
	offset: 4bytes
	 */
	int offset = 0;
	for(int i = C1_SCHEMA_SIZE - C1_OFFSET_SIZE;i< C1_SCHEMA_SIZE;++i){
		offset += ptr[i];
	}
	offset %= (C1_SCHEMA_SIZE - C1_KEY_SIZE - C1_OFFSET_SIZE);
	string key((char *)ptr + offset,C1_KEY_SIZE);
	//DebugL << "key offset:" << offset << ",key:" << hexdump(key.data(),key.size());
	return key;
}
void RtmpProtocol::send_complex_S0S1S2(int schemeType,const string &digest){
468
	//S1S2计算参考自:https://github.com/hitYangfei/golang/blob/master/rtmpserver.go
469 470
	//发送S0
	char handshake_head = HANDSHAKE_PLAINTEXT;
471
	onSendRawData(obtainBuffer(&handshake_head, 1));
472
	//S1
473
	RtmpHandshake s1(0);
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
	memcpy(s1.zero,"\x04\x05\x00\x01",4);
	char *digestPos;
	if(schemeType == 0){
		/* c1s1 schema0
		time: 4bytes
		version: 4bytes
		key: 764bytes
		digest: 764bytes
		 */
		get_C1_digest(s1.random + C1_SCHEMA_SIZE,&digestPos);
	}else{
		/* c1s1 schema1
		time: 4bytes
		version: 4bytes
		digest: 764bytes
		key: 764bytes
		 */
		get_C1_digest(s1.random,&digestPos);
	}
	char *s1_start = (char *)&s1;
	string s1_joined(s1_start,sizeof(s1));
	s1_joined.erase(digestPos - s1_start,C1_DIGEST_SIZE);
	string s1_digest = openssl_HMACsha256(FMSKey,S1_FMS_KEY_SIZE,s1_joined.data(),s1_joined.size());
	memcpy(digestPos,s1_digest.data(),s1_digest.size());
498
	onSendRawData(obtainBuffer((char *) &s1, sizeof(s1)));
xzl committed
499

500 501 502 503 504 505
	//S2
	string s2_key = openssl_HMACsha256(FMSKey,S2_FMS_KEY_SIZE,digest.data(),digest.size());
	RtmpHandshake s2(0);
	s2.random_generate((char *)&s2,8);
	string s2_digest = openssl_HMACsha256(s2_key.data(),s2_key.size(),&s2,sizeof(s2) - C1_DIGEST_SIZE);
	memcpy((char *)&s2 + C1_HANDSHARK_SIZE - C1_DIGEST_SIZE,s2_digest.data(),C1_DIGEST_SIZE);
506
	onSendRawData(obtainBuffer((char *)&s2, sizeof(s2)));
507
	//等待C2
508
	_nextHandle = [this]() {
509 510 511
		handle_C2();
	};
}
512
#endif //ENABLE_OPENSSL
xzl committed
513
void RtmpProtocol::handle_C2() {
514
	if (_strRcvBuf.size() < C1_HANDSHARK_SIZE) {
xzl committed
515 516 517
		//need more data!
		return;
	}
518
	_strRcvBuf.erase(0, C1_HANDSHARK_SIZE);
xzl committed
519
	//握手结束,进入命令模式
520
	if (!_strRcvBuf.empty()) {
xzl committed
521 522
		handle_rtmp();
	}
523
	_nextHandle = [this]() {
xzl committed
524 525 526 527 528
		handle_rtmp();
	};
}

void RtmpProtocol::handle_rtmp() {
529 530
	while (!_strRcvBuf.empty()) {
		uint8_t flags = _strRcvBuf[0];
xzl committed
531 532 533
		int iOffset = 0;
		static const size_t HEADER_LENGTH[] = { 12, 8, 4, 1 };
		size_t iHeaderLen = HEADER_LENGTH[flags >> 6];
534 535
		_iNowChunkID = flags & 0x3f;
        if(_iNowChunkID >10){
xzl committed
536 537 538
            int i=0;
            i++;
        }
539
		switch (_iNowChunkID) {
xzl committed
540 541 542
		case 0: {
			//0 值表示二字节形式,并且 ID 范围 64 - 319
			//(第二个字节 + 64)。
543
			if (_strRcvBuf.size() < 2) {
xzl committed
544 545 546
				//need more data
				return;
			}
547
			_iNowChunkID = 64 + (uint8_t) (_strRcvBuf[1]);
xzl committed
548 549 550 551 552 553
			iOffset = 1;
		}
			break;
		case 1: {
			//1 值表示三字节形式,并且 ID 范围为 64 - 65599
			//((第三个字节) * 256 + 第二个字节 + 64)。
554
			if (_strRcvBuf.size() < 3) {
xzl committed
555 556 557
				//need more data
				return;
			}
558
			_iNowChunkID = 64 + ((uint8_t) (_strRcvBuf[2]) << 8) + (uint8_t) (_strRcvBuf[1]);
xzl committed
559 560 561 562 563 564 565 566
			iOffset = 2;
		}
			break;
		default:
			//带有 2 值的块流 ID 被保留,用于下层协议控制消息和命令。
			break;
		}

567
		if (_strRcvBuf.size() < iHeaderLen + iOffset) {
xzl committed
568 569 570
			//need more data
			return;
		}
571 572 573
		RtmpHeader &header = *((RtmpHeader *) (_strRcvBuf.data() + iOffset));
		auto &chunkData = _mapChunkData[_iNowChunkID];
		chunkData.chunkId = _iNowChunkID;
xzl committed
574 575
		switch (iHeaderLen) {
		case 12:
xzl committed
576
            chunkData.hasAbsStamp = true;
xzl committed
577 578 579 580 581
			chunkData.streamId = load_le32(header.streamId);
		case 8:
			chunkData.bodySize = load_be24(header.bodySize);
			chunkData.typeId = header.typeId;
		case 4:
xzl committed
582
			chunkData.deltaStamp = load_be24(header.timeStamp);
xzl committed
583
            chunkData.hasExtStamp = chunkData.deltaStamp == 0xFFFFFF;
xzl committed
584
		}
xzl committed
585
		
xzl committed
586
        if (chunkData.hasExtStamp) {
587
			if (_strRcvBuf.size() < iHeaderLen + iOffset + 4) {
xzl committed
588 589 590
				//need more data
				return;
			}
591
            chunkData.deltaStamp = load_be32(_strRcvBuf.data() + iOffset + iHeaderLen);
xzl committed
592 593
			iOffset += 4;
		}
xzl committed
594 595
		
        if (chunkData.bodySize < chunkData.strBuf.size()) {
xzl committed
596 597
			throw std::runtime_error("非法的bodySize");
		}
xzl committed
598
        
599 600
		auto iMore = min(_iChunkLenIn, chunkData.bodySize - chunkData.strBuf.size());
		if (_strRcvBuf.size() < iHeaderLen + iOffset + iMore) {
xzl committed
601 602 603
			//need more data
			return;
		}
xzl committed
604
		
605 606
        chunkData.strBuf.append(_strRcvBuf, iHeaderLen + iOffset, iMore);
		_strRcvBuf.erase(0, iHeaderLen + iOffset + iMore);
xzl committed
607
        
xzl committed
608
		if (chunkData.strBuf.size() == chunkData.bodySize) {
xzl committed
609
            //frame is ready
610
            _iNowStreamID = chunkData.streamId;
xzl committed
611
            chunkData.timeStamp = chunkData.deltaStamp + (chunkData.hasAbsStamp ? 0 : chunkData.timeStamp);
xzl committed
612
            
613 614 615
			if(chunkData.bodySize){
				handle_rtmpChunk(chunkData);
			}
xzl committed
616
			chunkData.strBuf.clear();
xzl committed
617 618 619
            chunkData.hasAbsStamp = false;
            chunkData.hasExtStamp = false;
            chunkData.deltaStamp = 0;
xzl committed
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
		}
	}
}

void RtmpProtocol::handle_rtmpChunk(RtmpPacket& chunkData) {
	switch (chunkData.typeId) {
		case MSG_ACK: {
			if (chunkData.strBuf.size() < 4) {
				throw std::runtime_error("MSG_ACK: Not enough data");
			}
			//auto bytePeerRecv = load_be32(&chunkData.strBuf[0]);
			//TraceL << "MSG_ACK:" << bytePeerRecv;
		}
			break;
		case MSG_SET_CHUNK: {
			if (chunkData.strBuf.size() < 4) {
				throw std::runtime_error("MSG_SET_CHUNK :Not enough data");
			}
638 639
			_iChunkLenIn = load_be32(&chunkData.strBuf[0]);
			TraceL << "MSG_SET_CHUNK:" << _iChunkLenIn;
xzl committed
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
		}
			break;
		case MSG_USER_CONTROL: {
			//user control message
			if (chunkData.strBuf.size() < 2) {
				throw std::runtime_error("MSG_USER_CONTROL: Not enough data.");
			}
			uint16_t event_type = load_be16(&chunkData.strBuf[0]);
			chunkData.strBuf.erase(0, 2);
			switch (event_type) {
			case CONTROL_PING_REQUEST: {
					if (chunkData.strBuf.size() < 4) {
						throw std::runtime_error("CONTROL_PING_REQUEST: Not enough data.");
					}
					uint32_t timeStamp = load_be32(&chunkData.strBuf[0]);
					//TraceL << "CONTROL_PING_REQUEST:" << timeStamp;
					sendUserControl(CONTROL_PING_RESPONSE, timeStamp);
				}
					break;
			case CONTROL_PING_RESPONSE: {
				if (chunkData.strBuf.size() < 4) {
					throw std::runtime_error("CONTROL_PING_RESPONSE: Not enough data.");
				}
				//uint32_t timeStamp = load_be32(&chunkData.strBuf[0]);
				//TraceL << "CONTROL_PING_RESPONSE:" << timeStamp;
			}
				break;
			case CONTROL_STREAM_BEGIN: {
				//开始播放
				if (chunkData.strBuf.size() < 4) {
					throw std::runtime_error("CONTROL_STREAM_BEGIN: Not enough data.");
				}
				uint32_t stramId = load_be32(&chunkData.strBuf[0]);
				onStreamBegin(stramId);
				TraceL << "CONTROL_STREAM_BEGIN:" << stramId;
			}
				break;

			case CONTROL_STREAM_EOF: {
				//暂停
				if (chunkData.strBuf.size() < 4) {
					throw std::runtime_error("CONTROL_STREAM_EOF: Not enough data.");
				}
				uint32_t stramId = load_be32(&chunkData.strBuf[0]);
				onStreamEof(stramId);
				TraceL << "CONTROL_STREAM_EOF:" << stramId;
			}
				break;
			case CONTROL_STREAM_DRY: {
				//停止播放
				if (chunkData.strBuf.size() < 4) {
					throw std::runtime_error("CONTROL_STREAM_DRY: Not enough data.");
				}
				uint32_t stramId = load_be32(&chunkData.strBuf[0]);
				onStreamDry(stramId);
				TraceL << "CONTROL_STREAM_DRY:" << stramId;
			}
				break;
			default:
				//WarnL << "unhandled user control:" << event_type;
				break;
			}
		}
			break;

		case MSG_WIN_SIZE: {
706 707
			_ui32WinSize = load_be32(&chunkData.strBuf[0]);
			TraceL << "MSG_WIN_SIZE:" << _ui32WinSize;
xzl committed
708 709 710
		}
			break;
		case MSG_SET_PEER_BW: {
711 712 713
			_ui32Bandwidth = load_be32(&chunkData.strBuf[0]);
			_ui8LimitType =  chunkData.strBuf[4];
			TraceL << "MSG_SET_PEER_BW:" << _ui32WinSize;
xzl committed
714 715
		}
			break;
xiongziliang committed
716 717
		case MSG_AGGREGATE: {
			auto ptr = (uint8_t*)chunkData.strBuf.data();
718 719
			auto ptr_tail = ptr + chunkData.strBuf.length() ;
			while(ptr + 8 + 3 < ptr_tail){
xiongziliang committed
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
				auto type = *ptr;
				ptr += 1;
				auto size = load_be24(ptr);
				ptr += 3;
				auto ts = load_be24(ptr);
				ptr += 3;
				ts |= (*ptr << 24);
				ptr += 1;

				//参考ffmpeg忽略了3个字节
				/**
				 *  while (next - pkt->data < pkt->size - RTMP_HEADER) {
						type = bytestream_get_byte(&next);
						size = bytestream_get_be24(&next);
						cts  = bytestream_get_be24(&next);
						cts |= bytestream_get_byte(&next) << 24;
						if (!pts)
							pts = cts;
						ts += cts - pts;
						pts = cts;
						if (size + 3 + 4 > pkt->data + pkt->size - next)
							break;
						bytestream_put_byte(&p, type);
						bytestream_put_be24(&p, size);
						bytestream_put_be24(&p, ts);
						bytestream_put_byte(&p, ts >> 24);
						memcpy(p, next, size + 3 + 4);
						p    += size + 3;
						bytestream_put_be32(&p, size + RTMP_HEADER);
						next += size + 3 + 4;
					}
				 */
				ptr += 3;
				//参考FFmpeg多拷贝了4个字节
				size += 4;
				if(ptr + size > ptr_tail){
756
//				    ErrorL << ptr + size << " " << ptr_tail << " " << ptr_tail - ptr - size;
xiongziliang committed
757 758
					break;
				}
759
//				DebugL << (int)type << " " << size << " " << ts << " " << chunkData.timeStamp << " " << ptr_tail - ptr;
xiongziliang committed
760 761 762 763 764 765 766 767 768 769 770
				RtmpPacket sub_packet ;
				sub_packet.strBuf.resize(size);
				memcpy((char *)sub_packet.strBuf.data(),ptr,size);
				sub_packet.typeId = type;
				sub_packet.bodySize = size;
				sub_packet.timeStamp = ts;
				sub_packet.streamId = chunkData.streamId;
				sub_packet.chunkId = chunkData.chunkId;
				handle_rtmpChunk(sub_packet);
				ptr += size;
			}
771
//			InfoL << ptr_tail - ptr;
xiongziliang committed
772
		}
xzl committed
773 774 775 776 777 778 779
			break;
		default:
			onRtmpChunk(chunkData);
			break;
		}
}

xiongziliang committed
780 781 782 783
BufferRaw::Ptr RtmpProtocol::obtainBuffer() {
    return std::make_shared<BufferRaw>() ;//_bufferPool.obtain();
}

784 785 786 787 788 789
BufferRaw::Ptr RtmpProtocol::obtainBuffer(const void *data, int len) {
	auto buffer = obtainBuffer();
	buffer->assign((const char *)data,len);
	return buffer;
}

xiongziliang committed
790
} /* namespace mediakit */