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