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 void parseEvent(final Element event, final Jid from, final Account account) {
167 Element items = event.findChild("items");
168 String node = items == null ? null : items.getAttribute("node");
169 if ("urn:xmpp:avatar:metadata".equals(node)) {
170 Avatar avatar = Avatar.parseMetadata(items);
171 if (avatar != null) {
172 avatar.owner = from.toBareJid();
173 if (mXmppConnectionService.getFileBackend().isAvatarCached(avatar)) {
174 if (account.getJid().toBareJid().equals(from)) {
175 if (account.setAvatar(avatar.getFilename())) {
176 mXmppConnectionService.databaseBackend.updateAccount(account);
177 }
178 mXmppConnectionService.getAvatarService().clear(account);
179 mXmppConnectionService.updateConversationUi();
180 mXmppConnectionService.updateAccountUi();
181 } else {
182 Contact contact = account.getRoster().getContact(from);
183 contact.setAvatar(avatar);
184 mXmppConnectionService.getAvatarService().clear(contact);
185 mXmppConnectionService.updateConversationUi();
186 mXmppConnectionService.updateRosterUi();
187 }
188 } else {
189 mXmppConnectionService.fetchAvatar(account, avatar);
190 }
191 }
192 } else if ("http://jabber.org/protocol/nick".equals(node)) {
193 Element i = items.findChild("item");
194 Element nick = i == null ? null : i.findChild("nick", "http://jabber.org/protocol/nick");
195 if (nick != null && nick.getContent() != null) {
196 Contact contact = account.getRoster().getContact(from);
197 contact.setPresenceName(nick.getContent());
198 mXmppConnectionService.getAvatarService().clear(account);
199 mXmppConnectionService.updateConversationUi();
200 mXmppConnectionService.updateAccountUi();
201 }
202 } else if (AxolotlService.PEP_DEVICE_LIST.equals(node)) {
203 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received PEP device list update from "+ from + ", processing...");
204 Element item = items.findChild("item");
205 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
206 AxolotlService axolotlService = account.getAxolotlService();
207 axolotlService.registerDevices(from, deviceIds);
208 mXmppConnectionService.updateAccountUi();
209 }
210 }
211
212 private boolean handleErrorMessage(Account account, MessagePacket packet) {
213 if (packet.getType() == MessagePacket.TYPE_ERROR) {
214 Jid from = packet.getFrom();
215 if (from != null) {
216 Element error = packet.findChild("error");
217 String text = error == null ? null : error.findChildContent("text");
218 if (text != null) {
219 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + text);
220 } else if (error != null) {
221 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending message to "+ from+ " failed - " + error);
222 }
223 Message message = mXmppConnectionService.markMessage(account,
224 from.toBareJid(),
225 packet.getId(),
226 Message.STATUS_SEND_FAILED);
227 if (message != null && message.getEncryption() == Message.ENCRYPTION_OTR) {
228 message.getConversation().endOtrIfNeeded();
229 }
230 }
231 return true;
232 }
233 return false;
234 }
235
236 @Override
237 public void onMessagePacketReceived(Account account, MessagePacket original) {
238 if (handleErrorMessage(account, original)) {
239 return;
240 }
241 final MessagePacket packet;
242 Long timestamp = null;
243 final boolean isForwarded;
244 boolean isCarbon = false;
245 String serverMsgId = null;
246 final Element fin = original.findChild("fin", "urn:xmpp:mam:0");
247 if (fin != null) {
248 mXmppConnectionService.getMessageArchiveService().processFin(fin,original.getFrom());
249 return;
250 }
251 final Element result = original.findChild("result","urn:xmpp:mam:0");
252 final MessageArchiveService.Query query = result == null ? null : mXmppConnectionService.getMessageArchiveService().findQuery(result.getAttribute("queryid"));
253 if (query != null && query.validFrom(original.getFrom())) {
254 Pair<MessagePacket, Long> f = original.getForwardedMessagePacket("result", "urn:xmpp:mam:0");
255 if (f == null) {
256 return;
257 }
258 timestamp = f.second;
259 packet = f.first;
260 isForwarded = true;
261 serverMsgId = result.getAttribute("id");
262 query.incrementTotalCount();
263 } else if (query != null) {
264 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received mam result from invalid sender");
265 return;
266 } else if (original.fromServer(account)) {
267 Pair<MessagePacket, Long> f;
268 f = original.getForwardedMessagePacket("received", "urn:xmpp:carbons:2");
269 f = f == null ? original.getForwardedMessagePacket("sent", "urn:xmpp:carbons:2") : f;
270 packet = f != null ? f.first : original;
271 if (handleErrorMessage(account, packet)) {
272 return;
273 }
274 timestamp = f != null ? f.second : null;
275 isCarbon = f != null;
276 isForwarded = isCarbon;
277 } else {
278 packet = original;
279 isForwarded = false;
280 }
281
282 if (timestamp == null) {
283 timestamp = AbstractParser.getTimestamp(packet, System.currentTimeMillis());
284 }
285 final String body = packet.getBody();
286 final Element mucUserElement = packet.findChild("x", "http://jabber.org/protocol/muc#user");
287 final String pgpEncrypted = packet.findChildContent("x", "jabber:x:encrypted");
288 final Element axolotlEncrypted = packet.findChild(XmppAxolotlMessage.CONTAINERTAG, AxolotlService.PEP_PREFIX);
289 int status;
290 final Jid counterpart;
291 final Jid to = packet.getTo();
292 final Jid from = packet.getFrom();
293 final String remoteMsgId = packet.getId();
294
295 if (from == null || to == null) {
296 Log.d(Config.LOGTAG,"no to or from in: "+packet.toString());
297 return;
298 }
299
300 boolean isTypeGroupChat = packet.getType() == MessagePacket.TYPE_GROUPCHAT;
301 boolean isProperlyAddressed = !to.isBareJid() || account.countPresences() == 1;
302 boolean isMucStatusMessage = from.isBareJid() && mucUserElement != null && mucUserElement.hasChild("status");
303 if (packet.fromAccount(account)) {
304 status = Message.STATUS_SEND;
305 counterpart = to;
306 } else {
307 status = Message.STATUS_RECEIVED;
308 counterpart = from;
309 }
310
311 Invite invite = extractInvite(packet);
312 if (invite != null && invite.execute(account)) {
313 return;
314 }
315
316 if (extractChatState(mXmppConnectionService.find(account, counterpart.toBareJid()), packet)) {
317 mXmppConnectionService.updateConversationUi();
318 }
319
320 if ((body != null || pgpEncrypted != null || axolotlEncrypted != null) && !isMucStatusMessage) {
321 Conversation conversation = mXmppConnectionService.findOrCreateConversation(account, counterpart.toBareJid(), isTypeGroupChat);
322 if (isTypeGroupChat) {
323 if (counterpart.getResourcepart().equals(conversation.getMucOptions().getActualNick())) {
324 status = Message.STATUS_SEND_RECEIVED;
325 if (mXmppConnectionService.markMessage(conversation, remoteMsgId, status)) {
326 return;
327 } else if (remoteMsgId == null || Config.IGNORE_ID_REWRITE_IN_MUC) {
328 Message message = conversation.findSentMessageWithBody(packet.getBody());
329 if (message != null) {
330 mXmppConnectionService.markMessage(message, status);
331 return;
332 }
333 }
334 } else {
335 status = Message.STATUS_RECEIVED;
336 }
337 }
338 Message message;
339 if (body != null && body.startsWith("?OTR")) {
340 if (!isForwarded && !isTypeGroupChat && isProperlyAddressed) {
341 message = parseOtrChat(body, from, remoteMsgId, conversation);
342 if (message == null) {
343 return;
344 }
345 } else {
346 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
347 }
348 } else if (pgpEncrypted != null) {
349 message = parsePGPChat(conversation, pgpEncrypted, status);
350 } else if (axolotlEncrypted != null) {
351 message = parseAxolotlChat(axolotlEncrypted, from, remoteMsgId, conversation, status);
352 if (message == null) {
353 return;
354 }
355 } else {
356 message = new Message(conversation, body, Message.ENCRYPTION_NONE, status);
357 }
358 message.setCounterpart(counterpart);
359 message.setRemoteMsgId(remoteMsgId);
360 message.setServerMsgId(serverMsgId);
361 message.setCarbon(isCarbon);
362 message.setTime(timestamp);
363 message.markable = packet.hasChild("markable", "urn:xmpp:chat-markers:0");
364 if (conversation.getMode() == Conversation.MODE_MULTI) {
365 Jid trueCounterpart = conversation.getMucOptions().getTrueCounterpart(counterpart.getResourcepart());
366 message.setTrueCounterpart(trueCounterpart);
367 if (trueCounterpart != null) {
368 updateLastseen(packet,account,trueCounterpart,false);
369 }
370 if (!isTypeGroupChat) {
371 message.setType(Message.TYPE_PRIVATE);
372 }
373 }
374 updateLastseen(packet,account,true);
375 boolean checkForDuplicates = serverMsgId != null
376 || (isTypeGroupChat && packet.hasChild("delay","urn:xmpp:delay"))
377 || message.getType() == Message.TYPE_PRIVATE;
378 if (checkForDuplicates && conversation.hasDuplicateMessage(message)) {
379 Log.d(Config.LOGTAG,"skipping duplicate message from "+message.getCounterpart().toString()+" "+message.getBody());
380 return;
381 }
382 if (query != null) {
383 query.incrementMessageCount();
384 }
385 conversation.add(message);
386 if (serverMsgId == null) {
387 if (status == Message.STATUS_SEND || status == Message.STATUS_SEND_RECEIVED) {
388 mXmppConnectionService.markRead(conversation);
389 account.activateGracePeriod();
390 } else {
391 message.markUnread();
392 }
393 mXmppConnectionService.updateConversationUi();
394 }
395
396 if (mXmppConnectionService.confirmMessages() && remoteMsgId != null && !isForwarded && !isTypeGroupChat) {
397 ArrayList<String> receiptsNamespaces = new ArrayList<>();
398 if (packet.hasChild("markable", "urn:xmpp:chat-markers:0")) {
399 receiptsNamespaces.add("urn:xmpp:chat-markers:0");
400 }
401 if (packet.hasChild("request", "urn:xmpp:receipts")) {
402 receiptsNamespaces.add("urn:xmpp:receipts");
403 }
404 if (receiptsNamespaces.size() > 0) {
405 MessagePacket receipt = mXmppConnectionService.getMessageGenerator().received(account,
406 packet,
407 receiptsNamespaces,
408 packet.getType());
409 mXmppConnectionService.sendMessagePacket(account, receipt);
410 }
411 }
412 if (account.getXmppConnection() != null && account.getXmppConnection().getFeatures().advancedStreamFeaturesLoaded()) {
413 if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) {
414 mXmppConnectionService.updateConversation(conversation);
415 }
416 }
417
418 if (message.getStatus() == Message.STATUS_RECEIVED
419 && conversation.getOtrSession() != null
420 && !conversation.getOtrSession().getSessionID().getUserID()
421 .equals(message.getCounterpart().getResourcepart())) {
422 conversation.endOtrIfNeeded();
423 }
424
425 if (message.getEncryption() == Message.ENCRYPTION_NONE || mXmppConnectionService.saveEncryptedMessages()) {
426 mXmppConnectionService.databaseBackend.createMessage(message);
427 }
428 final HttpConnectionManager manager = this.mXmppConnectionService.getHttpConnectionManager();
429 if (message.trusted() && message.treatAsDownloadable() != Message.Decision.NEVER && manager.getAutoAcceptFileSize() > 0) {
430 manager.createNewDownloadConnection(message);
431 } else if (!message.isRead()) {
432 mXmppConnectionService.getNotificationService().push(message);
433 }
434 } else { //no body
435 if (isTypeGroupChat) {
436 Conversation conversation = mXmppConnectionService.find(account, from.toBareJid());
437 if (packet.hasChild("subject")) {
438 if (conversation != null && conversation.getMode() == Conversation.MODE_MULTI) {
439 conversation.setHasMessagesLeftOnServer(conversation.countMessages() > 0);
440 conversation.getMucOptions().setSubject(packet.findChildContent("subject"));
441 mXmppConnectionService.updateConversationUi();
442 return;
443 }
444 }
445
446 if (conversation != null && isMucStatusMessage) {
447 for (Element child : mucUserElement.getChildren()) {
448 if (child.getName().equals("status")
449 && MucOptions.STATUS_CODE_ROOM_CONFIG_CHANGED.equals(child.getAttribute("code"))) {
450 mXmppConnectionService.fetchConferenceConfiguration(conversation);
451 }
452 }
453 }
454 }
455 }
456
457 Element received = packet.findChild("received", "urn:xmpp:chat-markers:0");
458 if (received == null) {
459 received = packet.findChild("received", "urn:xmpp:receipts");
460 }
461 if (received != null && !packet.fromAccount(account)) {
462 mXmppConnectionService.markMessage(account, from.toBareJid(), received.getAttribute("id"), Message.STATUS_SEND_RECEIVED);
463 }
464 Element displayed = packet.findChild("displayed", "urn:xmpp:chat-markers:0");
465 if (displayed != null) {
466 if (packet.fromAccount(account)) {
467 Conversation conversation = mXmppConnectionService.find(account,counterpart.toBareJid());
468 if (conversation != null) {
469 mXmppConnectionService.markRead(conversation);
470 }
471 } else {
472 updateLastseen(packet, account, true);
473 final Message displayedMessage = mXmppConnectionService.markMessage(account, from.toBareJid(), displayed.getAttribute("id"), Message.STATUS_SEND_DISPLAYED);
474 Message message = displayedMessage == null ? null : displayedMessage.prev();
475 while (message != null
476 && message.getStatus() == Message.STATUS_SEND_RECEIVED
477 && message.getTimeSent() < displayedMessage.getTimeSent()) {
478 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_DISPLAYED);
479 message = message.prev();
480 }
481 }
482 }
483
484 Element event = packet.findChild("event", "http://jabber.org/protocol/pubsub#event");
485 if (event != null) {
486 parseEvent(event, from, account);
487 }
488
489 String nick = packet.findChildContent("nick", "http://jabber.org/protocol/nick");
490 if (nick != null) {
491 Contact contact = account.getRoster().getContact(from);
492 contact.setPresenceName(nick);
493 }
494 }
495}