Example #1
0
 def _available_transports(self):
     from main import settings
     atransports = []
     if settings.enableTCP() and settings.enableTCPreceiving() and settings.enableTCPsending():
         atransports.append('service_tcp_transport')
     if settings.enableUDP() and settings.enableUDPreceiving() and settings.enableUDPsending():
         atransports.append('service_udp_transport')
     return atransports
Example #2
0
 def dependent_on(self):
     from main import settings
     depends = ['service_gateway',
                'service_identity_propagate', ]
     if settings.enableTCP():
         depends.append('service_tcp_transport')
     if settings.enableUDP():
         depends.append('service_udp_transport')
     return depends
 def _available_transports(self):
     from main import settings
     atransports = []
     if settings.enableTCP() and settings.enableTCPreceiving(
     ) and settings.enableTCPsending():
         atransports.append('service_tcp_transport')
     if settings.enableUDP() and settings.enableUDPreceiving(
     ) and settings.enableUDPsending():
         atransports.append('service_udp_transport')
     return atransports
    def dependent_on(self):
        from main import settings
        depends = ['service_gateway',
                   'service_identity_propagate', ]
        if settings.enableTCP():
            depends.append('service_tcp_transport')
        if settings.enableUDP():
            depends.append('service_udp_transport')
#         if settings.enablePROXY():
#             depends.append('service_proxy_transport')
        return depends
def UpdateUPNP():
    """
    Use ``lib.run_upnpc`` to configure UPnP device to create a port forwarding.
    """
    if _Debug:
        lg.out(_DebugLevel, 'network_connector.UpdateUPNP ')
    protos_need_upnp = set(['tcp', ])
    if not settings.enableTCP():
        # need to update only enabled protocols
        protos_need_upnp.discard('tcp')

    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

    def _call_upnp(port):
        # start messing with upnp settings
        # success can be false if you're behind a router that doesn't support upnp
        # or if you are not behind a router at all and have an external ip address
        from system import run_upnpc
        shutdowner.A('block')
        success, port = run_upnpc.update(port)
        shutdowner.A('unblock')
        return (success, port)

    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

    _update_next_proto()
Example #6
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
Example #7
0
 def _push(self):
     from transport import gateway
     if self.route:
         # if this packet is routed - send directly to route host
         gateway.send_file(
             strng.to_bin(self.route['remoteid']),
             strng.to_text(self.route['proto']),
             strng.to_bin(self.route['host']),
             self.filename,
             self.description,
             self,
         )
         self.items.append(
             WorkItem(strng.to_text(self.route['proto']),
                      strng.to_bin(self.route['host']), self.filesize))
         self.automat('items-sent')
         return
     # get info about his local IP
     localIP = identitycache.GetLocalIP(self.remote_idurl)
     workitem_sent = False
     if self.wide:
         # send to all his contacts
         for contactmethod in self.remote_identity.getContacts():
             proto, host = nameurl.IdContactSplit(contactmethod)
             if host.strip() and \
                     settings.transportIsEnabled(proto) and \
                     settings.transportSendingIsEnabled(proto) and \
                     gateway.can_send(proto) and \
                     gateway.is_installed(proto):
                 if proto == 'tcp' and localIP:
                     host = localIP
                 gateway.send_file(
                     strng.to_bin(self.remote_idurl),
                     strng.to_text(proto),
                     strng.to_bin(host),
                     self.filename,
                     self.description,
                     self,
                 )
                 self.items.append(
                     WorkItem(strng.to_text(proto), strng.to_bin(host),
                              self.filesize))
                 workitem_sent = True
         if not workitem_sent:
             self.automat('nothing-to-send')
             lg.warn('(wide) no supported protocols with %s' %
                     self.remote_idurl)
         else:
             self.automat('items-sent')
         return
     # send to one of his contacts,
     # now need to decide which transport to use
     # let's prepare his contacts first
     byproto = self.remote_identity.getContactsByProto()
     tcp_contact = None
     if settings.enableTCP() and settings.enableTCPsending():
         tcp_contact = byproto.get('tcp', None)
     udp_contact = None
     if settings.enableUDP() and settings.enableUDPsending():
         udp_contact = byproto.get('udp', None)
     http_contact = None
     if settings.enableHTTP() and settings.enableHTTPsending():
         http_contact = byproto.get('http', None)
     proxy_contact = None
     if settings.enablePROXY() and settings.enablePROXYsending():
         proxy_contact = byproto.get('proxy', None)
     working_protos = p2p_stats.peers_protos().get(self.remote_idurl, set())
     # tcp seems to be the most stable proto
     # now let's check if we know his local IP and
     # he enabled tcp in his settings to be able to receive packets from others
     # try to send to his local IP first, not external
     if tcp_contact and localIP:
         if gateway.is_installed('tcp') and gateway.can_send(proto):
             proto, host, port, fn = nameurl.UrlParse(tcp_contact)
             if port:
                 host = localIP + ':' + str(port)
             gateway.send_file(strng.to_bin(self.remote_idurl),
                               strng.to_text(proto), strng.to_bin(host),
                               self.filename, self.description, self)
             self.items.append(
                 WorkItem(strng.to_text(proto), strng.to_bin(host),
                          self.filesize))
             self.automat('items-sent')
             return
     # tcp is the best proto - if it is working - this is the best case!!!
     if tcp_contact and 'tcp' in working_protos:
         proto, host, port, fn = nameurl.UrlParse(tcp_contact)
         if host.strip() and gateway.is_installed(
                 proto) and gateway.can_send(proto):
             if port:
                 host = host + ':' + str(port)
             gateway.send_file(strng.to_bin(self.remote_idurl),
                               strng.to_text(proto), strng.to_bin(host),
                               self.filename, self.description)
             self.items.append(
                 WorkItem(strng.to_text(proto), strng.to_bin(host),
                          self.filesize))
             self.automat('items-sent')
             return
     # udp contact
     if udp_contact and 'udp' in working_protos:
         proto, host = nameurl.IdContactSplit(udp_contact)
         if host.strip() and gateway.is_installed(
                 'udp') and gateway.can_send(proto):
             gateway.send_file(strng.to_bin(self.remote_idurl),
                               strng.to_text(proto), strng.to_bin(host),
                               self.filename, self.description, self)
             self.items.append(
                 WorkItem(strng.to_text(proto), strng.to_bin(host),
                          self.filesize))
             self.automat('items-sent')
             return
     # http contact
     if http_contact and 'http' in working_protos:
         proto, host, port, _ = nameurl.UrlParse(http_contact)
         if host.strip() and gateway.is_installed(
                 proto) and gateway.can_send(proto):
             if port:
                 host = host + ':' + str(port)
             gateway.send_file(strng.to_bin(self.remote_idurl),
                               strng.to_text(proto), strng.to_bin(host),
                               self.filename, self.description, self)
             self.items.append(
                 WorkItem(strng.to_text(proto), strng.to_bin(host),
                          self.filesize))
             self.automat('items-sent')
             return
     # proxy contact - he may use other node to receive and send packets
     if proxy_contact and 'proxy' in working_protos:
         proto, host = nameurl.IdContactSplit(proxy_contact)
         if host.strip() and gateway.is_installed(
                 'proxy') and gateway.can_send(proto):
             gateway.send_file(strng.to_bin(self.remote_idurl),
                               strng.to_text(proto), strng.to_bin(host),
                               self.filename, self.description, self)
             self.items.append(
                 WorkItem(strng.to_text(proto), strng.to_bin(host),
                          self.filesize))
             self.automat('items-sent')
             return
     # finally use the first proto we supported if we can not find the best preferable method
     for contactmethod in self.remote_identity.getContacts():
         proto, host, port, fn = nameurl.UrlParse(contactmethod)
         if port:
             host = host + ':' + str(port)
         # if method exist but empty - don't use it
         if host.strip():
             # try sending with tcp even if it is switched off in the settings
             if gateway.is_installed(proto) and gateway.can_send(proto):
                 if settings.enableTransport(
                         proto) and settings.transportSendingIsEnabled(
                             proto):
                     gateway.send_file(strng.to_bin(self.remote_idurl),
                                       strng.to_text(proto),
                                       strng.to_bin(host), self.filename,
                                       self.description, self)
                     self.items.append(
                         WorkItem(strng.to_text(proto), strng.to_bin(host),
                                  self.filesize))
                     self.automat('items-sent')
                     return
     self.automat('nothing-to-send')
     lg.warn('no supported protocols with %s : %s %s %s, byproto:%s' %
             (self.remote_idurl, tcp_contact, udp_contact, working_protos,
              str(byproto)))
Example #8
0
 def _push(self):
     if self.route:
         # if this packet is routed - send directly to route host
         gateway.send_file(
             self.route["remoteid"], self.route["proto"], self.route["host"], self.filename, self.description
         )
         self.items.append(WorkItem(self.route["proto"], self.route["host"], self.filesize))
         self.automat("items-sent")
         return
     # get info about his local IP
     localIP = identitycache.GetLocalIP(self.remote_idurl)
     workitem_sent = False
     if self.wide:
         # send to all his contacts
         for contactmethod in self.remote_identity.getContacts():
             proto, host = nameurl.IdContactSplit(contactmethod)
             if (
                 host.strip()
                 and settings.transportIsEnabled(proto)
                 and settings.transportSendingIsEnabled(proto)
                 and gateway.can_send(proto)
                 and gateway.is_installed(proto)
             ):
                 if proto == "tcp" and localIP:
                     host = localIP
                 gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
                 self.items.append(WorkItem(proto, host, self.filesize))
                 workitem_sent = True
         if not workitem_sent:
             self.automat("nothing-to-send")
             lg.warn("(wide) no supported protocols with %s" % self.remote_idurl)
         else:
             self.automat("items-sent")
         return
     # send to one of his contacts,
     # now need to decide which transport to use
     # let's prepare his contacts first
     byproto = self.remote_identity.getContactsByProto()
     tcp_contact = None
     if settings.enableTCP() and settings.enableTCPsending():
         tcp_contact = byproto.get("tcp", None)
     udp_contact = None
     if settings.enableUDP() and settings.enableUDPsending():
         udp_contact = byproto.get("udp", None)
     proxy_contact = None
     if settings.enablePROXY() and settings.enablePROXYsending():
         proxy_contact = byproto.get("proxy", None)
     working_protos = stats.peers_protos().get(self.remote_idurl, set())
     # tcp seems to be the most stable proto
     # now let's check if we know his local IP and
     # he enabled tcp in his settings to be able to receive packets from others
     # try to send to his local IP first, not external
     if tcp_contact and localIP:
         if gateway.is_installed("tcp") and gateway.can_send(proto):
             proto, host, port, fn = nameurl.UrlParse(tcp_contact)
             if port:
                 host = localIP + ":" + str(port)
             gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
             self.items.append(WorkItem(proto, host, self.filesize))
             self.automat("items-sent")
             return
     # tcp is the best proto - if it is working - this is the best case!!!
     if tcp_contact and "tcp" in working_protos:
         proto, host, port, fn = nameurl.UrlParse(tcp_contact)
         if host.strip() and gateway.is_installed(proto) and gateway.can_send(proto):
             if port:
                 host = host + ":" + str(port)
             gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
             self.items.append(WorkItem(proto, host, self.filesize))
             self.automat("items-sent")
             return
     # udp contact
     if udp_contact and "udp" in working_protos:
         proto, host = nameurl.IdContactSplit(udp_contact)
         if host.strip() and gateway.is_installed("udp") and gateway.can_send(proto):
             gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
             self.items.append(WorkItem(proto, host, self.filesize))
             self.automat("items-sent")
             return
     # proxy contact - he may use other node to receive and send packets
     if proxy_contact and "proxy" in working_protos:
         proto, host = nameurl.IdContactSplit(proxy_contact)
         if host.strip() and gateway.is_installed("proxy") and gateway.can_send(proto):
             gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
             self.items.append(WorkItem(proto, host, self.filesize))
             self.automat("items-sent")
             return
     # finally use the first proto we supported if we can not find the best preferable method
     for contactmethod in self.remote_identity.getContacts():
         proto, host, port, fn = nameurl.UrlParse(contactmethod)
         if port:
             host = host + ":" + str(port)
         # if method exist but empty - don't use it
         if host.strip():
             # try sending with tcp even if it is switched off in the settings
             if gateway.is_installed(proto) and gateway.can_send(proto):
                 if settings.enableTransport(proto) and settings.transportSendingIsEnabled(proto):
                     gateway.send_file(self.remote_idurl, proto, host, self.filename, self.description)
                     self.items.append(WorkItem(proto, host, self.filesize))
                     self.automat("items-sent")
                     return
     self.automat("nothing-to-send")
     lg.warn(
         "no supported protocols with %s : %s %s %s, byproto:%s"
         % (self.remote_idurl, tcp_contact, udp_contact, working_protos, str(byproto))
     )