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