IqGenerator.java

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