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];
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 this.mFileInputStream = pair.first;
122 Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD);
123 IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
124 mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
125 @Override
126 public void onIqPacketReceived(Account account, IqPacket packet) {
127 if (packet.getType() == IqPacket.TYPE.RESULT) {
128 Element slot = packet.findChild("slot", Namespace.HTTP_UPLOAD);
129 if (slot != null) {
130 try {
131 mGetUrl = new URL(slot.findChildContent("get"));
132 mPutUrl = new URL(slot.findChildContent("put"));
133 if (!canceled) {
134 new Thread(new FileUploader()).start();
135 }
136 return;
137 } catch (MalformedURLException e) {
138 //fall through
139 }
140 }
141 }
142 Log.d(Config.LOGTAG,account.getJid().toString()+": invalid response to slot request "+packet);
143 fail(IqParser.extractErrorMessage(packet));
144 }
145 });
146 message.setTransferable(this);
147 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
148 }
149
150 private class FileUploader implements Runnable {
151
152 @Override
153 public void run() {
154 this.upload();
155 }
156
157 private void upload() {
158 OutputStream os = null;
159 HttpURLConnection connection = null;
160 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
161 try {
162 wakeLock.acquire();
163 final int expectedFileSize = (int) file.getExpectedSize();
164 final int readTimeout = Math.max(Config.SOCKET_TIMEOUT,expectedFileSize / 2048); //assuming a minimum transfer speed of 16kbit/s
165 Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString()+ " w/ read timeout of "+readTimeout+"s");
166 if (mUseTor) {
167 connection = (HttpURLConnection) mPutUrl.openConnection(mHttpConnectionManager.getProxy());
168 } else {
169 connection = (HttpURLConnection) mPutUrl.openConnection();
170 }
171 if (connection instanceof HttpsURLConnection) {
172 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
173 }
174 connection.setRequestMethod("PUT");
175 connection.setFixedLengthStreamingMode(expectedFileSize);
176 connection.setRequestProperty("Content-Type", mime == null ? "application/octet-stream" : mime);
177 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
178 connection.setDoOutput(true);
179 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
180 connection.setReadTimeout(readTimeout * 1000);
181 connection.connect();
182 os = connection.getOutputStream();
183 transmitted = 0;
184 int count;
185 byte[] buffer = new byte[4096];
186 while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
187 transmitted += count;
188 os.write(buffer, 0, count);
189 mHttpConnectionManager.updateConversationUi(false);
190 }
191 os.flush();
192 os.close();
193 mFileInputStream.close();
194 int code = connection.getResponseCode();
195 if (code == 200 || code == 201) {
196 Log.d(Config.LOGTAG, "finished uploading file");
197 if (key != null) {
198 mGetUrl = CryptoHelper.toAesGcmUrl(new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key)));
199 }
200 mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
201 mXmppConnectionService.getFileBackend().updateMediaScanner(file);
202 message.setTransferable(null);
203 message.setCounterpart(message.getConversation().getJid().toBareJid());
204 mXmppConnectionService.resendMessage(message, delayed);
205 } else {
206 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
207 fail("http upload failed because response code was "+code);
208 }
209 } catch (IOException e) {
210 e.printStackTrace();
211 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
212 fail(e.getMessage());
213 } finally {
214 FileBackend.close(mFileInputStream);
215 FileBackend.close(os);
216 if (connection != null) {
217 connection.disconnect();
218 }
219 wakeLock.release();
220 }
221 }
222 }
223}