HttpDownloadConnection.java

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