HttpConnectionManager.java

  1package eu.siacs.conversations.http;
  2
  3import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
  4
  5import android.os.Build;
  6import android.util.Log;
  7
  8import org.apache.http.conn.ssl.StrictHostnameVerifier;
  9
 10import java.io.IOException;
 11import java.io.InputStream;
 12import java.net.InetAddress;
 13import java.net.InetSocketAddress;
 14import java.net.Proxy;
 15import java.net.UnknownHostException;
 16import java.security.KeyManagementException;
 17import java.security.NoSuchAlgorithmException;
 18import java.util.ArrayList;
 19import java.util.List;
 20import java.util.concurrent.Executor;
 21import java.util.concurrent.Executors;
 22import java.util.concurrent.TimeUnit;
 23
 24import javax.net.ssl.SSLSocketFactory;
 25import javax.net.ssl.X509TrustManager;
 26
 27import eu.siacs.conversations.BuildConfig;
 28import eu.siacs.conversations.Config;
 29import eu.siacs.conversations.entities.Account;
 30import eu.siacs.conversations.entities.Message;
 31import eu.siacs.conversations.services.AbstractConnectionManager;
 32import eu.siacs.conversations.services.XmppConnectionService;
 33import eu.siacs.conversations.utils.TLSSocketFactory;
 34import okhttp3.HttpUrl;
 35import okhttp3.OkHttpClient;
 36import okhttp3.Request;
 37import okhttp3.ResponseBody;
 38
 39public class HttpConnectionManager extends AbstractConnectionManager {
 40
 41    private final List<HttpDownloadConnection> downloadConnections = new ArrayList<>();
 42    private final List<HttpUploadConnection> uploadConnections = new ArrayList<>();
 43
 44    public static final Executor EXECUTOR = Executors.newFixedThreadPool(4);
 45
 46    public static final OkHttpClient OK_HTTP_CLIENT;
 47
 48    static {
 49        OK_HTTP_CLIENT = new OkHttpClient.Builder()
 50                .addInterceptor(chain -> {
 51                    final Request original = chain.request();
 52                    final Request modified = original.newBuilder()
 53                            .header("User-Agent", getUserAgent())
 54                            .build();
 55                    return chain.proceed(modified);
 56                })
 57                .build();
 58    }
 59
 60
 61    public static String getUserAgent() {
 62        return String.format("%s/%s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME);
 63    }
 64
 65    public HttpConnectionManager(XmppConnectionService service) {
 66        super(service);
 67    }
 68
 69    public static Proxy getProxy() {
 70        final InetAddress localhost;
 71        try {
 72            localhost = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
 73        } catch (final UnknownHostException e) {
 74            throw new IllegalStateException(e);
 75        }
 76        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 77            return new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(localhost, 9050));
 78        } else {
 79            return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(localhost, 8118));
 80        }
 81    }
 82
 83    public void createNewDownloadConnection(Message message) {
 84        this.createNewDownloadConnection(message, false);
 85    }
 86
 87    public void createNewDownloadConnection(final Message message, boolean interactive) {
 88        synchronized (this.downloadConnections) {
 89            for (HttpDownloadConnection connection : this.downloadConnections) {
 90                if (connection.getMessage() == message) {
 91                    Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": download already in progress");
 92                    return;
 93                }
 94            }
 95            final HttpDownloadConnection connection = new HttpDownloadConnection(message, this);
 96            connection.init(interactive);
 97            this.downloadConnections.add(connection);
 98        }
 99    }
100
101    public void createNewUploadConnection(final Message message, boolean delay) {
102        synchronized (this.uploadConnections) {
103            for (HttpUploadConnection connection : this.uploadConnections) {
104                if (connection.getMessage() == message) {
105                    Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": upload already in progress");
106                    return;
107                }
108            }
109            HttpUploadConnection connection = new HttpUploadConnection(message, Method.determine(message.getConversation().getAccount()), this);
110            connection.init(delay);
111            this.uploadConnections.add(connection);
112        }
113    }
114
115    void finishConnection(HttpDownloadConnection connection) {
116        synchronized (this.downloadConnections) {
117            this.downloadConnections.remove(connection);
118        }
119    }
120
121    void finishUploadConnection(HttpUploadConnection httpUploadConnection) {
122        synchronized (this.uploadConnections) {
123            this.uploadConnections.remove(httpUploadConnection);
124        }
125    }
126
127    OkHttpClient buildHttpClient(final HttpUrl url, final Account account, boolean interactive) {
128        return buildHttpClient(url, account, 30, interactive);
129    }
130
131    OkHttpClient buildHttpClient(final HttpUrl url, final Account account, int readTimeout, boolean interactive) {
132        final String slotHostname = url.host();
133        final boolean onionSlot = slotHostname.endsWith(".onion");
134        final OkHttpClient.Builder builder = newBuilder(mXmppConnectionService.useTorToConnect() || account.isOnion() || onionSlot);
135        builder.readTimeout(readTimeout, TimeUnit.SECONDS);
136        setupTrustManager(builder, interactive);
137        return builder.build();
138    }
139
140    private void setupTrustManager(final OkHttpClient.Builder builder, final boolean interactive) {
141        final X509TrustManager trustManager;
142        if (interactive) {
143            trustManager = mXmppConnectionService.getMemorizingTrustManager().getInteractive();
144        } else {
145            trustManager = mXmppConnectionService.getMemorizingTrustManager().getNonInteractive();
146        }
147        try {
148            final SSLSocketFactory sf = new TLSSocketFactory(new X509TrustManager[]{trustManager}, SECURE_RANDOM);
149            builder.sslSocketFactory(sf, trustManager);
150            builder.hostnameVerifier(new StrictHostnameVerifier());
151        } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
152        }
153    }
154
155    public static OkHttpClient.Builder newBuilder(final boolean tor) {
156        final OkHttpClient.Builder builder = OK_HTTP_CLIENT.newBuilder();
157        builder.writeTimeout(30, TimeUnit.SECONDS);
158        builder.readTimeout(30, TimeUnit.SECONDS);
159        if (tor) {
160            builder.proxy(HttpConnectionManager.getProxy()).build();
161        }
162        return builder;
163    }
164
165    public static InputStream open(final String url, final boolean tor) throws IOException {
166        return open(HttpUrl.get(url), tor);
167    }
168
169    public static InputStream open(final HttpUrl httpUrl, final boolean tor) throws IOException {
170        final OkHttpClient client = newBuilder(tor).build();
171        final Request request = new Request.Builder().get().url(httpUrl).build();
172        final ResponseBody body = client.newCall(request).execute().body();
173        if (body == null) {
174            throw new IOException("No response body found");
175        }
176        return body.byteStream();
177    }
178}