aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/xmpp/jingle/JingleInbandTransport.java
blob: fbf494295880687784e20a5a17bdb67b79664d38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package de.pixart.messenger.xmpp.jingle;

import android.util.Base64;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import de.pixart.messenger.Config;
import de.pixart.messenger.entities.Account;
import de.pixart.messenger.entities.DownloadableFile;
import de.pixart.messenger.persistance.FileBackend;
import de.pixart.messenger.utils.CryptoHelper;
import de.pixart.messenger.xml.Element;
import de.pixart.messenger.xmpp.OnIqPacketReceived;
import de.pixart.messenger.xmpp.jid.Jid;
import de.pixart.messenger.xmpp.stanzas.IqPacket;

public class JingleInbandTransport extends JingleTransport {

    private Account account;
    private Jid counterpart;
    private int blockSize;
    private int seq = 0;
    private String sessionId;

    private boolean established = false;

    private boolean connected = true;

    private DownloadableFile file;
    private JingleConnection connection;

    private InputStream fileInputStream = null;
    private OutputStream fileOutputStream = null;
    private long remainingSize = 0;
    private long fileSize = 0;
    private MessageDigest digest;

    private OnFileTransmissionStatusChanged onFileTransmissionStatusChanged;

    private OnIqPacketReceived onAckReceived = new OnIqPacketReceived() {
        @Override
        public void onIqPacketReceived(Account account, IqPacket packet) {
            if (connected && packet.getType() == IqPacket.TYPE.RESULT) {
                if (remainingSize > 0) {
                    sendNextBlock();
                }
            }
        }
    };

    public JingleInbandTransport(final JingleConnection connection, final String sid, final int blocksize) {
        this.connection = connection;
        this.account = connection.getAccount();
        this.counterpart = connection.getCounterPart();
        this.blockSize = blocksize;
        this.sessionId = sid;
    }

    private void sendClose() {
        IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
        iq.setTo(this.counterpart);
        Element close = iq.addChild("close", "http://jabber.org/protocol/ibb");
        close.setAttribute("sid", this.sessionId);
        this.account.getXmppConnection().sendIqPacket(iq, null);
    }

    public void connect(final OnTransportConnected callback) {
        IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
        iq.setTo(this.counterpart);
        Element open = iq.addChild("open", "http://jabber.org/protocol/ibb");
        open.setAttribute("sid", this.sessionId);
        open.setAttribute("stanza", "iq");
        open.setAttribute("block-size", Integer.toString(this.blockSize));
        this.connected = true;
        this.account.getXmppConnection().sendIqPacket(iq,
                new OnIqPacketReceived() {

                    @Override
                    public void onIqPacketReceived(Account account,
                                                   IqPacket packet) {
                        if (packet.getType() != IqPacket.TYPE.RESULT) {
                            callback.failed();
                        } else {
                            callback.established();
                        }
                    }
                });
    }

    @Override
    public void receive(DownloadableFile file,
                        OnFileTransmissionStatusChanged callback) {
        this.onFileTransmissionStatusChanged = callback;
        this.file = file;
        try {
            this.digest = MessageDigest.getInstance("SHA-1");
            digest.reset();
            file.getParentFile().mkdirs();
            file.createNewFile();
            this.fileOutputStream = connection.getFileOutputStream();
            if (this.fileOutputStream == null) {
                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not create output stream");
                callback.onFileTransferAborted();
                return;
            }
            this.remainingSize = this.fileSize = file.getExpectedSize();
        } catch (final NoSuchAlgorithmException | IOException e) {
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + " " + e.getMessage());
            callback.onFileTransferAborted();
        }
    }

    @Override
    public void send(DownloadableFile file,
                     OnFileTransmissionStatusChanged callback) {
        this.onFileTransmissionStatusChanged = callback;
        this.file = file;
        try {
            this.remainingSize = this.file.getExpectedSize();
            this.fileSize = this.remainingSize;
            this.digest = MessageDigest.getInstance("SHA-1");
            this.digest.reset();
            fileInputStream = connection.getFileInputStream();
            if (fileInputStream == null) {
                Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could no create input stream");
                callback.onFileTransferAborted();
                return;
            }
            if (this.connected) {
                this.sendNextBlock();
            }
        } catch (NoSuchAlgorithmException e) {
            callback.onFileTransferAborted();
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": " + e.getMessage());
        }
    }

    @Override
    public void disconnect() {
        this.connected = false;
        if (this.fileOutputStream != null) {
            try {
                this.fileOutputStream.close();
            } catch (IOException e) {

            }
        }
        if (this.fileInputStream != null) {
            try {
                this.fileInputStream.close();
            } catch (IOException e) {

            }
        }
    }

    private void sendNextBlock() {
        byte[] buffer = new byte[this.blockSize];
        try {
            int count = fileInputStream.read(buffer);
            if (count == -1) {
                sendClose();
                file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest()));
                this.onFileTransmissionStatusChanged.onFileTransmitted(file);
                fileInputStream.close();
                return;
            } else if (count != buffer.length) {
                int rem = fileInputStream.read(buffer, count, buffer.length - count);
                if (rem > 0) {
                    count += rem;
                }
            }
            this.remainingSize -= count;
            this.digest.update(buffer, 0, count);
            String base64 = Base64.encodeToString(buffer, 0, count, Base64.NO_WRAP);
            IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
            iq.setTo(this.counterpart);
            Element data = iq.addChild("data", "http://jabber.org/protocol/ibb");
            data.setAttribute("seq", Integer.toString(this.seq));
            data.setAttribute("block-size", Integer.toString(this.blockSize));
            data.setAttribute("sid", this.sessionId);
            data.setContent(base64);
            this.account.getXmppConnection().sendIqPacket(iq, this.onAckReceived);
            this.account.getXmppConnection().r(); //don't fill up stanza queue too much
            this.seq++;
            if (this.remainingSize > 0) {
                connection.updateProgress((int) ((((double) (this.fileSize - this.remainingSize)) / this.fileSize) * 100));
            } else {
                sendClose();
                file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest()));
                this.onFileTransmissionStatusChanged.onFileTransmitted(file);
                fileInputStream.close();
            }
        } catch (IOException e) {
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception during sendNextBlock() " + e.getMessage());
            FileBackend.close(fileInputStream);
            this.onFileTransmissionStatusChanged.onFileTransferAborted();
        }
    }

    private void receiveNextBlock(String data) {
        try {
            byte[] buffer = Base64.decode(data, Base64.NO_WRAP);
            if (this.remainingSize < buffer.length) {
                buffer = Arrays.copyOfRange(buffer, 0, (int) this.remainingSize);
            }
            this.remainingSize -= buffer.length;
            this.fileOutputStream.write(buffer);
            this.digest.update(buffer);
            if (this.remainingSize <= 0) {
                file.setSha1Sum(CryptoHelper.bytesToHex(digest.digest()));
                fileOutputStream.flush();
                fileOutputStream.close();
                this.onFileTransmissionStatusChanged.onFileTransmitted(file);
            } else {
                connection.updateProgress((int) ((((double) (this.fileSize - this.remainingSize)) / this.fileSize) * 100));
            }
        } catch (Exception e) {
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": " + e.getMessage());
            FileBackend.close(fileOutputStream);
            this.onFileTransmissionStatusChanged.onFileTransferAborted();
        }
    }

    public void deliverPayload(IqPacket packet, Element payload) {
        if (payload.getName().equals("open")) {
            if (!established) {
                established = true;
                connected = true;
                this.receiveNextBlock("");
                this.account.getXmppConnection().sendIqPacket(
                        packet.generateResponse(IqPacket.TYPE.RESULT), null);
            } else {
                this.account.getXmppConnection().sendIqPacket(
                        packet.generateResponse(IqPacket.TYPE.ERROR), null);
            }
        } else if (connected && payload.getName().equals("data")) {
            this.receiveNextBlock(payload.getContent());
            this.account.getXmppConnection().sendIqPacket(
                    packet.generateResponse(IqPacket.TYPE.RESULT), null);
        } else if (connected && payload.getName().equals("close")) {
            this.connected = false;
            this.account.getXmppConnection().sendIqPacket(
                    packet.generateResponse(IqPacket.TYPE.RESULT), null);
            Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received ibb close");
        } else {
            Log.d(Config.LOGTAG, payload.toString());
            // TODO some sort of exception
        }
    }
}