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