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 message.setTransferable(null);
135 if (message.isFileOrImage()) {
136 message.setDeleted(true);
137 }
138 mHttpConnectionManager.updateConversationUi(true);
139 }
140
141 private void finish() {
142 message.setTransferable(null);
143 mHttpConnectionManager.finishConnection(this);
144 boolean notify = acceptedAutomatically && !message.isRead();
145 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
146 notify = message.getConversation().getAccount().getPgpDecryptionService().decrypt(message, notify);
147 }
148 mHttpConnectionManager.updateConversationUi(true);
149 final boolean notifyAfterScan = notify;
150 mXmppConnectionService.getFileBackend().updateMediaScanner(file, () -> {
151 if (notifyAfterScan) {
152 mXmppConnectionService.getNotificationService().push(message);
153 }
154 });
155 }
156
157 private void changeStatus(int status) {
158 this.mStatus = status;
159 mHttpConnectionManager.updateConversationUi(true);
160 }
161
162 private void showToastForException(Exception e) {
163 if (e instanceof java.net.UnknownHostException) {
164 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
165 } else if (e instanceof java.net.ConnectException) {
166 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
167 } else if (e instanceof FileWriterException) {
168 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file);
169 } else if (!(e instanceof CancellationException)) {
170 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
171 }
172 }
173
174 private void updateProgress(long i) {
175 this.mProgress = (int) i;
176 mHttpConnectionManager.updateConversationUi(false);
177 }
178
179 @Override
180 public int getStatus() {
181 return this.mStatus;
182 }
183
184 @Override
185 public long getFileSize() {
186 if (this.file != null) {
187 return this.file.getExpectedSize();
188 } else {
189 return 0;
190 }
191 }
192
193 @Override
194 public int getProgress() {
195 return this.mProgress;
196 }
197
198 private class FileSizeChecker implements Runnable {
199
200 private final boolean interactive;
201
202 FileSizeChecker(boolean interactive) {
203 this.interactive = interactive;
204 }
205
206
207 @Override
208 public void run() {
209 if (mUrl.getProtocol().equalsIgnoreCase(P1S3UrlStreamHandler.PROTOCOL_NAME)) {
210 retrieveUrl();
211 } else {
212 check();
213 }
214 }
215
216 private void retrieveUrl() {
217 changeStatus(STATUS_CHECKING);
218 final Account account = message.getConversation().getAccount();
219 IqPacket request = mXmppConnectionService.getIqGenerator().requestP1S3Url(Jid.of(account.getJid().getDomain()), mUrl.getHost());
220 mXmppConnectionService.sendIqPacket(message.getConversation().getAccount(), request, (a, packet) -> {
221 if (packet.getType() == IqPacket.TYPE.RESULT) {
222 String download = packet.query().getAttribute("download");
223 if (download != null) {
224 try {
225 mUrl = new URL(download);
226 check();
227 return;
228 } catch (MalformedURLException e) {
229 //fallthrough
230 }
231 }
232 }
233 Log.d(Config.LOGTAG,"unable to retrieve actual download url");
234 retrieveFailed(null);
235 });
236 }
237
238 private void retrieveFailed(@Nullable Exception e) {
239 changeStatus(STATUS_OFFER_CHECK_FILESIZE);
240 if (interactive) {
241 if (e != null) {
242 showToastForException(e);
243 }
244 } else {
245 HttpDownloadConnection.this.acceptedAutomatically = false;
246 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
247 }
248 cancel();
249 }
250
251 private void check() {
252 long size;
253 try {
254 size = retrieveFileSize();
255 } catch (Exception e) {
256 Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
257 retrieveFailed(e);
258 return;
259 }
260 file.setExpectedSize(size);
261 message.resetFileParams();
262 if (mHttpConnectionManager.hasStoragePermission()
263 && size <= mHttpConnectionManager.getAutoAcceptFileSize()
264 && mXmppConnectionService.isDataSaverDisabled()) {
265 HttpDownloadConnection.this.acceptedAutomatically = true;
266 download(interactive);
267 } else {
268 changeStatus(STATUS_OFFER);
269 HttpDownloadConnection.this.acceptedAutomatically = false;
270 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
271 }
272 }
273
274 private long retrieveFileSize() throws IOException {
275 try {
276 Log.d(Config.LOGTAG, "retrieve file size. interactive:" + String.valueOf(interactive));
277 changeStatus(STATUS_CHECKING);
278 HttpURLConnection connection;
279 if (mUseTor || message.getConversation().getAccount().isOnion()) {
280 connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy());
281 } else {
282 connection = (HttpURLConnection) mUrl.openConnection();
283 }
284 if (method == Method.P1_S3) {
285 connection.setRequestMethod("GET");
286 connection.addRequestProperty("Range","bytes=0-0");
287 } else {
288 connection.setRequestMethod("HEAD");
289 }
290 connection.setUseCaches(false);
291 Log.d(Config.LOGTAG, "url: " + connection.getURL().toString());
292 connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
293 if (connection instanceof HttpsURLConnection) {
294 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
295 }
296 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
297 connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
298 connection.connect();
299 String contentLength;
300 if (method == Method.P1_S3) {
301 String contentRange = connection.getHeaderField("Content-Range");
302 String[] contentRangeParts = contentRange == null ? new String[0] : contentRange.split("/");
303 if (contentRangeParts.length != 2) {
304 contentLength = null;
305 } else {
306 contentLength = contentRangeParts[1];
307 }
308 } else {
309 contentLength = connection.getHeaderField("Content-Length");
310 }
311 connection.disconnect();
312 if (contentLength == null) {
313 throw new IOException("no content-length found in HEAD response");
314 }
315 return Long.parseLong(contentLength, 10);
316 } catch (IOException e) {
317 Log.d(Config.LOGTAG, "io exception during HEAD " + e.getMessage());
318 throw e;
319 } catch (NumberFormatException e) {
320 throw new IOException();
321 }
322 }
323
324 }
325
326 private class FileDownloader implements Runnable {
327
328 private final boolean interactive;
329
330 private OutputStream os;
331
332 public FileDownloader(boolean interactive) {
333 this.interactive = interactive;
334 }
335
336 @Override
337 public void run() {
338 try {
339 changeStatus(STATUS_DOWNLOADING);
340 download();
341 updateImageBounds();
342 finish();
343 } catch (SSLHandshakeException e) {
344 changeStatus(STATUS_OFFER);
345 } catch (Exception e) {
346 if (interactive) {
347 showToastForException(e);
348 } else {
349 HttpDownloadConnection.this.acceptedAutomatically = false;
350 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
351 }
352 cancel();
353 }
354 }
355
356 private void download() throws Exception {
357 InputStream is = null;
358 HttpURLConnection connection = null;
359 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_download_" + message.getUuid());
360 try {
361 wakeLock.acquire();
362 if (mUseTor || message.getConversation().getAccount().isOnion()) {
363 connection = (HttpURLConnection) mUrl.openConnection(HttpConnectionManager.getProxy());
364 } else {
365 connection = (HttpURLConnection) mUrl.openConnection();
366 }
367 if (connection instanceof HttpsURLConnection) {
368 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
369 }
370 connection.setUseCaches(false);
371 connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getUserAgent());
372 final boolean tryResume = file.exists() && file.getKey() == null && file.getSize() > 0;
373 long resumeSize = 0;
374 long expected = file.getExpectedSize();
375 if (tryResume) {
376 resumeSize = file.getSize();
377 Log.d(Config.LOGTAG, "http download trying resume after" + resumeSize + " of " + expected);
378 connection.setRequestProperty("Range", "bytes=" + resumeSize + "-");
379 }
380 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
381 connection.setReadTimeout(Config.SOCKET_TIMEOUT * 1000);
382 connection.connect();
383 is = new BufferedInputStream(connection.getInputStream());
384 final String contentRange = connection.getHeaderField("Content-Range");
385 boolean serverResumed = tryResume && contentRange != null && contentRange.startsWith("bytes " + resumeSize + "-");
386 long transmitted = 0;
387 if (tryResume && serverResumed) {
388 Log.d(Config.LOGTAG, "server resumed");
389 transmitted = file.getSize();
390 updateProgress(Math.round(((double) transmitted / expected) * 100));
391 os = AbstractConnectionManager.createAppendedOutputStream(file);
392 if (os == null) {
393 throw new FileWriterException();
394 }
395 } else {
396 long reportedContentLengthOnGet;
397 try {
398 reportedContentLengthOnGet = Long.parseLong(connection.getHeaderField("Content-Length"));
399 } catch (NumberFormatException | NullPointerException e) {
400 reportedContentLengthOnGet = 0;
401 }
402 if (expected != reportedContentLengthOnGet) {
403 Log.d(Config.LOGTAG, "content-length reported on GET (" + reportedContentLengthOnGet + ") did not match Content-Length reported on HEAD (" + expected + ")");
404 }
405 file.getParentFile().mkdirs();
406 if (!file.exists() && !file.createNewFile()) {
407 throw new FileWriterException();
408 }
409 os = AbstractConnectionManager.createOutputStream(file);
410 }
411 int count;
412 byte[] buffer = new byte[4096];
413 while ((count = is.read(buffer)) != -1) {
414 transmitted += count;
415 try {
416 os.write(buffer, 0, count);
417 } catch (IOException e) {
418 throw new FileWriterException();
419 }
420 updateProgress(Math.round(((double) transmitted / expected) * 100));
421 if (canceled) {
422 throw new CancellationException();
423 }
424 }
425 try {
426 os.flush();
427 } catch (IOException e) {
428 throw new FileWriterException();
429 }
430 } catch (CancellationException | IOException e) {
431 Log.d(Config.LOGTAG, "http download failed " + e.getMessage());
432 throw e;
433 } finally {
434 FileBackend.close(os);
435 FileBackend.close(is);
436 if (connection != null) {
437 connection.disconnect();
438 }
439 WakeLockHelper.release(wakeLock);
440 }
441 }
442
443 private void updateImageBounds() {
444 message.setType(Message.TYPE_FILE);
445 final URL url;
446 final String ref = mUrl.getRef();
447 if (method == Method.P1_S3) {
448 url = message.getFileParams().url;
449 } else if (ref != null && AesGcmURLStreamHandler.IV_KEY.matcher(ref).matches()) {
450 url = CryptoHelper.toAesGcmUrl(mUrl);
451 } else {
452 url = mUrl;
453 }
454 mXmppConnectionService.getFileBackend().updateFileParams(message, url);
455 mXmppConnectionService.updateMessage(message);
456 }
457
458 }
459}