1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
|
# Copyright (c) str4d <str4d@mail.i2p>
# See COPYING for details.
from __future__ import print_function
from builtins import range
from builtins import object
import os
from parsley import makeProtocol
from twisted.internet.error import ConnectError, UnknownHostError
from twisted.internet.interfaces import IListeningPort
from twisted.internet.protocol import Protocol
from twisted.python.failure import Failure
from zope.interface import implementer
from txi2p import grammar
from txi2p.address import (
I2PAddress,
I2PTunnelTransport,
I2PServerTunnelProtocol,
)
DEFAULT_INPORT = 9000
DEFAULT_OUTPORT = 9001
class BOBSender(object):
def __init__(self, transport):
self.transport = transport
def sendClear(self):
self.transport.write(b'clear\n')
def sendGetdest(self):
self.transport.write(b'getdest\n')
def sendGetkeys(self):
self.transport.write(b'getkeys\n')
def sendGetnick(self, tunnelNick):
msg = 'getnick %s\n' % tunnelNick
self.transport.write(msg.encode('utf-8'))
def sendInhost(self, inhost):
msg = 'inhost %s\n' % inhost
self.transport.write(msg.encode('utf-8'))
def sendInport(self, inport):
msg = 'inport %s\n' % inport
self.transport.write(msg.encode('utf-8'))
def sendList(self):
self.transport.write(b'list\n')
def sendNewkeys(self):
self.transport.write(b'newkeys\n')
def sendOption(self, options={}):
msg = 'option'
for key in sorted(options):
msg += ' %s=%s' % (key, options[key])
msg += '\n'
self.transport.write(msg.encode('utf-8'))
def sendOuthost(self, outhost):
msg = 'outhost %s\n' % outhost
self.transport.write(msg.encode('utf-8'))
def sendOutport(self, outport):
msg = 'outport %s\n' % outport
self.transport.write(msg.encode('utf-8'))
def sendQuiet(self):
self.transport.write(b'quiet\n')
def sendQuit(self):
self.transport.write(b'quit\n')
def sendSetkeys(self, keys):
msg = 'setkeys %s\n' % keys
self.transport.write(msg.encode('utf-8'))
def sendSetnick(self, tunnelNick):
msg = 'setnick %s\n' % tunnelNick
self.transport.write(msg.encode('utf-8'))
def sendShow(self):
self.transport.write(b'show\n')
def sendShowprops(self):
self.transport.write(b'showprops\n')
def sendStart(self):
self.transport.write(b'start\n')
def sendStatus(self, tunnelNick):
msg = 'status %s\n' % tunnelNick
self.transport.write(msg.encode('utf-8'))
def sendStop(self):
self.transport.write(b'stop\n')
def sendVerify(self, key):
msg = 'verify %s\n' % key
self.transport.write(msg.encode('utf-8'))
def sendVisit(self):
self.transport.write(b'visit\n')
class BOBReceiver(object):
currentRule = 'State_init'
def __init__(self, sender):
self.sender = sender
self.tunnelExists = False
def prepareParsing(self, parser):
# Store the factory for later use
self.factory = parser.factory
def finishParsing(self, reason):
if self.currentRule != 'State_quit':
self.factory.bobConnectionFailed(reason)
def initBOB(self, version):
self.sender.sendList()
self.currentRule = 'State_list'
def processTunnelList(self, tunnels):
if not (hasattr(self.factory, 'tunnelNick') and self.factory.tunnelNick):
# All tunnels in the same process use the same tunnelNick
# TODO is using the PID a security risk?
self.factory.tunnelNick = 'txi2p-%d' % os.getpid()
used_ports = []
for i in range(0, len(tunnels)):
if tunnels[i]['nickname'] == self.factory.tunnelNick:
# Tunnel already exists, use its settings.
self.tunnelExists = True
self.tunnelRunning = tunnels[i]['running']
self.factory.inhost = tunnels[i]['inhost']
self.factory.inport = tunnels[i]['inport']
self.factory.outhost = tunnels[i]['outhost']
self.factory.outport = tunnels[i]['outport']
# The tunnel will be removed by the Factory
# that created it.
self.factory.removeTunnelWhenFinished = False
break
else:
if tunnels[i]['inport']:
used_ports.append(tunnels[i]['inport'])
if tunnels[i]['outport']:
used_ports.append(tunnels[i]['outport'])
else:
# This is a new tunnel.
# Default port offset is at the end of the tunnels list
offset = 2*(len(tunnels))
# Find an offset that does not clash
while (DEFAULT_INPORT + offset) in used_ports or (DEFAULT_OUTPORT + offset) in used_ports:
offset += 2
# If the in/outport were not user-configured, set them.
if not (hasattr(self.factory, 'inport') and self.factory.inport):
self.factory.inport = DEFAULT_INPORT + offset
if not (hasattr(self.factory, 'outport') and self.factory.outport):
self.factory.outport = DEFAULT_OUTPORT + offset
def getnick(self, success, info):
if success:
if self.tunnelRunning:
self.sender.sendStop()
self.currentRule = 'State_stop'
else:
# Update the local Destination
self.sender.sendGetdest()
self.currentRule = 'State_getdest'
else:
print('ERROR: %s' % info)
def stop(self, success, info):
if success:
# Update the local Destination
self.sender.sendGetdest()
self.currentRule = 'State_getdest'
else:
print('stop ERROR: %s' % info)
def setnick(self, success, info):
if success:
# Set the options
self.sender.sendOption(self.factory.options)
self.currentRule = 'State_option'
else:
print('setnick ERROR: %s' % info)
def option(self, success, info):
if success:
if hasattr(self.factory, 'keypair') and self.factory.keypair: # If a keypair was provided, use it
self.sender.sendSetkeys(self.factory.keypair)
self.currentRule = 'State_setkeys'
else: # Get a new keypair
self.sender.sendNewkeys()
self.currentRule = 'State_newkeys'
else:
print('option ERROR: %s' % info)
def setkeys(self, success, info):
if success:
# Update the local Destination
self.sender.sendGetdest()
self.currentRule = 'State_getdest'
else:
print('setkeys ERROR: %s' % info)
def newkeys(self, success, info):
if success:
# Save the new local Destination
self.factory.localDest = info
# Get the new keypair
self.sender.sendGetkeys()
self.currentRule = 'State_getkeys'
else:
print('newkeys ERROR: %s' % info)
def quit(self, success, info):
pass
class I2PClientTunnelCreatorBOBReceiver(BOBReceiver):
def list(self, success, info, data):
if success:
self.processTunnelList(data)
if self.tunnelExists:
self.sender.sendGetnick(self.factory.tunnelNick)
self.currentRule = 'State_getnick'
else:
# Set tunnel nickname (and update keypair/localDest state)
self.sender.sendSetnick(self.factory.tunnelNick)
self.currentRule = 'State_setnick'
else:
print('list ERROR: %s' % info)
def getdest(self, success, info):
if success:
# Save the local Destination
self.factory.localDest = info
if self.tunnelExists:
# Get the keypair
self.sender.sendGetkeys()
self.currentRule = 'State_getkeys'
else:
self._setInhost()
else:
print('getdest ERROR: %s' % info)
def getkeys(self, success, info):
if success:
# Save the keypair
self.factory.keypair = info
self._setInhost()
else:
print('getkeys ERROR: %s' % info)
def _setInhost(self):
self.sender.sendInhost(self.factory.inhost)
self.currentRule = 'State_inhost'
def inhost(self, success, info):
if success:
self.sender.sendInport(self.factory.inport)
self.currentRule = 'State_inport'
else:
if info in ['tunnel is active',
'tunnel shutting down']:
# Try again. TODO: Limit retries
self.sender.sendInhost(self.factory.inhost)
else:
print('inhost ERROR: %s' % info)
def inport(self, success, info):
if success:
self.sender.sendStart()
self.currentRule = 'State_start'
else:
print('inport ERROR: %s' % info)
def start(self, success, info):
if success:
print("Client tunnel started")
self.factory.i2pTunnelCreated()
self.sender.sendQuit()
self.currentRule = 'State_quit'
else:
print('start ERROR: %s' % info)
class I2PServerTunnelCreatorBOBReceiver(BOBReceiver):
def list(self, success, info, data):
if success:
self.processTunnelList(data)
if self.tunnelExists:
self.sender.sendGetnick(self.factory.tunnelNick)
self.currentRule = 'State_getnick'
else:
# Set tunnel nickname (and update keypair/localDest state)
self.sender.sendSetnick(self.factory.tunnelNick)
self.currentRule = 'State_setnick'
else:
print('list ERROR: %s' % info)
def getdest(self, success, info):
if success:
# Save the local Destination
self.factory.localDest = info
self._setOuthost()
else:
print('getdest ERROR: %s' % info)
def getkeys(self, success, info):
if success:
# Save the keypair
self.factory.keypair = info
self._setOuthost()
else:
print('getkeys ERROR: %s' % info)
def _setOuthost(self):
self.sender.sendOuthost(self.factory.outhost)
self.currentRule = 'State_outhost'
def outhost(self, success, info):
if success:
self.sender.sendOutport(self.factory.outport)
self.currentRule = 'State_outport'
else:
if info in ['tunnel is active',
'tunnel shutting down']:
# Try again. TODO: Limit retries
self.sender.sendOuthost(self.factory.outhost)
else:
print('outhost ERROR: %s' % info)
def outport(self, success, info):
if success:
self.sender.sendStart()
self.currentRule = 'State_start'
else:
print('outport ERROR: %s' % info)
def start(self, success, info):
if success:
print("Server tunnel started")
self.factory.i2pTunnelCreated()
self.sender.sendQuit()
self.currentRule = 'State_quit'
else:
print('start ERROR: %s' % info)
class I2PTunnelRemoverBOBReceiver(BOBReceiver):
def list(self, success, info, data):
if success:
self.processTunnelList(data)
if self.tunnelExists:
# Get tunnel for nickname
self.sender.sendGetnick(self.factory.tunnelNick)
self.currentRule = 'State_getnick'
else:
# Tunnel already removed
pass
else:
print('list ERROR: %s' % info)
def getnick(self, success, info):
if success:
self.sender.sendStop()
self.currentRule = 'State_stop'
else:
print('getnick ERROR: %s' % info)
def stop(self, success, info):
if success:
self.sender.sendClear()
self.currentRule = 'State_clear'
else:
print('stop ERROR: %s' % info)
def clear(self, success, info):
if success:
print('Tunnel removed')
self.factory.i2pTunnelRemoved()
self.sender.sendQuit()
self.currentRule = 'State_quit'
else:
if info in ['tunnel is active',
'tunnel shutting down']:
# Try again. TODO: Limit retries
self.sender.sendClear()
else:
print('clear ERROR: %s ' % info)
# A Protocol for making an I2P client tunnel via BOB
I2PClientTunnelCreatorBOBClient = makeProtocol(
grammar.bobGrammarSource,
BOBSender,
I2PClientTunnelCreatorBOBReceiver)
# A Protocol for making an I2P server tunnel via BOB
I2PServerTunnelCreatorBOBClient = makeProtocol(
grammar.bobGrammarSource,
BOBSender,
I2PServerTunnelCreatorBOBReceiver)
# A Protocol for removing a BOB I2P tunnel
I2PTunnelRemoverBOBClient = makeProtocol(
grammar.bobGrammarSource,
BOBSender,
I2PTunnelRemoverBOBReceiver)
class I2PClientTunnelProtocol(Protocol):
def __init__(self, wrappedProto, clientAddr, dest):
self.wrappedProto = wrappedProto
self._clientAddr = clientAddr
self.dest = dest
self._errmsg = None
def connectionMade(self):
# Substitute transport for an I2P wrapper
self.transport = I2PTunnelTransport(self.transport, self._clientAddr,
I2PAddress(self.dest))
self.isConnected = False
# First line sent must be the Destination to connect to.
self.transport.write((self.dest + '\n').encode('utf-8'))
self.wrappedProto.makeConnection(self.transport)
def dataReceived(self, data):
# Check for a successful connection
if not self.isConnected:
if data.startswith('ERROR'):
self._errmsg = data[6:]
# I2P connection failed
self.transport.loseConnection()
return
else:
self.isConnected = True
# Pass all received data to the wrapped Protocol.
self.wrappedProto.dataReceived(data.encode('utf-8'))
def connectionLost(self, reason):
if self._errmsg:
if self._errmsg.startswith("Can't find destination"):
reason = Failure(UnknownHostError(string=self._errmsg))
else:
reason = Failure(ConnectError(string=self._errmsg))
self.factory.i2pConnectionLost(self.wrappedProto, reason)
@implementer(IListeningPort)
class I2PListeningPort(object):
def __init__(self, wrappedPort, factoryWrapper, serverAddr):
self._wrappedPort = wrappedPort
self._factoryWrapper = factoryWrapper
self._serverAddr = serverAddr
def startListening(self):
self._wrappedPort.startListening()
def stopListening(self):
self._factoryWrapper.stopListening(self._wrappedPort)
def getHost(self):
return self._serverAddr
|