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