Read and execute a command from the server socket

@throws IOException
3464
@FFDCIgnore({ IOException.class })
    private boolean acceptAndExecuteCommand() {
        boolean socketValid = false;
        try {
            //exceptions thrown by accept are assumed to mean the channel is no longer usable.
            SocketChannel sc = serverSocketChannel.accept();
            socketValid = true;
            if (sc != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "accepted socket", sc);
                }

                try {
                    String uuidAndCommand = read(sc);
                    ServerCommandID commandID = new ServerCommandID(uuidAndCommand);
                    String command = commandID.getOperation();

                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        // Don't trace uuidAndCommand to avoid putting it in logs
                        // (not as secure as the workarea).
                        Tr.debug(tc, "read UUID and command", command);
                    }

                    // As a first level of security, require that the user has read access to the .sCommand file.
                    if (!commandID.validate()) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "invalid UUID", uuidAndCommand);
                        }
                    } else {
                        // As a second level of security, ensure that the client has write access to the workarea. We do
                        // this because by default, many umasks create world-readable files, which means everyone on a
                        // system can read the .sCommand file.
                        //
                        // Generate a unique filename in .sCommandAuth and request that the client create the named file.
                        String authID;
                        File authFile;
                        do {
                            authID = Integer.toString(nextCommandAuthID++);
                            authFile = new File(commandAuthDir, authID);
                        } while (authFile.exists());

                        // The server is going to create the file (to ensure server ownership bits are preserved),
                        authFile.createNewFile();

                        // write the authId: the client will delete the file to prove write-access
                        write(sc, authID);

                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "wrote authorization challenge", authID, authFile);
                        }

                        // Read the response: the caller should have deleted the file.
                        String authIDResponse = read(sc);
                        if (!authIDResponse.equals(authID) || authFile.exists()) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "authorization failed");
                            }
                        } else {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "authorization succeeded");
                            }

                            sc = executeCommand(sc, command);
                        }
                    }
                } finally {
                    // Close the socket: one command per connection.
                    Utils.tryToClose(sc);
                }
            }
        } catch (IOException ex) {
            // FFDCIgnore of IOExceptions: some expected due to async close
        } catch (Throwable t) {
            // Don't allow an exception from a single command to
            // break the entire command listener.
        }
        return socketValid;
    }
1351757
private void init(String command, Socket socket) throws IOException {
        lock.lock();
        try {
            initTokens = new Hashtable<String, Integer>();

            DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
            dout.writeInt(BYTES_INT);
            dout.writeInt(1);
            dout.flush();
        } finally {
            lock.unlock();
        }
    }
1228251
def execute_command(self, *args, **options):
        ""
        pool = self.connection_pool
        command_name = args[0]
        connection = pool.get_connection(command_name, **options)
        try:
            connection.send_command(*args)
            return self.parse_response(connection, command_name, **options)
        except (ConnectionError, TimeoutError) as e:
            connection.disconnect()
            if not (connection.retry_on_timeout and
                    isinstance(e, TimeoutError)):
                raise
            connection.send_command(*args)
            return self.parse_response(connection, command_name, **options)
        finally:
            pool.release(connection)
28311
protected Pair<Integer, InputStream> executeCommand(String command) {
        int resultVal = 1;
        InputStream inputStream = null;
        try {
            logger.debug("Executing command: {}", command);
            Process process =  Runtime.getRuntime().exec(command);

            resultVal = process.waitFor();
            inputStream = process.getInputStream();

        } catch (InterruptedException e) {
            logger.info("Execution of {} failed: code - {} ; message - {}", command, resultVal, e.getMessage());
            Thread.currentThread().interrupt();
        } catch (IOException  e) {
            logger.info("Execution of {} failed: code - {} ; message - {}", command, resultVal, e.getMessage());
        }
        if (inputStream == null) {
           // Create an empty InputStream instead of returning a null
           inputStream = new InputStream() {
               @Override
               public int read() throws IOException {
                   return -1;
               }
           } ;
        }
        return new Pair<>(resultVal, inputStream);
    }
1334777
private void init(int port, File commandFileTmp) throws IOException {
        if (port != -1) {
            serverSocketChannel = SelectorProvider.provider().openServerSocketChannel();

            // Open the socket for loopback only..
            InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(null), port);

            IOException bindError = null;

            boolean isWindows = System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows");

            try {
                //Attempt bind with reuseAddress set to false.
                serverSocketChannel.socket().setReuseAddress(false);
                serverSocketChannel.socket().bind(address);

                //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                //for future binds.
                if (!isWindows) {
                    serverSocketChannel.socket().setReuseAddress(true);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                    }
                }
            } catch (IOException ioe) {
                // see if we got the error because port is in waiting to be cleaned up.
                // If so, no one should be accepting connections on it, and open should fail.
                // If that's the case, we can set ReuseAddr to expedite the bind process.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                }
                bindError = ioe;
                try {
                    InetSocketAddress testAddr = new InetSocketAddress(InetAddress.getByName(null), port);
                    if (!testAddr.isUnresolved()) {
                        SocketChannel testChannel = SocketChannel.open(testAddr);
                        // if we get here, socket opened successfully, which means someone is really listening
                        // so close connection and don't bother trying to bind again
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "attempt to connect to command port to check listen status worked, someone else is using the port!");
                        }
                        testChannel.close();
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                        }
                    }
                } catch (IOException testioe) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "attempt to connect to command port to check listen status failed with IOException: " + testioe.getMessage());
                    }
                    try {
                        // open (or close) got IOException, retry with reuseAddress set to true
                        serverSocketChannel.socket().setReuseAddress(true);
                        serverSocketChannel.socket().bind(address);
                        bindError = null;

                    } catch (IOException newioe) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                        }
                        bindError = newioe;
                    }
                }
            }

            if (bindError == null) {
                // if we requested an ephemeral port, find out what port we ended up with
                if (port == 0) {
                    port = serverSocketChannel.socket().getLocalPort();
                }
                listenForCommands = true;
            } else {
                throw bindError;
            }
        }

        ServerCommandID sci = new ServerCommandID(port, serverUUID);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(commandFileTmp);
            fos.write(sci.getIDString().getBytes());
            fos.close();
        } finally {
            Utils.tryToClose(fos);
        }
    }
1234491
def command(self, command, arg=None):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            sock.connect((self.host, self.port))
            payload = {"command": command}
            if arg is not None:
                # Parameter must be converted to basestring (no int)
                payload.update({'parameter': unicode(arg)})

            sock.send(json.dumps(payload))
            received = self._receive(sock)
        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()

        return json.loads(received[:-1])
54583
function postExec (req, res) {
  let cmd = req.body.cmd;
  let connection = res.locals.connection;
  let parts = myutil.split(cmd);
  parts[0] = parts[0].toLowerCase();
  let commandName = parts[0].toLowerCase();

  // must be in our white list to be allowed in read only mode
  if (req.app.locals.redisReadOnly) {
    if (!isReadOnlyCommand(commandName, connection)) {
      return res.send('ERROR: Command not read-only');
    }
  }

  let args = parts.slice(1);
  args.push(function (err, results) {
      if (err) {
          return res.send(err.message);
      }
      return res.send(JSON.stringify(results));
  });
  // check if command is valid is done by ioredis if called with
  // 'connection.call(command, ...)' and our callback called to handle it
  // but throws Error if called via 'connection[commandName].apply(connection, ...)'
  connection.call(commandName, ...args);
}
995713
void handle() throws IOException {
        if (null == handler) {
            println("Command not recognized: %s", command());
            return;
        }
        if (handler == Exit.INSTANCE) {
            handler.handle(this);
        }
        CommandLineParser parser = commandLine();
        boolean help = parser.getBoolean("-h", "--help");
        if (help) {
            Help.INSTANCE.showHelp(parser.command(), this);
        } else {
            try {
                session.handler(handler);
                handler.handle(this);
            } catch ($.Break b) {
                throw b;
            } catch (Exception e) {
                console.println("Error: " + e.getMessage());
            }
        }
    }
1292776
def execute(self, cmd, block_size=DEFAULT_EXECUTE_READ_BLOCK_SIZE):
        
    
        with SshChannel(self) as sc:
            self.__log.debug("Executing command: %s" % (cmd))

            sc.open_session()
            sc.request_exec(cmd)

            buffer_ = bytearray()
            while 1:
                bytes = sc.read(block_size)
                yield bytes
                
                if len(bytes) < block_size:
                    break
133865
void executeCommand() throws CertificateException {
        String exceptionMessage;
        Throwable cause = null;

        try {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Executing keytool command: " + this.toString());
            }
            Process proc = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));

            if (logger.isLoggable(Level.FINE)) {
                logger.fine("Waiting for keytool command process to complete...");
            }
            int exitCode = proc.waitFor();
            if (exitCode == 0) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("keytool command process completed successfully");
                }
                return;
            } else {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("keytool command process failed to complete successfully (exit code: " + exitCode + ")");
                }
                exceptionMessage = getProcErrorOutput(proc);
            }
        } catch (IOException e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("keytool command process execution resulted in IOException: " + e.getMessage());
            }
            exceptionMessage = e.getLocalizedMessage();
            cause = e;
        } catch (InterruptedException e) {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("InterruptedException while waiting for keytool command process result: " + e.getMessage());
            }
            exceptionMessage = e.getLocalizedMessage();
            cause = e;
        }

        if (cause != null) {
            throw new CertificateException(exceptionMessage, cause);
        } else {
            throw new CertificateException(exceptionMessage);
        }
    }
940569
def execute(self, command):
        """"""
        pData = c_char_p(command)
        cbData = DWORD(len(command) + 1)
        hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD())
        if not hDdeData:
            raise DDEError("Unable to send command", self._idInst)
        DDE.FreeDataHandle(hDdeData)
273822
private synchronized void runCommand() throws IOException {
    String command = "";  
    for (String s : this.getExecString()) { 
      command += s + " "; 
    } 
    LOG.debug("Running shell command : " + command);
    if (isDisabled()) {
      LOG.error("Trying to execute a shell call while it is disabled.");
      // Print stack trace to the log
      try {
        throw new Exception();
      } catch (Exception e) {
        LOG.error(StringUtils.stringifyException(e));
      }
      // Make the execution result a fixed string.
      parseExecResult(new BufferedReader(
          new StringReader(NO_SHELL_CALL_ALLOWED_STRING)));
      return;
    }
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);
    
    if (environment != null) {
      builder.environment().putAll(this.environment);
    }
    if (dir != null) {
      builder.directory(this.dir);
    }
    
    process = builder.start();
    if (timeOutInterval > 0) {
      timeOutTimer = new Timer();
      timeoutTimerTask = new ShellTimeoutTimerTask(
          this);
      //One time scheduling.
      timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = 
            new BufferedReader(new InputStreamReader(process
                                                     .getErrorStream()));
    BufferedReader inReader = 
            new BufferedReader(new InputStreamReader(process
                                                     .getInputStream()));
    final StringBuffer errMsg = new StringBuffer();
    
    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
      @Override
      public void run() {
        try {
          String line = errReader.readLine();
          while((line != null) && !isInterrupted()) {
            errMsg.append(line);
            errMsg.append(System.getProperty("line.separator"));
            line = errReader.readLine();
          }
        } catch(IOException ioe) {
          LOG.warn("Error reading the error stream", ioe);
        }
      }
    };
    try {
      errThread.start();
    } catch (IllegalStateException ise) { }
    try {
      parseExecResult(inReader); // parse the output
      // clear the input stream buffer
      String line = inReader.readLine();
      while(line != null) { 
        line = inReader.readLine();
      }
      // wait for the process to finish and check the exit code
      exitCode  = process.waitFor();
      try {
        // make sure that the error thread exits
        errThread.join();
      } catch (InterruptedException ie) {
        LOG.warn("Interrupted while reading the error stream", ie);
      }
      completed.set(true);
      //the timeout thread handling
      //taken care in finally block
      if (exitCode != 0) {
        throw new ExitCodeException(exitCode, errMsg.toString());
      }
    } catch (InterruptedException ie) {
      throw new IOException(ie.toString());
    } finally {
      if ((timeOutTimer!=null) && !timedOut.get()) {
        timeOutTimer.cancel();
      }
      // close the input stream
      try {
        inReader.close();
      } catch (IOException ioe) {
        LOG.warn("Error while closing the input stream", ioe);
      }
      if (!completed.get()) {
        errThread.interrupt();
      }
      try {
        errReader.close();
      } catch (IOException ioe) {
        LOG.warn("Error while closing the error stream", ioe);
      }
      process.destroy();
      lastTime = System.currentTimeMillis();
    }
  }
15706
public void execute() throws IOException {
        int argsSize = args.size();
        String[] cmd = new String[argsSize + 2];
        cmd[0] = ffmpegExecutablePath;
        for (int i = 0; i < argsSize; i++)
        {
            cmd[i + 1] = args.get(i);
        }
        cmd[argsSize + 1] = "-hide_banner";  // Don't show banner
        if (LOG.isDebugEnabled())
        {
            StringBuilder sb = new StringBuilder();
            for (String c : cmd)
            {
                sb.append(c);
                sb.append(' ');
            }
            LOG.debug("About to execute " + sb.toString());
        }
        Runtime runtime = Runtime.getRuntime();
        ffmpeg = runtime.exec(cmd);
        ffmpegKiller = new ProcessKiller(ffmpeg);
        runtime.addShutdownHook(ffmpegKiller);
        inputStream = ffmpeg.getInputStream();
        outputStream = ffmpeg.getOutputStream();
        errorStream = ffmpeg.getErrorStream();
    }
73114
def executeCommand(self, command):
        
        if not command.strip():
            return self.waitForInput()
        
        # store the current block
        self._history.append(command)
        self._currentHistoryIndex = len(self._history)
        
        lines = []
        for line in command.split('\n'):
            line = re.sub('^>>> ', '', line)
            line = re.sub('^\.\.\. ', '', line)
            lines.append(line)
        
        command = '\n'.join(lines)
        
        # ensure we are at the end
        self.moveCursor(QTextCursor.End)
        self.scrollToEnd()
        self.insertPlainText('\n')
        cmdresult = None
        
        try:
            cmdresult = eval(command, self.scope(), self.scope())
        
        except SyntaxError:
            exec(command) in self.scope(), self.scope()
        
        else:
            if cmdresult is not None:
                # check to see if the command we executed actually caused
                # the destruction of this object -- if it did, then
                # the commands below will error
                if self.isDestroyed():
                    return
                
                try:
                    result = projex.text.nativestring(repr(cmdresult))
                except:
                    result = '<<< error formatting result to utf-8 >>>'
                
                self.information(result)
        
        finally:
            self.waitForInput()
3091
def execute_command(self, *args, **options):
        """"""
        pool = self.connection_pool
        command_name = args[0]
        for i in _xrange(self.execution_attempts):
            connection = pool.get_connection(command_name, **options)
            try:
                connection.send_command(*args)
                res = self.parse_response(connection, command_name, **options)
                pool.release(connection)
                return res
            except ConnectionError:
                pool.purge(connection)
                if i >= self.execution_attempts - 1:
                    raise
1338644
public static void exec(ProcessBuilder pb) throws IOException
    {
        Process p = pb.start();
        try
        {
            int errCode = p.waitFor();
            if (errCode != 0)
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                StringBuilder sb = new StringBuilder();
                String str;
                while ((str = in.readLine()) != null)
                    sb.append(str).append(System.getProperty("line.separator"));
                while ((str = err.readLine()) != null)
                    sb.append(str).append(System.getProperty("line.separator"));
                throw new IOException("Exception while executing the command: "+ StringUtils.join(pb.command(), " ") +
                                      ", command error Code: " + errCode +
                                      ", command output: "+ sb.toString());
            }
        }
        catch (InterruptedException e)
        {
            throw new AssertionError(e);
        }
    }
678896
public static void exec(final boolean wait, final String command, final String... parms)
            throws IOException
   {
      String[] commandTokens = parms == null ? new String[1] : new String[parms.length + 1];
      commandTokens[0] = command;

      if (commandTokens.length > 1)
      {
         System.arraycopy(parms, 0, commandTokens, 1, parms.length);
      }

      Runtime.getRuntime().exec(commandTokens, null);
   }