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