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