MessageParser.java

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