MessageParser.java

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