Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Review Async implementation vs Channels Implementation. #31

Open
TerminalFi opened this issue Sep 10, 2019 · 0 comments
Open

Review Async implementation vs Channels Implementation. #31

TerminalFi opened this issue Sep 10, 2019 · 0 comments
Labels
research Research further

Comments

@TerminalFi
Copy link
Collaborator

TerminalFi commented Sep 10, 2019

Review current Bufio Async implementation vs Async channel implementation.

The below is fully working AsyncRun with Channels

// RunAsync runs nmap asynchronously and returns error.
func (s *Scanner) RunAsync() (<-chan []byte, <-chan []byte, error) {
	stdoutChannel := make(chan []byte)
	stderrChannel := make(chan []byte)

	// Enable XML output.
	s.args = append(s.args, "-oX")

	// Get XML output in stdout instead of writing it in a file.
	s.args = append(s.args, "-")
	s.cmd = exec.Command(s.binaryPath, s.args...)

	// Get CMD Stderr Pipe
	stderr, err := s.cmd.StderrPipe()
	if err != nil {
		return nil, nil, fmt.Errorf("unable to get error output from asynchronous nmap run: %v", err)
	}

	// Get CMD Stdout Pipe
	stdout, err := s.cmd.StdoutPipe()
	if err != nil {
		return nil, nil, fmt.Errorf("unable to get standard output from asynchronous nmap run: %v", err)
	}

	if err := s.cmd.Start(); err != nil {
		return nil, nil, fmt.Errorf("unable to execute asynchronous nmap run: %v", err)
	}

	// Stream stdout to the stdoutChannel
	go func() {
		defer close(stdoutChannel)
		for {
			buf := make([]byte, 1024)
			n, err := stdout.Read(buf)
			if err != nil {
				if err != io.EOF {
					log.Fatal(err)
				}
				if n == 0 {
					break
				}
			}
			stdoutChannel <- buf[:n]
		}
	}()

	// Stream stderr to the stderrChannel
	go func() {
		defer close(stderrChannel)
		for {
			buf := make([]byte, 2048)
			n, err := stderr.Read(buf)
			if err != nil {
				if err != io.EOF {
					log.Fatal(err)
				}
				if n == 0 {
					break
				}
			}
			stderrChannel <- buf[:n]
		}
	}()

	go func() {
		<-s.ctx.Done()
		_ = s.cmd.Process.Kill()
	}()

	return stdoutChannel, stderrChannel, nil
}
@TerminalFi TerminalFi added the research Research further label Sep 10, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
research Research further
Projects
None yet
Development

No branches or pull requests

1 participant