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.Conversation;
 28import eu.siacs.conversations.entities.DownloadableFile;
 29import eu.siacs.conversations.services.MessageArchiveService;
 30import eu.siacs.conversations.services.XmppConnectionService;
 31import eu.siacs.conversations.xml.Namespace;
 32import eu.siacs.conversations.xml.Element;
 33import eu.siacs.conversations.xmpp.forms.Data;
 34import eu.siacs.conversations.xmpp.jid.Jid;
 35import eu.siacs.conversations.xmpp.pep.Avatar;
 36import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 37
 38public class IqGenerator extends AbstractGenerator {
 39
 40	public IqGenerator(final XmppConnectionService service) {
 41		super(service);
 42	}
 43
 44	public IqPacket discoResponse(final IqPacket request) {
 45		final IqPacket packet = new IqPacket(IqPacket.TYPE.RESULT);
 46		packet.setId(request.getId());
 47		packet.setTo(request.getFrom());
 48		final Element query = packet.addChild("query",
 49				"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()) {
 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	protected IqPacket publish(final String node, final Element item, final Bundle options) {
 95		final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
 96		final Element pubsub = packet.addChild("pubsub",
 97				"http://jabber.org/protocol/pubsub");
 98		final Element publish = pubsub.addChild("publish");
 99		publish.setAttribute("node", node);
100		publish.addChild(item);
101		if (options != null) {
102			final Element publishOptions = pubsub.addChild("publish-options");
103			publishOptions.addChild(Data.create(Namespace.PUBSUB_PUBLISH_OPTIONS, options));
104		}
105		return packet;
106	}
107
108	protected IqPacket publish(final String node, final Element item) {
109		return publish(node,item,null);
110	}
111
112	protected IqPacket retrieve(String node, Element item) {
113		final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
114		final Element pubsub = packet.addChild("pubsub",
115				"http://jabber.org/protocol/pubsub");
116		final Element items = pubsub.addChild("items");
117		items.setAttribute("node", node);
118		if (item != null) {
119			items.addChild(item);
120		}
121		return packet;
122	}
123
124	public IqPacket publishNick(String nick) {
125		final Element item = new Element("item");
126		item.addChild("nick","http://jabber.org/protocol/nick").setContent(nick);
127		return publish("http://jabber.org/protocol/nick", item);
128	}
129
130	public IqPacket publishAvatar(Avatar avatar) {
131		final Element item = new Element("item");
132		item.setAttribute("id", avatar.sha1sum);
133		final Element data = item.addChild("data", "urn:xmpp:avatar:data");
134		data.setContent(avatar.image);
135		return publish("urn:xmpp:avatar:data", item);
136	}
137
138	public IqPacket publishAvatarMetadata(final Avatar avatar) {
139		final Element item = new Element("item");
140		item.setAttribute("id", avatar.sha1sum);
141		final Element metadata = item
142			.addChild("metadata", "urn:xmpp:avatar:metadata");
143		final Element info = metadata.addChild("info");
144		info.setAttribute("bytes", avatar.size);
145		info.setAttribute("id", avatar.sha1sum);
146		info.setAttribute("height", avatar.height);
147		info.setAttribute("width", avatar.height);
148		info.setAttribute("type", avatar.type);
149		return publish("urn:xmpp:avatar:metadata", item);
150	}
151
152	public IqPacket retrievePepAvatar(final Avatar avatar) {
153		final Element item = new Element("item");
154		item.setAttribute("id", avatar.sha1sum);
155		final IqPacket packet = retrieve("urn:xmpp:avatar:data", item);
156		packet.setTo(avatar.owner);
157		return packet;
158	}
159
160	public IqPacket retrieveVcardAvatar(final Avatar avatar) {
161		final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
162		packet.setTo(avatar.owner);
163		packet.addChild("vCard", "vcard-temp");
164		return packet;
165	}
166
167	public IqPacket retrieveAvatarMetaData(final Jid to) {
168		final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
169		if (to != null) {
170			packet.setTo(to);
171		}
172		return packet;
173	}
174
175	public IqPacket retrieveDeviceIds(final Jid to) {
176		final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
177		if(to != null) {
178			packet.setTo(to);
179		}
180		return packet;
181	}
182
183	public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
184		final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES+":"+deviceid, null);
185		packet.setTo(to);
186		return packet;
187	}
188
189	public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
190		final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION+":"+deviceid, null);
191		packet.setTo(to);
192		return packet;
193	}
194
195	public IqPacket publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
196		final Element item = new Element("item");
197		final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
198		for(Integer id:ids) {
199			final Element device = new Element("device");
200			device.setAttribute("id", id);
201			list.addChild(device);
202		}
203		return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
204	}
205
206	public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
207								   final Set<PreKeyRecord> preKeyRecords, final int deviceId, Bundle publishOptions) {
208		final Element item = new Element("item");
209		final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
210		final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
211		signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
212		ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
213		signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(),Base64.DEFAULT));
214		final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
215		signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(),Base64.DEFAULT));
216		final Element identityKeyElement = bundle.addChild("identityKey");
217		identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT));
218
219		final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
220		for(PreKeyRecord preKeyRecord:preKeyRecords) {
221			final Element prekey = prekeys.addChild("preKeyPublic");
222			prekey.setAttribute("preKeyId", preKeyRecord.getId());
223			prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.DEFAULT));
224		}
225
226		return publish(AxolotlService.PEP_BUNDLES+":"+deviceId, item, publishOptions);
227	}
228
229	public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
230		final Element item = new Element("item");
231		final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
232		final Element chain = verification.addChild("chain");
233		for(int i = 0; i < certificates.length; ++i) {
234			try {
235				Element certificate = chain.addChild("certificate");
236				certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.DEFAULT));
237				certificate.setAttribute("index",i);
238			} catch (CertificateEncodingException e) {
239				Log.d(Config.LOGTAG, "could not encode certificate");
240			}
241		}
242		verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.DEFAULT));
243		return publish(AxolotlService.PEP_VERIFICATION+":"+deviceId, item);
244	}
245
246	public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
247		final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
248		final Element query = packet.query(mam.isLegacy() ? Namespace.MAM_LEGACY : Namespace.MAM);
249		query.setAttribute("queryid", mam.getQueryId());
250		final Data data = new Data();
251		data.setFormType(mam.isLegacy() ? Namespace.MAM_LEGACY : Namespace.MAM);
252		if (mam.muc()) {
253			packet.setTo(mam.getWith());
254		} else if (mam.getWith()!=null) {
255			data.put("with", mam.getWith().toString());
256		}
257		if (mam.getStart() != 0) {
258			data.put("start", getTimestamp(mam.getStart()));
259		}
260		data.put("end", getTimestamp(mam.getEnd()));
261		data.submit();
262		query.addChild(data);
263		Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
264		if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
265			set.addChild("before").setContent(mam.getReference());
266		} else if (mam.getReference() != null) {
267			set.addChild("after").setContent(mam.getReference());
268		}
269		set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
270		return packet;
271	}
272	public IqPacket generateGetBlockList() {
273		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
274		iq.addChild("blocklist", Namespace.BLOCKING);
275
276		return iq;
277	}
278
279	public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
280		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
281		final Element block = iq.addChild("block", Namespace.BLOCKING);
282		final Element item = block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
283		if (reportSpam) {
284			item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
285		}
286		Log.d(Config.LOGTAG,iq.toString());
287		return iq;
288	}
289
290	public IqPacket generateSetUnblockRequest(final Jid jid) {
291		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
292		final Element block = iq.addChild("unblock", Namespace.BLOCKING);
293		block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
294		return iq;
295	}
296
297	public IqPacket generateSetPassword(final Account account, final String newPassword) {
298		final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
299		packet.setTo(account.getServer());
300		final Element query = packet.addChild("query", Namespace.REGISTER);
301		final Jid jid = account.getJid();
302		query.addChild("username").setContent(jid.getLocalpart());
303		query.addChild("password").setContent(newPassword);
304		return packet;
305	}
306
307	public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
308		List<Jid> jids = new ArrayList<>();
309		jids.add(jid);
310		return changeAffiliation(conference,jids,affiliation);
311	}
312
313	public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
314		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
315		packet.setTo(conference.getJid().toBareJid());
316		packet.setFrom(conference.getAccount().getJid());
317		Element query = packet.query("http://jabber.org/protocol/muc#admin");
318		for(Jid jid : jids) {
319			Element item = query.addChild("item");
320			item.setAttribute("jid", jid.toString());
321			item.setAttribute("affiliation", affiliation);
322		}
323		return packet;
324	}
325
326	public IqPacket changeRole(Conversation conference, String nick, String role) {
327		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
328		packet.setTo(conference.getJid().toBareJid());
329		packet.setFrom(conference.getAccount().getJid());
330		Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
331		item.setAttribute("nick", nick);
332		item.setAttribute("role", role);
333		return packet;
334	}
335
336	public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String mime) {
337		IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
338		packet.setTo(host);
339		Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
340		request.addChild("filename").setContent(convertFilename(file.getName()));
341		request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
342		if (mime != null) {
343			request.addChild("content-type").setContent(mime);
344		}
345		return packet;
346	}
347
348	private static String convertFilename(String name) {
349		int pos = name.indexOf('.');
350		if (pos != -1) {
351			try {
352				UUID uuid = UUID.fromString(name.substring(0, pos));
353				ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
354				bb.putLong(uuid.getMostSignificantBits());
355				bb.putLong(uuid.getLeastSignificantBits());
356				return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos, name.length());
357			} catch (Exception e) {
358				return name;
359			}
360		} else {
361			return name;
362		}
363	}
364
365	public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
366		final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
367		register.setFrom(account.getJid().toBareJid());
368		register.setTo(account.getServer());
369		register.setId(id);
370		Element query = register.query("jabber:iq:register");
371		if (data != null) {
372			query.addChild(data);
373		}
374		return register;
375	}
376
377	public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
378		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
379		packet.setTo(appServer);
380		Element command = packet.addChild("command", "http://jabber.org/protocol/commands");
381		command.setAttribute("node","register-push-gcm");
382		command.setAttribute("action","execute");
383		Data data = new Data();
384		data.put("token", token);
385		data.put("device-id", deviceId);
386		data.submit();
387		command.addChild(data);
388		return packet;
389	}
390
391	public IqPacket enablePush(Jid jid, String node, String secret) {
392		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
393		Element enable = packet.addChild("enable","urn:xmpp:push:0");
394		enable.setAttribute("jid",jid.toString());
395		enable.setAttribute("node", node);
396		Data data = new Data();
397		data.setFormType("http://jabber.org/protocol/pubsub#publish-options");
398		data.put("secret",secret);
399		data.submit();
400		enable.addChild(data);
401		return packet;
402	}
403
404	public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
405		IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
406		packet.setTo(conversation.getJid().toBareJid());
407		packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation",affiliation);
408		return packet;
409	}
410
411	public static Bundle defaultRoomConfiguration() {
412		Bundle options = new Bundle();
413		options.putString("muc#roomconfig_persistentroom", "1");
414		options.putString("muc#roomconfig_membersonly", "1");
415		options.putString("muc#roomconfig_publicroom", "0");
416		options.putString("muc#roomconfig_whois", "anyone");
417		options.putString("mam","1");
418		return options;
419	}
420
421	public IqPacket requestPubsubConfiguration(Jid jid, String node) {
422		return pubsubConfiguration(jid, node, null);
423	}
424
425	public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
426		return pubsubConfiguration(jid,node,data);
427	}
428
429	private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
430		IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
431		packet.setTo(jid);
432		Element pubsub = packet.addChild("pubsub","http://jabber.org/protocol/pubsub#owner");
433		Element configure = pubsub.addChild("configure").setAttribute("node",node);
434		if (data != null) {
435			configure.addChild(data);
436		}
437		return packet;
438	}
439}