MadelineProto/src/danog/MadelineProto/VoIP/AuthKeyHandler.php

330 lines
17 KiB
PHP
Raw Normal View History

<?php
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
/**
* AuthKeyHandler module.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2020-02-17 14:13:46 +01:00
* @copyright 2016-2020 Daniil Gentili <daniil@daniil.it>
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
*
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
*/
2018-02-24 17:54:39 +01:00
namespace danog\MadelineProto\VoIP;
2020-07-28 20:39:32 +02:00
use danog\MadelineProto\Loop\Update\UpdateLoop;
2020-10-03 15:36:03 +02:00
use danog\MadelineProto\MTProtoTools\Crypt;
2020-03-01 16:31:56 +01:00
use danog\MadelineProto\Tools;
/**
* Manages the creation of the authorization key.
*
* https://core.telegram.org/mtproto/auth_key
* https://core.telegram.org/mtproto/samples-auth_key
*/
trait AuthKeyHandler
{
2017-05-27 23:21:14 +02:00
private $calls = [];
/**
2020-03-01 16:31:56 +01:00
* Accept call from VoIP instance.
*
2020-03-01 16:31:56 +01:00
* @param \danog\MadelineProto\VoIP $instance Call instance
* @param array $user User
*
2020-03-03 00:08:39 +01:00
* @internal
*
2020-03-01 16:31:56 +01:00
* @return mixed
*/
2020-03-01 16:31:56 +01:00
public function acceptCallFrom($instance, $user)
2019-05-15 22:08:49 +02:00
{
2020-03-01 16:31:56 +01:00
$promise = Tools::call((function () use ($instance, $user) {
if (!$res = yield from $this->acceptCall($user)) {
$instance->discard();
return false;
}
return $instance;
})());
if ($this->wrapper && $this->wrapper->isAsync()) {
return $promise;
}
return Tools::wait($promise);
2019-05-15 22:08:49 +02:00
}
/**
2020-03-01 16:31:56 +01:00
* Undocumented function.
*
2020-03-01 16:31:56 +01:00
* @param \danog\MadelineProto\VoIP $instance Call instance
* @param array $call Call info
* @param array $reason Discard reason
* @param array $rating Rating
* @param boolean $need_debug Needs debug?
*
2020-03-03 00:08:39 +01:00
* @internal
*
2020-03-01 16:31:56 +01:00
* @return mixed
*/
2020-03-01 16:31:56 +01:00
public function discardCallFrom($instance, $call, $reason, $rating = [], $need_debug = true)
2019-05-15 22:08:49 +02:00
{
2020-03-01 16:31:56 +01:00
$promise = Tools::call(function () use ($instance, $call, $reason, $rating, $need_debug) {
if (!$res = yield from $this->discardCall($call, $reason, $rating, $need_debug)) {
return false;
}
return $instance;
});
if ($this->wrapper && $this->wrapper->isAsync()) {
return $promise;
}
return Tools::wait($promise);
2019-05-15 22:08:49 +02:00
}
/**
* Request VoIP call.
*
* @param mixed $user User
*
2020-10-01 21:36:07 +02:00
* @return \Generator
*/
2020-03-01 16:31:56 +01:00
public function requestCall($user): \Generator
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-19 12:41:18 +02:00
}
2020-01-31 19:49:58 +01:00
$user = (yield from $this->getInfo($user));
2017-07-20 16:20:19 +02:00
if (!isset($user['InputUser']) || $user['InputUser']['_'] === 'inputUserSelf') {
throw new \danog\MadelineProto\Exception(\danog\MadelineProto\Lang::$current_lang['peer_not_in_db']);
2017-05-02 12:13:27 +02:00
}
2017-05-02 12:13:01 +02:00
$user = $user['InputUser'];
2020-09-26 17:11:41 +02:00
$this->logger->logger(\sprintf("Calling %s...", $user['user_id']), \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger(\danog\MadelineProto\Lang::$current_lang['generating_a'], \danog\MadelineProto\Logger::VERBOSE);
$a = \tgseclib\Math\BigInteger::randomRange(\danog\MadelineProto\Magic::$two, $dh_config['p']->subtract(\danog\MadelineProto\Magic::$two));
2018-04-08 19:53:30 +02:00
$this->logger->logger(\danog\MadelineProto\Lang::$current_lang['generating_g_a'], \danog\MadelineProto\Logger::VERBOSE);
$g_a = $dh_config['g']->powMod($a, $dh_config['p']);
2020-10-03 15:36:03 +02:00
Crypt::checkG($g_a, $dh_config['p']);
2019-03-29 20:25:42 +01:00
$controller = new \danog\MadelineProto\VoIP(true, $user['user_id'], $this, \danog\MadelineProto\VoIP::CALL_STATE_REQUESTED);
2019-09-02 17:08:36 +02:00
$controller->storage = ['a' => $a, 'g_a' => \str_pad($g_a->toBytes(), 256, \chr(0), \STR_PAD_LEFT)];
2020-02-05 17:37:01 +01:00
$res = yield from $this->methodCallAsyncRead('phone.requestCall', ['user_id' => $user, 'g_a_hash' => \hash('sha256', $g_a->toBytes(), true), 'protocol' => ['_' => 'phoneCallProtocol', 'udp_p2p' => true, 'udp_reflector' => true, 'min_layer' => 65, 'max_layer' => \danog\MadelineProto\VoIP::getConnectionMaxLayer()]], ['datacenter' => $this->datacenter->curdc]);
2019-03-29 20:25:42 +01:00
$controller->setCall($res['phone_call']);
$this->calls[$res['phone_call']['id']] = $controller;
2020-07-28 20:39:32 +02:00
yield $this->updaters[UpdateLoop::GENERIC]->resume();
2017-07-19 12:41:18 +02:00
return $controller;
}
/**
* Accept call.
*
* @param array $call Call
*
* @return \Generator
*/
2020-03-01 16:31:56 +01:00
public function acceptCall(array $call): \Generator
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
throw new \danog\MadelineProto\Exception();
2017-04-02 16:43:47 +02:00
}
2019-10-29 21:33:23 +01:00
if ($this->callStatus($call['id']) !== \danog\MadelineProto\VoIP::CALL_STATE_ACCEPTED) {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_error_1'], $call['id']));
2017-07-31 16:42:24 +02:00
return false;
}
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['accepting_call'], $this->calls[$call['id']]->getOtherID()), \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger(\danog\MadelineProto\Lang::$current_lang['generating_b'], \danog\MadelineProto\Logger::VERBOSE);
$b = \tgseclib\Math\BigInteger::randomRange(\danog\MadelineProto\Magic::$two, $dh_config['p']->subtract(\danog\MadelineProto\Magic::$two));
2017-04-02 16:42:17 +02:00
$g_b = $dh_config['g']->powMod($b, $dh_config['p']);
2020-10-03 15:36:03 +02:00
Crypt::checkG($g_b, $dh_config['p']);
try {
2020-02-05 17:37:01 +01:00
$res = yield from $this->methodCallAsyncRead('phone.acceptCall', ['peer' => $call, 'g_b' => $g_b->toBytes(), 'protocol' => ['_' => 'phoneCallProtocol', 'udp_reflector' => true, 'udp_p2p' => true, 'min_layer' => 65, 'max_layer' => \danog\MadelineProto\VoIP::getConnectionMaxLayer()]], ['datacenter' => $this->datacenter->curdc]);
} catch (\danog\MadelineProto\RPCErrorException $e) {
2017-07-28 22:38:13 +02:00
if ($e->rpc === 'CALL_ALREADY_ACCEPTED') {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_already_accepted'], $call['id']));
return true;
}
2017-07-31 16:42:24 +02:00
if ($e->rpc === 'CALL_ALREADY_DECLINED') {
2018-04-08 19:53:30 +02:00
$this->logger->logger(\danog\MadelineProto\Lang::$current_lang['call_already_declined']);
2020-03-01 16:31:56 +01:00
yield from $this->discardCall($call['id'], ['_' => 'phoneCallDiscardReasonHangup']);
2017-07-31 16:42:24 +02:00
return false;
}
throw $e;
}
2017-07-20 16:20:19 +02:00
$this->calls[$res['phone_call']['id']]->storage['b'] = $b;
2020-07-28 20:39:32 +02:00
yield $this->updaters[UpdateLoop::GENERIC]->resume();
2017-07-31 16:42:24 +02:00
return true;
2017-04-02 16:42:17 +02:00
}
/**
* Confirm call.
*
* @param array $params Params
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
public function confirmCall(array $params): \Generator
2017-04-02 16:42:17 +02:00
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-19 12:41:18 +02:00
}
2019-10-29 21:33:23 +01:00
if ($this->callStatus($params['id']) !== \danog\MadelineProto\VoIP::CALL_STATE_REQUESTED) {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_error_2'], $params['id']));
2017-04-02 16:42:17 +02:00
return false;
}
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_confirming'], $this->calls[$params['id']]->getOtherID()), \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
$params['g_b'] = new \tgseclib\Math\BigInteger((string) $params['g_b'], 256);
2020-10-03 15:36:03 +02:00
Crypt::checkG($params['g_b'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = \str_pad($params['g_b']->powMod($this->calls[$params['id']]->storage['a'], $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT);
2019-07-21 16:50:48 +02:00
try {
2020-02-05 17:37:01 +01:00
$res = (yield from $this->methodCallAsyncRead('phone.confirmCall', ['key_fingerprint' => \substr(\sha1($key, true), -8), 'peer' => ['id' => $params['id'], 'access_hash' => $params['access_hash'], '_' => 'inputPhoneCall'], 'g_a' => $this->calls[$params['id']]->storage['g_a'], 'protocol' => ['_' => 'phoneCallProtocol', 'udp_reflector' => true, 'min_layer' => 65, 'max_layer' => \danog\MadelineProto\VoIP::getConnectionMaxLayer()]], ['datacenter' => $this->datacenter->curdc]))['phone_call'];
2019-07-21 16:50:48 +02:00
} catch (\danog\MadelineProto\RPCErrorException $e) {
if ($e->rpc === 'CALL_ALREADY_ACCEPTED') {
2020-03-08 17:24:31 +01:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_already_accepted'], $params['id']));
2019-07-21 16:50:48 +02:00
return true;
}
if ($e->rpc === 'CALL_ALREADY_DECLINED') {
$this->logger->logger(\danog\MadelineProto\Lang::$current_lang['call_already_declined']);
2020-03-08 17:24:31 +01:00
yield from $this->discardCall($params['id'], ['_' => 'phoneCallDiscardReasonHangup']);
2019-07-21 16:50:48 +02:00
return false;
}
throw $e;
}
2020-03-28 17:10:35 +01:00
$this->calls[$params['id']]->setCall($res);
2017-07-20 16:20:19 +02:00
$visualization = [];
$length = new \tgseclib\Math\BigInteger(\count(\danog\MadelineProto\Magic::$emojis));
2020-03-01 16:31:56 +01:00
foreach (\str_split(\hash('sha256', $key.\str_pad($this->calls[$params['id']]->storage['g_a'], 256, \chr(0), \STR_PAD_LEFT), true), 8) as $number) {
2019-09-02 17:08:36 +02:00
$number[0] = \chr(\ord($number[0]) & 0x7f);
$visualization[] = \danog\MadelineProto\Magic::$emojis[(int) (new \tgseclib\Math\BigInteger($number, 256))->divide($length)[1]->toString()];
2017-07-19 12:41:18 +02:00
}
2017-07-20 16:20:19 +02:00
$this->calls[$params['id']]->setVisualization($visualization);
2019-09-02 17:08:36 +02:00
$this->calls[$params['id']]->configuration['endpoints'] = \array_merge($res['connections'], $this->calls[$params['id']]->configuration['endpoints']);
$this->calls[$params['id']]->configuration = \array_merge(['recv_timeout' => $this->config['call_receive_timeout_ms'] / 1000, 'init_timeout' => $this->config['call_connect_timeout_ms'] / 1000, 'data_saving' => \danog\MadelineProto\VoIP::DATA_SAVING_NEVER, 'enable_NS' => true, 'enable_AEC' => true, 'enable_AGC' => true, 'auth_key' => $key, 'auth_key_id' => \substr(\sha1($key, true), -8), 'call_id' => \substr(\hash('sha256', $key, true), -16), 'network_type' => \danog\MadelineProto\VoIP::NET_TYPE_ETHERNET], $this->calls[$params['id']]->configuration);
2017-07-19 12:41:18 +02:00
$this->calls[$params['id']]->parseConfig();
2017-07-31 20:57:13 +02:00
$res = $this->calls[$params['id']]->startTheMagic();
return $res;
2017-04-02 16:42:17 +02:00
}
/**
* Complete call handshake.
*
* @param array $params Params
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
public function completeCall(array $params): \Generator
2017-04-02 16:43:47 +02:00
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-19 12:41:18 +02:00
}
2019-10-29 21:33:23 +01:00
if ($this->callStatus($params['id']) !== \danog\MadelineProto\VoIP::CALL_STATE_ACCEPTED || !isset($this->calls[$params['id']]->storage['b'])) {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_error_3'], $params['id']));
return false;
}
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_completing'], $this->calls[$params['id']]->getOtherID()), \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2019-09-02 17:08:36 +02:00
if (\hash('sha256', $params['g_a_or_b'], true) != $this->calls[$params['id']]->storage['g_a_hash']) {
throw new \danog\MadelineProto\SecurityException(\danog\MadelineProto\Lang::$current_lang['invalid_g_a']);
2017-04-02 16:42:17 +02:00
}
$params['g_a_or_b'] = new \tgseclib\Math\BigInteger((string) $params['g_a_or_b'], 256);
2020-10-03 15:36:03 +02:00
Crypt::checkG($params['g_a_or_b'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = \str_pad($params['g_a_or_b']->powMod($this->calls[$params['id']]->storage['b'], $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT);
if (\substr(\sha1($key, true), -8) != $params['key_fingerprint']) {
throw new \danog\MadelineProto\SecurityException(\danog\MadelineProto\Lang::$current_lang['fingerprint_invalid']);
}
2017-07-20 16:20:19 +02:00
$visualization = [];
$length = new \tgseclib\Math\BigInteger(\count(\danog\MadelineProto\Magic::$emojis));
2020-03-01 16:31:56 +01:00
foreach (\str_split(\hash('sha256', $key.\str_pad($params['g_a_or_b']->toBytes(), 256, \chr(0), \STR_PAD_LEFT), true), 8) as $number) {
2019-09-02 17:08:36 +02:00
$number[0] = \chr(\ord($number[0]) & 0x7f);
$visualization[] = \danog\MadelineProto\Magic::$emojis[(int) (new \tgseclib\Math\BigInteger($number, 256))->divide($length)[1]->toString()];
2017-07-20 16:20:19 +02:00
}
$this->calls[$params['id']]->setVisualization($visualization);
2019-09-02 17:08:36 +02:00
$this->calls[$params['id']]->configuration['endpoints'] = \array_merge($params['connections'], $this->calls[$params['id']]->configuration['endpoints']);
$this->calls[$params['id']]->configuration = \array_merge(['recv_timeout' => $this->config['call_receive_timeout_ms'] / 1000, 'init_timeout' => $this->config['call_connect_timeout_ms'] / 1000, 'data_saving' => \danog\MadelineProto\VoIP::DATA_SAVING_NEVER, 'enable_NS' => true, 'enable_AEC' => true, 'enable_AGC' => true, 'auth_key' => $key, 'auth_key_id' => \substr(\sha1($key, true), -8), 'call_id' => \substr(\hash('sha256', $key, true), -16), 'network_type' => \danog\MadelineProto\VoIP::NET_TYPE_ETHERNET], $this->calls[$params['id']]->configuration);
2017-07-20 16:20:19 +02:00
$this->calls[$params['id']]->parseConfig();
2017-07-31 20:57:13 +02:00
return $this->calls[$params['id']]->startTheMagic();
}
/**
* Get call status.
*
2019-12-28 17:11:08 +01:00
* @param int $id Call ID
*
* @return integer
*/
public function callStatus($id): int
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-19 12:41:18 +02:00
}
if (isset($this->calls[$id])) {
2017-07-19 12:41:18 +02:00
return $this->calls[$id]->getCallState();
}
2017-07-20 19:31:09 +02:00
return \danog\MadelineProto\VoIP::CALL_STATE_NONE;
}
/**
* Get call info.
*
2019-12-28 17:11:08 +01:00
* @param int $call Call ID
*
* @return array
*/
public function getCall($call): array
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-19 12:41:18 +02:00
}
return $this->calls[$call];
}
/**
* Discard call.
*
* @param array $call Call
2020-10-01 21:36:07 +02:00
* @param array $reason
* @param array $rating Rating
* @param boolean $need_debug Need debug?
*
* @return \Generator
*/
2020-03-01 16:31:56 +01:00
public function discardCall(array $call, array $reason, array $rating = [], bool $need_debug = true): \Generator
{
2019-09-02 17:08:36 +02:00
if (!\class_exists('\\danog\\MadelineProto\\VoIP')) {
2019-06-26 17:16:06 +02:00
throw \danog\MadelineProto\Exception::extension('libtgvoip');
2017-07-20 16:20:19 +02:00
}
2017-07-22 01:02:48 +02:00
if (!isset($this->calls[$call['id']])) {
return;
}
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_discarding'], $call['id']), \danog\MadelineProto\Logger::VERBOSE);
2017-07-20 16:20:19 +02:00
try {
2020-02-05 17:37:01 +01:00
$res = yield from $this->methodCallAsyncRead('phone.discardCall', ['peer' => $call, 'duration' => \time() - $this->calls[$call['id']]->whenCreated(), 'connection_id' => $this->calls[$call['id']]->getPreferredRelayID(), 'reason' => $reason], ['datacenter' => $this->datacenter->curdc]);
2017-07-20 16:20:19 +02:00
} catch (\danog\MadelineProto\RPCErrorException $e) {
2019-09-02 17:08:36 +02:00
if (!\in_array($e->rpc, ['CALL_ALREADY_DECLINED', 'CALL_ALREADY_ACCEPTED'])) {
2017-07-20 16:20:19 +02:00
throw $e;
}
}
2017-07-20 16:20:19 +02:00
if (!empty($rating)) {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_set_rating'], $call['id']), \danog\MadelineProto\Logger::VERBOSE);
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('phone.setCallRating', ['peer' => $call, 'rating' => $rating['rating'], 'comment' => $rating['comment']], ['datacenter' => $this->datacenter->curdc]);
2017-07-20 16:20:19 +02:00
}
2019-05-10 13:34:44 +02:00
if ($need_debug && isset($this->calls[$call['id']])) {
2019-09-02 17:08:36 +02:00
$this->logger->logger(\sprintf(\danog\MadelineProto\Lang::$current_lang['call_debug_saving'], $call['id']), \danog\MadelineProto\Logger::VERBOSE);
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('phone.saveCallDebug', ['peer' => $call, 'debug' => $this->calls[$call['id']]->getDebugLog()], ['datacenter' => $this->datacenter->curdc]);
2017-07-20 16:20:19 +02:00
}
2017-07-21 12:23:09 +02:00
$update = ['_' => 'updatePhoneCall', 'phone_call' => $this->calls[$call['id']]];
$this->updates[$this->updates_key++] = $update;
2017-07-21 12:23:09 +02:00
unset($this->calls[$call['id']]);
}
/**
* Check state of calls.
*
2020-10-06 20:37:11 +02:00
* @internal
*
* @return void
*/
public function checkCalls(): void
{
2019-09-02 17:08:36 +02:00
\array_walk($this->calls, function ($controller, $id) {
2017-07-20 16:21:07 +02:00
if ($controller->getCallState() === \danog\MadelineProto\VoIP::CALL_STATE_ENDED) {
$controller->discard();
}
});
}
2018-02-24 17:54:39 +01:00
}