HttpUploadConnection.java

  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			this.key = new byte[44];
114			mXmppConnectionService.getRNG().nextBytes(this.key);
115			this.file.setKeyAndIv(this.key);
116		}
117
118		final String md5;
119
120		if (method == Method.P1_S3) {
121			try {
122				md5 = Checksum.md5(AbstractConnectionManager.upgrade(file, new FileInputStream(file)));
123			} catch (Exception e) {
124				Log.d(Config.LOGTAG, account.getJid().asBareJid()+": unable to calculate md5()", e);
125				fail(e.getMessage());
126				return;
127			}
128		} else {
129			md5 = null;
130		}
131
132		this.file.setExpectedSize(originalFileSize + (file.getKey() != null ? 16 : 0));
133		message.resetFileParams();
134		this.mSlotRequester.request(method, account, file, mime, md5, new SlotRequester.OnSlotRequested() {
135			@Override
136			public void success(SlotRequester.Slot slot) {
137				if (!cancelled) {
138					HttpUploadConnection.this.slot = slot;
139					new Thread(HttpUploadConnection.this::upload).start();
140				}
141			}
142
143			@Override
144			public void failure(String message) {
145				fail(message);
146			}
147		});
148		message.setTransferable(this);
149		mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
150	}
151
152	private void upload() {
153		OutputStream os = null;
154		InputStream fileInputStream = null;
155		HttpURLConnection connection = null;
156		PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
157		try {
158			fileInputStream = new FileInputStream(file);
159			final String slotHostname = slot.getPutUrl().getHost();
160			final boolean onionSlot = slotHostname != null && slotHostname.endsWith(".onion");
161			final int expectedFileSize = (int) file.getExpectedSize();
162			final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s
163			wakeLock.acquire(readTimeout);
164			Log.d(Config.LOGTAG, "uploading to " + slot.getPutUrl().toString()+ " w/ read timeout of "+readTimeout+"s");
165
166			if (mUseTor || message.getConversation().getAccount().isOnion() || onionSlot) {
167				connection = (HttpURLConnection) slot.getPutUrl().openConnection(HttpConnectionManager.getProxy());
168			} else {
169				connection = (HttpURLConnection) slot.getPutUrl().openConnection();
170			}
171			if (connection instanceof HttpsURLConnection) {
172				mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
173			}
174			connection.setUseCaches(false);
175			connection.setRequestMethod("PUT");
176			connection.setFixedLengthStreamingMode(expectedFileSize);
177			connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getUserAgent());
178			if(slot.getHeaders() != null) {
179				for(HashMap.Entry<String,String> entry : slot.getHeaders().entrySet()) {
180					connection.setRequestProperty(entry.getKey(),entry.getValue());
181				}
182			}
183			connection.setDoOutput(true);
184			connection.setDoInput(true);
185			connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
186			connection.setReadTimeout(readTimeout * 1000);
187			connection.connect();
188			final InputStream innerInputStream = AbstractConnectionManager.upgrade(file, fileInputStream);
189			os = connection.getOutputStream();
190			transmitted = 0;
191			int count;
192			byte[] buffer = new byte[4096];
193			while (((count = innerInputStream.read(buffer)) != -1) && !cancelled) {
194				transmitted += count;
195				os.write(buffer, 0, count);
196				mHttpConnectionManager.updateConversationUi(false);
197			}
198			os.flush();
199			os.close();
200			int code = connection.getResponseCode();
201			InputStream is = connection.getErrorStream();
202			if (is != null) {
203				try (Scanner scanner = new Scanner(is)) {
204					scanner.useDelimiter("\\Z");
205					Log.d(Config.LOGTAG, "body: " + scanner.next());
206				}
207			}
208			if (code == 200 || code == 201) {
209				Log.d(Config.LOGTAG, "finished uploading file");
210				final URL get;
211				if (key != null) {
212					if (method == Method.P1_S3) {
213						get = new URL(slot.getGetUrl().toString()+"#"+CryptoHelper.bytesToHex(key));
214					} else {
215						get = CryptoHelper.toAesGcmUrl(new URL(slot.getGetUrl().toString() + "#" + CryptoHelper.bytesToHex(key)));
216					}
217				} else {
218					get = slot.getGetUrl();
219				}
220				mXmppConnectionService.getFileBackend().updateFileParams(message, get);
221				mXmppConnectionService.getFileBackend().updateMediaScanner(file);
222				finish();
223				if (!message.isPrivateMessage()) {
224					message.setCounterpart(message.getConversation().getJid().asBareJid());
225				}
226				mXmppConnectionService.resendMessage(message, delayed);
227			} else {
228				Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
229				fail("http upload failed because response code was "+code);
230			}
231		} catch (Exception e) {
232			e.printStackTrace();
233			Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
234			fail(e.getMessage());
235		} finally {
236			FileBackend.close(fileInputStream);
237			FileBackend.close(os);
238			if (connection != null) {
239				connection.disconnect();
240			}
241			WakeLockHelper.release(wakeLock);
242		}
243	}
244
245	public Message getMessage() {
246		return message;
247	}
248}