A Tor client initially contacts Directory Authorities to fetch the consensus (i.e. a file containing all relays of the Tor network at that time with details such as IP address, exit policy, public key etc.) As soon as a Tor client gathers sufficient information about existing relays, it tries to build circuit paths. How does the Tor client choose which nodes to use for a circuit?
Taken from Tor Path Specification document:
We choose the path for each new circuit before we build it. We choose the exit node first, followed by the other nodes in the circuit. All paths we generate obey the following constraints:
- We do not choose the same router twice for the same path.
- We do not choose any router in the same family as another in the same path. (Two routers are in the same family if each one lists the other in the "family" entries of its descriptor.)
- We do not choose more than one router in a given /16 subnet.
- We don't choose any non-running or non-valid router unless we have been configured to do so. By default, we are configured to allow non-valid routers in "middle" and "rendezvous" positions.
- The first node must be a Guard node.
Relay selection is not uniform but weighted by relay bandwidth. Faster relays have a higher probability of being picked than slower ones.
I want to add some details to alaf's answer:
A Tor circuit consists always of three nodes. Longer paths may hurt your anonymity in the case of Tor.
- Exit node is chosen.
torrcmight have some settings about which exits to (not) choose.
- Tor chooses an exit relay which actually allows you to exit the Tor network. Some only allow web traffic (port 80) which is not useful when someone wants to send emails.
- The exit relay has to have available capacities. Tor tries to choose such exits which have enough ressources available.
- Some exit relays are considered as bad exits. They might listen in your traffic, change your traffic etc. Tor does not choose them (as long as you don't explicitly allow it).
- Entry and middle relay is chosen.
- Tor tries not to choose relays which might belong to the same operator.
- Relay is not in the same /16 subnet. So Tor only uses one IP address in a range from 10.12.0.0 to 10.12.255.255 (10 and 12 can be any number).
- Operators who run more than one relay should declare those relays their 'family' (There is a special option in the configuration). Tor doesn't choose more then one relay from a family.
- A client can also set such a family option. This will also be respected.
The other answers give an overview of what happens, but if you want to learn the consequences of the path selection algorithm you need to have a simulation based on real data. Fortunately there now is one – TorPS which was written for the paper "Users Get Routed: Traffic Correlation on Tor by Realistic Adversaries".