Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 89bb9932 authored by Paul Jensen's avatar Paul Jensen
Browse files

Fix socket leaks in various android.net.Network methods.

Bug: 72124526
Test: make CtsNetTestCases
Change-Id: I3398b67272360f894e01a8cdfbc47b17d77c2330
parent 3e264bf0
Loading
Loading
Loading
Loading
+33 −7
Original line number Diff line number Diff line
@@ -26,6 +26,8 @@ import android.util.proto.ProtoOutputStream;
import com.android.okhttp.internalandroidapi.Dns;
import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory;

import libcore.io.IoUtils;

import java.io.FileDescriptor;
import java.io.IOException;
import java.net.DatagramSocket;
@@ -137,9 +139,15 @@ public class Network implements Parcelable {
            for (int i = 0; i < hostAddresses.length; i++) {
                try {
                    Socket socket = createSocket();
                    boolean failed = true;
                    try {
                        if (localAddress != null) socket.bind(localAddress);
                        socket.connect(new InetSocketAddress(hostAddresses[i], port));
                        failed = false;
                        return socket;
                    } finally {
                        if (failed) IoUtils.closeQuietly(socket);
                    }
                } catch (IOException e) {
                    if (i == (hostAddresses.length - 1)) throw e;
                }
@@ -156,15 +164,27 @@ public class Network implements Parcelable {
        public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
                int localPort) throws IOException {
            Socket socket = createSocket();
            boolean failed = true;
            try {
                socket.bind(new InetSocketAddress(localAddress, localPort));
                socket.connect(new InetSocketAddress(address, port));
                failed = false;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
            return socket;
        }

        @Override
        public Socket createSocket(InetAddress host, int port) throws IOException {
            Socket socket = createSocket();
            boolean failed = true;
            try {
                socket.connect(new InetSocketAddress(host, port));
                failed = false;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
            return socket;
        }

@@ -176,7 +196,13 @@ public class Network implements Parcelable {
        @Override
        public Socket createSocket() throws IOException {
            Socket socket = new Socket();
            boolean failed = true;
            try {
                bindSocket(socket);
                failed = false;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
            return socket;
        }
    }