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;
14import java.util.HashMap;
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.parser.IqParser;
24import eu.siacs.conversations.persistance.FileBackend;
25import eu.siacs.conversations.services.AbstractConnectionManager;
26import eu.siacs.conversations.services.XmppConnectionService;
27import eu.siacs.conversations.utils.CryptoHelper;
28import eu.siacs.conversations.xml.Namespace;
29import eu.siacs.conversations.xml.Element;
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 HashMap<String,String> mPutHeaders;
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(String errorMessage) {
90 mHttpConnectionManager.finishUploadConnection(this);
91 message.setTransferable(null);
92 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED, errorMessage);
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 if (message.getEncryption() == Message.ENCRYPTION_PGP || message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
101 this.mime = "application/pgp-encrypted";
102 } else {
103 this.mime = this.file.getMimeType();
104 }
105 this.delayed = delay;
106 if (Config.ENCRYPT_ON_HTTP_UPLOADED
107 || message.getEncryption() == Message.ENCRYPTION_AXOLOTL
108 || message.getEncryption() == Message.ENCRYPTION_OTR) {
109 this.key = new byte[48]; // todo: change this to 44 for 12-byte IV instead of 16-byte at some point in future
110 mXmppConnectionService.getRNG().nextBytes(this.key);
111 this.file.setKeyAndIv(this.key);
112 }
113 Pair<InputStream,Integer> pair;
114 try {
115 pair = AbstractConnectionManager.createInputStream(file, true);
116 } catch (FileNotFoundException e) {
117 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not find file to upload - "+e.getMessage());
118 fail(e.getMessage());
119 return;
120 }
121 this.file.setExpectedSize(pair.second);
122 message.resetFileParams();
123 this.mFileInputStream = pair.first;
124 Jid host = account.getXmppConnection().findDiscoItemByFeature(Namespace.HTTP_UPLOAD);
125 IqPacket request = mXmppConnectionService.getIqGenerator().requestHttpUploadSlot(host,file,mime);
126 mXmppConnectionService.sendIqPacket(account, request, (account, packet) -> {
127 if (packet.getType() == IqPacket.TYPE.RESULT) {
128 Element slot = packet.findChild("slot", Namespace.HTTP_UPLOAD);
129 if (slot != null) {
130 try {
131 final Element put = slot.findChild("put");
132 final Element get = slot.findChild("get");
133 final String putUrl = put == null ? null : put.getAttribute("url");
134 final String getUrl = get == null ? null : get.getAttribute("url");
135 if (getUrl != null && putUrl != null) {
136 this.mGetUrl = new URL(getUrl);
137 this.mPutUrl = new URL(putUrl);
138 this.mPutHeaders = new HashMap<>();
139 for(Element child : put.getChildren()) {
140 if ("header".equals(child.getName())) {
141 String name = child.getAttribute("name");
142 String value = child.getContent();
143 if (name != null && value != null && !name.trim().contains("\n") && !value.trim().contains("\n")) {
144 this.mPutHeaders.put(name.trim(),value.trim());
145 }
146 }
147 }
148 }
149 if (!canceled) {
150 new Thread(this::upload).start();
151 }
152 return;
153 } catch (MalformedURLException e) {
154 //fall through
155 }
156 }
157 }
158 Log.d(Config.LOGTAG,account.getJid().toString()+": invalid response to slot request "+packet);
159 fail(IqParser.extractErrorMessage(packet));
160 });
161 message.setTransferable(this);
162 mXmppConnectionService.markMessage(message, Message.STATUS_UNSEND);
163 }
164
165 private void upload() {
166 OutputStream os = null;
167 HttpURLConnection connection = null;
168 PowerManager.WakeLock wakeLock = mHttpConnectionManager.createWakeLock("http_upload_"+message.getUuid());
169 try {
170 final int expectedFileSize = (int) file.getExpectedSize();
171 final int readTimeout = (expectedFileSize / 2048) + Config.SOCKET_TIMEOUT; //assuming a minimum transfer speed of 16kbit/s
172 wakeLock.acquire(readTimeout);
173 Log.d(Config.LOGTAG, "uploading to " + mPutUrl.toString()+ " w/ read timeout of "+readTimeout+"s");
174 if (mUseTor) {
175 connection = (HttpURLConnection) mPutUrl.openConnection(mHttpConnectionManager.getProxy());
176 } else {
177 connection = (HttpURLConnection) mPutUrl.openConnection();
178 }
179 if (connection instanceof HttpsURLConnection) {
180 mHttpConnectionManager.setupTrustManager((HttpsURLConnection) connection, true);
181 }
182 connection.setRequestMethod("PUT");
183 connection.setFixedLengthStreamingMode(expectedFileSize);
184 connection.setRequestProperty("Content-Type", mime == null ? "application/octet-stream" : mime);
185 connection.setRequestProperty("User-Agent",mXmppConnectionService.getIqGenerator().getIdentityName());
186 if(mPutHeaders != null) {
187 for(HashMap.Entry<String,String> entry : mPutHeaders.entrySet()) {
188 connection.setRequestProperty(entry.getKey(),entry.getValue());
189 }
190 }
191 connection.setDoOutput(true);
192 connection.setConnectTimeout(Config.SOCKET_TIMEOUT * 1000);
193 connection.setReadTimeout(readTimeout * 1000);
194 connection.connect();
195 os = connection.getOutputStream();
196 transmitted = 0;
197 int count;
198 byte[] buffer = new byte[4096];
199 while (((count = mFileInputStream.read(buffer)) != -1) && !canceled) {
200 transmitted += count;
201 os.write(buffer, 0, count);
202 mHttpConnectionManager.updateConversationUi(false);
203 }
204 os.flush();
205 os.close();
206 mFileInputStream.close();
207 int code = connection.getResponseCode();
208 if (code == 200 || code == 201) {
209 Log.d(Config.LOGTAG, "finished uploading file");
210 if (key != null) {
211 mGetUrl = CryptoHelper.toAesGcmUrl(new URL(mGetUrl.toString() + "#" + CryptoHelper.bytesToHex(key)));
212 }
213 mXmppConnectionService.getFileBackend().updateFileParams(message, mGetUrl);
214 mXmppConnectionService.getFileBackend().updateMediaScanner(file);
215 message.setTransferable(null);
216 message.setCounterpart(message.getConversation().getJid().toBareJid());
217 mXmppConnectionService.resendMessage(message, delayed);
218 } else {
219 Log.d(Config.LOGTAG,"http upload failed because response code was "+code);
220 fail("http upload failed because response code was "+code);
221 }
222 } catch (IOException e) {
223 e.printStackTrace();
224 Log.d(Config.LOGTAG,"http upload failed "+e.getMessage());
225 fail(e.getMessage());
226 } finally {
227 FileBackend.close(mFileInputStream);
228 FileBackend.close(os);
229 if (connection != null) {
230 connection.disconnect();
231 }
232 wakeLock.release();
233 }
234 }
235}