/**
   * Called from native code to share a surface texture with another child process. Through using
   * the callback object the browser is used as a proxy to route the call to the correct process.
   *
   * @param pid Process handle of the child process to share the SurfaceTexture with.
   * @param surfaceObject The Surface or SurfaceTexture to share with the other child process.
   * @param primaryID Used to route the call to the correct client instance.
   * @param secondaryID Used to route the call to the correct client instance.
   */
  @SuppressWarnings("unused")
  @CalledByNative
  private void establishSurfaceTexturePeer(
      int pid, Object surfaceObject, int primaryID, int secondaryID) {
    if (mCallback == null) {
      Log.e(TAG, "No callback interface has been provided.");
      return;
    }

    Surface surface = null;
    boolean needRelease = false;
    if (surfaceObject instanceof Surface) {
      surface = (Surface) surfaceObject;
    } else if (surfaceObject instanceof SurfaceTexture) {
      surface = new Surface((SurfaceTexture) surfaceObject);
      needRelease = true;
    } else {
      Log.e(TAG, "Not a valid surfaceObject: %s", surfaceObject);
      return;
    }
    try {
      mCallback.establishSurfacePeer(pid, surface, primaryID, secondaryID);
    } catch (RemoteException e) {
      Log.e(TAG, "Unable to call establishSurfaceTexturePeer: %s", e);
      return;
    } finally {
      if (needRelease) {
        surface.release();
      }
    }
  }
Beispiel #2
0
  @Override
  protected boolean isStartedUpCorrectly(Intent intent) {
    int tabId = ActivityDelegate.getTabIdFromIntent(getIntent());

    // Fire a MAIN Intent to send the user back through ChromeLauncherActivity.
    Log.e(TAG, "User shouldn't be here.  Sending back to ChromeLauncherActivity.");

    // Try to bring this tab forward after migration.
    Intent tabbedIntent = null;
    if (tabId != Tab.INVALID_TAB_ID) tabbedIntent = Tab.createBringTabToFrontIntent(tabId);

    if (tabbedIntent == null) {
      tabbedIntent = new Intent(Intent.ACTION_MAIN);
      tabbedIntent.setPackage(getPackageName());
    }

    // Launch the other Activity in its own task so it stays when this one finishes.
    tabbedIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    tabbedIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);

    startActivity(tabbedIntent);
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

    Log.e(TAG, "Discarding Intent: Tab = " + tabId);
    return false;
  }
Beispiel #3
0
  /**
   * Restores the encryption key from the given Bundle. Expected to be called when an Activity is
   * being restored after being killed in the background. If the Activity was explicitly killed by
   * the user, Android gives no Bundle (and therefore no key).
   *
   * @param savedInstanceState Bundle containing the Activity's previous state. Null if the user
   *     explicitly killed the Activity.
   * @return True if the data was restored successfully from the Bundle, or if the CipherData in use
   *     matches the Bundle contents.
   */
  public boolean restoreFromBundle(Bundle savedInstanceState) {
    if (savedInstanceState == null) return false;

    byte[] wrappedKey = savedInstanceState.getByteArray(BUNDLE_KEY);
    byte[] iv = savedInstanceState.getByteArray(BUNDLE_IV);
    if (wrappedKey == null || iv == null) return false;

    try {
      Key bundledKey = new SecretKeySpec(wrappedKey, "AES");
      synchronized (mDataLock) {
        if (mData == null) {
          mData = new CipherData(bundledKey, iv);
          return true;
        } else if (mData.key.equals(bundledKey) && Arrays.equals(mData.iv, iv)) {
          return true;
        } else {
          Log.e(TAG, "Attempted to restore different cipher data.");
        }
      }
    } catch (IllegalArgumentException e) {
      Log.e(TAG, "Error in restoring the key from the bundle.");
    }

    return false;
  }
    /** Registers this object with the location service. */
    private void registerForLocationUpdates(boolean enableHighAccuracy) {
      ensureLocationManagerCreated();
      if (usePassiveOneShotLocation()) return;

      assert !mIsRunning;
      mIsRunning = true;

      // We're running on the main thread. The C++ side is responsible to
      // bounce notifications to the Geolocation thread as they arrive in the mainLooper.
      try {
        Criteria criteria = new Criteria();
        if (enableHighAccuracy) criteria.setAccuracy(Criteria.ACCURACY_FINE);
        mLocationManager.requestLocationUpdates(
            0, 0, criteria, this, ThreadUtils.getUiThreadLooper());
      } catch (SecurityException e) {
        Log.e(
            TAG,
            "Caught security exception while registering for location updates "
                + "from the system. The application does not have sufficient geolocation "
                + "permissions.");
        unregisterFromLocationUpdates();
        // Propagate an error to JavaScript, this can happen in case of WebView
        // when the embedding app does not have sufficient permissions.
        LocationProviderAdapter.newErrorAvailable(
            "application does not have sufficient " + "geolocation permissions.");
      } catch (IllegalArgumentException e) {
        Log.e(TAG, "Caught IllegalArgumentException registering for location updates.");
        unregisterFromLocationUpdates();
        assert false;
      }
    }
Beispiel #5
0
  @CalledByNative
  public void startCapture() {
    Log.d(TAG, "startCapture");
    synchronized (mCaptureStateLock) {
      if (mCaptureState != CaptureState.ALLOWED) {
        Log.e(TAG, "startCapture() invoked without user permission.");
        return;
      }
    }
    mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData);
    if (mMediaProjection == null) {
      Log.e(TAG, "mMediaProjection is null");
      return;
    }
    mMediaProjection.registerCallback(new MediaProjectionCallback(), null);

    mThread = new HandlerThread("ScreenCapture");
    mThread.start();
    mBackgroundHandler = new Handler(mThread.getLooper());

    // On Android M and above, YUV420 is prefered. Some Android L devices will silently
    // fail with YUV420, so keep with RGBA_8888 on L.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
      mFormat = PixelFormat.RGBA_8888;
    } else {
      mFormat = ImageFormat.YUV_420_888;
    }
    maybeDoRotation();
    createImageReaderWithFormat();
    createVirtualDisplay();

    changeCaptureStateAndNotify(CaptureState.STARTED);
  }
Beispiel #6
0
 private void waitForDebuggerIfNeeded() {
   if (CommandLine.getInstance().hasSwitch(BaseSwitches.WAIT_FOR_JAVA_DEBUGGER)) {
     Log.e(TAG, "Waiting for Java debugger to connect...");
     android.os.Debug.waitForDebugger();
     Log.e(TAG, "Java debugger connected. Resuming execution.");
   }
 }
Beispiel #7
0
  /**
   * Return the OpenSSLEngine object corresponding to a given PrivateKey object.
   *
   * <p>This shall only be used for Android 4.1 to work around a platform bug. See
   * https://crbug.com/381465.
   *
   * @param privateKey The PrivateKey handle.
   * @return The OpenSSLEngine object (or null if not available)
   */
  @CalledByNative
  private static Object getOpenSSLEngineForPrivateKey(PrivateKey privateKey) {
    // Find the system OpenSSLEngine class.
    Class<?> engineClass;
    try {
      engineClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLEngine");
    } catch (Exception e) {
      // This may happen if the target device has a completely different
      // implementation of the java.security APIs, compared to vanilla
      // Android. Highly unlikely, but still possible.
      Log.e(TAG, "Cannot find system OpenSSLEngine class: " + e);
      return null;
    }

    Object opensslKey = getOpenSSLKeyForPrivateKey(privateKey);
    if (opensslKey == null) return null;

    try {
      // Use reflection to invoke the 'getEngine' method on the
      // result of the getOpenSSLKey().
      Method getEngine;
      try {
        getEngine = opensslKey.getClass().getDeclaredMethod("getEngine");
      } catch (Exception e) {
        // Bail here too, something really not working as expected.
        Log.e(TAG, "No getEngine() method on OpenSSLKey member:" + e);
        return null;
      }
      getEngine.setAccessible(true);
      Object engine = null;
      try {
        engine = getEngine.invoke(opensslKey);
      } finally {
        getEngine.setAccessible(false);
      }
      if (engine == null) {
        // The PrivateKey is probably rotten for some reason.
        Log.e(TAG, "getEngine() returned null");
      }
      // Sanity-check the returned engine.
      if (!engineClass.isInstance(engine)) {
        Log.e(
            TAG,
            "Engine is not an OpenSSLEngine instance, its class name is:"
                + engine.getClass().getCanonicalName());
        return null;
      }
      return engine;

    } catch (Exception e) {
      Log.e(TAG, "Exception while trying to retrieve OpenSSLEngine object: " + e);
      return null;
    }
  }
  @SuppressWarnings("unused")
  @CalledByNative
  private void destroySurfaceTextureSurface(int surfaceTextureId, int clientId) {
    if (mCallback == null) {
      Log.e(TAG, "No callback interface has been provided.");
      return;
    }

    try {
      mCallback.unregisterSurfaceTextureSurface(surfaceTextureId, clientId);
    } catch (RemoteException e) {
      Log.e(TAG, "Unable to call unregisterSurfaceTextureSurface: %s", e);
    }
  }
  @SuppressWarnings("unused")
  @CalledByNative
  private Surface getSurfaceTextureSurface(int surfaceTextureId) {
    if (mCallback == null) {
      Log.e(TAG, "No callback interface has been provided.");
      return null;
    }

    try {
      return mCallback.getSurfaceTextureSurface(surfaceTextureId).getSurface();
    } catch (RemoteException e) {
      Log.e(TAG, "Unable to call getSurfaceTextureSurface: %s", e);
      return null;
    }
  }
Beispiel #10
0
  // SET_VOLUME messages have a |level| and |muted| properties. One of them is
  // |null| and the other one isn't. |muted| is expected to be a boolean while
  // |level| is a float from 0.0 to 1.0.
  // Example:
  // {
  //   "volume" {
  //     "level": 0.9,
  //     "muted": null
  //   }
  // }
  @Override
  public HandleVolumeMessageResult handleVolumeMessage(
      JSONObject volume, final String clientId, final int sequenceNumber) throws JSONException {
    if (volume == null) return new HandleVolumeMessageResult(false, false);

    if (isApiClientInvalid()) return new HandleVolumeMessageResult(false, false);

    boolean waitForVolumeChange = false;
    try {
      if (!volume.isNull("muted")) {
        boolean newMuted = volume.getBoolean("muted");
        if (Cast.CastApi.isMute(mApiClient) != newMuted) {
          Cast.CastApi.setMute(mApiClient, newMuted);
          waitForVolumeChange = true;
        }
      }
      if (!volume.isNull("level")) {
        double newLevel = volume.getDouble("level");
        double currentLevel = Cast.CastApi.getVolume(mApiClient);
        if (!Double.isNaN(currentLevel)
            && Math.abs(currentLevel - newLevel) > MIN_VOLUME_LEVEL_DELTA) {
          Cast.CastApi.setVolume(mApiClient, newLevel);
          waitForVolumeChange = true;
        }
      }
    } catch (IOException e) {
      Log.e(TAG, "Failed to send volume command: " + e);
      return new HandleVolumeMessageResult(false, false);
    }

    return new HandleVolumeMessageResult(true, waitForVolumeChange);
  }
 private void ensureLocationManagerCreated() {
   if (mLocationManager != null) return;
   mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
   if (mLocationManager == null) {
     Log.e(TAG, "Could not get location manager.");
   }
 }
  @SuppressWarnings("unused")
  @CalledByNative
  private void createSurfaceTextureSurface(
      int surfaceTextureId, int clientId, SurfaceTexture surfaceTexture) {
    if (mCallback == null) {
      Log.e(TAG, "No callback interface has been provided.");
      return;
    }

    Surface surface = new Surface(surfaceTexture);
    try {
      mCallback.registerSurfaceTextureSurface(surfaceTextureId, clientId, surface);
    } catch (RemoteException e) {
      Log.e(TAG, "Unable to call registerSurfaceTextureSurface: %s", e);
    }
    surface.release();
  }
 private static void deleteFileForOverwrite(DownloadInfo info) {
   assert !ThreadUtils.runningOnUiThread();
   File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
   if (!dir.isDirectory()) return;
   final File file = new File(dir, info.getFileName());
   if (!file.delete()) {
     Log.e(TAG, "Failed to delete a file: " + info.getFileName());
   }
 }
 /**
  * Check the external storage and notify user on error.
  *
  * @param fullDirPath The dir path to download a file. Normally this is external storage.
  * @param externalStorageStatus The status of the external storage.
  * @return Whether external storage is ok for downloading.
  */
 private boolean checkExternalStorageAndNotify(
     String filename, String fullDirPath, String externalStorageStatus) {
   if (fullDirPath == null) {
     Log.e(TAG, "Download failed: no SD card");
     alertDownloadFailure(filename);
     return false;
   }
   if (!externalStorageStatus.equals(Environment.MEDIA_MOUNTED)) {
     // Check to see if the SDCard is busy, same as the music app
     if (externalStorageStatus.equals(Environment.MEDIA_SHARED)) {
       Log.e(TAG, "Download failed: SD card unavailable");
     } else {
       Log.e(TAG, "Download failed: no SD card");
     }
     alertDownloadFailure(filename);
     return false;
   }
   return true;
 }
Beispiel #15
0
  private void unregisterNamespace(String namespace) {
    assert mNamespaces.contains(namespace);

    if (isApiClientInvalid()) return;

    try {
      Cast.CastApi.removeMessageReceivedCallbacks(mApiClient, namespace);
      mNamespaces.remove(namespace);
    } catch (IOException e) {
      Log.e(TAG, "Failed to remove the namespace listener for %s", namespace, e);
    }
  }
  @CalledByNative
  private static SurfaceWrapper getSurfaceTextureSurface(int surfaceTextureId, int clientId) {
    Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId);

    Surface surface = sSurfaceTextureSurfaceMap.get(key);
    if (surface == null) {
      Log.e(TAG, "Invalid Id for surface texture.");
      return null;
    }
    assert surface.isValid();
    return new SurfaceWrapper(surface);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = getIntent();
    WebappInfo webappInfo = WebappInfo.create(intent);
    String webappId = webappInfo.id();
    String webappUrl = webappInfo.uri().toString();
    int webappSource = webappInfo.source();

    if (webappId != null && webappUrl != null) {
      String webappMacString = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_MAC);
      byte[] webappMac =
          webappMacString == null ? null : Base64.decode(webappMacString, Base64.DEFAULT);

      Intent launchIntent = null;
      if (webappMac != null && WebappAuthenticator.isUrlValid(this, webappUrl, webappMac)) {
        LaunchMetrics.recordHomeScreenLaunchIntoStandaloneActivity(webappUrl, webappSource);

        String activityName = WebappActivity.class.getName();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
          // Specifically assign the app to a particular WebappActivity instance.
          int activityIndex = ActivityAssigner.instance(this).assign(webappId);
          activityName += String.valueOf(activityIndex);
        }

        // Create an intent to launch the Webapp in an unmapped WebappActivity.
        launchIntent = new Intent();
        launchIntent.setClassName(this, activityName);
        webappInfo.setWebappIntentExtras(launchIntent);

        // On L+, firing intents with the exact same data should relaunch a particular
        // Activity.
        launchIntent.setAction(Intent.ACTION_VIEW);
        launchIntent.setData(Uri.parse(WebappActivity.WEBAPP_SCHEME + "://" + webappId));
      } else {
        Log.e(TAG, "Shortcut (" + webappUrl + ") opened in Chrome.");

        // The shortcut data doesn't match the current encoding.  Change the intent action
        // launch the URL with a VIEW Intent in the regular browser.
        launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(webappUrl));
        launchIntent.setClassName(getPackageName(), ChromeLauncherActivity.class.getName());
        launchIntent.putExtra(ShortcutHelper.REUSE_URL_MATCHING_TAB_ELSE_NEW_TAB, true);
        launchIntent.putExtra(ShortcutHelper.EXTRA_SOURCE, webappSource);
      }

      launchIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | ApiCompatibilityUtils.getActivityNewDocumentFlag());
      startActivity(launchIntent);
    }

    ApiCompatibilityUtils.finishAndRemoveTask(this);
  }
 @CalledByNative
 private static void launchExternalProtocol(String url) {
   Context context = ApplicationStatus.getApplicationContext();
   Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
   intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   intent.addCategory(Intent.CATEGORY_BROWSABLE);
   try {
     context.startActivity(intent);
   } catch (ActivityNotFoundException e) {
     Log.e(TAG, "cannot find activity to launch " + url, e);
   }
 }
Beispiel #19
0
  /**
   * Sign a given message with a given PrivateKey object. This method shall only be used to
   * implement signing in the context of SSL client certificate support.
   *
   * <p>The message will actually be a hash, computed by OpenSSL itself, depending on the type of
   * the key. The result should match exactly what the vanilla implementations of the following
   * OpenSSL function calls do:
   *
   * <p>- For a RSA private key, this should be equivalent to calling RSA_private_encrypt(...,
   * RSA_PKCS1_PADDING), i.e. it must generate a raw RSA signature. The message must be either a
   * combined, 36-byte MD5+SHA1 message digest or a DigestInfo value wrapping a message digest.
   *
   * <p>- For a ECDSA private keys, this should be equivalent to calling ECDSA_sign(0,...). The
   * message must be a hash and the function shall compute a direct ECDSA signature for it.
   *
   * @param privateKey The PrivateKey handle.
   * @param message The message to sign.
   * @return signature as a byte buffer.
   *     <p>Important: Due to a platform bug, this function will always fail on Android < 4.2 for
   *     RSA PrivateKey objects. See the getOpenSSLHandleForPrivateKey() below for work-around.
   */
  @CalledByNative
  private static byte[] rawSignDigestWithPrivateKey(PrivateKey privateKey, byte[] message) {
    // Get the Signature for this key.
    Signature signature = null;
    // Hint: Algorithm names come from:
    // http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
    try {
      String keyAlgorithm = privateKey.getAlgorithm();
      if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
        // IMPORTANT: Due to a platform bug, this will throw NoSuchAlgorithmException
        // on Android 4.1.x. Fixed in 4.2 and higher.
        // See https://android-review.googlesource.com/#/c/40352/
        signature = Signature.getInstance("NONEwithRSA");
      } else if ("EC".equalsIgnoreCase(keyAlgorithm)) {
        signature = Signature.getInstance("NONEwithECDSA");
      }
    } catch (NoSuchAlgorithmException e) {
      // Intentionally do nothing.
    }

    if (signature == null) {
      Log.e(TAG, "Unsupported private key algorithm: " + privateKey.getAlgorithm());
      return null;
    }

    // Sign the message.
    try {
      signature.initSign(privateKey);
      signature.update(message);
      return signature.sign();
    } catch (Exception e) {
      Log.e(
          TAG,
          "Exception while signing message with "
              + privateKey.getAlgorithm()
              + " private key: "
              + e);
      return null;
    }
  }
Beispiel #20
0
  /**
   * Return the system EVP_PKEY handle corresponding to a given PrivateKey object.
   *
   * <p>This shall only be used when the "NONEwithRSA" signature is not available, as described in
   * rawSignDigestWithPrivateKey(). I.e. never use this on Android 4.2 or higher.
   *
   * <p>This can only work in Android 4.0.4 and higher, for older versions of the platform (e.g.
   * 4.0.3), there is no system OpenSSL EVP_PKEY, but the private key contents can be retrieved
   * directly with the getEncoded() method.
   *
   * <p>This assumes that the target device uses a vanilla AOSP implementation of its java.security
   * classes, which is also based on OpenSSL (fortunately, no OEM has apperently changed to a
   * different implementation, according to the Android team).
   *
   * <p>Note that the object returned was created with the platform version of OpenSSL, and _not_
   * the one that comes with Chromium. It may not be used with the Chromium version of OpenSSL
   * (BoringSSL). See AndroidEVP_PKEY in net/android/legacy_openssl.h.
   *
   * <p>To better understand what's going on below, please refer to the following source files in
   * the Android 4.0.4 and 4.1 source trees:
   * libcore/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLRSAPrivateKey.java
   * libcore/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
   *
   * @param privateKey The PrivateKey handle.
   * @return The EVP_PKEY handle, as a 32-bit integer (0 if not available)
   */
  @CalledByNative
  private static long getOpenSSLHandleForPrivateKey(PrivateKey privateKey) {
    Object opensslKey = getOpenSSLKeyForPrivateKey(privateKey);
    if (opensslKey == null) return 0;

    try {
      // Use reflection to invoke the 'getPkeyContext' method on the
      // result of the getOpenSSLKey(). This is an 32-bit integer
      // which is the address of an EVP_PKEY object. Note that this
      // method these days returns a 64-bit long, but since this code
      // path is used for older Android versions, it may still return
      // a 32-bit int here. To be on the safe side, we cast the return
      // value via Number rather than directly to Integer or Long.
      Method getPkeyContext;
      try {
        getPkeyContext = opensslKey.getClass().getDeclaredMethod("getPkeyContext");
      } catch (Exception e) {
        // Bail here too, something really not working as expected.
        Log.e(TAG, "No getPkeyContext() method on OpenSSLKey member:" + e);
        return 0;
      }
      getPkeyContext.setAccessible(true);
      long evp_pkey = 0;
      try {
        evp_pkey = ((Number) getPkeyContext.invoke(opensslKey)).longValue();
      } finally {
        getPkeyContext.setAccessible(false);
      }
      if (evp_pkey == 0) {
        // The PrivateKey is probably rotten for some reason.
        Log.e(TAG, "getPkeyContext() returned null");
      }
      return evp_pkey;

    } catch (Exception e) {
      Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
      return 0;
    }
  }
Beispiel #21
0
  private static Object getOpenSSLKeyForPrivateKey(PrivateKey privateKey) {
    // Sanity checks
    if (privateKey == null) {
      Log.e(TAG, "privateKey == null");
      return null;
    }
    if (!(privateKey instanceof RSAPrivateKey)) {
      Log.e(TAG, "does not implement RSAPrivateKey");
      return null;
    }
    // First, check that this is a proper instance of OpenSSLRSAPrivateKey
    // or one of its sub-classes.
    Class<?> superClass;
    try {
      superClass = Class.forName("org.apache.harmony.xnet.provider.jsse.OpenSSLRSAPrivateKey");
    } catch (Exception e) {
      // This may happen if the target device has a completely different
      // implementation of the java.security APIs, compared to vanilla
      // Android. Highly unlikely, but still possible.
      Log.e(TAG, "Cannot find system OpenSSLRSAPrivateKey class: " + e);
      return null;
    }
    if (!superClass.isInstance(privateKey)) {
      // This may happen if the PrivateKey was not created by the "AndroidOpenSSL"
      // provider, which should be the default. That could happen if an OEM decided
      // to implement a different default provider. Also highly unlikely.
      Log.e(
          TAG,
          "Private key is not an OpenSSLRSAPrivateKey instance, its class name is:"
              + privateKey.getClass().getCanonicalName());
      return null;
    }

    try {
      // Use reflection to invoke the 'getOpenSSLKey()' method on the
      // private key. This returns another Java object that wraps a native
      // EVP_PKEY and OpenSSLEngine. Note that the method is final in Android
      // 4.1, so calling the superclass implementation is ok.
      Method getKey = superClass.getDeclaredMethod("getOpenSSLKey");
      getKey.setAccessible(true);
      Object opensslKey = null;
      try {
        opensslKey = getKey.invoke(privateKey);
      } finally {
        getKey.setAccessible(false);
      }
      if (opensslKey == null) {
        // Bail when detecting OEM "enhancement".
        Log.e(TAG, "getOpenSSLKey() returned null");
        return null;
      }
      return opensslKey;
    } catch (Exception e) {
      Log.e(TAG, "Exception while trying to retrieve system EVP_PKEY handle: " + e);
      return null;
    }
  }
Beispiel #22
0
  @CalledByNative
  public boolean startPrompt() {
    Log.d(TAG, "startPrompt");
    Activity activity = ApplicationStatus.getLastTrackedFocusedActivity();
    if (activity == null) {
      Log.e(TAG, "activity is null");
      return false;
    }
    FragmentManager fragmentManager = activity.getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(this, "screencapture");
    try {
      fragmentTransaction.commit();
    } catch (RuntimeException e) {
      Log.e(TAG, "ScreenCaptureExcaption " + e);
      return false;
    }

    synchronized (mCaptureStateLock) {
      while (mCaptureState != CaptureState.ATTACHED) {
        try {
          mCaptureStateLock.wait();
        } catch (InterruptedException ex) {
          Log.e(TAG, "ScreenCaptureException: " + ex);
        }
      }
    }

    try {
      startActivityForResult(
          mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
    } catch (android.content.ActivityNotFoundException e) {
      Log.e(TAG, "ScreenCaptureException " + e);
      return false;
    }
    return true;
  }
Beispiel #23
0
 /**
  * Extracts the mojo applications from the apk assets and returns the directory where they are.
  */
 @CalledByNative
 private static String extractMojoApplications(Context context) throws IOException {
   File cachedAppsDir = FileHelper.getCachedAppsDir(context);
   try {
     FileHelper.prepareDirectoryForAssets(context, cachedAppsDir);
     for (String assetPath : FileHelper.getAssetsList(context)) {
       FileHelper.extractFromAssets(
           context, assetPath, cachedAppsDir, FileHelper.FileType.PERMANENT);
     }
   } catch (Exception e) {
     Log.e(TAG, "ShellTestBase initialization failed.", e);
     throw new RuntimeException(e);
   }
   return cachedAppsDir.getAbsolutePath();
 }
Beispiel #24
0
  /**
   * Receive a broadcast intent.
   *
   * @param context The Context in which the receiver is running.
   * @param intent The intent received.
   */
  @Override
  public void onReceive(Context context, Intent intent) {
    int pid = intent.getIntExtra(TestStatusReporter.EXTRA_PID, 0);
    String testClass = intent.getStringExtra(TestStatusReporter.EXTRA_TEST_CLASS);
    String testMethod = intent.getStringExtra(TestStatusReporter.EXTRA_TEST_METHOD);
    String stackTrace = intent.getStringExtra(TestStatusReporter.EXTRA_STACK_TRACE);

    switch (intent.getAction()) {
      case TestStatusReporter.ACTION_TEST_STARTED:
        for (StartCallback c : mStartCallbacks) {
          c.testStarted(testClass, testMethod);
        }
        break;
      case TestStatusReporter.ACTION_TEST_PASSED:
        for (PassCallback c : mPassCallbacks) {
          c.testPassed(testClass, testMethod);
        }
        break;
      case TestStatusReporter.ACTION_TEST_FAILED:
        for (FailCallback c : mFailCallbacks) {
          c.testFailed(testClass, testMethod, stackTrace);
        }
        break;
      case TestStatusReporter.ACTION_HEARTBEAT:
        for (HeartbeatCallback c : mHeartbeatCallbacks) {
          c.heartbeat();
        }
        break;
      case TestStatusReporter.ACTION_TEST_RUN_STARTED:
        for (TestRunCallback c : mTestRunCallbacks) {
          c.testRunStarted(pid);
        }
        break;
      case TestStatusReporter.ACTION_TEST_RUN_FINISHED:
        for (TestRunCallback c : mTestRunCallbacks) {
          c.testRunFinished(pid);
        }
        break;
      case TestStatusReporter.ACTION_UNCAUGHT_EXCEPTION:
        for (TestRunCallback c : mTestRunCallbacks) {
          c.uncaughtException(pid, stackTrace);
        }
        break;
      default:
        Log.e(TAG, "Unrecognized intent received: %s", intent.toString());
        break;
    }
  }
Beispiel #25
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AwShellResourceProvider.registerResources(this);

    ContentApplication.initCommandLine(this);
    waitForDebuggerIfNeeded();

    AwBrowserProcess.loadLibrary(this);

    if (CommandLine.getInstance().hasSwitch(AwShellSwitches.ENABLE_ATRACE)) {
      Log.e(TAG, "Enabling Android trace.");
      TraceEvent.setATraceEnabled(true);
    }

    setContentView(R.layout.testshell_activity);

    mAwTestContainerView = createAwTestContainerView();

    mWebContents = mAwTestContainerView.getContentViewCore().getWebContents();
    mNavigationController = mWebContents.getNavigationController();
    LinearLayout contentContainer = (LinearLayout) findViewById(R.id.content_container);
    mAwTestContainerView.setLayoutParams(
        new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f));
    contentContainer.addView(mAwTestContainerView);
    mAwTestContainerView.requestFocus();

    initializeUrlField();
    initializeNavigationButtons();

    String startupUrl = getUrlFromIntent(getIntent());
    if (TextUtils.isEmpty(startupUrl)) {
      startupUrl = INITIAL_URL;
    }

    mAwTestContainerView.getAwContents().loadUrl(new LoadUrlParams(startupUrl));
    AwContents.setShouldDownloadFavicons();
    mUrlTextView.setText(startupUrl);

    if (CommandLine.getInstance().hasSwitch(ENABLE_DATA_REDUCTION_PROXY)) {
      String key = CommandLine.getInstance().getSwitchValue(DATA_REDUCTION_PROXY_KEY);
      if (key != null && !key.isEmpty()) {
        AwContentsStatics.setDataReductionProxyKey(key);
        AwContentsStatics.setDataReductionProxyEnabled(true);
      }
    }
  }
Beispiel #26
0
  /**
   * Creates a secure Cipher for encrypting data. This function blocks until data needed to generate
   * a Cipher has been created by the background thread.
   *
   * @param opmode One of Cipher.{ENCRYPT,DECRYPT}_MODE.
   * @return A Cipher, or null if it is not possible to instantiate one.
   */
  public Cipher getCipher(int opmode) {
    CipherData data = getCipherData(true);

    if (data != null) {
      try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(opmode, data.key, new IvParameterSpec(data.iv));
        return cipher;
      } catch (GeneralSecurityException e) {
        // Can't do anything here.
      }
    }

    Log.e(TAG, "Error in creating cipher instance.");
    return null;
  }
Beispiel #27
0
  @Override
  public void updateSessionStatus() {
    if (isApiClientInvalid()) return;

    try {
      mApplicationStatus = Cast.CastApi.getApplicationStatus(mApiClient);
      mApplicationMetadata = Cast.CastApi.getApplicationMetadata(mApiClient);

      updateNamespaces();

      mMessageHandler.broadcastClientMessage(
          "update_session", mMessageHandler.buildSessionMessage());
    } catch (IllegalStateException e) {
      Log.e(TAG, "Can't get application status", e);
    }
  }
 @CalledByNative
 private static FileDescriptorInfo makeFdInfo(
     int id, int fd, boolean autoClose, long offset, long size) {
   ParcelFileDescriptor pFd;
   if (autoClose) {
     // Adopt the FD, it will be closed when we close the ParcelFileDescriptor.
     pFd = ParcelFileDescriptor.adoptFd(fd);
   } else {
     try {
       pFd = ParcelFileDescriptor.fromFd(fd);
     } catch (IOException e) {
       Log.e(TAG, "Invalid FD provided for process connection, aborting connection.", e);
       return null;
     }
   }
   return new FileDescriptorInfo(id, pFd, offset, size);
 }
Beispiel #29
0
  private void addNamespace(String namespace) {
    assert !mNamespaces.contains(namespace);

    if (isApiClientInvalid()) return;

    // If application metadata is null, register the callback anyway.
    if (mApplicationMetadata != null && !mApplicationMetadata.isNamespaceSupported(namespace)) {
      return;
    }

    try {
      Cast.CastApi.setMessageReceivedCallbacks(mApiClient, namespace, mMessageChannel);
      mNamespaces.add(namespace);
    } catch (IOException e) {
      Log.e(TAG, "Failed to register namespace listener for %s", namespace, e);
    }
  }
Beispiel #30
0
 @Override
 protected List<SnippetListItem> doInBackground(Void... params) {
   FileInputStream fis = null;
   try {
     fis =
         new FileInputStream(
             new File(
                 Environment.getExternalStorageDirectory().getPath()
                     + "/chrome/reading_list.json"));
     List<SnippetListItem> listSnippetsGroups = readJsonStream(fis);
     return listSnippetsGroups;
   } catch (IOException ex) {
     Log.e(TAG, "Exception reading file: %s ", ex);
   } finally {
     StreamUtil.closeQuietly(fis);
   }
   return null;
 }