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