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