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