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 boolean notify = acceptedAutomatically && !message.isRead();
130 if (message.getEncryption() == Message.ENCRYPTION_PGP) {
131 notify = message.getConversation().getAccount().getPgpDecryptionService().decrypt(message, notify);
132 }
133 mXmppConnectionService.updateConversationUi();
134 if (notify) {
135 mXmppConnectionService.getNotificationService().push(message);
136 }
137 }
138
139 private void changeStatus(int status) {
140 this.mStatus = status;
141 mXmppConnectionService.updateConversationUi();
142 }
143
144 private class WriteException extends IOException {
145
146 }
147
148 private void showToastForException(Exception e) {
149 e.printStackTrace();
150 if (e instanceof java.net.UnknownHostException) {
151 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_server_not_found);
152 } else if (e instanceof java.net.ConnectException) {
153 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_connect);
154 } else if (e instanceof WriteException) {
155 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_could_not_write_file);
156 } else if (!(e instanceof CancellationException)) {
157 mXmppConnectionService.showErrorToastInUi(R.string.download_failed_file_not_found);
158 }
159 }
160
161 private class FileSizeChecker implements Runnable {
162
163 private boolean interactive = false;
164
165 public FileSizeChecker(boolean interactive) {
166 this.interactive = interactive;
167 }
168
169 @Override
170 public void run() {
171 long size;
172 try {
173 size = retrieveFileSize();
174 } catch (SSLHandshakeException e) {
175 changeStatus(STATUS_OFFER_CHECK_FILESIZE);
176 HttpDownloadConnection.this.acceptedAutomatically = false;
177 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
178 return;
179 } catch (IOException e) {
180 Log.d(Config.LOGTAG, "io exception in http file size checker: " + e.getMessage());
181 if (interactive) {
182 showToastForException(e);
183 }
184 cancel();
185 return;
186 }
187 file.setExpectedSize(size);
188 if (mHttpConnectionManager.hasStoragePermission() && size <= mHttpConnectionManager.getAutoAcceptFileSize()) {
189 HttpDownloadConnection.this.acceptedAutomatically = true;
190 new Thread(new FileDownloader(interactive)).start();
191 } else {
192 changeStatus(STATUS_OFFER);
193 HttpDownloadConnection.this.acceptedAutomatically = false;
194 HttpDownloadConnection.this.mXmppConnectionService.getNotificationService().push(message);
195 }
196 }
197
198 private long retrieveFileSize() throws IOException {
199 try {
200 Log.d(Config.LOGTAG, "retrieve file size. interactive:" + String.valueOf(interactive));
201 changeStatus(STATUS_CHECKING);
202 HttpURLConnection connection;
203 if (mUseTor) {
204 connection = (HttpURLConnection) mUrl.openConnection(mHttpConnectionManager.getProxy());
205 } else {
206 connection = (HttpURLConnection) mUrl.openConnection();
207 }
208 connection.setRequestMethod("HEAD");
209 Log.d(Config.LOGTAG,"url: "+connection.getURL().toString());
210 Log.d(Config.LOGTAG,"connection: "+connection.toString());
211 connection.setRequestProperty("User-Agent", mXmppConnectionService.getIqGenerator().getIdentityName());
212 if (connection instanceof HttpsURLConnection) {
213 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
214 }
215 connection.connect();
216 String contentLength = connection.getHeaderField("Content-Length");
217 connection.disconnect();
218 if (contentLength == null) {
219 throw new IOException();
220 }
221 return Long.parseLong(contentLength, 10);
222 } catch (IOException e) {
223 throw e;
224 } catch (NumberFormatException e) {
225 throw new IOException();
226 }
227 }
228
229 }
230
231 private class FileDownloader implements Runnable {
232
233 private boolean interactive = false;
234
235 private OutputStream os;
236
237 public FileDownloader(boolean interactive) {
238 this.interactive = interactive;
239 }
240
241 @Override
242 public void run() {
243 try {
244 changeStatus(STATUS_DOWNLOADING);
245 download();
246 updateImageBounds();
247 finish();
248 } catch (SSLHandshakeException e) {
249 changeStatus(STATUS_OFFER);
250 } catch (Exception e) {
251 if (interactive) {
252 showToastForException(e);
253 }
254 cancel();
255 }
256 }
257
258 private void download() throws Exception {
259 InputStream is = null;
260 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_download_"+message.getUuid());
261 try {
262 wakeLock.acquire();
263 HttpURLConnection connection;
264 if (mUseTor) {
265 connection = (HttpURLConnection) mUrl.openConnection(mHttpConnectionManager.getProxy());
266 } else {
267 connection = (HttpURLConnection) mUrl.openConnection();
268 }
269 if (connection instanceof HttpsURLConnection) {
270 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, interactive);
271 }
272 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
273 final boolean tryResume = file.exists() && file.getKey() == null;
274 if (tryResume) {
275 Log.d(Config.LOGTAG,"http download trying resume");
276 long size = file.getSize();
277 connection.setRequestProperty("Range", "bytes="+size+"-");
278 }
279 connection.connect();
280 is = new BufferedInputStream(connection.getInputStream());
281 boolean serverResumed = "bytes".equals(connection.getHeaderField("Accept-Ranges"));
282 long transmitted = 0;
283 long expected = file.getExpectedSize();
284 if (tryResume && serverResumed) {
285 Log.d(Config.LOGTAG,"server resumed");
286 transmitted = file.getSize();
287 updateProgress((int) ((((double) transmitted) / expected) * 100));
288 os = AbstractConnectionManager.createAppendedOutputStream(file);
289 } else {
290 file.getParentFile().mkdirs();
291 file.createNewFile();
292 os = AbstractConnectionManager.createOutputStream(file, true);
293 }
294 int count;
295 byte[] buffer = new byte[1024];
296 while ((count = is.read(buffer)) != -1) {
297 transmitted += count;
298 try {
299 os.write(buffer, 0, count);
300 } catch (IOException e) {
301 throw new WriteException();
302 }
303 updateProgress((int) ((((double) transmitted) / expected) * 100));
304 if (canceled) {
305 throw new CancellationException();
306 }
307 }
308 try {
309 os.flush();
310 } catch (IOException e) {
311 throw new WriteException();
312 }
313 } catch (CancellationException | IOException e) {
314 throw e;
315 } finally {
316 FileBackend.close(os);
317 FileBackend.close(is);
318 wakeLock.release();
319 }
320 }
321
322 private void updateImageBounds() {
323 message.setType(Message.TYPE_FILE);
324 mXmppConnectionService.getFileBackend().updateFileParams(message, mUrl);
325 mXmppConnectionService.updateMessage(message);
326 }
327
328 }
329
330 public void updateProgress(int i) {
331 this.mProgress = i;
332 mXmppConnectionService.updateConversationUi();
333 }
334
335 @Override
336 public int getStatus() {
337 return this.mStatus;
338 }
339
340 @Override
341 public long getFileSize() {
342 if (this.file != null) {
343 return this.file.getExpectedSize();
344 } else {
345 return 0;
346 }
347 }
348
349 @Override
350 public int getProgress() {
351 return this.mProgress;
352 }
353}