1package eu.siacs.conversations.generator;
2
3
4import android.os.Bundle;
5import android.util.Base64;
6import android.util.Log;
7
8import org.whispersystems.libsignal.IdentityKey;
9import org.whispersystems.libsignal.ecc.ECPublicKey;
10import org.whispersystems.libsignal.state.PreKeyRecord;
11import org.whispersystems.libsignal.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.Bookmark;
28import eu.siacs.conversations.entities.Conversation;
29import eu.siacs.conversations.entities.DownloadableFile;
30import eu.siacs.conversations.services.MessageArchiveService;
31import eu.siacs.conversations.services.XmppConnectionService;
32import eu.siacs.conversations.xml.Namespace;
33import eu.siacs.conversations.xml.Element;
34import eu.siacs.conversations.xmpp.forms.Data;
35import eu.siacs.conversations.xmpp.pep.Avatar;
36import eu.siacs.conversations.xmpp.stanzas.IqPacket;
37import rocks.xmpp.addr.Jid;
38
39public class IqGenerator extends AbstractGenerator {
40
41 public IqGenerator(final XmppConnectionService service) {
42 super(service);
43 }
44
45 public IqPacket discoResponse(final Account account, final IqPacket request) {
46 final IqPacket packet = new IqPacket(IqPacket.TYPE.RESULT);
47 packet.setId(request.getId());
48 packet.setTo(request.getFrom());
49 final Element query = packet.addChild("query", "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(account)) {
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 public IqPacket purgeOfflineMessages() {
95 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
96 packet.addChild("offline", Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL).addChild("purge");
97 return packet;
98 }
99
100 protected IqPacket publish(final String node, final Element item, final Bundle options) {
101 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
102 final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
103 final Element publish = pubsub.addChild("publish");
104 publish.setAttribute("node", node);
105 publish.addChild(item);
106 if (options != null) {
107 final Element publishOptions = pubsub.addChild("publish-options");
108 publishOptions.addChild(Data.create(Namespace.PUBSUB_PUBLISH_OPTIONS, options));
109 }
110 return packet;
111 }
112
113 protected IqPacket publish(final String node, final Element item) {
114 return publish(node, item, null);
115 }
116
117 private IqPacket retrieve(String node, Element item) {
118 final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
119 final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
120 final Element items = pubsub.addChild("items");
121 items.setAttribute("node", node);
122 if (item != null) {
123 items.addChild(item);
124 }
125 return packet;
126 }
127
128 public IqPacket retrieveBookmarks() {
129 return retrieve(Namespace.BOOKMARK, null);
130 }
131
132 public IqPacket publishNick(String nick) {
133 final Element item = new Element("item");
134 item.addChild("nick", Namespace.NICK).setContent(nick);
135 return publish(Namespace.NICK, item);
136 }
137
138 public IqPacket deleteNode(String node) {
139 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
140 final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB_OWNER);
141 pubsub.addChild("delete").setAttribute("node", node);
142 return packet;
143 }
144
145 public IqPacket deleteItem(final String node, final String id) {
146 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
147 final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
148 final Element retract = pubsub.addChild("retract");
149 retract.setAttribute("node", node);
150 retract.addChild("item").setAttribute("id", id);
151 return packet;
152 }
153
154 public IqPacket publishAvatar(Avatar avatar, Bundle options) {
155 final Element item = new Element("item");
156 item.setAttribute("id", avatar.sha1sum);
157 final Element data = item.addChild("data", "urn:xmpp:avatar:data");
158 data.setContent(avatar.image);
159 return publish("urn:xmpp:avatar:data", item, options);
160 }
161
162 public IqPacket publishElement(final String namespace, final Element element, final Bundle options) {
163 return publishElement(namespace, element, "curent", options);
164 }
165
166 public IqPacket publishElement(final String namespace, final Element element, String id, final Bundle options) {
167 final Element item = new Element("item");
168 item.setAttribute("id", id);
169 item.addChild(element);
170 return publish(namespace, item, options);
171 }
172
173 public IqPacket publishAvatarMetadata(final Avatar avatar, final Bundle options) {
174 final Element item = new Element("item");
175 item.setAttribute("id", avatar.sha1sum);
176 final Element metadata = item
177 .addChild("metadata", "urn:xmpp:avatar:metadata");
178 final Element info = metadata.addChild("info");
179 info.setAttribute("bytes", avatar.size);
180 info.setAttribute("id", avatar.sha1sum);
181 info.setAttribute("height", avatar.height);
182 info.setAttribute("width", avatar.height);
183 info.setAttribute("type", avatar.type);
184 return publish("urn:xmpp:avatar:metadata", item, options);
185 }
186
187 public IqPacket retrievePepAvatar(final Avatar avatar) {
188 final Element item = new Element("item");
189 item.setAttribute("id", avatar.sha1sum);
190 final IqPacket packet = retrieve("urn:xmpp:avatar:data", item);
191 packet.setTo(avatar.owner);
192 return packet;
193 }
194
195 public IqPacket retrieveVcardAvatar(final Avatar avatar) {
196 final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
197 packet.setTo(avatar.owner);
198 packet.addChild("vCard", "vcard-temp");
199 return packet;
200 }
201
202 public IqPacket retrieveAvatarMetaData(final Jid to) {
203 final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
204 if (to != null) {
205 packet.setTo(to);
206 }
207 return packet;
208 }
209
210 public IqPacket retrieveDeviceIds(final Jid to) {
211 final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
212 if (to != null) {
213 packet.setTo(to);
214 }
215 return packet;
216 }
217
218 public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
219 final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES + ":" + deviceid, null);
220 packet.setTo(to);
221 return packet;
222 }
223
224 public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
225 final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION + ":" + deviceid, null);
226 packet.setTo(to);
227 return packet;
228 }
229
230 public IqPacket publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
231 final Element item = new Element("item");
232 item.setAttribute("id", "current");
233 final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
234 for (Integer id : ids) {
235 final Element device = new Element("device");
236 device.setAttribute("id", id);
237 list.addChild(device);
238 }
239 return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
240 }
241
242 public Element publishBookmarkItem(final Bookmark bookmark) {
243 final String name = bookmark.getBookmarkName();
244 final String nick = bookmark.getNick();
245 final Element conference = new Element("conference", Namespace.BOOKMARK);
246 if (name != null) {
247 conference.setAttribute("name", name);
248 }
249 if (nick != null) {
250 conference.addChild("nick").setContent(nick);
251 }
252 return conference;
253 }
254
255 public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
256 final Set<PreKeyRecord> preKeyRecords, final int deviceId, Bundle publishOptions) {
257 final Element item = new Element("item");
258 item.setAttribute("id", "current");
259 final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
260 final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
261 signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
262 ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
263 signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(), Base64.DEFAULT));
264 final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
265 signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(), Base64.DEFAULT));
266 final Element identityKeyElement = bundle.addChild("identityKey");
267 identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT));
268
269 final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
270 for (PreKeyRecord preKeyRecord : preKeyRecords) {
271 final Element prekey = prekeys.addChild("preKeyPublic");
272 prekey.setAttribute("preKeyId", preKeyRecord.getId());
273 prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.DEFAULT));
274 }
275
276 return publish(AxolotlService.PEP_BUNDLES + ":" + deviceId, item, publishOptions);
277 }
278
279 public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
280 final Element item = new Element("item");
281 item.setAttribute("id", "current");
282 final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
283 final Element chain = verification.addChild("chain");
284 for (int i = 0; i < certificates.length; ++i) {
285 try {
286 Element certificate = chain.addChild("certificate");
287 certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.DEFAULT));
288 certificate.setAttribute("index", i);
289 } catch (CertificateEncodingException e) {
290 Log.d(Config.LOGTAG, "could not encode certificate");
291 }
292 }
293 verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.DEFAULT));
294 return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
295 }
296
297 public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
298 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
299 final Element query = packet.query(mam.version.namespace);
300 query.setAttribute("queryid", mam.getQueryId());
301 final Data data = new Data();
302 data.setFormType(mam.version.namespace);
303 if (mam.muc()) {
304 packet.setTo(mam.getWith());
305 } else if (mam.getWith() != null) {
306 data.put("with", mam.getWith().toString());
307 }
308 final long start = mam.getStart();
309 final long end = mam.getEnd();
310 if (start != 0) {
311 data.put("start", getTimestamp(start));
312 }
313 if (end != 0) {
314 data.put("end", getTimestamp(end));
315 }
316 data.submit();
317 query.addChild(data);
318 Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
319 if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
320 set.addChild("before").setContent(mam.getReference());
321 } else if (mam.getReference() != null) {
322 set.addChild("after").setContent(mam.getReference());
323 }
324 set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
325 return packet;
326 }
327
328 public IqPacket generateGetBlockList() {
329 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
330 iq.addChild("blocklist", Namespace.BLOCKING);
331
332 return iq;
333 }
334
335 public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
336 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
337 final Element block = iq.addChild("block", Namespace.BLOCKING);
338 final Element item = block.addChild("item").setAttribute("jid", jid.toEscapedString());
339 if (reportSpam) {
340 item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
341 }
342 Log.d(Config.LOGTAG, iq.toString());
343 return iq;
344 }
345
346 public IqPacket generateSetUnblockRequest(final Jid jid) {
347 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
348 final Element block = iq.addChild("unblock", Namespace.BLOCKING);
349 block.addChild("item").setAttribute("jid", jid.toEscapedString());
350 return iq;
351 }
352
353 public IqPacket generateSetPassword(final Account account, final String newPassword) {
354 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
355 packet.setTo(Jid.of(account.getServer()));
356 final Element query = packet.addChild("query", Namespace.REGISTER);
357 final Jid jid = account.getJid();
358 query.addChild("username").setContent(jid.getLocal());
359 query.addChild("password").setContent(newPassword);
360 return packet;
361 }
362
363 public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
364 List<Jid> jids = new ArrayList<>();
365 jids.add(jid);
366 return changeAffiliation(conference, jids, affiliation);
367 }
368
369 public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
370 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
371 packet.setTo(conference.getJid().asBareJid());
372 packet.setFrom(conference.getAccount().getJid());
373 Element query = packet.query("http://jabber.org/protocol/muc#admin");
374 for (Jid jid : jids) {
375 Element item = query.addChild("item");
376 item.setAttribute("jid", jid.toEscapedString());
377 item.setAttribute("affiliation", affiliation);
378 }
379 return packet;
380 }
381
382 public IqPacket changeRole(Conversation conference, String nick, String role) {
383 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
384 packet.setTo(conference.getJid().asBareJid());
385 packet.setFrom(conference.getAccount().getJid());
386 Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
387 item.setAttribute("nick", nick);
388 item.setAttribute("role", role);
389 return packet;
390 }
391
392 public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String mime) {
393 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
394 packet.setTo(host);
395 Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
396 request.setAttribute("filename", convertFilename(file.getName()));
397 request.setAttribute("size", file.getExpectedSize());
398 request.setAttribute("content-type", mime);
399 return packet;
400 }
401
402 public IqPacket requestHttpUploadLegacySlot(Jid host, DownloadableFile file, String mime) {
403 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
404 packet.setTo(host);
405 Element request = packet.addChild("request", Namespace.HTTP_UPLOAD_LEGACY);
406 request.addChild("filename").setContent(convertFilename(file.getName()));
407 request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
408 request.addChild("content-type").setContent(mime);
409 return packet;
410 }
411
412 public IqPacket requestP1S3Slot(Jid host, String md5) {
413 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
414 packet.setTo(host);
415 packet.query(Namespace.P1_S3_FILE_TRANSFER).setAttribute("md5", md5);
416 return packet;
417 }
418
419 public IqPacket requestP1S3Url(Jid host, String fileId) {
420 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
421 packet.setTo(host);
422 packet.query(Namespace.P1_S3_FILE_TRANSFER).setAttribute("fileid", fileId);
423 return packet;
424 }
425
426 private static String convertFilename(String name) {
427 int pos = name.indexOf('.');
428 if (pos != -1) {
429 try {
430 UUID uuid = UUID.fromString(name.substring(0, pos));
431 ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
432 bb.putLong(uuid.getMostSignificantBits());
433 bb.putLong(uuid.getLeastSignificantBits());
434 return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos, name.length());
435 } catch (Exception e) {
436 return name;
437 }
438 } else {
439 return name;
440 }
441 }
442
443 public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
444 final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
445 register.setFrom(account.getJid().asBareJid());
446 register.setTo(Jid.of(account.getServer()));
447 register.setId(id);
448 Element query = register.query(Namespace.REGISTER);
449 if (data != null) {
450 query.addChild(data);
451 }
452 return register;
453 }
454
455 public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
456 return pushTokenToAppServer(appServer, token, deviceId, null);
457 }
458
459 public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId, Jid muc) {
460 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
461 packet.setTo(appServer);
462 final Element command = packet.addChild("command", Namespace.COMMANDS);
463 command.setAttribute("node", "register-push-fcm");
464 command.setAttribute("action", "execute");
465 final Data data = new Data();
466 data.put("token", token);
467 data.put("android-id", deviceId);
468 if (muc != null) {
469 data.put("muc", muc.toEscapedString());
470 }
471 data.submit();
472 command.addChild(data);
473 return packet;
474 }
475
476 public IqPacket unregisterChannelOnAppServer(Jid appServer, String deviceId, String channel) {
477 final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
478 packet.setTo(appServer);
479 final Element command = packet.addChild("command", Namespace.COMMANDS);
480 command.setAttribute("node", "unregister-push-fcm");
481 command.setAttribute("action", "execute");
482 final Data data = new Data();
483 data.put("channel", channel);
484 data.put("android-id", deviceId);
485 data.submit();
486 command.addChild(data);
487 return packet;
488 }
489
490 public IqPacket enablePush(final Jid jid, final String node, final String secret) {
491 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
492 Element enable = packet.addChild("enable", Namespace.PUSH);
493 enable.setAttribute("jid", jid.toString());
494 enable.setAttribute("node", node);
495 if (secret != null) {
496 Data data = new Data();
497 data.setFormType(Namespace.PUBSUB_PUBLISH_OPTIONS);
498 data.put("secret", secret);
499 data.submit();
500 enable.addChild(data);
501 }
502 return packet;
503 }
504
505 public IqPacket disablePush(final Jid jid, final String node) {
506 IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
507 Element disable = packet.addChild("disable", Namespace.PUSH);
508 disable.setAttribute("jid", jid.toEscapedString());
509 disable.setAttribute("node", node);
510 return packet;
511 }
512
513 public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
514 IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
515 packet.setTo(conversation.getJid().asBareJid());
516 packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation", affiliation);
517 return packet;
518 }
519
520 public static Bundle defaultGroupChatConfiguration() {
521 Bundle options = new Bundle();
522 options.putString("muc#roomconfig_persistentroom", "1");
523 options.putString("muc#roomconfig_membersonly", "1");
524 options.putString("muc#roomconfig_publicroom", "0");
525 options.putString("muc#roomconfig_whois", "anyone");
526 options.putString("muc#roomconfig_changesubject", "0");
527 options.putString("muc#roomconfig_allowinvites", "0");
528 options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
529 options.putString("mam", "1"); //ejabberd community
530 options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
531 return options;
532 }
533
534 public static Bundle defaultChannelConfiguration() {
535 Bundle options = new Bundle();
536 options.putString("muc#roomconfig_persistentroom", "1");
537 options.putString("muc#roomconfig_membersonly", "0");
538 options.putString("muc#roomconfig_publicroom", "1");
539 options.putString("muc#roomconfig_whois", "moderators");
540 options.putString("muc#roomconfig_changesubject", "0");
541 options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
542 options.putString("mam", "1"); //ejabberd community
543 options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
544 return options;
545 }
546
547 public IqPacket requestPubsubConfiguration(Jid jid, String node) {
548 return pubsubConfiguration(jid, node, null);
549 }
550
551 public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
552 return pubsubConfiguration(jid, node, data);
553 }
554
555 private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
556 IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
557 packet.setTo(jid);
558 Element pubsub = packet.addChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
559 Element configure = pubsub.addChild("configure").setAttribute("node", node);
560 if (data != null) {
561 configure.addChild(data);
562 }
563 return packet;
564 }
565}