1package eu.siacs.conversations.parser;
2
3import android.os.Build;
4import android.text.Html;
5import android.util.Log;
6import android.util.Pair;
7
8import net.java.otr4j.session.Session;
9import net.java.otr4j.session.SessionStatus;
10
11import java.text.SimpleDateFormat;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Date;
15import java.util.List;
16import java.util.Locale;
17import java.util.Set;
18import java.util.UUID;
19
20import eu.siacs.conversations.Config;
21import eu.siacs.conversations.R;
22import eu.siacs.conversations.crypto.OtrService;
23import eu.siacs.conversations.crypto.axolotl.AxolotlService;
24import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
25import eu.siacs.conversations.entities.Account;
26import eu.siacs.conversations.entities.Bookmark;
27import eu.siacs.conversations.entities.Contact;
28import eu.siacs.conversations.entities.Conversation;
29import eu.siacs.conversations.entities.Message;
30import eu.siacs.conversations.entities.MucOptions;
31import eu.siacs.conversations.entities.Presence;
32import eu.siacs.conversations.entities.ReadByMarker;
33import eu.siacs.conversations.entities.ReceiptRequest;
34import eu.siacs.conversations.entities.ServiceDiscoveryResult;
35import eu.siacs.conversations.http.HttpConnectionManager;
36import eu.siacs.conversations.services.MessageArchiveService;
37import eu.siacs.conversations.services.XmppConnectionService;
38import eu.siacs.conversations.utils.CryptoHelper;
39import eu.siacs.conversations.xml.Namespace;
40import eu.siacs.conversations.xml.Element;
41import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
42import eu.siacs.conversations.xmpp.chatstate.ChatState;
43import eu.siacs.conversations.xmpp.jid.Jid;
44import eu.siacs.conversations.xmpp.pep.Avatar;
45import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
46
47public class MessageParser extends AbstractParser implements OnMessagePacketReceived {
48
49 private static final List<String> CLIENTS_SENDING_HTML_IN_OTR = Arrays.asList("Pidgin", "Adium", "Trillian");
50
51 public MessageParser(XmppConnectionService service) {
52 super(service);
53 }
54
55 private boolean extractChatState(Conversation c, final boolean isTypeGroupChat, final MessagePacket packet) {
56 ChatState state = ChatState.parse(packet);
57 if (state != null && c != null) {
58 final Account account = c.getAccount();
59 Jid from = packet.getFrom();
60 if (from.toBareJid().equals(account.getJid().toBareJid())) {
61 c.setOutgoingChatState(state);
62 if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
63 mXmppConnectionService.markRead(c);
64 activateGracePeriod(account);
65 }
66 return false;
67 } else {
68 if (isTypeGroupChat) {
69 MucOptions.User user = c.getMucOptions().findUserByFullJid(from);
70 if (user != null) {
71 return user.setChatState(state);
72 } else {
73 return false;
74 }
75 } else {
76 return c.setIncomingChatState(state);
77 }
78 }
79 }
80 return false;
81 }
82
83 private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
84 String presence;
85 if (from.isBareJid()) {
86 presence = "";
87 } else {
88 presence = from.getResourcepart();
89 }
90 if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
91 conversation.endOtrIfNeeded();
92 }
93 if (!conversation.hasValidOtrSession()) {
94 conversation.startOtrSession(presence, false);
95 } else {
96 String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
97 if (!foreignPresence.equals(presence)) {
98 conversation.endOtrIfNeeded();
99 conversation.startOtrSession(presence, false);
100 }
101 }
102 try {
103 conversation.setLastReceivedOtrMessageId(id);
104 Session otrSession = conversation.getOtrSession();
105 body = otrSession.transformReceiving(body);
106 SessionStatus status = otrSession.getSessionStatus();
107 if (body == null && status == SessionStatus.ENCRYPTED) {
108 mXmppConnectionService.onOtrSessionEstablished(conversation);
109 return null;
110 } else if (body == null && status == SessionStatus.FINISHED) {
111 conversation.resetOtrSession();
112 mXmppConnectionService.updateConversationUi();
113 return null;
114 } else if (body == null || (body.isEmpty())) {
115 return null;
116 }
117 if (body.startsWith(CryptoHelper.FILETRANSFER)) {
118 String key = body.substring(CryptoHelper.FILETRANSFER.length());
119 conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
120 return null;
121 }
122 if (clientMightSendHtml(conversation.getAccount(), from)) {
123 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": received OTR message from bad behaving client. escaping HTML…");
124 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
125 body = Html.fromHtml(body, Html.FROM_HTML_MODE_LEGACY).toString();
126 } else {
127 body = Html.fromHtml(body).toString();
128 }
129 }
130
131 final OtrService otrService = conversation.getAccount().getOtrService();
132 Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
133 finishedMessage.setFingerprint(otrService.getFingerprint(otrSession.getRemotePublicKey()));
134 conversation.setLastReceivedOtrMessageId(null);
135
136 return finishedMessage;
137 } catch (Exception e) {
138 conversation.resetOtrSession();
139 return null;
140 }
141 }
142
143 private static boolean clientMightSendHtml(Account account, Jid from) {
144 String resource = from.getResourcepart();
145 if (resource == null) {
146 return false;
147 }
148 Presence presence = account.getRoster().getContact(from).getPresences().getPresences().get(resource);
149 ServiceDiscoveryResult disco = presence == null ? null : presence.getServiceDiscoveryResult();
150 if (disco == null) {
151 return false;
152 }
153 return hasIdentityKnowForSendingHtml(disco.getIdentities());
154 }
155
156 private static boolean hasIdentityKnowForSendingHtml(List<ServiceDiscoveryResult.Identity> identities) {
157 for (ServiceDiscoveryResult.Identity identity : identities) {
158 if (identity.getName() != null) {
159 if (CLIENTS_SENDING_HTML_IN_OTR.contains(identity.getName())) {
160 return true;
161 }
162 }
163 }
164 return false;
165 }
166
167 private Message parseAxolotlChat(Element axolotlMessage, Jid from, Conversation conversation, int status, boolean postpone) {
168 final AxolotlService service = conversation.getAccount().getAxolotlService();
169 final XmppAxolotlMessage xmppAxolotlMessage;
170 try {
171 xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
172 } catch (Exception e) {
173 Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": invalid omemo message received " + e.getMessage());
174 return null;
175 }
176 if (xmppAxolotlMessage.hasPayload()) {
177 final XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage, postpone);
178 if (plaintextMessage != null) {
179 Message finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
180 finishedMessage.setFingerprint(plaintextMessage.getFingerprint());
181 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount()) + " Received Message with session fingerprint: " + plaintextMessage.getFingerprint());
182 return finishedMessage;
183 }
184 } else {
185 Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": received OMEMO key transport message");
186 service.processReceivingKeyTransportMessage(xmppAxolotlMessage, postpone);
187 }
188 return null;
189 }
190
191 private class Invite {
192 final Jid jid;
193 final String password;
194 final Contact inviter;
195
196 Invite(Jid jid, String password, Contact inviter) {
197 this.jid = jid;
198 this.password = password;
199 this.inviter = inviter;
200 }
201
202 public boolean execute(Account account) {
203 if (jid != null) {
204 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true, false);
205 if (!conversation.getMucOptions().online()) {
206 conversation.getMucOptions().setPassword(password);
207 mXmppConnectionService.databaseBackend.updateConversation(conversation);
208 mXmppConnectionService.joinMuc(conversation, inviter != null && inviter.mutualPresenceSubscription());
209 mXmppConnectionService.updateConversationUi();
210 }
211 return true;
212 }
213 return false;
214 }
215 }
216
217 private Invite extractInvite(Account account, Element message) {
218 Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
219 if (x != null) {
220 Element invite = x.findChild("invite");
221 if (invite != null) {
222 Element pw = x.findChild("password");
223 Jid from = invite.getAttributeAsJid("from");
224 Contact contact = from == null ? null : account.getRoster().getContact(from);
225 return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent() : null, contact);
226 }
227 } else {
228 x = message.findChild("x", "jabber:x:conference");
229 if (x != null) {
230 Jid from = message.getAttributeAsJid("from");
231 Contact contact = from == null ? null : account.getRoster().getContact(from);
232 return new Invite(x.getAttributeAsJid("jid"), x.getAttribute("password"), contact);
233 }
234 }
235 return null;
236 }
237
238 private static String extractStanzaId(Element packet, boolean isTypeGroupChat, Conversation conversation) {
239 final Jid by;
240 final boolean safeToExtract;
241 if (isTypeGroupChat) {
242 by = conversation.getJid().toBareJid();
243 safeToExtract = conversation.getMucOptions().hasFeature(Namespace.STANZA_IDS);
244 } else {
245 Account account = conversation.getAccount();
246 by = account.getJid().toBareJid();
247 safeToExtract = account.getXmppConnection().getFeatures().stanzaIds();
248 }
249 return safeToExtract ? extractStanzaId(packet, by) : null;
250 }
251
252 private static String extractStanzaId(Element packet, Jid by) {
253 for (Element child : packet.getChildren()) {
254 if (child.getName().equals("stanza-id")
255 && Namespace.STANZA_IDS.equals(child.getNamespace())
256 && by.equals(child.getAttributeAsJid("by"))) {
257 return child.getAttribute("id");
258 }
259 }
260 return null;
261 }
262
263 private void parseEvent(final Element event, final Jid from, final Account account) {
264 Element items = event.findChild("items");
265 String node = items == null ? null : items.getAttribute("node");
266 if ("urn:xmpp:avatar:metadata".equals(node)) {
267 Avatar avatar = Avatar.parseMetadata(items);
268 if (avatar != null) {
269 avatar.owner = from.toBareJid();
270 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
271 if (account.getJid().toBareJid().equals(from)) {
272 if (account.setAvatar(avatar.getFilename())) {
273 mXmppConnectionService.databaseBackend.updateAccount(account);
274 }
275 mXmppConnectionService.getAvatarService().clear(account);
276 mXmppConnectionService.updateConversationUi();
277 mXmppConnectionService.updateAccountUi();
278 } else {
279 Contact contact = account.getRoster().getContact(from);
280 contact.setAvatar(avatar);
281 mXmppConnectionService.getAvatarService().clear(contact);
282 mXmppConnectionService.updateConversationUi();
283 mXmppConnectionService.updateRosterUi();
284 }
285 } else if (mXmppConnectionService.isDataSaverDisabled()) {
286 mXmppConnectionService.fetchAvatar(account, avatar);
287 }
288 }
289 } else if ("http://jabber.org/protocol/nick".equals(node)) {
290 final Element i = items.findChild("item");
291 final String nick = i == null ? null : i.findChildContent("nick", Namespace.NICK);
292 if (nick != null) {
293 Contact contact = account.getRoster().getContact(from);
294 if (contact.setPresenceName(nick)) {
295 mXmppConnectionService.getAvatarService().clear(contact);
296 }
297 mXmppConnectionService.updateConversationUi();
298 mXmppConnectionService.updateAccountUi();
299 }
300 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
301 Element item = items.findChild("item");
302 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
303 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received PEP device list " + deviceIds + " update from " + from + ", processing... ");
304 AxolotlService axolotlService = account.getAxolotlService();
305 axolotlService.registerDevices(from, deviceIds);
306 mXmppConnectionService.updateAccountUi();
307 }
308 }
309
310 private boolean handleErrorMessage(Account account, MessagePacket packet) {
311 if (packet.getType() == MessagePacket.TYPE_ERROR) {
312 Jid from = packet.getFrom();
313 if (from != null) {
314 Message message = mXmppConnectionService.markMessage(account,
315 from.toBareJid(),
316 packet.getId(),
317 Message.STATUS_SEND_FAILED,
318 extractErrorMessage(packet));
319 if (message != null) {
320 if (message.getEncryption() == Message.ENCRYPTION_OTR) {
321 message.getConversation().endOtrIfNeeded();
322 }
323 }
324 }
325 return true;
326 }
327 return false;
328 }
329
330 @Override
331 public void onMessagePacketReceived(Account account, MessagePacket original) {
332 if (handleErrorMessage(account, original)) {
333 return;
334 }
335 final MessagePacket packet;
336 Long timestamp = null;
337 final boolean isForwarded;
338 boolean isCarbon = false;
339 String serverMsgId = null;
340 final Element fin = original.findChild("fin", Namespace.MAM_LEGACY);
341 if (fin != null) {
342 mXmppConnectionService.getMessageArchiveService().processFinLegacy(fin, original.getFrom());
343 return;
344 }
345 final boolean mamLegacy = original.hasChild("result", Namespace.MAM_LEGACY);
346 final Element result = original.findChild("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
347 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
348 if (query != null && query.validFrom(original.getFrom())) {
349 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", mamLegacy ? Namespace.MAM_LEGACY : Namespace.MAM);
350 if (f == null) {
351 return;
352 }
353 timestamp = f.second;
354 packet = f.first;
355 isForwarded = true;
356 serverMsgId = result.getAttribute("id");
357 query.incrementMessageCount();
358 } else if (query != null) {
359 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received mam result from invalid sender");
360 return;
361 } else if (original.fromServer(account)) {
362 Pair<MessagePacket, Long> f;
363 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
364 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
365 packet = f != null ? f.first : original;
366 if (handleErrorMessage(account, packet)) {
367 return;
368 }
369 timestamp = f != null ? f.second : null;
370 isCarbon = f != null;
371 isForwarded = isCarbon;
372 } else {
373 packet = original;
374 isForwarded = false;
375 }
376
377 if (timestamp == null) {
378 timestamp = AbstractParser.parseTimestamp(original, AbstractParser.parseTimestamp(packet));
379 }
380 final String body = packet.getBody();
381 final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
382 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
383 final Element replaceElement = packet.findChild("replace", "urn:xmpp:message-correct:0");
384 final Element oob = packet.findChild("x", Namespace.OOB);
385 final String oobUrl = oob != null ? oob.findChildContent("url") : null;
386 final String replacementId = replaceElement == null ? null : replaceElement.getAttribute("id");
387 final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
388 int status;
389 final Jid counterpart;
390 final Jid to = packet.getTo();
391 final Jid from = packet.getFrom();
392 final Element originId = packet.findChild("origin-id", Namespace.STANZA_IDS);
393 final String remoteMsgId;
394 if (originId != null && originId.getAttribute("id") != null) {
395 remoteMsgId = originId.getAttribute("id");
396 } else {
397 remoteMsgId = packet.getId();
398 }
399 boolean notify = false;
400
401 if (from == null) {
402 Log.d(Config.LOGTAG, "no from in: " + packet.toString());
403 return;
404 }
405
406 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
407 if (query != null && !query.muc() && isTypeGroupChat) {
408 Log.e(Config.LOGTAG,account.getJid().toBareJid()+": received groupchat ("+from+") message on regular MAM request. skipping");
409 return;
410 }
411 boolean isProperlyAddressed = (to != null) && (!to.isBareJid() || account.countPresences() == 0);
412 boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
413 if (packet.fromAccount(account)) {
414 status = Message.STATUS_SEND;
415 counterpart = to != null ? to : account.getJid();
416 } else {
417 status = Message.STATUS_RECEIVED;
418 counterpart = from;
419 }
420
421 Invite invite = extractInvite(account, packet);
422 if (invite != null && invite.execute(account)) {
423 return;
424 }
425
426 if ((body != null || pgpEncrypted != null || (axolotlEncrypted != null && axolotlEncrypted.hasChild("payload")) || oobUrl != null) && !isMucStatusMessage) {
427 final Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat, false, query, false);
428 final boolean conversationMultiMode = conversation.getMode() == Conversation.MODE_MULTI;
429
430 if (serverMsgId == null) {
431 serverMsgId = extractStanzaId(packet, isTypeGroupChat, conversation);
432 }
433
434 if (isTypeGroupChat) {
435 if (conversation.getMucOptions().isSelf(counterpart)) {
436 status = Message.STATUS_SEND_RECEIVED;
437 isCarbon = true; //not really carbon but received from another resource
438 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status, serverMsgId)) {
439 return;
440 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
441 Message message = conversation.findSentMessageWithBody(packet.getBody());
442 if (message != null) {
443 mXmppConnectionService.markMessage(message, status);
444 return;
445 }
446 }
447 } else {
448 status = Message.STATUS_RECEIVED;
449 }
450 }
451 final Message message;
452 if (body != null && body.startsWith("?OTR") && Config.supportOtr()) {
453 if (!isForwarded && !isTypeGroupChat && isProperlyAddressed && !conversationMultiMode) {
454 message = parseOtrChat(body, from, remoteMsgId, conversation);
455 if (message == null) {
456 return;
457 }
458 } else {
459 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": ignoring OTR message from " + from + " isForwarded=" + Boolean.toString(isForwarded) + ", isProperlyAddressed=" + Boolean.valueOf(isProperlyAddressed));
460 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
461 }
462 } else if (pgpEncrypted != null && Config.supportOpenPgp()) {
463 message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
464 } else if (axolotlEncrypted != null && Config.supportOmemo()) {
465 Jid origin;
466 if (conversationMultiMode) {
467 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
468 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
469 if (origin == null) {
470 Log.d(Config.LOGTAG, "axolotl message in non anonymous conference received");
471 return;
472 }
473 } else {
474 origin = from;
475 }
476 message = parseAxolotlChat(axolotlEncrypted, origin, conversation, status, query != null);
477 if (message == null) {
478 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
479 mXmppConnectionService.updateConversationUi();
480 }
481 if (query != null && status == Message.STATUS_SEND && remoteMsgId != null) {
482 Message previouslySent = conversation.findSentMessageWithUuid(remoteMsgId);
483 if (previouslySent != null && previouslySent.getServerMsgId() == null && serverMsgId != null) {
484 previouslySent.setServerMsgId(serverMsgId);
485 mXmppConnectionService.databaseBackend.updateMessage(previouslySent);
486 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": encountered previously sent OMEMO message without serverId. updating...");
487 }
488 }
489 return;
490 }
491 if (conversationMultiMode) {
492 message.setTrueCounterpart(origin);
493 }
494 } else if (body == null && oobUrl != null) {
495 message = new Message(conversation, oobUrl, Message.ENCRYPTION_NONE, status);
496 message.setOob(true);
497 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
498 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
499 }
500 } else {
501 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
502 }
503
504 message.setCounterpart(counterpart);
505 message.setRemoteMsgId(remoteMsgId);
506 message.setServerMsgId(serverMsgId);
507 message.setCarbon(isCarbon);
508 message.setTime(timestamp);
509 if (body != null && body.equals(oobUrl)) {
510 message.setOob(true);
511 if (CryptoHelper.isPgpEncryptedUrl(oobUrl)) {
512 message.setEncryption(Message.ENCRYPTION_DECRYPTED);
513 }
514 }
515 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
516 if (conversationMultiMode) {
517 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
518 Jid trueCounterpart;
519 if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL) {
520 trueCounterpart = message.getTrueCounterpart();
521 } else if (query != null && query.safeToExtractTrueCounterpart()) {
522 trueCounterpart = getTrueCounterpart(mucUserElement, fallback);
523 } else {
524 trueCounterpart = fallback;
525 }
526 if (trueCounterpart != null && trueCounterpart.toBareJid().equals(account.getJid().toBareJid())) {
527 status = isTypeGroupChat ? Message.STATUS_SEND_RECEIVED : Message.STATUS_SEND;
528 }
529 message.setStatus(status);
530 message.setTrueCounterpart(trueCounterpart);
531 if (!isTypeGroupChat) {
532 message.setType(Message.TYPE_PRIVATE);
533 }
534 } else {
535 updateLastseen(account, from);
536 }
537
538 if (replacementId != null && mXmppConnectionService.allowMessageCorrection()) {
539 final Message replacedMessage = conversation.findMessageWithRemoteIdAndCounterpart(replacementId,
540 counterpart,
541 message.getStatus() == Message.STATUS_RECEIVED,
542 message.isCarbon());
543 if (replacedMessage != null) {
544 final boolean fingerprintsMatch = replacedMessage.getFingerprint() == null
545 || replacedMessage.getFingerprint().equals(message.getFingerprint());
546 final boolean trueCountersMatch = replacedMessage.getTrueCounterpart() != null
547 && replacedMessage.getTrueCounterpart().equals(message.getTrueCounterpart());
548 final boolean duplicate = conversation.hasDuplicateMessage(message);
549 if (fingerprintsMatch && (trueCountersMatch || !conversationMultiMode) && !duplicate) {
550 Log.d(Config.LOGTAG, "replaced message '" + replacedMessage.getBody() + "' with '" + message.getBody() + "'");
551 synchronized (replacedMessage) {
552 final String uuid = replacedMessage.getUuid();
553 replacedMessage.setUuid(UUID.randomUUID().toString());
554 replacedMessage.setBody(message.getBody());
555 replacedMessage.setEdited(replacedMessage.getRemoteMsgId());
556 replacedMessage.setRemoteMsgId(remoteMsgId);
557 if (replacedMessage.getServerMsgId() == null || message.getServerMsgId() != null) {
558 replacedMessage.setServerMsgId(message.getServerMsgId());
559 }
560 replacedMessage.setEncryption(message.getEncryption());
561 if (replacedMessage.getStatus() == Message.STATUS_RECEIVED) {
562 replacedMessage.markUnread();
563 }
564 extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet);
565 mXmppConnectionService.updateMessage(replacedMessage, uuid);
566 mXmppConnectionService.getNotificationService().updateNotification(false);
567 if (mXmppConnectionService.confirmMessages()
568 && replacedMessage.getStatus() == Message.STATUS_RECEIVED
569 && (replacedMessage.trusted() || replacedMessage.getType() == Message.TYPE_PRIVATE)
570 && remoteMsgId != null
571 && !isTypeGroupChat) {
572 processMessageReceipts(account, packet, query);
573 }
574 if (replacedMessage.getEncryption() == Message.ENCRYPTION_PGP) {
575 conversation.getAccount().getPgpDecryptionService().discard(replacedMessage);
576 conversation.getAccount().getPgpDecryptionService().decrypt(replacedMessage, false);
577 }
578 }
579 return;
580 } else {
581 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received message correction but verification didn't check out");
582 }
583 }
584 }
585
586 long deletionDate = mXmppConnectionService.getAutomaticMessageDeletionDate();
587 if (deletionDate != 0 && message.getTimeSent() < deletionDate) {
588 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": skipping message from " + message.getCounterpart().toString() + " because it was sent prior to our deletion date");
589 return;
590 }
591
592 boolean checkForDuplicates = (isTypeGroupChat && packet.hasChild("delay", "urn:xmpp:delay"))
593 || message.getType() == Message.TYPE_PRIVATE
594 || message.getServerMsgId() != null;
595 if (checkForDuplicates ) {
596 final Message duplicate = conversation.findDuplicateMessage(message);
597 if (duplicate != null) {
598 final boolean serverMsgIdUpdated;
599 if (duplicate.getStatus() != Message.STATUS_RECEIVED
600 && duplicate.getUuid().equals(message.getRemoteMsgId())
601 && duplicate.getServerMsgId() == null
602 && message.getServerMsgId() != null) {
603 duplicate.setServerMsgId(message.getServerMsgId());
604 mXmppConnectionService.databaseBackend.updateMessage(message);
605 serverMsgIdUpdated = true;
606 } else {
607 serverMsgIdUpdated = false;
608 }
609 Log.d(Config.LOGTAG, "skipping duplicate message with " + message.getCounterpart()+". serverMsgIdUpdated="+Boolean.toString(serverMsgIdUpdated));
610 return;
611 }
612 }
613
614 if (query != null && query.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
615 conversation.prepend(message);
616 } else {
617 conversation.add(message);
618 }
619 if (query != null) {
620 query.incrementActualMessageCount();
621 }
622
623 if (query == null || query.isCatchup()) { //either no mam or catchup
624 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
625 mXmppConnectionService.markRead(conversation);
626 if (query == null) {
627 activateGracePeriod(account);
628 }
629 } else {
630 message.markUnread();
631 notify = true;
632 }
633 }
634
635 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
636 notify = conversation.getAccount().getPgpDecryptionService().decrypt(message, notify);
637 }
638
639 if (query == null) {
640 extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet);
641 mXmppConnectionService.updateConversationUi();
642 }
643
644 if (mXmppConnectionService.confirmMessages()
645 && message.getStatus() == Message.STATUS_RECEIVED
646 && (message.trusted() || message.getType() == Message.TYPE_PRIVATE)
647 && remoteMsgId != null
648 && !isTypeGroupChat) {
649 processMessageReceipts(account, packet, query);
650 }
651
652 if (message.getStatus() == Message.STATUS_RECEIVED
653 && conversation.getOtrSession() != null
654 && !conversation.getOtrSession().getSessionID().getUserID()
655 .equals(message.getCounterpart().getResourcepart())) {
656 conversation.endOtrIfNeeded();
657 }
658
659 mXmppConnectionService.databaseBackend.createMessage(message);
660 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
661 if (message.trusted() && message.treatAsDownloadable() && manager.getAutoAcceptFileSize() > 0) {
662 manager.createNewDownloadConnection(message);
663 } else if (notify) {
664 if (query != null && query.isCatchup()) {
665 mXmppConnectionService.getNotificationService().pushFromBacklog(message);
666 } else {
667 mXmppConnectionService.getNotificationService().push(message);
668 }
669 }
670 } else if (!packet.hasChild("body")) { //no body
671
672 final Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
673 if (axolotlEncrypted != null) {
674 Jid origin;
675 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
676 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
677 origin = getTrueCounterpart(query != null ? mucUserElement : null, fallback);
678 if (origin == null) {
679 Log.d(Config.LOGTAG, "omemo key transport message in non anonymous conference received");
680 return;
681 }
682 } else if (isTypeGroupChat) {
683 return;
684 } else {
685 origin = from;
686 }
687 try {
688 final XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlEncrypted, origin.toBareJid());
689 account.getAxolotlService().processReceivingKeyTransportMessage(xmppAxolotlMessage, query != null);
690 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": omemo key transport message received from "+origin);
691 } catch (Exception e) {
692 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": invalid omemo key transport message received " + e.getMessage());
693 return;
694 }
695 }
696
697 if (query == null && extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), isTypeGroupChat, packet)) {
698 mXmppConnectionService.updateConversationUi();
699 }
700
701 if (isTypeGroupChat) {
702 if (packet.hasChild("subject")) {
703 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
704 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
705 String subject = packet.findChildContent("subject");
706 if (conversation.getMucOptions().setSubject(subject)) {
707 mXmppConnectionService.updateConversation(conversation);
708 }
709 final Bookmark bookmark = conversation.getBookmark();
710 if (bookmark != null && bookmark.getBookmarkName() == null) {
711 if (bookmark.setBookmarkName(subject)) {
712 mXmppConnectionService.pushBookmarks(account);
713 }
714 }
715 mXmppConnectionService.updateConversationUi();
716 return;
717 }
718 }
719 }
720 if (conversation != null && mucUserElement != null && from.isBareJid()) {
721 for (Element child : mucUserElement.getChildren()) {
722 if ("status".equals(child.getName())) {
723 try {
724 int code = Integer.parseInt(child.getAttribute("code"));
725 if ((code >= 170 && code <= 174) || (code >= 102 && code <= 104)) {
726 mXmppConnectionService.fetchConferenceConfiguration(conversation);
727 break;
728 }
729 } catch (Exception e) {
730 //ignored
731 }
732 } else if ("item".equals(child.getName())) {
733 MucOptions.User user = AbstractParser.parseItem(conversation, child);
734 Log.d(Config.LOGTAG, account.getJid() + ": changing affiliation for "
735 + user.getRealJid() + " to " + user.getAffiliation() + " in "
736 + conversation.getJid().toBareJid());
737 if (!user.realJidMatchesAccount()) {
738 boolean isNew = conversation.getMucOptions().updateUser(user);
739 mXmppConnectionService.getAvatarService().clear(conversation);
740 mXmppConnectionService.updateMucRosterUi();
741 mXmppConnectionService.updateConversationUi();
742 if (!user.getAffiliation().ranks(MucOptions.Affiliation.MEMBER)) {
743 Jid jid = user.getRealJid();
744 List<Jid> cryptoTargets = conversation.getAcceptedCryptoTargets();
745 if (cryptoTargets.remove(user.getRealJid())) {
746 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": removed " + jid + " from crypto targets of " + conversation.getName());
747 conversation.setAcceptedCryptoTargets(cryptoTargets);
748 mXmppConnectionService.updateConversation(conversation);
749 }
750 } else if (isNew && user.getRealJid() != null && account.getAxolotlService().hasEmptyDeviceList(user.getRealJid())) {
751 account.getAxolotlService().fetchDeviceIds(user.getRealJid());
752 }
753 }
754 }
755 }
756 }
757 }
758
759 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
760 if (received == null) {
761 received = packet.findChild("received", "urn:xmpp:receipts");
762 }
763 if (received != null) {
764 String id = received.getAttribute("id");
765 if (packet.fromAccount(account)) {
766 if (query != null && id != null && packet.getTo() != null) {
767 query.pendingReceiptRequests.remove(new ReceiptRequest(packet.getTo(),id));
768 }
769 } else {
770 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
771 }
772 }
773 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
774 if (displayed != null) {
775 final String id = displayed.getAttribute("id");
776 final Jid sender = displayed.getAttributeAsJid("sender");
777 if (packet.fromAccount(account)) {
778 Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid());
779 if (conversation != null && (query == null || query.isCatchup())) {
780 mXmppConnectionService.markRead(conversation); //TODO only mark messages read that are older than timestamp
781 }
782 } else if (isTypeGroupChat) {
783 Conversation conversation = mXmppConnectionService.find(account, counterpart.toBareJid());
784 if (conversation != null && id != null && sender != null) {
785 Message message = conversation.findMessageWithRemoteId(id, sender);
786 if (message != null) {
787 final Jid fallback = conversation.getMucOptions().getTrueCounterpart(counterpart);
788 final Jid trueJid = getTrueCounterpart((query != null && query.safeToExtractTrueCounterpart()) ? mucUserElement : null, fallback);
789 final boolean trueJidMatchesAccount = account.getJid().toBareJid().equals(trueJid == null ? null : trueJid.toBareJid());
790 if (trueJidMatchesAccount || conversation.getMucOptions().isSelf(counterpart)) {
791 if (!message.isRead() && (query == null || query.isCatchup())) { //checking if message is unread fixes race conditions with reflections
792 mXmppConnectionService.markRead(conversation);
793 }
794 } else if (!counterpart.isBareJid() && trueJid != null){
795 ReadByMarker readByMarker = ReadByMarker.from(counterpart, trueJid);
796 if (message.addReadByMarker(readByMarker)) {
797 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": added read by (" + readByMarker.getRealJid() + ") to message '" + message.getBody() + "'");
798 mXmppConnectionService.updateMessage(message);
799 }
800 }
801 }
802 }
803 } else {
804 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), id, Message.STATUS_SEND_DISPLAYED);
805 Message message = displayedMessage == null ? null : displayedMessage.prev();
806 while (message != null
807 && message.getStatus() == Message.STATUS_SEND_RECEIVED
808 && message.getTimeSent() < displayedMessage.getTimeSent()) {
809 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
810 message = message.prev();
811 }
812 }
813 }
814
815 Element event = original.findChild("event", "http://jabber.org/protocol/pubsub#event");
816 if (event != null) {
817 parseEvent(event, original.getFrom(), account);
818 }
819
820 final String nick = packet.findChildContent("nick", Namespace.NICK);
821 if (nick != null) {
822 Contact contact = account.getRoster().getContact(from);
823 if (contact.setPresenceName(nick)) {
824 mXmppConnectionService.getAvatarService().clear(contact);
825 }
826 }
827 }
828
829 private static Jid getTrueCounterpart(Element mucUserElement, Jid fallback) {
830 final Element item = mucUserElement == null ? null : mucUserElement.findChild("item");
831 Jid result = item == null ? null : item.getAttributeAsJid("jid");
832 return result != null ? result : fallback;
833 }
834
835 private void processMessageReceipts(Account account, MessagePacket packet, MessageArchiveService.Query query) {
836 final boolean markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
837 final boolean request = packet.hasChild("request", "urn:xmpp:receipts");
838 if (query == null) {
839 final ArrayList<String> receiptsNamespaces = new ArrayList<>();
840 if (markable) {
841 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
842 }
843 if (request) {
844 receiptsNamespaces.add("urn:xmpp:receipts");
845 }
846 if (receiptsNamespaces.size() > 0) {
847 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
848 packet,
849 receiptsNamespaces,
850 packet.getType());
851 mXmppConnectionService.sendMessagePacket(account, receipt);
852 }
853 } else {
854 if (request) {
855 query.pendingReceiptRequests.add(new ReceiptRequest(packet.getFrom(),packet.getId()));
856 }
857 }
858 }
859
860 private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
861
862 private void activateGracePeriod(Account account) {
863 long duration = mXmppConnectionService.getLongPreference("grace_period_length", R.integer.grace_period) * 1000;
864 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": activating grace period till " + TIME_FORMAT.format(new Date(System.currentTimeMillis() + duration)));
865 account.activateGracePeriod(duration);
866 }
867}