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