1package eu.siacs.conversations.generator;
2
3
4import android.os.Bundle;
5import android.util.Base64;
6import android.util.Log;
7
8import org.whispersystems.libaxolotl.IdentityKey;
9import org.whispersystems.libaxolotl.ecc.ECPublicKey;
10import org.whispersystems.libaxolotl.state.PreKeyRecord;
11import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
12
13import java.nio.ByteBuffer;
14import java.security.cert.CertificateEncodingException;
15import java.security.cert.X509Certificate;
16import java.util.ArrayList;
17import java.util.List;
18import java.util.Locale;
19import java.util.Set;
20import java.util.TimeZone;
21import java.util.UUID;
22
23import eu.siacs.conversations.Config;
24import eu.siacs.conversations.R;
25import eu.siacs.conversations.crypto.axolotl.AxolotlService;
26import eu.siacs.conversations.entities.Account;
27import eu.siacs.conversations.entities.Conversation;
28import eu.siacs.conversations.entities.DownloadableFile;
29import eu.siacs.conversations.services.MessageArchiveService;
30import eu.siacs.conversations.services.XmppConnectionService;
31import eu.siacs.conversations.xml.Namespace;
32import eu.siacs.conversations.xml.Element;
33import eu.siacs.conversations.xmpp.forms.Data;
34import eu.siacs.conversations.xmpp.jid.Jid;
35import eu.siacs.conversations.xmpp.pep.Avatar;
36import eu.siacs.conversations.xmpp.stanzas.IqPacket;
37
38public class IqGenerator extends AbstractGenerator {
39
40 public IqGenerator(final XmppConnectionService service) {
41 super(service);
42 }
43
44 public IqPacket discoResponse(final IqPacket request) {
45 final IqPacket packet = new IqPacket(IqPacket.TYPE.RESULT);
46 packet.setId(request.getId());
47 packet.setTo(request.getFrom());
48 final Element query = packet.addChild("query",
49 "http://jabber.org/protocol/disco#info");
50 query.setAttribute("node", request.query().getAttribute("node"));
51 final Element identity = query.addChild("identity");
52 identity.setAttribute("category", "client");
53 identity.setAttribute("type", getIdentityType());
54 identity.setAttribute("name", getIdentityName());
55 for (final String feature : getFeatures()) {
56 query.addChild("feature").setAttribute("var", feature);
57 }
58 return packet;
59 }
60
61 public IqPacket versionResponse(final IqPacket request) {
62 final IqPacket packet = request.generateResponse(IqPacket.TYPE.RESULT);
63 Element query = packet.query("jabber:iq:version");
64 query.addChild("name").setContent(mXmppConnectionService.getString(R.string.app_name));
65 query.addChild("version").setContent(getIdentityVersion());
66 if ("chromium".equals(android.os.Build.BRAND)) {
67 query.addChild("os").setContent("Chrome OS");
68 } else{
69 query.addChild("os").setContent("Android");
70 }
71 return packet;
72 }
73
74 public IqPacket entityTimeResponse(IqPacket request) {
75 final IqPacket packet = request.generateResponse(IqPacket.TYPE.RESULT);
76 Element time = packet.addChild("time","urn:xmpp:time");
77 final long now = System.currentTimeMillis();
78 time.addChild("utc").setContent(getTimestamp(now));
79 TimeZone ourTimezone = TimeZone.getDefault();
80 long offsetSeconds = ourTimezone.getOffset(now) / 1000;
81 long offsetMinutes = Math.abs((offsetSeconds % 3600) / 60);
82 long offsetHours = offsetSeconds / 3600;
83 String hours;
84 if (offsetHours<0) {
85 hours = String.format(Locale.US,"%03d",offsetHours);
86 } else {
87 hours = String.format(Locale.US,"%02d",offsetHours);
88 }
89 String minutes = String.format(Locale.US,"%02d",offsetMinutes);
90 time.addChild("tzo").setContent(hours+":"+minutes);
91 return packet;
92 }
93
94 protected IqPacket publish(final String node, final Element item) {
95 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
96 final Element pubsub = packet.addChild("pubsub",
97 "http://jabber.org/protocol/pubsub");
98 final Element publish = pubsub.addChild("publish");
99 publish.setAttribute("node", node);
100 publish.addChild(item);
101 return packet;
102 }
103
104 protected IqPacket retrieve(String node, Element item) {
105 final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
106 final Element pubsub = packet.addChild("pubsub",
107 "http://jabber.org/protocol/pubsub");
108 final Element items = pubsub.addChild("items");
109 items.setAttribute("node", node);
110 if (item != null) {
111 items.addChild(item);
112 }
113 return packet;
114 }
115
116 public IqPacket publishNick(String nick) {
117 final Element item = new Element("item");
118 item.addChild("nick","http://jabber.org/protocol/nick").setContent(nick);
119 return publish("http://jabber.org/protocol/nick", item);
120 }
121
122 public IqPacket publishAvatar(Avatar avatar) {
123 final Element item = new Element("item");
124 item.setAttribute("id", avatar.sha1sum);
125 final Element data = item.addChild("data", "urn:xmpp:avatar:data");
126 data.setContent(avatar.image);
127 return publish("urn:xmpp:avatar:data", item);
128 }
129
130 public IqPacket publishAvatarMetadata(final Avatar avatar) {
131 final Element item = new Element("item");
132 item.setAttribute("id", avatar.sha1sum);
133 final Element metadata = item
134 .addChild("metadata", "urn:xmpp:avatar:metadata");
135 final Element info = metadata.addChild("info");
136 info.setAttribute("bytes", avatar.size);
137 info.setAttribute("id", avatar.sha1sum);
138 info.setAttribute("height", avatar.height);
139 info.setAttribute("width", avatar.height);
140 info.setAttribute("type", avatar.type);
141 return publish("urn:xmpp:avatar:metadata", item);
142 }
143
144 public IqPacket retrievePepAvatar(final Avatar avatar) {
145 final Element item = new Element("item");
146 item.setAttribute("id", avatar.sha1sum);
147 final IqPacket packet = retrieve("urn:xmpp:avatar:data", item);
148 packet.setTo(avatar.owner);
149 return packet;
150 }
151
152 public IqPacket retrieveVcardAvatar(final Avatar avatar) {
153 final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
154 packet.setTo(avatar.owner);
155 packet.addChild("vCard", "vcard-temp");
156 return packet;
157 }
158
159 public IqPacket retrieveAvatarMetaData(final Jid to) {
160 final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
161 if (to != null) {
162 packet.setTo(to);
163 }
164 return packet;
165 }
166
167 public IqPacket retrieveDeviceIds(final Jid to) {
168 final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
169 if(to != null) {
170 packet.setTo(to);
171 }
172 return packet;
173 }
174
175 public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
176 final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES+":"+deviceid, null);
177 packet.setTo(to);
178 return packet;
179 }
180
181 public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
182 final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION+":"+deviceid, null);
183 packet.setTo(to);
184 return packet;
185 }
186
187 public IqPacket publishDeviceIds(final Set<Integer> ids) {
188 final Element item = new Element("item");
189 final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
190 for(Integer id:ids) {
191 final Element device = new Element("device");
192 device.setAttribute("id", id);
193 list.addChild(device);
194 }
195 return publish(AxolotlService.PEP_DEVICE_LIST, item);
196 }
197
198 public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
199 final Set<PreKeyRecord> preKeyRecords, final int deviceId) {
200 final Element item = new Element("item");
201 final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
202 final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
203 signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
204 ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
205 signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(),Base64.DEFAULT));
206 final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
207 signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(),Base64.DEFAULT));
208 final Element identityKeyElement = bundle.addChild("identityKey");
209 identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT));
210
211 final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
212 for(PreKeyRecord preKeyRecord:preKeyRecords) {
213 final Element prekey = prekeys.addChild("preKeyPublic");
214 prekey.setAttribute("preKeyId", preKeyRecord.getId());
215 prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.DEFAULT));
216 }
217
218 return publish(AxolotlService.PEP_BUNDLES+":"+deviceId, item);
219 }
220
221 public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
222 final Element item = new Element("item");
223 final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
224 final Element chain = verification.addChild("chain");
225 for(int i = 0; i < certificates.length; ++i) {
226 try {
227 Element certificate = chain.addChild("certificate");
228 certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.DEFAULT));
229 certificate.setAttribute("index",i);
230 } catch (CertificateEncodingException e) {
231 Log.d(Config.LOGTAG, "could not encode certificate");
232 }
233 }
234 verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.DEFAULT));
235 return publish(AxolotlService.PEP_VERIFICATION+":"+deviceId, item);
236 }
237
238 public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
239 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
240 final Element query = packet.query(mam.isLegacy() ? Namespace.MAM_LEGACY : Namespace.MAM);
241 query.setAttribute("queryid", mam.getQueryId());
242 final Data data = new Data();
243 data.setFormType(mam.isLegacy() ? Namespace.MAM_LEGACY : Namespace.MAM);
244 if (mam.muc()) {
245 packet.setTo(mam.getWith());
246 } else if (mam.getWith()!=null) {
247 data.put("with", mam.getWith().toString());
248 }
249 data.put("start", getTimestamp(mam.getStart()));
250 data.put("end", getTimestamp(mam.getEnd()));
251 data.submit();
252 query.addChild(data);
253 Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
254 if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
255 set.addChild("before").setContent(mam.getReference());
256 } else if (mam.getReference() != null) {
257 set.addChild("after").setContent(mam.getReference());
258 }
259 set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
260 return packet;
261 }
262 public IqPacket generateGetBlockList() {
263 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
264 iq.addChild("blocklist", Namespace.BLOCKING);
265
266 return iq;
267 }
268
269 public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
270 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
271 final Element block = iq.addChild("block", Namespace.BLOCKING);
272 final Element item = block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
273 if (reportSpam) {
274 item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
275 }
276 Log.d(Config.LOGTAG,iq.toString());
277 return iq;
278 }
279
280 public IqPacket generateSetUnblockRequest(final Jid jid) {
281 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
282 final Element block = iq.addChild("unblock", Namespace.BLOCKING);
283 block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
284 return iq;
285 }
286
287 public IqPacket generateSetPassword(final Account account, final String newPassword) {
288 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
289 packet.setTo(account.getServer());
290 final Element query = packet.addChild("query", Namespace.REGISTER);
291 final Jid jid = account.getJid();
292 query.addChild("username").setContent(jid.getLocalpart());
293 query.addChild("password").setContent(newPassword);
294 return packet;
295 }
296
297 public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
298 List<Jid> jids = new ArrayList<>();
299 jids.add(jid);
300 return changeAffiliation(conference,jids,affiliation);
301 }
302
303 public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
304 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
305 packet.setTo(conference.getJid().toBareJid());
306 packet.setFrom(conference.getAccount().getJid());
307 Element query = packet.query("http://jabber.org/protocol/muc#admin");
308 for(Jid jid : jids) {
309 Element item = query.addChild("item");
310 item.setAttribute("jid", jid.toString());
311 item.setAttribute("affiliation", affiliation);
312 }
313 return packet;
314 }
315
316 public IqPacket changeRole(Conversation conference, String nick, String role) {
317 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
318 packet.setTo(conference.getJid().toBareJid());
319 packet.setFrom(conference.getAccount().getJid());
320 Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
321 item.setAttribute("nick", nick);
322 item.setAttribute("role", role);
323 return packet;
324 }
325
326 public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String mime) {
327 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
328 packet.setTo(host);
329 Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
330 request.addChild("filename").setContent(convertFilename(file.getName()));
331 request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
332 if (mime != null) {
333 request.addChild("content-type").setContent(mime);
334 }
335 return packet;
336 }
337
338 private static String convertFilename(String name) {
339 int pos = name.indexOf('.');
340 if (pos != -1) {
341 try {
342 UUID uuid = UUID.fromString(name.substring(0, pos));
343 ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
344 bb.putLong(uuid.getMostSignificantBits());
345 bb.putLong(uuid.getLeastSignificantBits());
346 return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos, name.length());
347 } catch (Exception e) {
348 return name;
349 }
350 } else {
351 return name;
352 }
353 }
354
355 public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
356 final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
357 register.setFrom(account.getJid().toBareJid());
358 register.setTo(account.getServer());
359 register.setId(id);
360 Element query = register.query("jabber:iq:register");
361 if (data != null) {
362 query.addChild(data);
363 }
364 return register;
365 }
366
367 public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
368 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
369 packet.setTo(appServer);
370 Element command = packet.addChild("command", "http://jabber.org/protocol/commands");
371 command.setAttribute("node","register-push-gcm");
372 command.setAttribute("action","execute");
373 Data data = new Data();
374 data.put("token", token);
375 data.put("device-id", deviceId);
376 data.submit();
377 command.addChild(data);
378 return packet;
379 }
380
381 public IqPacket enablePush(Jid jid, String node, String secret) {
382 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
383 Element enable = packet.addChild("enable","urn:xmpp:push:0");
384 enable.setAttribute("jid",jid.toString());
385 enable.setAttribute("node", node);
386 Data data = new Data();
387 data.setFormType("http://jabber.org/protocol/pubsub#publish-options");
388 data.put("secret",secret);
389 data.submit();
390 enable.addChild(data);
391 return packet;
392 }
393
394 public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
395 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
396 packet.setTo(conversation.getJid().toBareJid());
397 packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation",affiliation);
398 return packet;
399 }
400
401 public static Bundle defaultRoomConfiguration() {
402 Bundle options = new Bundle();
403 options.putString("muc#roomconfig_persistentroom", "1");
404 options.putString("muc#roomconfig_membersonly", "1");
405 options.putString("muc#roomconfig_publicroom", "0");
406 options.putString("muc#roomconfig_whois", "anyone");
407 return options;
408 }
409
410 public IqPacket requestPubsubConfiguration(Jid jid, String node) {
411 return pubsubConfiguration(jid, node, null);
412 }
413
414 public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
415 return pubsubConfiguration(jid,node,data);
416 }
417
418 private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
419 IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
420 packet.setTo(jid);
421 Element pubsub = packet.addChild("pubsub","http://jabber.org/protocol/pubsub#owner");
422 Element configure = pubsub.addChild("configure").setAttribute("node",node);
423 if (data != null) {
424 configure.addChild(data);
425 }
426 return packet;
427 }
428}