Welcome to mirror list, hosted at ThFree Co, Russian Federation.

PlatformSocket.java « location « maps « mapswithme « com « src « android - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 002e783efc6ef09ab4fc1d4ba2e2462837424911 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package com.mapswithme.maps.location;

import android.annotation.SuppressLint;
import android.net.SSLCertificateSocketFactory;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.mapswithme.maps.BuildConfig;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

/**
 * Implements interface that will be used by the core for
 * sending/receiving the raw data trough platform socket interface.
 * <p>
 * The instance of this class is supposed to be created in JNI layer
 * and supposed to be used in the thread safe environment, i.e. thread safety
 * should be provided externally (by the client of this class).
 * <p>
 * <b>All public methods are blocking and shouldn't be called from the main thread.</b>
 */
class PlatformSocket
{
  private final static int DEFAULT_TIMEOUT = 30 * 1000;
  private final static String TAG = PlatformSocket.class.getSimpleName();
  @NonNull
  private final static Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.GPS_TRACKING);
  private static volatile long sSslConnectionCounter;
  @Nullable
  private Socket mSocket;
  @Nullable
  private String mHost;
  private int mPort;
  private int mTimeout = DEFAULT_TIMEOUT;

  PlatformSocket()
  {
    sSslConnectionCounter = 0;
    LOGGER.d(TAG, "***********************************************************************************");
    LOGGER.d(TAG, "Platform socket is created by core, ssl connection counter is discarded.");
  }

  public boolean open(@NonNull String host, int port)
  {
    if (mSocket != null)
    {
      LOGGER.e(TAG, "Socket is already opened. Seems that it wasn't closed.");
      return false;
    }

    if (!isPortAllowed(port))
    {
      LOGGER.e(TAG, "A wrong port number = " + port + ", it must be within (0-65535) range");
      return false;
    }

    mHost = host;
    mPort = port;

    Socket socket = createSocket(host, port, true);
    if (socket != null && socket.isConnected())
    {
      setReadSocketTimeout(socket, mTimeout);
      mSocket = socket;
    }

    return mSocket != null;
  }

  private static boolean isPortAllowed(int port)
  {
    return port >= 0 && port <= 65535;
  }

  @Nullable
  private static Socket createSocket(@NonNull String host, int port, boolean ssl)
  {
    return ssl ? createSslSocket(host, port) : createRegularSocket(host, port);
  }

  @Nullable
  private static Socket createSslSocket(@NonNull String host, int port)
  {
    Socket socket = null;
    try
    {
      SocketFactory sf = getSocketFactory();
      socket = sf.createSocket(host, port);
      sSslConnectionCounter++;
      LOGGER.d(TAG, "###############################################################################");
      LOGGER.d(TAG, sSslConnectionCounter + " ssl connection is established.");
    }
    catch (IOException e)
    {
      LOGGER.e(TAG, "Failed to create the ssl socket, mHost = " + host + " mPort = " + port);
    }
    return socket;
  }

  @Nullable
  private static Socket createRegularSocket(@NonNull String host, int port)
  {
    Socket socket = null;
    try
    {
      socket = new Socket(host, port);
      LOGGER.d(TAG, "Regular socket is created and tcp handshake is passed successfully");
    }
    catch (IOException e)
    {
      LOGGER.e(TAG, "Failed to create the socket, mHost = " + host + " mPort = " + port);
    }
    return socket;
  }

  @SuppressLint("SSLCertificateSocketFactoryGetInsecure")
  @NonNull
  private static SocketFactory getSocketFactory()
  {
    // Trusting to any ssl certificate factory that will be used in
    // debug mode, for testing purposes only.
    if (BuildConfig.DEBUG)
      //TODO: implement the custom KeyStore to make the self-signed certificates work
      return SSLCertificateSocketFactory.getInsecure(0, null);

    return SSLSocketFactory.getDefault();
  }

  public void close()
  {
    if (mSocket == null)
    {
      LOGGER.d(TAG, "Socket is already closed or it wasn't opened yet\n");
      return;
    }

    try
    {
      mSocket.close();
      LOGGER.d(TAG, "Socket has been closed: " + this + "\n");
    } catch (IOException e)
    {
      LOGGER.e(TAG, "Failed to close socket: " + this + "\n");
    } finally
    {
      mSocket = null;
    }
  }

  public boolean read(@NonNull byte[] data, int count)
  {
    if (!checkSocketAndArguments(data, count))
      return false;

    LOGGER.d(TAG, "Reading method is started, data.length = " + data.length + ", count = " + count);
    long startTime = SystemClock.elapsedRealtime();
    int readBytes = 0;
    try
    {
      if (mSocket == null)
        throw new AssertionError("mSocket cannot be null");

      InputStream in = mSocket.getInputStream();
      while (readBytes != count && (SystemClock.elapsedRealtime() - startTime) < mTimeout)
      {
        try
        {
          LOGGER.d(TAG, "Attempting to read " + count + " bytes from offset = " + readBytes);
          int read = in.read(data, readBytes, count - readBytes);

          if (read == -1)
          {
            LOGGER.d(TAG, "All data is read from the stream, read bytes count = " + readBytes + "\n");
            break;
          }

          if (read == 0)
          {
            LOGGER.e(TAG, "0 bytes are obtained. It's considered as error\n");
            break;
          }

          LOGGER.d(TAG, "Read bytes count = " + read + "\n");
          readBytes += read;
        } catch (SocketTimeoutException e)
        {
          long readingTime = SystemClock.elapsedRealtime() - startTime;
          LOGGER.e(TAG, "Socked timeout has occurred after " + readingTime + " (ms)\n ");
          if (readingTime > mTimeout)
          {
            LOGGER.e(TAG, "Socket wrapper timeout has occurred, requested count = " +
                     (count - readBytes) + ", readBytes = " + readBytes + "\n");
            break;
          }
        }
      }
    } catch (IOException e)
    {
      LOGGER.e(TAG, "Failed to read data from socket: " + this + "\n");
    }

    return count == readBytes;
  }

  public boolean write(@NonNull byte[] data, int count)
  {
    if (!checkSocketAndArguments(data, count))
      return false;

    LOGGER.d(TAG, "Writing method is started, data.length = " + data.length + ", count = " + count);
    long startTime = SystemClock.elapsedRealtime();
    try
    {
      if (mSocket == null)
        throw new AssertionError("mSocket cannot be null");

      OutputStream out = mSocket.getOutputStream();
      out.write(data, 0, count);
      LOGGER.d(TAG, count + " bytes are written\n");
      return true;
    } catch (SocketTimeoutException e)
    {
      long writingTime = SystemClock.elapsedRealtime() - startTime;
      LOGGER.e(TAG, "Socked timeout has occurred after " + writingTime + " (ms)\n");
    } catch (IOException e)
    {
      LOGGER.e(TAG, "Failed to write data to socket: " + this + "\n");
    }

    return false;
  }

  private boolean checkSocketAndArguments(@NonNull byte[] data, int count)
  {
    if (mSocket == null)
    {
      LOGGER.e(TAG, "Socket must be opened before reading/writing\n");
      return false;
    }

    if (count < 0 || count > data.length)
    {
      LOGGER.e(TAG, "Illegal arguments, data.length = " + data.length + ", count = " + count + "\n");
      return false;
    }

    return true;
  }

  public void setTimeout(int millis)
  {
    mTimeout = millis;
    LOGGER.d(TAG, "Setting the socket wrapper timeout = " + millis + " ms\n");
  }

  private void setReadSocketTimeout(@NonNull Socket socket, int millis)
  {
    try
    {
      socket.setSoTimeout(millis);
    } catch (SocketException e)
    {
      LOGGER.e(TAG, "Failed to set system socket timeout: " + millis + "ms, " + this + "\n");
    }
  }

  @Override
  public String toString()
  {
    return "PlatformSocket{" +
           "mSocket=" + mSocket +
           ", mHost='" + mHost + '\'' +
           ", mPort=" + mPort +
           '}';
  }
}