1package eu.siacs.conversations.http;
2
3import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
4
5import android.content.Context;
6import android.os.Build;
7import android.util.Log;
8
9import androidx.core.util.Consumer;
10
11import eu.siacs.conversations.BuildConfig;
12import eu.siacs.conversations.Config;
13import eu.siacs.conversations.crypto.TrustManagers;
14import eu.siacs.conversations.entities.Account;
15import eu.siacs.conversations.entities.DownloadableFile;
16import eu.siacs.conversations.entities.Message;
17import eu.siacs.conversations.services.AbstractConnectionManager;
18import eu.siacs.conversations.services.XmppConnectionService;
19import eu.siacs.conversations.utils.TLSSocketFactory;
20
21import okhttp3.HttpUrl;
22import okhttp3.OkHttpClient;
23import okhttp3.Request;
24import okhttp3.ResponseBody;
25
26import org.apache.http.conn.ssl.StrictHostnameVerifier;
27
28import java.io.IOException;
29import java.io.InputStream;
30import java.net.InetAddress;
31import java.net.InetSocketAddress;
32import java.net.Proxy;
33import java.net.UnknownHostException;
34import java.security.KeyManagementException;
35import java.security.KeyStoreException;
36import java.security.NoSuchAlgorithmException;
37import java.security.cert.CertificateException;
38import java.util.ArrayList;
39import java.util.List;
40import java.util.concurrent.Executor;
41import java.util.concurrent.Executors;
42import java.util.concurrent.TimeUnit;
43
44import javax.net.ssl.SSLSocketFactory;
45import javax.net.ssl.X509TrustManager;
46
47public class HttpConnectionManager extends AbstractConnectionManager {
48
49 private final List<HttpDownloadConnection> downloadConnections = new ArrayList<>();
50 private final List<HttpUploadConnection> uploadConnections = new ArrayList<>();
51
52 public static final Executor EXECUTOR = Executors.newFixedThreadPool(4);
53
54 private static final OkHttpClient OK_HTTP_CLIENT;
55
56 static {
57 OK_HTTP_CLIENT = new OkHttpClient.Builder()
58 .addInterceptor(chain -> {
59 final Request original = chain.request();
60 final Request modified = original.newBuilder()
61 .header("User-Agent", getUserAgent())
62 .build();
63 return chain.proceed(modified);
64 })
65 .build();
66 }
67
68
69 public static String getUserAgent() {
70 return String.format("%s/%s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME);
71 }
72
73 public HttpConnectionManager(XmppConnectionService service) {
74 super(service);
75 }
76
77 public static Proxy getProxy() {
78 final InetAddress localhost;
79 try {
80 localhost = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
81 } catch (final UnknownHostException e) {
82 throw new IllegalStateException(e);
83 }
84 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
85 return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(localhost, 9050));
86 } else {
87 return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(localhost, 8118));
88 }
89 }
90
91 public void createNewDownloadConnection(Message message) {
92 this.createNewDownloadConnection(message, false);
93 }
94
95 public void createNewDownloadConnection(final Message message, boolean interactive) {
96 createNewDownloadConnection(message, interactive, null);
97 }
98
99 public void createNewDownloadConnection(final Message message, boolean interactive, Consumer<DownloadableFile> cb) {
100 synchronized (this.downloadConnections) {
101 for (HttpDownloadConnection connection : this.downloadConnections) {
102 if (connection.getMessage() == message) {
103 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": download already in progress");
104 return;
105 }
106 }
107 final HttpDownloadConnection connection = new HttpDownloadConnection(message, this, cb);
108 connection.init(interactive);
109 this.downloadConnections.add(connection);
110 }
111 }
112
113 public void createNewUploadConnection(final Message message, boolean delay) {
114 synchronized (this.uploadConnections) {
115 for (HttpUploadConnection connection : this.uploadConnections) {
116 if (connection.getMessage() == message) {
117 Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": upload already in progress");
118 return;
119 }
120 }
121 HttpUploadConnection connection = new HttpUploadConnection(message, Method.determine(message.getConversation().getAccount()), this);
122 connection.init(delay);
123 this.uploadConnections.add(connection);
124 }
125 }
126
127 void finishConnection(HttpDownloadConnection connection) {
128 synchronized (this.downloadConnections) {
129 this.downloadConnections.remove(connection);
130 }
131 }
132
133 void finishUploadConnection(HttpUploadConnection httpUploadConnection) {
134 synchronized (this.uploadConnections) {
135 this.uploadConnections.remove(httpUploadConnection);
136 }
137 }
138
139 public OkHttpClient buildHttpClient(final HttpUrl url, final Account account, boolean interactive) {
140 return buildHttpClient(url, account, 30, interactive);
141 }
142
143 public OkHttpClient buildHttpClient(final HttpUrl url, final Account account, int readTimeout, boolean interactive) {
144 final String slotHostname = url.host();
145 final boolean onionSlot = slotHostname.endsWith(".onion");
146 final OkHttpClient.Builder builder = newBuilder(mXmppConnectionService.useTorToConnect() || account.isOnion() || onionSlot);
147 builder.readTimeout(readTimeout, TimeUnit.SECONDS);
148 setupTrustManager(builder, interactive);
149 return builder.build();
150 }
151
152 private void setupTrustManager(final OkHttpClient.Builder builder, final boolean interactive) {
153 final X509TrustManager trustManager;
154 if (interactive) {
155 trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive();
156 } else {
157 trustManager = mXmppConnectionService.getMemorizingTrustManager().getNonInteractive();
158 }
159 try {
160 final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[]{trustManager}, SECURE_RANDOM);
161 builder.sslSocketFactory(sf, trustManager);
162 builder.hostnameVerifier(new StrictHostnameVerifier());
163 } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
164 }
165 }
166
167 public static OkHttpClient.Builder newBuilder(final boolean tor) {
168 final OkHttpClient.Builder builder = OK_HTTP_CLIENT.newBuilder();
169 builder.writeTimeout(30, TimeUnit.SECONDS);
170 builder.readTimeout(30, TimeUnit.SECONDS);
171 if (tor) {
172 builder.proxy(HttpConnectionManager.getProxy()).build();
173 }
174 return builder;
175 }
176
177 public static InputStream open(final String url, final boolean tor) throws IOException {
178 return open(HttpUrl.get(url), tor);
179 }
180
181 public static InputStream open(final HttpUrl httpUrl, final boolean tor) throws IOException {
182 final OkHttpClient client = newBuilder(tor).build();
183 final Request request = new Request.Builder().get().url(httpUrl).build();
184 final ResponseBody body = client.newCall(request).execute().body();
185 if (body == null) {
186 throw new IOException("No response body found");
187 }
188 return body.byteStream();
189 }
190
191 public static String extractFilenameFromResponse(okhttp3.Response response) {
192 String filename = null;
193
194 // Try to extract filename from the Content-Disposition header
195 String contentDisposition = response.header("Content-Disposition");
196 if (contentDisposition != null && contentDisposition.contains("filename=")) {
197 String[] parts = contentDisposition.split(";");
198 for (String part : parts) {
199 if (part.trim().startsWith("filename=")) {
200 filename = part.substring("filename=".length()).trim().replace("\"", "");
201 break;
202 }
203 }
204 }
205
206 // If filename is not found in the Content-Disposition header, try to get it from the URL
207 if (filename == null || filename.isEmpty()) {
208 HttpUrl httpUrl = response.request().url();
209 List<String> pathSegments = httpUrl.pathSegments();
210 if (!pathSegments.isEmpty()) {
211 filename = pathSegments.get(pathSegments.size() - 1);
212 }
213 }
214
215 return filename;
216 }
217
218 public static OkHttpClient okHttpClient(final Context context) {
219 final OkHttpClient.Builder builder = HttpConnectionManager.OK_HTTP_CLIENT.newBuilder();
220 try {
221 final X509TrustManager trustManager;
222 if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
223 trustManager = TrustManagers.defaultWithBundledLetsEncrypt(context);
224 } else {
225 trustManager = TrustManagers.createDefaultTrustManager();
226 }
227 final SSLSocketFactory socketFactory =
228 new TLSSocketFactory(new X509TrustManager[] {trustManager}, SECURE_RANDOM);
229 builder.sslSocketFactory(socketFactory, trustManager);
230 } catch (final IOException
231 | KeyManagementException
232 | NoSuchAlgorithmException
233 | KeyStoreException
234 | CertificateException e) {
235 Log.d(Config.LOGTAG, "not reconfiguring service to work with bundled LetsEncrypt");
236 throw new RuntimeException(e);
237 }
238 return builder.build();
239 }
240}