1package eu.siacs.conversations.http;
2
3import android.os.PowerManager;
4import android.support.annotation.Nullable;
5import android.util.Log;
6
7import com.google.common.io.ByteStreams;
8
9import java.io.BufferedInputStream;
10import java.io.FileInputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.io.OutputStream;
14import java.net.HttpURLConnection;
15import java.net.MalformedURLException;
16import java.net.URL;
17import java.util.concurrent.CancellationException;
18
19import javax.net.ssl.HttpsURLConnection;
20import javax.net.ssl.SSLHandshakeException;
21
22import eu.siacs.conversations.Config;
23import eu.siacs.conversations.R;
24import eu.siacs.conversations.entities.Account;
25import eu.siacs.conversations.entities.DownloadableFile;
26import eu.siacs.conversations.entities.Message;
27import eu.siacs.conversations.entities.Transferable;
28import eu.siacs.conversations.persistance.FileBackend;
29import eu.siacs.conversations.services.AbstractConnectionManager;
30import eu.siacs.conversations.services.XmppConnectionService;
31import eu.siacs.conversations.utils.CryptoHelper;
32import eu.siacs.conversations.utils.FileWriterException;
33import eu.siacs.conversations.utils.WakeLockHelper;
34import eu.siacs.conversations.xmpp.stanzas.IqPacket;
35import rocks.xmpp.addr.Jid;
36
37public class HttpDownloadConnection implements Transferable {
38
39 private final Message message;
40 private final boolean mUseTor;
41 private HttpConnectionManager mHttpConnectionManager;
42 private XmppConnectionService mXmppConnectionService;
43 private URL mUrl;
44 private DownloadableFile file;
45 private int mStatus = Transferable.STATUS_UNKNOWN;
46 private boolean acceptedAutomatically = false;
47 private int mProgress = 0;
48 private boolean canceled = false;
49 private Method method = Method.HTTP_UPLOAD;
50
51 HttpDownloadConnection(Message message, HttpConnectionManager manager) {
52 this.message = message;
53 this.mHttpConnectionManager = manager;
54 this.mXmppConnectionService = manager.getXmppConnectionService();
55 this.mUseTor = mXmppConnectionService.useTorToConnect();
56 }
57
58 @Override
59 public boolean start() {
60 if (mXmppConnectionService.hasInternetConnection()) {
61 if (this.mStatus == STATUS_OFFER_CHECK_FILESIZE) {
62 checkFileSize(true);
63 } else {
64 download(true);
65 }
66 return true;
67 } else {
68 return false;
69 }
70 }
71
72 public void init(boolean interactive) {
73 if (message.isDeleted()) {
74 if (message.getType() == Message.TYPE_PRIVATE_FILE) {
75 message.setType(Message.TYPE_PRIVATE);
76 } else if (message.isFileOrImage()) {
77 message.setType(Message.TYPE_TEXT);
78 }
79 message.setDeleted(false);
80 mXmppConnectionService.updateMessage(message);
81 }
82 this.message.setTransferable(this);
83 try {
84 final Message.FileParams fileParams = message.getFileParams();
85 if (message.hasFileOnRemoteHost()) {
86 mUrl = CryptoHelper.toHttpsUrl(fileParams.url);
87 } else if (message.isOOb() && fileParams.url != null && fileParams.size > 0) {
88 mUrl = fileParams.url;
89 } else {
90 mUrl = CryptoHelper.toHttpsUrl(new URL(message.getBody().split("\n")[0]));
91 }
92 final AbstractConnectionManager.Extension extension = AbstractConnectionManager.Extension.of(mUrl.getPath());
93 if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) {
94 this.message.setEncryption(Message.ENCRYPTION_PGP);
95 } else if (message.getEncryption() != Message.ENCRYPTION_OTR
96 && message.getEncryption() != Message.ENCRYPTION_AXOLOTL) {
97 this.message.setEncryption(Message.ENCRYPTION_NONE);
98 }
99 final String ext;
100 if (VALID_CRYPTO_EXTENSIONS.contains(extension.main)) {
101 ext = extension.secondary;
102 } else {
103 ext = extension.main;
104 }
105 message.setRelativeFilePath(message.getUuid() + (ext != null ? ("." + ext) : ""));
106 final String reference = mUrl.getRef();
107 if (reference != null && AesGcmURLStreamHandler.IV_KEY.matcher(reference).matches()) {
108 this.file = new DownloadableFile(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + message.getUuid());
109 this.file.setKeyAndIv(CryptoHelper.hexToBytes(reference));
110 Log.d(Config.LOGTAG, "create temporary OMEMO encrypted file: " + this.file.getAbsolutePath() + "(" + message.getMimeType() + ")");
111 } else {
112 this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
113 }
114
115
116 if (this.message.getEncryption() == Message.ENCRYPTION_AXOLOTL && this.file.getKey() == null) {
117 this.message.setEncryption(Message.ENCRYPTION_NONE);
118 }
119 method = mUrl.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME) ? Method.P1_S3 : Method.HTTP_UPLOAD;
120 long knownFileSize = message.getFileParams().size;
121 if (knownFileSize > 0 && interactive && method != Method.P1_S3) {
122 this.file.setExpectedSize(knownFileSize);
123 download(true);
124 } else {
125 checkFileSize(interactive);
126 }
127 } catch (MalformedURLException e) {
128 this.cancel();
129 }
130 }
131
132 private void download(boolean interactive) {
133 new Thread(new FileDownloader(interactive)).start();
134 }
135
136 private void checkFileSize(boolean interactive) {
137 new Thread(new FileSizeChecker(interactive)).start();
138 }
139
140 @Override
141 public void cancel() {
142 this.canceled = true;
143 mHttpConnectionManager.finishConnection(this);
144 message.setTransferable(null);
145 if (message.isFileOrImage()) {
146 message.setDeleted(true);
147 }
148 mHttpConnectionManager.updateConversationUi(true);
149 }
150
151 private void decryptFile() throws IOException {
152 final DownloadableFile outputFile = mXmppConnectionService.getFileBackend().getFile(message, true);
153
154 if (outputFile.getParentFile().mkdirs()) {
155 Log.d(Config.LOGTAG, "created parent directories for " + outputFile.getAbsolutePath());
156 }
157
158 if (!outputFile.createNewFile()) {
159 Log.w(Config.LOGTAG, "unable to create output file " + outputFile.getAbsolutePath());
160 }
161
162 final InputStream is = new FileInputStream(this.file);
163
164 outputFile.setKey(this.file.getKey());
165 outputFile.setIv(this.file.getIv());
166 final OutputStream os = AbstractConnectionManager.createOutputStream(outputFile, false, true);
167
168 ByteStreams.copy(is, os);
169
170 FileBackend.close(is);
171 FileBackend.close(os);
172
173 if (!file.delete()) {
174 Log.w(Config.LOGTAG, "unable to delete temporary OMEMO encrypted file " + file.getAbsolutePath());
175 }
176
177 //TODO can this be skipped?
178 //message.setRelativeFilePath(outputFile.getPath());
179
180 }
181
182 private void finish() {
183 message.setTransferable(null);
184 mHttpConnectionManager.finishConnection(this);
185 boolean notify = acceptedAutomatically && !message.isRead();
186 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
187 notify = message.getConversation().getAccount().getPgpDecryptionService().decrypt(message, notify);
188 }
189 mHttpConnectionManager.updateConversationUi(true);
190 final boolean notifyAfterScan = notify;
191 final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message, true);
192 mXmppConnectionService.getFileBackend().updateMediaScanner(file, () -> {
193 if (notifyAfterScan) {
194 mXmppConnectionService.getNotificationService().push(message);
195 }
196 });
197 }
198
199 private void decryptIfNeeded() throws IOException {
200 if (file.getKey() != null && file.getIv() != null) {
201 decryptFile();
202 }
203 }
204
205 private void changeStatus(int status) {
206 this.mStatus = status;
207 mHttpConnectionManager.updateConversationUi(true);
208 }
209
210 private void showToastForException(Exception e) {
211 if (e instanceof java.net.UnknownHostException) {
212 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
213 } else if (e instanceof java.net.ConnectException) {
214 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
215 } else if (e instanceof FileWriterException) {
216 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file);
217 } else if (!(e instanceof CancellationException)) {
218 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
219 }
220 }
221
222 private void updateProgress(long i) {
223 this.mProgress = (int) i;
224 mHttpConnectionManager.updateConversationUi(false);
225 }
226
227 @Override
228 public int getStatus() {
229 return this.mStatus;
230 }
231
232 @Override
233 public long getFileSize() {
234 if (this.file != null) {
235 return this.file.getExpectedSize();
236 } else {
237 return 0;
238 }
239 }
240
241 @Override
242 public int getProgress() {
243 return this.mProgress;
244 }
245
246 public Message getMessage() {
247 return message;
248 }
249
250 private class FileSizeChecker implements Runnable {
251
252 private final boolean interactive;
253
254 FileSizeChecker(boolean interactive) {
255 this.interactive = interactive;
256 }
257
258
259 @Override
260 public void run() {
261 if (mUrl.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME)) {
262 retrieveUrl();
263 } else {
264 check();
265 }
266 }
267
268 private void retrieveUrl() {
269 changeStatus(STATUS_CHECKING);
270 final Account account = message.getConversation().getAccount();
271 IqPacket request = mXmppConnectionService.getIqGenerator().requestP1S3Url(Jid.of(account.getJid().getDomain()), mUrl.getHost());
272 mXmppConnectionService.sendIqPacket(message.getConversation().getAccount(), request, (a, packet) -> {
273 if (packet.getType() == IqPacket.TYPE.RESULT) {
274 String download = packet.query().getAttribute("download");
275 if (download != null) {
276 try {
277 mUrl = new URL(download);
278 check();
279 return;
280 } catch (MalformedURLException e) {
281 //fallthrough
282 }
283 }
284 }
285 Log.d(Config.LOGTAG, "unable to retrieve actual download url");
286 retrieveFailed(null);
287 });
288 }
289
290 private void retrieveFailed(@Nullable Exception e) {
291 changeStatus(STATUS_OFFER_CHECK_FILESIZE);
292 if (interactive) {
293 if (e != null) {
294 showToastForException(e);
295 }
296 } else {
297 HttpDownloadConnection.this.acceptedAutomatically = false;
298 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
299 }
300 cancel();
301 }
302
303 private void check() {
304 long size;
305 try {
306 size = retrieveFileSize();
307 } catch (Exception e) {
308 Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
309 retrieveFailed(e);
310 return;
311 }
312 final Message.FileParams fileParams = message.getFileParams();
313 FileBackend.updateFileParams(message, fileParams.url, size);
314 message.setOob(true);
315 mXmppConnectionService.databaseBackend.updateMessage(message, true);
316 file.setExpectedSize(size);
317 message.resetFileParams();
318 if (mHttpConnectionManager.hasStoragePermission()
319 && size <= mHttpConnectionManager.getAutoAcceptFileSize()
320 && mXmppConnectionService.isDataSaverDisabled()) {
321 HttpDownloadConnection.this.acceptedAutomatically = true;
322 download(interactive);
323 } else {
324 changeStatus(STATUS_OFFER);
325 HttpDownloadConnection.this.acceptedAutomatically = false;
326 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
327 }
328 }
329
330 private long retrieveFileSize() throws IOException {
331 try {
332 Log.d(Config.LOGTAG, "retrieve file size. interactive:" + String.valueOf(interactive));
333 changeStatus(STATUS_CHECKING);
334 HttpURLConnection connection;
335 final String hostname = mUrl.getHost();
336 final boolean onion = hostname != null && hostname.endsWith(".onion");
337 if (mUseTor || message.getConversation().getAccount().isOnion() || onion) {
338 connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy());
339 } else {
340 connection = (HttpURLConnection) mUrl.openConnection();
341 }
342 if (method == Method.P1_S3) {
343 connection.setRequestMethod("GET");
344 connection.addRequestProperty("Range", "bytes=0-0");
345 } else {
346 connection.setRequestMethod("HEAD");
347 }
348 connection.setUseCaches(false);
349 Log.d(Config.LOGTAG, "url: " + connection.getURL().toString());
350 connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
351 if (connection instanceof HttpsURLConnection) {
352 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
353 }
354 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
355 connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
356 connection.connect();
357 String contentLength;
358 if (method == Method.P1_S3) {
359 String contentRange = connection.getHeaderField("Content-Range");
360 String[] contentRangeParts = contentRange == null ? new String[0] : contentRange.split("/");
361 if (contentRangeParts.length != 2) {
362 contentLength = null;
363 } else {
364 contentLength = contentRangeParts[1];
365 }
366 } else {
367 contentLength = connection.getHeaderField("Content-Length");
368 }
369 connection.disconnect();
370 if (contentLength == null) {
371 throw new IOException("no content-length found in HEAD response");
372 }
373 return Long.parseLong(contentLength, 10);
374 } catch (IOException e) {
375 Log.d(Config.LOGTAG, "io exception during HEAD " + e.getMessage());
376 throw e;
377 } catch (NumberFormatException e) {
378 throw new IOException();
379 }
380 }
381
382 }
383
384 private class FileDownloader implements Runnable {
385
386 private final boolean interactive;
387
388 private OutputStream os;
389
390 public FileDownloader(boolean interactive) {
391 this.interactive = interactive;
392 }
393
394 @Override
395 public void run() {
396 try {
397 changeStatus(STATUS_DOWNLOADING);
398 download();
399 decryptIfNeeded();
400 updateImageBounds();
401 finish();
402 } catch (SSLHandshakeException e) {
403 changeStatus(STATUS_OFFER);
404 } catch (Exception 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 InputStream is = null;
417 HttpURLConnection connection = null;
418 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_download_" + message.getUuid());
419 try {
420 wakeLock.acquire();
421 if (mUseTor || message.getConversation().getAccount().isOnion()) {
422 connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy());
423 } else {
424 connection = (HttpURLConnection) mUrl.openConnection();
425 }
426 if (connection instanceof HttpsURLConnection) {
427 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
428 }
429 connection.setUseCaches(false);
430 connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
431 final long expected = file.getExpectedSize();
432 final boolean tryResume = file.exists() && file.getSize() > 0 && file.getSize() < expected;
433 long resumeSize = 0;
434
435 if (tryResume) {
436 resumeSize = file.getSize();
437 Log.d(Config.LOGTAG, "http download trying resume after " + resumeSize + " of " + expected);
438 connection.setRequestProperty("Range", "bytes=" + resumeSize + "-");
439 }
440 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
441 connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
442 connection.connect();
443 is = new BufferedInputStream(connection.getInputStream());
444 final String contentRange = connection.getHeaderField("Content-Range");
445 boolean serverResumed = tryResume && contentRange != null && contentRange.startsWith("bytes " + resumeSize + "-");
446 long transmitted = 0;
447 if (tryResume && serverResumed) {
448 Log.d(Config.LOGTAG, "server resumed");
449 transmitted = file.getSize();
450 updateProgress(Math.round(((double) transmitted / expected) * 100));
451 os = AbstractConnectionManager.createOutputStream(file, true, false);
452 if (os == null) {
453 throw new FileWriterException();
454 }
455 } else {
456 long reportedContentLengthOnGet;
457 try {
458 reportedContentLengthOnGet = Long.parseLong(connection.getHeaderField("Content-Length"));
459 } catch (NumberFormatException | NullPointerException e) {
460 reportedContentLengthOnGet = 0;
461 }
462 if (expected != reportedContentLengthOnGet) {
463 Log.d(Config.LOGTAG, "content-length reported on GET (" + reportedContentLengthOnGet + ") did not match Content-Length reported on HEAD (" + expected + ")");
464 }
465 file.getParentFile().mkdirs();
466 if (!file.exists() && !file.createNewFile()) {
467 throw new FileWriterException();
468 }
469 os = AbstractConnectionManager.createOutputStream(file, false, false);
470 }
471 int count;
472 byte[] buffer = new byte[4096];
473 while ((count = is.read(buffer)) != -1) {
474 transmitted += count;
475 try {
476 os.write(buffer, 0, count);
477 } catch (IOException e) {
478 throw new FileWriterException();
479 }
480 updateProgress(Math.round(((double) transmitted / expected) * 100));
481 if (canceled) {
482 throw new CancellationException();
483 }
484 }
485 try {
486 os.flush();
487 } catch (IOException e) {
488 throw new FileWriterException();
489 }
490 } catch (CancellationException | IOException e) {
491 Log.d(Config.LOGTAG, "http download failed " + e.getMessage());
492 throw e;
493 } finally {
494 FileBackend.close(os);
495 FileBackend.close(is);
496 if (connection != null) {
497 connection.disconnect();
498 }
499 WakeLockHelper.release(wakeLock);
500 }
501 }
502
503 private void updateImageBounds() {
504 final boolean privateMessage = message.isPrivateMessage();
505 message.setType(privateMessage ? Message.TYPE_PRIVATE_FILE : Message.TYPE_FILE);
506 final URL url;
507 final String ref = mUrl.getRef();
508 if (method == Method.P1_S3) {
509 url = message.getFileParams().url;
510 } else if (ref != null && AesGcmURLStreamHandler.IV_KEY.matcher(ref).matches()) {
511 url = CryptoHelper.toAesGcmUrl(mUrl);
512 } else {
513 url = mUrl;
514 }
515 mXmppConnectionService.getFileBackend().updateFileParams(message, url);
516 mXmppConnectionService.updateMessage(message);
517 }
518
519 }
520}