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