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		if (mam.getStart() != 0) {
250			data.put("start", getTimestamp(mam.getStart()));
251		}
252		data.put("end", getTimestamp(mam.getEnd()));
253		data.submit();
254		query.addChild(data);
255		Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
256		if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
257			set.addChild("before").setContent(mam.getReference());
258		} else if (mam.getReference() != null) {
259			set.addChild("after").setContent(mam.getReference());
260		}
261		set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
262		return packet;
263	}
264	public IqPacket generateGetBlockList() {
265		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
266		iq.addChild("blocklist", Namespace.BLOCKING);
267
268		return iq;
269	}
270
271	public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
272		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
273		final Element block = iq.addChild("block", Namespace.BLOCKING);
274		final Element item = block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
275		if (reportSpam) {
276			item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
277		}
278		Log.d(Config.LOGTAG,iq.toString());
279		return iq;
280	}
281
282	public IqPacket generateSetUnblockRequest(final Jid jid) {
283		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
284		final Element block = iq.addChild("unblock", Namespace.BLOCKING);
285		block.addChild("item").setAttribute("jid", jid.toBareJid().toString());
286		return iq;
287	}
288
289	public IqPacket generateSetPassword(final Account account, final String newPassword) {
290		final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
291		packet.setTo(account.getServer());
292		final Element query = packet.addChild("query", Namespace.REGISTER);
293		final Jid jid = account.getJid();
294		query.addChild("username").setContent(jid.getLocalpart());
295		query.addChild("password").setContent(newPassword);
296		return packet;
297	}
298
299	public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
300		List<Jid> jids = new ArrayList<>();
301		jids.add(jid);
302		return changeAffiliation(conference,jids,affiliation);
303	}
304
305	public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
306		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
307		packet.setTo(conference.getJid().toBareJid());
308		packet.setFrom(conference.getAccount().getJid());
309		Element query = packet.query("http://jabber.org/protocol/muc#admin");
310		for(Jid jid : jids) {
311			Element item = query.addChild("item");
312			item.setAttribute("jid", jid.toString());
313			item.setAttribute("affiliation", affiliation);
314		}
315		return packet;
316	}
317
318	public IqPacket changeRole(Conversation conference, String nick, String role) {
319		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
320		packet.setTo(conference.getJid().toBareJid());
321		packet.setFrom(conference.getAccount().getJid());
322		Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
323		item.setAttribute("nick", nick);
324		item.setAttribute("role", role);
325		return packet;
326	}
327
328	public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String mime) {
329		IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
330		packet.setTo(host);
331		Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
332		request.addChild("filename").setContent(convertFilename(file.getName()));
333		request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
334		if (mime != null) {
335			request.addChild("content-type").setContent(mime);
336		}
337		return packet;
338	}
339
340	private static String convertFilename(String name) {
341		int pos = name.indexOf('.');
342		if (pos != -1) {
343			try {
344				UUID uuid = UUID.fromString(name.substring(0, pos));
345				ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
346				bb.putLong(uuid.getMostSignificantBits());
347				bb.putLong(uuid.getLeastSignificantBits());
348				return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos, name.length());
349			} catch (Exception e) {
350				return name;
351			}
352		} else {
353			return name;
354		}
355	}
356
357	public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
358		final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
359		register.setFrom(account.getJid().toBareJid());
360		register.setTo(account.getServer());
361		register.setId(id);
362		Element query = register.query("jabber:iq:register");
363		if (data != null) {
364			query.addChild(data);
365		}
366		return register;
367	}
368
369	public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
370		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
371		packet.setTo(appServer);
372		Element command = packet.addChild("command", "http://jabber.org/protocol/commands");
373		command.setAttribute("node","register-push-gcm");
374		command.setAttribute("action","execute");
375		Data data = new Data();
376		data.put("token", token);
377		data.put("device-id", deviceId);
378		data.submit();
379		command.addChild(data);
380		return packet;
381	}
382
383	public IqPacket enablePush(Jid jid, String node, String secret) {
384		IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
385		Element enable = packet.addChild("enable","urn:xmpp:push:0");
386		enable.setAttribute("jid",jid.toString());
387		enable.setAttribute("node", node);
388		Data data = new Data();
389		data.setFormType("http://jabber.org/protocol/pubsub#publish-options");
390		data.put("secret",secret);
391		data.submit();
392		enable.addChild(data);
393		return packet;
394	}
395
396	public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
397		IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
398		packet.setTo(conversation.getJid().toBareJid());
399		packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation",affiliation);
400		return packet;
401	}
402
403	public static Bundle defaultRoomConfiguration() {
404		Bundle options = new Bundle();
405		options.putString("muc#roomconfig_persistentroom", "1");
406		options.putString("muc#roomconfig_membersonly", "1");
407		options.putString("muc#roomconfig_publicroom", "0");
408		options.putString("muc#roomconfig_whois", "anyone");
409		return options;
410	}
411
412	public IqPacket requestPubsubConfiguration(Jid jid, String node) {
413		return pubsubConfiguration(jid, node, null);
414	}
415
416	public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
417		return pubsubConfiguration(jid,node,data);
418	}
419
420	private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
421		IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
422		packet.setTo(jid);
423		Element pubsub = packet.addChild("pubsub","http://jabber.org/protocol/pubsub#owner");
424		Element configure = pubsub.addChild("configure").setAttribute("node",node);
425		if (data != null) {
426			configure.addChild(data);
427		}
428		return packet;
429	}
430}