You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

528 lines
19 KiB

6 years ago
6 years ago
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRMessagingDataMessageManager.h"
  17. #import "Protos/GtalkCore.pbobjc.h"
  18. #import "FIRMessagingClient.h"
  19. #import "FIRMessagingConnection.h"
  20. #import "FIRMessagingConstants.h"
  21. #import "FIRMessagingDefines.h"
  22. #import "FIRMessagingDelayedMessageQueue.h"
  23. #import "FIRMessagingLogger.h"
  24. #import "FIRMessagingReceiver.h"
  25. #import "FIRMessagingRmqManager.h"
  26. #import "FIRMessaging_Private.h"
  27. #import "FIRMessagingSyncMessageManager.h"
  28. #import "FIRMessagingUtilities.h"
  29. #import "NSError+FIRMessaging.h"
  30. static const int kMaxAppDataSizeDefault = 4 * 1024; // 4k
  31. static const int kMinDelaySeconds = 1; // 1 second
  32. static const int kMaxDelaySeconds = 60 * 60; // 1 hour
  33. static NSString *const kFromForFIRMessagingMessages = @"mcs.android.com";
  34. static NSString *const kGSFMessageCategory = @"com.google.android.gsf.gtalkservice";
  35. // TODO: Update Gcm to FIRMessaging in the constants below
  36. static NSString *const kFCMMessageCategory = @"com.google.gcm";
  37. static NSString *const kMessageReservedPrefix = @"google.";
  38. static NSString *const kFCMMessageSpecialMessage = @"message_type";
  39. // special messages sent by the server
  40. static NSString *const kFCMMessageTypeDeletedMessages = @"deleted_messages";
  41. static NSString *const kMCSNotificationPrefix = @"gcm.notification.";
  42. static NSString *const kDataMessageNotificationKey = @"notification";
  43. typedef NS_ENUM(int8_t, UpstreamForceReconnect) {
  44. // Never force reconnect on upstream messages
  45. kUpstreamForceReconnectOff = 0,
  46. // Force reconnect for TTL=0 upstream messages
  47. kUpstreamForceReconnectTTL0 = 1,
  48. // Force reconnect for all upstream messages
  49. kUpstreamForceReconnectAll = 2,
  50. };
  51. @interface FIRMessagingDataMessageManager ()
  52. @property(nonatomic, readwrite, weak) FIRMessagingClient *client;
  53. @property(nonatomic, readwrite, weak) FIRMessagingRmqManager *rmq2Manager;
  54. @property(nonatomic, readwrite, weak) FIRMessagingSyncMessageManager *syncMessageManager;
  55. @property(nonatomic, readwrite, weak) id<FIRMessagingDataMessageManagerDelegate> delegate;
  56. @property(nonatomic, readwrite, strong) FIRMessagingDelayedMessageQueue *delayedMessagesQueue;
  57. @property(nonatomic, readwrite, assign) int ttl;
  58. @property(nonatomic, readwrite, copy) NSString *deviceAuthID;
  59. @property(nonatomic, readwrite, copy) NSString *secretToken;
  60. @property(nonatomic, readwrite, assign) int maxAppDataSize;
  61. @property(nonatomic, readwrite, assign) UpstreamForceReconnect upstreamForceReconnect;
  62. @end
  63. @implementation FIRMessagingDataMessageManager
  64. - (instancetype)initWithDelegate:(id<FIRMessagingDataMessageManagerDelegate>)delegate
  65. client:(FIRMessagingClient *)client
  66. rmq2Manager:(FIRMessagingRmqManager *)rmq2Manager
  67. syncMessageManager:(FIRMessagingSyncMessageManager *)syncMessageManager {
  68. self = [super init];
  69. if (self) {
  70. _delegate = delegate;
  71. _client = client;
  72. _rmq2Manager = rmq2Manager;
  73. _syncMessageManager = syncMessageManager;
  74. _ttl = kFIRMessagingSendTtlDefault;
  75. _maxAppDataSize = kMaxAppDataSizeDefault;
  76. // on by default
  77. _upstreamForceReconnect = kUpstreamForceReconnectAll;
  78. }
  79. return self;
  80. }
  81. - (void)setDeviceAuthID:(NSString *)deviceAuthID secretToken:(NSString *)secretToken {
  82. _FIRMessagingDevAssert([deviceAuthID length] && [secretToken length],
  83. @"Invalid credentials for FIRMessaging");
  84. self.deviceAuthID = deviceAuthID;
  85. self.secretToken = secretToken;
  86. }
  87. - (void)refreshDelayedMessages {
  88. FIRMessaging_WEAKIFY(self);
  89. self.delayedMessagesQueue =
  90. [[FIRMessagingDelayedMessageQueue alloc] initWithRmqScanner:self.rmq2Manager
  91. sendDelayedMessagesHandler:^(NSArray *messages) {
  92. FIRMessaging_STRONGIFY(self);
  93. [self sendDelayedMessages:messages];
  94. }];
  95. }
  96. - (nullable NSDictionary *)processPacket:(GtalkDataMessageStanza *)dataMessage {
  97. NSString *category = dataMessage.category;
  98. NSString *from = dataMessage.from;
  99. if ([kFCMMessageCategory isEqualToString:category] ||
  100. [kGSFMessageCategory isEqualToString:category]) {
  101. [self handleMCSDataMessage:dataMessage];
  102. return nil;
  103. } else if ([kFromForFIRMessagingMessages isEqualToString:from]) {
  104. [self handleMCSDataMessage:dataMessage];
  105. return nil;
  106. }
  107. return [self parseDataMessage:dataMessage];
  108. }
  109. - (void)handleMCSDataMessage:(GtalkDataMessageStanza *)dataMessage {
  110. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager000,
  111. @"Received message for FIRMessaging from downstream %@", dataMessage);
  112. }
  113. - (NSDictionary *)parseDataMessage:(GtalkDataMessageStanza *)dataMessage {
  114. NSMutableDictionary *message = [NSMutableDictionary dictionary];
  115. NSString *from = [dataMessage from];
  116. if ([from length]) {
  117. message[kFIRMessagingFromKey] = from;
  118. }
  119. // raw data
  120. NSData *rawData = [dataMessage rawData];
  121. if ([rawData length]) {
  122. message[kFIRMessagingRawDataKey] = rawData;
  123. }
  124. NSString *token = [dataMessage token];
  125. if ([token length]) {
  126. message[kFIRMessagingCollapseKey] = token;
  127. }
  128. // Add the persistent_id. This would be removed later before sending the message to the device.
  129. NSString *persistentID = [dataMessage persistentId];
  130. _FIRMessagingDevAssert([persistentID length], @"Invalid MCS message without persistentID");
  131. if ([persistentID length]) {
  132. message[kFIRMessagingMessageIDKey] = persistentID;
  133. }
  134. // third-party data
  135. for (GtalkAppData *item in dataMessage.appDataArray) {
  136. _FIRMessagingDevAssert(item.hasKey && item.hasValue, @"Invalid AppData");
  137. // do not process the "from" key -- is not useful
  138. if ([kFIRMessagingFromKey isEqualToString:item.key]) {
  139. continue;
  140. }
  141. // Filter the "gcm.notification." keys in the message
  142. if ([item.key hasPrefix:kMCSNotificationPrefix]) {
  143. NSString *key = [item.key substringFromIndex:[kMCSNotificationPrefix length]];
  144. if ([key length]) {
  145. if (!message[kDataMessageNotificationKey]) {
  146. message[kDataMessageNotificationKey] = [NSMutableDictionary dictionary];
  147. }
  148. message[kDataMessageNotificationKey][key] = item.value;
  149. } else {
  150. _FIRMessagingDevAssert([key length], @"Invalid key in MCS message: %@", key);
  151. FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager001,
  152. @"Invalid key in MCS message: %@", key);
  153. }
  154. continue;
  155. }
  156. // Filter the "gcm.duplex" key
  157. if ([item.key isEqualToString:kFIRMessagingMessageSyncViaMCSKey]) {
  158. BOOL value = [item.value boolValue];
  159. message[kFIRMessagingMessageSyncViaMCSKey] = @(value);
  160. continue;
  161. }
  162. // do not allow keys with "reserved" keyword
  163. if ([[item.key lowercaseString] hasPrefix:kMessageReservedPrefix]) {
  164. continue;
  165. }
  166. [message setObject:item.value forKey:item.key];
  167. }
  168. // TODO: Add support for encrypting raw data later
  169. return [NSDictionary dictionaryWithDictionary:message];
  170. }
  171. - (void)didReceiveParsedMessage:(NSDictionary *)message {
  172. if ([message[kFCMMessageSpecialMessage] length]) {
  173. NSString *messageType = message[kFCMMessageSpecialMessage];
  174. if ([kFCMMessageTypeDeletedMessages isEqualToString:messageType]) {
  175. // TODO: Maybe trim down message to remove some unnecessary fields.
  176. // tell the FCM receiver of deleted messages
  177. [self.delegate didDeleteMessagesOnServer];
  178. return;
  179. }
  180. FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager002,
  181. @"Invalid message type received: %@", messageType);
  182. } else if (message[kFIRMessagingMessageSyncViaMCSKey]) {
  183. // Update SYNC_RMQ with the message
  184. BOOL isDuplicate = [self.syncMessageManager didReceiveMCSSyncMessage:message];
  185. if (isDuplicate) {
  186. return;
  187. }
  188. }
  189. NSString *messageId = message[kFIRMessagingMessageIDKey];
  190. NSDictionary *filteredMessage = [self filterInternalFIRMessagingKeysFromMessage:message];
  191. [self.delegate didReceiveMessage:filteredMessage withIdentifier:messageId];
  192. }
  193. - (NSDictionary *)filterInternalFIRMessagingKeysFromMessage:(NSDictionary *)message {
  194. NSMutableDictionary *newMessage = [NSMutableDictionary dictionaryWithDictionary:message];
  195. for (NSString *key in message) {
  196. if ([key hasPrefix:kFIRMessagingMessageInternalReservedKeyword]) {
  197. [newMessage removeObjectForKey:key];
  198. }
  199. }
  200. return [newMessage copy];
  201. }
  202. - (void)sendDataMessageStanza:(NSMutableDictionary *)dataMessage {
  203. NSNumber *ttlNumber = dataMessage[kFIRMessagingSendTTL];
  204. NSString *to = dataMessage[kFIRMessagingSendTo];
  205. NSString *msgId = dataMessage[kFIRMessagingSendMessageID];
  206. NSString *appPackage = [self categoryForUpstreamMessages];
  207. GtalkDataMessageStanza *stanza = [[GtalkDataMessageStanza alloc] init];
  208. // TODO: enforce TTL (right now only ttl=0 is special, means no storage)
  209. int ttl = [ttlNumber intValue];
  210. if (ttl < 0 || ttl > self.ttl) {
  211. ttl = self.ttl;
  212. }
  213. [stanza setTtl:ttl];
  214. [stanza setSent:FIRMessagingCurrentTimestampInSeconds()];
  215. int delay = [self delayForMessage:dataMessage];
  216. if (delay > 0) {
  217. [stanza setMaxDelay:delay];
  218. }
  219. if (msgId) {
  220. [stanza setId_p:msgId];
  221. }
  222. // collapse key as given by the sender
  223. NSString *token = dataMessage[KFIRMessagingSendMessageAppData][kFIRMessagingCollapseKey];
  224. if ([token length]) {
  225. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager003,
  226. @"FIRMessaging using %@ as collapse key", token);
  227. [stanza setToken:token];
  228. }
  229. if (!self.secretToken) {
  230. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager004,
  231. @"Trying to send data message without a secret token. "
  232. @"Authentication failed.");
  233. [self willSendDataMessageFail:stanza
  234. withMessageId:msgId
  235. error:kFIRMessagingErrorCodeMissingDeviceID];
  236. return;
  237. }
  238. if (![to length]) {
  239. [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorMissingTo];
  240. return;
  241. }
  242. [stanza setTo:to];
  243. [stanza setCategory:appPackage];
  244. // required field in the proto this is set by the server
  245. // set it to a sentinel so the runtime doesn't throw an exception
  246. [stanza setFrom:@""];
  247. // MCS itself would set the registration ID
  248. // [stanza setRegId:nil];
  249. int size = [self addData:dataMessage[KFIRMessagingSendMessageAppData] toStanza:stanza];
  250. if (size > kMaxAppDataSizeDefault) {
  251. [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorSizeExceeded];
  252. return;
  253. }
  254. BOOL useRmq = (ttl != 0) && (msgId != nil);
  255. if (useRmq) {
  256. if (!self.client.isConnected) {
  257. // do nothing assuming rmq save is enabled
  258. }
  259. NSError *error;
  260. if (![self.rmq2Manager saveRmqMessage:stanza error:&error]) {
  261. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager005, @"%@", error);
  262. [self willSendDataMessageFail:stanza withMessageId:msgId error:kFIRMessagingErrorSave];
  263. return;
  264. }
  265. [self willSendDataMessageSuccess:stanza withMessageId:msgId];
  266. }
  267. // if delay > 0 we don't really care about sending the message right now
  268. // so we piggy-back on any other urgent(delay = 0) message that we are sending
  269. if (delay > 0 && [self delayMessage:stanza]) {
  270. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager006, @"Delaying Message %@",
  271. dataMessage);
  272. return;
  273. }
  274. // send delayed messages
  275. [self sendDelayedMessages:[self.delayedMessagesQueue removeDelayedMessages]];
  276. BOOL sending = [self tryToSendDataMessageStanza:stanza];
  277. if (!sending) {
  278. if (useRmq) {
  279. NSString *event __unused = [NSString stringWithFormat:@"Queued message: %@", [stanza id_p]];
  280. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager007, @"%@", event);
  281. } else {
  282. [self willSendDataMessageFail:stanza
  283. withMessageId:msgId
  284. error:kFIRMessagingErrorCodeNetwork];
  285. return;
  286. }
  287. }
  288. }
  289. - (void)sendDelayedMessages:(NSArray *)delayedMessages {
  290. for (GtalkDataMessageStanza *message in delayedMessages) {
  291. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager008,
  292. @"%@ Sending delayed message %@", @"DMM", message);
  293. [message setActualDelay:(int)(FIRMessagingCurrentTimestampInSeconds() - message.sent)];
  294. [self tryToSendDataMessageStanza:message];
  295. }
  296. }
  297. - (void)didSendDataMessageStanza:(GtalkDataMessageStanza *)message {
  298. NSString *msgId = [message id_p] ?: @"";
  299. [self.delegate didSendDataMessageWithID:msgId];
  300. }
  301. - (void)addParamWithKey:(NSString *)key
  302. value:(NSString *)val
  303. toStanza:(GtalkDataMessageStanza *)stanza {
  304. if (!key || !val) {
  305. return;
  306. }
  307. GtalkAppData *appData = [[GtalkAppData alloc] init];
  308. [appData setKey:key];
  309. [appData setValue:val];
  310. [[stanza appDataArray] addObject:appData];
  311. }
  312. /**
  313. @return The size of the data being added to stanza.
  314. */
  315. - (int)addData:(NSDictionary *)data toStanza:(GtalkDataMessageStanza *)stanza {
  316. int size = 0;
  317. for (NSString *key in data) {
  318. NSObject *val = data[key];
  319. if ([val isKindOfClass:[NSString class]]) {
  320. NSString *strVal = (NSString *)val;
  321. [self addParamWithKey:key value:strVal toStanza:stanza];
  322. size += [key length] + [strVal length];
  323. } else if ([val isKindOfClass:[NSNumber class]]) {
  324. NSString *strVal = [(NSNumber *)val stringValue];
  325. [self addParamWithKey:key value:strVal toStanza:stanza];
  326. size += [key length] + [strVal length];
  327. } else if ([kFIRMessagingRawDataKey isEqualToString:key] &&
  328. [val isKindOfClass:[NSData class]]) {
  329. NSData *rawData = (NSData *)val;
  330. [stanza setRawData:[rawData copy]];
  331. size += [rawData length];
  332. } else {
  333. FIRMessagingLoggerError(kFIRMessagingMessageCodeDataMessageManager009, @"Ignoring key: %@",
  334. key);
  335. }
  336. }
  337. return size;
  338. }
  339. /**
  340. * Notify the messenger that send data message completed with success. This is called for
  341. * TTL=0, after the message has been sent, or when message is saved, to unlock the send()
  342. * method.
  343. */
  344. - (void)willSendDataMessageSuccess:(GtalkDataMessageStanza *)stanza
  345. withMessageId:(NSString *)messageId {
  346. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager010,
  347. @"send message success: %@", messageId);
  348. [self.delegate willSendDataMessageWithID:messageId error:nil];
  349. }
  350. /**
  351. * We send 'send failures' from server as normal FIRMessaging messages, with a 'message_type'
  352. * extra - same as 'message deleted'.
  353. *
  354. * For TTL=0 or errors that can be detected during send ( too many messages, invalid, etc)
  355. * we throw IOExceptions
  356. */
  357. - (void)willSendDataMessageFail:(GtalkDataMessageStanza *)stanza
  358. withMessageId:(NSString *)messageId
  359. error:(FIRMessagingInternalErrorCode)errorCode {
  360. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager011,
  361. @"Send message fail: %@ error: %lu", messageId, (unsigned long)errorCode);
  362. NSError *error = [NSError errorWithFCMErrorCode:errorCode];
  363. if ([self.delegate respondsToSelector:@selector(willSendDataMessageWithID:error:)]) {
  364. [self.delegate willSendDataMessageWithID:messageId error:error];
  365. }
  366. }
  367. - (void)resendMessagesWithConnection:(FIRMessagingConnection *)connection {
  368. NSMutableString *rmqIdsResent = [NSMutableString string];
  369. NSMutableArray *toRemoveRmqIds = [NSMutableArray array];
  370. FIRMessaging_WEAKIFY(self);
  371. FIRMessaging_WEAKIFY(connection);
  372. FIRMessagingRmqMessageHandler messageHandler = ^(int64_t rmqId, int8_t tag, NSData *data) {
  373. FIRMessaging_STRONGIFY(self);
  374. FIRMessaging_STRONGIFY(connection);
  375. GPBMessage *proto =
  376. [FIRMessagingGetClassForTag((FIRMessagingProtoTag)tag) parseFromData:data error:NULL];
  377. if ([proto isKindOfClass:GtalkDataMessageStanza.class]) {
  378. GtalkDataMessageStanza *stanza = (GtalkDataMessageStanza *)proto;
  379. if (![self handleExpirationForDataMessage:stanza]) {
  380. // time expired let's delete from RMQ
  381. [toRemoveRmqIds addObject:stanza.persistentId];
  382. return;
  383. }
  384. [rmqIdsResent appendString:[NSString stringWithFormat:@"%@,", stanza.id_p]];
  385. }
  386. [connection sendProto:proto];
  387. };
  388. [self.rmq2Manager scanWithRmqMessageHandler:messageHandler
  389. dataMessageHandler:nil];
  390. if ([rmqIdsResent length]) {
  391. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeDataMessageManager012, @"Resent: %@",
  392. rmqIdsResent);
  393. }
  394. if ([toRemoveRmqIds count]) {
  395. [self.rmq2Manager removeRmqMessagesWithRmqIds:toRemoveRmqIds];
  396. }
  397. }
  398. /**
  399. * Check the TTL and generate an error if needed.
  400. *
  401. * @return false if the message needs to be deleted
  402. */
  403. - (BOOL)handleExpirationForDataMessage:(GtalkDataMessageStanza *)message {
  404. if (message.ttl == 0) {
  405. return NO;
  406. }
  407. int64_t now = FIRMessagingCurrentTimestampInSeconds();
  408. if (now > message.sent + message.ttl) {
  409. [self willSendDataMessageFail:message
  410. withMessageId:message.id_p
  411. error:kFIRMessagingErrorServiceNotAvailable];
  412. return NO;
  413. }
  414. return YES;
  415. }
  416. #pragma mark - Private
  417. - (int)delayForMessage:(NSMutableDictionary *)message {
  418. int delay = 0; // default
  419. if (message[kFIRMessagingSendDelay]) {
  420. delay = [message[kFIRMessagingSendDelay] intValue];
  421. [message removeObjectForKey:kFIRMessagingSendDelay];
  422. if (delay < kMinDelaySeconds) {
  423. delay = 0;
  424. } else if (delay > kMaxDelaySeconds) {
  425. delay = kMaxDelaySeconds;
  426. }
  427. }
  428. return delay;
  429. }
  430. // return True if successfully delayed else False
  431. - (BOOL)delayMessage:(GtalkDataMessageStanza *)message {
  432. return [self.delayedMessagesQueue queueMessage:message];
  433. }
  434. - (BOOL)tryToSendDataMessageStanza:(GtalkDataMessageStanza *)stanza {
  435. if (self.client.isConnectionActive) {
  436. [self.client sendMessage:stanza];
  437. return YES;
  438. }
  439. // if we only reconnect for TTL = 0 messages check if we ttl = 0 or
  440. // if we reconnect for all messages try to reconnect
  441. if ((self.upstreamForceReconnect == kUpstreamForceReconnectTTL0 && stanza.ttl == 0) ||
  442. self.upstreamForceReconnect == kUpstreamForceReconnectAll) {
  443. BOOL isNetworkAvailable = [[FIRMessaging messaging] isNetworkAvailable];
  444. if (isNetworkAvailable) {
  445. if (stanza.ttl == 0) {
  446. // Add TTL = 0 messages to be sent on next connect. TTL != 0 messages are
  447. // persisted, and will be sent from the RMQ.
  448. [self.client sendOnConnectOrDrop:stanza];
  449. }
  450. [self.client retryConnectionImmediately:YES];
  451. return YES;
  452. }
  453. }
  454. return NO;
  455. }
  456. - (NSString *)categoryForUpstreamMessages {
  457. return FIRMessagingAppIdentifier();
  458. }
  459. @end