| 136 | return self.connectController() |
| 137 | |
| 138 | def connectController(self): |
| 139 | if "socket_noproxy" in dir(socket): # Socket proxy-patched, use non-proxy one |
| 140 | conn = socket.socket_noproxy(socket.AF_INET, socket.SOCK_STREAM) |
| 141 | else: |
| 142 | conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 143 | |
| 144 | self.log.debug("Connecting to Tor Controller %s:%s" % (self.ip, self.port)) |
| 145 | self.connecting = True |
| 146 | try: |
| 147 | with self.lock: |
| 148 | conn.connect((self.ip, self.port)) |
| 149 | |
| 150 | # Auth cookie file |
| 151 | res_protocol = self.send("PROTOCOLINFO", conn) |
| 152 | cookie_match = re.search('COOKIEFILE="(.*?)"', res_protocol) |
| 153 | |
| 154 | if config.tor_password: |
| 155 | res_auth = self.send('AUTHENTICATE "%s"' % config.tor_password, conn) |
| 156 | elif cookie_match: |
| 157 | cookie_file = cookie_match.group(1).encode("ascii").decode("unicode_escape") |
| 158 | auth_hex = binascii.b2a_hex(open(cookie_file, "rb").read()) |
| 159 | res_auth = self.send("AUTHENTICATE %s" % auth_hex.decode("utf8"), conn) |
| 160 | else: |
| 161 | res_auth = self.send("AUTHENTICATE", conn) |
| 162 | |
| 163 | if "250 OK" not in res_auth: |
| 164 | raise Exception("Authenticate error %s" % res_auth) |
| 165 | |
| 166 | # Version 0.2.7.5 required because ADD_ONION support |
| 167 | res_version = self.send("GETINFO version", conn) |
| 168 | version = re.search(r'version=([0-9\.]+)', res_version).group(1) |
| 169 | if float(version.replace(".", "0", 2)) < 207.5: |
| 170 | raise Exception("Tor version >=0.2.7.5 required, found: %s" % version) |
| 171 | |
| 172 | self.setStatus("Connected (%s)" % res_auth) |
| 173 | self.event_started.set(True) |
| 174 | self.starting = False |
| 175 | self.connecting = False |
| 176 | self.conn = conn |
| 177 | except Exception as err: |
| 178 | self.conn = None |
| 179 | self.setStatus("Error (%s)" % str(err)) |
| 180 | self.log.warning("Tor controller connect error: %s" % Debug.formatException(str(err))) |
| 181 | self.enabled = False |
| 182 | return self.conn |
| 183 | |
| 184 | def disconnect(self): |
| 185 | if self.conn: |