rapid7/meterpreter — pull request #38 by OJ (2013-10-28 04:27:38+00:00)
Title: Refactor of channels to better manage lifetimes and clean up nicely

This PR contains a bit of work that has the goal of making channel lifetime management much better. We have a number of issues where channels don't behave properly.

Main issues were:

* Channel lifetimes were managed across threads, which didn't help when it came to cleaning things up.
* Backrounding a channel with `CTRL+Z` actually destroyed parts of the channel context, which meant that forgrounding with `channel -i ` didn't work at all. Sometimes it even crashed meterpreter.
* Channels that were backgrounded left their underlying processes behind. For example, calling `shell` would result in either `cmd.exe` or `/bin/sh` hanging behind the scenes).

Context is managed a bit differently now. The thread which manages the channel is no longer destroyed when backgrounded, instead it's paused.

The POSIX version of the scheduler was _very_ different to the Windows version. They have been normalised a bit in this commit. I had intended for this commit to combine the POSIX and Windows versions into one file so that code duplication was kept to a minimum. However I couldn't get the build system to behave on POSIX so I have shelved that idea for now and will come back to it another time.

## Verification
- [ ] Builds cleanly on Windows
- [ ] Builds cleanly on POSIX
- [ ] Channels function as they did before with uploads
- [ ] Channels function as they did before with port forwards
- [ ] Backgrounding and foregrounding shells works properly without causing problems
- [ ] Terminating a background channel using `channel -c ` works correctly without crashing locally
- [ ] When a shell's interactive channels is closed on Windows, calling `exit` in the shell terminates `cmd.exe` properly
- [ ] When a shell's interactive channels is closed on Windows, calling `channel -c ` in meterpreter terminates `cmd.exe` properly
- [ ] When a shell's interactive channels is closed on POSIX, calling `exit` in the shell terminates `/bin/sh` properly
- [ ] When a shell's interactive channels is closed on POSIX, calling `channel -c ` in meterpreter terminates `/bin/sh` properly

**Note:** Channels left open when meterpreter is exited will not be closed properly until https://github.com/rapid7/meterpreter/pull/34 lands.