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