diff --git a/telethon/errors/__init__.py b/telethon/errors/__init__.py index ca07f6c0..7bb56af8 100644 --- a/telethon/errors/__init__.py +++ b/telethon/errors/__init__.py @@ -3,7 +3,7 @@ import re from .common import ( ReadCancelledError, InvalidParameterError, TypeNotFoundError, - InvalidChecksumError, CdnFileTamperedError + InvalidChecksumError, BrokenAuthKeyError, CdnFileTamperedError ) from .rpc_errors import ( diff --git a/telethon/errors/common.py b/telethon/errors/common.py index fc0a8e5f..49742da4 100644 --- a/telethon/errors/common.py +++ b/telethon/errors/common.py @@ -38,6 +38,14 @@ class InvalidChecksumError(Exception): self.valid_checksum = valid_checksum +class BrokenAuthKeyError(Exception): + def __init__(self): + super().__init__( + self, + 'The authorization key is broken, and it must be reset.' + ) + + class CdnFileTamperedError(Exception): def __init__(self): super().__init__( diff --git a/telethon/network/mtproto_plain_sender.py b/telethon/network/mtproto_plain_sender.py index 77600abd..5ced50a9 100644 --- a/telethon/network/mtproto_plain_sender.py +++ b/telethon/network/mtproto_plain_sender.py @@ -1,5 +1,6 @@ import time +from ..errors import BrokenAuthKeyError from ..extensions import BinaryReader, BinaryWriter @@ -36,6 +37,10 @@ class MtProtoPlainSender: def receive(self): """Receives a plain packet, returning the body of the response""" body = self._connection.recv() + if body == b'l\xfe\xff\xff': # -404 little endian signed + # Broken authorization, must reset the auth key + raise BrokenAuthKeyError() + with BinaryReader(body) as reader: reader.read_long() # auth_key_id reader.read_long() # msg_id diff --git a/telethon/telegram_bare_client.py b/telethon/telegram_bare_client.py index 0990fa27..f4ecf490 100644 --- a/telethon/telegram_bare_client.py +++ b/telethon/telegram_bare_client.py @@ -7,13 +7,14 @@ from os import path from . import helpers as utils from .crypto import rsa, CdnDecrypter from .errors import ( - RPCError, FloodWaitError, FileMigrateError, TypeNotFoundError + RPCError, BrokenAuthKeyError, + FloodWaitError, FileMigrateError, TypeNotFoundError ) from .network import authenticator, MtProtoSender, Connection, ConnectionMode from .tl import TLObject, Session from .tl.all_tlobjects import LAYER from .tl.functions import ( - InitConnectionRequest, InvokeWithLayerRequest, PingRequest + InitConnectionRequest, InvokeWithLayerRequest ) from .tl.functions.auth import ( ImportAuthorizationRequest, ExportAuthorizationRequest @@ -115,8 +116,11 @@ class TelegramBareClient: if not self.session.auth_key: # New key, we need to tell the server we're going to use # the latest layer - self.session.auth_key, self.session.time_offset = \ - authenticator.do_authentication(connection) + try: + self.session.auth_key, self.session.time_offset = \ + authenticator.do_authentication(connection) + except BrokenAuthKeyError: + return False self.session.layer = LAYER self.session.save()