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