Merge pull request #18 from jaicis/fix#3

Network files fixes
This commit is contained in:
lakshyacis 2020-01-02 16:33:17 +05:30 committed by GitHub
commit 102ea32d28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 93 additions and 88 deletions

View File

@ -1,13 +1,13 @@
from .addrthread import AddrThread from network.addrthread import AddrThread
from .announcethread import AnnounceThread from network.announcethread import AnnounceThread
from .connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from .dandelion import Dandelion from network.dandelion import Dandelion
from .downloadthread import DownloadThread from network.downloadthread import DownloadThread
from .invthread import InvThread from network.invthread import InvThread
from .networkthread import BMNetworkThread from network.networkthread import BMNetworkThread
from .receivequeuethread import ReceiveQueueThread from network.receivequeuethread import ReceiveQueueThread
from .threads import StoppableThread from network.threads import StoppableThread
from .uploadthread import UploadThread from network.uploadthread import UploadThread
__all__ = [ __all__ = [

View File

@ -1,4 +1,3 @@
# import queue as Queue
""" """
Announce addresses as they are received from other hosts Announce addresses as they are received from other hosts
""" """

View File

@ -3,7 +3,6 @@ src/network/advanceddispatcher.py
================================= =================================
""" """
# pylint: disable=attribute-defined-outside-init # pylint: disable=attribute-defined-outside-init
# import pdb;pdb.set_trace()
import socket import socket
import threading import threading
import time import time
@ -32,7 +31,7 @@ class AdvancedDispatcher(asyncore.dispatcher):
# python 2 below condition is used # python 2 below condition is used
# if not hasattr(self, '_map'): # if not hasattr(self, '_map'):
# python 3 below condition is used # python 3 below condition is used
if not '_map' in dir(self): if '_map' not in dir(self):
asyncore.dispatcher.__init__(self, sock) asyncore.dispatcher.__init__(self, sock)
self.read_buf = bytearray() self.read_buf = bytearray()
self.write_buf = bytearray() self.write_buf = bytearray()

View File

@ -11,7 +11,7 @@ from bmconfigparser import BMConfigParser
from network.assemble import assemble_addr from network.assemble import assemble_addr
from network.connectionpool import BMConnectionPool from network.connectionpool import BMConnectionPool
from network.udp import UDPSocket from network.udp import UDPSocket
from .node import Peer from network.node import Peer
from network.threads import StoppableThread from network.threads import StoppableThread
@ -38,11 +38,9 @@ class AnnounceThread(StoppableThread):
for stream in state.streamsInWhichIAmParticipating: for stream in state.streamsInWhichIAmParticipating:
addr = ( addr = (
stream, stream,
# state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))), # state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))),
# int(time.time())) # int(time.time()))
# connection.append_write_buf(BMProto.assembleAddr([addr])) # connection.append_write_buf(BMProto.assembleAddr([addr]))
Peer( Peer(
'127.0.0.1', '127.0.0.1',
BMConfigParser().safeGetInt('bitmessagesettings', 'port')), BMConfigParser().safeGetInt('bitmessagesettings', 'port')),

View File

@ -13,7 +13,7 @@ from protocol import CreatePacket, encodeHost
def assemble_addr(peerList): def assemble_addr(peerList):
"""Create address command""" """Create address command"""
if isinstance(peerList, Peer): if isinstance(peerList, Peer):
peerList = (peerList) peerList = [peerList]
if not peerList: if not peerList:
return b'' return b''
retval = b'' retval = b''

View File

@ -102,7 +102,9 @@ def _strerror(err):
return os.strerror(err) return os.strerror(err)
except (ValueError, OverflowError, NameError): except (ValueError, OverflowError, NameError):
if err in errorcode: if err in errorcode:
ret18 ("Unknown error {}".format(err)) return errorcode[err]
return "Unknown error %s" % err
# ret18 ("Unknown error {}".format(err))
class ExitNow(Exception): class ExitNow(Exception):
@ -477,7 +479,7 @@ def kqueue_poller(timeout=0.0, map=None):
current_thread().stop.wait(timeout) current_thread().stop.wait(timeout)
def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None): def loop(timeout=30.0, _=False, map=None, count=None, poller=None):
"""Poll in a loop, until count or timeout is reached""" """Poll in a loop, until count or timeout is reached"""
# pylint: disable=redefined-builtin # pylint: disable=redefined-builtin
@ -518,7 +520,7 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
count = count - 1 count = count - 1
class dispatcher: class dispatcher(object):
"""Dispatcher for socket objects""" """Dispatcher for socket objects"""
# pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class # pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class

View File

@ -32,7 +32,7 @@ from network.bmobject import (
BMObjectInvalidError, BMObjectAlreadyHaveError) BMObjectInvalidError, BMObjectAlreadyHaveError)
from network.proxy import ProxyError from network.proxy import ProxyError
from network.objectracker import missingObjects, ObjectTracker from network.objectracker import missingObjects, ObjectTracker
from .node import Node, Peer from network.node import Node, Peer
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue
from network.randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
@ -52,6 +52,7 @@ count = 0
logger = logging.getLogger('default') logger = logging.getLogger('default')
class BMProtoError(ProxyError): class BMProtoError(ProxyError):
"""A Bitmessage Protocol Base Error""" """A Bitmessage Protocol Base Error"""
errorCodes = ("Protocol error") errorCodes = ("Protocol error")
@ -94,12 +95,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.object = None self.object = None
def state_bm_header(self): def state_bm_header(self):
"""Process incoming header""" """Process incoming header"""
self.magic, self.command, self.payloadLength, self.checksum = \ self.magic, self.command, self.payloadLength, self.checksum = \
protocol.Header.unpack(self.read_buf[:protocol.Header.size]) protocol.Header.unpack(self.read_buf[:protocol.Header.size])
# its shoule be in string # its shoule be in string
self.command = self.command.rstrip('\x00'.encode('utf-8')) self.command = self.command.rstrip('\x00'.encode('utf-8'))
# pylint: disable=global-statement
global count, addr_version, addr_count, addr_verack global count, addr_version, addr_count, addr_verack
count += 1 count += 1
if self.command == 'verack'.encode(): if self.command == 'verack'.encode():
@ -132,7 +133,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
length=protocol.Header.size, expectBytes=self.payloadLength) length=protocol.Header.size, expectBytes=self.payloadLength)
return True return True
def state_bm_command(self): # pylint: disable=too-many-branches def state_bm_command(self): # pylint: disable=too-many-branches, too-many-statements
"""Process incoming command""" """Process incoming command"""
self.payload = self.read_buf[:self.payloadLength] self.payload = self.read_buf[:self.payloadLength]
if self.checksum != hashlib.sha512(self.payload).digest()[0:4]: if self.checksum != hashlib.sha512(self.payload).digest()[0:4]:
@ -346,8 +347,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def bm_command_error(self): def bm_command_error(self):
"""Decode an error message and log it""" """Decode an error message and log it"""
fatalStatus, banTime, inventoryVector, errorText = \ err_values = self.decode_payload_content("vvlsls")
self.decode_payload_content("vvlsls") fatalStatus = err_values[0]
# banTime = err_values[1]
# inventoryVector = err_values[2]
errorText = err_values[3]
logger.error( logger.error(
'%s:%i error: %i, %s', self.destination.host, '%s:%i error: %i, %s', self.destination.host,
self.destination.port, fatalStatus, errorText) self.destination.port, fatalStatus, errorText)
@ -467,7 +471,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"""Incoming addresses, process them""" """Incoming addresses, process them"""
addresses = self._decode_addr() # pylint: disable=redefined-outer-name addresses = self._decode_addr() # pylint: disable=redefined-outer-name
for i in addresses: for i in addresses:
seenTime, stream, services, ip, port = i seenTime, stream, _, ip, port = i
decodedIP = protocol.checkIPAddress(ip) decodedIP = protocol.checkIPAddress(ip)
if stream not in state.streamsInWhichIAmParticipating: if stream not in state.streamsInWhichIAmParticipating:
continue continue
@ -533,6 +537,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"tls_init" if self.isSSL else "connection_fully_established", "tls_init" if self.isSSL else "connection_fully_established",
length=self.payloadLength, expectBytes=0) length=self.payloadLength, expectBytes=0)
return False return False
def bm_command_version(self): def bm_command_version(self):
# print('inside the bmproto ') # print('inside the bmproto ')
""" """
@ -566,7 +571,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
logger.debug( logger.debug(
'%(host)s:%(port)i sending version', '%(host)s:%(port)i sending version',
self.destination._asdict()) self.destination._asdict())
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL)): if self.services & protocol.NODE_SSL == protocol.NODE_SSL:
# self.isSSL = True # self.isSSL = True
pass pass
if not self.verackReceived: if not self.verackReceived:
@ -660,10 +665,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"Closed connection to %s because I'm connected to myself.", "Closed connection to %s because I'm connected to myself.",
self.destination) self.destination)
return False return False
return True return True
@staticmethod @staticmethod
def stopDownloadingObject(hashId, forwardAnyway=False): def stopDownloadingObject(hashId, forwardAnyway=False):
"""Stop downloading an object""" """Stop downloading an object"""

View File

@ -17,11 +17,11 @@ from bmconfigparser import BMConfigParser
from network.connectionchooser import chooseConnection from network.connectionchooser import chooseConnection
from network.proxy import Proxy from network.proxy import Proxy
from .node import Peer
from singleton import Singleton
from network.tcp import ( from network.tcp import (
TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap) TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap)
from network.udp import UDPSocket from network.udp import UDPSocket
from singleton import Singleton
from .node import Peer
logger = logging.getLogger('default') logger = logging.getLogger('default')
@ -430,14 +430,13 @@ class BMConnectionPool(object):
# list(self.udpSockets.values()) # list(self.udpSockets.values())
# ): # ):
for i in ( for i in (
# [inboundConnections for inboundConnections in self.inboundConnections.values()] + # [inboundConnections for inboundConnections in self.inboundConnections.values()] +
# [outboundConnections for outboundConnections in self.outboundConnections.values()] + # [outboundConnections for outboundConnections in self.outboundConnections.values()] +
# [listeningSockets for listeningSockets in self.listeningSockets.values()] + # [listeningSockets for listeningSockets in self.listeningSockets.values()] +
# [udpSockets for udpSockets in self.udpSockets.values()] # [udpSockets for udpSockets in self.udpSockets.values()]
self.connections() +
self.connections() [listeningSockets for listeningSockets in self.listeningSockets.values()] +
+ [listeningSockets for listeningSockets in self.listeningSockets.values()] + [udpSockets for udpSockets in self.udpSockets.values()] [udpSockets for udpSockets in self.udpSockets.values()]
): ):
if not (i.accepting or i.connecting or i.connected): if not (i.accepting or i.connecting or i.connected):
reaper.append(i) reaper.append(i)

View File

@ -28,7 +28,7 @@ logger = logging.getLogger('default')
@Singleton @Singleton
class Dandelion(): # pylint: disable=old-style-class class Dandelion(object):
"""Dandelion class for tracking stem/fluff stages.""" """Dandelion class for tracking stem/fluff stages."""
def __init__(self): def __init__(self):
# currently assignable child stems # currently assignable child stems

View File

@ -44,7 +44,8 @@ class DownloadThread(StoppableThread):
# Choose downloading peers randomly # Choose downloading peers randomly
# connections = [ # connections = [
# x for x in # x for x in
# list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) # list(BMConnectionPool().inboundConnections.values()) +
# list(BMConnectionPool().outboundConnections.values())
# if x.fullyEstablished] # if x.fullyEstablished]
connections = BMConnectionPool().establishedConnections() connections = BMConnectionPool().establishedConnections()

View File

@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name, too-many-ancestors, missing-docstring
import socket import socket
from advanceddispatcher import AdvancedDispatcher from advanceddispatcher import AdvancedDispatcher
@ -12,7 +13,7 @@ class HttpError(ProxyError):
class HttpConnection(AdvancedDispatcher): class HttpConnection(AdvancedDispatcher):
def __init__(self, host, path="/"): # pylint: disable=redefined-outer-name def __init__(self, host, path="/"):
AdvancedDispatcher.__init__(self) AdvancedDispatcher.__init__(self)
self.path = path self.path = path
self.destination = (host, 80) self.destination = (host, 80)
@ -38,7 +39,7 @@ class HttpConnection(AdvancedDispatcher):
class Socks5HttpConnection(Socks5Connection, HttpConnection): class Socks5HttpConnection(Socks5Connection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
self.path = path self.path = path
Socks5Connection.__init__(self, address=(host, 80)) Socks5Connection.__init__(self, address=(host, 80))
@ -48,7 +49,7 @@ class Socks5HttpConnection(Socks5Connection, HttpConnection):
class Socks4aHttpConnection(Socks4aConnection, HttpConnection): class Socks4aHttpConnection(Socks4aConnection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
Socks4aConnection.__init__(self, address=(host, 80)) Socks4aConnection.__init__(self, address=(host, 80))
self.path = path self.path = path

View File

@ -1,3 +1,6 @@
"""
src/network/http_old.py
"""
import asyncore import asyncore
import socket import socket
import time import time

View File

@ -5,7 +5,7 @@ src/network/httpd.py
import asyncore import asyncore
import socket import socket
from tls import TLSHandshake from .tls import TLSHandshake
class HTTPRequestHandler(asyncore.dispatcher): class HTTPRequestHandler(asyncore.dispatcher):
@ -129,7 +129,7 @@ class HTTPServer(asyncore.dispatcher):
def handle_accept(self): def handle_accept(self):
pair = self.accept() pair = self.accept()
if pair is not None: if pair is not None:
sock, addr = pair sock, _ = pair
# print 'Incoming connection from %s' % repr(addr) # print 'Incoming connection from %s' % repr(addr)
self.connections += 1 self.connections += 1
# if self.connections % 1000 == 0: # if self.connections % 1000 == 0:
@ -148,7 +148,7 @@ class HTTPSServer(HTTPServer):
def handle_accept(self): def handle_accept(self):
pair = self.accept() pair = self.accept()
if pair is not None: if pair is not None:
sock, addr = pair sock, _ = pair
# print 'Incoming connection from %s' % repr(addr) # print 'Incoming connection from %s' % repr(addr)
self.connections += 1 self.connections += 1
# if self.connections % 1000 == 0: # if self.connections % 1000 == 0:

View File

@ -1,8 +1,8 @@
# pylint: disable=missing-docstring
import asyncore import asyncore
from http import HTTPClient from .http import HTTPClient
from tls import TLSHandshake from .tls import TLSHandshake
""" """
self.sslSock = ssl.wrap_socket( self.sslSock = ssl.wrap_socket(
self.sock, self.sock,
@ -17,6 +17,7 @@ self.sslSock = ssl.wrap_socket(
class HTTPSClient(HTTPClient, TLSHandshake): class HTTPSClient(HTTPClient, TLSHandshake):
def __init__(self, host, path): def __init__(self, host, path):
# pylint: disable=non-parent-init-called
if not hasattr(self, '_map'): if not hasattr(self, '_map'):
asyncore.dispatcher.__init__(self) asyncore.dispatcher.__init__(self)
self.tlsDone = False self.tlsDone = False

View File

@ -90,7 +90,7 @@ class TCPConnection(BMProto, TLSDispatcher):
ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called
self.bm_proto_reset() self.bm_proto_reset()
# print('--------------tcp------------------') # print('--------------tcp------------------')
from network import stats # from network import stats
self.set_state("bm_header", expectBytes=protocol.Header.size) self.set_state("bm_header", expectBytes=protocol.Header.size)
def antiIntersectionDelay(self, initial=False): def antiIntersectionDelay(self, initial=False):

View File

@ -1,7 +1,6 @@
""" """
SSL/TLS negotiation. SSL/TLS negotiation.
""" """
import logging import logging
import os import os
import socket import socket