HttpUploadConnection.java

  1package eu.siacs.conversations.http;
  2
  3import android.app.PendingIntent;
  4import android.content.Intent;
  5import android.net.Uri;
  6import android.util.Log;
  7
  8import org.bouncycastle.crypto.engines.AESEngine;
  9import org.bouncycastle.crypto.io.CipherInputStream;
 10import org.bouncycastle.crypto.modes.AEADBlockCipher;
 11import org.bouncycastle.crypto.modes.GCMBlockCipher;
 12import org.bouncycastle.crypto.params.AEADParameters;
 13import org.bouncycastle.crypto.params.KeyParameter;
 14
 15import java.io.FileInputStream;
 16import java.io.IOException;
 17import java.io.InputStream;
 18import java.io.OutputStream;
 19import java.net.HttpURLConnection;
 20import java.net.MalformedURLException;
 21import java.net.URL;
 22
 23import javax.net.ssl.HttpsURLConnection;
 24
 25import eu.siacs.conversations.Config;
 26import eu.siacs.conversations.entities.Account;
 27import eu.siacs.conversations.entities.DownloadableFile;
 28import eu.siacs.conversations.entities.Message;
 29import eu.siacs.conversations.entities.Transferable;
 30import eu.siacs.conversations.persistance.FileBackend;
 31import eu.siacs.conversations.services.XmppConnectionService;
 32import eu.siacs.conversations.ui.UiCallback;
 33import eu.siacs.conversations.utils.CryptoHelper;
 34import eu.siacs.conversations.utils.Xmlns;
 35import eu.siacs.conversations.xml.Element;
 36import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 37import eu.siacs.conversations.xmpp.jid.Jid;
 38import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 39
 40public class HttpUploadConnection implements Transferable {
 41
 42	private HttpConnectionManager mHttpConnectionManager;
 43	private XmppConnectionService mXmppConnectionService;
 44
 45	private boolean canceled = false;
 46	private boolean delayed = false;
 47	private Account account;
 48	private DownloadableFile file;
 49	private Message message;
 50	private URL mGetUrl;
 51	private URL mPutUrl;
 52
 53	private byte[] key = null;
 54
 55	private long transmitted = 0;
 56	private int expected = 1;
 57
 58	public HttpUploadConnection(HttpConnectionManager httpConnectionManager) {
 59		this.mHttpConnectionManager = httpConnectionManager;
 60		this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
 61	}
 62
 63	@Override
 64	public boolean start() {
 65		return false;
 66	}
 67
 68	@Override
 69	public int getStatus() {
 70		return STATUS_UPLOADING;
 71	}
 72
 73	@Override
 74	public long getFileSize() {
 75		return this.file.getExpectedSize();
 76	}
 77
 78	@Override
 79	public int getProgress() {
 80		return (int) ((((double) transmitted) / expected) * 100);
 81	}
 82
 83	@Override
 84	public void cancel() {
 85		this.canceled = true;
 86	}
 87
 88	private void fail() {
 89		mHttpConnectionManager.finishUploadConnection(this);
 90		message.setTransferable(null);
 91		mXmppConnectionService.markMessage(message,Message.STATUS_SEND_FAILED);
 92	}
 93
 94	public void init(Message message, boolean delay) {
 95		this.message = message;
 96		message.setTransferable(this);
 97		mXmppConnectionService.markMessage(message,Message.STATUS_UNSEND);
 98		this.account = message.getConversation().getAccount();
 99		this.file = mXmppConnectionService.getFileBackend().getFile(message, false);
100		this.file.setExpectedSize(this.file.getSize());
101		this.delayed = delay;
102
103		if (Config.ENCRYPT_ON_HTTP_UPLOADED
104				|| message.getEncryption() == Message.ENCRYPTION_AXOLOTL
105				|| message.getEncryption() == Message.ENCRYPTION_OTR) {
106			this.key = new byte[48];
107			mXmppConnectionService.getRNG().nextBytes(this.key);
108			this.file.setKey(this.key);
109		}
110
111		Jid host = account.getXmppConnection().findDiscoItemByFeature(Xmlns.HTTP_UPLOAD);
112		IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file);
113		mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
114			@Override
115			public void onIqPacketReceived(Account account, IqPacket packet) {
116				if (packet.getType() == IqPacket.TYPE.RESULT) {
117					Element slot = packet.findChild("slot",Xmlns.HTTP_UPLOAD);
118					if (slot != null) {
119						try {
120							mGetUrl = new URL(slot.findChildContent("get"));
121							mPutUrl = new URL(slot.findChildContent("put"));
122							if (!canceled) {
123								new Thread(new FileUploader()).start();
124							}
125						} catch (MalformedURLException e) {
126							fail();
127						}
128					} else {
129						fail();
130					}
131				} else {
132					fail();
133				}
134			}
135		});
136	}
137
138	private class FileUploader implements Runnable {
139
140		@Override
141		public void run() {
142			this.upload();
143		}
144
145		private void upload() {
146			OutputStream os = null;
147			InputStream is = null;
148			HttpURLConnection connection = null;
149			try {
150				Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString());
151				connection = (HttpURLConnection) mPutUrl.openConnection();
152				if (connection instanceof HttpsURLConnection) {
153					mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
154				}
155				if (file.getKey() != null) {
156					AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
157					cipher.init(true, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv()));
158					expected = cipher.getOutputSize((int) file.getSize());
159					is = new CipherInputStream(new FileInputStream(file), cipher);
160				} else {
161					expected = (int) file.getSize();
162					is = new FileInputStream(file);
163				}
164				connection.setRequestMethod("PUT");
165				connection.setFixedLengthStreamingMode(expected);
166				connection.setDoOutput(true);
167				connection.connect();
168				os = connection.getOutputStream();
169				transmitted = 0;
170				int count = -1;
171				byte[] buffer = new byte[4096];
172				while (((count = is.read(buffer)) != -1) && !canceled) {
173					transmitted += count;
174					os.write(buffer, 0, count);
175					mXmppConnectionService.updateConversationUi();
176				}
177				os.flush();
178				os.close();
179				is.close();
180				int code = connection.getResponseCode();
181				if (code == 200 || code == 201) {
182					Log.d(Config.LOGTAG, "finished uploading file");
183					if (key != null) {
184						mGetUrl = new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key));
185					}
186					mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
187					Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
188					intent.setData(Uri.fromFile(file));
189					mXmppConnectionService.sendBroadcast(intent);
190					message.setTransferable(null);
191					message.setCounterpart(message.getConversation().getJid().toBareJid());
192					if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
193						mXmppConnectionService.getPgpEngine().encrypt(message, new UiCallback<Message>() {
194							@Override
195							public void success(Message message) {
196								mXmppConnectionService.resendMessage(message,delayed);
197							}
198
199							@Override
200							public void error(int errorCode, Message object) {
201								fail();
202							}
203
204							@Override
205							public void userInputRequried(PendingIntent pi, Message object) {
206								fail();
207							}
208						});
209					} else {
210						mXmppConnectionService.resendMessage(message, delayed);
211					}
212				} else {
213					fail();
214				}
215			} catch (IOException e) {
216				e.printStackTrace();
217				Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
218				fail();
219			} finally {
220				FileBackend.close(is);
221				FileBackend.close(os);
222				if (connection != null) {
223					connection.disconnect();
224				}
225			}
226		}
227	}
228}