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 message.setTrueCounterpart(conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart()));
357 if (!isTypeGroupChat) {
358 message.setType(Message.TYPE_PRIVATE);
359 }
360 }
361 updateLastseen(packet,account,true);
362 boolean checkForDuplicates = serverMsgId != null
363 || (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
364 || message.getType() == Message.TYPE_PRIVATE;
365 if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
366 Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
367 return;
368 }
369 if (query != null) {
370 query.incrementMessageCount();
371 }
372 conversation.add(message);
373 if (serverMsgId == null) {
374 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
375 mXmppConnectionService.markRead(conversation);
376 account.activateGracePeriod();
377 } else {
378 message.markUnread();
379 }
380 mXmppConnectionService.updateConversationUi();
381 }
382
383 if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
384 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
385 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
386 packet,
387 "urn:xmpp:chat-markers:0",
388 MessagePacket.TYPE_CHAT);
389 mXmppConnectionService.sendMessagePacket(account, receipt);
390 }
391 if (packet.hasChild("request", "urn:xmpp:receipts")) {
392 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
393 packet,
394 "urn:xmpp:receipts",
395 packet.getType());
396 mXmppConnectionService.sendMessagePacket(account, receipt);
397 }
398 }
399 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
400 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
401 mXmppConnectionService.updateConversation(conversation);
402 }
403 }
404
405 if (message.getStatus() == Message.STATUS_RECEIVED
406 && conversation.getOtrSession() != null
407 && !conversation.getOtrSession().getSessionID().getUserID()
408 .equals(message.getCounterpart().getResourcepart())) {
409 conversation.endOtrIfNeeded();
410 }
411
412 if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
413 mXmppConnectionService.databaseBackend.createMessage(message);
414 }
415 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
416 if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
417 manager.createNewDownloadConnection(message);
418 } else if (!message.isRead()) {
419 mXmppConnectionService.getNotificationService().push(message);
420 }
421 } else { //no body
422 if (isTypeGroupChat) {
423 Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
424 if (packet.hasChild("subject")) {
425 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
426 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
427 conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
428 mXmppConnectionService.updateConversationUi();
429 return;
430 }
431 }
432
433 if (conversation != null && isMucStatusMessage) {
434 for (Element child : mucUserElement.getChildren()) {
435 if (child.getName().equals("status")
436 && MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
437 mXmppConnectionService.fetchConferenceConfiguration(conversation);
438 }
439 }
440 }
441 }
442 }
443
444 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
445 if (received == null) {
446 received = packet.findChild("received", "urn:xmpp:receipts");
447 }
448 if (received != null && !packet.fromAccount(account)) {
449 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
450 }
451 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
452 if (displayed != null) {
453 if (packet.fromAccount(account)) {
454 Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
455 if (conversation != null) {
456 mXmppConnectionService.markRead(conversation);
457 }
458 } else {
459 updateLastseen(packet, account, true);
460 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
461 Message message = displayedMessage == null ? null : displayedMessage.prev();
462 while (message != null
463 && message.getStatus() == Message.STATUS_SEND_RECEIVED
464 && message.getTimeSent() < displayedMessage.getTimeSent()) {
465 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
466 message = message.prev();
467 }
468 }
469 }
470
471 Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
472 if (event != null) {
473 parseEvent(event, from, account);
474 }
475
476 String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
477 if (nick != null) {
478 Contact contact = account.getRoster().getContact(from);
479 contact.setPresenceName(nick);
480 }
481 }
482}