1package eu.siacs.conversations.http;
2
3import android.os.PowerManager;
4import android.util.Log;
5import android.util.Pair;
6
7import java.io.FileNotFoundException;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.OutputStream;
11import java.net.HttpURLConnection;
12import java.net.MalformedURLException;
13import java.net.URL;
14
15import javax.net.ssl.HttpsURLConnection;
16
17import eu.siacs.conversations.Config;
18import eu.siacs.conversations.entities.Account;
19import eu.siacs.conversations.entities.DownloadableFile;
20import eu.siacs.conversations.entities.Message;
21import eu.siacs.conversations.entities.Transferable;
22import eu.siacs.conversations.parser.IqParser;
23import eu.siacs.conversations.persistance.FileBackend;
24import eu.siacs.conversations.services.AbstractConnectionManager;
25import eu.siacs.conversations.services.XmppConnectionService;
26import eu.siacs.conversations.utils.CryptoHelper;
27import eu.siacs.conversations.xml.Namespace;
28import eu.siacs.conversations.xml.Element;
29import eu.siacs.conversations.xmpp.OnIqPacketReceived;
30import eu.siacs.conversations.xmpp.jid.Jid;
31import eu.siacs.conversations.xmpp.stanzas.IqPacket;
32
33public class HttpUploadConnection implements Transferable {
34
35 private HttpConnectionManager mHttpConnectionManager;
36 private XmppConnectionService mXmppConnectionService;
37
38 private boolean canceled = false;
39 private boolean delayed = false;
40 private Account account;
41 private DownloadableFile file;
42 private Message message;
43 private String mime;
44 private URL mGetUrl;
45 private URL mPutUrl;
46 private boolean mUseTor = false;
47
48 private byte[] key = null;
49
50 private long transmitted = 0;
51
52 private InputStream mFileInputStream;
53
54 public HttpUploadConnection(HttpConnectionManager httpConnectionManager) {
55 this.mHttpConnectionManager = httpConnectionManager;
56 this.mXmppConnectionService = httpConnectionManager.getXmppConnectionService();
57 this.mUseTor = mXmppConnectionService.useTorToConnect();
58 }
59
60 @Override
61 public boolean start() {
62 return false;
63 }
64
65 @Override
66 public int getStatus() {
67 return STATUS_UPLOADING;
68 }
69
70 @Override
71 public long getFileSize() {
72 return file == null ? 0 : file.getExpectedSize();
73 }
74
75 @Override
76 public int getProgress() {
77 if (file == null) {
78 return 0;
79 }
80 return (int) ((((double) transmitted) / file.getExpectedSize()) * 100);
81 }
82
83 @Override
84 public void cancel() {
85 this.canceled = true;
86 }
87
88 private void fail(String errorMessage) {
89 mHttpConnectionManager.finishUploadConnection(this);
90 message.setTransferable(null);
91 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, errorMessage);
92 FileBackend.close(mFileInputStream);
93 }
94
95 public void init(Message message, boolean delay) {
96 this.message = message;
97 this.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]; // todo: change this to 44 for 12-byte IV instead of 16-byte at some point in future
109 mXmppConnectionService.getRNG().nextBytes(this.key);
110 this.file.setKeyAndIv(this.key);
111 }
112 Pair<InputStream,Integer> pair;
113 try {
114 pair = AbstractConnectionManager.createInputStream(file, true);
115 } catch (FileNotFoundException e) {
116 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not find file to upload - "+e.getMessage());
117 fail(e.getMessage());
118 return;
119 }
120 this.file.setExpectedSize(pair.second);
121 message.resetFileParams();
122 this.mFileInputStream = pair.first;
123 Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD);
124 IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
125 mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
126 @Override
127 public void onIqPacketReceived(Account account, IqPacket packet) {
128 if (packet.getType() == IqPacket.TYPE.RESULT) {
129 Element slot = packet.findChild("slot", Namespace.HTTP_UPLOAD);
130 if (slot != null) {
131 try {
132 mGetUrl = new URL(slot.findChildContent("get"));
133 mPutUrl = new URL(slot.findChildContent("put"));
134 if (!canceled) {
135 new Thread(new FileUploader()).start();
136 }
137 return;
138 } catch (MalformedURLException e) {
139 //fall through
140 }
141 }
142 }
143 Log.d(Config.LOGTAG,account.getJid().toString()+": invalid response to slot request "+packet);
144 fail(IqParser.extractErrorMessage(packet));
145 }
146 });
147 message.setTransferable(this);
148 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
149 }
150
151 private class FileUploader implements Runnable {
152
153 @Override
154 public void run() {
155 this.upload();
156 }
157
158 private void upload() {
159 OutputStream os = null;
160 HttpURLConnection connection = null;
161 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
162 try {
163 wakeLock.acquire();
164 final int expectedFileSize = (int) file.getExpectedSize();
165 final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s
166 Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString()+ " w/ read timeout of "+readTimeout+"s");
167 if (mUseTor) {
168 connection = (HttpURLConnection) mPutUrl.openConnection(mHttpConnectionManager.getProxy());
169 } else {
170 connection = (HttpURLConnection) mPutUrl.openConnection();
171 }
172 if (connection instanceof HttpsURLConnection) {
173 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
174 }
175 connection.setRequestMethod("PUT");
176 connection.setFixedLengthStreamingMode(expectedFileSize);
177 connection.setRequestProperty("Content-Type", mime == null ? "application/octet-stream" : mime);
178 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
179 connection.setDoOutput(true);
180 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
181 connection.setReadTimeout(readTimeout * 1000);
182 connection.connect();
183 os = connection.getOutputStream();
184 transmitted = 0;
185 int count;
186 byte[] buffer = new byte[4096];
187 while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
188 transmitted += count;
189 os.write(buffer, 0, count);
190 mHttpConnectionManager.updateConversationUi(false);
191 }
192 os.flush();
193 os.close();
194 mFileInputStream.close();
195 int code = connection.getResponseCode();
196 if (code == 200 || code == 201) {
197 Log.d(Config.LOGTAG, "finished uploading file");
198 if (key != null) {
199 mGetUrl = CryptoHelper.toAesGcmUrl(new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key)));
200 }
201 mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
202 mXmppConnectionService.getFileBackend().updateMediaScanner(file);
203 message.setTransferable(null);
204 message.setCounterpart(message.getConversation().getJid().toBareJid());
205 mXmppConnectionService.resendMessage(message, delayed);
206 } else {
207 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
208 fail("http upload failed because response code was "+code);
209 }
210 } catch (IOException e) {
211 e.printStackTrace();
212 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
213 fail(e.getMessage());
214 } finally {
215 FileBackend.close(mFileInputStream);
216 FileBackend.close(os);
217 if (connection != null) {
218 connection.disconnect();
219 }
220 wakeLock.release();
221 }
222 }
223 }
224}