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 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not find file to upload - "+e.getMessage());
114 fail();
115 return;
116 }
117 this.file.setExpectedSize(pair.second);
118 this.mFileInputStream = pair.first;
119 Jid host = account.getXmppConnection().findDiscoItemByFeature(Xmlns.HTTP_UPLOAD);
120 IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
121 mXmppConnectionService.sendIqPacket(account, request, new OnIqPacketReceived() {
122 @Override
123 public void onIqPacketReceived(Account account, IqPacket packet) {
124 if (packet.getType() == IqPacket.TYPE.RESULT) {
125 Element slot = packet.findChild("slot",Xmlns.HTTP_UPLOAD);
126 if (slot != null) {
127 try {
128 mGetUrl = new URL(slot.findChildContent("get"));
129 mPutUrl = new URL(slot.findChildContent("put"));
130 if (!canceled) {
131 new Thread(new FileUploader()).start();
132 }
133 return;
134 } catch (MalformedURLException e) {
135 //fall through
136 }
137 }
138 }
139 Log.d(Config.LOGTAG,account.getJid().toString()+": invalid response to slot request "+packet);
140 fail();
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 Log.d(Config.LOGTAG,"pgp encryption failed");
207 fail();
208 }
209
210 @Override
211 public void userInputRequried(PendingIntent pi, Message object) {
212 fail();
213 }
214 });
215 } else {
216 mXmppConnectionService.resendMessage(message, delayed);
217 }
218 } else {
219 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
220 fail();
221 }
222 } catch (IOException e) {
223 e.printStackTrace();
224 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
225 fail();
226 } finally {
227 FileBackend.close(mFileInputStream);
228 FileBackend.close(os);
229 if (connection != null) {
230 connection.disconnect();
231 }
232 wakeLock.release();
233 }
234 }
235 }
236}