1

It is possible to start Tor with the following arguments (or parameters in Tor's config file):

--ControlPort auto --ControlPortWriteToFile <TEMPORARY_FILE_PATH>>

So Tor writes to <TEMPORARY_FILE_PATH> file the following:

PORT=127.0.0.1:58771

and you just read it in your program. This sounds obvious but if I'm not missing something it is not.

So I think the following steps are necessary to read the correct port number:

  1. Make sure that <TEMPORARY_FILE_PATH> does not exist [to eliminate risk that you read some old value].
  2. Start Tor process with the arguments
  3. Wait until <TEMPORARY_FILE_PATH> file exists [the file may exist but its content may not be flushed just yet now]
  4. Repeat
    • Open <TEMPORARY_FILE_PATH> file for reading and read a single line (ending with \n)
    • When the line starts with PORT=, you can parse the port -> success & break from loop.

I'm aware that you can start Tor and just wait few hunder milliseconds, read the file and you'll get most likely the correct port number. However, I want to read always the correct port number.

My question is: What is the recommended (and correct) procedure to read the control port number?

1

1 Answer 1

1

Nick Mathewson answered the question here: https://gitlab.torproject.org/tpo/core/tor/-/issues/40386#note_2735298

That sounds plausible to me. I'd suggest adding a step 0: make sure that the path is somewhere randomly generated that only you have write access, to eliminate the risk of somebody else writing to it. (Using mkstemp or similar should take care of that part.)

You might also want to monitor the Tor process that you launched, in case it exits for some reason before it can open this port.

If you're writing your program for a unix-like operating system, you might consider using OwningControllerFd instead: it provides an easier method to start Tor with a connection to an open control port. Hope this helps!

Edit: Upon further research, it seems that one only watch until the Tor control port file exists because what Tor does (implementation detail!) is:

Meaning, Tor creates a temporary file (your specified file with .tmp suffix), writes to it and rename to your specified file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .