1package eu.siacs.conversations.parser;
2
3import android.support.annotation.NonNull;
4import android.util.Base64;
5import android.util.Log;
6import android.util.Pair;
7
8import org.whispersystems.libaxolotl.IdentityKey;
9import org.whispersystems.libaxolotl.ecc.Curve;
10import org.whispersystems.libaxolotl.ecc.ECPublicKey;
11import org.whispersystems.libaxolotl.state.PreKeyBundle;
12
13import java.io.ByteArrayInputStream;
14import java.security.cert.CertificateException;
15import java.security.cert.CertificateFactory;
16import java.security.cert.X509Certificate;
17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.HashMap;
20import java.util.HashSet;
21import java.util.List;
22import java.util.Map;
23import java.util.Set;
24
25import eu.siacs.conversations.Config;
26import eu.siacs.conversations.crypto.axolotl.AxolotlService;
27import eu.siacs.conversations.entities.Account;
28import eu.siacs.conversations.entities.Contact;
29import eu.siacs.conversations.services.XmppConnectionService;
30import eu.siacs.conversations.utils.Xmlns;
31import eu.siacs.conversations.xml.Element;
32import eu.siacs.conversations.xmpp.OnIqPacketReceived;
33import eu.siacs.conversations.xmpp.OnUpdateBlocklist;
34import eu.siacs.conversations.xmpp.jid.Jid;
35import eu.siacs.conversations.xmpp.stanzas.IqPacket;
36
37public class IqParser extends AbstractParser implements OnIqPacketReceived {
38
39 public IqParser(final XmppConnectionService service) {
40 super(service);
41 }
42
43 private void rosterItems(final Account account, final Element query) {
44 final String version = query.getAttribute("ver");
45 if (version != null) {
46 account.getRoster().setVersion(version);
47 }
48 for (final Element item : query.getChildren()) {
49 if (item.getName().equals("item")) {
50 final Jid jid = item.getAttributeAsJid("jid");
51 if (jid == null) {
52 continue;
53 }
54 final String name = item.getAttribute("name");
55 final String subscription = item.getAttribute("subscription");
56 final Contact contact = account.getRoster().getContact(jid);
57 boolean bothPre = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
58 if (!contact.getOption(Contact.Options.DIRTY_PUSH)) {
59 contact.setServerName(name);
60 contact.parseGroupsFromElement(item);
61 }
62 if (subscription != null) {
63 if (subscription.equals("remove")) {
64 contact.resetOption(Contact.Options.IN_ROSTER);
65 contact.resetOption(Contact.Options.DIRTY_DELETE);
66 contact.resetOption(Contact.Options.PREEMPTIVE_GRANT);
67 } else {
68 contact.setOption(Contact.Options.IN_ROSTER);
69 contact.resetOption(Contact.Options.DIRTY_PUSH);
70 contact.parseSubscriptionFromElement(item);
71 }
72 }
73 boolean both = contact.getOption(Contact.Options.TO) && contact.getOption(Contact.Options.FROM);
74 if ((both != bothPre) && both) {
75 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": gained mutual presence subscription with "+contact.getJid());
76 AxolotlService axolotlService = account.getAxolotlService();
77 if (axolotlService != null) {
78 axolotlService.clearErrorsInFetchStatusMap(contact.getJid());
79 }
80 }
81 mXmppConnectionService.getAvatarService().clear(contact);
82 }
83 }
84 mXmppConnectionService.updateConversationUi();
85 mXmppConnectionService.updateRosterUi();
86 }
87
88 public String avatarData(final IqPacket packet) {
89 final Element pubsub = packet.findChild("pubsub",
90 "http://jabber.org/protocol/pubsub");
91 if (pubsub == null) {
92 return null;
93 }
94 final Element items = pubsub.findChild("items");
95 if (items == null) {
96 return null;
97 }
98 return super.avatarData(items);
99 }
100
101 public Element getItem(final IqPacket packet) {
102 final Element pubsub = packet.findChild("pubsub",
103 "http://jabber.org/protocol/pubsub");
104 if (pubsub == null) {
105 return null;
106 }
107 final Element items = pubsub.findChild("items");
108 if (items == null) {
109 return null;
110 }
111 return items.findChild("item");
112 }
113
114 @NonNull
115 public Set<Integer> deviceIds(final Element item) {
116 Set<Integer> deviceIds = new HashSet<>();
117 if (item != null) {
118 final Element list = item.findChild("list");
119 if (list != null) {
120 for (Element device : list.getChildren()) {
121 if (!device.getName().equals("device")) {
122 continue;
123 }
124 try {
125 Integer id = Integer.valueOf(device.getAttribute("id"));
126 deviceIds.add(id);
127 } catch (NumberFormatException e) {
128 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered invalid <device> node in PEP ("+e.getMessage()+"):" + device.toString()+ ", skipping...");
129 continue;
130 }
131 }
132 }
133 }
134 return deviceIds;
135 }
136
137 public Integer signedPreKeyId(final Element bundle) {
138 final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
139 if(signedPreKeyPublic == null) {
140 return null;
141 }
142 return Integer.valueOf(signedPreKeyPublic.getAttribute("signedPreKeyId"));
143 }
144
145 public ECPublicKey signedPreKeyPublic(final Element bundle) {
146 ECPublicKey publicKey = null;
147 final Element signedPreKeyPublic = bundle.findChild("signedPreKeyPublic");
148 if(signedPreKeyPublic == null) {
149 return null;
150 }
151 try {
152 publicKey = Curve.decodePoint(Base64.decode(signedPreKeyPublic.getContent(),Base64.DEFAULT), 0);
153 } catch (Throwable e) {
154 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid signedPreKeyPublic in PEP: " + e.getMessage());
155 }
156 return publicKey;
157 }
158
159 public byte[] signedPreKeySignature(final Element bundle) {
160 final Element signedPreKeySignature = bundle.findChild("signedPreKeySignature");
161 if(signedPreKeySignature == null) {
162 return null;
163 }
164 try {
165 return Base64.decode(signedPreKeySignature.getContent(), Base64.DEFAULT);
166 } catch (Throwable e) {
167 Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : Invalid base64 in signedPreKeySignature");
168 return null;
169 }
170 }
171
172 public IdentityKey identityKey(final Element bundle) {
173 IdentityKey identityKey = null;
174 final Element identityKeyElement = bundle.findChild("identityKey");
175 if(identityKeyElement == null) {
176 return null;
177 }
178 try {
179 identityKey = new IdentityKey(Base64.decode(identityKeyElement.getContent(), Base64.DEFAULT), 0);
180 } catch (Throwable e) {
181 Log.e(Config.LOGTAG,AxolotlService.LOGPREFIX+" : "+"Invalid identityKey in PEP: "+e.getMessage());
182 }
183 return identityKey;
184 }
185
186 public Map<Integer, ECPublicKey> preKeyPublics(final IqPacket packet) {
187 Map<Integer, ECPublicKey> preKeyRecords = new HashMap<>();
188 Element item = getItem(packet);
189 if (item == null) {
190 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <item> in bundle IQ packet: " + packet);
191 return null;
192 }
193 final Element bundleElement = item.findChild("bundle");
194 if(bundleElement == null) {
195 return null;
196 }
197 final Element prekeysElement = bundleElement.findChild("prekeys");
198 if(prekeysElement == null) {
199 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Couldn't find <prekeys> in bundle IQ packet: " + packet);
200 return null;
201 }
202 for(Element preKeyPublicElement : prekeysElement.getChildren()) {
203 if(!preKeyPublicElement.getName().equals("preKeyPublic")){
204 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Encountered unexpected tag in prekeys list: " + preKeyPublicElement);
205 continue;
206 }
207 Integer preKeyId = Integer.valueOf(preKeyPublicElement.getAttribute("preKeyId"));
208 try {
209 ECPublicKey preKeyPublic = Curve.decodePoint(Base64.decode(preKeyPublicElement.getContent(), Base64.DEFAULT), 0);
210 preKeyRecords.put(preKeyId, preKeyPublic);
211 } catch (Throwable e) {
212 Log.e(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Invalid preKeyPublic (ID="+preKeyId+") in PEP: "+ e.getMessage()+", skipping...");
213 continue;
214 }
215 }
216 return preKeyRecords;
217 }
218
219 public Pair<X509Certificate[],byte[]> verification(final IqPacket packet) {
220 Element item = getItem(packet);
221 Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null;
222 Element chain = verification != null ? verification.findChild("chain") : null;
223 Element signature = verification != null ? verification.findChild("signature") : null;
224 if (chain != null && signature != null) {
225 List<Element> certElements = chain.getChildren();
226 X509Certificate[] certificates = new X509Certificate[certElements.size()];
227 try {
228 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
229 int i = 0;
230 for(Element cert : certElements) {
231 certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT)));
232 ++i;
233 }
234 return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT));
235 } catch (CertificateException e) {
236 return null;
237 }
238 } else {
239 return null;
240 }
241 }
242
243 public PreKeyBundle bundle(final IqPacket bundle) {
244 Element bundleItem = getItem(bundle);
245 if(bundleItem == null) {
246 return null;
247 }
248 final Element bundleElement = bundleItem.findChild("bundle");
249 if(bundleElement == null) {
250 return null;
251 }
252 ECPublicKey signedPreKeyPublic = signedPreKeyPublic(bundleElement);
253 Integer signedPreKeyId = signedPreKeyId(bundleElement);
254 byte[] signedPreKeySignature = signedPreKeySignature(bundleElement);
255 IdentityKey identityKey = identityKey(bundleElement);
256 if(signedPreKeyPublic == null || identityKey == null) {
257 return null;
258 }
259
260 return new PreKeyBundle(0, 0, 0, null,
261 signedPreKeyId, signedPreKeyPublic, signedPreKeySignature, identityKey);
262 }
263
264 public List<PreKeyBundle> preKeys(final IqPacket preKeys) {
265 List<PreKeyBundle> bundles = new ArrayList<>();
266 Map<Integer, ECPublicKey> preKeyPublics = preKeyPublics(preKeys);
267 if ( preKeyPublics != null) {
268 for (Integer preKeyId : preKeyPublics.keySet()) {
269 ECPublicKey preKeyPublic = preKeyPublics.get(preKeyId);
270 bundles.add(new PreKeyBundle(0, 0, preKeyId, preKeyPublic,
271 0, null, null, null));
272 }
273 }
274
275 return bundles;
276 }
277
278 @Override
279 public void onIqPacketReceived(final Account account, final IqPacket packet) {
280 if (packet.getType() == IqPacket.TYPE.ERROR || packet.getType() == IqPacket.TYPE.TIMEOUT) {
281 return;
282 } else if (packet.hasChild("query", Xmlns.ROSTER) && packet.fromServer(account)) {
283 final Element query = packet.findChild("query");
284 // If this is in response to a query for the whole roster:
285 if (packet.getType() == IqPacket.TYPE.RESULT) {
286 account.getRoster().markAllAsNotInRoster();
287 }
288 this.rosterItems(account, query);
289 } else if ((packet.hasChild("block", Xmlns.BLOCKING) || packet.hasChild("blocklist", Xmlns.BLOCKING)) &&
290 packet.fromServer(account)) {
291 // Block list or block push.
292 Log.d(Config.LOGTAG, "Received blocklist update from server");
293 final Element blocklist = packet.findChild("blocklist", Xmlns.BLOCKING);
294 final Element block = packet.findChild("block", Xmlns.BLOCKING);
295 final Collection<Element> items = blocklist != null ? blocklist.getChildren() :
296 (block != null ? block.getChildren() : null);
297 // If this is a response to a blocklist query, clear the block list and replace with the new one.
298 // Otherwise, just update the existing blocklist.
299 if (packet.getType() == IqPacket.TYPE.RESULT) {
300 account.clearBlocklist();
301 account.getXmppConnection().getFeatures().setBlockListRequested(true);
302 }
303 if (items != null) {
304 final Collection<Jid> jids = new ArrayList<>(items.size());
305 // Create a collection of Jids from the packet
306 for (final Element item : items) {
307 if (item.getName().equals("item")) {
308 final Jid jid = item.getAttributeAsJid("jid");
309 if (jid != null) {
310 jids.add(jid);
311 }
312 }
313 }
314 account.getBlocklist().addAll(jids);
315 }
316 // Update the UI
317 mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.BLOCKED);
318 if (packet.getType() == IqPacket.TYPE.SET) {
319 final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
320 mXmppConnectionService.sendIqPacket(account, response, null);
321 }
322 } else if (packet.hasChild("unblock", Xmlns.BLOCKING) &&
323 packet.fromServer(account) && packet.getType() == IqPacket.TYPE.SET) {
324 Log.d(Config.LOGTAG, "Received unblock update from server");
325 final Collection<Element> items = packet.findChild("unblock", Xmlns.BLOCKING).getChildren();
326 if (items.size() == 0) {
327 // No children to unblock == unblock all
328 account.getBlocklist().clear();
329 } else {
330 final Collection<Jid> jids = new ArrayList<>(items.size());
331 for (final Element item : items) {
332 if (item.getName().equals("item")) {
333 final Jid jid = item.getAttributeAsJid("jid");
334 if (jid != null) {
335 jids.add(jid);
336 }
337 }
338 }
339 account.getBlocklist().removeAll(jids);
340 }
341 mXmppConnectionService.updateBlocklistUi(OnUpdateBlocklist.Status.UNBLOCKED);
342 final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
343 mXmppConnectionService.sendIqPacket(account, response, null);
344 } else if (packet.hasChild("open", "http://jabber.org/protocol/ibb")
345 || packet.hasChild("data", "http://jabber.org/protocol/ibb")) {
346 mXmppConnectionService.getJingleConnectionManager()
347 .deliverIbbPacket(account, packet);
348 } else if (packet.hasChild("query", "http://jabber.org/protocol/disco#info")) {
349 final IqPacket response = mXmppConnectionService.getIqGenerator().discoResponse(packet);
350 mXmppConnectionService.sendIqPacket(account, response, null);
351 } else if (packet.hasChild("query","jabber:iq:version")) {
352 final IqPacket response = mXmppConnectionService.getIqGenerator().versionResponse(packet);
353 mXmppConnectionService.sendIqPacket(account,response,null);
354 } else if (packet.hasChild("ping", "urn:xmpp:ping")) {
355 final IqPacket response = packet.generateResponse(IqPacket.TYPE.RESULT);
356 mXmppConnectionService.sendIqPacket(account, response, null);
357 } else {
358 if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
359 final IqPacket response = packet.generateResponse(IqPacket.TYPE.ERROR);
360 final Element error = response.addChild("error");
361 error.setAttribute("type", "cancel");
362 error.addChild("feature-not-implemented","urn:ietf:params:xml:ns:xmpp-stanzas");
363 account.getXmppConnection().sendIqPacket(response, null);
364 }
365 }
366 }
367
368}