amf.cpp 15.5 KB
Newer Older
xiongziliang committed
1
/*
xiongziliang committed
2 3
 * MIT License
 *
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 25
 *
 * 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
26
#include <string.h>
xiongzilaing committed
27 28 29
#include <stdexcept>
#include "amf.h"
#include "utils.h"
xzl committed
30
#include "Util/util.h"
31 32
#include "Util/logger.h"
#include "Network/sockutil.h"
xiongziliang committed
33
#include "Util/util.h"
xiongziliang committed
34
using namespace toolkit;
xzl committed
35 36 37

/////////////////////AMFValue/////////////////////////////
inline void AMFValue::destroy() {
38
	switch (_type) {
xzl committed
39
	case AMF_STRING:
40 41 42
		if (_value.string) {
			delete _value.string;
			_value.string = nullptr;
xzl committed
43 44 45 46
		}
		break;
	case AMF_OBJECT:
	case AMF_ECMA_ARRAY:
47 48 49
		if (_value.object) {
			delete _value.object;
			_value.object = nullptr;
xzl committed
50 51 52
		}
		break;
	case AMF_STRICT_ARRAY:
53 54 55
		if (_value.array) {
			delete _value.array;
			_value.array = nullptr;
xzl committed
56 57 58 59 60 61 62
		}
		break;
	default:
		break;
	}
}
inline void AMFValue::init() {
63
	switch (_type) {
xzl committed
64 65
	case AMF_OBJECT:
	case AMF_ECMA_ARRAY:
66
		_value.object = new mapType;
xzl committed
67 68
		break;
	case AMF_STRING:
69
		_value.string = new std::string;
xzl committed
70 71
		break;
	case AMF_STRICT_ARRAY:
72
		_value.array = new arrayType;
xzl committed
73 74 75 76 77 78 79
		break;

	default:
		break;
	}

}
xiongziliang committed
80 81
AMFValue::AMFValue(AMFType type) :
		_type(type) {
xzl committed
82 83 84 85 86 87 88 89 90
	init();
}


AMFValue::~AMFValue() {
	destroy();
}

AMFValue::AMFValue(const char *s) :
91
		_type(AMF_STRING) {
xzl committed
92
	init();
93
	*_value.string = s;
xzl committed
94 95 96 97
}


AMFValue::AMFValue(const std::string &s) :
98
		_type(AMF_STRING) {
xzl committed
99
	init();
100
	*_value.string = s;
xzl committed
101 102 103
}

AMFValue::AMFValue(double n) :
104
		_type(AMF_NUMBER) {
xzl committed
105
	init();
106
	_value.number = n;
xzl committed
107 108 109
}

AMFValue::AMFValue(int i) :
110
		_type(AMF_INTEGER) {
xzl committed
111
	init();
112
	_value.integer = i;
xzl committed
113 114 115
}

AMFValue::AMFValue(bool b) :
116
		_type(AMF_BOOLEAN) {
xzl committed
117
	init();
118
	_value.boolean = b;
xzl committed
119 120 121
}

AMFValue::AMFValue(const AMFValue &from) :
122
		_type(AMF_NULL) {
xzl committed
123 124 125 126
	*this = from;
}

AMFValue::AMFValue(AMFValue &&from) {
xiongziliang committed
127
	*this = std::forward<AMFValue>(from);
xzl committed
128 129 130 131 132 133 134 135
}

AMFValue& AMFValue::operator =(const AMFValue &from) {
	return *this = const_cast<AMFValue &&>(from);

}
AMFValue& AMFValue::operator =(AMFValue &&from) {
	destroy();
136
	_type = from._type;
xzl committed
137
	init();
138
	switch (_type) {
xzl committed
139
	case AMF_STRING:
140
		*_value.string = (*from._value.string);
xzl committed
141 142 143
		break;
	case AMF_OBJECT:
	case AMF_ECMA_ARRAY:
144
		*_value.object = (*from._value.object);
xzl committed
145 146
		break;
	case AMF_STRICT_ARRAY:
147
		*_value.array = (*from._value.array);
xzl committed
148 149
		break;
	case AMF_NUMBER:
150
		_value.number = from._value.number;
xzl committed
151 152
		break;
	case AMF_INTEGER:
153
		_value.integer = from._value.integer;
xzl committed
154 155
		break;
	case AMF_BOOLEAN:
156
		_value.boolean = from._value.boolean;
xzl committed
157 158 159 160 161 162 163 164
		break;
	default:
		break;
	}
	return *this;

}

xiongziliang committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 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
void AMFValue::clear() {
    switch (_type) {
        case AMF_STRING:
            _value.string->clear();
            break;
        case AMF_OBJECT:
        case AMF_ECMA_ARRAY:
            _value.object->clear();
            break;
        default:
            break;
    }
}

AMFType AMFValue::type() const {
    return _type;
}

const std::string &AMFValue::as_string() const {
    if(_type != AMF_STRING){
        throw std::runtime_error("AMF not a string");
    }
    return *_value.string;
}

double AMFValue::as_number() const {
    switch (_type) {
        case AMF_NUMBER:
            return _value.number;
        case AMF_INTEGER:
            return _value.integer;
        case AMF_BOOLEAN:
            return _value.boolean;
        default:
            throw std::runtime_error("AMF not a number");
    }
}

int AMFValue::as_integer() const {
    switch (_type) {
        case AMF_NUMBER:
            return _value.number;
        case AMF_INTEGER:
            return _value.integer;
        case AMF_BOOLEAN:
            return _value.boolean;
        default:
            throw std::runtime_error("AMF not a integer");
    }
}

bool AMFValue::as_boolean() const {
    switch (_type) {
        case AMF_NUMBER:
            return _value.number;
        case AMF_INTEGER:
            return _value.integer;
        case AMF_BOOLEAN:
            return _value.boolean;
        default:
            throw std::runtime_error("AMF not a boolean");
    }
}

xiongziliang committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
string AMFValue::to_string() const{
    switch (_type) {
        case AMF_NUMBER:
            return StrPrinter << _value.number;
        case AMF_INTEGER:
            return StrPrinter << _value.integer;
        case AMF_BOOLEAN:
            return _value.boolean ? "true" : "false";
        case AMF_STRING:
            return *(_value.string);
        case AMF_OBJECT:
            return "object";
        case AMF_NULL:
            return "null";
        case AMF_UNDEFINED:
            return "undefined";
        case AMF_ECMA_ARRAY:
            return "ecma_array";
        case AMF_STRICT_ARRAY:
            return "strict_array";
        default:
            throw std::runtime_error("can not convert to string ");
    }
}


xiongziliang committed
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 292 293 294 295 296 297 298 299 300 301 302 303 304
const AMFValue& AMFValue::operator[](const char *str) const {
    if (_type != AMF_OBJECT && _type != AMF_ECMA_ARRAY) {
        throw std::runtime_error("AMF not a object");
    }
    auto i = _value.object->find(str);
    if (i == _value.object->end()) {
        static AMFValue val(AMF_NULL);
        return val;
    }
    return i->second;
}

void AMFValue::object_for_each(const function<void(const string &key, const AMFValue &val)> &fun) const {
    if (_type != AMF_OBJECT && _type != AMF_ECMA_ARRAY) {
        throw std::runtime_error("AMF not a object");
    }
    for (auto & pr : *(_value.object)) {
        fun(pr.first, pr.second);
    }
}

AMFValue::operator bool() const{
    return _type != AMF_NULL;
}
void AMFValue::set(const std::string &s, const AMFValue &val) {
    if (_type != AMF_OBJECT && _type != AMF_ECMA_ARRAY) {
        throw std::runtime_error("AMF not a object");
    }
    _value.object->emplace(s, val);
}
void AMFValue::add(const AMFValue &val) {
    if (_type != AMF_STRICT_ARRAY) {
        throw std::runtime_error("AMF not a array");
    }
    assert(_type == AMF_STRICT_ARRAY);
    _value.array->push_back(val);
}

const AMFValue::mapType &AMFValue::getMap() const {
    if (_type != AMF_OBJECT && _type != AMF_ECMA_ARRAY) {
        throw std::runtime_error("AMF not a object");
    }
    return *_value.object;
}
const AMFValue::arrayType &AMFValue::getArr() const {
    if (_type != AMF_STRICT_ARRAY) {
        throw std::runtime_error("AMF not a array");
    }
    return *_value.array;
}
xzl committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 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 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
///////////////////////////////////////////////////////////////////////////

enum {
	AMF0_NUMBER,
	AMF0_BOOLEAN,
	AMF0_STRING,
	AMF0_OBJECT,
	AMF0_MOVIECLIP,
	AMF0_NULL,
	AMF0_UNDEFINED,
	AMF0_REFERENCE,
	AMF0_ECMA_ARRAY,
	AMF0_OBJECT_END,
	AMF0_STRICT_ARRAY,
	AMF0_DATE,
	AMF0_LONG_STRING,
	AMF0_UNSUPPORTED,
	AMF0_RECORD_SET,
	AMF0_XML_OBJECT,
	AMF0_TYPED_OBJECT,
	AMF0_SWITCH_AMF3,
};

enum {
	AMF3_UNDEFINED,
	AMF3_NULL,
	AMF3_FALSE,
	AMF3_TRUE,
	AMF3_INTEGER,
	AMF3_NUMBER,
	AMF3_STRING,
	AMF3_LEGACY_XML,
	AMF3_DATE,
	AMF3_ARRAY,
	AMF3_OBJECT,
	AMF3_XML,
	AMF3_BYTE_ARRAY,
};

////////////////////////////////Encoder//////////////////////////////////////////
AMFEncoder & AMFEncoder::operator <<(const char *s) {
	if (s) {
		buf += char(AMF0_STRING);
		uint16_t str_len = htons(strlen(s));
		buf.append((char *) &str_len, 2);
		buf += s;
	} else {
		buf += char(AMF0_NULL);
	}
	return *this;
}
AMFEncoder & AMFEncoder::operator <<(const std::string &s) {
	if (!s.empty()) {
		buf += char(AMF0_STRING);
		uint16_t str_len = htons(s.size());
		buf.append((char *) &str_len, 2);
		buf += s;
	} else {
		buf += char(AMF0_NULL);
	}
	return *this;
}
AMFEncoder & AMFEncoder::operator <<(std::nullptr_t) {
	buf += char(AMF0_NULL);
	return *this;
}
AMFEncoder & AMFEncoder::write_undefined() {
	buf += char(AMF0_UNDEFINED);
	return *this;

}
AMFEncoder & AMFEncoder::operator <<(const int n){
	return (*this) << (double)n;
}
AMFEncoder & AMFEncoder::operator <<(const double n) {
	buf += char(AMF0_NUMBER);
	uint64_t encoded = 0;
	memcpy(&encoded, &n, 8);
	uint32_t val = htonl(encoded >> 32);
	buf.append((char *) &val, 4);
	val = htonl(encoded);
	buf.append((char *) &val, 4);
	return *this;
}

AMFEncoder & AMFEncoder::operator <<(const bool b) {
	buf += char(AMF0_BOOLEAN);
	buf += char(b);
	return *this;
}

AMFEncoder & AMFEncoder::operator <<(const AMFValue& value) {
	switch ((int) value.type()) {
	case AMF_STRING:
		*this << value.as_string();
		break;
	case AMF_NUMBER:
		*this << value.as_number();
		break;
	case AMF_INTEGER:
		*this << value.as_integer();
		break;
	case AMF_BOOLEAN:
		*this << value.as_boolean();
		break;
	case AMF_OBJECT: {
		buf += char(AMF0_OBJECT);
		for (auto &pr : value.getMap()) {
			write_key(pr.first);
			*this << pr.second;
		}
		write_key("");
		buf += char(AMF0_OBJECT_END);
	}
		break;
	case AMF_ECMA_ARRAY: {
		buf += char(AMF0_ECMA_ARRAY);
		uint32_t sz = htonl(value.getMap().size());
		buf.append((char *) &sz, 4);
		for (auto &pr : value.getMap()) {
			write_key(pr.first);
			*this << pr.second;
		}
		write_key("");
		buf += char(AMF0_OBJECT_END);
	}
		break;
	case AMF_NULL:
		*this << nullptr;
		break;
	case AMF_UNDEFINED:
		this->write_undefined();
		break;
	case AMF_STRICT_ARRAY: {
		buf += char(AMF0_STRICT_ARRAY);
		uint32_t sz = htonl(value.getArr().size());
		buf.append((char *) &sz, 4);
		for (auto &val : value.getArr()) {
			*this << val;
		}
		//write_key("");
		//buf += char(AMF0_OBJECT_END);
	}
		break;
	}
	return *this;

}

void AMFEncoder::write_key(const std::string& s) {
	uint16_t str_len = htons(s.size());
	buf.append((char *) &str_len, 2);
	buf += s;
}

xiongziliang committed
460 461 462 463 464 465 466 467
void AMFEncoder::clear() {
    buf.clear();
}

const std::string& AMFEncoder::data() const {
    return buf;
}

xzl committed
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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 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
//////////////////Decoder//////////////////

uint8_t AMFDecoder::front() {
	if (pos >= buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	return uint8_t(buf[pos]);
}

uint8_t AMFDecoder::pop_front() {
	if (version == 0 && front() == AMF0_SWITCH_AMF3) {
		InfoL << "entering AMF3 mode";
		pos++;
		version = 3;
	}

	if (pos >= buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	return uint8_t(buf[pos++]);
}

template<>
double AMFDecoder::load<double>() {
	if (pop_front() != AMF0_NUMBER) {
		throw std::runtime_error("Expected a number");
	}
	if (pos + 8 > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	uint64_t val = ((uint64_t) load_be32(&buf[pos]) << 32)
			| load_be32(&buf[pos + 4]);
	double n = 0;
	memcpy(&n, &val, 8);
	pos += 8;
	return n;

}

template<>
bool AMFDecoder::load<bool>() {
	if (pop_front() != AMF0_BOOLEAN) {
		throw std::runtime_error("Expected a boolean");
	}
	return pop_front() != 0;
}
template<>
unsigned int AMFDecoder::load<unsigned int>() {
	unsigned int value = 0;
	for (int i = 0; i < 4; ++i) {
		uint8_t b = pop_front();
		if (i == 3) {
			/* use all bits from 4th byte */
			value = (value << 8) | b;
			break;
		}
		value = (value << 7) | (b & 0x7f);
		if ((b & 0x80) == 0)
			break;
	}
	return value;
}

template<>
int AMFDecoder::load<int>() {
	if (version == 3) {
		return load<unsigned int>();
	} else {
		return load<double>();
	}
}

template<>
std::string AMFDecoder::load<std::string>() {
	size_t str_len = 0;
	uint8_t type = pop_front();
	if (version == 3) {
		if (type != AMF3_STRING) {
			throw std::runtime_error("Expected a string");
		}
		str_len = load<unsigned int>() / 2;

	} else {
		if (type != AMF0_STRING) {
			throw std::runtime_error("Expected a string");
		}
		if (pos + 2 > buf.size()) {
			throw std::runtime_error("Not enough data");
		}
		str_len = load_be16(&buf[pos]);
		pos += 2;
	}
	if (pos + str_len > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	std::string s(buf, pos, str_len);
	pos += str_len;
	return s;
}

template<>
AMFValue AMFDecoder::load<AMFValue>() {
	uint8_t type = front();
	if (version == 3) {
		switch (type) {
		case AMF3_STRING:
			return load<std::string>();
		case AMF3_NUMBER:
			return load<double>();
		case AMF3_INTEGER:
			return load<int>();
		case AMF3_FALSE:
			pos++;
			return false;
		case AMF3_TRUE:
			pos++;
			return true;
		case AMF3_OBJECT:
			return load_object();
		case AMF3_ARRAY:
			return load_ecma();
		case AMF3_NULL:
			pos++;
			return AMF_NULL;
		case AMF3_UNDEFINED:
			pos++;
			return AMF_UNDEFINED;
		default:
			throw std::runtime_error(
			StrPrinter << "Unsupported AMF3 type:" << (int) type << endl);
		}
	} else {
		switch (type) {
		case AMF0_STRING:
			return load<std::string>();
		case AMF0_NUMBER:
			return load<double>();
		case AMF0_BOOLEAN:
			return load<bool>();
		case AMF0_OBJECT:
			return load_object();
		case AMF0_ECMA_ARRAY:
			return load_ecma();
		case AMF0_NULL:
			pos++;
			return AMF_NULL;
		case AMF0_UNDEFINED:
			pos++;
			return AMF_UNDEFINED;
		case AMF0_STRICT_ARRAY:
			return load_arr();
		default:
			throw std::runtime_error(
			StrPrinter << "Unsupported AMF type:" << (int) type << endl);
		}
	}

}

std::string AMFDecoder::load_key() {
	if (pos + 2 > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	size_t str_len = load_be16(&buf[pos]);
	pos += 2;
	if (pos + str_len > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	std::string s(buf, pos, str_len);
	pos += str_len;
	return s;

}

AMFValue AMFDecoder::load_object() {
	AMFValue object(AMF_OBJECT);
	if (pop_front() != AMF0_OBJECT) {
		throw std::runtime_error("Expected an object");
	}
	while (1) {
		std::string key = load_key();
		if (key.empty())
			break;
		AMFValue value = load<AMFValue>();
		object.set(key, value);
	}
	if (pop_front() != AMF0_OBJECT_END) {
		throw std::runtime_error("expected object end");
	}
	return object;
}

AMFValue AMFDecoder::load_ecma() {
	/* ECMA array is the same as object, with 4 extra zero bytes */
	AMFValue object(AMF_ECMA_ARRAY);
	if (pop_front() != AMF0_ECMA_ARRAY) {
		throw std::runtime_error("Expected an ECMA array");
	}
	if (pos + 4 > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	pos += 4;
	while (1) {
		std::string key = load_key();
		if (key.empty())
			break;
		AMFValue value = load<AMFValue>();
		object.set(key, value);
	}
	if (pop_front() != AMF0_OBJECT_END) {
		throw std::runtime_error("expected object end");
	}
	return object;
}
AMFValue AMFDecoder::load_arr() {
	/* ECMA array is the same as object, with 4 extra zero bytes */
	AMFValue object(AMF_STRICT_ARRAY);
	if (pop_front() != AMF0_STRICT_ARRAY) {
		throw std::runtime_error("Expected an STRICT array");
	}
	if (pos + 4 > buf.size()) {
		throw std::runtime_error("Not enough data");
	}
	int arrSize = load_be32(&buf[pos]);
	pos += 4;
	while (arrSize--) {
		AMFValue value = load<AMFValue>();
		object.add(value);
	}
	/*pos += 2;
	if (pop_front() != AMF0_OBJECT_END) {
		throw std::runtime_error("expected object end");
	}*/
	return object;
}
xiongziliang committed
703 704 705 706 707

AMFDecoder::AMFDecoder(const std::string &buf_in, size_t pos_in, int version_in) :
        buf(buf_in), pos(pos_in), version(version_in) {
}