1package eu.siacs.conversations.generator;
  2
  3import android.os.Bundle;
  4import android.util.Base64;
  5import android.util.Log;
  6import eu.siacs.conversations.Config;
  7import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  8import eu.siacs.conversations.entities.Account;
  9import eu.siacs.conversations.entities.Conversation;
 10import eu.siacs.conversations.services.MessageArchiveService;
 11import eu.siacs.conversations.services.XmppConnectionService;
 12import eu.siacs.conversations.xml.Element;
 13import eu.siacs.conversations.xml.Namespace;
 14import eu.siacs.conversations.xmpp.Jid;
 15import eu.siacs.conversations.xmpp.forms.Data;
 16import im.conversations.android.xmpp.model.stanza.Iq;
 17import java.security.cert.CertificateEncodingException;
 18import java.security.cert.X509Certificate;
 19import java.util.ArrayList;
 20import java.util.List;
 21import java.util.Set;
 22import org.whispersystems.libsignal.IdentityKey;
 23import org.whispersystems.libsignal.ecc.ECPublicKey;
 24import org.whispersystems.libsignal.state.PreKeyRecord;
 25import org.whispersystems.libsignal.state.SignedPreKeyRecord;
 26
 27public class IqGenerator extends AbstractGenerator {
 28
 29    public IqGenerator(final XmppConnectionService service) {
 30        super(service);
 31    }
 32
 33    public static Iq purgeOfflineMessages() {
 34        final Iq packet = new Iq(Iq.Type.SET);
 35        packet.addChild("offline", Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL).addChild("purge");
 36        return packet;
 37    }
 38
 39    protected Iq publish(final String node, final Element item, final Bundle options) {
 40        final var packet = new Iq(Iq.Type.SET);
 41        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
 42        final Element publish = pubsub.addChild("publish");
 43        publish.setAttribute("node", node);
 44        publish.addChild(item);
 45        if (options != null) {
 46            final Element publishOptions = pubsub.addChild("publish-options");
 47            publishOptions.addChild(Data.create(Namespace.PUBSUB_PUBLISH_OPTIONS, options));
 48        }
 49        return packet;
 50    }
 51
 52    protected Iq publish(final String node, final Element item) {
 53        return publish(node, item, null);
 54    }
 55
 56    private Iq retrieve(String node, Element item) {
 57        final var packet = new Iq(Iq.Type.GET);
 58        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB);
 59        final Element items = pubsub.addChild("items");
 60        items.setAttribute("node", node);
 61        if (item != null) {
 62            items.addChild(item);
 63        }
 64        return packet;
 65    }
 66
 67    public Iq deleteNode(final String node) {
 68        final var packet = new Iq(Iq.Type.SET);
 69        final Element pubsub = packet.addChild("pubsub", Namespace.PUBSUB_OWNER);
 70        pubsub.addChild("delete").setAttribute("node", node);
 71        return packet;
 72    }
 73
 74    public Iq retrieveDeviceIds(final Jid to) {
 75        final var packet = retrieve(AxolotlService.PEP_DEVICE_LIST, null);
 76        if (to != null) {
 77            packet.setTo(to);
 78        }
 79        return packet;
 80    }
 81
 82    public Iq retrieveBundlesForDevice(final Jid to, final int deviceid) {
 83        final var packet = retrieve(AxolotlService.PEP_BUNDLES + ":" + deviceid, null);
 84        packet.setTo(to);
 85        return packet;
 86    }
 87
 88    public Iq retrieveVerificationForDevice(final Jid to, final int deviceid) {
 89        final var packet = retrieve(AxolotlService.PEP_VERIFICATION + ":" + deviceid, null);
 90        packet.setTo(to);
 91        return packet;
 92    }
 93
 94    public Iq publishDeviceIds(final Set<Integer> ids, final Bundle publishOptions) {
 95        final Element item = new Element("item");
 96        item.setAttribute("id", "current");
 97        final Element list = item.addChild("list", AxolotlService.PEP_PREFIX);
 98        for (Integer id : ids) {
 99            final Element device = new Element("device");
100            device.setAttribute("id", id);
101            list.addChild(device);
102        }
103        return publish(AxolotlService.PEP_DEVICE_LIST, item, publishOptions);
104    }
105
106    public Iq publishBundles(
107            final SignedPreKeyRecord signedPreKeyRecord,
108            final IdentityKey identityKey,
109            final Set<PreKeyRecord> preKeyRecords,
110            final int deviceId,
111            Bundle publishOptions) {
112        final Element item = new Element("item");
113        item.setAttribute("id", "current");
114        final Element bundle = item.addChild("bundle", AxolotlService.PEP_PREFIX);
115        final Element signedPreKeyPublic = bundle.addChild("signedPreKeyPublic");
116        signedPreKeyPublic.setAttribute("signedPreKeyId", signedPreKeyRecord.getId());
117        ECPublicKey publicKey = signedPreKeyRecord.getKeyPair().getPublicKey();
118        signedPreKeyPublic.setContent(Base64.encodeToString(publicKey.serialize(), Base64.NO_WRAP));
119        final Element signedPreKeySignature = bundle.addChild("signedPreKeySignature");
120        signedPreKeySignature.setContent(
121                Base64.encodeToString(signedPreKeyRecord.getSignature(), Base64.NO_WRAP));
122        final Element identityKeyElement = bundle.addChild("identityKey");
123        identityKeyElement.setContent(
124                Base64.encodeToString(identityKey.serialize(), Base64.NO_WRAP));
125
126        final Element prekeys = bundle.addChild("prekeys", AxolotlService.PEP_PREFIX);
127        for (PreKeyRecord preKeyRecord : preKeyRecords) {
128            final Element prekey = prekeys.addChild("preKeyPublic");
129            prekey.setAttribute("preKeyId", preKeyRecord.getId());
130            prekey.setContent(
131                    Base64.encodeToString(
132                            preKeyRecord.getKeyPair().getPublicKey().serialize(), Base64.NO_WRAP));
133        }
134
135        return publish(AxolotlService.PEP_BUNDLES + ":" + deviceId, item, publishOptions);
136    }
137
138    public Iq publishVerification(
139            byte[] signature, X509Certificate[] certificates, final int deviceId) {
140        final Element item = new Element("item");
141        item.setAttribute("id", "current");
142        final Element verification = item.addChild("verification", AxolotlService.PEP_PREFIX);
143        final Element chain = verification.addChild("chain");
144        for (int i = 0; i < certificates.length; ++i) {
145            try {
146                Element certificate = chain.addChild("certificate");
147                certificate.setContent(
148                        Base64.encodeToString(certificates[i].getEncoded(), Base64.NO_WRAP));
149                certificate.setAttribute("index", i);
150            } catch (CertificateEncodingException e) {
151                Log.d(Config.LOGTAG, "could not encode certificate");
152            }
153        }
154        verification
155                .addChild("signature")
156                .setContent(Base64.encodeToString(signature, Base64.NO_WRAP));
157        return publish(AxolotlService.PEP_VERIFICATION + ":" + deviceId, item);
158    }
159
160    public Iq queryMessageArchiveManagement(final MessageArchiveService.Query mam) {
161        final Iq packet = new Iq(Iq.Type.SET);
162        final Element query = packet.query(mam.version.namespace);
163        query.setAttribute("queryid", mam.getQueryId());
164        final Data data = new Data();
165        data.setFormType(mam.version.namespace);
166        if (mam.muc()) {
167            packet.setTo(mam.getWith());
168        } else if (mam.getWith() != null) {
169            data.put("with", mam.getWith().toString());
170        }
171        final long start = mam.getStart();
172        final long end = mam.getEnd();
173        if (start != 0) {
174            data.put("start", getTimestamp(start));
175        }
176        if (end != 0) {
177            data.put("end", getTimestamp(end));
178        }
179        data.submit();
180        query.addChild(data);
181        Element set = query.addChild("set", "http://jabber.org/protocol/rsm");
182        if (mam.getPagingOrder() == MessageArchiveService.PagingOrder.REVERSE) {
183            set.addChild("before").setContent(mam.getReference());
184        } else if (mam.getReference() != null) {
185            set.addChild("after").setContent(mam.getReference());
186        }
187        set.addChild("max").setContent(String.valueOf(Config.PAGE_SIZE));
188        return packet;
189    }
190
191    public Iq generateSetPassword(final Account account, final String newPassword) {
192        final Iq packet = new Iq(Iq.Type.SET);
193        packet.setTo(account.getDomain());
194        final Element query = packet.addChild("query", Namespace.REGISTER);
195        final Jid jid = account.getJid();
196        query.addChild("username").setContent(jid.getLocal());
197        query.addChild("password").setContent(newPassword);
198        return packet;
199    }
200
201    public Iq changeAffiliation(Conversation conference, Jid jid, String affiliation) {
202        List<Jid> jids = new ArrayList<>();
203        jids.add(jid);
204        return changeAffiliation(conference, jids, affiliation);
205    }
206
207    public Iq changeAffiliation(Conversation conference, List<Jid> jids, String affiliation) {
208        final Iq packet = new Iq(Iq.Type.SET);
209        packet.setTo(conference.getJid().asBareJid());
210        packet.setFrom(conference.getAccount().getJid());
211        Element query = packet.query("http://jabber.org/protocol/muc#admin");
212        for (Jid jid : jids) {
213            Element item = query.addChild("item");
214            item.setAttribute("jid", jid);
215            item.setAttribute("affiliation", affiliation);
216        }
217        return packet;
218    }
219
220    public Iq changeRole(Conversation conference, String nick, String role) {
221        final Iq packet = new Iq(Iq.Type.SET);
222        packet.setTo(conference.getJid().asBareJid());
223        packet.setFrom(conference.getAccount().getJid());
224        Element item = packet.query("http://jabber.org/protocol/muc#admin").addChild("item");
225        item.setAttribute("nick", nick);
226        item.setAttribute("role", role);
227        return packet;
228    }
229
230    public static Iq generateCreateAccountWithCaptcha(
231            final Account account, final String id, final Data data) {
232        final Iq register = new Iq(Iq.Type.SET);
233        register.setFrom(account.getJid().asBareJid());
234        register.setTo(account.getDomain());
235        register.setId(id);
236        Element query = register.query(Namespace.REGISTER);
237        if (data != null) {
238            query.addChild(data);
239        }
240        return register;
241    }
242
243    public Iq pushTokenToAppServer(Jid appServer, String token, String deviceId) {
244        return pushTokenToAppServer(appServer, token, deviceId, null);
245    }
246
247    public Iq pushTokenToAppServer(Jid appServer, String token, String deviceId, Jid muc) {
248        final Iq packet = new Iq(Iq.Type.SET);
249        packet.setTo(appServer);
250        final Element command = packet.addChild("command", Namespace.COMMANDS);
251        command.setAttribute("node", "register-push-fcm");
252        command.setAttribute("action", "execute");
253        final Data data = new Data();
254        data.put("token", token);
255        data.put("android-id", deviceId);
256        if (muc != null) {
257            data.put("muc", muc.toString());
258        }
259        data.submit();
260        command.addChild(data);
261        return packet;
262    }
263
264    public Iq unregisterChannelOnAppServer(Jid appServer, String deviceId, String channel) {
265        final Iq packet = new Iq(Iq.Type.SET);
266        packet.setTo(appServer);
267        final Element command = packet.addChild("command", Namespace.COMMANDS);
268        command.setAttribute("node", "unregister-push-fcm");
269        command.setAttribute("action", "execute");
270        final Data data = new Data();
271        data.put("channel", channel);
272        data.put("android-id", deviceId);
273        data.submit();
274        command.addChild(data);
275        return packet;
276    }
277
278    public Iq enablePush(final Jid jid, final String node, final String secret) {
279        final Iq packet = new Iq(Iq.Type.SET);
280        Element enable = packet.addChild("enable", Namespace.PUSH);
281        enable.setAttribute("jid", jid);
282        enable.setAttribute("node", node);
283        if (secret != null) {
284            Data data = new Data();
285            data.setFormType(Namespace.PUBSUB_PUBLISH_OPTIONS);
286            data.put("secret", secret);
287            data.submit();
288            enable.addChild(data);
289        }
290        return packet;
291    }
292
293    public Iq disablePush(final Jid jid, final String node) {
294        Iq packet = new Iq(Iq.Type.SET);
295        Element disable = packet.addChild("disable", Namespace.PUSH);
296        disable.setAttribute("jid", jid);
297        disable.setAttribute("node", node);
298        return packet;
299    }
300
301    public Iq queryAffiliation(Conversation conversation, String affiliation) {
302        final Iq packet = new Iq(Iq.Type.GET);
303        packet.setTo(conversation.getJid().asBareJid());
304        packet.query("http://jabber.org/protocol/muc#admin")
305                .addChild("item")
306                .setAttribute("affiliation", affiliation);
307        return packet;
308    }
309
310    public static Bundle defaultGroupChatConfiguration() {
311        Bundle options = new Bundle();
312        options.putString("muc#roomconfig_persistentroom", "1");
313        options.putString("muc#roomconfig_membersonly", "1");
314        options.putString("muc#roomconfig_publicroom", "0");
315        options.putString("muc#roomconfig_whois", "anyone");
316        options.putString("muc#roomconfig_changesubject", "0");
317        options.putString("muc#roomconfig_allowinvites", "0");
318        options.putString("muc#roomconfig_enablearchiving", "1"); // prosody
319        options.putString("mam", "1"); // ejabberd community
320        options.putString("muc#roomconfig_mam", "1"); // ejabberd saas
321        return options;
322    }
323
324    public static Bundle defaultChannelConfiguration() {
325        Bundle options = new Bundle();
326        options.putString("muc#roomconfig_persistentroom", "1");
327        options.putString("muc#roomconfig_membersonly", "0");
328        options.putString("muc#roomconfig_publicroom", "1");
329        options.putString("muc#roomconfig_whois", "moderators");
330        options.putString("muc#roomconfig_changesubject", "0");
331        options.putString("muc#roomconfig_enablearchiving", "1"); // prosody
332        options.putString("mam", "1"); // ejabberd community
333        options.putString("muc#roomconfig_mam", "1"); // ejabberd saas
334        return options;
335    }
336
337    public Iq requestPubsubConfiguration(Jid jid, String node) {
338        return pubsubConfiguration(jid, node, null);
339    }
340
341    public Iq publishPubsubConfiguration(Jid jid, String node, Data data) {
342        return pubsubConfiguration(jid, node, data);
343    }
344
345    private Iq pubsubConfiguration(Jid jid, String node, Data data) {
346        final Iq packet = new Iq(data == null ? Iq.Type.GET : Iq.Type.SET);
347        packet.setTo(jid);
348        Element pubsub = packet.addChild("pubsub", "http://jabber.org/protocol/pubsub#owner");
349        Element configure = pubsub.addChild("configure").setAttribute("node", node);
350        if (data != null) {
351            configure.addChild(data);
352        }
353        return packet;
354    }
355}