Example #1
0
 def verify_contacts(self, id_obj):
     """
     """
     nowip = strng.to_bin(misc.readExternalIP())
     tcp_contact = 'tcp://%s:%d' % (
         nowip,
         settings.getTCPPort(),
     )
     if id_obj.getContactIndex(contact=tcp_contact) < 0:
         if _Debug:
             lg.out(
                 4,
                 'tcp_interface.verify_contacts returning False: tcp contact not found or changed'
             )
         return False
     if tcp_node.get_internal_port() != settings.getTCPPort():
         if _Debug:
             lg.out(
                 4,
                 'tcp_interface.verify_contacts returning False: tcp port has been changed'
             )
         return False
     if _Debug:
         lg.out(4, 'tcp_interface.verify_contacts returning True')
     return True
 def doStart(self, arg):
     """
     Action method.
     """
     options = {'idurl': my_id.getLocalID(), }
     id_contact = ''
     default_host = ''
     ident = my_id.getLocalIdentity()
     if ident:
         id_contact = ident.getContactsByProto().get(self.proto, '')
     if id_contact:
         assert id_contact.startswith(self.proto + '://')
         id_contact = id_contact.strip(self.proto + '://')
     if self.proto == 'tcp':
         if not id_contact:
             default_host = misc.readExternalIP() + ':' + str(settings.getTCPPort())
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = nameurl.GetName(my_id.getLocalID()) + '@' + platform.node()
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     if _Debug:
         lg.out(8, 'network_transport.doStart connecting %s transport : %s' % (self.proto.upper(), options))
     self.interface.connect(options)
 def _upnp_proto_done(result, proto):
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.UpdateUPNP._upnp_proto_done %s: %s' % (proto, str(result)))
     if result[0] == 'upnp-done':
         if proto == 'tcp':
             if str(settings.getTCPPort()) != str(result[1]).strip():
                 lg.out(_DebugLevel, '    !!!!!!!!!! created a new port mapping, TCP port were changed: %s -> %s' % (
                     settings.getTCPPort(), str(result[1])))
             settings.setTCPPort(result[1])
     protos_need_upnp.discard(proto)
     reactor.callLater(0, _update_next_proto)  # @UndefinedVariable
Example #4
0
def parseCommandLine():
    oparser = optparse.OptionParser()
    oparser.add_option("-d",
                       "--debug",
                       dest="debug",
                       type="int",
                       help="set debug level")
    oparser.set_default('debug', 10)
    oparser.add_option("-t",
                       "--tcpport",
                       dest="tcpport",
                       type="int",
                       help="specify port for TCP transport")
    oparser.set_default('tcpport', settings.getTCPPort())
    oparser.add_option("-u",
                       "--udpport",
                       dest="udpport",
                       type="int",
                       help="specify port for UDP transport")
    oparser.set_default('udpport', settings.getUDPPort())
    oparser.add_option("-p",
                       "--dhtport",
                       dest="dhtport",
                       type="int",
                       help="specify UDP port for DHT network")
    oparser.set_default('dhtport', settings.getDHTPort())
    oparser.add_option("-s",
                       "--packetsize",
                       dest="packetsize",
                       type="int",
                       help="set size of UDP datagrams")
    oparser.set_default('packetsize', 480)
    (options, args) = oparser.parse_args()
    return options, args
Example #5
0
 def doStart(self, *args, **kwargs):
     """
     Action method.
     """
     options = {'idurl': my_id.getLocalID(), }
     id_contact = ''
     default_host = ''
     if self.proto == 'tcp':
         if not id_contact:
             default_host = strng.to_bin(misc.readExternalIP()) + b':' + strng.to_bin(str(settings.getTCPPort()))
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = strng.to_bin(nameurl.GetName(my_id.getLocalID())) + b'@' + strng.to_bin(platform.node())
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     elif self.proto == 'http':
         if not id_contact:
             default_host = strng.to_bin(misc.readExternalIP()) + b':' + strng.to_bin(str(settings.getHTTPPort()))
         options['host'] = id_contact or default_host
         options['http_port'] = settings.getHTTPPort()
     if _Debug:
         lg.out(8, 'network_transport.doStart connecting %s transport : %s' % (self.proto.upper(), options))
     self.interface.connect(options)
 def doStart(self, arg):
     """
     Action method.
     """
     options = {
         'idurl': my_id.getLocalID(),
     }
     id_contact = ''
     default_host = ''
     #         ident = my_id.getLocalIdentity()
     #         if ident:
     #             id_contact = ident.getContactsByProto().get(self.proto, '')
     #         if id_contact:
     #             assert id_contact.startswith(self.proto + '://')
     #             id_contact = id_contact.lstrip(self.proto + '://')
     if self.proto == 'tcp':
         if not id_contact:
             default_host = strng.to_bin(
                 misc.readExternalIP()) + b':' + strng.to_bin(
                     str(settings.getTCPPort()))
         options['host'] = id_contact or default_host
         options['tcp_port'] = settings.getTCPPort()
     elif self.proto == 'udp':
         if not id_contact:
             default_host = strng.to_bin(nameurl.GetName(
                 my_id.getLocalID())) + b'@' + strng.to_bin(platform.node())
         options['host'] = id_contact or default_host
         options['dht_port'] = settings.getDHTPort()
         options['udp_port'] = settings.getUDPPort()
     elif self.proto == 'proxy':
         pass
     elif self.proto == 'http':
         if not id_contact:
             default_host = strng.to_bin(
                 misc.readExternalIP()) + b':' + strng.to_bin(
                     str(settings.getHTTPPort()))
         options['host'] = id_contact or default_host
         options['http_port'] = settings.getHTTPPort()
     if _Debug:
         lg.out(
             8, 'network_transport.doStart connecting %s transport : %s' %
             (self.proto.upper(), options))
     self.interface.connect(options)
 def isNeedUPNP(self, *args, **kwargs):
     if not settings.enableUPNP():
         return False
     if driver.is_on('service_tcp_transport'):
         try:
             from transport.tcp import tcp_node
             if int(tcp_node.get_internal_port()) != int(settings.getTCPPort()):
                 return True
         except:
             lg.exc()
             return False
     return time.time() - self.last_upnp_time > 60 * 60
Example #8
0
def parseCommandLine():
    oparser = optparse.OptionParser()
    oparser.add_option("-d", "--debug", dest="debug", type="int", help="set debug level")
    oparser.set_default("debug", 10)
    oparser.add_option("-t", "--tcpport", dest="tcpport", type="int", help="specify port for TCP transport")
    oparser.set_default("tcpport", settings.getTCPPort())
    oparser.add_option("-u", "--udpport", dest="udpport", type="int", help="specify port for UDP transport")
    oparser.set_default("udpport", settings.getUDPPort())
    oparser.add_option("-p", "--dhtport", dest="dhtport", type="int", help="specify UDP port for DHT network")
    oparser.set_default("dhtport", settings.getDHTPort())
    oparser.add_option("-s", "--packetsize", dest="packetsize", type="int", help="set size of UDP datagrams")
    oparser.set_default("packetsize", 480)
    (options, args) = oparser.parse_args()
    return options, args
Example #9
0
 def build_contacts(self, id_obj):
     """
     """
     result = []
     nowip = misc.readExternalIP()
     result.append('tcp://%s:%s' % (nowip, str(settings.getTCPPort())))
     # TODO:
     #    # if IP is not external and upnp configuration was failed for some reasons
     #    # we may want to use another contact methods, NOT tcp
     #    if IPisLocal() and run_upnpc.last_result('tcp') != 'upnp-done':
     #        lg.out(4, 'p2p_connector.update_identity want to push tcp contact: local IP, no upnp ...')
     #        lid.pushProtoContact('tcp')
     if _Debug:
         lg.out(4, 'tcp_interface.build_contacts : %s' % str(result))
     return result
 def _update_next_proto():
     if len(protos_need_upnp) == 0:
         lg.out(_DebugLevel, 'network_connector.update_upnp done, sending "upnp-done" event')
         A('upnp-done')
         return
     if _Debug:
         lg.out(_DebugLevel, 'network_connector.UpdateUPNP._update_next_proto ' + str(protos_need_upnp))
     proto = protos_need_upnp.pop()
     protos_need_upnp.add(proto)
     port = -1
     if proto == 'tcp':
         port = settings.getTCPPort()
     if port > 0:
         d = threads.deferToThread(_call_upnp, port)
         d.addCallback(_upnp_proto_done, proto)
     else:
         reactor.callLater(0, _upnp_proto_done, proto)  # @UndefinedVariable
Example #11
0
def buildDefaultIdentity(name='', ip='', idurls=[]):
    """
    Use some local settings and config files to create some new identity.

    Nice to provide a user name or it will have a form like: [ip_address]_[date].
    """
    if not ip:
        ip = misc.readExternalIP()
    if not name:
        name = ip.replace('.', '-') + '_' + time.strftime('%M%S')
    lg.out(4, 'my_id.buildDefaultIdentity: %s %s' % (name, ip))
    # create a new identity object
    # it is stored in memory and another copy on disk drive
    ident = identity.identity(xmlsrc=identity.default_identity_src)
    # this is my IDURL address
    # you can have many IDURL locations for same identity
    # just need to keep all them synchronized
    # this is identity propagate procedure, see p2p/propagate.py
    if len(idurls) == 0:
        idurls.append(b'http://127.0.0.1/%s.xml' % strng.to_bin(name.lower()))
    for idurl in idurls:
        ident.sources.append(strng.to_bin(idurl.strip()))
    # create a full list of needed transport methods
    # to be able to accept incoming traffic from other nodes
    new_contacts, new_order = buildProtoContacts(ident)
    if len(new_contacts) == 0:
        if settings.enableTCP() and settings.enableTCPreceiving():
            new_contacts['tcp'] = b'tcp://' + strng.to_bin(
                ip) + b':' + strng.to_bin(str(settings.getTCPPort()))
            new_order.append('tcp')
        if settings.enableUDP() and settings.enableUDPreceiving():
            _, servername, _, _ = nameurl.UrlParse(ident.sources[0])
            new_contacts['udp'] = b'udp://' + strng.to_bin(
                name.lower()) + b'@' + strng.to_bin(servername)
            new_order.append('udp')
        if settings.enableHTTP() and settings.enableHTTPreceiving():
            new_contacts['http'] = b'http://' + strng.to_bin(
                ip) + b':' + strng.to_bin(str(settings.getHTTPPort()))
            new_order.append('http')
    # erase current contacts from my identity
    ident.clearContacts()
    # add contacts data to the local identity
    for proto in new_order:
        contact = new_contacts.get(proto, None)
        if contact is None:
            lg.warn('proto %s was not found in contacts' % proto)
            continue
        ident.setProtoContact(proto, contact)
    # set other info
    # ident.certificates = []
    ident.setDate(time.strftime('%b %d, %Y'))
    ident.setPostage(1)
    ident.setRevision(0)
    ident.setVersion('')  # TODO: put latest git commit hash here
    # update software version number
    # version_number = bpio.ReadTextFile(settings.VersionNumberFile()).strip()
    # repo, location = misc.ReadRepoLocation()
    # ident.version = (version_number.strip() + ' ' + repo.strip() + ' ' + bpio.osinfo().strip()).strip()
    # build a version info
    # vernum = bpio.ReadTextFile(settings.VersionNumberFile())
    # repo, location = misc.ReadRepoLocation()
    # ident.version = (vernum.strip() + ' ' + repo.strip() + ' ' + bpio.osinfo().strip()).strip()
    # put my public key in my identity
    ident.setPublicKey(key.MyPublicKey())
    # generate signature
    ident.sign()
    # validate new identity
    if not ident.Valid():
        lg.warn('generated identity is not valid !!!')
    return ident