@NotNull
  @Override
  public CommandStatus execute(
      @NotNull CouchbaseMock mock, @NotNull Command command, @NotNull JsonObject payload) {
    super.execute(mock, command, payload);
    try {
      executeReal(payload, command);
    } catch (AccessControlException e) {
      error = e.getMessage();
    }

    return getResponse();
  }
Esempio n. 2
0
    void init_midi(LContext lcontext) {
	if (!midiSynthInitialized) {
	    midiSynthInitialized = true;
	    try {
		midiSynth = MidiSystem.getSynthesizer();
		midiSynth.open();
		if (midiSynth.getDefaultSoundbank() == null) {
		    ((LContext) lcontext).canvas.setMessage
			("Reading sound bank from server. Please wait...");
		    if (lcontext != null) {
			/* empty */
		    }
		    URL url = new URL(((LContext) lcontext).codeBase
				      + "soundbank.gm");
		    Soundbank soundbank = MidiSystem.getSoundbank(url);
		    if (soundbank != null) {
			midiSynth.loadAllInstruments(soundbank);
			((LContext) lcontext).canvas.setMessage("");
		    } else {
			midiSynth.close();
			midiSynth = null;
		    }
		}
	    } catch (MidiUnavailableException midiunavailableexception) {
		midiunavailableexception.printStackTrace();
		midiSynth = null;
	    } catch (MalformedURLException malformedurlexception) {
		malformedurlexception.printStackTrace();
		midiSynth = null;
	    } catch (InvalidMidiDataException invalidmididataexception) {
		invalidmididataexception.printStackTrace();
		midiSynth = null;
	    } catch (IOException ioexception) {
		ioexception.printStackTrace();
		midiSynth = null;
	    } catch (AccessControlException accesscontrolexception) {
		accesscontrolexception.printStackTrace();
		midiSynth = null;
	    }
	    if (midiSynth != null) {
		MidiChannel[] midichannels = midiSynth.getChannels();
		for (int i = 0; i < midichannels.length; i++) {
		    if (midichannels[i] != null)
			midichannels[i].programChange(0);
		}
	    } else
		((LContext) lcontext).canvas.setMessage
		    ("No soundbank; note & drum commands disabled.");
	}
    }
Esempio n. 3
0
 /**
  * This kludge is specific to get over AccessControlException thrown during Applet.stop() or
  * destroy() when static thread is suspended. Set a flag in AppletClassLoader to indicate that an
  * AccessControlException for RuntimePermission "modifyThread" or "modifyThreadGroup" had
  * occurred.
  */
 private void setExceptionStatus(AccessControlException e) {
   Permission p = e.getPermission();
   if (p instanceof RuntimePermission) {
     if (p.getName().startsWith("modifyThread")) {
       if (loader == null) loader = getClassLoader(getCodeBase(), getClassLoaderCacheKey());
       loader.setExceptionStatus();
     }
   }
 }
  @Override
  public Thread newThread(final Runnable command) {
    final Thread t;
    // attach the thread to a group only if there is no security manager:
    // when sandboxed, the code does not have the RuntimePermission modifyThreadGroup
    if (System.getSecurityManager() == null) {
      t =
          new Thread(
              group,
              command,
              "Thread-" + threadCount.getAndIncrement() + " (" + group.getName() + ")");
    } else {
      t = new Thread(command, "Thread-" + threadCount.getAndIncrement());
    }

    AccessController.doPrivileged(
        new PrivilegedAction<Object>() {
          @Override
          public Object run() {
            t.setDaemon(daemon);
            t.setPriority(threadPriority);
            return null;
          }
        });

    try {
      AccessController.doPrivileged(
          new PrivilegedAction<Object>() {
            @Override
            public Object run() {
              t.setContextClassLoader(tccl);
              return null;
            }
          });
    } catch (java.security.AccessControlException e) {
      e.printStackTrace();
    }

    return t;
  }
Esempio n. 5
0
  @Test
  public void mustChangePassword() {
    // PRE: reset vivaldi's password
    UserPatch userPatch = new UserPatch();
    userPatch.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee");
    userPatch.setPassword(new PasswordPatch.Builder().value("password321").build());
    userService.update(userPatch);

    // 0. access as vivaldi -> succeed
    SyncopeClient vivaldiClient = clientFactory.create("vivaldi", "password321");
    Pair<Map<String, Set<String>>, UserTO> self = vivaldiClient.self();
    assertFalse(self.getRight().isMustChangePassword());

    // 1. update user vivaldi (3) requirig password update
    userPatch = new UserPatch();
    userPatch.setKey("b3cbc78d-32e6-4bd4-92e0-bbe07566a2ee");
    userPatch.setMustChangePassword(new BooleanReplacePatchItem.Builder().value(true).build());
    UserTO vivaldi = updateUser(userPatch).getEntity();
    assertTrue(vivaldi.isMustChangePassword());

    // 2. attempt to access -> fail
    try {
      vivaldiClient.getService(ResourceService.class).list();
      fail();
    } catch (AccessControlException e) {
      assertNotNull(e);
      assertEquals("Please change your password first", e.getMessage());
    }

    // 3. change password
    vivaldiClient.getService(UserSelfService.class).changePassword("password123");

    // 4. verify it worked
    self = clientFactory.create("vivaldi", "password123").self();
    assertFalse(self.getRight().isMustChangePassword());
  }
  /**
   * Wait until a proper shutdown command is received, then return. This keeps the main thread alive
   * - the thread pool listening for http connections is daemon threads.
   *
   * <p>NOTE: This method has been copied and modified slightly from
   * org.apache.catalina.core.StandardServer.await() We should have just called
   * container.getServer().await() but it returns null for getServer() and i do not know why :)
   */
  public void await() {
    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port, 1, InetAddress.getByName(address));
    } catch (IOException e) {
      System.out.println(
          "TomcatManager.await: create[" + address + ":" + port + "]: " + e.getMessage());
      System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

      // Wait for the next connection
      Socket socket = null;
      InputStream stream = null;
      try {
        socket = serverSocket.accept();
        socket.setSoTimeout(10 * 1000); // Ten seconds
        stream = socket.getInputStream();
      } catch (AccessControlException ace) {
        System.out.println("TomcatManager.accept security exception: " + ace.getMessage());
        continue;
      } catch (IOException e) {
        System.out.println("TomcatManager.await: accept: " + e.getMessage());
        System.exit(1);
      }

      // Read a set of characters from the socket
      StringBuilder command = new StringBuilder();
      int expected = 1024; // Cut off to avoid DoS attack
      while (expected < shutdown.length()) {
        if (random == null) {
          random = new Random();
        }
        expected += (random.nextInt() % 1024);
      }
      while (expected > 0) {
        int ch = -1;
        try {
          ch = stream.read();
        } catch (IOException e) {
          System.out.println("TomcatManager.await: read: " + e.getMessage());
          ch = -1;
        }
        if (ch < 32) { // Control character or EOF terminates loop
          break;
        }
        command.append((char) ch);
        expected--;
      }

      // Close the socket now that we are done with it
      try {
        socket.close();
      } catch (IOException e) {
        // Ignore
      }

      // Match against our command string
      boolean match = command.toString().equals(shutdown);
      if (match) {
        System.out.println("TomcatManager.shutdownViaPort");
        break;
      } else {
        System.out.println(
            "TomcatManager.await: Invalid command '" + command.toString() + "' received");
      }
    }

    // Close the server socket and return
    try {
      serverSocket.close();
    } catch (IOException e) {
      // Ignore
    }
  }
 @Override
 public void handle(
     Session aSession,
     Consumer<ServerModuleStructureRequest.Response> onSuccess,
     Consumer<Exception> onFailure) {
   String moduleName = getRequest().getModuleName();
   if (moduleName == null || moduleName.isEmpty()) {
     onFailure.accept(
         new Exception("Module name is missing. Unnamed server modules are not allowed."));
   } else {
     Date clientModuleTime = getRequest().getTimeStamp();
     try {
       AppElementFiles files = serverCore.getIndexer().nameToFiles(moduleName);
       if (files != null && files.isModule()) {
         ServerModuleStructureRequest.Response response =
             new ServerModuleStructureRequest.Response(null);
         Date serverModuleTime = files.getLastModified();
         if (clientModuleTime == null || serverModuleTime.after(clientModuleTime)) {
           ScriptDocument config = serverCore.getScriptsConfigs().get(moduleName, files);
           checkPrincipalPermission(config.getModuleAllowedRoles(), moduleName);
           StringBuilder json =
               JSONUtils.o(
                   RemoteServerModulesProxy.CREATE_MODULE_RESPONSE_FUNCTIONS_PROP,
                       JSONUtils.as(config.getFunctionProperties().toArray(new String[] {}))
                           .toString(),
                   RemoteServerModulesProxy.CREATE_MODULE_RESPONSE_IS_PERMITTED_PROP,
                       String.valueOf(true));
           response.setInfoJson(json.toString());
           response.setTimeStamp(serverModuleTime);
         }
         onSuccess.accept(response);
       } else {
         onFailure.accept(
             new IllegalArgumentException(
                 String.format("No module: %s, or it is not a module", moduleName)));
       }
     } catch (AccessControlException ex) {
       if (ex.getPermission() instanceof AuthPermission) {
         onFailure.accept(ex);
       } else {
         StringBuilder json =
             JSONUtils.o(
                 RemoteServerModulesProxy.CREATE_MODULE_RESPONSE_FUNCTIONS_PROP,
                     JSONUtils.a(Collections.emptySet().toArray(new String[] {})).toString(),
                 RemoteServerModulesProxy.CREATE_MODULE_RESPONSE_IS_PERMITTED_PROP,
                     String.valueOf(false));
         ServerModuleStructureRequest.Response response =
             new ServerModuleStructureRequest.Response(json.toString());
         if (clientModuleTime == null) {
           // If a client has no the resource, let's give it a chance to update the resource, when
           // it will be permitted
           response.setTimeStamp(new Date(0));
         } else {
           // Let's override client's resource timestamp to guarantee, that permitted == false will
           // be accepted
           response.setTimeStamp(new Date(clientModuleTime.getTime() + 1000));
         }
         onSuccess.accept(response);
       }
     } catch (Exception ex) {
       onFailure.accept(ex);
     }
   }
 }
  /**
   * Read configuration for the specified classloader.
   *
   * @param classLoader
   * @throws IOException Error
   */
  protected void readConfiguration(ClassLoader classLoader) throws IOException {

    InputStream is = null;
    // Special case for URL classloaders which are used in containers:
    // only look in the local repositories to avoid redefining loggers 20 times
    try {
      if (classLoader instanceof URLClassLoader) {
        URL logConfig = ((URLClassLoader) classLoader).findResource("logging.properties");

        if (null != logConfig) {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName()
                    + ".readConfiguration(): "
                    + "Found logging.properties at "
                    + logConfig);

          is = classLoader.getResourceAsStream("logging.properties");
        } else {
          if (Boolean.getBoolean(DEBUG_PROPERTY))
            System.err.println(
                getClass().getName() + ".readConfiguration(): " + "Found no logging.properties");
        }
      }
    } catch (AccessControlException ace) {
      // No permission to configure logging in context
      // Log and carry on
      ClassLoaderLogManagerClassLoaderLogInfo info =
          classLoaderLoggers.get(ClassLoader.getSystemClassLoader());
      if (info != null) {
        Logger log = info.getLoggers().get("");
        if (log != null) {
          Permission perm = ace.getPermission();
          if (perm instanceof FilePermission && perm.getActions().equals("read")) {
            log.warning(
                "Reading "
                    + perm.getName()
                    + " is not permitted. See \"per context logging\" in the default catalina.policy file.");
          } else {
            log.warning(
                "Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file.");
            log.warning("Original error was: " + ace.getMessage());
          }
        }
      }
    }
    if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) {
      String configFileStr = System.getProperty("java.util.logging.config.file");
      if (configFileStr != null) {
        try {
          is = new FileInputStream(replace(configFileStr));
        } catch (IOException e) {
          // Ignore
        }
      }
      // Try the default JVM configuration
      if (is == null) {
        File defaultFile =
            new File(new File(System.getProperty("java.home"), "lib"), "logging.properties");
        try {
          is = new FileInputStream(defaultFile);
        } catch (IOException e) {
          // Critical problem, do something ...
        }
      }
    }

    Logger localClassLoaderLogManagerRootLogger = new ClassLoaderLogManagerRootLogger();
    if (is == null) {
      // Retrieve the root logger of the parent classloader instead
      ClassLoader current = classLoader.getParent();
      ClassLoaderLogManagerClassLoaderLogInfo info = null;
      while (current != null && info == null) {
        info = getClassLoaderInfo(current);
        current = current.getParent();
      }
      if (info != null) {
        localClassLoaderLogManagerRootLogger.setParent(info.getRootNode().getLogger());
      }
    }
    ClassLoaderLogManagerClassLoaderLogInfo info =
        new ClassLoaderLogManagerClassLoaderLogInfo(
            new ClassLoaderLogManagerLogNode(null, localClassLoaderLogManagerRootLogger));
    classLoaderLoggers.put(classLoader, info);

    if (is != null) {
      readConfiguration(is, classLoader);
    }
    addLogger(localClassLoaderLogManagerRootLogger);
  }
Esempio n. 9
0
  /**
   * Wait until a proper shutdown command is received, then return. This keeps the main thread alive
   * - the thread pool listening for http connections is daemon threads.
   */
  public void await() {
    // Negative values - don't wait on port - tomcat is embedded or we just don't like ports
    if (port == -2) {
      // undocumented yet - for embedding apps that are around, alive.
      return;
    }
    if (port == -1) {
      while (true) {
        try {
          Thread.sleep(10000);
        } catch (InterruptedException ex) {
        }
        if (stopAwait) return;
      }
    }

    // Set up a server socket to wait on
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(port, 1, InetAddress.getByName("localhost"));
    } catch (IOException e) {
      log.error("StandardServer.await: create[" + port + "]: ", e);
      System.exit(1);
    }

    // Loop waiting for a connection and a valid command
    while (true) {

      // Wait for the next connection
      Socket socket = null;
      InputStream stream = null;
      try {
        socket = serverSocket.accept();
        socket.setSoTimeout(10 * 1000); // Ten seconds
        stream = socket.getInputStream();
      } catch (AccessControlException ace) {
        log.warn("StandardServer.accept security exception: " + ace.getMessage(), ace);
        continue;
      } catch (IOException e) {
        log.error("StandardServer.await: accept: ", e);
        System.exit(1);
      }

      // Read a set of characters from the socket
      StringBuffer command = new StringBuffer();
      int expected = 1024; // Cut off to avoid DoS attack
      while (expected < shutdown.length()) {
        if (random == null) random = new Random();
        expected += (random.nextInt() % 1024);
      }
      while (expected > 0) {
        int ch = -1;
        try {
          ch = stream.read();
        } catch (IOException e) {
          log.warn("StandardServer.await: read: ", e);
          ch = -1;
        }
        if (ch < 32) // Control character or EOF terminates loop
        break;
        command.append((char) ch);
        expected--;
      }

      // Close the socket now that we are done with it
      try {
        socket.close();
      } catch (IOException e) {;
      }

      // Match against our command string
      boolean match = command.toString().equals(shutdown);
      if (match) {
        break;
      } else
        log.warn("StandardServer.await: Invalid command '" + command.toString() + "' received");
    }

    // Close the server socket and return
    try {
      serverSocket.close();
    } catch (IOException e) {;
    }
  }
Esempio n. 10
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  public void run() {
    init();
    this.state = 3;
    this.percentage = 5;
    try {
      loadJarURLs();
      String path =
          (String)
              AccessController.doPrivileged(
                  new PrivilegedExceptionAction() {
                    public Object run() throws Exception {
                      return Util.getWorkingDirectory() + File.separator + "bin" + File.separator;
                    }
                  });
      File dir = new File(path);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      if (this.latestVersion != null) {
        File versionFile = new File(dir, "version");
        boolean cacheAvailable = false;
        if ((versionFile.exists())
            && ((this.latestVersion.equals("-1"))
                || (this.latestVersion.equals(readVersionFile(versionFile))))) {
          cacheAvailable = true;
          this.percentage = 90;
        }
        boolean updateLauncher = false;
        if (this.forceUpdate == 1) {
          updateLauncher = true;
        }
        try {
          String versionLauncher = "";
          URL url_version = new URL(versionFileTxt);
          try {
            BufferedReader in = new BufferedReader(new InputStreamReader(url_version.openStream()));
            versionLauncher = in.readLine();
          } catch (Exception e) {
            System.err.println(e);
          }
          File current_versionLauncher = new File(dir, "vose.txt");
          if (!current_versionLauncher.exists()) {
            updateLauncher = true;
            try {
              BufferedWriter bw = new BufferedWriter(new FileWriter(current_versionLauncher));
              bw.append(versionLauncher);
              bw.close();
            } catch (IOException e) {
              System.out.println("Erreur");
            }
          } else {
            try {
              Scanner scanner = new Scanner(current_versionLauncher);
              while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!versionLauncher.equals(line)) {
                  updateLauncher = true;
                  try {
                    BufferedWriter bw = new BufferedWriter(new FileWriter(current_versionLauncher));
                    bw.append(versionLauncher);
                    bw.close();
                  } catch (IOException e) {
                    System.out.println("Erreur");
                  }
                }
              }

              scanner.close();
            } catch (IOException e) {
              System.out.println("Erreur" + e.getMessage());
            }
          }
        } catch (Exception localException1) {
        }
        if ((!cacheAvailable) || (updateLauncher)) {
          downloadJars(path);
          extractJars(path);
          extractNatives(path);
          if (this.latestVersion != null) {
            this.percentage = 90;
            writeVersionFile(versionFile, this.latestVersion);
          }
        }
      }
      updateClassPath(dir);
      this.state = 10;
    } catch (AccessControlException ace) {
      fatalErrorOccured(ace.getMessage(), ace);
      this.certificateRefused = true;
    } catch (Exception e) {
      fatalErrorOccured(e.getMessage(), e);
    } finally {
      this.loaderThread = null;
    }
  }
Esempio n. 11
0
  public static void main(String args[]) {

    sameGroup = true;

    RMID rmid = null;

    System.err.println("\nRegression test for bug/rfe 4179055\n");

    try {
      TestLibrary.suggestSecurityManager("java.lang.SecurityManager");

      registry = java.rmi.registry.LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT);

      // must run with java.lang.SecurityManager or the test
      // result will be nullified if running with a build where
      // 4180392 has not been fixed.
      String smClassName = System.getSecurityManager().getClass().getName();
      if (!smClassName.equals("java.lang.SecurityManager")) {
        TestLibrary.bomb("Test must run with java.lang.SecurityManager");
      }

      // start an rmid.
      RMID.removeLog();
      rmid = RMID.createRMID();
      rmid.start();

      // rmid.addOptions(new String[] {"-C-Djava.rmi.server.logCalls=true"});

      // Ensure that activation groups run with the correct
      // security manager.
      //
      Properties p = new Properties();
      p.put("java.security.policy", TestParams.defaultGroupPolicy);
      p.put("java.security.manager", "java.lang.SecurityManager");

      // This action causes the following classes to be created
      // in this VM (RMI must permit the creation of these classes):
      //
      // sun.rmi.server.Activation$ActivationSystemImpl_Stub
      // sun.rmi.server.Activation$ActivationMonitorImpl_Stub
      //
      System.err.println("Create activation group, in a new VM");
      ActivationGroupDesc groupDesc = new ActivationGroupDesc(p, null);
      ActivationSystem system = ActivationGroup.getSystem();
      ActivationGroupID groupID = system.registerGroup(groupDesc);

      System.err.println("register activatable");
      // Fix for: 4271615: make sure activation group runs in a new VM
      ActivationDesc desc = new ActivationDesc(groupID, "StubClassesPermitted", null, null);
      canCreateStubs = (CanCreateStubs) Activatable.register(desc);

      // ensure registry stub can be passed in a remote call
      System.err.println("getting the registry");
      registry = canCreateStubs.getRegistry();

      // make sure a client cant load just any sun.* class, just
      // as a sanity check, try to create a class we are not
      // allowed to access but which was passed in a remote call
      try {
        System.err.println("accessing forbidden class");
        Object secureRandom = canCreateStubs.getForbiddenClass();

        TestLibrary.bomb(
            "test allowed to access forbidden class," + " sun.security.provider.SecureRandom");
      } catch (java.security.AccessControlException e) {

        // Make sure we received a *local* AccessControlException
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bout);
        e.printStackTrace(ps);
        ps.flush();
        String trace = new String(bout.toByteArray());
        if ((trace.indexOf("exceptionReceivedFromServer") >= 0) || trace.equals("")) {
          throw e;
        }
        System.err.println("received expected local access control exception");
      }

      // make sure that an ActivationGroupID can be passed in a
      // remote call; this is slightly more inclusive than
      // just passing a reference to the activation system
      System.err.println("returning group desc");
      canCreateStubs.returnGroupID();

      // Clean up object
      System.err.println("Deactivate object via method call");
      canCreateStubs.shutdown();

      System.err.println("\nsuccess: StubClassesPermitted test passed ");

    } catch (Exception e) {
      TestLibrary.bomb("\nfailure: unexpected exception ", e);
    } finally {
      try {
        Thread.sleep(4000);
      } catch (InterruptedException e) {
      }

      canCreateStubs = null;
      ActivationLibrary.rmidCleanup(rmid);
      System.err.println("rmid shut down");
    }
  }