HttpDownloadConnection.java

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