Check -404

This commit is contained in:
Ali 2019-11-15 16:47:30 +04:00
parent 29a7e6e0c8
commit 8ae455eb5e
9 changed files with 168 additions and 24 deletions

View File

@ -3,6 +3,7 @@
@class MTContext;
@class MTDatacenterAddress;
@class MTSignal;
@class MTDatacenterAuthKey;
typedef struct {
uint8_t nonce[16];
@ -14,4 +15,6 @@ typedef struct {
+ (MTSignal *)discoverSchemeWithContext:(MTContext *)context datacenterId:(NSInteger)datacenterId addressList:(NSArray *)addressList media:(bool)media isProxy:(bool)isProxy;
+ (MTSignal * _Nonnull)checkIfAuthKeyRemovedWithContext:(MTContext * _Nonnull)context datacenterId:(NSInteger)datacenterId authKey:(MTDatacenterAuthKey *)authKey;
@end

View File

@ -13,6 +13,7 @@
#import "MTContext.h"
#import "MTApiEnvironment.h"
#import "MTLogging.h"
#import "MTDatacenterAuthAction.h"
#import <netinet/in.h>
#import <arpa/inet.h>
@ -245,4 +246,25 @@
}];
}
+ (MTSignal * _Nonnull)checkIfAuthKeyRemovedWithContext:(MTContext * _Nonnull)context datacenterId:(NSInteger)datacenterId authKey:(MTDatacenterAuthKey *)authKey {
return [[MTSignal alloc] initWithGenerator:^id<MTDisposable>(MTSubscriber *subscriber) {
MTMetaDisposable *disposable = [[MTMetaDisposable alloc] init];
[[MTContext contextQueue] dispatchOnQueue:^{
MTDatacenterAuthAction *action = [[MTDatacenterAuthAction alloc] initWithTempAuth:true tempAuthKeyType:MTDatacenterAuthTempKeyTypeMain bindKey:authKey];
action.completedWithResult = ^(bool success) {
[subscriber putNext:@(!success)];
[subscriber putCompletion];
};
[action execute:context datacenterId:datacenterId isCdn:false];
[disposable setDisposable:[[MTBlockDisposable alloc] initWithBlock:^{
[action cancel];
}]];
}];
return disposable;
}];
}
@end

View File

@ -13,6 +13,7 @@
@class MTSessionInfo;
@class MTApiEnvironment;
@class MTSignal;
@class MTQueue;
@protocol MTContextChangeListener <NSObject>
@ -27,6 +28,7 @@
- (MTSignal *)fetchContextDatacenterPublicKeys:(MTContext *)context datacenterId:(NSInteger)datacenterId;
- (void)contextApiEnvironmentUpdated:(MTContext *)context apiEnvironment:(MTApiEnvironment *)apiEnvironment;
- (MTSignal *)isContextNetworkAccessAllowed:(MTContext *)context;
- (void)contextLoggedOut:(MTContext *)context;
@end
@ -51,6 +53,8 @@
+ (int32_t)fixedTimeDifference;
+ (void)setFixedTimeDifference:(int32_t)fixedTimeDifference;
+ (MTQueue *)contextQueue;
- (instancetype)initWithSerialization:(id<MTSerialization>)serialization encryptionProvider:(id<EncryptionProvider>)encryptionProvider apiEnvironment:(MTApiEnvironment *)apiEnvironment isTestingEnvironment:(bool)isTestingEnvironment useTempAuthKeys:(bool)useTempAuthKeys;
- (void)performBatchUpdates:(void (^)())block;
@ -113,4 +117,6 @@
- (void)beginExplicitBackupAddressDiscovery;
- (void)checkIfLoggedOut:(NSInteger)datacenterId;
@end

View File

@ -143,6 +143,9 @@
NSMutableDictionary *_datacenterTempAuthActions;
NSMutableDictionary *_datacenterTransferAuthActions;
NSMutableDictionary<NSNumber *, NSNumber *> *_datacenterCheckKeyRemovedActionTimestamps;
NSMutableDictionary<NSNumber *, id<MTDisposable> > *_datacenterCheckKeyRemovedActions;
NSMutableDictionary *_cleanupSessionIdsByAuthKeyId;
NSMutableArray *_currentSessionInfos;
@ -218,6 +221,8 @@ static int32_t fixedTimeDifferenceValue = 0;
_datacenterAuthActions = [[NSMutableDictionary alloc] init];
_datacenterTempAuthActions = [[NSMutableDictionary alloc] init];
_datacenterTransferAuthActions = [[NSMutableDictionary alloc] init];
_datacenterCheckKeyRemovedActionTimestamps = [[NSMutableDictionary alloc] init];
_datacenterCheckKeyRemovedActions = [[NSMutableDictionary alloc] init];
_cleanupSessionIdsByAuthKeyId = [[NSMutableDictionary alloc] init];
_currentSessionInfos = [[NSMutableArray alloc] init];
@ -263,6 +268,9 @@ static int32_t fixedTimeDifferenceValue = 0;
NSDictionary *datacenterTransferAuthActions = _datacenterTransferAuthActions;
_datacenterTransferAuthActions = nil;
NSDictionary *datacenterCheckKeyRemovedActions = _datacenterCheckKeyRemovedActions;
_datacenterCheckKeyRemovedActions = nil;
NSDictionary *fetchPublicKeysActions = _fetchPublicKeysActions;
_fetchPublicKeysActions = nil;
@ -304,6 +312,10 @@ static int32_t fixedTimeDifferenceValue = 0;
[disposable dispose];
}
for (NSNumber *nDatacenterId in datacenterCheckKeyRemovedActions) {
[datacenterCheckKeyRemovedActions[nDatacenterId] dispose];
}
[cleanupSessionInfoDisposables dispose];
}];
}
@ -1245,7 +1257,7 @@ static int32_t fixedTimeDifferenceValue = 0;
{
if (_datacenterAuthActions[@(datacenterId)] == nil)
{
MTDatacenterAuthAction *authAction = [[MTDatacenterAuthAction alloc] initWithTempAuth:false tempAuthKeyType:MTDatacenterAuthTempKeyTypeMain];
MTDatacenterAuthAction *authAction = [[MTDatacenterAuthAction alloc] initWithTempAuth:false tempAuthKeyType:MTDatacenterAuthTempKeyTypeMain bindKey:nil];
authAction.delegate = self;
_datacenterAuthActions[@(datacenterId)] = authAction;
[authAction execute:self datacenterId:datacenterId isCdn:isCdn];
@ -1256,7 +1268,7 @@ static int32_t fixedTimeDifferenceValue = 0;
- (void)tempAuthKeyForDatacenterWithIdRequired:(NSInteger)datacenterId keyType:(MTDatacenterAuthTempKeyType)keyType {
[[MTContext contextQueue] dispatchOnQueue:^{
if (_datacenterTempAuthActions[@(datacenterId)] == nil) {
MTDatacenterAuthAction *authAction = [[MTDatacenterAuthAction alloc] initWithTempAuth:true tempAuthKeyType:keyType];
MTDatacenterAuthAction *authAction = [[MTDatacenterAuthAction alloc] initWithTempAuth:true tempAuthKeyType:keyType bindKey:nil];
authAction.delegate = self;
_datacenterTempAuthActions[@(datacenterId)] = authAction;
[authAction execute:self datacenterId:datacenterId isCdn:false];
@ -1357,4 +1369,37 @@ static int32_t fixedTimeDifferenceValue = 0;
}];
}
- (void)checkIfLoggedOut:(NSInteger)datacenterId {
[[MTContext contextQueue] dispatchOnQueue:^{
MTDatacenterAuthInfo *authInfo = [self authInfoForDatacenterWithId:datacenterId];
if (authInfo == nil || authInfo.authKey == nil) {
return;
}
int32_t timestamp = (int32_t)CFAbsoluteTimeGetCurrent();
NSNumber *currentTimestamp = _datacenterCheckKeyRemovedActionTimestamps[@(datacenterId)];
if (currentTimestamp == nil || [currentTimestamp intValue] + 60 < timestamp) {
_datacenterCheckKeyRemovedActionTimestamps[@(datacenterId)] = currentTimestamp;
[_datacenterCheckKeyRemovedActions[@(datacenterId)] dispose];
__weak MTContext *weakSelf = self;
_datacenterCheckKeyRemovedActions[@(datacenterId)] = [[MTDiscoverConnectionSignals checkIfAuthKeyRemovedWithContext:self datacenterId:datacenterId authKey:authInfo.authKey] startWithNext:^(NSNumber *isRemoved) {
[[MTContext contextQueue] dispatchOnQueue:^{
__strong MTContext *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if ([isRemoved boolValue]) {
NSArray *currentListeners = [[NSArray alloc] initWithArray:strongSelf->_changeListeners];
for (id<MTContextChangeListener> listener in currentListeners) {
if ([listener respondsToSelector:@selector(contextLoggedOut:)])
[listener contextLoggedOut:self];
}
}
}];
}];
}
}];
}
@end

View File

@ -16,8 +16,9 @@
@property (nonatomic, readonly) bool tempAuth;
@property (nonatomic, weak) id<MTDatacenterAuthActionDelegate> delegate;
@property (nonatomic, copy) void (^completedWithResult)(bool);
- (instancetype)initWithTempAuth:(bool)tempAuth tempAuthKeyType:(MTDatacenterAuthTempKeyType)tempAuthKeyType;
- (instancetype)initWithTempAuth:(bool)tempAuth tempAuthKeyType:(MTDatacenterAuthTempKeyType)tempAuthKeyType bindKey:(MTDatacenterAuthKey *)bindKey;
- (void)execute:(MTContext *)context datacenterId:(NSInteger)datacenterId isCdn:(bool)isCdn;
- (void)cancel;

View File

@ -22,12 +22,14 @@
{
bool _isCdn;
MTDatacenterAuthTempKeyType _tempAuthKeyType;
MTDatacenterAuthKey *_bindKey;
NSInteger _datacenterId;
__weak MTContext *_context;
bool _awaitingAddresSetUpdate;
MTProto *_authMtProto;
MTProto *_bindMtProto;
MTMetaDisposable *_verifyDisposable;
}
@ -36,11 +38,12 @@
@implementation MTDatacenterAuthAction
- (instancetype)initWithTempAuth:(bool)tempAuth tempAuthKeyType:(MTDatacenterAuthTempKeyType)tempAuthKeyType {
- (instancetype)initWithTempAuth:(bool)tempAuth tempAuthKeyType:(MTDatacenterAuthTempKeyType)tempAuthKeyType bindKey:(MTDatacenterAuthKey *)bindKey {
self = [super init];
if (self != nil) {
_tempAuth = tempAuth;
_tempAuthKeyType = tempAuthKeyType;
_bindKey = bindKey;
_verifyDisposable = [[MTMetaDisposable alloc] init];
}
return self;
@ -61,7 +64,7 @@
{
bool alreadyCompleted = false;
MTDatacenterAuthInfo *currentAuthInfo = [context authInfoForDatacenterWithId:_datacenterId];
if (currentAuthInfo != nil) {
if (currentAuthInfo != nil && _bindKey == nil) {
if (_tempAuth) {
if ([currentAuthInfo tempAuthKeyWithType:_tempAuthKeyType] != nil) {
alreadyCompleted = true;
@ -108,15 +111,35 @@
if (_tempAuth) {
MTContext *mainContext = _context;
if (mainContext != nil) {
MTContext *context = _context;
[context performBatchUpdates:^{
MTDatacenterAuthInfo *authInfo = [context authInfoForDatacenterWithId:_datacenterId];
if (authInfo != nil) {
authInfo = [authInfo withUpdatedTempAuthKeyWithType:_tempAuthKeyType key:authKey];
[context updateAuthInfoForDatacenterWithId:_datacenterId authInfo:authInfo];
}
}];
[self complete];
if (_bindKey != nil) {
_bindMtProto = [[MTProto alloc] initWithContext:mainContext datacenterId:_datacenterId usageCalculationInfo:nil requiredAuthToken:nil authTokenMasterDatacenterId:0];
_bindMtProto.cdn = false;
_bindMtProto.useUnauthorizedMode = false;
_bindMtProto.useTempAuthKeys = true;
__weak MTDatacenterAuthAction *weakSelf = self;
_bindMtProto.tempAuthKeyBindingResultUpdated = ^(bool success) {
__strong MTDatacenterAuthAction *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
[strongSelf->_bindMtProto stop];
if (strongSelf->_completedWithResult) {
strongSelf->_completedWithResult(success);
}
};
_bindMtProto.useExplicitAuthKey = authKey;
[_bindMtProto resume];
} else {
MTContext *context = _context;
[context performBatchUpdates:^{
MTDatacenterAuthInfo *authInfo = [context authInfoForDatacenterWithId:_datacenterId];
if (authInfo != nil) {
authInfo = [authInfo withUpdatedTempAuthKeyWithType:_tempAuthKeyType key:authKey];
[context updateAuthInfoForDatacenterWithId:_datacenterId authInfo:authInfo];
}
}];
[self complete];
}
}
} else {
MTDatacenterAuthInfo *authInfo = [[MTDatacenterAuthInfo alloc] initWithAuthKey:authKey.authKey authKeyId:authKey.authKeyId saltSet:@[[[MTDatacenterSaltInfo alloc] initWithSalt:0 firstValidMessageId:timestamp lastValidMessageId:timestamp + (29.0 * 60.0) * 4294967296]] authKeyAttributes:nil mainTempAuthKey:nil mediaTempAuthKey:nil];

View File

@ -37,6 +37,9 @@
@property (nonatomic, strong, readonly) MTContext *context;
@property (nonatomic, strong, readonly) MTApiEnvironment *apiEnvironment;
@property (nonatomic) NSInteger datacenterId;
@property (nonatomic, strong) MTDatacenterAuthKey *useExplicitAuthKey;
@property (nonatomic, copy) void (^tempAuthKeyBindingResultUpdated)(bool);
@property (nonatomic) bool shouldStayConnected;
@property (nonatomic) bool useUnauthorizedMode;

View File

@ -174,6 +174,15 @@ static const NSUInteger MTMaxUnacknowledgedMessageCount = 64;
}];
}
- (void)setUseExplicitAuthKey:(MTDatacenterAuthKey *)useExplicitAuthKey {
_useExplicitAuthKey = useExplicitAuthKey;
if (_useExplicitAuthKey != nil) {
_authInfo = [_authInfo withUpdatedTempAuthKeyWithType:MTDatacenterAuthTempKeyTypeMain key:useExplicitAuthKey];
[self setMtState:_mtState | MTProtoStateBindingTempAuthKey];
[self requestTransportTransaction];
}
}
- (void)setUsageCalculationInfo:(MTNetworkUsageCalculationInfo *)usageCalculationInfo {
[[MTProto managerQueue] dispatchOnQueue:^{
_usageCalculationInfo = usageCalculationInfo;
@ -282,18 +291,17 @@ static const NSUInteger MTMaxUnacknowledgedMessageCount = 64;
[previousTransport stop];
if (_transport != nil && _useTempAuthKeys) {
assert(false);
/*MTDatacenterAuthTempKeyType tempAuthKeyType = MTDatacenterAuthTempKeyTypeMain;
if (_transport.scheme.address.preferForMedia) {
MTDatacenterAuthTempKeyType tempAuthKeyType = MTDatacenterAuthTempKeyTypeMain;
/*if (_transport.scheme.address.preferForMedia) {
tempAuthKeyType = MTDatacenterAuthTempKeyTypeMedia;
}
}*/
MTDatacenterAuthKey *effectiveAuthKey = [_authInfo tempAuthKeyWithType:tempAuthKeyType];
if (effectiveAuthKey == nil) {
if (MTLogEnabled()) {
MTLog(@"[MTProto#%p setTransport temp auth key missing]", self);
}
}*/
}
}
if (_transport != nil)
@ -2033,7 +2041,17 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
}
- (void)transportHasIncomingData:(MTTransport *)transport scheme:(MTTransportScheme *)scheme data:(NSData *)data transactionId:(id)transactionId requestTransactionAfterProcessing:(bool)requestTransactionAfterProcessing decodeResult:(void (^)(id transactionId, bool success))decodeResult
{
{
/*__block bool simulateError = false;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
simulateError = true;
});
if (simulateError) {
int32_t protocolErrorCode = -404;
data = [NSData dataWithBytes:&protocolErrorCode length:4];
}*/
[[MTProto managerQueue] dispatchOnQueue:^
{
if (_transport != transport || [self isStopped])
@ -2151,7 +2169,8 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
- (void)handleMissingKey:(MTDatacenterAddress *)address {
NSAssert([[MTProto managerQueue] isCurrentQueue], @"invalid queue");
if (_cdn) {
if (_useExplicitAuthKey != nil) {
} else if (_cdn) {
_authInfo = nil;
[_context performBatchUpdates:^{
[_context updateAuthInfoForDatacenterWithId:_datacenterId authInfo:nil];
@ -2193,6 +2212,8 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
[_context authInfoForDatacenterWithIdRequired:_datacenterId isCdn:false];
}];
_mtState |= MTProtoStateAwaitingDatacenterAuthorization;
} else {
[_context checkIfLoggedOut:_datacenterId];
}
}
}
@ -2666,7 +2687,12 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
NSMutableDictionary *authKeyAttributes = [[NSMutableDictionary alloc] initWithDictionary:_authInfo.authKeyAttributes];
[authKeyAttributes removeObjectForKey:@"apiInitializationHash"];
_authInfo = [_authInfo withUpdatedAuthKeyAttributes:authKeyAttributes];
[_context updateAuthInfoForDatacenterWithId:_datacenterId authInfo:_authInfo];
if (_useExplicitAuthKey == nil) {
[_context updateAuthInfoForDatacenterWithId:_datacenterId authInfo:_authInfo];
}
if (_tempAuthKeyBindingResultUpdated) {
_tempAuthKeyBindingResultUpdated(true);
}
}
_bindingTempAuthKeyId = 0;
if ((_mtState & MTProtoStateBindingTempAuthKey) != 0) {
@ -2680,6 +2706,10 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
MTShortLog(@"[MTProto#%p@%p bindTempAuthKey error %@]", self, _context, rpcError);
[self requestTransportTransaction];
if (_tempAuthKeyBindingResultUpdated) {
_tempAuthKeyBindingResultUpdated(false);
}
}
}
}
@ -2705,6 +2735,9 @@ static NSString *dumpHexString(NSData *data, int maxLength) {
if (!_useUnauthorizedMode && context == _context && datacenterId == _datacenterId)
{
_authInfo = authInfo;
if (_useExplicitAuthKey != nil) {
_authInfo = [_authInfo withUpdatedTempAuthKeyWithType:MTDatacenterAuthTempKeyTypeMain key:_useExplicitAuthKey];
}
bool wasSuspended = _mtState & (MTProtoStateAwaitingDatacenterAuthorization | MTProtoStateAwaitingDatacenterTempAuthKey);

View File

@ -586,13 +586,14 @@ func initializedNetwork(arguments: NetworkInitializationArguments, supplementary
private final class NetworkHelper: NSObject, MTContextChangeListener {
private let requestPublicKeys: (Int) -> Signal<NSArray, NoError>
private let isContextNetworkAccessAllowedImpl: () -> Signal<Bool, NoError>
private let contextProxyIdUpdated: (NetworkContextProxyId?) -> Void
private let contextLoggedOutUpdated: () -> Void
init(requestPublicKeys: @escaping (Int) -> Signal<NSArray, NoError>, isContextNetworkAccessAllowed: @escaping () -> Signal<Bool, NoError>, contextProxyIdUpdated: @escaping (NetworkContextProxyId?) -> Void) {
init(requestPublicKeys: @escaping (Int) -> Signal<NSArray, NoError>, isContextNetworkAccessAllowed: @escaping () -> Signal<Bool, NoError>, contextProxyIdUpdated: @escaping (NetworkContextProxyId?) -> Void, contextLoggedOutUpdated: @escaping () -> Void) {
self.requestPublicKeys = requestPublicKeys
self.isContextNetworkAccessAllowedImpl = isContextNetworkAccessAllowed
self.contextProxyIdUpdated = contextProxyIdUpdated
self.contextLoggedOutUpdated = contextLoggedOutUpdated
}
func fetchContextDatacenterPublicKeys(_ context: MTContext!, datacenterId: Int) -> MTSignal! {
@ -625,6 +626,10 @@ private final class NetworkHelper: NSObject, MTContextChangeListener {
let settings: MTSocksProxySettings? = apiEnvironment.socksProxySettings
self.contextProxyIdUpdated(settings.flatMap(NetworkContextProxyId.init(settings:)))
}
func contextLoggedOut(_ context: MTContext!) {
self.contextLoggedOutUpdated()
}
}
struct NetworkContextProxyId: Equatable {
@ -772,6 +777,9 @@ public final class Network: NSObject, MTRequestMessageServiceDelegate {
}
}, contextProxyIdUpdated: { value in
_contextProxyId.set(value)
}, contextLoggedOutUpdated: { [weak self] in
Logger.shared.log("Network", "contextLoggedOut")
self?.loggedOut?()
}))
requestService.delegate = self