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