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 final 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(Message message, Method method, HttpConnectionManager httpConnectionManager) {
54 this.message = message;
55 this.method = method;
56 this.mHttpConnectionManager = httpConnectionManager;
57 this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
58 this.mSlotRequester = new SlotRequester(this.mXmppConnectionService);
59 this.mUseTor = mXmppConnectionService.useTorToConnect();
60 }
61
62 @Override
63 public boolean start() {
64 return false;
65 }
66
67 @Override
68 public int getStatus() {
69 return STATUS_UPLOADING;
70 }
71
72 @Override
73 public long getFileSize() {
74 return file == null ? 0 : file.getExpectedSize();
75 }
76
77 @Override
78 public int getProgress() {
79 if (file == null) {
80 return 0;
81 }
82 return (int) ((((double) transmitted) / file.getExpectedSize()) * 100);
83 }
84
85 @Override
86 public void cancel() {
87 this.cancelled = true;
88 }
89
90 private void fail(String errorMessage) {
91 finish();
92 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, cancelled ? Message.ERROR_MESSAGE_CANCELLED : errorMessage);
93 }
94
95 private void finish() {
96 mHttpConnectionManager.finishUploadConnection(this);
97 message.setTransferable(null);
98 }
99
100 public void init(boolean delay) {
101 final Account account = message.getConversation().getAccount();
102 this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
103 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
104 this.mime = "application/pgp-encrypted";
105 } else {
106 this.mime = this.file.getMimeType();
107 }
108 final long originalFileSize = file.getSize();
109 this.delayed = delay;
110 if (Config.ENCRYPT_ON_HTTP_UPLOADED
111 || message.getEncryption() == Message.ENCRYPTION_AXOLOTL
112 || message.getEncryption() == Message.ENCRYPTION_OTR) {
113 //ok, this is going to sound super crazy but on Android 9+ a 12 byte IV will use the
114 //internal conscrypt library (provided by the OS) instead of bounce castle, while 16 bytes
115 //will still 'fallback' to bounce castle even on Android 9+ because conscrypt doesnt
116 //have support for anything but 12.
117 //For large files conscrypt has extremely bad performance; so why not always use 16 you ask?
118 //well the ecosystem was moving and some clients like Monal *only* support 12
119 //so the result of this code is that we can only send 'small' files to Monal.
120 //'small' was relatively arbitrarily choose and correlates to roughly 'small' compressed images
121 this.key = new byte[originalFileSize <= 786432 ? 44 : 48];
122 mXmppConnectionService.getRNG().nextBytes(this.key);
123 this.file.setKeyAndIv(this.key);
124 }
125
126 final String md5;
127
128 if (method == Method.P1_S3) {
129 try {
130 md5 = Checksum.md5(AbstractConnectionManager.upgrade(file, new FileInputStream(file)));
131 } catch (Exception e) {
132 Log.d(Config.LOGTAG, account.getJid().asBareJid()+": unable to calculate md5()", e);
133 fail(e.getMessage());
134 return;
135 }
136 } else {
137 md5 = null;
138 }
139
140 this.file.setExpectedSize(originalFileSize + (file.getKey() != null ? 16 : 0));
141 message.resetFileParams();
142 this.mSlotRequester.request(method, account, file, mime, md5, new SlotRequester.OnSlotRequested() {
143 @Override
144 public void success(SlotRequester.Slot slot) {
145 if (!cancelled) {
146 HttpUploadConnection.this.slot = slot;
147 new Thread(HttpUploadConnection.this::upload).start();
148 }
149 }
150
151 @Override
152 public void failure(String message) {
153 fail(message);
154 }
155 });
156 message.setTransferable(this);
157 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
158 }
159
160 private void upload() {
161 OutputStream os = null;
162 InputStream fileInputStream = null;
163 HttpURLConnection connection = null;
164 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
165 try {
166 fileInputStream = new FileInputStream(file);
167 final String slotHostname = slot.getPutUrl().getHost();
168 final boolean onionSlot = slotHostname != null && slotHostname.endsWith(".onion");
169 final int expectedFileSize = (int) file.getExpectedSize();
170 final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s
171 wakeLock.acquire(readTimeout);
172 Log.d(Config.LOGTAG, "uploading to " + slot.getPutUrl().toString()+ " w/ read timeout of "+readTimeout+"s");
173
174 if (mUseTor || message.getConversation().getAccount().isOnion() || onionSlot) {
175 connection = (HttpURLConnection) slot.getPutUrl().openConnection(HttpConnectionManager.getProxy());
176 } else {
177 connection = (HttpURLConnection) slot.getPutUrl().openConnection();
178 }
179 if (connection instanceof HttpsURLConnection) {
180 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
181 }
182 connection.setUseCaches(false);
183 connection.setRequestMethod("PUT");
184 connection.setFixedLengthStreamingMode(expectedFileSize);
185 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getUserAgent());
186 if(slot.getHeaders() != null) {
187 for(HashMap.Entry<String,String> entry : slot.getHeaders().entrySet()) {
188 connection.setRequestProperty(entry.getKey(),entry.getValue());
189 }
190 }
191 connection.setDoOutput(true);
192 connection.setDoInput(true);
193 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
194 connection.setReadTimeout(readTimeout * 1000);
195 connection.connect();
196 final InputStream innerInputStream = AbstractConnectionManager.upgrade(file, fileInputStream);
197 os = connection.getOutputStream();
198 transmitted = 0;
199 int count;
200 byte[] buffer = new byte[4096];
201 while (((count = innerInputStream.read(buffer)) != -1) && !cancelled) {
202 transmitted += count;
203 os.write(buffer, 0, count);
204 mHttpConnectionManager.updateConversationUi(false);
205 }
206 os.flush();
207 os.close();
208 int code = connection.getResponseCode();
209 InputStream is = connection.getErrorStream();
210 if (is != null) {
211 try (Scanner scanner = new Scanner(is)) {
212 scanner.useDelimiter("\\Z");
213 Log.d(Config.LOGTAG, "body: " + scanner.next());
214 }
215 }
216 if (code == 200 || code == 201) {
217 Log.d(Config.LOGTAG, "finished uploading file");
218 final URL get;
219 if (key != null) {
220 if (method == Method.P1_S3) {
221 get = new URL(slot.getGetUrl().toString()+"#"+CryptoHelper.bytesToHex(key));
222 } else {
223 get = CryptoHelper.toAesGcmUrl(new URL(slot.getGetUrl().toString() + "#" + CryptoHelper.bytesToHex(key)));
224 }
225 } else {
226 get = slot.getGetUrl();
227 }
228 mXmppConnectionService.getFileBackend().updateFileParams(message, get);
229 mXmppConnectionService.getFileBackend().updateMediaScanner(file);
230 finish();
231 if (!message.isPrivateMessage()) {
232 message.setCounterpart(message.getConversation().getJid().asBareJid());
233 }
234 mXmppConnectionService.resendMessage(message, delayed);
235 } else {
236 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
237 fail("http upload failed because response code was "+code);
238 }
239 } catch (Exception e) {
240 e.printStackTrace();
241 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
242 fail(e.getMessage());
243 } finally {
244 FileBackend.close(fileInputStream);
245 FileBackend.close(os);
246 if (connection != null) {
247 connection.disconnect();
248 }
249 WakeLockHelper.release(wakeLock);
250 }
251 }
252
253 public Message getMessage() {
254 return message;
255 }
256}