Describe how to detect v0 or v1 protocol
[tor.git] / doc / control-spec.txt
blob7bf7c50b39ac121bf998e51ac19d86b068c1add2
1 $Id$
3                    TC: A Tor control protocol (Version 1)
5 0 Scope
7   This document describes an implementation-specific protocol that is used
8   for other programs (such as frontend user-interfaces) to communicate with a
9   locally running Tor process.  It is not part of the Tor onion routing
10   protocol.
12   This protocol replaces version 0 of TC, which is now deprecated.  For
13   reference, TC is described in "control-spec-v0.txt".  Implementors are
14   recommended to avoid using TC directly, but instead to use a library that
15   can easily be updated to use the newer protocol.
17 1 Protocol outline
19   TC is a bidirectional message-based protocol.  It assumes an underlying
20   stream for communication between a controlling process (the "client"
21   or "controller") and a Tor process (or "server").  The stream may be
22   implemented via TCP, TLS-over-TCP, a Unix-domain socket, or so on,
23   but it must provide reliable in-order delivery.  For security, the
24   stream should not be accessible by untrusted parties.
26   In TC, the client and server send typed messages to each other over the
27   underlying stream.  The client sends "commands" and the server sends
28   "replies".
30   By default, all messages from the server are in response to messages from
31   the client.  Some client requests, however, will cause the server to send
32   messages to the client indefinitely far into the future.  Such
33   "asynchronous" replies are marked as such.
35   Servers respond to messages in the order messages are received.
37 2 Message format
39 2.1 Description format
41   The message formats listed below use ABNF as described in RFC2234.
42   The protocol itself is loosely based on SMTP (see RFC 2821).
44   We use the following nonterminals from RFC2822: atom, qcontent
46   We define the following general-use nonterminals:
48      String = DQUOTE *qcontent DQUOTE
50   There are explicitly no limits on line length.  All 8-bit characters are
51   permitted unless explicitly disallowed.
53 2.2 Commands from controller to Tor
55     Command = Keyword Arguments CRLF / "+" Keyword Arguments CRLF Data
56     Keyword = 1*ALPHA
57     Arguments = *(SP / VCHAR)
59   Specific commands and their arguments are described below in section 3.
61 2.3 Replies from Tor to the controller
63     Reply = *(MidReplyLine / DataReplyLine) EndReplyLine
65     MidReplyLine = "-" ReplyLine
66     DataReplyLine = "+" ReplyLine Data
67     EndReplyLine = SP ReplyLine
68     ReplyLine = StatusCode [ SP ReplyText ]  CRLF
69     ReplyText = XXXX
70     StatusCode = XXXX
72   Specific replies are mentioned below in section 3, and described more fully
73   in section 4.
75 2.4 General-use tokens
77   ; Identifiers for servers.
78   ServerID = Nickname / Fingerprint
79   Nickname = 1*19 NicknameChar
80   NicknameChar = "a"-"z" / "A"-"Z" / "0" - "9"
81   Fingerprint = "$" 40*HEXDIG
83   ; Unique identifiers for streams or circuits.  Currently, Tor only
84   ; uses digits, but this may change
85   StreamID = 1*16 IDChar
86   CircuitID = 1*16 IDChar
87   IDChar = ALPHA / DIGIT
89   Address = ip4-address / ip6-address / hostname   (XXXX Define these)
92   ; A "Data" section is a sequence of octets concluded by the terminating
93   ; sequence CRLF "." CRLF.  The terminating sequence may not appear in the
94   ; body of the data.  Leading periods on lines in the data are escaped with
95   ; an additional leading period as in RFC2821 section 4.5.2
96   Data = *DataLine "." CRLF
97   DataLine = CRLF / "." 1*LineItem CRLF/ NonDotItem *LineItem CRLF
98   LineItem = NonCR / 1*CR NonCRLF
99   NonDotItem = NonDotCR / 1*CR NonCRLF
101 3 Commands
103   All commands and other keywords are case-insensitive.
105 3.1 SETCONF
107   Change the value of one or more configuration variables.  The syntax is:
109     "SETCONF" 1*(SP keyword ["=" String]) CRLF
111   Tor behaves as though it had just read each of the key-value pairs
112   from its configuration file.  Keywords with no corresponding values have
113   their configuration values reset to their defaults.  SETCONF is
114   all-or-nothing: if there is an error in any of the configuration settings,
115   Tor sets none of them.
117   Tor responds with a "250 configuration values set" reply on success.
118   Tor responds with a "513 syntax error in configuration values" reply on
119   syntax error, or a "553 impossible configuration setting" reply on a
120   semantic error.
122   When a configuration option takes multiple values, or when multiple
123   configuration keys form a context-sensitive group (see GETCONF below), then
124   setting _any_ of the options in a SETCONF command is taken to reset all of
125   the others.  For example, if two ORBindAddress values are configured, and a
126   SETCONF command arrives containing a single ORBindAddress value, the new
127   command's value replaces the two old values.
129   To _remove_ all settings for a given option entirely (and go back to its
130   default value), send a single line containing the key and no value.
132 3.2 GETCONF
134   Request the value of a configuration variable.  The syntax is:
136     "GETCONF" 1*(SP keyword) CRLF
138   If all of the listed keywords exist in the Tor configuration, Tor replies
139   with a series of reply lines of the form:
140       250 keyword=value
141   If any option is set to a 'default' value semantically different from an
142   empty string, Tor may reply with a reply line of the form:
143       250 keyword
145   If some of the listed keywords can't be found, Tor replies with a
146    "552 unknown configuration keyword" message.
148   If an option appears multiple times in the configuration, all of its
149   key-value pairs are returned in order.
151   Some options are context-sensitive, and depend on other options with
152   different keywords.  These cannot be fetched directly.  Currently there
153   is only one such option: clients should use the "HiddenServiceOptions"
154   virtual keyword to get all HiddenServiceDir, HiddenServicePort,
155   HiddenServiceNodes, and HiddenServiceExcludeNodes option settings.
157 3.3 SETEVENTS
159   Request the server to inform the client about interesting events.  The
160   syntax is:
162      "SETEVENTS" *(SP EventCode) CRLF
164      EventCode = "CIRC" / "STREAM" / "ORCONN" / "BW" / "DEBUG" /
165          "INFO" / "NOTICE" / "WARN" / "ERR" / "NEWDESC" / "ADDRMAP"
167 [XXX We should have an "ADDRESSMAP" event to hear when we learn
168 about dns resolves, etc, so the controller can keep synced. -RD]
170   Any events *not* listed in the SETEVENTS line are turned off; thus, sending
171   SETEVENTS with an empty body turns off all event reporting.
173   The server responds with a "250 OK" reply on success, and a "552
174   Unrecognized event" reply if one of the event codes isn't recognized.  (On
175   error, the list of active event codes isn't changed.)
177 3.4 AUTHENTICATE
179   Sent from the client to the server.  The syntax is:
180      "AUTHENTICATE" SP 1*HEXDIG / QuotedString CRLF
182   The server responds with "250 OK" on success or "515 Bad authentication" if
183   the authentication cookie is incorrect.
185   The format of the 'cookie' is implementation-dependent; see 5.1 below for
186   information on how the standard Tor implementation handles it.
188   If Tor requires authentication and the controller has not yet sent an
189   AUTHENTICATE message, Tor sends a "514 authentication required" reply to
190   any other kind of message.
192 3.5 SAVECONF
194   Sent from the client to the server.  The syntax is:
195      "SAVECONF" CRLF
197   Instructs the server to write out its config options into its torrc. Server
198   returns "250 OK" if successful, or "551 Unable to write configuration
199   to disk" if it can't write the file or some other error occurs.
201 3.6 SIGNAL
203   Sent from the client to the server. The syntax is:
205      "SIGNAL" SP Signal CRLF
207      Signal = "RELOAD" / "SHUTDOWN" / "DUMP" / "DEBUG" / "HALT" /
208               "HUP" / "INT" / "USR1" / "USR2" / "TERM"
210   The meaning of the signals are:
212       RELOAD    -- Reload: reload config items, refetch directory. (like HUP)
213       SHUTDOWN  -- Controlled shutdown: if server is an OP, exit immediately.
214                    If it's an OR, close listeners and exit after 30 seconds.
215                    (like INT)
216       DUMP      -- Dump stats: log information about open connections and
217                    circuits. (like USR1)
218       DEBUG     -- Debug: switch all open logs to loglevel debug. (like USR2)
219       HALT      -- Immediate shutdown: clean up and exit now. (like TERM)
221   The server responds with "250 OK" if the signal is recognized (or simply
222   closes the socket if it was asked to close immediately), or "552
223   Unrecognized signal" if the signal is unrecognized.
225 3.7 MAPADDRESS
227   Sent from the client to the server.  The syntax is:
229     "MAPADDRESS" 1*(Address "=" Address SP) CRLF
231   The first address in each pair is an "original" address; the second is a
232   "replacement" address.  The client sends this message to the server in
233   order to tell it that future SOCKS requests for connections to the original
234   address should be replaced with connections to the specified replacement
235   address.  If the addresses are well-formed, and the server is able to
236   fulfill the request, the server replies with a 250 message:
237     250-OldAddress1=NewAddress1
238     250 OldAddress2=NewAddress2
240   containing the source and destination addresses.  If request is malformed,
241   the server replies with "512 syntax error in command argument".  If the server
242   can't fulfill the request, it replies with "451 resource exhausted."
244   The client may decline to provide a body for the original address, and
245   instead send a special null address ("0.0.0.0" for IPv4, "::0" for IPv6, or
246   "." for hostname), signifying that the server should choose the original
247   address itself, and return that address in the reply.  The server
248   should ensure that it returns an element of address space that is unlikely
249   to be in actual use.  If there is already an address mapped to the
250   destination address, the server may reuse that mapping.
252   If the original address is already mapped to a different address, the old
253   mapping is removed.  If the original address and the destination address
254   are the same, the server removes any mapping in place for the original
255   address.
257   Example:
258     C: MAPADDRESS 0.0.0.0=tor.eff.org 1.2.3.4=tor.freehaven.net
259     S: 250-127.192.10.10=tor.eff.org
260     S: 250 1.2.3.4=tor.freehaven.net
262   {Note: This feature is designed to be used to help Tor-ify applications
263   that need to use SOCKS4 or hostname-less SOCKS5.  There are three
264   approaches to doing this:
265      1. Somehow make them use SOCKS4a or SOCKS5-with-hostnames instead.
266      2. Use tor-resolve (or another interface to Tor's resolve-over-SOCKS
267         feature) to resolve the hostname remotely.  This doesn't work
268         with special addresses like x.onion or x.y.exit.
269      3. Use MAPADDRESS to map an IP address to the desired hostname, and then
270         arrange to fool the application into thinking that the hostname
271         has resolved to that IP.
272   This functionality is designed to help implement the 3rd approach.}
274   Mappings set by the controller last until the Tor process exits:
275   they never expire. If the controller wants the mapping to last only
276   a certain time, then it must explicitly un-map the address when that
277   time has elapsed.
279 3.8 GETINFO
281   Sent from the client to the server.  The syntax is as for GETCONF:
282     "GETINFO" 1*(SP keyword) CRLF
283   one or more NL-terminated strings.  The server replies with an INFOVALUE
284   message.
286   Unlike GETCONF, this message is used for data that are not stored in the Tor
287   configuration file, and that may be longer than a single line.  On success,
288   one ReplyLine is sent for each requested value, followed by a final 250 OK
289   ReplyLine.  If a value fits on a single line, the format is:
290       250-keyword=value
291   If avalue must be split over multiple lines, the format is:
292       250+keyword=
293       value
294       .
295   Recognized key and their values include:
297     "version" -- The version of the server's software, including the name
298       of the software. (example: "Tor 0.0.9.4")
300     "desc/id/<OR identity>" or "desc/name/<OR nickname>" -- the latest server
301       descriptor for a given OR, NUL-terminated.  If no such OR is known, the
302       corresponding value is an empty string.
304     "network-status" -- a space-separated list of all known OR identities.
305       This is in the same format as the router-status line in directories;
306       see tor-spec.txt for details.
308     "addr-mappings/all"
309     "addr-mappings/config"
310     "addr-mappings/cache"
311     "addr-mappings/control" -- a space-separated list of address mappings, each
312       in the form of "from-address=to-address".  The 'config' key
313       returns those address mappings set in the configuration; the 'cache'
314       key returns the mappings in the client-side DNS cache; the 'control'
315       key returns the mappings set via the control interface; the 'all'
316       target returns the mappings set through any mechanism.
318     "circuit-status"
319       A series of lines as for a circuit status event. Each line is of the form:
320          CircuitID SP CircStatus SP Path CRLF
322     "stream-status"
323       A series of lines as for a stream status event.  Each is of the form:
324          StreamID SP StreamStatus SP CircID SP Target CRLF
326     "orconn-status"
327       A series of lines as for an OR connection status event.  Each is of the
328       form:
329          ServerID SP ORStatus CRLF
331   Examples:
332      C: GETINFO version desc/name/moria1
333      S: 250+desc/name/moria=
334      S: [Descriptor for moria]
335      S: .
336      S: 250-version=Tor 0.1.1.0-alpha-cvs
337      S: 250 OK
339 3.9 EXTENDCIRCUIT
341   Sent from the client to the server.  The format is:
342       "EXTENDCIRCUIT" SP CircuitID SP ServerID *("," ServerID) CRLF
344   This request takes one of two forms: either the Circuit ID is zero, in
345   which case it is a request for the server to build a new circuit according
346   to the specified path, or the Circuit ID is nonzero, in which case it is a
347   request for the server to extend an existing circuit with that ID according
348   to the specified path.
350   If the request is successful, the server sends a reply containing a message
351   body consisting of the Circuit ID of the (maybe newly created) circuit.
352   The syntax is "250" SP "EXTENDED" SP CircuitID CRLF.
354 3.10 ATTACHSTREAM
356   Sent from the client to the server.  The syntax is:
357      "ATTACHSTREAM" SP StreamID SP CircuitID CRLF
359   This message informs the server that the specified stream should be
360   associated with the specified circuit.  Each stream may be associated with
361   at most one circuit, and multiple streams may share the same circuit.
362   Streams can only be attached to completed circuits (that is, circuits that
363   have sent a circuit status 'BUILT' event or are listed as built in a
364   GETINFO circuit-status request).
366   If the circuit ID is 0, responsibility for attaching the given stream is
367   returned to Tor.
369   Tor responds with "250 OK" if it can attach the stream, 552 if the circuit
370   or stream didn't exist, or 551 if the stream couldn't be attached for
371   another reason.
373   {Implementation note: By default, Tor automatically attaches streams to
374   circuits itself, unless the configuration variable
375   "__LeaveStreamsUnattached" is set to "1".  Attempting to attach streams
376   via TC when "__LeaveStreamsUnattached" is false may cause a race between
377   Tor and the controller, as both attempt to attach streams to circuits.}
379 3.11 POSTDESCRIPTOR
381   Sent from the client to the server. The syntax is:
382     "+POSTDESCRIPTOR" CRLF Descriptor CRLF "." CRLF
384   This message informs the server about a new descriptor.
386   The descriptor, when parsed, must contain a number of well-specified
387   fields, including fields for its nickname and identity.
389   If there is an error in parsing the descriptor, the server must send a "554
390   Invalid descriptor" reply.  If the descriptor is well-formed but the server
391   chooses not to add it, it must reply with a 251 message whose body explains
392   why the server was not added.  If the descriptor is added, Tor replies with
393   "250 OK".
395 3.12 REDIRECTSTREAM
397   Sent from the client to the server. The syntax is:
398     "REDIRECTSTREAM" SP StreamID SP Address CRLF
400   Tells the server to change the exit address on the specified stream.  No
401   remapping is performed on the new provided address.
403   To be sure that the modified address will be used, this event must be sent
404   after a new stream event is received, and before attaching this stream to
405   a circuit.
407   Tor replies with "250 OK" on success.
409 3.13 CLOSESTREAM
411   Sent from the client to the server.  The syntax is:
413     "CLOSESTREAM" SP StreamID SP Reason *(SP Flag) CRLF
415   Tells the server to close the specified stream.  The reason should be one
416   of the Tor RELAY_END reasons given in tor-spec.txt, as a decimal.  Flags is
417   not used currently; Tor servers SHOULD ignore unrecognized flags.  Tor may
418   hold the stream open for a while to flush any data that is pending.
420 3.14 CLOSECIRCUIT
422    The syntax is:
423      CLOSECIRCUIT SP CircuitID *(SP Flag) CRLF
424      Flag = "IfUnused"
426   Tells the server to close the specified circuit.   If "IfUnused" is
427   provided, do not close the circuit unless it is unused.
429   Other flags may be defined in the future; Tor SHOULD ignore unrecognized
430   flags.
432 4 Replies
434   Reply codes follow the same 3-character format as used by SMTP, with the
435   first character defining a status, the second character defining a
436   subsystem, and the third designating fine-grained information.
438   The TC protocol currently uses the following first characters:
440     2yz   Positive Completion Reply
441        The command was successful; a new request can be started.
443     4yz   Temporary Negative Completion reply
444        The command was unsuccessful but might be reattempted later.
446     5yz   Permanent Negative Completion Reply
447        The command was unsuccessful; the client should not try exactly
448        that sequence of commands again.
450     6yz   Asynchronous Reply
451        Sent out-of-order in response to an earlier SETEVENTS command.
453   The following second characters are used:
455     x0z   Syntax
456        Sent in response to ill-formed or nonsensical commands.
458     x1z   Protocol
459        Refers to operations of the Tor Control protocol.
461     x5z   Tor
462        Refers to actual operations of Tor system.
464   The following codes are defined:
466      250 OK
467      251 Operation was unnecessary
468          [Tor has declined to perform the operation, but no harm was done.]
470      451 Resource exhausted
472      500 Syntax error: protocol
474      510 Unrecognized command
475      511 Unimplemented command
476      512 Syntax error in command argument
477      513 Unrecognized command argument
478      514 Authentication required
479      515 Bad authentication
481      550 Unspecified Tor error
483      551 Internal error
484                [Something went wrong inside Tor, so that the client's
485                 request couldn't be fulfilled.]
487      552 Unrecognized entity
488                [A configuration key, a stream ID, circuit ID, event,
489                 mentioned in the command did not actually exist.]
491      553 Invalid configuration value
492          [The client tried to set a configuration option to an
493            incorrect, ill-formed, or impossible value.]
495      554 Invalid descriptor
497      555 Unmanaged entity
499      650 Asynchronous event notification
501   Unless specified to have specific contents, the human-readable messages
502   in error replies should not be relied upon to match those in this document.
504 4.1 Asynchronous events
506   These replies can be sent after a corresponding SETEVENTS command has been
507   received.  They will not be interleaved with other Reply elements, but they
508   can appear between a command and its corresponding reply.  For example,
509   this sequence is possible:
511      C: SETEVENTS CIRC
512      S: 250 OK
513      C: GETCONFIG SOCKSPORT ORPORT
514      S: 650 CIRC 1000 EXTENDED moria1,moria2
515      S: 250-SOCKSPORT=9050
516      S: 250 ORPORT=0
518   But this sequence is disallowed:
519      C: SETEVENTS CIRC
520      S: 250 OK
521      C: GETCONFIG SOCKSPORT ORPORT
522      S: 250-SOCKSPORT=9050
523      S: 650 CIRC 1000 EXTENDED moria1,moria2
524      S: 250 ORPORT=0
526   Clients SHOULD tolerate more arguments in an asynchonous reply than
527   expected, and SHOULD tolerate more lines in an asynchronous reply than
528   expected.  For instance, a client that expects a CIRC message like:
529       650 CIRC 1000 EXTENDED moria1,moria2
530   should tolerate:
531       650+CIRC 1000 EXTENDED moria1,moria2 0xBEEF
532       650-EXTRAMAGIC=99
533       650 ANONYMITY=high
535 4.1.1 Circuit status changed
537    The syntax is:
539      "650" SP "CIRC" SP CircuitID SP CircStatus SP Path
541       CircStatus =
542                "LAUNCHED" / ; circuit ID assigned to new circuit
543                "BUILT"    / ; all hops finished, can now accept streams
544                "EXTENDED" / ; one more hop has been completed
545                "FAILED"   / ; circuit closed (was not built)
546                "CLOSED"     ; circuit closed (was built)
548       Path = ServerID *("," ServerID)
550 4.1.2. Stream status changed
552     The syntax is:
554       "650" SP "STREAM" SP StreamID SP StreamStatus SP CircID SP Target SP 
556       StreamStatus =
557                "NEW"          / ; New request to connect
558                "NEWRESOLVE"  / ; New request to resolve an address
559                "SENTCONNECT" / ; Sent a connect cell along a circuit
560                "SENTRESOLVE" / ; Sent a resolve cell along a circuit
561                "SUCCEEDED"    / ; Received a reply; stream established
562                "FAILED"       / ; Stream failed and not retriable.
563                "CLOSED"       / ; Stream closed
564                "DETACHED"       ; Detached from circuit; still retriable.
566        Target = Address ":" Port
568   The circuit ID designates which circuit this stream is attached to.  If
569   the stream is unattached, the circuit ID "0" is given.
571 4.1.3 OR Connection status changed
573   The syntax is:
574     "650" SP "ORCONN" SP ServerID SP ORStatus
576     ORStatus = "LAUNCHED" / "CONNECTED" / "FAILED" / "CLOSED"
578 4.1.3 Bandwidth used in the last second
580   The syntax is:
581      "650" SP "BW" SP BytesRead SP BytesWritten
582      BytesRead = 1*DIGIT
583      BytesWritten = 1*DIGIT
585 4.1.4 Log message
587   The syntax is:
588      "650" SP Severity SP ReplyText
589   or
590      "650+" Severity CRLF Data
592      Severity = "DEBUG" / "INFO" / "NOTICE" / "WARN"/ "ERR"
594 4.1.5 New descriptors available
596   Syntax:
597      "650" SP "NEWDESC" 1*(SP ServerID)
599 4.1.6 New Address mapping
601   Syntax:
602      "650" SP "ADDRMAP" SP Address SP Address SP Expiry
603      Expiry = DQOUTE ISOTime DQUOTE / "NEVER"
605 5. Implementation notes
607 5.1. Authentication
609   By default, the current Tor implementation trusts all local users.
611   If the 'CookieAuthentication' option is true, Tor writes a "magic cookie"
612   file named "control_auth_cookie" into its data directory.  To authenticate,
613   the controller must send the contents of this file.
615   If the 'HashedControlPassword' option is set, it must contain the salted
616   hash of a secret password.  The salted hash is computed according to the
617   S2K algorithm in RFC 2440 (OpenPGP), and prefixed with the s2k specifier.
618   This is then encoded in hexadecimal, prefixed by the indicator sequence
619   "16:".  Thus, for example, the password 'foo' could encode to:
620      16:660537E3E1CD49996044A3BF558097A981F539FEA2F9DA662B4626C1C2
621         ++++++++++++++++**^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
622            salt                       hashed value
623                        indicator
624   You can generate the salt of a password by calling
625            'tor --hash-password <password>'
626   or by using the example code in the Python and Java controller libraries.
627   To authenticate under this scheme, the controller sends Tor the original
628   secret that was used to generate the password.
630 5.2. Don't let the buffer get too big.
632   If you ask for lots of events, and 16MB of them queue up on the buffer,
633   the Tor process will close the socket.
635 5.3. Backward compatibility
637   For backward compatibility with the "version 0" control protocol, Tor checks
638   whether the third octet the first command is zero.  If it is, Tor
639   assumes that version 0 is in use.  This feature is deprecated, and will be
640   removed in the 0.1.2.x Tor development series.
642   In order to detect which version of the protocol is supported controllers
643   should send the sequence [00 00 0D 0A].  This is a valid and unrecognized
644   command in both protocol versions, and implementations can detect which
645   error they have received.