public JSONObject textToSpeech(Object input) {
    JSONObject args = (JSONObject) JSObjectConverter.scriptableToJSON((Scriptable) input);
    JSONObject theReturn = null;
    URL url = null;
    try {
      theReturn = new JSONObject();
      String host = (String) args.get(ATTConstant.ARG_URL);
      url = new URL(host);

      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

      conn.setDoOutput(true);
      conn.setDoInput(true);

      conn.setRequestMethod("POST");
      conn.setRequestProperty("Authorization", (String) args.get(ATTConstant.ARG_TOKEN));

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_TYPE)) {
        conn.setRequestProperty(
            "Content-Type", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_TYPE));
      } else {
        conn.setRequestProperty("Content-Type", "text/plain");
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_ACCEPT)) {
        conn.setRequestProperty(
            ATTConstant.ARG_HEADER_ACCEPT, (String) args.get(ATTConstant.ARG_HEADER_ACCEPT));
      } else {
        conn.setRequestProperty(ATTConstant.ARG_HEADER_ACCEPT, ATTConstant.VAL_CONTENT_TYPE_AMRWB);
      }

      if (args.containsKey(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE)) {
        conn.setRequestProperty(
            "Content-Language", (String) args.get(ATTConstant.ARG_HEADER_CONTENT_LANGUAGE));
      } else {
        conn.setRequestProperty("Content-Language", ATTConstant.VAL_EN_US);
      }

      String body = (String) args.get(ATTConstant.ARG_BODY);
      conn.setRequestProperty("Content-Length", Integer.toString(body.length()));

      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty("X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG));
      }

      String clientSdk = "ClientSdk=att.worklight." + ATTConstant.ARG_HEADER_XARG_VERSION;
      if (args.containsKey(ATTConstant.ARG_HEADER_XARG)) {
        conn.setRequestProperty(
            "X-Arg", (String) args.get(ATTConstant.ARG_HEADER_XARG) + "," + clientSdk);
      } else {
        conn.setRequestProperty("X-Arg", clientSdk);
      }

      System.out.println("********* TextToSpeech JAVA ADAPTER LOGS ***********");

      OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream());
      outStream.write(body);
      outStream.flush();
      outStream.close();

      /*@SuppressWarnings("unchecked")
      Map<String,List<String>> header = conn.getHeaderFields();
      for (String key: header.keySet ())
         System.out.println (key+": "+conn.getHeaderField (key));
         */

      int responseCode = conn.getResponseCode();
      String responseCodeString = Integer.toString(responseCode);
      JSONObject response = new JSONObject();
      response.put("code", responseCodeString);

      if (responseCode < 400) { // Handle binary response
        // Get all the headers to pass through
        // Read the response and convert to base64
        BufferedInputStream inputStream = new BufferedInputStream(conn.getInputStream());

        int iContentLength = conn.getHeaderFieldInt("Content-Length", 0);
        int totalRead = 0;
        int currentRead = 0;
        byte[] binaryBody = new byte[iContentLength];
        do {
          currentRead = inputStream.read(binaryBody, totalRead, iContentLength - totalRead);
          totalRead += currentRead;
        } while (totalRead < iContentLength);

        String encodedBody = Base64.encode(binaryBody);
        Base64.encode(binaryBody, iContentLength);
        response.put("content", encodedBody.toString());
        response.put("contentType", conn.getHeaderField("Content-Type") + ";base64");
        response.put("contentLength", conn.getHeaderField("Content-Length"));
      } else { // handle html response
        StringBuffer errorString = new StringBuffer();
        BufferedReader is = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        String str;
        while (null != ((str = is.readLine()))) {
          errorString.append(str);
        }
        is.close();
        response.put("error", errorString.toString());
      }
      theReturn.put("message", response);
    } catch (Exception e) {
      e.printStackTrace();
      String message = null;
      String code = null;
      if (e.equals(ATTConstant.ERR_INV_STATUS_MSG)) {
        code = ATTConstant.ERR_INV_STATUS_CODE;
        message = ATTConstant.ERR_INV_STATUS_MSG;
      } else {
        code = ATTConstant.ERR_PROCESS_REQ_CODE;
        message = e.getLocalizedMessage(); // ATTConstant.ERR_PROCESS_REQ_MSG;
      }
      theReturn.put(code, message);
      return theReturn;
    } finally {
      args.clear();
      args = null;
    }
    return theReturn;
  }
예제 #2
0
 // Get the size of a file from URL response header.
 public static Long getRemoteSize(String url) {
   Long remoteSize = (long) 0;
   HttpURLConnection httpConn = null;
   HttpsURLConnection httpsConn = null;
   try {
     URI uri = new URI(url);
     if (uri.getScheme().equalsIgnoreCase("http")) {
       httpConn = (HttpURLConnection) uri.toURL().openConnection();
       if (httpConn != null) {
         String contentLength = httpConn.getHeaderField("content-length");
         if (contentLength != null) {
           remoteSize = Long.parseLong(contentLength);
         }
         httpConn.disconnect();
       }
     } else if (uri.getScheme().equalsIgnoreCase("https")) {
       httpsConn = (HttpsURLConnection) uri.toURL().openConnection();
       if (httpsConn != null) {
         String contentLength = httpsConn.getHeaderField("content-length");
         if (contentLength != null) {
           remoteSize = Long.parseLong(contentLength);
         }
         httpsConn.disconnect();
       }
     }
   } catch (URISyntaxException e) {
     throw new IllegalArgumentException("Invalid URL " + url);
   } catch (IOException e) {
     throw new IllegalArgumentException("Unable to establish connection with URL " + url);
   }
   return remoteSize;
 }
예제 #3
0
  public static String sendRequestOverHTTPS(
      boolean isBusReq, URL url, String request, Map resContentHeaders, int timeout)
      throws Exception {

    // Set up buffers and streams
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    String fullResponse = null;

    try {
      HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      sendRequestString(isBusReq, out, request);

      // recv response
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      String contentType = urlc.getHeaderField("Content-Type");
      fullResponse = receiveResponseString(in, contentType);

      out.close();
      in.close();

      populateHTTPSHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return fullResponse;
  }
예제 #4
0
  /**
   * @deprecated As of proxy release 1.0.10, replaced by {@link
   *     #populateHTTPHeaderContentMap(HttpURLConnection urlc, Map resContentHeaders)}
   */
  private static void populateHTTPSHeaderContentMap(HttpsURLConnection urlc, Map resContentHeaders)
      throws Exception {
    if (resContentHeaders.isEmpty()) {
      return;
    }

    Iterator iter = resContentHeaders.keySet().iterator();
    String key = null;
    String value = null;
    while (iter.hasNext()) {
      key = (String) iter.next();
      value = (String) urlc.getHeaderField(key);
      resContentHeaders.put(key, value);
    }
  }
  // gets VM home and data page based on boolean parameter
  public static String fetchURL(String username, String password, Boolean getData) {
    String line = "";

    String url = "https://www2.virginmobileusa.com/login/login.do";
    String dataUrl = "https://www2.virginmobileusa.com/myaccount/dataPlanHistory.do";
    try {
      TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              public void checkClientTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}

              public void checkServerTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}
            }
          };
      try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      } catch (Exception e) {
        e.getMessage();
      }

      HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
      ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

      connection.setDoOutput(true);

      String content = "loginRoutingInfo=&min=" + username + "&vkey=" + password + "&submit=submit";

      connection.setFixedLengthStreamingMode(content.length());
      connection.setRequestProperty("Host", "www2.virginmobileusa.com");
      connection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");

      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
      out.write(content);
      out.close();

      InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());

      BufferedReader buff = new BufferedReader(in);

      StringBuilder sb = new StringBuilder();

      while ((line = buff.readLine()) != null) {
        sb.append(line);
      }

      // telephone
      int tel_infoStartIndex = sb.indexOf("id=\"headerimage\"");
      int tel_infoEndIndex = sb.indexOf("<ul class=\"tabnav\">");
      // balance info
      int balance_infoStartIndex = sb.indexOf("id=\"balance_info2b\">");
      int balance_infoEndIndex = sb.indexOf("id=\"payment_strip\"");
      // account activity
      int account_activityStartIndex = sb.indexOf("id=\"account_activity\"");
      int account_activityEndIndex = sb.indexOf("id=\"for_your_phone\"");

      // int mainContentIndex = sb.indexOf("id=\"mainContent\"");
      if (tel_infoStartIndex == -1) {
        line = "";
      } else {
        line = sb.substring(tel_infoStartIndex, tel_infoEndIndex);
      }
      if (balance_infoStartIndex != -1) {

        line += sb.substring(balance_infoStartIndex, balance_infoEndIndex);
      }
      if (account_activityStartIndex != -1) {
        line += sb.substring(account_activityStartIndex, account_activityEndIndex);
      }
      // Now, try to grab data usage
      String cookies = "";
      // 1. Grab and store cookies
      String headerName = null;
      for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase("Set-Cookie")) {
          String cookie = connection.getHeaderField(i);
          cookie = cookie.substring(0, cookie.indexOf(";"));
          String cookieName = cookie.substring(0, cookie.indexOf("="));
          String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
          cookies = cookies + cookieName + "=" + cookieValue + "; ";
        }
      }
      if (getData == true) {
        // get data page
        HttpsURLConnection connection2 = (HttpsURLConnection) new URL(dataUrl).openConnection();
        ((HttpsURLConnection) connection2).setHostnameVerifier(new AllowAllHostnameVerifier());

        connection2.setDoOutput(true);
        connection2.setRequestProperty("Cookie", cookies);
        connection2.connect();
        InputStreamReader in2 = new InputStreamReader((InputStream) connection2.getContent());

        BufferedReader buff2 = new BufferedReader(in2);

        StringBuilder sb2 = new StringBuilder();

        String dataPage;
        while ((dataPage = buff2.readLine()) != null) {
          sb2.append(dataPage);
        }

        int dataContentIndex = sb2.indexOf("<h2>Mobile Web History</h2>");
        if (dataContentIndex == -1) {
          dataPage = "";
        } else {
          dataPage = sb2.substring(dataContentIndex);
          line += ("****************" + dataPage);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      // System.err.println("exception 83");
      // System.err.println(e.getMessage());
      // System.err.println(line);
      return line;
      // rc.put("isValid", "FALSE");
    }
    return line;
  }
  public static String fetchScreen(String username, String password) {
    String line = "";

    try {
      TrustManager[] trustAllCerts =
          new TrustManager[] {
            new X509TrustManager() {
              public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
              }

              public void checkClientTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}

              public void checkServerTrusted(
                  java.security.cert.X509Certificate[] certs, String authType) {}
            }
          };

      String url = "https://www2.virginmobileusa.com/login/login.do";
      String dataUrl = "https://www2.virginmobileusa.com/myaccount/dataPlanHistory.do";
      // String url = "https://www1.virginmobileusa.com/login/login.do";
      //   String url = "https://www1.virginmobileusa.com/myaccount/home.do";

      try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      } catch (Exception e) {
        e.getMessage();
      }

      // HttpsURLConnection.setFollowRedirects(true);

      HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
      ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

      // connection.setFollowRedirects(true);

      connection.setDoOutput(true);

      String content = "loginRoutingInfo=&min=" + username + "&vkey=" + password + "&submit=submit";

      connection.setFixedLengthStreamingMode(content.length());
      connection.setRequestProperty("Host", "www2.virginmobileusa.com");
      connection.setRequestProperty("Accept-Language", "en-US,en;q=0.9");

      // try {
      // Thread.sleep(5000);
      OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
      out.write(content);
      out.close();
      // } catch (IOException e) {
      //   e.printStackTrace();
      // }

      // connection.connect();

      InputStreamReader in = new InputStreamReader((InputStream) connection.getContent());

      BufferedReader buff = new BufferedReader(in);

      StringBuilder sb = new StringBuilder();

      while ((line = buff.readLine()) != null) {
        sb.append(line);
      }

      int mainContentIndex = sb.indexOf("id=\"mainContent\"");
      if (mainContentIndex == -1) {
        line = "";
      } else {
        line = sb.substring(mainContentIndex);
      }

      // Now, try to grab data usage
      String cookies = "";
      // 1. Grab and store cookies
      String headerName = null;
      for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
        if (headerName.equalsIgnoreCase("Set-Cookie")) {
          String cookie = connection.getHeaderField(i);
          cookie = cookie.substring(0, cookie.indexOf(";"));
          String cookieName = cookie.substring(0, cookie.indexOf("="));
          String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
          cookies = cookies + cookieName + "=" + cookieValue + "; ";
        }
      }
      // connection.disconnect();

      // 2. Grab the next page
      BufferedReader buff2 = new BufferedReader(in);

      StringBuilder sb2 = new StringBuilder();

      connection = (HttpsURLConnection) new URL(dataUrl).openConnection();
      ((HttpsURLConnection) connection).setHostnameVerifier(new AllowAllHostnameVerifier());

      // connection.setFollowRedirects(true);
      connection.setDoOutput(true);
      connection.setRequestProperty("Cookie", cookies);

      // connection.connect();

      in = new InputStreamReader((InputStream) connection.getContent());

      buff2 = new BufferedReader(in);

      sb2 = new StringBuilder();

      String dataPage;
      while ((dataPage = buff2.readLine()) != null) {
        sb2.append(dataPage);
      }

      int dataContentIndex = sb2.indexOf("<h2>Mobile Web History</h2>");
      if (dataContentIndex == -1) {
        dataPage = "";
      } else {
        dataPage = sb2.substring(dataContentIndex);
      }

      // Simply concat the output with our data page output
      if (line != null) {

        // line.concat("---------------TEST----------------------"+ dataPage);
        // line = dataPage;
      }
    } catch (Exception e) {
      e.printStackTrace();
      // System.err.println("exception 83");
      // System.err.println(e.getMessage());
      // System.err.println(line);
      return line;
      // rc.put("isValid", "FALSE");
    }
    // line = null;
    if (line == null) {
      // line = "";
    }
    // System.err.println(line);
    return line;
  }
예제 #7
0
 public void recursiveRequest(String path, String reffer) {
   URL url = null;
   try {
     url = new URL(path);
     conn = (HttpsURLConnection) url.openConnection();
     // 同步接口获取IP
     String ip = httpdns.getIpByHostAsync(url.getHost());
     if (ip != null) {
       // 通过HTTPDNS获取IP成功,进行URL替换和HOST头设置
       Log.d(TAG, "Get IP: " + ip + " for host: " + url.getHost() + " from HTTPDNS successfully!");
       String newUrl = path.replaceFirst(url.getHost(), ip);
       conn = (HttpsURLConnection) new URL(newUrl).openConnection();
       // 设置HTTP请求头Host域
       conn.setRequestProperty("Host", url.getHost());
     }
     conn.setConnectTimeout(30000);
     conn.setReadTimeout(30000);
     conn.setInstanceFollowRedirects(false);
     TlsSniSocketFactory sslSocketFactory = new TlsSniSocketFactory(conn);
     conn.setSSLSocketFactory(sslSocketFactory);
     conn.setHostnameVerifier(
         new HostnameVerifier() {
           /*
            * 关于这个接口的说明,官方有文档描述:
            * This is an extended verification option that implementers can provide.
            * It is to be used during a handshake if the URL's hostname does not match the
            * peer's identification hostname.
            *
            * 使用HTTPDNS后URL里设置的hostname不是远程的主机名(如:m.taobao.com),与证书颁发的域不匹配,
            * Android HttpsURLConnection提供了回调接口让用户来处理这种定制化场景。
            * 在确认HTTPDNS返回的源站IP与Session携带的IP信息一致后,您可以在回调方法中将待验证域名替换为原来的真实域名进行验证。
            *
            */
           @Override
           public boolean verify(String hostname, SSLSession session) {
             String host = conn.getRequestProperty("Host");
             if (null == host) {
               host = conn.getURL().getHost();
             }
             return HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session);
           }
         });
     int code = conn.getResponseCode(); // Network block
     if (needRedirect(code)) {
       // 临时重定向和永久重定向location的大小写有区分
       String location = conn.getHeaderField("Location");
       if (location == null) {
         location = conn.getHeaderField("location");
       }
       if (!(location.startsWith("http://") || location.startsWith("https://"))) {
         // 某些时候会省略host,只返回后面的path,所以需要补全url
         URL originalUrl = new URL(path);
         location = originalUrl.getProtocol() + "://" + originalUrl.getHost() + location;
       }
       recursiveRequest(location, path);
     } else {
       // redirect finish.
       DataInputStream dis = new DataInputStream(conn.getInputStream());
       int len;
       byte[] buff = new byte[4096];
       StringBuilder response = new StringBuilder();
       while ((len = dis.read(buff)) != -1) {
         response.append(new String(buff, 0, len));
       }
       Log.d(TAG, "Response: " + response.toString());
     }
   } catch (MalformedURLException e) {
     Log.w(TAG, "recursiveRequest MalformedURLException");
   } catch (IOException e) {
     Log.w(TAG, "recursiveRequest IOException");
   } catch (Exception e) {
     Log.w(TAG, "unknow exception");
   } finally {
     if (conn != null) {
       conn.disconnect();
     }
   }
 }
예제 #8
0
  @Override
  protected void onHandleIntent(Intent intent) {
    try {
      rec = intent.getParcelableExtra("receiverTag");
      String user = intent.getStringExtra("username");
      String pass = intent.getStringExtra("password");
      String login = "******";
      URL urlForLogin = new URL(login);
      conn = (HttpsURLConnection) urlForLogin.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Cookie", "utmccn=(referral)");
      conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
      conn.setRequestProperty("Accept-Language", "en-US");
      conn.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D)");
      conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
      conn.setRequestProperty("Host", "login.gatech.edu");
      conn.setRequestProperty("DNT", "1");
      conn.setRequestProperty("Connection", "Keep-Alive");
      String cookie = conn.getHeaderField("Set-Cookie"); // Real usage
      String js = parseJsession(cookie); // URL usage
      cookie = (cookie.split(";", 2)[0]);
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String LT = "                        <input type=\"hidden\" name=\"lt\" value=\"";
      String input;
      // LT parameter algorithm
      while ((input = in.readLine()) != null) {
        if (input.startsWith("                        <input type=\"hidden\" name=\"lt\" value="))
          LT = input.substring(LT.length(), input.length() - 4);
      }

      strForHtml = login + js;
      Log.d("StrForHTML:", strForHtml);
      Log.d("LT:", LT);
      URL urlForHtml = new URL(strForHtml);
      conn = (HttpsURLConnection) urlForHtml.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Cookie", cookie + ";utmccn=(referral)");
      conn.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
      conn.setRequestProperty("Accept-Language", "en-US");
      conn.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D)");
      conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
      conn.setRequestProperty("Host", "login.gatech.edu");
      conn.setRequestProperty("DNT", "1");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Referer", "https://login.gatech.edu/cas/login");
      conn.setRequestProperty("Cache-Control", "no-cache");
      conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      String urlParameters =
          "username="******"&password="******"&lt="
              + LT
              + "&execution=e1s1"
              + "&_eventId=submit&submit=LOGIN";
      conn.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(urlParameters);
      wr.flush();
      wr.close();

      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;
      StringBuffer html = new StringBuffer();

      while ((inputLine = in.readLine()) != null) {
        if (inputLine.contains("class=\"errors\"")) {
          html.append(inputLine);
        }
      }
      in.close();

      if (!html.toString().contains("class=\"errors\"")) {
        Log.e("check", "Loged in successfully");
        Bundle b = new Bundle();
        b.putBoolean("ServiceTag", true);
        rec.send(0, b);
      } else {
        Log.e("check", "Wrong username or password!");
        Bundle b = new Bundle();
        b.putBoolean("ServiceTag", false);
        rec.send(0, b);
      }
    } catch (Throwable e) {
      Log.e("check", "ERROR");
    }
  }
예제 #9
0
  @Override
  protected XrayUpdater.CheckResult doInBackground(Void... v) {
    HttpsURLConnection urlConnection = null;
    InputStream inputStream = null;
    XrayUpdater.CheckResult result = XrayUpdater.CheckResult.UP_TO_DATE;

    Log.d(TAG, "Attempting to fetch manifest...");

    try {
      // issue a GET request to determine the latest available apk version
      URL url = new URL(XrayUpdater.VERSION_URL);
      urlConnection =
          PinningHelper.getPinnedHttpsURLConnection(context, XrayUpdater.CERT_PINS, url);
      urlConnection.setConnectTimeout(XrayUpdater.CONNECTION_TIMEOUT);
      urlConnection.setReadTimeout(XrayUpdater.READ_TIMEOUT);
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoInput(true);
      urlConnection.connect();

      int responseCode = urlConnection.getResponseCode();
      int apkVersion = -1;
      String apkName = null;
      String apkChecksum = null;

      // read the results into a byte array stream
      inputStream = new BufferedInputStream(urlConnection.getInputStream());
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      if (responseCode != HttpURLConnection.HTTP_OK) {
        Log.d(TAG, "Error fetching app version, HTTP request returned: " + responseCode);
      } else if (!XrayUpdater.writeToOutputStream(inputStream, byteStream)) {
        Log.d(TAG, "Error fetching app version, invalid input stream");
      } else {
        // request looks okay, let's verify response signature
        Signature ecdsaSignature =
            Signature.getInstance(XrayUpdater.ECDSA_ALGORITHM, XrayUpdater.ECDSA_PROVIDER);
        PublicKey extPubKey = crypto.readPublicKey(XrayUpdater.SERVER_PUB_KEY);
        ecdsaSignature.initVerify(extPubKey);
        ecdsaSignature.update(byteStream.toByteArray());

        String signature = urlConnection.getHeaderField("Xray-Signature");
        byte[] signature_bytes = crypto.base64Decode(signature);

        if (!ecdsaSignature.verify(signature_bytes)) {
          Log.d(TAG, "Invalid signature");
        } else {
          Log.d(TAG, "Signature valid. Reading JSON response...");

          // signature is valid, so read version and filename from JSON response
          inputStream = new ByteArrayInputStream(byteStream.toByteArray());
          JsonReader reader = new JsonReader(new InputStreamReader(inputStream));
          reader.beginObject();
          while (reader.hasNext()) {
            String key = reader.nextName();
            if (key.equals("apkVersion")) {
              apkVersion = Integer.parseInt(reader.nextString());
            } else if (key.equals("apkName")) {
              apkName = reader.nextString();
            } else if (key.equals("apkChecksum")) {
              apkChecksum = reader.nextString();
            } else {
              reader.skipValue();
            }
          }
          reader.endObject();
        }
      }

      if (apkVersion < 0 || apkName == null || apkChecksum == null) {
        Log.d(TAG, "Error fetching app version, JSON response missing fields");
      } else if (apkVersion == BuildConfig.VERSION_CODE) {
        Log.d(TAG, "Already up to date");
      } else { // out of date
        XrayUpdater.setSharedPreference("apkName", apkName);
        XrayUpdater.setSharedPreference("apkChecksum", apkChecksum);
        result = XrayUpdater.CheckResult.OUT_OF_DATE;
      }
    } catch (MalformedURLException e) {
      Log.d(TAG, "Found malformed URL when trying to update");
    } catch (SocketTimeoutException e) {
      Log.d(TAG, "Socket timed out when trying to update: " + e.toString());
    } catch (SSLHandshakeException e) {
      Log.d(TAG, "Failed SSL Handshake when trying to update: " + e.toString());
      result = XrayUpdater.CheckResult.SSL_ERROR;
    } catch (IOException e) {
      Log.d(TAG, "Found IO exception when trying to update: " + e.toString());
    } catch (Exception e) {
      Log.d(TAG, "Received error when trying to update: " + e.toString());
    } finally {
      Log.d(TAG, "Cleaning up check task...");

      // close the GET connection
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          Log.d(TAG, "Found IO exception when trying to close inputstream: " + e.toString());
        }
      }
      if (urlConnection != null) {
        urlConnection.disconnect();
      }

      Log.d(TAG, "Exiting check task");
    }
    return result;
  }