Skip to content

Commit

Permalink
- Organized Imports
Browse files Browse the repository at this point in the history
- Shorted Over 80 Char Lines
- Corrected not in statements
  • Loading branch information
super3 committed Jan 19, 2016
1 parent da14e05 commit ec91bb1
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 42 deletions.
7 changes: 4 additions & 3 deletions pyp2p/dht_msg.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import sys
import time
import binascii
import requests
from ast import literal_eval

Expand All @@ -16,6 +14,7 @@
except:
import simplejson as json

import string
import binascii

try:
Expand Down Expand Up @@ -71,7 +70,9 @@ def add_message_handler(self, handler):
self.message_handlers.add(handler)

def rand_str(self, length):
return ''.join(random.choice(u'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(length))
return ''.join(random.choice(string.digits + string.lowercase +
string.ascii_uppercase
) for i in range(length))

def register(self, node_id, password, no=1):
# Only retry up to 5 times.
Expand Down
19 changes: 3 additions & 16 deletions pyp2p/lib.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@
import os
import platform
import sys
import time
import netifaces
import random
import socket

import ipaddress
import ntplib
import time
import sys

try:
from urllib.request import urlopen
except:
from urllib2 import urlopen

import select
import hashlib
import random
import datetime
import binascii
import re
import base64
import struct
import uuid
from threading import Thread
try:
import json
except:
import simplejson as json
import traceback

from decimal import Decimal
from .ipgetter import *
from .ip_routes import *

Expand Down
19 changes: 13 additions & 6 deletions pyp2p/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,9 @@ def advertise(self):
# Tell rendezvous server to list us.
try:
# We're a passive node.
if self.node_type == "passive" and self.passive_port is not None and self.enable_advertise:
if self.node_type == "passive" and\
self.passive_port is not None and\
self.enable_advertise:
self.rendezvous.passive_listen(self.passive_port,
self.max_inbound)

Expand Down Expand Up @@ -632,7 +634,8 @@ def determine_node(self):
lan_ip = self.passive_bind

# Passive node checks.
if lan_ip is not None and self.passive_port is not None and self.enable_forwarding:
if lan_ip is not None \
and self.passive_port is not None and self.enable_forwarding:
self.debug_print("Checking if port is forwarded.")

# Check port isn't already forwarded.
Expand Down Expand Up @@ -1077,23 +1080,26 @@ def success(con):
processed.append(dht_response)

# Found reverse query (did you make this?)
elif re.match("^REVERSE_QUERY:[a-zA-Z0-9+/-=_\s]+$", msg) is not None:
elif re.match("^REVERSE_QUERY:[a-zA-Z0-9+/-=_\s]+$", msg)\
is not None:
# Process message.
self.debug_print("Received reverse query")
call, their_unl = msg.split(":")
their_unl = UNL(value=their_unl).deconstruct()
node_id = their_unl["node_id"]

# Do we know about this?
if their_unl["value"] not in self.unl.pending_reverse_con:
if their_unl["value"] not in \
self.unl.pending_reverse_con:
self.debug_print(their_unl)
self.debug_print(str(self.unl.pending_reverse_con))
self.debug_print("oops, we don't know about this"
" reverse query!")
processed.append(dht_response)
continue
else:
self.unl.pending_reverse_con.remove(their_unl["value"])
self.unl.pending_reverse_con.remove(
their_unl["value"])

# Send query.
query = "REVERSE_ORIGIN:" + self.unl.value
Expand All @@ -1102,7 +1108,8 @@ def success(con):
processed.append(dht_response)

# Found reverse origin (yes I made this.)
elif re.match("^REVERSE_ORIGIN:[a-zA-Z0-9+/-=_\s]+$", msg) is not None:
elif re.match("^REVERSE_ORIGIN:[a-zA-Z0-9+/-=_\s]+$", msg) \
is not None:
self.debug_print("Received reverse origin")
for reverse_query in self.pending_reverse_queries:
pattern = "^REVERSE_ORIGIN:" + reverse_query["unl"]
Expand Down
2 changes: 1 addition & 1 deletion pyp2p/rendezvous_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def predict_mappings(self, mappings):

# Overflow or underflow = wrap port around.
if mapping["remote"] > max_port:
mapping["remote"] = mapping["remote"] - max_port
mapping["remote"] -= max_port
if mapping["remote"] < 0:
mapping["remote"] = max_port - -mapping["remote"]

Expand Down
24 changes: 14 additions & 10 deletions pyp2p/rendezvous_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def propogate_candidates(self, node_ip):
candidate["ip_addr"],
" ".join(map(str, candidate["predictions"])),
candidate["proto"])

self.factory.nodes["simultaneous"][node_ip]["con"].\
send_line(msg)
old_candidates.append(candidate)
Expand Down Expand Up @@ -178,7 +178,7 @@ def synchronize_simultaneous(self, node_ip):
self.factory.nodes["simultaneous"][node_ip]["con"].\
send_line(msg)
return

self.cleanup_candidates(node_ip)
self.propogate_candidates(node_ip)

Expand Down Expand Up @@ -245,7 +245,8 @@ def connectionLost(self, reason):
# Hole punching is ms time sensitive.
# Candidates older than this is safe to assume
# they're not needed.
if not node_ip in self.factory.nodes["simultaneous"] and t - candidate["time"] >= self.challenge_timeout * 5:
if node_ip not in self.factory.nodes["simultaneous"] \
and t - candidate["time"] >= self.challenge_timeout * 5:
old_candidates.append(candidate)

# Remove old candidates.
Expand All @@ -254,7 +255,7 @@ def connectionLost(self, reason):

# Record old node IPs.
if not len(self.factory.candidates[node_ip]) and \
not node_ip in self.factory.nodes["simultaneous"]:
node_ip not in self.factory.nodes["simultaneous"]:
old_node_ips.append(node_ip)

# Remove old node IPs.
Expand Down Expand Up @@ -284,7 +285,7 @@ def lineReceived(self, line):
if not len(parts):
break
n = int(parts[0])

# Invalid number.
if n < 1 or n > 100:
break
Expand Down Expand Up @@ -314,7 +315,8 @@ def lineReceived(self, line):
continue

# Not connected.
if node_type == "simultaneous" and not element["con"].connected:
if node_type == "simultaneous" and\
not element["con"].connected:
i -= 1
ip_addr_list.remove(ip_addr)
continue
Expand All @@ -334,7 +336,8 @@ def lineReceived(self, line):
break

# Add node details to relevant sections.
if re.match("^(SIMULTANEOUS|PASSIVE) READY [0-9]+ [0-9]+$", line) is not None:
if re.match("^(SIMULTANEOUS|PASSIVE) READY [0-9]+ [0-9]+$", line)\
is not None:
# Get type.
node_type, passive_port, max_inbound = re.findall("^(SIMULTANEOUS|PASSIVE) READY ([0-9]+) ([0-9]+)", line)[0]
node_type = node_type.lower()
Expand All @@ -355,7 +358,7 @@ def lineReceived(self, line):

# Passive doesn't have a candidates list.
if node_type == "simultaneous":
if not node_ip in self.factory.candidates:
if node_ip not in self.factory.candidates:
self.factory.candidates[node_ip] = []
else:
self.cleanup_candidates(node_ip)
Expand Down Expand Up @@ -449,7 +452,7 @@ def lineReceived(self, line):
client_ip, predictions, proto, ntp = parts[0]

# Invalid IP address.
node_ip = self.transport.getPeer().host
node_ip = self.transport.getPeer().host
if node_ip not in self.factory.candidates:
break

Expand All @@ -466,7 +469,8 @@ def lineReceived(self, line):
ntp = ntp
t = time.time()
minute = 60 * 10
if int(float(ntp)) < t - minute or int(float(ntp)) > t + minute:
if int(float(ntp)) < t - minute or\
int(float(ntp)) > t + minute:
break

# Relay fight to client_ip.
Expand Down
1 change: 1 addition & 0 deletions pyp2p/unl.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import binascii
import base64
import logging
import hashlib
from threading import Thread, Lock

logging.basicConfig()
Expand Down
11 changes: 5 additions & 6 deletions pyp2p/upnp.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@
from urllib2 import urlopen
from urllib2 import Request

import multiprocessing
import threading
import subprocess
import platform
import subprocess
from threading import Thread

"""
Expand Down Expand Up @@ -98,7 +96,7 @@ def find_gateway(self):
s = None

# Error: no UPnP replies - try guess gateway.
if replies == []:
if not replies:
default_gateway = get_default_gateway(self.interface)
if default_gateway is None or default_gateway == {}:
return None
Expand Down Expand Up @@ -218,13 +216,14 @@ def forward_port(self, proto, src_port, dest_ip, dest_port=None):
res = res.replace('\r', '')
res = res.replace('\n', '')
res = res.replace('\t', '')
pres = res.split('<serviceId>urn:upnp-org:serviceId:WANIPConn1</serviceId>')
pres = res.split('<serviceId>urn:upnp-org:serviceId:WANIPConn1'
'</serviceId>')
p2res = pres[1].split('</controlURL>')
p3res = p2res[0].split('<controlURL>')
ctrl = p3res[1]
rip = res.split('<presentationURL>')
rip1 = rip[1].split('</presentationURL>')
routerIP = rip1[0]
router_ip = rip1[0]

port_map_desc = "PyP2P"
msg = \
Expand Down

0 comments on commit ec91bb1

Please sign in to comment.