MessageParser.java

  1package eu.siacs.conversations.parser;
  2
  3import android.util.Log;
  4import android.util.Pair;
  5
  6import eu.siacs.conversations.crypto.PgpDecryptionService;
  7import net.java.otr4j.session.Session;
  8import net.java.otr4j.session.SessionStatus;
  9
 10import java.util.ArrayList;
 11import java.util.Set;
 12
 13import eu.siacs.conversations.Config;
 14import eu.siacs.conversations.crypto.axolotl.AxolotlService;
 15import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage;
 16import eu.siacs.conversations.entities.Account;
 17import eu.siacs.conversations.entities.Contact;
 18import eu.siacs.conversations.entities.Conversation;
 19import eu.siacs.conversations.entities.Message;
 20import eu.siacs.conversations.entities.MucOptions;
 21import eu.siacs.conversations.http.HttpConnectionManager;
 22import eu.siacs.conversations.services.MessageArchiveService;
 23import eu.siacs.conversations.services.XmppConnectionService;
 24import eu.siacs.conversations.utils.CryptoHelper;
 25import eu.siacs.conversations.xml.Element;
 26import eu.siacs.conversations.xmpp.OnMessagePacketReceived;
 27import eu.siacs.conversations.xmpp.chatstate.ChatState;
 28import eu.siacs.conversations.xmpp.jid.Jid;
 29import eu.siacs.conversations.xmpp.pep.Avatar;
 30import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 31
 32public class MessageParser extends AbstractParser implements
 33		OnMessagePacketReceived {
 34	public MessageParser(XmppConnectionService service) {
 35		super(service);
 36	}
 37
 38	private boolean extractChatState(Conversation conversation, final MessagePacket packet) {
 39		ChatState state = ChatState.parse(packet);
 40		if (state != null && conversation != null) {
 41			final Account account = conversation.getAccount();
 42			Jid from = packet.getFrom();
 43			if (from.toBareJid().equals(account.getJid().toBareJid())) {
 44				conversation.setOutgoingChatState(state);
 45				if (state == ChatState.ACTIVE || state == ChatState.COMPOSING) {
 46					mXmppConnectionService.markRead(conversation);
 47					account.activateGracePeriod();
 48				}
 49				return false;
 50			} else {
 51				return conversation.setIncomingChatState(state);
 52			}
 53		}
 54		return false;
 55	}
 56
 57	private Message parseOtrChat(String body, Jid from, String id, Conversation conversation) {
 58		String presence;
 59		if (from.isBareJid()) {
 60			presence = "";
 61		} else {
 62			presence = from.getResourcepart();
 63		}
 64		if (body.matches("^\\?OTRv\\d{1,2}\\?.*")) {
 65			conversation.endOtrIfNeeded();
 66		}
 67		if (!conversation.hasValidOtrSession()) {
 68			conversation.startOtrSession(presence,false);
 69		} else {
 70			String foreignPresence = conversation.getOtrSession().getSessionID().getUserID();
 71			if (!foreignPresence.equals(presence)) {
 72				conversation.endOtrIfNeeded();
 73				conversation.startOtrSession(presence, false);
 74			}
 75		}
 76		try {
 77			conversation.setLastReceivedOtrMessageId(id);
 78			Session otrSession = conversation.getOtrSession();
 79			body = otrSession.transformReceiving(body);
 80			SessionStatus status = otrSession.getSessionStatus();
 81			if (body == null && status == SessionStatus.ENCRYPTED) {
 82				mXmppConnectionService.onOtrSessionEstablished(conversation);
 83				return null;
 84			} else if (body == null && status == SessionStatus.FINISHED) {
 85				conversation.resetOtrSession();
 86				mXmppConnectionService.updateConversationUi();
 87				return null;
 88			} else if (body == null || (body.isEmpty())) {
 89				return null;
 90			}
 91			if (body.startsWith(CryptoHelper.FILETRANSFER)) {
 92				String key = body.substring(CryptoHelper.FILETRANSFER.length());
 93				conversation.setSymmetricKey(CryptoHelper.hexToBytes(key));
 94				return null;
 95			}
 96			Message finishedMessage = new Message(conversation, body, Message.ENCRYPTION_OTR, Message.STATUS_RECEIVED);
 97			conversation.setLastReceivedOtrMessageId(null);
 98			return finishedMessage;
 99		} catch (Exception e) {
100			conversation.resetOtrSession();
101			return null;
102		}
103	}
104
105	private Message parseAxolotlChat(Element axolotlMessage, Jid from, String id, Conversation conversation, int status) {
106		Message finishedMessage = null;
107		AxolotlService service = conversation.getAccount().getAxolotlService();
108		XmppAxolotlMessage xmppAxolotlMessage = XmppAxolotlMessage.fromElement(axolotlMessage, from.toBareJid());
109		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = service.processReceivingPayloadMessage(xmppAxolotlMessage);
110		if(plaintextMessage != null) {
111			finishedMessage = new Message(conversation, plaintextMessage.getPlaintext(), Message.ENCRYPTION_AXOLOTL, status);
112			finishedMessage.setAxolotlFingerprint(plaintextMessage.getFingerprint());
113			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(finishedMessage.getConversation().getAccount())+" Received Message with session fingerprint: "+plaintextMessage.getFingerprint());
114		}
115
116		return finishedMessage;
117	}
118
119	private Message parsePGPChat(final Conversation conversation, String pgpEncrypted, int status) {
120		final Message message = new Message(conversation, pgpEncrypted, Message.ENCRYPTION_PGP, status);
121		PgpDecryptionService pgpDecryptionService = conversation.getAccount().getPgpDecryptionService();
122		pgpDecryptionService.add(message);
123		return message;
124	}
125
126	private class Invite {
127		Jid jid;
128		String password;
129		Invite(Jid jid, String password) {
130			this.jid = jid;
131			this.password = password;
132		}
133
134		public boolean execute(Account account) {
135			if (jid != null) {
136				Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, jid, true);
137				if (!conversation.getMucOptions().online()) {
138					conversation.getMucOptions().setPassword(password);
139					mXmppConnectionService.databaseBackend.updateConversation(conversation);
140					mXmppConnectionService.joinMuc(conversation);
141					mXmppConnectionService.updateConversationUi();
142				}
143				return true;
144			}
145			return false;
146		}
147	}
148
149	private Invite extractInvite(Element message) {
150		Element x = message.findChild("x", "http://jabber.org/protocol/muc#user");
151		if (x != null) {
152			Element invite = x.findChild("invite");
153			if (invite != null) {
154				Element pw = x.findChild("password");
155				return new Invite(message.getAttributeAsJid("from"), pw != null ? pw.getContent(): null);
156			}
157		} else {
158			x = message.findChild("x","jabber:x:conference");
159			if (x != null) {
160				return new Invite(x.getAttributeAsJid("jid"),x.getAttribute("password"));
161			}
162		}
163		return null;
164	}
165
166	private static String extractStanzaId(Element packet, Jid by) {
167		for(Element child : packet.getChildren()) {
168			if (child.getName().equals("stanza-id")
169					&& "urn:xmpp:sid:0".equals(child.getNamespace())
170					&& by.equals(child.getAttributeAsJid("by"))) {
171				return child.getAttribute("id");
172			}
173		}
174		return null;
175	}
176
177	private void parseEvent(final Element event, final Jid from, final Account account) {
178		Element items = event.findChild("items");
179		String node = items == null ? null : items.getAttribute("node");
180		if ("urn:xmpp:avatar:metadata".equals(node)) {
181			Avatar avatar = Avatar.parseMetadata(items);
182			if (avatar != null) {
183				avatar.owner = from.toBareJid();
184				if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
185					if (account.getJid().toBareJid().equals(from)) {
186						if (account.setAvatar(avatar.getFilename())) {
187							mXmppConnectionService.databaseBackend.updateAccount(account);
188						}
189						mXmppConnectionService.getAvatarService().clear(account);
190						mXmppConnectionService.updateConversationUi();
191						mXmppConnectionService.updateAccountUi();
192					} else {
193						Contact contact = account.getRoster().getContact(from);
194						contact.setAvatar(avatar);
195						mXmppConnectionService.getAvatarService().clear(contact);
196						mXmppConnectionService.updateConversationUi();
197						mXmppConnectionService.updateRosterUi();
198					}
199				} else {
200					mXmppConnectionService.fetchAvatar(account, avatar);
201				}
202			}
203		} else if ("http://jabber.org/protocol/nick".equals(node)) {
204			Element i = items.findChild("item");
205			Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
206			if (nick != null && nick.getContent() != null) {
207				Contact contact = account.getRoster().getContact(from);
208				contact.setPresenceName(nick.getContent());
209				mXmppConnectionService.getAvatarService().clear(account);
210				mXmppConnectionService.updateConversationUi();
211				mXmppConnectionService.updateAccountUi();
212			}
213		} else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
214			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list update from "+ from + ", processing...");
215			Element item = items.findChild("item");
216			Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
217			AxolotlService axolotlService = account.getAxolotlService();
218			axolotlService.registerDevices(from, deviceIds);
219			mXmppConnectionService.updateAccountUi();
220		}
221	}
222
223	private boolean handleErrorMessage(Account account, MessagePacket packet) {
224		if (packet.getType() == MessagePacket.TYPE_ERROR) {
225			Jid from = packet.getFrom();
226			if (from != null) {
227				Element error = packet.findChild("error");
228				String text = error == null ? null : error.findChildContent("text");
229				if (text != null) {
230					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + text);
231				} else if (error != null) {
232					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + error);
233				}
234				Message message = mXmppConnectionService.markMessage(account,
235						from.toBareJid(),
236						packet.getId(),
237						Message.STATUS_SEND_FAILED);
238				if (message != null && message.getEncryption() == Message.ENCRYPTION_OTR) {
239					message.getConversation().endOtrIfNeeded();
240				}
241			}
242			return true;
243		}
244		return false;
245	}
246
247	@Override
248	public void onMessagePacketReceived(Account account, MessagePacket original) {
249		if (handleErrorMessage(account, original)) {
250			return;
251		}
252		final MessagePacket packet;
253		Long timestamp = null;
254		final boolean isForwarded;
255		boolean isCarbon = false;
256		String serverMsgId = null;
257		final Element fin = original.findChild("fin", "urn:xmpp:mam:0");
258		if (fin != null) {
259			mXmppConnectionService.getMessageArchiveService().processFin(fin,original.getFrom());
260			return;
261		}
262		final Element result = original.findChild("result","urn:xmpp:mam:0");
263		final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
264		if (query != null && query.validFrom(original.getFrom())) {
265			Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", "urn:xmpp:mam:0");
266			if (f == null) {
267				return;
268			}
269			timestamp = f.second;
270			packet = f.first;
271			isForwarded = true;
272			serverMsgId = result.getAttribute("id");
273			query.incrementTotalCount();
274		} else if (query != null) {
275			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
276			return;
277		} else if (original.fromServer(account)) {
278			Pair<MessagePacket, Long> f;
279			f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
280			f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
281			packet = f != null ? f.first : original;
282			if (handleErrorMessage(account, packet)) {
283				return;
284			}
285			timestamp = f != null ? f.second : null;
286			isCarbon = f != null;
287			isForwarded = isCarbon;
288		} else {
289			packet = original;
290			isForwarded = false;
291		}
292
293		if (timestamp == null) {
294			timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
295		}
296		final String body = packet.getBody();
297		final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
298		final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
299		final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
300		int status;
301		final Jid counterpart;
302		final Jid to = packet.getTo();
303		final Jid from = packet.getFrom();
304		final String remoteMsgId = packet.getId();
305
306		if (from == null || to == null) {
307			Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
308			return;
309		}
310		
311		boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
312		boolean isProperlyAddressed = !to.isBareJid() || account.countPresences() == 1;
313		boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
314		if (packet.fromAccount(account)) {
315			status = Message.STATUS_SEND;
316			counterpart = to;
317		} else {
318			status = Message.STATUS_RECEIVED;
319			counterpart = from;
320		}
321
322		Invite invite = extractInvite(packet);
323		if (invite != null && invite.execute(account)) {
324			return;
325		}
326
327		if (extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), packet)) {
328			mXmppConnectionService.updateConversationUi();
329		}
330
331		if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
332			Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
333			if (isTypeGroupChat) {
334				if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
335					status = Message.STATUS_SEND_RECEIVED;
336					if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
337						return;
338					} else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
339						Message message = conversation.findSentMessageWithBody(packet.getBody());
340						if (message != null) {
341							mXmppConnectionService.markMessage(message, status);
342							return;
343						}
344					}
345				} else {
346					status = Message.STATUS_RECEIVED;
347				}
348			}
349			Message message;
350			if (body != null && body.startsWith("?OTR")) {
351				if (!isForwarded && !isTypeGroupChat && isProperlyAddressed) {
352					message = parseOtrChat(body, from, remoteMsgId, conversation);
353					if (message == null) {
354						return;
355					}
356				} else {
357					message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
358				}
359			} else if (pgpEncrypted != null) {
360				message = parsePGPChat(conversation, pgpEncrypted, status);
361			} else if (axolotlEncrypted != null) {
362				message = parseAxolotlChat(axolotlEncrypted, from, remoteMsgId, conversation, status);
363				if (message == null) {
364					return;
365				}
366			} else {
367				message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
368			}
369
370			if (serverMsgId == null) {
371				serverMsgId = extractStanzaId(packet, isTypeGroupChat ? conversation.getJid().toBareJid() : account.getServer());
372			}
373
374			message.setCounterpart(counterpart);
375			message.setRemoteMsgId(remoteMsgId);
376			message.setServerMsgId(serverMsgId);
377			message.setCarbon(isCarbon);
378			message.setTime(timestamp);
379			message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
380			if (conversation.getMode() == Conversation.MODE_MULTI) {
381				Jid trueCounterpart = conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart());
382				message.setTrueCounterpart(trueCounterpart);
383				if (trueCounterpart != null) {
384					updateLastseen(packet,account,trueCounterpart,false);
385				}
386				if (!isTypeGroupChat) {
387					message.setType(Message.TYPE_PRIVATE);
388				}
389			}
390			updateLastseen(packet,account,true);
391			boolean checkForDuplicates = serverMsgId != null
392					|| (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
393					|| message.getType() == Message.TYPE_PRIVATE;
394			if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
395				Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
396				return;
397			}
398
399			conversation.add(message);
400			if (query != null) {
401				query.incrementMessageCount();
402			} else {
403				if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
404					mXmppConnectionService.markRead(conversation);
405					account.activateGracePeriod();
406				} else {
407					message.markUnread();
408				}
409				mXmppConnectionService.updateConversationUi();
410			}
411
412			if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
413				ArrayList<String> receiptsNamespaces = new ArrayList<>();
414				if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
415					receiptsNamespaces.add("urn:xmpp:chat-markers:0");
416				}
417				if (packet.hasChild("request", "urn:xmpp:receipts")) {
418					receiptsNamespaces.add("urn:xmpp:receipts");
419				}
420				if (receiptsNamespaces.size() > 0) {
421					MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
422							packet,
423							receiptsNamespaces,
424							packet.getType());
425					mXmppConnectionService.sendMessagePacket(account, receipt);
426				}
427			}
428			if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
429				if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
430					mXmppConnectionService.updateConversation(conversation);
431				}
432			}
433
434			if (message.getStatus() == Message.STATUS_RECEIVED
435					&& conversation.getOtrSession() != null
436					&& !conversation.getOtrSession().getSessionID().getUserID()
437					.equals(message.getCounterpart().getResourcepart())) {
438				conversation.endOtrIfNeeded();
439			}
440
441			if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
442				mXmppConnectionService.databaseBackend.createMessage(message);
443			}
444			final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
445			if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
446				manager.createNewDownloadConnection(message);
447			} else if (!message.isRead()) {
448				mXmppConnectionService.getNotificationService().push(message);
449			}
450		} else { //no body
451			if (isTypeGroupChat) {
452				Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
453				if (packet.hasChild("subject")) {
454					if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
455						conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
456						conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
457						mXmppConnectionService.updateConversationUi();
458						return;
459					}
460				}
461
462				if (conversation != null && isMucStatusMessage) {
463					for (Element child : mucUserElement.getChildren()) {
464						if (child.getName().equals("status")
465								&& MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
466							mXmppConnectionService.fetchConferenceConfiguration(conversation);
467						}
468					}
469				}
470			}
471		}
472
473		Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
474		if (received == null) {
475			received = packet.findChild("received", "urn:xmpp:receipts");
476		}
477		if (received != null && !packet.fromAccount(account)) {
478			mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
479		}
480		Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
481		if (displayed != null) {
482			if (packet.fromAccount(account)) {
483				Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
484				if (conversation != null) {
485					mXmppConnectionService.markRead(conversation);
486				}
487			} else {
488				updateLastseen(packet, account, true);
489				final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
490				Message message = displayedMessage == null ? null : displayedMessage.prev();
491				while (message != null
492						&& message.getStatus() == Message.STATUS_SEND_RECEIVED
493						&& message.getTimeSent() < displayedMessage.getTimeSent()) {
494					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
495					message = message.prev();
496				}
497			}
498		}
499
500		Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
501		if (event != null) {
502			parseEvent(event, from, account);
503		}
504
505		String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
506		if (nick != null) {
507			Contact contact = account.getRoster().getContact(from);
508			contact.setPresenceName(nick);
509		}
510	}
511}