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