Improve concurrency and connection state transitions

The state is now changed atomically, and allowed transitions are checked.

Also, we ensure concurrent access of the authentication handler.
The thread that makes the state transition is the only one that will
execute the instructions in the block.