1package eu.siacs.conversations.http;
2
3import android.os.PowerManager;
4import android.util.Log;
5
6import java.io.FileInputStream;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.net.HttpURLConnection;
10import java.net.URL;
11import java.util.Arrays;
12import java.util.HashMap;
13import java.util.List;
14import java.util.Scanner;
15
16import javax.net.ssl.HttpsURLConnection;
17
18import eu.siacs.conversations.Config;
19import eu.siacs.conversations.entities.Account;
20import eu.siacs.conversations.entities.DownloadableFile;
21import eu.siacs.conversations.entities.Message;
22import eu.siacs.conversations.entities.Transferable;
23import eu.siacs.conversations.persistance.FileBackend;
24import eu.siacs.conversations.services.AbstractConnectionManager;
25import eu.siacs.conversations.services.XmppConnectionService;
26import eu.siacs.conversations.utils.Checksum;
27import eu.siacs.conversations.utils.CryptoHelper;
28import eu.siacs.conversations.utils.WakeLockHelper;
29
30public class HttpUploadConnection implements Transferable {
31
32 static final List<String> WHITE_LISTED_HEADERS = Arrays.asList(
33 "Authorization",
34 "Cookie",
35 "Expires"
36 );
37
38 private final HttpConnectionManager mHttpConnectionManager;
39 private final XmppConnectionService mXmppConnectionService;
40 private final SlotRequester mSlotRequester;
41 private final Method method;
42 private final boolean mUseTor;
43 private boolean cancelled = false;
44 private boolean delayed = false;
45 private DownloadableFile file;
46 private Message message;
47 private String mime;
48 private SlotRequester.Slot slot;
49 private byte[] key = null;
50
51 private long transmitted = 0;
52
53 public HttpUploadConnection(Method method, HttpConnectionManager httpConnectionManager) {
54 this.method = method;
55 this.mHttpConnectionManager = httpConnectionManager;
56 this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
57 this.mSlotRequester = new SlotRequester(this.mXmppConnectionService);
58 this.mUseTor = mXmppConnectionService.useTorToConnect();
59 }
60
61 @Override
62 public boolean start() {
63 return false;
64 }
65
66 @Override
67 public int getStatus() {
68 return STATUS_UPLOADING;
69 }
70
71 @Override
72 public long getFileSize() {
73 return file == null ? 0 : file.getExpectedSize();
74 }
75
76 @Override
77 public int getProgress() {
78 if (file == null) {
79 return 0;
80 }
81 return (int) ((((double) transmitted) / file.getExpectedSize()) * 100);
82 }
83
84 @Override
85 public void cancel() {
86 this.cancelled = true;
87 }
88
89 private void fail(String errorMessage) {
90 mHttpConnectionManager.finishUploadConnection(this);
91 message.setTransferable(null);
92 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
93 }
94
95 public void init(Message message, boolean delay) {
96 this.message = message;
97 final Account account = message.getConversation().getAccount();
98 this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
99 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
100 this.mime = "application/pgp-encrypted";
101 } else {
102 this.mime = this.file.getMimeType();
103 }
104 this.delayed = delay;
105 if (Config.ENCRYPT_ON_HTTP_UPLOADED
106 || message.getEncryption() == Message.ENCRYPTION_AXOLOTL
107 || message.getEncryption() == Message.ENCRYPTION_OTR) {
108 this.key = new byte[48];
109 mXmppConnectionService.getRNG().nextBytes(this.key);
110 this.file.setKeyAndIv(this.key);
111 }
112
113 final String md5;
114
115 if (method == Method.P1_S3) {
116 try {
117 md5 = Checksum.md5(AbstractConnectionManager.upgrade(file, new FileInputStream(file)));
118 } catch (Exception e) {
119 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": unable to calculate md5()", e);
120 fail(e.getMessage());
121 return;
122 }
123 } else {
124 md5 = null;
125 }
126
127 this.file.setExpectedSize(file.getSize() + (file.getKey() != null ? 16 : 0));
128 message.resetFileParams();
129 this.mSlotRequester.request(method, account, file, mime, md5, new SlotRequester.OnSlotRequested() {
130 @Override
131 public void success(SlotRequester.Slot slot) {
132 if (!cancelled) {
133 HttpUploadConnection.this.slot = slot;
134 new Thread(HttpUploadConnection.this::upload).start();
135 }
136 }
137
138 @Override
139 public void failure(String message) {
140 fail(message);
141 }
142 });
143 message.setTransferable(this);
144 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
145 }
146
147 private void upload() {
148 OutputStream os = null;
149 InputStream fileInputStream = null;
150 HttpURLConnection connection = null;
151 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
152 try {
153 fileInputStream = new FileInputStream(file);
154 final int expectedFileSize = (int) file.getExpectedSize();
155 final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s
156 wakeLock.acquire(readTimeout);
157 Log.d(Config.LOGTAG, "uploading to " + slot.getPutUrl().toString()+ " w/ read timeout of "+readTimeout+"s");
158 if (mUseTor || message.getConversation().getAccount().isOnion()) {
159 connection = (HttpURLConnection) slot.getPutUrl().openConnection(HttpConnectionManager.getProxy());
160 } else {
161 connection = (HttpURLConnection) slot.getPutUrl().openConnection();
162 }
163 if (connection instanceof HttpsURLConnection) {
164 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
165 }
166 connection.setUseCaches(false);
167 connection.setRequestMethod("PUT");
168 connection.setFixedLengthStreamingMode(expectedFileSize);
169 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getUserAgent());
170 if(slot.getHeaders() != null) {
171 for(HashMap.Entry<String,String> entry : slot.getHeaders().entrySet()) {
172 connection.setRequestProperty(entry.getKey(),entry.getValue());
173 }
174 }
175 connection.setDoOutput(true);
176 connection.setDoInput(true);
177 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
178 connection.setReadTimeout(readTimeout * 1000);
179 connection.connect();
180 final InputStream innerInputStream = AbstractConnectionManager.upgrade(file, fileInputStream);
181 os = connection.getOutputStream();
182 transmitted = 0;
183 int count;
184 byte[] buffer = new byte[4096];
185 while (((count = innerInputStream.read(buffer)) != -1) && !cancelled) {
186 transmitted += count;
187 os.write(buffer, 0, count);
188 mHttpConnectionManager.updateConversationUi(false);
189 }
190 os.flush();
191 os.close();
192 int code = connection.getResponseCode();
193 InputStream is = connection.getErrorStream();
194 if (is != null) {
195 try (Scanner scanner = new Scanner(is)) {
196 scanner.useDelimiter("\\Z");
197 Log.d(Config.LOGTAG, "body: " + scanner.next());
198 }
199 }
200 if (code == 200 || code == 201) {
201 Log.d(Config.LOGTAG, "finished uploading file");
202 final URL get;
203 if (key != null) {
204 if (method == Method.P1_S3) {
205 get = new URL(slot.getGetUrl().toString()+"#"+CryptoHelper.bytesToHex(key));
206 } else {
207 get = CryptoHelper.toAesGcmUrl(new URL(slot.getGetUrl().toString() + "#" + CryptoHelper.bytesToHex(key)));
208 }
209 } else {
210 get = slot.getGetUrl();
211 }
212 mXmppConnectionService.getFileBackend().updateFileParams(message, get);
213 mXmppConnectionService.getFileBackend().updateMediaScanner(file);
214 message.setTransferable(null);
215 message.setCounterpart(message.getConversation().getJid().asBareJid());
216 mXmppConnectionService.resendMessage(message, delayed);
217 } else {
218 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
219 fail("http upload failed because response code was "+code);
220 }
221 } catch (Exception e) {
222 e.printStackTrace();
223 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
224 fail(e.getMessage());
225 } finally {
226 FileBackend.close(fileInputStream);
227 FileBackend.close(os);
228 if (connection != null) {
229 connection.disconnect();
230 }
231 WakeLockHelper.release(wakeLock);
232 }
233 }
234}