HttpDownloadConnection.java

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