예제 #1
0
파일: Util.java 프로젝트: paour/XPrivacy
  public static void log(XHook hook, int priority, String msg) {
    // Check if logging enabled
    int uid = Process.myUid();
    if (!mLogDetermined && uid > 0) {
      mLogDetermined = true;
      try {
        if (uid == Process.SYSTEM_UID)
          mLog = PrivacyService.getSettingBool(0, PrivacyManager.cSettingLog, false);
        else mLog = PrivacyManager.getSettingBool(0, PrivacyManager.cSettingLog, false, true);
      } catch (Throwable ignored) {
        mLog = false;
      }
    }

    // Log if enabled
    if (priority != Log.DEBUG && (priority == Log.INFO ? mLog : true))
      if (hook == null) Log.println(priority, "XPrivacy", msg);
      else
        Log.println(priority, String.format("XPrivacy/%s", hook.getClass().getSimpleName()), msg);

    // Report to service
    if (Process.myUid() > 0 && priority == Log.ERROR)
      if (Process.myUid() == Process.SYSTEM_UID) PrivacyService.reportErrorInternal(msg);
      else
        try {
          IPrivacyService client = PrivacyService.getClient();
          if (client != null) client.reportError(msg);
        } catch (RemoteException ignored) {
        }
  }
예제 #2
0
파일: Util.java 프로젝트: paour/XPrivacy
  public static String[] getProLicenseUnchecked() {
    // Get license file name
    String storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    File licenseFile = new File(storageDir + File.separator + LICENSE_FILE_NAME);
    if (!licenseFile.exists())
      licenseFile =
          new File(storageDir + File.separator + ".xprivacy" + File.separator + LICENSE_FILE_NAME);

    // Get imported license file name
    String importedLicense =
        getUserDataDirectory(Process.myUid()) + File.separator + LICENSE_FILE_NAME;

    // Import license file
    if (licenseFile.exists()) {
      try {
        File out = new File(importedLicense);
        Util.log(null, Log.WARN, "Licensing: importing " + out.getAbsolutePath());
        InputStream is = new FileInputStream(licenseFile.getAbsolutePath());
        OutputStream os = new FileOutputStream(out.getAbsolutePath());
        byte[] buffer = new byte[1024];
        int read;
        while ((read = is.read(buffer)) != -1) os.write(buffer, 0, read);
        is.close();
        os.flush();
        os.close();

        // Protect license file
        setPermissions(out.getAbsolutePath(), 0700, Process.myUid(), Process.myUid());

        licenseFile.delete();
      } catch (Throwable ex) {
        Util.bug(null, ex);
      }
    }

    // Check license file
    licenseFile = new File(importedLicense);
    if (licenseFile.exists()) {
      // Read license
      try {
        IniFile iniFile = new IniFile(licenseFile);
        String name = iniFile.get("name", "");
        String email = iniFile.get("email", "");
        String signature = iniFile.get("signature", "");
        return new String[] {name, email, signature};
      } catch (Throwable ex) {
        bug(null, ex);
        return null;
      }
    } else Util.log(null, Log.INFO, "Licensing: no license file");
    return null;
  }
예제 #3
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    if (PrivacyService.checkClient()) {
      // Set theme
      int userId = Util.getUserId(Process.myUid());
      String themeName = PrivacyManager.getSetting(userId, PrivacyManager.cSettingTheme, "");
      mThemeId = (themeName.equals("Dark") ? R.style.CustomTheme : R.style.CustomTheme_Light);
      setTheme(mThemeId);
      super.onCreate(savedInstanceState);
    } else {
      super.onCreate(savedInstanceState);
      // Privacy client now available
      setContentView(R.layout.reboot);

      try {
        PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        TextView tvVersion = (TextView) findViewById(R.id.tvVersion);
        tvVersion.setText(pInfo.versionName);
      } catch (Throwable ex) {
        Util.bug(null, ex);
      }

      // Show reason
      if (PrivacyService.getClient() == null) {
        TextView tvRebootClient = (TextView) findViewById(R.id.tvRebootClient);
        tvRebootClient.setVisibility(View.VISIBLE);
        Requirements.checkCompatibility(this);
      } else {
        TextView tvRebootClient = (TextView) findViewById(R.id.tvRebootVersion);
        tvRebootClient.setVisibility(View.VISIBLE);
        Requirements.check(this);
      }
    }
  }
예제 #4
0
파일: SerFloat.java 프로젝트: zhl3391/face
 @Override
 public void onCreate() {
   super.onCreate();
   mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
   mHandler =
       new Handler() {
         public void handleMessage(Message msg) {
           switch (msg.what) {
             case MSG_SHOW:
               ((ButtonFloatSmall) mFloatView).setIconRes(mSendWayEnum.getIconResId());
               mFloatView.setVisibility(View.VISIBLE);
               break;
             case MSG_HIDE:
               mFloatView.setVisibility(View.GONE);
               break;
             default:
               break;
           }
         }
       };
   initFloatView();
   createFloatView();
   schedule();
   startForeground(android.os.Process.myUid(), new Notification());
 }
예제 #5
0
 public AwSettings(Context context) {
   mContext = context;
   mBlockNetworkLoads =
       mContext.checkPermission(
               android.Manifest.permission.INTERNET, Process.myPid(), Process.myUid())
           != PackageManager.PERMISSION_GRANTED;
 }
 public boolean canGetUsageStats() {
   if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
     return true;
   }
   AppOpsManager aom = (AppOpsManager) getSystemService(APP_OPS_SERVICE);
   int uid = android.os.Process.myUid();
   int mode = aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, uid, getPackageName());
   return mode == AppOpsManager.MODE_ALLOWED;
 }
예제 #7
0
 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 public static boolean usageAccessGranted(Context context) {
   AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
   int mode =
       appOps.checkOpNoThrow(
           AppOpsManager.OPSTR_GET_USAGE_STATS,
           android.os.Process.myUid(),
           context.getPackageName());
   return mode == AppOpsManager.MODE_ALLOWED;
 }
 private final void grantUriLocked(Uri uri, String pkg) {
   long ident = Binder.clearCallingIdentity();
   try {
     mAm.grantUriPermissionFromOwner(
         mPermissionOwner, Process.myUid(), pkg, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
   } catch (RemoteException e) {
   } finally {
     Binder.restoreCallingIdentity(ident);
   }
 }
  private String executeScript(String name) {
    File scriptFile = writeAssetToCacheFile(name);
    if (scriptFile == null) return "Could not find asset \"" + name + "\"";

    File busybox = writeAssetToCacheFile("busybox-xposed");
    if (busybox == null) {
      scriptFile.delete();
      return "Could not find asset \"busybox-xposed\"";
    }

    scriptFile.setReadable(true, false);
    scriptFile.setExecutable(true, false);

    busybox.setReadable(true, false);
    busybox.setExecutable(true, false);

    try {
      Process p =
          Runtime.getRuntime()
              .exec(
                  new String[] {
                    "su",
                    "-c",
                    "cd "
                        + getActivity().getCacheDir()
                        + "; "
                        + scriptFile.getAbsolutePath()
                        + " "
                        + android.os.Process.myUid()
                        + " 2>&1"
                  });
      BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = stdout.readLine()) != null) {
        sb.append(line);
        sb.append('\n');
      }
      while ((line = stderr.readLine()) != null) {
        sb.append(line);
        sb.append('\n');
      }
      stdout.close();
      return sb.toString();

    } catch (IOException e) {
      StringWriter sw = new StringWriter();
      e.printStackTrace(new PrintWriter(sw));
      return sw.toString();
    } finally {
      scriptFile.delete();
      busybox.delete();
    }
  }
  /** Clean up orphan downloads, both in database and on disk. */
  public void cleanOrphans() {
    final ContentResolver resolver = getContentResolver();

    // Collect known files from database
    final HashSet<ConcreteFile> fromDb = Sets.newHashSet();
    final Cursor cursor =
        resolver.query(
            Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, OrphanQuery.PROJECTION, null, null, null);
    try {
      while (cursor.moveToNext()) {
        final String path = cursor.getString(OrphanQuery._DATA);
        if (TextUtils.isEmpty(path)) continue;

        final File file = new File(path);
        try {
          fromDb.add(new ConcreteFile(file));
        } catch (ErrnoException e) {
          // File probably no longer exists
          final String state = Environment.getExternalStorageState(file);
          if (Environment.MEDIA_UNKNOWN.equals(state) || Environment.MEDIA_MOUNTED.equals(state)) {
            // File appears to live on internal storage, or a
            // currently mounted device, so remove it from database.
            // This logic preserves files on external storage while
            // media is removed.
            final long id = cursor.getLong(OrphanQuery._ID);
            Slog.d(TAG, "Missing " + file + ", deleting " + id);
            resolver.delete(
                ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id),
                null,
                null);
          }
        }
      }
    } finally {
      IoUtils.closeQuietly(cursor);
    }

    // Collect known files from disk
    final int uid = android.os.Process.myUid();
    final ArrayList<ConcreteFile> fromDisk = Lists.newArrayList();
    fromDisk.addAll(listFilesRecursive(getCacheDir(), null, uid));
    fromDisk.addAll(listFilesRecursive(getFilesDir(), null, uid));
    fromDisk.addAll(listFilesRecursive(Environment.getDownloadCacheDirectory(), null, uid));

    Slog.d(TAG, "Found " + fromDb.size() + " files in database");
    Slog.d(TAG, "Found " + fromDisk.size() + " files on disk");

    // Delete files no longer referenced by database
    for (ConcreteFile file : fromDisk) {
      if (!fromDb.contains(file)) {
        Slog.d(TAG, "Missing db entry, deleting " + file.file);
        file.file.delete();
      }
    }
  }
예제 #11
0
 /** See {@link android.webkit.WebSettings#setBlockNetworkLoads}. */
 public void setBlockNetworkLoads(boolean flag) {
   synchronized (mXWalkSettingsLock) {
     if (!flag
         && mContext.checkPermission(
                 android.Manifest.permission.INTERNET, Process.myPid(), Process.myUid())
             != PackageManager.PERMISSION_GRANTED) {
       throw new SecurityException(
           "Permission denied - " + "application missing INTERNET permission");
     }
     mBlockNetworkLoads = flag;
   }
 }
예제 #12
0
 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 private static boolean weOwnFileLollipop(Uri uri) {
   try {
     File file = new File(uri.getPath());
     FileDescriptor fd =
         ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
     StructStat st = Os.fstat(fd);
     return st.st_uid == android.os.Process.myUid();
   } catch (FileNotFoundException e) {
     return false;
   } catch (Exception e) {
     return true;
   }
 }
예제 #13
0
 /** Generates a device- and invocation-specific seed to be mixed into the Linux PRNG. */
 private static byte[] generateSeed() {
   try {
     ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
     DataOutputStream seedBufferOut = new DataOutputStream(seedBuffer);
     seedBufferOut.writeLong(System.currentTimeMillis());
     seedBufferOut.writeLong(System.nanoTime());
     seedBufferOut.writeInt(Process.myPid());
     seedBufferOut.writeInt(Process.myUid());
     seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
     seedBufferOut.close();
     return seedBuffer.toByteArray();
   } catch (IOException e) {
     throw new SecurityException("Failed to generate seed", e);
   }
 }
예제 #14
0
 private static ActivityManager.ProcessErrorStateInfo kC()
 {
   Object localObject = ((ActivityManager)y.getContext().getSystemService("activity")).getProcessesInErrorState();
   if (localObject == null) {
     return null;
   }
   localObject = ((List)localObject).iterator();
   while (((Iterator)localObject).hasNext())
   {
     ActivityManager.ProcessErrorStateInfo localProcessErrorStateInfo = (ActivityManager.ProcessErrorStateInfo)((Iterator)localObject).next();
     if ((uid == Process.myUid()) && (condition == 2)) {
       return localProcessErrorStateInfo;
     }
   }
   return null;
 }
예제 #15
0
  public XWalkSettings(
      Context context, long nativeWebContents, boolean isAccessFromFileURLsGrantedByDefault) {
    ThreadUtils.assertOnUiThread();
    mContext = context;
    mBlockNetworkLoads =
        mContext.checkPermission(
                android.Manifest.permission.INTERNET, Process.myPid(), Process.myUid())
            != PackageManager.PERMISSION_GRANTED;

    if (isAccessFromFileURLsGrantedByDefault) {
      mAllowUniversalAccessFromFileURLs = true;
      mAllowFileAccessFromFileURLs = true;
    }

    mUserAgent = LazyDefaultUserAgent.sInstance;

    mEventHandler = new EventHandler();

    setWebContents(nativeWebContents);
  }
예제 #16
0
  @Override
  protected void before(MethodHookParam param) throws Throwable {
    if (mMethod == Methods.exec) {
      // Get programs
      String[] progs = null;
      if (param.args.length > 0 && param.args[0] != null)
        if (String.class.isAssignableFrom(param.args[0].getClass()))
          progs = new String[] {(String) param.args[0]};
        else progs = (String[]) param.args[0];

      // Check programs
      if (progs != null) {
        String command = TextUtils.join(" ", progs);
        if ((mCommand == null && !command.contains("sh ") && !command.contains("su "))
            || (mCommand != null && command.contains(mCommand + " ")))
          if (isRestricted(param, mCommand == null ? getMethodName() : mCommand))
            param.setThrowable(new IOException());
      }
    } else if (mMethod == Methods.load || mMethod == Methods.loadLibrary) {
      // Skip pre Android
      if (Process.myUid() != 0)
        if (isRestricted(param)) param.setResult(new UnsatisfiedLinkError());
    } else Util.log(this, Log.WARN, "Unknown method=" + param.method.getName());
  }
예제 #17
0
  public RState(int uid, String restrictionName, String methodName, Version version) {
    mUid = uid;
    mRestrictionName = restrictionName;
    mMethodName = methodName;

    int userId = Util.getUserId(Process.myUid());

    // Get if on demand
    boolean onDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemand, true);
    if (onDemand)
      onDemand = PrivacyManager.getSettingBool(-uid, PrivacyManager.cSettingOnDemand, false);

    boolean allRestricted = true;
    boolean someRestricted = false;
    boolean allAsk = true;
    boolean someAsk = false;

    if (methodName == null) {
      if (restrictionName == null) {
        // Examine the category state
        someAsk = onDemand;
        for (String rRestrictionName : PrivacyManager.getRestrictions()) {
          PRestriction query = PrivacyManager.getRestrictionEx(uid, rRestrictionName, null);
          allRestricted = (allRestricted && query.restricted);
          someRestricted = (someRestricted || query.restricted);
          allAsk = (allAsk && !query.asked);
          someAsk = (someAsk || !query.asked);
        }
        asked = !onDemand;
      } else {
        // Examine the category/method states
        PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, null);
        someRestricted = query.restricted;
        someAsk = !query.asked;
        for (PRestriction restriction : PrivacyManager.getRestrictionList(uid, restrictionName)) {
          Hook hook = PrivacyManager.getHook(restrictionName, restriction.methodName);
          if (version != null
              && hook != null
              && hook.getFrom() != null
              && version.compareTo(hook.getFrom()) < 0) continue;

          allRestricted = (allRestricted && restriction.restricted);
          someRestricted = (someRestricted || restriction.restricted);
          if (hook == null || hook.canOnDemand()) {
            allAsk = (allAsk && !restriction.asked);
            someAsk = (someAsk || !restriction.asked);
          }
        }
        asked = query.asked;
      }
    } else {
      // Examine the method state
      PRestriction query = PrivacyManager.getRestrictionEx(uid, restrictionName, methodName);
      allRestricted = query.restricted;
      someRestricted = false;
      asked = query.asked;
    }

    boolean isApp = PrivacyManager.isApplication(uid);
    boolean odSystem =
        PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingOnDemandSystem, false);

    restricted = (allRestricted || someRestricted);
    asked = (!onDemand || !(isApp || odSystem) || asked);
    partialRestricted = (!allRestricted && someRestricted);
    partialAsk = (onDemand && (isApp || odSystem) && !allAsk && someAsk);
  }
 public static boolean havePermission(Context c) {
   return c.checkPermission(PERMISSION_RUN_TASKS, Process.myPid(), Process.myUid())
       == PackageManager.PERMISSION_GRANTED;
 }
예제 #19
0
 /**
  * @return Number of bytes received since device boot that were attributed to caller's UID. Counts
  *     packets across all network interfaces, and always increases monotonically since device
  *     boot. Statistics are measured at the network layer, so they include both TCP and UDP usage.
  */
 @CalledByNative
 private static long getCurrentUidRxBytes() {
   long bytes = TrafficStats.getUidRxBytes(Process.myUid());
   return bytes != TrafficStats.UNSUPPORTED ? bytes : TrafficStatsError.ERROR_NOT_SUPPORTED;
 }
예제 #20
0
파일: Util.java 프로젝트: paour/XPrivacy
 public static void bug(XHook hook, Throwable ex) {
   log(
       hook,
       ex instanceof OutOfMemoryError ? Log.WARN : Log.ERROR,
       ex.toString() + " uid=" + Process.myUid() + "\n" + Log.getStackTraceString(ex));
 }
예제 #21
0
  void downloadFile() {

    try {
      per = 0;

      URL url = new URL(dwnload_file_path);
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);

      // connect
      urlConnection.connect();

      FileOutputStream fileOutput = new FileOutputStream(file);

      // Stream used for reading the data from the internet
      inputStream = urlConnection.getInputStream();

      // this is the total size of the file which we are downloading
      totalSize = urlConnection.getContentLength();

      getActivity()
          .runOnUiThread(
              new Runnable() {
                public void run() {

                  pb.setMax(totalSize);
                }
              });

      // create a buffer...
      byte[] buffer = new byte[1024];
      int bufferLength = 0;

      while ((bufferLength = inputStream.read(buffer)) > 0) {
        fileOutput.write(buffer, 0, bufferLength);

        downloadedSize += bufferLength;
        // update the progressbar //
        getActivity()
            .runOnUiThread(
                new Runnable() {
                  public void run() {
                    pb.setProgress(downloadedSize);
                    per = ((float) downloadedSize / totalSize) * 100;
                    cur_val.setText("Download   " + (int) per + "%");
                  }
                });
      }
      // close the output stream when complete //
      fileOutput.close();
      dialog.dismiss();
      android.os.Process.killProcess(android.os.Process.myUid());
      getActivity().finish();
      Intent activity = new Intent(getActivity(), SubMenu3Activity.class);
      startActivity(activity);

    } catch (final MalformedURLException e) {
      showError("Error : MalformedURLException " + e);
      e.printStackTrace();
      file.delete();
      downloadedSize = 0;
      dialog.dismiss();
    } catch (final IOException e) {
      showError("Error : IOException " + e);
      e.printStackTrace();
      downloadedSize = 0;
      file.delete();
      dialog.dismiss();
    } catch (final Exception e) {
      showError("Error : Please check your internet connection " + e);
      file.delete();
      downloadedSize = 0;
      dialog.dismiss();
    }
  }
 @Override
 public DisplayInfo getDisplayInfo(int displayId) {
   return getDisplayInfoInternal(displayId, Process.myUid());
 }
예제 #23
0
  protected void doDownloadAndUpload() {
    context.print("doDownloadAndUpload()...");
    Message msg = new Message();
    Bundle bndle = new Bundle();

    String sResponseCode = "", sResponseDesc = "";
    try {

      ftp = new FTP(handler);
      if (ftp.ftpConnect(sHostURL, sUsername, sPassword, port)) {

        timer = new Timer();
        uid = android.os.Process.myUid();
        if (Constants.OS_VERSION_JELLY_BEAN_MR2 <= deviceOSVersion) {
          StartRXBytes = DeviceUtil.getStats(uid).getReceiveCount();
          // StartRXBytes = TrafficStats.getUidRxBytes(uid);
          StartRXSegments = TrafficStats.getUidTcpRxSegments(uid);
        } else {
          StartRXBytes = TrafficStats.getUidTcpRxBytes(uid);
          StartRXSegments = TrafficStats.getUidTcpRxSegments(uid);
        }
        context.debug(
            "Initial RX bytes - " + StartRXBytes + ", Initial RX Segments - " + StartRXSegments);
        downloadTimerTask = new DownloadTimeTask();
        timer.schedule(downloadTimerTask, 0, Constants.FTP_LOG_INTERVAL * 1000);

        // Download

        if (ftp.ftpDownload(sDownloadSrcFilePath, sDownloadDestFilePath)) {
          context.print("File downloaded");
          sResponseCode = ResponseCodes.SUCCESS;
          timer.cancel();

          try {

            timer = new Timer();
            /*
            Constants.OS_VERSION_JELLY_BEAN_MR2 == deviceOSVersion
            		|| Constants.OS_VERSION_KIT_KAT == deviceOSVersion || Constants.OS_VERSION_LOLLIPOP == deviceOSVersion
            		|| Constants.OS_VERSION_LOLLIPOP_MR2 == deviceOSVersion || Constants.OS_VERSION_MARSHMALLOW == deviceOSVersion*/

            if (Constants.OS_VERSION_JELLY_BEAN_MR2 <= deviceOSVersion) {
              StartTXBytes = TrafficStats.getUidTxBytes(uid);
              StartTXSegments = TrafficStats.getUidTcpTxSegments(uid);
            } else {
              StartTXBytes = TrafficStats.getUidTcpTxBytes(uid);
              StartTXSegments = TrafficStats.getUidTcpTxSegments(uid);
            }

            context.debug(
                "Initial TX bytes - "
                    + StartTXBytes
                    + ", Initial TX segments - "
                    + StartTXSegments);
            uploadTimerTask = new UploadTimeTask();
            timer.schedule(uploadTimerTask, 0, Constants.FTP_LOG_INTERVAL * 1000);

            L.debug("Upload Section- src file path: " + sUploadSrcFilePath);
            L.debug("Upload Section- dest file path: " + sUploadDestDirPath);

            // Upload

            if (ftp.ftpUpload(
                sUploadSrcFilePath, new File(sUploadSrcFilePath).getName(), sUploadDestDirPath)) {
              context.print("File uploaded");
              sResponseCode = ResponseCodes.SUCCESS;
              L.debug("********* FTP UPLOADING SUCCESS **********");
            } else {
              context.print("File upload failed - " + ftp.getServerError());
              sResponseCode = StringUtils.ERROR_CODE;
              sResponseDesc = Messages.FTP_UPLOAD_FAILED + "(" + ftp.getServerError() + ")";
            }
          } catch (Exception e) {
            e.printStackTrace();
            sResponseCode = StringUtils.ERROR_CODE;
            sResponseDesc = Messages.FTP_UPLOAD_FAILED + "(" + Messages.err(e) + ")";
          }

        } else {
          context.print("File download failed - " + ftp.getServerError());
          sResponseCode = StringUtils.ERROR_CODE;
          sResponseDesc = Messages.FTP_DOWNLOAD_FAILED;
        }
        timer.cancel();
      } else {
        sResponseCode = StringUtils.ERROR_CODE;
        sResponseDesc = Messages.FTP_LOGIN_FAILED;
      }
      try {
        if (ftp.getClient().isConnected()) ftp.ftpDisconnect();
      } catch (Exception e) {

      }
    } catch (Exception e) {
      e.printStackTrace();
      sResponseCode = StringUtils.ERROR_CODE;
      sResponseDesc = Messages.err(e);
    }

    bndle.putString(StringUtils.CODE, sResponseCode);
    bndle.putString(StringUtils.DESC, sResponseDesc);
    msg.setData(bndle);
    if (!pref.isTestCanceled() && pref.isTestRunning()) DownloadAndUploadHandler.sendMessage(msg);
  }
예제 #24
0
 private void enforcePermission() throws SecurityException {
   if (Binder.getCallingUid() != Process.myUid()) throw new SecurityException();
 }
예제 #25
0
/** Tests for ClientManager. */
public class ClientManagerTest extends InstrumentationTestCase {
  private static final String URL = "https://www.android.com";
  private ClientManager mClientManager;
  private ICustomTabsCallback mCallback = new CustomTabsTestUtils.DummyCallback();
  private IBinder mSession = mCallback.asBinder();
  private int mUid = Process.myUid();

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    Context context = getInstrumentation().getTargetContext().getApplicationContext();
    mClientManager = new ClientManager(context);
  }

  @SmallTest
  public void testNoSessionNoWarmup() {
    assertEquals(ClientManager.NO_SESSION_NO_WARMUP, mClientManager.getWarmupState(null));
  }

  @SmallTest
  public void testNoSessionWarmup() {
    mClientManager.recordUidHasCalledWarmup(mUid);
    assertEquals(ClientManager.NO_SESSION_WARMUP, mClientManager.getWarmupState(null));
  }

  @SmallTest
  public void testInvalidSessionNoWarmup() {
    assertEquals(ClientManager.NO_SESSION_NO_WARMUP, mClientManager.getWarmupState(mSession));
  }

  @SmallTest
  public void testInvalidSessionWarmup() {
    mClientManager.recordUidHasCalledWarmup(mUid);
    assertEquals(ClientManager.NO_SESSION_WARMUP, mClientManager.getWarmupState(mSession));
  }

  @SmallTest
  public void testValidSessionNoWarmup() {
    mClientManager.newSession(mCallback, mUid, null);
    assertEquals(
        ClientManager.SESSION_NO_WARMUP_NOT_CALLED, mClientManager.getWarmupState(mSession));
  }

  @SmallTest
  public void testValidSessionOtherWarmup() {
    mClientManager.recordUidHasCalledWarmup(mUid + 1);
    mClientManager.newSession(mCallback, mUid, null);
    assertEquals(
        ClientManager.SESSION_NO_WARMUP_ALREADY_CALLED, mClientManager.getWarmupState(mSession));
  }

  @SmallTest
  public void testValidSessionWarmup() {
    mClientManager.recordUidHasCalledWarmup(mUid);
    mClientManager.newSession(mCallback, mUid, null);
    assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));
  }

  @SmallTest
  public void testValidSessionWarmupSeveralCalls() {
    mClientManager.recordUidHasCalledWarmup(mUid);
    mClientManager.newSession(mCallback, mUid, null);
    assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));

    ICustomTabsCallback callback = new CustomTabsTestUtils.DummyCallback();
    IBinder session = callback.asBinder();
    mClientManager.newSession(callback, mUid, null);
    assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(session));
  }
}