forked from danog/MadelineProto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMTProto.php
2081 lines (2001 loc) · 69.6 KB
/
MTProto.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
133
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
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
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
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
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
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
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* MTProto 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 <[email protected]>
* @copyright 2016-2023 Daniil Gentili <[email protected]>
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
* @link https://docs.madelineproto.xyz MadelineProto documentation
*/
namespace danog\MadelineProto;
use Amp\ByteStream\ReadableBuffer;
use Amp\Cache\Cache;
use Amp\Cache\LocalCache;
use Amp\Cancellation;
use Amp\DeferredFuture;
use Amp\Dns\DnsResolver;
use Amp\Future;
use Amp\Future\UnhandledFutureError;
use Amp\Http\Client\HttpClient;
use Amp\Http\Client\Request;
use Amp\Http\HttpStatus;
use Amp\Http\Server\DefaultErrorHandler;
use Amp\Http\Server\Request as ServerRequest;
use Amp\Http\Server\RequestHandler;
use Amp\Http\Server\Response as ServerResponse;
use Amp\Http\Server\SocketHttpServer;
use Amp\SignalException;
use Amp\Sync\LocalKeyedMutex;
use Amp\Sync\LocalMutex;
use danog\AsyncOrm\Annotations\OrmMappedArray;
use danog\AsyncOrm\DbArray;
use danog\AsyncOrm\DbArrayBuilder;
use danog\AsyncOrm\Driver\MemoryArray;
use danog\AsyncOrm\KeyType;
use danog\AsyncOrm\Settings as OrmSettings;
use danog\AsyncOrm\ValueType;
use danog\BetterPrometheus\BetterCounter;
use danog\BetterPrometheus\BetterGauge;
use danog\BetterPrometheus\BetterHistogram;
use danog\BetterPrometheus\BetterSummary;
use danog\MadelineProto\Broadcast\Broadcast;
use danog\MadelineProto\EventHandler\Message;
use danog\MadelineProto\Ipc\Server;
use danog\MadelineProto\Loop\Generic\PeriodicLoopInternal;
use danog\MadelineProto\Loop\Update\FeedLoop;
use danog\MadelineProto\Loop\Update\SeqLoop;
use danog\MadelineProto\Loop\Update\UpdateLoop;
use danog\MadelineProto\MTProtoTools\AuthKeyHandler;
use danog\MadelineProto\MTProtoTools\CallHandler;
use danog\MadelineProto\MTProtoTools\CombinedUpdatesState;
use danog\MadelineProto\MTProtoTools\Files;
use danog\MadelineProto\MTProtoTools\MinDatabase;
use danog\MadelineProto\MTProtoTools\PasswordCalculator;
use danog\MadelineProto\MTProtoTools\PeerDatabase;
use danog\MadelineProto\MTProtoTools\PeerHandler;
use danog\MadelineProto\MTProtoTools\ReferenceDatabase;
use danog\MadelineProto\MTProtoTools\ResponseInfo;
use danog\MadelineProto\MTProtoTools\UpdateHandler;
use danog\MadelineProto\Settings\Database\DriverDatabaseAbstract;
use danog\MadelineProto\Settings\TLSchema;
use danog\MadelineProto\TL\Conversion\BotAPI;
use danog\MadelineProto\TL\Conversion\BotAPIFiles;
use danog\MadelineProto\TL\Conversion\TD;
use danog\MadelineProto\TL\TL;
use danog\MadelineProto\TL\TLCallback;
use danog\MadelineProto\TL\TLInterface;
use danog\MadelineProto\TL\Types\LoginQrCode;
use danog\MadelineProto\VoIP\CallState;
use danog\MadelineProto\Wrappers\Ads;
use danog\MadelineProto\Wrappers\Button;
use danog\MadelineProto\Wrappers\DialogHandler;
use danog\MadelineProto\Wrappers\Events;
use danog\MadelineProto\Wrappers\Login;
use danog\MadelineProto\Wrappers\Loop;
use danog\MadelineProto\Wrappers\Start;
use Prometheus\Counter;
use Prometheus\Gauge;
use Prometheus\Histogram;
use Prometheus\RendererInterface;
use Prometheus\RenderTextFormat;
use Prometheus\Summary;
use Psr\Log\LoggerInterface;
use Revolt\EventLoop;
use SplQueue;
use Throwable;
use Webmozart\Assert\Assert;
use function Amp\async;
use function Amp\ByteStream\pipe;
use function Amp\File\deleteFile;
use function Amp\File\getSize;
use function Amp\File\openFile;
use function Amp\Future\await;
use function time;
/**
* Manages all of the mtproto stuff.
*
* @psalm-suppress PropertyNotSetInConstructor
*
* @internal
*/
final class MTProto implements TLCallback, LoggerGetter, SettingsGetter
{
use AuthKeyHandler;
use CallHandler;
use PeerHandler;
use UpdateHandler;
use Files;
use \danog\MadelineProto\SecretChats\AuthKeyHandler;
use BotAPI;
use BotAPIFiles;
use TD;
use \danog\MadelineProto\VoIP\AuthKeyHandler;
use Ads;
use Button;
use DialogHandler;
use Events;
use Login;
use Loop;
use Start;
use LegacyMigrator {
LegacyMigrator::initDbProperties as private internalInitDbProperties;
LegacyMigrator::saveDbProperties as private internalSaveDbProperties;
}
use Broadcast;
private const MAX_ENTITY_LENGTH = 100;
private const MAX_ENTITY_SIZE = 8110;
/** @internal */
public const PFS_DURATION = 1*24*60*60;
/**
* Bad message error codes.
*
* @internal
* @var array
*/
public const BAD_MSG_ERROR_CODES = [16 => 'msg_id too low (most likely, client time is wrong; it would be worthwhile to synchronize it using msg_id notifications and re-send the original message with the correct msg_id or wrap it in a container with a new msg_id if the original message had waited too long on the client to be transmitted)', 17 => 'msg_id too high (similar to the previous case, the client time has to be synchronized, and the message re-sent with the correct msg_id)', 18 => 'incorrect two lower order msg_id bits (the server expects client message msg_id to be divisible by 4)', 19 => 'container msg_id is the same as msg_id of a previously received message (this must never happen)', 20 => 'message too old, and it cannot be verified whether the server has received a message with this msg_id or not', 32 => 'msg_seqno too low (the server has already received a message with a lower msg_id but with either a higher or an equal and odd seqno)', 33 => 'msg_seqno too high (similarly, there is a message with a higher msg_id but with either a lower or an equal and odd seqno)', 34 => 'an even msg_seqno expected (irrelevant message), but odd received', 35 => 'odd msg_seqno expected (relevant message), but even received', 48 => 'incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)', 64 => 'invalid container'];
/**
* Localized message info flags.
*
* @internal
* @var array
*/
public const MSGS_INFO_FLAGS = [1 => 'nothing is known about the message (msg_id too low, the other party may have forgotten it)', 2 => 'message not received (msg_id falls within the range of stored identifiers; however, the other party has certainly not received a message like that)', 3 => 'message not received (msg_id too high; however, the other party has certainly not received it yet)', 4 => 'message received (note that this response is also at the same time a receipt acknowledgment)', 8 => ' and message already acknowledged', 16 => ' and message not requiring acknowledgment', 32 => ' and RPC query contained in message being processed or processing already complete', 64 => ' and content-related response to message already generated', 128 => ' and other party knows for a fact that message is already received'];
/**
* @internal
*/
public const TD_PARAMS_CONVERSION = ['updateNewMessage' => ['_' => 'updateNewMessage', 'disable_notification' => ['message', 'silent'], 'message' => ['message']], 'message' => ['_' => 'message', 'id' => ['id'], 'sender_user_id' => ['from_id'], 'chat_id' => ['peer_id', 'choose_chat_id_from_botapi'], 'send_state' => ['choose_incoming_or_sent'], 'can_be_edited' => ['choose_can_edit'], 'can_be_deleted' => ['choose_can_delete'], 'is_post' => ['post'], 'date' => ['date'], 'edit_date' => ['edit_date'], 'forward_info' => ['fwd_info', 'choose_forward_info'], 'reply_to_message_id' => ['reply_to_msg_id'], 'ttl' => ['choose_ttl'], 'ttl_expires_in' => ['choose_ttl_expires_in'], 'via_bot_user_id' => ['via_bot_id'], 'views' => ['views'], 'content' => ['choose_message_content'], 'reply_markup' => ['reply_markup']], 'messages.sendMessage' => ['chat_id' => ['peer'], 'reply_to_message_id' => ['reply_to_msg_id'], 'disable_notification' => ['silent'], 'from_background' => ['background'], 'input_message_content' => ['choose_message_content'], 'reply_markup' => ['reply_markup']]];
/**
* @internal
*/
public const TD_REVERSE = ['sendMessage' => 'messages.sendMessage'];
/**
* @internal
*/
public const TD_IGNORE = ['updateMessageID'];
/**
* @internal
*/
public const BOTAPI_PARAMS_CONVERSION = ['disable_web_page_preview' => 'no_webpage', 'disable_notification' => 'silent', 'reply_to_message_id' => 'reply_to_msg_id', 'chat_id' => 'peer', 'text' => 'message'];
/**
* Array of references to all instances of MTProto.
*
* This seems like a recipe for memory leaks, but this is actually required to allow saving the session on shutdown.
* When using a network I/O-based database+the EvDriver of AMPHP, calling die(); causes premature garbage collection of the event loop.
* This garbage collection happens always, even if a reference to the event handler is already present elsewhere (probably ev dark magic).
*
* Finally, this causes the process to hang on shutdown, since the database driver cannot receive a reply from the server, because the event loop is down.
*
* To avoid this, we store each MTProto instance in here (unreferencing on shutdown in unreference()), and call serialize() on all instances before calling die; in Magic.
*
* @var array<self>
*/
public static array $references = [];
/**
* Instance of wrapper API.
*
*/
public APIWrapper $wrapper;
/**
* Settings object.
*
*/
public Settings $settings;
/**
* Config array.
*
*/
private array $config = ['expires' => -1];
/**
* Authorization info (User).
*
*/
public ?array $authorization = null;
/**
* Whether we're authorized.
*
* @var API::NOT_LOGGED_IN|API::WAITING_*|API::LOGGED_IN|API::LOGGED_OUT
*/
public int $authorized = API::NOT_LOGGED_IN;
/**
* Main authorized DC ID.
*/
public ?int $authorized_dc = null;
/**
* RSA keys.
*
* @var array<RSA>
*/
private array $rsa_keys = [];
/**
* RSA keys.
*
* @var array<RSA>
*/
private array $test_rsa_keys = [];
/**
* CDN RSA keys.
*
*/
private array $cdn_rsa_keys = [];
/**
* Diffie-hellman config.
*
*/
private array $dh_config = ['version' => 0];
/**
* Cached parameters for fetching channel participants.
*
* @var DbArray<string, array>
*/
#[OrmMappedArray(KeyType::STRING, ValueType::SCALAR)]
public $channelParticipants;
/**
* When we last stored data in remote peer database (now doesn't exist anymore).
*
*/
public int $last_stored = 0;
/**
* Temporary array of data to be sent to remote peer database.
*
*/
public array $qres = [];
/**
* Sponsored message database.
*
* @var DbArray<int, array>
*/
#[OrmMappedArray(KeyType::INT, ValueType::SCALAR)]
public $sponsoredMessages;
/**
* Latest chat message ID map for update handling.
*
*/
private array $msg_ids = [];
/**
* Version value for upgrades.
*
*/
private string|int $v = 0;
/**
* Cached getdialogs params.
*
*/
private array $dialog_params = ['limit' => 0, 'offset_date' => 0, 'offset_id' => 0, 'offset_peer' => ['_' => 'inputPeerEmpty'], 'count' => 0];
/**
* Support user ID.
*
*/
private int $supportUser = 0;
/**
* File reference database.
*
*/
public ?ReferenceDatabase $referenceDatabase = null;
/**
* Min database.
*
*/
public MinDatabase $minDatabase;
/**
* Peer database.
*
*/
public PeerDatabase $peerDatabase;
/**
* Phone config loop.
*/
public ?PeriodicLoopInternal $phoneConfigLoop = null;
/**
* Config loop.
*/
public ?PeriodicLoopInternal $configLoop = null;
/**
* Autoserialization loop.
*/
private ?PeriodicLoopInternal $serializeLoop = null;
/**
* SEQ update loop.
*/
private ?SeqLoop $seqUpdater = null;
/**
* IPC server.
*/
private ?Server $ipcServer = null;
private ?LoginQrCode $loginQrCode = null;
/**
* Feeder loops.
*
* @var array<FeedLoop>
*/
public array $feeders = [];
/**
* Updater loops.
*
* @var array<UpdateLoop>
*/
public array $updaters = [];
/**
* DataCenter instance.
*
*/
public DataCenter $datacenter;
/**
* Logger instance.
*
*/
public Logger $logger;
/**
* TL serializer.
*/
private TL $TL;
private Cache $reportCache;
/**
* Snitch.
*/
private Snitch $snitch;
/**
* DC list.
*/
public array $dcList = [
'test' => [
// Test datacenters
'ipv4' => [
// ipv4 addresses
10002 => [
// The rest will be fetched using help.getConfig
'ip_address' => '149.154.167.40',
'port' => 443,
'media_only' => false,
'tcpo_only' => false,
],
],
'ipv6' => [
// ipv6 addresses
10002 => [
// The rest will be fetched using help.getConfig
'ip_address' => '2001:067c:04e8:f002:0000:0000:0000:000e',
'port' => 443,
'media_only' => false,
'tcpo_only' => false,
],
],
],
'main' => [
// Main datacenters
'ipv4' => [
// ipv4 addresses
2 => [
// The rest will be fetched using help.getConfig
'ip_address' => '149.154.167.51',
'port' => 443,
'media_only' => false,
'tcpo_only' => false,
],
],
'ipv6' => [
// ipv6 addresses
2 => [
// The rest will be fetched using help.getConfig
'ip_address' => '2001:067c:04e8:f002:0000:0000:0000:000a',
'port' => 443,
'media_only' => false,
'tcpo_only' => false,
],
],
],
];
/**
* Nullcache array for storing main session file to DB.
*/
#[OrmMappedArray(KeyType::STRING, ValueType::SCALAR, cacheTtl: 0, optimizeIfWastedMb: 1, tablePostfix: 'session')]
public DbArray $sessionDb;
/**
* Returns an instance of a client by session name.
*
* @internal
*/
public static function giveInstanceBySession(string $session): MTProto
{
return self::$references[$session];
}
/**
* Serialize session, returning object to serialize to db.
*
* @internal
*/
public function serializeSession(object $data)
{
// Force migration
$this->getDbAutoProperties();
/** @psalm-suppress TypeDoesNotContainType */
if (!isset($this->sessionDb) || $this->sessionDb instanceof MemoryArray) {
return $data;
}
$this->sessionDb['data'] = $data;
$db = [];
$db []= async($this->referenceDatabase->saveDbProperties(...));
$db []= async($this->minDatabase->saveDbProperties(...));
$db []= async($this->peerDatabase->saveDbProperties(...));
$db []= async($this->internalSaveDbProperties(...));
if (isset($this->event_handler_instance)) {
$db []= async($this->event_handler_instance->internalSaveDbProperties(...));
}
await($db);
return new DbArrayBuilder(
$this->getDbPrefix().'_MTProto_session',
$this->getDbSettings(),
KeyType::STRING,
ValueType::SCALAR
);
}
/**
* @internal
* @return array<RSA>
*/
public function getRsaKeys(bool $test, bool $cdn): array
{
if ($cdn) {
return $this->cdn_rsa_keys;
}
if ($test) {
return $this->test_rsa_keys;
}
return $this->rsa_keys;
}
/**
* Serialize all instances.
*
* CALLED ONLY ON SHUTDOWN.
*
* @internal
*/
public static function serializeAll(): void
{
static $done = false;
if ($done) {
return;
}
$done = true;
if (self::$references) {
Logger::log('Prompting final serialization (SHUTDOWN)...');
foreach (self::$references as $instance) {
if ($instance->authorized === API::LOGGED_OUT) {
continue;
}
$instance->wrapper->serialize();
}
Logger::log('Done final serialization (SHUTDOWN)!');
}
}
private ?Future $initPromise = null;
/**
* Constructor function.
*
* @param Settings|SettingsEmpty $settings Settings
* @param null|APIWrapper $wrapper API wrapper
*/
public function __construct(Settings|SettingsEmpty $settings, ?APIWrapper $wrapper = null)
{
if ($wrapper) {
$this->wrapper = $wrapper;
self::$references[$this->getSessionName()] = $this;
}
$q = new SplQueue;
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$this->updateQueue ??= $q;
$initDeferred = new DeferredFuture;
$this->initPromise = $initDeferred->getFuture();
try {
$this->initialize($settings);
} catch (Throwable $e) {
try {
$this->report((string) $e);
} catch (Throwable) {
}
throw $e;
} finally {
$initDeferred->complete();
}
}
/**
* Renders prometheus stats using the specified renderer.
*
* By default uses the text renderer.
*/
public function renderPromStats(?RendererInterface $renderer = null): string
{
return ($renderer ?? new RenderTextFormat)->render(
GarbageCollector::$prometheus->storageAdapter->collect()
);
}
/**
* Creates and returns a prometheus gauge.
*
* Returns null if prometheus stats are disabled.
*
* @param array<string, string> $labels
*/
public function getPromGauge(string $namespace, string $name, string $help, array $labels = []): ?BetterGauge
{
if (!$this->getSettings()->getMetrics()->getEnablePrometheusCollection()) {
return null;
}
return GarbageCollector::$prometheus->getOrRegisterGauge(
$namespace,
$name,
$help,
$labels + ['session' => $this->getSessionName(), 'session_id' => (string) ($this->getSelf()['id'] ?? '')],
);
}
/**
* Creates and returns a prometheus counter.
*
* Returns null if prometheus stats are disabled.
*
* @param array<string, string> $labels
*/
public function getPromCounter(string $namespace, string $name, string $help, array $labels = []): ?BetterCounter
{
if (!$this->getSettings()->getMetrics()->getEnablePrometheusCollection()) {
return null;
}
return GarbageCollector::$prometheus->getOrRegisterCounter(
$namespace,
$name,
$help,
$labels + ['session' => $this->getSessionName(), 'session_id' => (string) ($this->getSelf()['id'] ?? '')],
);
}
/**
* Creates and returns a prometheus summary.
*
* Returns null if prometheus stats are disabled.
*
* @param array<string, string> $labels
* @param ?non-empty-list<float> $quantiles
*/
public function getPromSummary(string $namespace, string $name, string $help, array $labels = [], int $maxAgeSeconds = 600, ?array $quantiles = null): ?BetterSummary
{
if (!$this->getSettings()->getMetrics()->getEnablePrometheusCollection()) {
return null;
}
return GarbageCollector::$prometheus->getOrRegisterSummary(
$namespace,
$name,
$help,
$labels + ['session' => $this->getSessionName(), 'session_id' => (string) ($this->getSelf()['id'] ?? '')],
$maxAgeSeconds,
$quantiles
);
}
/**
* Creates and returns a prometheus histogram.
*
* Returns null if prometheus stats are disabled.
*
* @param array<string, string> $labels
* @param ?non-empty-list<float> $buckets
*/
public function getPromHistogram(string $namespace, string $name, string $help, array $labels = [], ?array $buckets = null): ?BetterHistogram
{
if (!$this->getSettings()->getMetrics()->getEnablePrometheusCollection()) {
return null;
}
return GarbageCollector::$prometheus->getOrRegisterHistogram(
$namespace,
$name,
$help,
$labels + ['session' => $this->getSessionName(), 'session_id' => (string) ($this->getSelf()['id'] ?? '')],
$buckets
);
}
/**
* Initialization function.
*
* @internal
*/
private function initialize(Settings|SettingsEmpty $settings): void
{
// Initialize needed stuffs
Magic::start(light: false);
// Parse and store settings
$this->updateSettingsInternal($settings, false);
// Actually instantiate needed classes like a boss
$this->cleanupProperties();
// Load rsa keys
$this->rsa_keys = [];
foreach ($this->settings->getConnection()->getRSAKeys() as $key) {
$key = RSA::load($this->TL, $key);
$this->rsa_keys[$key->fp] = $key;
}
$this->test_rsa_keys = [];
foreach ($this->settings->getConnection()->getTestRSAKeys() as $key) {
$key = RSA::load($this->TL, $key);
$this->test_rsa_keys[$key->fp] = $key;
}
// (re)-initialize TL
$callbacks = [$this, $this->peerDatabase];
if ($this->settings->getDb()->getEnableFileReferenceDb()) {
$callbacks []= $this->referenceDatabase;
}
if (!($this->authorization['user']['bot'] ?? false) && $this->settings->getDb()->getEnableMinDb()) {
$callbacks[] = $this->minDatabase;
}
$this->TL->init($this->settings->getSchema(), $callbacks);
$this->startLoops();
$this->datacenter->currentDatacenter = $this->settings->getConnection()->getTestMode() ? 10002 : 2;
$this->getConfig();
$this->startUpdateSystem(true);
$this->v = API::RELEASE;
$this->settings->applyChanges();
}
/**
* Get API wrapper.
*
* @internal
*/
public function getWrapper(): APIWrapper
{
return $this->wrapper;
}
/**
* Returns the session name.
*/
public function getSessionName(): string
{
return $this->wrapper->getSession()->getSessionDirectoryPath();
}
private ?string $tmpDbPrefix = null;
/** @internal */
public function getDbPrefix(): string
{
$prefix = null;
if ($this->settings->getDb() instanceof DriverDatabaseAbstract) {
$prefix = $this->settings->getDb()->getEphemeralFilesystemPrefix();
}
$prefix ??= $this->getSelf()['id'] ?? null;
if ($prefix === null) {
$this->tmpDbPrefix ??= 'tmp_'.hash('xxh3', $this->getSessionName());
$prefix = $this->tmpDbPrefix;
}
return (string) $prefix;
}
/** @internal */
public function getDbSettings(): OrmSettings
{
return $this->settings->getDb()->getOrmSettings();
}
/**
* Sleep function.
*
* @internal
*/
public function __sleep(): array
{
return [
// Databases
'referenceDatabase',
'minDatabase',
'peerDatabase',
'channelParticipants',
'sponsoredMessages',
'tmpDbPrefix',
// Misc caching
'searchingRightPts',
'bottomPts',
'topPts',
'botDialogsUpdatesState',
'cachedAllBotUsers',
'dialog_params',
'last_stored',
'qres',
'supportUser',
'broadcasts',
'broadcastId',
'loginQrCode',
'fetchedFullDialogs',
// Event handler
'event_handler',
'event_handler_instance',
'pluginInstances',
'updateQueue',
'getUpdatesQueue',
'getUpdatesQueueKey',
'webhookUrl',
'updateHandlerType',
// Settings
'settings',
'config',
'dcList',
// Authorization keys
'datacenter',
// Authorization state
'authorization',
'authorized',
'authorized_dc',
// Authorization cache
'rsa_keys',
'test_rsa_keys',
'dh_config',
// Update state
'got_state',
'updateState',
'msg_ids',
// Version
'v',
// TL
'TL',
// Secret chats
'secretChats',
'temp_requested_secret_chats',
// Report URI
'reportDest',
'calls',
'callsByPeer',
'snitch',
'seqUpdater',
'updaters',
'feeders',
];
}
/**
* Logger.
*
* @param mixed $param Parameter
* @param int $level Logging level
* @param string $file File where the message originated
*/
public function logger(mixed $param, int $level = Logger::NOTICE, string $file = ''): void
{
if (empty($file)) {
$file = basename(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['file'], '.php');
}
($this->logger ?? Logger::$default)?->logger($param, $level, $file);
}
/**
* Get TL namespaces.
*/
public function getMethodNamespaces(): array
{
return $this->TL->getMethodNamespaces();
}
/**
* Get namespaced methods (method => namespace).
*/
public function getMethodsNamespaced(): array
{
return $this->TL->getMethodsNamespaced();
}
/**
* Get TL serializer.
*/
public function getTL(): TLInterface
{
return $this->TL;
}
/**
* Get logger.
*/
public function getLogger(): Logger
{
return $this->logger;
}
/**
* Get PSR logger.
*/
public function getPsrLogger(): LoggerInterface
{
return $this->logger->getPsrLogger();
}
/**
* Get async HTTP client.
*/
public function getHTTPClient(): HttpClient
{
return $this->datacenter->getHTTPClient();
}
/**
* Get async DNS client.
*/
public function getDNSClient(): DnsResolver
{
return $this->datacenter->getDNSClient();
}
/**
* Get contents of remote file asynchronously.
*
* @param string $url URL
*/
public function fileGetContents(string $url, ?Cancellation $cancellation = null): string
{
return $this->getHTTPClient()->request(new Request($url), $cancellation)->getBody()->buffer($cancellation);
}
/**
* Get main DC ID.
*
* @internal
*/
public function getDataCenterId(): int|string
{
return $this->datacenter->currentDatacenter;
}
/**
* Prompt serialization of instance.
*
* @internal
*/
public function serialize(): void
{
if (isset($this->wrapper) && $this->isInited()) {
$this->wrapper->serialize();
}
}
/**
* Start all internal loops.
*/
private function startLoops(): void
{
$this->serializeLoop ??= new PeriodicLoopInternal($this, $this->serialize(...), 'serialize', $this->settings->getSerialization()->getInterval());
$this->phoneConfigLoop ??= new PeriodicLoopInternal($this, $this->getPhoneConfig(...), 'phone config', 3600);
$this->configLoop ??= new PeriodicLoopInternal($this, $this->getConfig(...), 'config', 3600);
$this->serializeLoop->start();
$this->phoneConfigLoop->start();
$this->configLoop->start();
try {
$this->ipcServer->start();
} catch (Throwable $e) {
if (Magic::$isIpcWorker) {
throw $e;
}
$this->logger->logger("Error while starting IPC server: $e", Logger::FATAL_ERROR);
}
}
/**
* Stop all internal loops.
*/
private function stopLoops(): void
{
if ($this->serializeLoop) {
$this->serializeLoop->stop();
$this->serializeLoop = null;
}
if ($this->phoneConfigLoop) {
$this->phoneConfigLoop->stop();
$this->phoneConfigLoop = null;
}
if ($this->configLoop) {
$this->configLoop->stop();
$this->configLoop = null;
}
if ($this->ipcServer) {
$this->ipcServer->stop();
$this->ipcServer = null;
}
}
private ?SocketHttpServer $promServer = null;
/**
* Clean up properties from previous versions of MadelineProto.
*
* @internal
*/
private function cleanupProperties(): void
{
if ($this->getSettings()->getMetrics()->getEnableMemprofCollection()) {
if (!\extension_loaded('memprof')) {
throw Exception::extension('memprof');
}
if (!memprof_enabled()) {
throw new Exception("Memory profiling is not enabled, set the MEMPROF_PROFILE=1 environment variable or GET parameter to enable it.");
}
}
$info = $this->getPromGauge("MadelineProto", "version", "Info about the MadelineProto instance");
$info?->set(1, [
'php_version' => PHP_VERSION,
'madeline_version' => API::RELEASE,
]);
$endpoint = $this->getSettings()->getMetrics()->getMetricsBindTo();
$this->promServer?->stop();
if ($endpoint === null) {
$this->promServer = null;
} else {
/** @psalm-suppress ImpureMethodCall */
$this->promServer = SocketHttpServer::createForDirectAccess(
$this->getPsrLogger()
);
$this->promServer->expose($endpoint);
$this->promServer->start(new class($this) implements RequestHandler {
public function __construct(
private readonly MTProto $API
) {
}
public function handleRequest(ServerRequest $request): ServerResponse
{
if ($request->getUri()->getPath() === '/metrics') {
return new ServerResponse(
status: HttpStatus::OK,
headers: ['Content-Type' => 'text/plain'],
body: $this->API->renderPromStats(),
);
}
if ($request->getUri()->getPath() === '/debug/pprof'
&& $this->API->getSettings()->getMetrics()->getEnableMemprofCollection()
) {
return new ServerResponse(
status: HttpStatus::OK,
headers: ['Content-Type' => 'text/plain'],
body: $this->API->getMemoryProfile(),
);
}
$result = ResponseInfo::error(HttpStatus::NOT_FOUND);
return new ServerResponse(
$result->getCode(),
$result->getHeaders(),
$result->getCodeExplanation()
);
}
}, new DefaultErrorHandler);
}
$this->updateCtr = $this->getPromCounter("MadelineProto", "update_count", "Number of received updates since the session was created");
// Start IPC server
if (!$this->ipcServer) {
$this->ipcServer = new Server($this);
$this->ipcServer->setIpcPath($this->wrapper->getSession());
}
$this->ipcServer->start();
if (!isset($this->updateQueue)) {