2016-06-30 10:11:33 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
2016-08-03 19:05:01 +02:00
|
|
|
import errno
|
2016-06-30 10:11:33 +02:00
|
|
|
import logging
|
2016-07-19 11:53:24 +02:00
|
|
|
import os
|
2016-06-30 10:11:33 +02:00
|
|
|
import random
|
2016-07-19 11:53:24 +02:00
|
|
|
import select
|
2016-06-30 10:11:33 +02:00
|
|
|
import socket
|
2016-07-19 11:53:24 +02:00
|
|
|
import ssl
|
2016-06-30 10:11:33 +02:00
|
|
|
import threading
|
|
|
|
import queue
|
|
|
|
import time
|
|
|
|
|
|
|
|
import message
|
|
|
|
import shared
|
|
|
|
import structure
|
|
|
|
|
|
|
|
|
|
|
|
class Connection(threading.Thread):
|
|
|
|
def __init__(self, host, port, s=None):
|
|
|
|
super().__init__(name='Connection to {}:{}'.format(host, port))
|
|
|
|
|
|
|
|
self.send_queue = queue.Queue()
|
|
|
|
|
|
|
|
self.vectors_to_get = set()
|
|
|
|
|
|
|
|
self.status = 'ready'
|
2016-07-19 12:48:04 +02:00
|
|
|
|
|
|
|
self.tls = False
|
|
|
|
|
|
|
|
self.verack_received = False
|
|
|
|
self.verack_sent = False
|
2016-06-30 10:11:33 +02:00
|
|
|
|
|
|
|
self.host = host
|
|
|
|
self.port = int(port)
|
|
|
|
|
|
|
|
self.s = s
|
|
|
|
|
|
|
|
self.remote_version = None
|
|
|
|
|
|
|
|
self.server = bool(s)
|
|
|
|
|
|
|
|
if self.server:
|
|
|
|
self.status = 'connected'
|
|
|
|
|
2016-08-03 19:05:01 +02:00
|
|
|
self.buffer_receive = b''
|
|
|
|
self.buffer_send = b''
|
|
|
|
|
2016-06-30 10:11:33 +02:00
|
|
|
self.next_message_size = shared.header_length
|
|
|
|
self.next_header = True
|
2016-08-03 19:05:01 +02:00
|
|
|
self.on_connection_fully_established_scheduled = False
|
2016-06-30 10:11:33 +02:00
|
|
|
|
|
|
|
self.last_message_received = time.time()
|
|
|
|
self.last_message_sent = time.time()
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
if self.s is None:
|
|
|
|
self._connect()
|
|
|
|
if self.status != 'connected':
|
|
|
|
return
|
2016-08-03 19:05:01 +02:00
|
|
|
self.s.settimeout(0)
|
2016-06-30 10:11:33 +02:00
|
|
|
if not self.server:
|
|
|
|
self.send_queue.put(message.Version(self.host, self.port))
|
|
|
|
while True:
|
2016-08-17 17:51:04 +02:00
|
|
|
if self.on_connection_fully_established_scheduled and not (self.buffer_send or self.buffer_receive):
|
|
|
|
self._on_connection_fully_established()
|
2016-06-30 10:11:33 +02:00
|
|
|
data = True
|
|
|
|
try:
|
2016-08-17 17:51:04 +02:00
|
|
|
if self.status == 'fully_established':
|
|
|
|
data = self.s.recv(4096)
|
|
|
|
self.buffer_receive += data
|
2016-08-17 18:11:00 +02:00
|
|
|
if data and len(self.buffer_receive) < self.next_message_size:
|
2016-08-17 18:00:02 +02:00
|
|
|
continue
|
2016-08-17 17:51:04 +02:00
|
|
|
else:
|
|
|
|
data = self.s.recv(self.next_message_size - len(self.buffer_receive))
|
|
|
|
self.buffer_receive += data
|
2016-08-03 19:05:01 +02:00
|
|
|
except ssl.SSLWantReadError:
|
|
|
|
pass
|
|
|
|
except socket.error as e:
|
|
|
|
err = e.args[0]
|
|
|
|
if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise
|
2016-06-30 10:11:33 +02:00
|
|
|
except ConnectionResetError:
|
2016-08-03 19:05:01 +02:00
|
|
|
logging.debug('Disconnecting from {}:{}. Reason: ConnectionResetError'.format(self.host, self.port))
|
2016-06-30 10:11:33 +02:00
|
|
|
data = None
|
2016-08-03 19:05:01 +02:00
|
|
|
self._process_buffer_receive()
|
2016-06-30 10:11:33 +02:00
|
|
|
self._request_objects()
|
|
|
|
self._process_queue()
|
2016-08-03 19:05:01 +02:00
|
|
|
self._send_data()
|
|
|
|
if time.time() - self.last_message_received > shared.timeout:
|
|
|
|
logging.debug(
|
|
|
|
'Disconnecting from {}:{}. Reason: time.time() - self.last_message_received > shared.timeout'.format(
|
|
|
|
self.host, self.port))
|
|
|
|
data = None
|
|
|
|
if time.time() - self.last_message_received > 30 and self.status != 'fully_established':
|
|
|
|
logging.debug(
|
|
|
|
'Disconnecting from {}:{}. Reason: time.time() - self.last_message_received > 30 and self.status != \'fully_established\''.format(
|
|
|
|
self.host, self.port))
|
|
|
|
data = None
|
|
|
|
if time.time() - self.last_message_sent > 300 and self.status == 'fully_established':
|
|
|
|
self.send_queue.put(message.Message(b'pong', b''))
|
2016-06-30 10:11:33 +02:00
|
|
|
if self.status == 'disconnecting':
|
|
|
|
data = None
|
|
|
|
if not data:
|
|
|
|
self.status = 'disconnected'
|
|
|
|
self.s.close()
|
|
|
|
logging.info('Disconnected from {}:{}'.format(self.host, self.port))
|
|
|
|
break
|
2016-08-17 17:51:04 +02:00
|
|
|
time.sleep(0.2)
|
2016-06-30 10:11:33 +02:00
|
|
|
|
|
|
|
def _connect(self):
|
|
|
|
logging.info('Connecting to {}:{}'.format(self.host, self.port))
|
|
|
|
|
|
|
|
try:
|
|
|
|
self.s = socket.create_connection((self.host, self.port))
|
|
|
|
self.status = 'connected'
|
|
|
|
logging.debug('Established TCP connection to {}:{}'.format(self.host, self.port))
|
|
|
|
except Exception as e:
|
|
|
|
logging.warning('Connection to {}:{} failed'.format(self.host, self.port))
|
|
|
|
logging.warning(e)
|
|
|
|
|
|
|
|
self.status = 'failed'
|
|
|
|
|
2016-08-03 19:05:01 +02:00
|
|
|
def _send_data(self):
|
2016-08-17 17:51:04 +02:00
|
|
|
if self.buffer_send:
|
|
|
|
try:
|
|
|
|
amount = self.s.send(self.buffer_send)
|
|
|
|
self.buffer_send = self.buffer_send[amount:]
|
|
|
|
except (BlockingIOError, ssl.SSLWantWriteError):
|
|
|
|
pass
|
2016-08-03 19:05:01 +02:00
|
|
|
|
2016-07-19 12:18:16 +02:00
|
|
|
def _do_tls_handshake(self):
|
|
|
|
logging.debug('Initializing TLS connection with {}:{}'.format(self.host, self.port))
|
|
|
|
self.s = ssl.wrap_socket(self.s, keyfile=os.path.join(shared.source_directory, 'tls', 'key.pem'),
|
|
|
|
certfile=os.path.join(shared.source_directory, 'tls', 'cert.pem'),
|
|
|
|
server_side=self.server, ssl_version=ssl.PROTOCOL_TLSv1, do_handshake_on_connect=False,
|
2016-08-03 19:05:01 +02:00
|
|
|
ciphers='AECDH-AES256-SHA', suppress_ragged_eofs=True)
|
2016-07-19 12:18:16 +02:00
|
|
|
if hasattr(self.s, "context"):
|
|
|
|
self.s.context.set_ecdh_curve("secp256k1")
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
self.s.do_handshake()
|
|
|
|
break
|
2016-08-03 19:05:01 +02:00
|
|
|
except ssl.SSLWantReadError:
|
|
|
|
select.select([self.s], [], [])
|
|
|
|
except ssl.SSLWantWriteError:
|
|
|
|
select.select([], [self.s], [])
|
2016-07-19 12:18:16 +02:00
|
|
|
except Exception as e:
|
2016-07-19 14:09:42 +02:00
|
|
|
logging.error(e)
|
2016-07-19 12:18:16 +02:00
|
|
|
break
|
2016-07-19 12:48:04 +02:00
|
|
|
self.tls = True
|
2016-07-19 12:18:16 +02:00
|
|
|
logging.debug('Established TLS connection with {}:{}'.format(self.host, self.port))
|
|
|
|
|
2016-06-30 10:11:33 +02:00
|
|
|
def _send_message(self, m):
|
|
|
|
if type(m) == message.Message and m.command == b'object':
|
|
|
|
logging.debug('{}:{} <- {}'.format(self.host, self.port, structure.Object.from_message(m)))
|
|
|
|
else:
|
|
|
|
logging.debug('{}:{} <- {}'.format(self.host, self.port, m))
|
2016-08-03 19:05:01 +02:00
|
|
|
self.buffer_send += m.to_bytes()
|
2016-06-30 10:11:33 +02:00
|
|
|
|
2016-07-19 11:53:24 +02:00
|
|
|
def _on_connection_fully_established(self):
|
2016-07-19 12:48:04 +02:00
|
|
|
logging.info('Established Bitmessage protocol connection to {}:{}'.format(self.host, self.port))
|
2016-08-03 19:05:01 +02:00
|
|
|
self.on_connection_fully_established_scheduled = False
|
2016-07-19 12:48:04 +02:00
|
|
|
if self.remote_version.services & 2: # NODE_SSL
|
|
|
|
self._do_tls_handshake()
|
2016-06-30 10:11:33 +02:00
|
|
|
with shared.objects_lock:
|
2016-07-19 14:09:42 +02:00
|
|
|
if len(shared.objects) > 0:
|
|
|
|
self.send_queue.put(message.Inv({vector for vector in shared.objects.keys() if shared.objects[vector].expires_time > time.time()}))
|
|
|
|
addr = {structure.NetAddr(c.remote_version.services, c.host, c.port) for c in shared.connections.copy() if not c.server and c.status == 'fully_established'}
|
2016-06-30 10:11:33 +02:00
|
|
|
if len(addr) != 0:
|
|
|
|
self.send_queue.put(message.Addr(addr))
|
2016-07-19 14:09:42 +02:00
|
|
|
self.status = 'fully_established'
|
2016-06-30 10:11:33 +02:00
|
|
|
|
|
|
|
def _process_queue(self):
|
|
|
|
while not self.send_queue.empty():
|
|
|
|
m = self.send_queue.get()
|
|
|
|
if m:
|
2016-07-19 12:48:04 +02:00
|
|
|
if m == 'fully_established':
|
2016-08-03 19:05:01 +02:00
|
|
|
self.on_connection_fully_established_scheduled = True
|
2016-07-19 12:48:04 +02:00
|
|
|
else:
|
|
|
|
self._send_message(m)
|
|
|
|
self.last_message_sent = time.time()
|
2016-06-30 10:11:33 +02:00
|
|
|
else:
|
|
|
|
self.status = 'disconnecting'
|
|
|
|
break
|
|
|
|
|
2016-08-03 19:05:01 +02:00
|
|
|
def _process_buffer_receive(self):
|
|
|
|
while len(self.buffer_receive) >= self.next_message_size:
|
2016-06-30 10:11:33 +02:00
|
|
|
if self.next_header:
|
|
|
|
self.next_header = False
|
2016-08-03 19:05:01 +02:00
|
|
|
h = message.Header.from_bytes(self.buffer_receive[:shared.header_length])
|
2016-06-30 10:11:33 +02:00
|
|
|
self.next_message_size += h.payload_length
|
|
|
|
else:
|
2016-08-03 19:05:01 +02:00
|
|
|
m = message.Message.from_bytes(self.buffer_receive[:self.next_message_size])
|
2016-06-30 10:11:33 +02:00
|
|
|
|
|
|
|
self.next_header = True
|
2016-08-03 19:05:01 +02:00
|
|
|
self.buffer_receive = self.buffer_receive[self.next_message_size:]
|
2016-06-30 10:11:33 +02:00
|
|
|
self.next_message_size = shared.header_length
|
|
|
|
self.last_message_received = time.time()
|
|
|
|
self._process_message(m)
|
|
|
|
|
|
|
|
def _process_message(self, m):
|
|
|
|
if m.command == b'version':
|
|
|
|
version = message.Version.from_bytes(m.to_bytes())
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, str(version)))
|
|
|
|
if version.protocol_version != shared.protocol_version or version.nonce == shared.nonce:
|
|
|
|
self.status = 'disconnecting'
|
|
|
|
self.send_queue.put(None)
|
|
|
|
else:
|
|
|
|
self.send_queue.put(message.Message(b'verack', b''))
|
2016-07-19 12:48:04 +02:00
|
|
|
self.verack_sent = True
|
2016-06-30 10:11:33 +02:00
|
|
|
self.remote_version = version
|
|
|
|
if not self.server:
|
2016-07-19 12:48:04 +02:00
|
|
|
self.send_queue.put('fully_established')
|
2016-06-30 10:11:33 +02:00
|
|
|
shared.address_advertise_queue.put(structure.NetAddr(version.services, self.host, self.port))
|
|
|
|
shared.node_pool.add((self.host, self.port))
|
|
|
|
shared.address_advertise_queue.put(structure.NetAddr(shared.services, version.host, shared.listening_port))
|
2016-07-19 12:18:16 +02:00
|
|
|
if self.server:
|
|
|
|
self.send_queue.put(message.Version(self.host, self.port))
|
2016-06-30 10:11:33 +02:00
|
|
|
elif m.command == b'verack':
|
2016-07-19 12:48:04 +02:00
|
|
|
self.verack_received = True
|
2016-06-30 10:11:33 +02:00
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, 'verack'))
|
2016-07-19 12:48:04 +02:00
|
|
|
if self.server:
|
|
|
|
self.send_queue.put('fully_established')
|
|
|
|
|
2016-06-30 10:11:33 +02:00
|
|
|
elif m.command == b'inv':
|
|
|
|
inv = message.Inv.from_message(m)
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, inv))
|
|
|
|
to_get = inv.vectors.copy()
|
|
|
|
to_get.difference_update(shared.objects.keys())
|
|
|
|
to_get.difference_update(shared.requested_objects)
|
|
|
|
self.vectors_to_get.update(to_get)
|
|
|
|
elif m.command == b'object':
|
|
|
|
obj = structure.Object.from_message(m)
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, obj))
|
|
|
|
if obj.is_valid() and obj.vector not in shared.objects:
|
|
|
|
with shared.objects_lock:
|
|
|
|
shared.objects[obj.vector] = obj
|
|
|
|
shared.vector_advertise_queue.put(obj.vector)
|
|
|
|
elif m.command == b'getdata':
|
|
|
|
getdata = message.GetData.from_message(m)
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, getdata))
|
|
|
|
for vector in getdata.vectors:
|
|
|
|
if vector in shared.objects:
|
|
|
|
self.send_queue.put(message.Message(b'object', shared.objects[vector].to_bytes()))
|
2016-07-09 19:37:07 +02:00
|
|
|
elif m.command == b'addr':
|
2016-06-30 10:11:33 +02:00
|
|
|
addr = message.Addr.from_message(m)
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, addr))
|
|
|
|
for a in addr.addresses:
|
|
|
|
shared.unchecked_node_pool.add((a.host, a.port))
|
2016-07-09 19:37:07 +02:00
|
|
|
elif m.command == b'ping':
|
|
|
|
logging.debug('{}:{} -> ping'.format(self.host, self.port))
|
|
|
|
self.send_queue.put(message.Message(b'pong', b''))
|
2016-06-30 10:11:33 +02:00
|
|
|
else:
|
|
|
|
logging.debug('{}:{} -> {}'.format(self.host, self.port, m))
|
|
|
|
|
|
|
|
def _request_objects(self):
|
|
|
|
if self.vectors_to_get:
|
|
|
|
if len(self.vectors_to_get) > 50000:
|
|
|
|
pack = random.sample(self.vectors_to_get, 50000)
|
|
|
|
self.send_queue.put(message.GetData(pack))
|
|
|
|
self.vectors_to_get.difference_update(pack)
|
|
|
|
if shared.conserve_bandwidth:
|
|
|
|
with shared.requested_objects_lock:
|
|
|
|
shared.requested_objects.update(pack)
|
|
|
|
else:
|
|
|
|
self.send_queue.put(message.GetData(self.vectors_to_get))
|
|
|
|
if shared.conserve_bandwidth:
|
|
|
|
with shared.requested_objects_lock:
|
|
|
|
shared.requested_objects.update(self.vectors_to_get)
|
|
|
|
self.vectors_to_get.clear()
|