Replace tpo git repository URL by gitlab
[stem.git] / stem / __init__.py
blobe8782115b9ace3d38062aa1ef81cfe4789dd3c55
1 # Copyright 2011-2020, Damian Johnson and The Tor Project
2 # See LICENSE for licensing information
4 """
5 Library for working with the tor process.
7 **Module Overview:**
9 ::
11 Endpoint - Networking endpoint.
12 |- ORPort - Tor relay endpoint.
13 +- DirPort - Descriptor mirror.
15 ControllerError - Base exception raised when using the controller.
16 |- ProtocolError - Malformed socket data.
18 |- OperationFailed - Tor was unable to successfully complete the operation.
19 | |- UnsatisfiableRequest - Tor was unable to satisfy a valid request.
20 | | |- CircuitExtensionFailed - Attempt to make or extend a circuit failed.
21 | | |- DescriptorUnavailable - The given relay descriptor is unavailable.
22 | | +- Timeout - Caller requested timeout was reached.
23 | |
24 | |
25 | +- InvalidRequest - Invalid request.
26 | +- InvalidArguments - Invalid request parameters.
28 +- SocketError - Communication with the socket failed.
29 +- SocketClosed - Socket has been shut down.
31 DownloadFailed - Inability to download a resource.
32 +- DownloadTimeout - Download timeout reached.
34 .. data:: Runlevel (enum)
36 Rating of importance used for event logging.
38 =========== ===========
39 Runlevel Description
40 =========== ===========
41 **ERR** critical issues that impair tor's ability to function
42 **WARN** non-critical issues the user should be aware of
43 **NOTICE** information that may be helpful to the user
44 **INFO** high level runtime information
45 **DEBUG** low level runtime information
46 =========== ===========
48 .. data:: Signal (enum)
50 Signals that the tor process will accept.
52 .. versionchanged:: 1.3.0
53 Added the HEARTBEAT signal.
55 .. versionchanged:: 1.8.0
56 Added the ACTIVE and DORMANT signals. You can check for Tor support for
57 these signals with the **DORMANT_MODE** :data:`~stem.version.Requirement`
59 ========================= ===========
60 Signal Description
61 ========================= ===========
62 **RELOAD** or **HUP** reloads our torrc
63 **SHUTDOWN** or **INT** shut down, waiting ShutdownWaitLength first if we're a relay
64 **DUMP** or **USR1** dumps information about open connections and circuits to our log
65 **DEBUG** or **USR2** switch our logging to the DEBUG runlevel
66 **HALT** or **TERM** exit tor immediately
67 **NEWNYM** switch to new circuits, so new application requests don't share any circuits with old ones (this also clears our DNS cache)
68 **CLEARDNSCACHE** clears cached DNS results
69 **HEARTBEAT** trigger a heartbeat log message
70 **DORMANT** enables *dormant mode*, during which tor will avoid cpu and network usage
71 **ACTIVE** disables *dormant mode*
72 ========================= ===========
74 .. data:: Flag (enum)
76 Flag assigned to tor relays by the authorities to indicate various
77 characteristics.
79 **Note:** The BADDIRECTORY flag was `removed from tor <https://gitweb.torproject.org/torspec.git/commit/dir-spec.txt?id=2f012f1>`_.
81 .. versionchanged:: 1.5.0
82 Added the NO_ED_CONSENSUS flag.
84 .. versionchanged:: 1.8.0
85 Added the STALE_DESC flag.
87 =================== ===========
88 Flag Description
89 =================== ===========
90 **AUTHORITY** relay is a directory authority
91 **BADEXIT** relay shouldn't be used as an exit due to being either problematic or malicious
92 **BADDIRECTORY** relay shouldn't be used for directory information
93 **EXIT** relay's exit policy makes it more useful as an exit rather than middle hop
94 **FAST** relay's suitable for high-bandwidth circuits
95 **GUARD** relay's suitable for being an entry guard (first hop)
96 **HSDIR** relay is being used as a v2 hidden service directory
97 **NAMED** relay can be referred to by its nickname
98 **NO_ED_CONSENSUS** relay's Ed25519 doesn't reflrect the consensus
99 **RUNNING** relay is currently usable
100 **STABLE** relay's suitable for long-lived circuits
101 **STALE_DESC** relay descriptor is outdated and should be re-uploaded
102 **UNNAMED** relay isn't currently bound to a nickname
103 **V2DIR** relay supports the v2 directory protocol
104 **VALID** relay has been validated
105 =================== ===========
107 .. data:: CircStatus (enum)
109 Statuses that a circuit can be in. Tor may provide statuses not in this enum.
111 .. versionchanged:: 1.6.0
112 Added the GUARD_WAIT signal.
114 ============== ===========
115 CircStatus Description
116 ============== ===========
117 **LAUNCHED** new circuit was created
118 **BUILT** circuit finished being created and can accept traffic
119 **GUARD_WAIT** waiting to see if there's a circuit with a better guard before using
120 **EXTENDED** circuit has been extended by a hop
121 **FAILED** circuit construction failed
122 **CLOSED** circuit has been closed
123 ============== ===========
125 .. data:: CircBuildFlag (enum)
127 Attributes about how a circuit is built. These were introduced in tor version
128 0.2.3.11. Tor may provide flags not in this enum.
130 ================= ===========
131 CircBuildFlag Description
132 ================= ===========
133 **ONEHOP_TUNNEL** single hop circuit to fetch directory information
134 **IS_INTERNAL** circuit that won't be used for client traffic
135 **NEED_CAPACITY** circuit only includes high capacity relays
136 **NEED_UPTIME** circuit only includes relays with a high uptime
137 ================= ===========
139 .. data:: CircPurpose (enum)
141 Description of what a circuit is intended for. These were introduced in tor
142 version 0.2.1.6. Tor may provide purposes not in this enum.
144 .. versionchanged:: 2.0.0
145 Added HS_VANGUARDS, PATH_BIAS_TESTING, and CIRCUIT_PADDING (:spec:`a9fee22`).
147 ======================= ===========
148 CircPurpose Description
149 ======================= ===========
150 **GENERAL** client traffic or fetching directory information
151 **HS_CLIENT_INTRO** client side introduction point for a hidden service circuit
152 **HS_CLIENT_REND** client side hidden service rendezvous circuit
153 **HS_SERVICE_INTRO** server side introduction point for a hidden service circuit
154 **HS_SERVICE_REND** server side hidden service rendezvous circuit
155 **TESTING** testing to see if we're reachable, so we can be used as a relay
156 **CONTROLLER** circuit that was built by a controller
157 **MEASURE_TIMEOUT** circuit being kept around to see how long it takes
158 **HS_VANGUARDS** constructed in advance for HS vanguards
159 **PATH_BIAS_TESTING** probing if circuits are being maliciously closed
160 **CIRCUIT_PADDING** circuit is unused, but remains open to disguise its closure time
161 ======================= ===========
163 .. data:: CircClosureReason (enum)
165 Reason that a circuit is being closed or failed to be established. Tor may
166 provide reasons not in this enum.
168 .. versionchanged:: 2.0.0
169 Added IP_NOW_REDUNDANT (:spec:`b418155`).
171 ========================= ===========
172 CircClosureReason Description
173 ========================= ===========
174 **NONE** no reason given
175 **TORPROTOCOL** violation in the tor protocol
176 **INTERNAL** internal error
177 **REQUESTED** requested by the client via a TRUNCATE command
178 **HIBERNATING** relay is currently hibernating
179 **RESOURCELIMIT** relay is out of memory, sockets, or circuit IDs
180 **CONNECTFAILED** unable to contact the relay
181 **OR_IDENTITY** relay had the wrong OR identification
182 **OR_CONN_CLOSED** connection failed after being established
183 **FINISHED** circuit has expired (see tor's MaxCircuitDirtiness config option)
184 **TIMEOUT** circuit construction timed out
185 **DESTROYED** circuit unexpectedly closed
186 **NOPATH** not enough relays to make a circuit
187 **NOSUCHSERVICE** requested hidden service does not exist
188 **MEASUREMENT_EXPIRED** same as **TIMEOUT** except that it was left open for measurement purposes
189 **IP_NOW_REDUNDANT** introduction point is redundant with another constructed circuit
190 ========================= ===========
192 .. data:: CircEvent (enum)
194 Type of change reflected in a circuit by a CIRC_MINOR event. Tor may provide
195 event types not in this enum.
197 ===================== ===========
198 CircEvent Description
199 ===================== ===========
200 **PURPOSE_CHANGED** circuit purpose or hidden service state has changed
201 **CANNIBALIZED** circuit connections are being reused for a different circuit
202 ===================== ===========
204 .. data:: HiddenServiceState (enum)
206 State that a hidden service circuit can have. These were introduced in tor
207 version 0.2.3.11. Tor may provide states not in this enum.
209 Enumerations fall into four groups based on their prefix...
211 ======= ===========
212 Prefix Description
213 ======= ===========
214 HSCI_* client-side introduction-point
215 HSCR_* client-side rendezvous-point
216 HSSI_* service-side introduction-point
217 HSSR_* service-side rendezvous-point
218 ======= ===========
220 ============================= ===========
221 HiddenServiceState Description
222 ============================= ===========
223 **HSCI_CONNECTING** connecting to the introductory point
224 **HSCI_INTRO_SENT** sent INTRODUCE1 and awaiting a reply
225 **HSCI_DONE** received a reply, circuit is closing
226 **HSCR_CONNECTING** connecting to the introductory point
227 **HSCR_ESTABLISHED_IDLE** rendezvous-point established, awaiting an introduction
228 **HSCR_ESTABLISHED_WAITING** introduction received, awaiting a rend
229 **HSCR_JOINED** connected to the hidden service
230 **HSSI_CONNECTING** connecting to the introductory point
231 **HSSI_ESTABLISHED** established introductory point
232 **HSSR_CONNECTING** connecting to the introductory point
233 **HSSR_JOINED** connected to the rendezvous-point
234 ============================= ===========
236 .. data:: RelayEndReason (enum)
238 Reasons why the stream is to be closed.
240 =================== ===========
241 RelayEndReason Description
242 =================== ===========
243 **MISC** none of the following reasons
244 **RESOLVEFAILED** unable to resolve the hostname
245 **CONNECTREFUSED** remote host refused the connection
246 **EXITPOLICY** OR refuses to connect to the destination
247 **DESTROY** circuit is being shut down
248 **DONE** connection has been closed
249 **TIMEOUT** connection timed out
250 **NOROUTE** routing error while contacting the destination
251 **HIBERNATING** relay is temporarily hibernating
252 **INTERNAL** internal error at the relay
253 **RESOURCELIMIT** relay has insufficient resources to service the request
254 **CONNRESET** connection was unexpectedly reset
255 **TORPROTOCOL** violation in the tor protocol
256 **NOTDIRECTORY** directory information requested from a relay that isn't mirroring it
257 =================== ===========
259 .. data:: StreamStatus (enum)
261 State that a stream going through tor can have. Tor may provide states not in
262 this enum.
264 =================== ===========
265 StreamStatus Description
266 =================== ===========
267 **NEW** request for a new connection
268 **NEWRESOLVE** request to resolve an address
269 **REMAP** address is being re-mapped to another
270 **SENTCONNECT** sent a connect cell along a circuit
271 **SENTRESOLVE** sent a resolve cell along a circuit
272 **SUCCEEDED** stream has been established
273 **FAILED** stream is detached, and won't be re-established
274 **DETACHED** stream is detached, but might be re-established
275 **CONTROLLER_WAIT** awaiting a controller's ATTACHSTREAM request
276 **CLOSED** stream has closed
277 =================== ===========
279 .. data:: StreamClosureReason (enum)
281 Reason that a stream is being closed or failed to be established. This
282 includes all values in the :data:`~stem.RelayEndReason` enumeration as
283 well as the following. Tor may provide reasons not in this enum.
285 ===================== ===========
286 StreamClosureReason Description
287 ===================== ===========
288 **END** endpoint has sent a RELAY_END cell
289 **PRIVATE_ADDR** endpoint was a private address (127.0.0.1, 10.0.0.1, etc)
290 ===================== ===========
292 .. data:: StreamSource (enum)
294 Cause of a stream being remapped to another address. Tor may provide sources
295 not in this enum.
297 ============= ===========
298 StreamSource Description
299 ============= ===========
300 **CACHE** tor is remapping because of a cached answer
301 **EXIT** exit relay requested the remap
302 ============= ===========
304 .. data:: StreamPurpose (enum)
306 Purpsoe of the stream. This is only provided with new streams and tor may
307 provide purposes not in this enum.
309 ================= ===========
310 StreamPurpose Description
311 ================= ===========
312 **DIR_FETCH** fetching directory information (descriptors, consensus, etc)
313 **DIR_UPLOAD** uploading our descriptor to an authority
314 **DNS_REQUEST** user initiated DNS request
315 **DIRPORT_TEST** checking that our directory port is reachable externally
316 **USER** either relaying user traffic or not one of the above categories
317 ================= ===========
319 .. data:: ORStatus (enum)
321 State that an OR connection can have. Tor may provide states not in this
322 enum.
324 =============== ===========
325 ORStatus Description
326 =============== ===========
327 **NEW** received OR connection, starting server-side handshake
328 **LAUNCHED** launched outbound OR connection, starting client-side handshake
329 **CONNECTED** OR connection has been established
330 **FAILED** attempt to establish OR connection failed
331 **CLOSED** OR connection has been closed
332 =============== ===========
334 .. data:: ORClosureReason (enum)
336 Reason that an OR connection is being closed or failed to be established. Tor
337 may provide reasons not in this enum.
339 =================== ===========
340 ORClosureReason Description
341 =================== ===========
342 **DONE** OR connection shut down cleanly
343 **CONNECTREFUSED** got a ECONNREFUSED when connecting to the relay
344 **IDENTITY** identity of the relay wasn't what we expected
345 **CONNECTRESET** got a ECONNRESET or similar error from relay
346 **TIMEOUT** got a ETIMEOUT or similar error from relay
347 **NOROUTE** got a ENOTCONN, ENETUNREACH, ENETDOWN, EHOSTUNREACH, or similar error from relay
348 **IOERROR** got a different kind of error from relay
349 **RESOURCELIMIT** relay has insufficient resources to service the request
350 **MISC** connection refused for another reason
351 **PT_MISSING** no pluggable transport was available
352 =================== ===========
354 .. data:: AuthDescriptorAction (enum)
356 Actions that directory authorities might take with relay descriptors. Tor may
357 provide reasons not in this enum.
359 ===================== ===========
360 AuthDescriptorAction Description
361 ===================== ===========
362 **ACCEPTED** accepting the descriptor as the newest version
363 **DROPPED** descriptor rejected without notifying the relay
364 **REJECTED** relay notified that its descriptor has been rejected
365 ===================== ===========
367 .. data:: StatusType (enum)
369 Sources for tor status events. Tor may provide types not in this enum.
371 ============= ===========
372 StatusType Description
373 ============= ===========
374 **GENERAL** general tor activity, not specifically as a client or relay
375 **CLIENT** related to our activity as a tor client
376 **SERVER** related to our activity as a tor relay
377 ============= ===========
379 .. data:: GuardType (enum)
381 Use a guard relay can be for. Tor may provide types not in this enum.
383 =========== ===========
384 GuardType Description
385 =========== ===========
386 **ENTRY** used to connect to the tor network
387 =========== ===========
389 .. data:: GuardStatus (enum)
391 Status a guard relay can have. Tor may provide types not in this enum.
393 ============= ===========
394 GuardStatus Description
395 ============= ===========
396 **NEW** new guard that we weren't previously using
397 **DROPPED** removed from use as one of our guards
398 **UP** guard is now reachable
399 **DOWN** guard is now unreachable
400 **BAD** consensus or relay considers this relay to be unusable as a guard
401 **GOOD** consensus or relay considers this relay to be usable as a guard
402 ============= ===========
404 .. data:: TimeoutSetType (enum)
406 Way in which the timeout value of a circuit is changing. Tor may provide
407 types not in this enum.
409 =============== ===========
410 TimeoutSetType Description
411 =============== ===========
412 **COMPUTED** tor has computed a new timeout based on prior circuits
413 **RESET** timeout reverted to its default
414 **SUSPENDED** timeout reverted to its default until network connectivity has recovered
415 **DISCARD** throwing out timeout value from when the network was down
416 **RESUME** resumed calculations to determine the proper timeout
417 =============== ===========
419 .. data:: ConnectionType (enum)
421 Purpose for a tor connection. Tor may provide types not in this enum.
423 .. versionadded:: 1.2.0
425 =============== ===========
426 ConnectionType Description
427 =============== ===========
428 **OR** carrying traffic within the tor network
429 **DIR** fetching or sending tor descriptor data
430 **EXIT** carrying traffic between the tor network and an external destination
431 =============== ===========
433 .. data:: TokenBucket (enum)
435 Bucket categories of TB_EMPTY events.
437 .. versionadded:: 1.2.0
439 =============== ===========
440 TokenBucket Description
441 =============== ===========
442 **GLOBAL** global token bucket
443 **RELAY** relay token bucket
444 **ORCONN** bucket used for OR connections
445 =============== ===========
447 .. data:: HSDescAction (enum)
449 Action beeing taken in a HS_DESC event.
451 .. versionadded:: 1.2.0
453 .. versionchanged:: 1.4.0
454 Added the UPLOAD and UPLOADED actions.
456 .. versionchanged:: 1.5.0
457 Added the CREATED action.
459 =============== ===========
460 HSDescAction Description
461 =============== ===========
462 **REQUESTED** uncached hidden service descriptor is being requested
463 **UPLOAD** descriptor is being uploaded with HSPOST
464 **RECEIVED** hidden service descriptor has been retrieved
465 **UPLOADED** descriptor was uploaded with HSPOST
466 **IGNORE** fetched descriptor was ignored because we already have its v0 descriptor
467 **FAILED** we were unable to retrieve the descriptor
468 **CREATED** hidden service descriptor was just created
469 =============== ===========
471 .. data:: HSDescReason (enum)
473 Reason for the hidden service descriptor to fail to be fetched.
475 .. versionadded:: 1.3.0
477 .. versionchanged:: 1.4.0
478 Added the UPLOAD_REJECTED reason.
480 .. versionchanged:: 1.6.0
481 Added the QUERY_NO_HSDIR reason.
483 .. versionchanged:: 1.8.0
484 Added the QUERY_RATE_LIMITED reason.
486 ======================= ===========
487 HSDescReason Description
488 ======================= ===========
489 **BAD_DESC** descriptor was unparseable
490 **QUERY_REJECTED** hidden service directory refused to provide the descriptor
491 **UPLOAD_REJECTED** descriptor was rejected by the hidden service directory
492 **NOT_FOUND** descriptor with the given identifier wasn't found
493 **QUERY_NO_HSDIR** no hidden service directory was found
494 **QUERY_RATE_LIMITED** request was throttled
495 **UNEXPECTED** failure type is unknown
496 ======================= ===========
498 .. data:: HSAuth (enum)
500 Type of authentication being used for a HS_DESC event.
502 .. versionadded:: 1.2.0
504 ================= ===========
505 HSAuth Description
506 ================= ===========
507 **NO_AUTH** no authentication
508 **BASIC_AUTH** general hidden service authentication
509 **STEALTH_AUTH** authentication method that hides service activity from unauthorized clients
510 **UNKNOWN** unrecognized method of authentication
511 ================= ===========
514 import traceback
516 import stem.util
517 import stem.util.enum
519 from typing import Any, Optional, Sequence
521 __version__ = '1.8.0-dev'
522 __author__ = 'Damian Johnson'
523 __contact__ = 'atagar@torproject.org'
524 __url__ = 'https://stem.torproject.org/'
525 __license__ = 'LGPLv3'
527 __all__ = [
528 'client',
529 'descriptor',
530 'response',
531 'util',
532 'connection',
533 'control',
534 'directory',
535 'exit_policy',
536 'process',
537 'socket',
538 'version',
539 'ControllerError',
540 'ProtocolError',
541 'OperationFailed',
542 'UnsatisfiableRequest',
543 'CircuitExtensionFailed',
544 'DescriptorUnavailable',
545 'Timeout',
546 'InvalidRequest',
547 'InvalidArguments',
548 'SocketError',
549 'SocketClosed',
550 'DownloadFailed',
551 'DownloadTimeout',
552 'Runlevel',
553 'Signal',
554 'Flag',
555 'CircStatus',
556 'CircBuildFlag',
557 'CircPurpose',
558 'CircClosureReason',
559 'CircEvent',
560 'HiddenServiceState',
561 'HSAuth',
562 'HSDescAction',
563 'HSDescReason',
564 'RelayEndReason',
565 'StreamStatus',
566 'StreamClosureReason',
567 'StreamSource',
568 'StreamPurpose',
569 'ORStatus',
570 'ORClosureReason',
571 'AuthDescriptorAction',
572 'StatusType',
573 'GuardType',
574 'GuardStatus',
575 'TimeoutSetType',
578 # Constant that we use by default for our User-Agent when downloading descriptors
579 USER_AGENT = 'Stem/%s' % __version__
581 # Constant to indicate an undefined argument default. Usually we'd use None for
582 # this, but users will commonly provide None as the argument so need something
583 # else fairly unique...
585 UNDEFINED = '<Undefined_ >'
588 class Endpoint(object):
590 Tor endpint that can be connected to.
592 .. versionadded:: 1.7.0
594 :var str address: ip address of the endpoint
595 :var int port: port of the endpoint
598 def __init__(self, address: str, port: int) -> None:
599 if not stem.util.connection.is_valid_ipv4_address(address) and not stem.util.connection.is_valid_ipv6_address(address):
600 raise ValueError("'%s' isn't a valid IPv4 or IPv6 address" % address)
601 elif not stem.util.connection.is_valid_port(port):
602 raise ValueError("'%s' isn't a valid port" % port)
604 self.address = address
605 self.port = int(port)
607 def __hash__(self) -> int:
608 return stem.util._hash_attr(self, 'address', 'port', cache = True)
610 def __eq__(self, other: Any) -> bool:
611 return hash(self) == hash(other) if isinstance(other, Endpoint) else False
613 def __ne__(self, other: Any) -> bool:
614 return not self == other
617 class ORPort(Endpoint):
619 Tor relay's ORPort. The endpoint on which Tor accepts relay traffic.
621 :var list link_protocols: link protocol version we're willing to establish
624 def __init__(self, address: str, port: int, link_protocols: Optional[Sequence['stem.client.datatype.LinkProtocol']] = None) -> None: # type: ignore
625 super(ORPort, self).__init__(address, port)
626 self.link_protocols = link_protocols
628 def __hash__(self) -> int:
629 return stem.util._hash_attr(self, 'link_protocols', parent = Endpoint, cache = True)
632 class DirPort(Endpoint):
634 Tor relay's DirPort. The endpoint on which Tor provides http access for
635 downloading descriptors.
639 class ControllerError(Exception):
640 'Base error for controller communication issues.'
643 class ProtocolError(ControllerError):
644 'Malformed content from the control socket.'
647 class OperationFailed(ControllerError):
649 Base exception class for failed operations that return an error code
651 :var str code: error code returned by Tor
652 :var str message: error message returned by Tor or a human readable error
653 message
656 # TODO: should the code be an int instead?
658 def __init__(self, code: Optional[str] = None, message: Optional[str] = None) -> None:
659 super(ControllerError, self).__init__(message)
660 self.code = code
661 self.message = message
664 class UnsatisfiableRequest(OperationFailed):
666 Exception raised if Tor was unable to process our request.
670 class CircuitExtensionFailed(UnsatisfiableRequest):
672 An attempt to create or extend a circuit failed.
674 :var stem.response.events.CircuitEvent circ: response notifying us of the failure
677 def __init__(self, message: str, circ: Optional['stem.response.events.CircuitEvent'] = None) -> None: # type: ignore
678 super(CircuitExtensionFailed, self).__init__(message = message)
679 self.circ = circ
682 class DescriptorUnavailable(UnsatisfiableRequest):
684 Tor was unable to provide a descriptor for the given relay.
686 .. versionchanged:: 1.7.0
687 Subclassed under UnsatisfiableRequest rather than OperationFailed.
690 def __init__(self, message: str) -> None:
691 super(DescriptorUnavailable, self).__init__(message = message)
694 class Timeout(UnsatisfiableRequest):
696 Timeout requested by the caller was reached.
698 .. versionadded:: 1.7.0
701 def __init__(self, message: str) -> None:
702 super(Timeout, self).__init__(message = message)
705 class InvalidRequest(OperationFailed):
707 Exception raised when the request was invalid or malformed.
711 class InvalidArguments(InvalidRequest):
713 Exception class for requests which had invalid arguments.
715 :var str code: error code returned by Tor
716 :var str message: error message returned by Tor or a human readable error
717 message
718 :var list arguments: a list of arguments which were invalid
721 def __init__(self, code: Optional[str] = None, message: Optional[str] = None, arguments: Optional[Sequence[str]] = None):
722 super(InvalidArguments, self).__init__(code, message)
723 self.arguments = arguments
726 class SocketError(ControllerError):
727 'Error arose while communicating with the control socket.'
730 class SocketClosed(SocketError):
731 'Control socket was closed before completing the message.'
734 class DownloadFailed(OSError):
736 Inability to download a resource. Python's urllib module raises
737 a wide variety of undocumented exceptions (urllib.request.URLError,
738 socket.timeout, and others).
740 This wraps lower level failures in a common exception type that
741 retains their exception and `stacktrace
742 <https://docs.python.org/3/library/traceback.html>`_.
744 .. versionadded:: 1.8.0
746 :var str url: url we failed to download from
747 :var Exception error: original urllib exception
748 :var traceback stacktrace: original stacktrace
749 :var str stacktrace_str: string representation of the stacktrace
752 def __init__(self, url: str, error: BaseException, stacktrace: Any, message: Optional[str] = None) -> None:
753 if message is None:
754 # The string representation of exceptions can reside in several places.
755 # urllib.URLError use a 'reason' attribute that in turn may referrence
756 # low level structures such as socket.gaierror. Whereas most exceptions
757 # use a 'message' attribute.
759 reason = str(error)
761 all_str_repr = (
762 getattr(getattr(error, 'reason', None), 'strerror', None),
763 getattr(error, 'reason', None),
764 getattr(error, 'message', None),
767 for str_repr in all_str_repr:
768 if str_repr and isinstance(str_repr, str):
769 reason = str_repr
770 break
772 message = 'Failed to download from %s (%s): %s' % (url, type(error).__name__, reason)
774 super(DownloadFailed, self).__init__(message)
776 self.url = url
777 self.error = error
778 self.stacktrace = stacktrace
779 self.stacktrace_str = ''.join(traceback.format_tb(stacktrace))
782 class DownloadTimeout(DownloadFailed):
784 Timeout reached while downloading this resource.
786 .. versionadded:: 1.8.0
789 def __init__(self, url: str, error: BaseException, stacktrace: Any, timeout: float):
790 message = 'Failed to download from %s: %0.1f second timeout reached' % (url, timeout)
791 super(DownloadTimeout, self).__init__(url, error, stacktrace, message)
794 Runlevel = stem.util.enum.UppercaseEnum(
795 'DEBUG',
796 'INFO',
797 'NOTICE',
798 'WARN',
799 'ERR',
802 Flag = stem.util.enum.Enum(
803 ('AUTHORITY', 'Authority'),
804 ('BADEXIT', 'BadExit'),
805 ('BADDIRECTORY', 'BadDirectory'),
806 ('EXIT', 'Exit'),
807 ('FAST', 'Fast'),
808 ('GUARD', 'Guard'),
809 ('HSDIR', 'HSDir'),
810 ('NAMED', 'Named'),
811 ('NO_ED_CONSENSUS', 'NoEdConsensus'),
812 ('RUNNING', 'Running'),
813 ('STABLE', 'Stable'),
814 ('STALE_DESC', 'StaleDesc'),
815 ('UNNAMED', 'Unnamed'),
816 ('V2DIR', 'V2Dir'),
817 ('V3DIR', 'V3Dir'),
818 ('VALID', 'Valid'),
821 Signal = stem.util.enum.UppercaseEnum(
822 'RELOAD',
823 'HUP',
824 'SHUTDOWN',
825 'INT',
826 'DUMP',
827 'USR1',
828 'DEBUG',
829 'USR2',
830 'HALT',
831 'TERM',
832 'NEWNYM',
833 'CLEARDNSCACHE',
834 'HEARTBEAT',
835 'ACTIVE',
836 'DORMANT',
839 CircStatus = stem.util.enum.UppercaseEnum(
840 'LAUNCHED',
841 'BUILT',
842 'GUARD_WAIT',
843 'EXTENDED',
844 'FAILED',
845 'CLOSED',
848 CircBuildFlag = stem.util.enum.UppercaseEnum(
849 'ONEHOP_TUNNEL',
850 'IS_INTERNAL',
851 'NEED_CAPACITY',
852 'NEED_UPTIME',
855 CircPurpose = stem.util.enum.UppercaseEnum(
856 'GENERAL',
857 'HS_CLIENT_INTRO',
858 'HS_CLIENT_REND',
859 'HS_SERVICE_INTRO',
860 'HS_SERVICE_REND',
861 'TESTING',
862 'CONTROLLER',
863 'MEASURE_TIMEOUT',
864 'HS_VANGUARDS',
865 'PATH_BIAS_TESTING',
866 'CIRCUIT_PADDING',
869 CircClosureReason = stem.util.enum.UppercaseEnum(
870 'NONE',
871 'TORPROTOCOL',
872 'INTERNAL',
873 'REQUESTED',
874 'HIBERNATING',
875 'RESOURCELIMIT',
876 'CONNECTFAILED',
877 'OR_IDENTITY',
878 'OR_CONN_CLOSED',
879 'FINISHED',
880 'TIMEOUT',
881 'DESTROYED',
882 'NOPATH',
883 'NOSUCHSERVICE',
884 'MEASUREMENT_EXPIRED',
885 'IP_NOW_REDUNDANT',
888 CircEvent = stem.util.enum.UppercaseEnum(
889 'PURPOSE_CHANGED',
890 'CANNIBALIZED',
893 HiddenServiceState = stem.util.enum.UppercaseEnum(
894 'HSCI_CONNECTING',
895 'HSCI_INTRO_SENT',
896 'HSCI_DONE',
897 'HSCR_CONNECTING',
898 'HSCR_ESTABLISHED_IDLE',
899 'HSCR_ESTABLISHED_WAITING',
900 'HSCR_JOINED',
901 'HSSI_CONNECTING',
902 'HSSI_ESTABLISHED',
903 'HSSR_CONNECTING',
904 'HSSR_JOINED',
907 RelayEndReason = stem.util.enum.UppercaseEnum(
908 'MISC',
909 'RESOLVEFAILED',
910 'CONNECTREFUSED',
911 'EXITPOLICY',
912 'DESTROY',
913 'DONE',
914 'TIMEOUT',
915 'NOROUTE',
916 'HIBERNATING',
917 'INTERNAL',
918 'RESOURCELIMIT',
919 'CONNRESET',
920 'TORPROTOCOL',
921 'NOTDIRECTORY',
924 StreamStatus = stem.util.enum.UppercaseEnum(
925 'NEW',
926 'NEWRESOLVE',
927 'REMAP',
928 'SENTCONNECT',
929 'SENTRESOLVE',
930 'SUCCEEDED',
931 'FAILED',
932 'DETACHED',
933 'CONTROLLER_WAIT',
934 'CLOSED',
937 # StreamClosureReason is a superset of RelayEndReason
938 StreamClosureReason = stem.util.enum.UppercaseEnum(*(RelayEndReason.keys() + [ # type: ignore
939 'END',
940 'PRIVATE_ADDR',
943 StreamSource = stem.util.enum.UppercaseEnum(
944 'CACHE',
945 'EXIT',
948 StreamPurpose = stem.util.enum.UppercaseEnum(
949 'DIR_FETCH',
950 'DIR_UPLOAD',
951 'DNS_REQUEST',
952 'DIRPORT_TEST',
953 'USER',
956 ORStatus = stem.util.enum.UppercaseEnum(
957 'NEW',
958 'LAUNCHED',
959 'CONNECTED',
960 'FAILED',
961 'CLOSED',
964 ORClosureReason = stem.util.enum.UppercaseEnum(
965 'DONE',
966 'CONNECTREFUSED',
967 'IDENTITY',
968 'CONNECTRESET',
969 'TIMEOUT',
970 'NOROUTE',
971 'IOERROR',
972 'RESOURCELIMIT',
973 'MISC',
974 'PT_MISSING',
977 AuthDescriptorAction = stem.util.enum.UppercaseEnum(
978 'ACCEPTED',
979 'DROPPED',
980 'REJECTED',
983 StatusType = stem.util.enum.UppercaseEnum(
984 'GENERAL',
985 'CLIENT',
986 'SERVER',
989 GuardType = stem.util.enum.UppercaseEnum(
990 'ENTRY',
993 GuardStatus = stem.util.enum.UppercaseEnum(
994 'NEW',
995 'UP',
996 'DOWN',
997 'BAD',
998 'GOOD',
999 'DROPPED',
1002 TimeoutSetType = stem.util.enum.UppercaseEnum(
1003 'COMPUTED',
1004 'RESET',
1005 'SUSPENDED',
1006 'DISCARD',
1007 'RESUME',
1010 ConnectionType = stem.util.enum.UppercaseEnum(
1011 'OR',
1012 'DIR',
1013 'EXIT',
1016 TokenBucket = stem.util.enum.UppercaseEnum(
1017 'GLOBAL',
1018 'RELAY',
1019 'ORCONN',
1022 HSDescAction = stem.util.enum.UppercaseEnum(
1023 'REQUESTED',
1024 'UPLOAD',
1025 'RECEIVED',
1026 'UPLOADED',
1027 'IGNORE',
1028 'FAILED',
1029 'CREATED',
1032 HSDescReason = stem.util.enum.UppercaseEnum(
1033 'BAD_DESC',
1034 'QUERY_REJECTED',
1035 'UPLOAD_REJECTED',
1036 'NOT_FOUND',
1037 'QUERY_NO_HSDIR',
1038 'UNEXPECTED',
1041 HSAuth = stem.util.enum.UppercaseEnum(
1042 'NO_AUTH',
1043 'BASIC_AUTH',
1044 'STEALTH_AUTH',
1045 'UNKNOWN',
1049 import stem.util.connection # importing afterward to avoid circular dependency