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.Element;
 33import eu.siacs.conversations.xml.Namespace;
 34import eu.siacs.conversations.xmpp.Jid;
 35import eu.siacs.conversations.xmpp.forms.Data;
 36import eu.siacs.conversations.xmpp.pep.Avatar;
 37import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 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 retrieveBookmarks() {
129        return retrieve(Namespace.BOOKMARKS2, null);
130    }
131
132    public IqPacket publishNick(String nick) {
133        final Element item = new Element("item");
134        item.addChild("nick", Namespace.NICK).setContent(nick);
135        return publish(Namespace.NICK, item);
136    }
137
138    public IqPacket deleteNode(String node) {
139        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
140        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB_OWNER);
141        pubsub.addChild("delete").setAttribute("node", node);
142        return packet;
143    }
144
145    public IqPacket deleteItem(final String node, final String id) {
146        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
147        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
148        final Element retract = pubsub.addChild("retract");
149        retract.setAttribute("node", node);
150        retract.setAttribute("notify","true");
151        retract.addChild("item").setAttribute("id", id);
152        return packet;
153    }
154
155    public IqPacket publishAvatar(Avatar avatar, Bundle options) {
156        final Element item = new Element("item");
157        item.setAttribute("id", avatar.sha1sum);
158        final Element data = item.addChild("data", "urn:xmpp:avatar:data");
159        data.setContent(avatar.image);
160        return publish("urn:xmpp:avatar:data", item, options);
161    }
162
163    public IqPacket publishElement(final String namespace, final Element element, String id, final Bundle options) {
164        final Element item = new Element("item");
165        item.setAttribute("id", id);
166        item.addChild(element);
167        return publish(namespace, item, options);
168    }
169
170    public IqPacket publishAvatarMetadata(final Avatar avatar, final Bundle options) {
171        final Element item = new Element("item");
172        item.setAttribute("id", avatar.sha1sum);
173        final Element metadata = item
174                .addChild("metadata", "urn:xmpp:avatar:metadata");
175        final Element info = metadata.addChild("info");
176        info.setAttribute("bytes", avatar.size);
177        info.setAttribute("id", avatar.sha1sum);
178        info.setAttribute("height", avatar.height);
179        info.setAttribute("width", avatar.height);
180        info.setAttribute("type", avatar.type);
181        return publish("urn:xmpp:avatar:metadata", item, options);
182    }
183
184    public IqPacket retrievePepAvatar(final Avatar avatar) {
185        final Element item = new Element("item");
186        item.setAttribute("id", avatar.sha1sum);
187        final IqPacket packet = retrieve("urn:xmpp:avatar:data", item);
188        packet.setTo(avatar.owner);
189        return packet;
190    }
191
192    public IqPacket retrieveVcardAvatar(final Avatar avatar) {
193        final IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
194        packet.setTo(avatar.owner);
195        packet.addChild("vCard", "vcard-temp");
196        return packet;
197    }
198
199    public IqPacket retrieveAvatarMetaData(final Jid to) {
200        final IqPacket packet = retrieve("urn:xmpp:avatar:metadata", null);
201        if (to != null) {
202            packet.setTo(to);
203        }
204        return packet;
205    }
206
207    public IqPacket retrieveDeviceIds(final Jid to) {
208        final IqPacket packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
209        if (to != null) {
210            packet.setTo(to);
211        }
212        return packet;
213    }
214
215    public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) {
216        final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES + ":" + deviceid, null);
217        packet.setTo(to);
218        return packet;
219    }
220
221    public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) {
222        final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION + ":" + deviceid, null);
223        packet.setTo(to);
224        return packet;
225    }
226
227    public IqPacket publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
228        final Element item = new Element("item");
229        item.setAttribute("id", "current");
230        final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
231        for (Integer id : ids) {
232            final Element device = new Element("device");
233            device.setAttribute("id", id);
234            list.addChild(device);
235        }
236        return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
237    }
238
239    public Element publishBookmarkItem(final Bookmark bookmark) {
240        final String name = bookmark.getBookmarkName();
241        final String nick = bookmark.getNick();
242        final boolean autojoin = bookmark.autojoin();
243        final Element conference = new Element("conference", Namespace.BOOKMARKS2);
244        if (name != null) {
245            conference.setAttribute("name", name);
246        }
247        if (nick != null) {
248            conference.addChild("nick").setContent(nick);
249        }
250        conference.setAttribute("autojoin",String.valueOf(autojoin));
251        return conference;
252    }
253
254    public IqPacket publishBundles(final SignedPreKeyRecord signedPreKeyRecord, final IdentityKey identityKey,
255                                   final Set<PreKeyRecord> preKeyRecords, final int deviceId, Bundle publishOptions) {
256        final Element item = new Element("item");
257        item.setAttribute("id", "current");
258        final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
259        final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
260        signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
261        ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
262        signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(), Base64.NO_WRAP));
263        final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
264        signedPreKeySignature.setContent(Base64.encodeToString(signedPreKeyRecord.getSignature(), Base64.NO_WRAP));
265        final Element identityKeyElement = bundle.addChild("identityKey");
266        identityKeyElement.setContent(Base64.encodeToString(identityKey.serialize(), Base64.NO_WRAP));
267
268        final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
269        for (PreKeyRecord preKeyRecord : preKeyRecords) {
270            final Element prekey = prekeys.addChild("preKeyPublic");
271            prekey.setAttribute("preKeyId", preKeyRecord.getId());
272            prekey.setContent(Base64.encodeToString(preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.NO_WRAP));
273        }
274
275        return publish(AxolotlService.PEP_BUNDLES + ":" + deviceId, item, publishOptions);
276    }
277
278    public IqPacket publishVerification(byte[] signature, X509Certificate[] certificates, final int deviceId) {
279        final Element item = new Element("item");
280        item.setAttribute("id", "current");
281        final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
282        final Element chain = verification.addChild("chain");
283        for (int i = 0; i < certificates.length; ++i) {
284            try {
285                Element certificate = chain.addChild("certificate");
286                certificate.setContent(Base64.encodeToString(certificates[i].getEncoded(), Base64.NO_WRAP));
287                certificate.setAttribute("index", i);
288            } catch (CertificateEncodingException e) {
289                Log.d(Config.LOGTAG, "could not encode certificate");
290            }
291        }
292        verification.addChild("signature").setContent(Base64.encodeToString(signature, Base64.NO_WRAP));
293        return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
294    }
295
296    public IqPacket queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
297        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
298        final Element query = packet.query(mam.version.namespace);
299        query.setAttribute("queryid", mam.getQueryId());
300        final Data data = new Data();
301        data.setFormType(mam.version.namespace);
302        if (mam.muc()) {
303            packet.setTo(mam.getWith());
304        } else if (mam.getWith() != null) {
305            data.put("with", mam.getWith().toEscapedString());
306        }
307        final long start = mam.getStart();
308        final long end = mam.getEnd();
309        if (start != 0) {
310            data.put("start", getTimestamp(start));
311        }
312        if (end != 0) {
313            data.put("end", getTimestamp(end));
314        }
315        data.submit();
316        query.addChild(data);
317        Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
318        if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
319            set.addChild("before").setContent(mam.getReference());
320        } else if (mam.getReference() != null) {
321            set.addChild("after").setContent(mam.getReference());
322        }
323        set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
324        return packet;
325    }
326
327    public IqPacket generateGetBlockList() {
328        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
329        iq.addChild("blocklist", Namespace.BLOCKING);
330
331        return iq;
332    }
333
334    public IqPacket generateSetBlockRequest(final Jid jid, boolean reportSpam) {
335        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
336        final Element block = iq.addChild("block", Namespace.BLOCKING);
337        final Element item = block.addChild("item").setAttribute("jid", jid);
338        if (reportSpam) {
339            item.addChild("report", "urn:xmpp:reporting:0").addChild("spam");
340        }
341        Log.d(Config.LOGTAG, iq.toString());
342        return iq;
343    }
344
345    public IqPacket generateSetUnblockRequest(final Jid jid) {
346        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
347        final Element block = iq.addChild("unblock", Namespace.BLOCKING);
348        block.addChild("item").setAttribute("jid", jid);
349        return iq;
350    }
351
352    public IqPacket generateSetPassword(final Account account, final String newPassword) {
353        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
354        packet.setTo(account.getDomain());
355        final Element query = packet.addChild("query", Namespace.REGISTER);
356        final Jid jid = account.getJid();
357        query.addChild("username").setContent(jid.getLocal());
358        query.addChild("password").setContent(newPassword);
359        return packet;
360    }
361
362    public IqPacket changeAffiliation(Conversation conference, Jid jid, String affiliation) {
363        List<Jid> jids = new ArrayList<>();
364        jids.add(jid);
365        return changeAffiliation(conference, jids, affiliation);
366    }
367
368    public IqPacket changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
369        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
370        packet.setTo(conference.getJid().asBareJid());
371        packet.setFrom(conference.getAccount().getJid());
372        Element query = packet.query("http://jabber.org/protocol/muc#admin");
373        for (Jid jid : jids) {
374            Element item = query.addChild("item");
375            item.setAttribute("jid", jid);
376            item.setAttribute("affiliation", affiliation);
377        }
378        return packet;
379    }
380
381    public IqPacket changeRole(Conversation conference, String nick, String role) {
382        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
383        packet.setTo(conference.getJid().asBareJid());
384        packet.setFrom(conference.getAccount().getJid());
385        Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
386        item.setAttribute("nick", nick);
387        item.setAttribute("role", role);
388        return packet;
389    }
390
391    public IqPacket requestHttpUploadSlot(Jid host, DownloadableFile file, String mime) {
392        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
393        packet.setTo(host);
394        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD);
395        request.setAttribute("filename", convertFilename(file.getName()));
396        request.setAttribute("size", file.getExpectedSize());
397        request.setAttribute("content-type", mime);
398        return packet;
399    }
400
401    public IqPacket requestHttpUploadLegacySlot(Jid host, DownloadableFile file, String mime) {
402        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
403        packet.setTo(host);
404        Element request = packet.addChild("request", Namespace.HTTP_UPLOAD_LEGACY);
405        request.addChild("filename").setContent(convertFilename(file.getName()));
406        request.addChild("size").setContent(String.valueOf(file.getExpectedSize()));
407        request.addChild("content-type").setContent(mime);
408        return packet;
409    }
410
411    private static String convertFilename(String name) {
412        int pos = name.indexOf('.');
413        if (pos != -1) {
414            try {
415                UUID uuid = UUID.fromString(name.substring(0, pos));
416                ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
417                bb.putLong(uuid.getMostSignificantBits());
418                bb.putLong(uuid.getLeastSignificantBits());
419                return Base64.encodeToString(bb.array(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP) + name.substring(pos);
420            } catch (Exception e) {
421                return name;
422            }
423        } else {
424            return name;
425        }
426    }
427
428    public IqPacket generateCreateAccountWithCaptcha(Account account, String id, Data data) {
429        final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
430        register.setFrom(account.getJid().asBareJid());
431        register.setTo(account.getDomain());
432        register.setId(id);
433        Element query = register.query(Namespace.REGISTER);
434        if (data != null) {
435            query.addChild(data);
436        }
437        return register;
438    }
439
440    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId) {
441        return pushTokenToAppServer(appServer, token, deviceId, null);
442    }
443
444    public IqPacket pushTokenToAppServer(Jid appServer, String token, String deviceId, Jid muc) {
445        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
446        packet.setTo(appServer);
447        final Element command = packet.addChild("command", Namespace.COMMANDS);
448        command.setAttribute("node", "register-push-fcm");
449        command.setAttribute("action", "execute");
450        final Data data = new Data();
451        data.put("token", token);
452        data.put("android-id", deviceId);
453        if (muc != null) {
454            data.put("muc", muc.toEscapedString());
455        }
456        data.submit();
457        command.addChild(data);
458        return packet;
459    }
460
461    public IqPacket unregisterChannelOnAppServer(Jid appServer, String deviceId, String channel) {
462        final IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
463        packet.setTo(appServer);
464        final Element command = packet.addChild("command", Namespace.COMMANDS);
465        command.setAttribute("node", "unregister-push-fcm");
466        command.setAttribute("action", "execute");
467        final Data data = new Data();
468        data.put("channel", channel);
469        data.put("android-id", deviceId);
470        data.submit();
471        command.addChild(data);
472        return packet;
473    }
474
475    public IqPacket enablePush(final Jid jid, final String node, final String secret) {
476        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
477        Element enable = packet.addChild("enable", Namespace.PUSH);
478        enable.setAttribute("jid", jid);
479        enable.setAttribute("node", node);
480        if (secret != null) {
481            Data data = new Data();
482            data.setFormType(Namespace.PUBSUB_PUBLISH_OPTIONS);
483            data.put("secret", secret);
484            data.submit();
485            enable.addChild(data);
486        }
487        return packet;
488    }
489
490    public IqPacket disablePush(final Jid jid, final String node) {
491        IqPacket packet = new IqPacket(IqPacket.TYPE.SET);
492        Element disable = packet.addChild("disable", Namespace.PUSH);
493        disable.setAttribute("jid", jid);
494        disable.setAttribute("node", node);
495        return packet;
496    }
497
498    public IqPacket queryAffiliation(Conversation conversation, String affiliation) {
499        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
500        packet.setTo(conversation.getJid().asBareJid());
501        packet.query("http://jabber.org/protocol/muc#admin").addChild("item").setAttribute("affiliation", affiliation);
502        return packet;
503    }
504
505    public static Bundle defaultGroupChatConfiguration() {
506        Bundle options = new Bundle();
507        options.putString("muc#roomconfig_persistentroom", "1");
508        options.putString("muc#roomconfig_membersonly", "1");
509        options.putString("muc#roomconfig_publicroom", "0");
510        options.putString("muc#roomconfig_whois", "anyone");
511        options.putString("muc#roomconfig_changesubject", "0");
512        options.putString("muc#roomconfig_allowinvites", "0");
513        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
514        options.putString("mam", "1"); //ejabberd community
515        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
516        return options;
517    }
518
519    public static Bundle defaultChannelConfiguration() {
520        Bundle options = new Bundle();
521        options.putString("muc#roomconfig_persistentroom", "1");
522        options.putString("muc#roomconfig_membersonly", "0");
523        options.putString("muc#roomconfig_publicroom", "1");
524        options.putString("muc#roomconfig_whois", "moderators");
525        options.putString("muc#roomconfig_changesubject", "0");
526        options.putString("muc#roomconfig_enablearchiving", "1"); //prosody
527        options.putString("mam", "1"); //ejabberd community
528        options.putString("muc#roomconfig_mam", "1"); //ejabberd saas
529        return options;
530    }
531
532    public IqPacket requestPubsubConfiguration(Jid jid, String node) {
533        return pubsubConfiguration(jid, node, null);
534    }
535
536    public IqPacket publishPubsubConfiguration(Jid jid, String node, Data data) {
537        return pubsubConfiguration(jid, node, data);
538    }
539
540    private IqPacket pubsubConfiguration(Jid jid, String node, Data data) {
541        IqPacket packet = new IqPacket(data == null ? IqPacket.TYPE.GET : IqPacket.TYPE.SET);
542        packet.setTo(jid);
543        Element pubsub = packet.addChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
544        Element configure = pubsub.addChild("configure").setAttribute("node", node);
545        if (data != null) {
546            configure.addChild(data);
547        }
548        return packet;
549    }
550
551    public IqPacket queryDiscoItems(Jid jid) {
552        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
553        packet.setTo(jid);
554        packet.addChild("query",Namespace.DISCO_ITEMS);
555        return packet;
556    }
557
558    public IqPacket queryDiscoInfo(Jid jid) {
559        IqPacket packet = new IqPacket(IqPacket.TYPE.GET);
560        packet.setTo(jid);
561        packet.addChild("query",Namespace.DISCO_INFO);
562        return packet;
563    }
564}