HttpDownloadConnection.java

  1package eu.siacs.conversations.http;
  2
  3import android.util.Log;
  4
  5import androidx.annotation.Nullable;
  6import androidx.core.util.Consumer;
  7
  8import com.google.common.base.Strings;
  9import com.google.common.io.ByteStreams;
 10import com.google.common.primitives.Longs;
 11
 12import java.io.FileInputStream;
 13import java.io.IOException;
 14import java.io.InputStream;
 15import java.io.OutputStream;
 16import java.util.Locale;
 17
 18import javax.net.ssl.SSLHandshakeException;
 19
 20import eu.siacs.conversations.Config;
 21import eu.siacs.conversations.R;
 22import eu.siacs.conversations.entities.DownloadableFile;
 23import eu.siacs.conversations.entities.Message;
 24import eu.siacs.conversations.entities.Transferable;
 25import eu.siacs.conversations.persistance.FileBackend;
 26import eu.siacs.conversations.services.AbstractConnectionManager;
 27import eu.siacs.conversations.services.XmppConnectionService;
 28import eu.siacs.conversations.utils.CryptoHelper;
 29import eu.siacs.conversations.utils.FileWriterException;
 30import eu.siacs.conversations.utils.MimeUtils;
 31import okhttp3.Call;
 32import okhttp3.HttpUrl;
 33import okhttp3.OkHttpClient;
 34import okhttp3.Request;
 35import okhttp3.Response;
 36
 37import static eu.siacs.conversations.http.HttpConnectionManager.EXECUTOR;
 38
 39public class HttpDownloadConnection implements Transferable {
 40
 41    private final Message message;
 42    private final HttpConnectionManager mHttpConnectionManager;
 43    private final XmppConnectionService mXmppConnectionService;
 44    private HttpUrl mUrl;
 45    private DownloadableFile file;
 46    private int mStatus = Transferable.STATUS_UNKNOWN;
 47    private boolean acceptedAutomatically = false;
 48    private int mProgress = 0;
 49    private Call mostRecentCall;
 50    final private Consumer<DownloadableFile> cb;
 51
 52    HttpDownloadConnection(Message message, HttpConnectionManager manager, Consumer<DownloadableFile> cb) {
 53        this.message = message;
 54        this.mHttpConnectionManager = manager;
 55        this.mXmppConnectionService = manager.getXmppConnectionService();
 56        this.cb = cb;
 57    }
 58
 59    @Override
 60    public boolean start() {
 61        if (mXmppConnectionService.hasInternetConnection()) {
 62            if (this.mStatus == STATUS_OFFER_CHECK_FILESIZE) {
 63                checkFileSize(true);
 64            } else {
 65                download(true);
 66            }
 67            return true;
 68        } else {
 69            return false;
 70        }
 71    }
 72
 73    public void init(boolean interactive) {
 74        final Message.FileParams fileParams = message.getFileParams();
 75        if (message.isDeleted()) {
 76            if (message.getType() == Message.TYPE_PRIVATE_FILE) {
 77                message.setType(Message.TYPE_PRIVATE);
 78            } else if (message.isFileOrImage()) {
 79                message.setType(Message.TYPE_TEXT);
 80            }
 81            message.setDeleted(false);
 82            mXmppConnectionService.updateMessage(message);
 83        }
 84        this.message.setTransferable(this);
 85        try {
 86            if (message.hasFileOnRemoteHost()) {
 87                mUrl = AesGcmURL.of(fileParams.url);
 88            } else if (message.isOOb() && fileParams.url != null) {
 89                mUrl = AesGcmURL.of(fileParams.url);
 90            } else {
 91                mUrl = AesGcmURL.of(message.getBody().split("\n")[0]);
 92            }
 93            final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.encodedPath());
 94            if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) {
 95                this.message.setEncryption(Message.ENCRYPTION_PGP);
 96            } else if (message.getEncryption() != Message.ENCRYPTION_OTR
 97                    && message.getEncryption() != Message.ENCRYPTION_AXOLOTL) {
 98                this.message.setEncryption(Message.ENCRYPTION_NONE);
 99            }
100            String ext = extension.getExtension();
101            if (ext == null && fileParams.getMediaType() != null) {
102                ext = MimeUtils.guessExtensionFromMimeType(fileParams.getMediaType());
103            }
104            final String filename = Strings.isNullOrEmpty(ext) ? message.getUuid() : String.format("%s.%s", message.getUuid(), ext);
105            mXmppConnectionService.getFileBackend().setupRelativeFilePath(message, filename);
106            setupFile();
107            if (this.message.getEncryption() == Message.ENCRYPTION_AXOLOTL && this.file.getKey() == null) {
108                this.message.setEncryption(Message.ENCRYPTION_NONE);
109            }
110            final Long knownFileSize;
111            if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
112                knownFileSize = null;
113            } else {
114                knownFileSize = message.getFileParams().size;
115            }
116            Log.d(Config.LOGTAG,"knownFileSize: "+knownFileSize+", body="+message.getBody());
117            if (knownFileSize != null && interactive) {
118                if (message.getEncryption() == Message.ENCRYPTION_AXOLOTL
119                        && this.file.getKey() != null) {
120                    this.file.setExpectedSize(knownFileSize + 16);
121                } else {
122                    this.file.setExpectedSize(knownFileSize);
123                }
124                download(true);
125            } else {
126                checkFileSize(interactive);
127            }
128        } catch (final IllegalArgumentException e) {
129            this.cancel();
130        }
131    }
132
133    private void setupFile() {
134        final String reference = mUrl.fragment();
135        if (reference != null && AesGcmURL.IV_KEY.matcher(reference).matches()) {
136            this.file = new DownloadableFile(mXmppConnectionService.getCacheDir(), message.getUuid());
137            this.file.setKeyAndIv(CryptoHelper.hexToBytes(reference));
138            Log.d(Config.LOGTAG, "create temporary OMEMO encrypted file: " + this.file.getAbsolutePath() + "(" + message.getMimeType() + ")");
139        } else {
140            this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
141        }
142    }
143
144    private void download(final boolean interactive) {
145        EXECUTOR.execute(new FileDownloader(interactive));
146    }
147
148    private void checkFileSize(final boolean interactive) {
149        EXECUTOR.execute(new FileSizeChecker(interactive));
150    }
151
152    @Override
153    public void cancel() {
154        final Call call = this.mostRecentCall;
155        if (call != null && !call.isCanceled()) {
156            call.cancel();
157        }
158        mHttpConnectionManager.finishConnection(this);
159        message.setTransferable(null);
160        if (message.isFileOrImage()) {
161            message.setDeleted(true);
162        }
163        mHttpConnectionManager.updateConversationUi(true);
164    }
165
166    private void decryptFile() throws IOException {
167        final DownloadableFile outputFile = mXmppConnectionService.getFileBackend().getFile(message, true);
168
169        if (outputFile.getParentFile().mkdirs()) {
170            Log.d(Config.LOGTAG, "created parent directories for " + outputFile.getAbsolutePath());
171        }
172
173        if (!outputFile.createNewFile()) {
174            Log.w(Config.LOGTAG, "unable to create output file " + outputFile.getAbsolutePath());
175        }
176
177        final InputStream is = new FileInputStream(this.file);
178
179        outputFile.setKey(this.file.getKey());
180        outputFile.setIv(this.file.getIv());
181        final OutputStream os = AbstractConnectionManager.createOutputStream(outputFile, false, true);
182
183        ByteStreams.copy(is, os);
184
185        FileBackend.close(is);
186        FileBackend.close(os);
187
188        if (!file.delete()) {
189            Log.w(Config.LOGTAG, "unable to delete temporary OMEMO encrypted file " + file.getAbsolutePath());
190        }
191    }
192
193    private void finish() {
194        boolean notify = acceptedAutomatically && !message.isRead() && cb == null;
195        if (message.getEncryption() == Message.ENCRYPTION_PGP) {
196            notify = message.getConversation().getAccount().getPgpDecryptionService().decrypt(message, notify);
197        }
198        final DownloadableFile tmp = file;
199        final String extension = MimeUtils.extractRelevantExtension(tmp.getName());
200        try {
201            mXmppConnectionService.getFileBackend().setupRelativeFilePath(message, new FileInputStream(tmp), extension);
202            file = mXmppConnectionService.getFileBackend().getFile(message);
203            boolean didRename = tmp.renameTo(file);
204            if (!didRename) throw new IOException("rename failed");
205        } catch (final IOException e) {
206            Log.w(Config.LOGTAG, "Failed to rename downloaded file: " + e);
207            file = tmp;
208            message.setRelativeFilePath(file.getAbsolutePath());
209        } catch (final XmppConnectionService.BlockedMediaException e) {
210            file = tmp;
211            tmp.delete();
212            message.setDeleted(true);
213        }
214        message.setTransferable(null);
215        mXmppConnectionService.updateMessage(message);
216        mHttpConnectionManager.finishConnection(this);
217        final boolean notifyAfterScan = notify;
218        mXmppConnectionService.getFileBackend().updateMediaScanner(file, () -> {
219            if (notifyAfterScan) {
220                mXmppConnectionService.getNotificationService().push(message);
221            }
222        });
223    }
224
225    private void decryptIfNeeded() throws IOException {
226        if (file.getKey() != null && file.getIv() != null) {
227            decryptFile();
228        }
229    }
230
231    private void changeStatus(int status) {
232        this.mStatus = status;
233        mHttpConnectionManager.updateConversationUi(true);
234    }
235
236    private void showToastForException(final Exception e) {
237        final Call call = mostRecentCall;
238        final boolean cancelled = call != null && call.isCanceled();
239        if (e == null || cancelled) {
240            return;
241        }
242        if (e instanceof java.net.UnknownHostException) {
243            mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
244        } else if (e instanceof java.net.ConnectException) {
245            mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
246        } else if (e instanceof FileWriterException) {
247            mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file);
248        } else if (e instanceof InvalidFileException) {
249            mXmppConnectionService.showErrorToastInUi(R.string.download_failed_invalid_file);
250        } else {
251            mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
252        }
253    }
254
255    private void updateProgress(long i) {
256        this.mProgress = (int) i;
257        mHttpConnectionManager.updateConversationUi(false);
258    }
259
260    @Override
261    public int getStatus() {
262        return this.mStatus;
263    }
264
265    @Override
266    public Long getFileSize() {
267        if (this.file != null) {
268            return this.file.getExpectedSize();
269        } else {
270            return null;
271        }
272    }
273
274    @Override
275    public int getProgress() {
276        return this.mProgress;
277    }
278
279    public Message getMessage() {
280        return message;
281    }
282
283    private class FileSizeChecker implements Runnable {
284
285        private final boolean interactive;
286
287        FileSizeChecker(boolean interactive) {
288            this.interactive = interactive;
289        }
290
291
292        @Override
293        public void run() {
294            check();
295        }
296
297        private void retrieveFailed(@Nullable final Exception e) {
298            changeStatus(STATUS_OFFER_CHECK_FILESIZE);
299            if (interactive) {
300                showToastForException(e);
301            } else {
302                HttpDownloadConnection.this.acceptedAutomatically = false;
303                HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
304            }
305            cancel();
306        }
307
308        private void check() {
309            long size;
310            try {
311                size = retrieveFileSize();
312            } catch (final Exception e) {
313                Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
314                retrieveFailed(e);
315                return;
316            }
317            final Message.FileParams fileParams = message.getFileParams();
318            FileBackend.updateFileParams(message, fileParams.url, size);
319            mXmppConnectionService.databaseBackend.updateMessage(message, true);
320            file.setExpectedSize(size);
321            message.resetFileParams();
322            if (mHttpConnectionManager.hasStoragePermission()
323                    && size <= mHttpConnectionManager.getAutoAcceptFileSize()
324                    && mXmppConnectionService.isDataSaverDisabled()) {
325                HttpDownloadConnection.this.acceptedAutomatically = true;
326                download(interactive);
327            } else {
328                changeStatus(STATUS_OFFER);
329                HttpDownloadConnection.this.acceptedAutomatically = false;
330                if (cb == null) {
331                    HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
332                } else {
333                    cb.accept(null);
334                }
335            }
336        }
337
338        private long retrieveFileSize() throws IOException {
339            Log.d(Config.LOGTAG, "retrieve file size. interactive:" + interactive);
340            changeStatus(STATUS_CHECKING);
341            final OkHttpClient client = mHttpConnectionManager.buildHttpClient(
342                    mUrl,
343                    message.getConversation().getAccount(),
344                    interactive
345            );
346            final Request request = new Request.Builder()
347                    .url(URL.stripFragment(mUrl))
348                    .addHeader("Accept-Encoding", "identity")
349                    .head()
350                    .build();
351            mostRecentCall = client.newCall(request);
352            try {
353                final Response response = mostRecentCall.execute();
354                throwOnInvalidCode(response);
355                final String contentLength = response.header("Content-Length");
356                final String contentType = response.header("Content-Type");
357                final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.encodedPath());
358                if (Strings.isNullOrEmpty(extension.getExtension()) && contentType != null) {
359                    final String fileExtension = MimeUtils.guessExtensionFromMimeType(contentType);
360                    if (fileExtension != null) {
361                        mXmppConnectionService.getFileBackend().setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), fileExtension), contentType);
362                        Log.d(Config.LOGTAG, "rewriting name after not finding extension in url but in content type");
363                        setupFile();
364                    }
365                }
366                if (Strings.isNullOrEmpty(contentLength)) {
367                    throw new IOException("no content-length found in HEAD response");
368                }
369                final long size = Long.parseLong(contentLength, 10);
370                if (size < 0) {
371                    throw new IOException("Server reported negative file size");
372                }
373                return size;
374            } catch (final IOException e) {
375                Log.d(Config.LOGTAG, "io exception during HEAD " + e.getMessage());
376                throw e;
377            } catch (final NumberFormatException e) {
378                throw new IOException(e);
379            }
380        }
381
382    }
383
384    private class FileDownloader implements Runnable {
385
386        private final boolean interactive;
387
388        public FileDownloader(boolean interactive) {
389            this.interactive = interactive;
390        }
391
392        @Override
393        public void run() {
394            try {
395                changeStatus(STATUS_DOWNLOADING);
396                download();
397                decryptIfNeeded();
398                finish();
399                updateImageBounds();
400                if (cb != null) cb.accept(file);
401            } catch (final SSLHandshakeException e) {
402                changeStatus(STATUS_OFFER);
403            } catch (final Exception e) {
404                Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": unable to download file", e);
405                if (interactive) {
406                    showToastForException(e);
407                } else {
408                    HttpDownloadConnection.this.acceptedAutomatically = false;
409                    HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
410                }
411                cancel();
412            }
413        }
414
415        private void download() throws Exception {
416            final OkHttpClient client = mHttpConnectionManager.buildHttpClient(
417                    mUrl,
418                    message.getConversation().getAccount(),
419                    interactive
420            );
421
422            final Request.Builder requestBuilder = new Request.Builder().url(URL.stripFragment(mUrl));
423
424            final long expected = file.getExpectedSize();
425            final boolean tryResume = file.exists() && file.getSize() > 0 && file.getSize() < expected;
426            final long resumeSize;
427            if (tryResume) {
428                resumeSize = file.getSize();
429                Log.d(Config.LOGTAG, "http download trying resume after " + resumeSize + " of " + expected);
430                requestBuilder.addHeader("Range", String.format(Locale.ENGLISH, "bytes=%d-", resumeSize));
431            } else {
432                resumeSize = 0;
433            }
434            final Request request = requestBuilder.build();
435            mostRecentCall = client.newCall(request);
436            final Response response = mostRecentCall.execute();
437            throwOnInvalidCode(response);
438            final String contentRange = response.header("Content-Range");
439            final boolean serverResumed = tryResume && contentRange != null && contentRange.startsWith("bytes " + resumeSize + "-");
440            final InputStream inputStream = response.body().byteStream();
441            final OutputStream outputStream;
442            long transmitted = 0;
443            if (tryResume && serverResumed) {
444                Log.d(Config.LOGTAG, "server resumed");
445                transmitted = file.getSize();
446                updateProgress(Math.round(((double) transmitted / expected) * 100));
447                outputStream = AbstractConnectionManager.createOutputStream(file, true, false);
448            } else {
449                final String contentLength = response.header("Content-Length");
450                final long size = Strings.isNullOrEmpty(contentLength) ? 0 : Longs.tryParse(contentLength);
451                if (expected != size) {
452                    Log.d(Config.LOGTAG, "content-length reported on GET (" + size + ") did not match Content-Length reported on HEAD (" + expected + ")");
453                }
454                file.getParentFile().mkdirs();
455                Log.d(Config.LOGTAG,"creating file: "+file.getAbsolutePath());
456                if (!file.exists() && !file.createNewFile()) {
457                    throw new FileWriterException(file);
458                }
459                outputStream = AbstractConnectionManager.createOutputStream(file, false, false);
460            }
461            int count;
462            final byte[] buffer = new byte[4096];
463            while ((count = inputStream.read(buffer)) != -1) {
464                transmitted += count;
465                try {
466                    outputStream.write(buffer, 0, count);
467                } catch (final IOException e) {
468                    throw new FileWriterException(file);
469                }
470                if (transmitted > expected) {
471                    throw new InvalidFileException(String.format("File exceeds expected size of %d", expected));
472                }
473                updateProgress(Math.round(((double) transmitted / expected) * 100));
474            }
475            outputStream.flush();
476        }
477
478        private void updateImageBounds() {
479            final boolean privateMessage = message.isPrivateMessage();
480            message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : Message.TYPE_FILE);
481            final String url;
482            final String ref = mUrl.fragment();
483            if (ref != null && AesGcmURL.IV_KEY.matcher(ref).matches()) {
484                url = AesGcmURL.toAesGcmUrl(mUrl);
485            } else {
486                url = mUrl.toString();
487            }
488            mXmppConnectionService.getFileBackend().updateFileParams(message, url);
489            mXmppConnectionService.updateMessage(message);
490        }
491
492    }
493
494    private static void throwOnInvalidCode(final Response response) throws IOException {
495        final int code = response.code();
496        if (code < 200 || code >= 300) {
497            throw new IOException(String.format(Locale.ENGLISH, "HTTP Status code was %d", code));
498        }
499    }
500
501    private static class InvalidFileException extends IOException {
502
503        private InvalidFileException(final String message) {
504            super(message);
505        }
506
507    }
508}