示例#1
0
def SendSingleCustomer(idurl, response_callback=None):
    dhnio.Dprint(6, "identitypropagate.SendSingleCustomer [%s]" % nameurl.GetName(idurl))
    MyID = misc.getLocalID()
    packet = dhnpacket.dhnpacket(commands.Identity(), MyID, MyID, MyID, misc.getLocalIdentity().serialize(), idurl)
    transport_control.outboxNoAck(packet)
    if response_callback is not None:
        transport_control.RegisterInterest(response_callback, packet.RemoteID, packet.PacketID)
def CreateNewIdentity():
    global _NewIdentity
    
    dhncrypto.InitMyKey()
    misc.loadLocalIdentity()
    if misc.isLocalIdentityReady():
        try:
            lid = misc.getLocalIdentity()
            lid.sign()
            # misc.setLocalIdentity(lid)
            # misc.saveLocalIdentity()
            valid = lid.Valid()
        except:
            valid = False
            dhnio.DprintException()
        if valid:
            _NewIdentity = lid
            return
        dhnio.Dprint(2, 'identity_registrator.CreateNewIdentity existing local identity is not VALID')

    login = dhnio.ReadTextFile(settings.UserNameFilename())
    externalIP = dhnio.ReadTextFile(settings.ExternalIPFilename())
    localIP = dhnio.ReadTextFile(settings.LocalIPFilename())

    dhnio.Dprint(4, 'identity_registrator.CreateNewIdentity %s %s ' % (login, externalIP))
    
    idurl = 'http://'+settings.IdentityServerName()+'/'+login.lower()+'.xml'
    ident = identity.identity( )
    ident.sources.append(idurl)

    cdict = {}
    if settings.enableTCP():
        cdict['tcp'] = 'tcp://'+externalIP+':'+settings.getTCPPort()
    if settings.enableCSpace() and transport_control._TransportCSpaceEnable:
        cdict['cspace'] = 'cspace://'
        if settings.getCSpaceKeyID() != '':
            cdict['cspace'] += settings.getCSpaceKeyID()
    if settings.enableUDP() and transport_control._TransportUDPEnable:
        if stun.getUDPClient() is not None:
            if stun.getUDPClient().externalAddress is not None: # _altStunAddress
                cdict['udp'] = 'udp://'+stun.getUDPClient().externalAddress[0]+':'+str(stun.getUDPClient().externalAddress[1])
        
    for c in misc.validTransports:
        if cdict.has_key(c):
            ident.contacts.append(cdict[c])

    ident.publickey = dhncrypto.MyPublicKey()
    ident.date = time.ctime() #time.strftime('%b %d, %Y')

    revnum = dhnio.ReadTextFile(settings.RevisionNumberFile()).strip()
    repo, location = misc.ReadRepoLocation()
    ident.version = (revnum.strip() + ' ' + repo.strip() + ' ' + dhnio.osinfo().strip()).strip()

    ident.sign()
    
    dhnio.WriteFile(settings.LocalIdentityFilename()+'.new', ident.serialize())
    
    _NewIdentity = ident
示例#3
0
def SendIdentity(doAck=False):
    """
    Register our identity with Central server.
    """
    LocalIdentity = misc.getLocalIdentity()
    dhnio.Dprint(4, "central_service.SendIdentity") #' version=[%s] contacts=[%s]" % (str(LocalIdentity.version), str(LocalIdentity.contacts)))
    data = LocalIdentity.serialize()
    ret = send2central(commands.Identity(), data, doAck, misc.getLocalID())
    return ret
示例#4
0
def RequestIdentity(request):
    dhnio.Dprint(6, "p2p_service.RequestIdentity starting")
    MyID = misc.getLocalID()
    RemoteID = request.OwnerID
    PacketID = request.PacketID
    identitystr = misc.getLocalIdentity().serialize()
    dhnio.Dprint(12, "p2p_service.RequestIdentity returning ")
    result = dhnpacket.dhnpacket(commands.Identity(), MyID, MyID, PacketID, identitystr, RemoteID)
    transport_control.outboxNoAck(result)
示例#5
0
def SendRequestMarketList(doAck=True, packetID=None):
    """
    Send my "Identity" packet to the Market server to request a list if my opened bids and offers.
    """
    LocalIdentity = misc.getLocalIdentity()
    dhnio.Dprint(4, "central_service.SendRequestMarketList")
    data = LocalIdentity.serialize()
    if packetID is None:
        packetID = packetid.UniqueID()
    # transport_control.RegisterInterest(MarketListAck, settings.MarketServerID(), packetID)
    return send2market(commands.Identity(), data, doAck, packetID)
示例#6
0
 def _stop_transports():
     stoplist = []
     for proto in transport_control.ListSupportedProtocols():
         contact = misc.getLocalIdentity().getProtoContact(proto)
         if contact is None:
             dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport %s because not present in local identity' % proto)
             stoplist.append(transport_control.StopProtocol(proto))
             continue
         proto_, host, port, filename = nameurl.UrlParse(contact)
         if host.strip() == '':
             continue
         opts = transport_control.ProtocolOptions(proto)
         if opts[0].strip() == '':
             continue
         if proto != proto_:
             dhnio.Dprint(8, 'p2p_connector.UpdateTransports WARNING identity contact is %s, but proto is %s' % (contact, proto))
             continue
         #---tcp---
         if proto == 'tcp':
             if opts[0] != host:
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [tcp] because IP changed')
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
             if opts[1] != port:
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [tcp] because port changed')
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
         #---cspace---
         if proto == 'cspace':
             if opts[0] != host:
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [cspace] because keyID changed: %s to %s' % (
                     host, opts[0]))
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
         #---udp---
         if proto == 'udp':
             if opts[0] != host:
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [udp] because IP were changed')
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
             if opts[1] != port:
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [udp] because port were changed')
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
             if 'transport.transport-udp.transport-udp-port' in changes and settings.enableUDP():
                 dhnio.Dprint(4, 'p2p_connector.UpdateTransports want to stop transport [udp] because port were changed by user')
                 stoplist.append(transport_control.StopProtocol(proto))
                 continue
     #need to wait before all listeners will be stopped
     return DeferredList(stoplist)
示例#7
0
def SendServers():
    sendfile, sendfilename = tmpfile.make("propagate")
    os.close(sendfile)
    LocalIdentity = misc.getLocalIdentity()
    dhnio.WriteFile(sendfilename, LocalIdentity.serialize())
    dlist = []
    for idurl in LocalIdentity.sources:
        # sources for out identity are servers we need to send to
        protocol, host, port, filename = nameurl.UrlParse(idurl)
        port = settings.IdentityServerPort()
        d = Deferred()
        transport_tcp.sendsingle(sendfilename, host, port, do_status_report=False, result_defer=d, description='Identity')
        dlist.append(d) 
    dl = DeferredList(dlist, consumeErrors=True)
    return dl
示例#8
0
def DoWeUseTheBestProto():
    global _WorkingProtocols
    #dhnio.Dprint(4, 'p2p_connector.DoWeUseTheBestProto _WorkingProtocols=%s' % str(_WorkingProtocols))
    #if no incomming traffic - do nothing
    if len(_WorkingProtocols) == 0:
        return True
    lid = misc.getLocalIdentity()
    order = lid.getProtoOrder()
    #if no protocols in local identity - do nothing
    if len(order) == 0:
        return True
    first = order[0]
    #if first contact in local identity is not working yet
    #but there is another working methods - switch first method
    if first not in _WorkingProtocols:
        dhnio.Dprint(2, 'p2p_connector.DoWeUseTheBestProto first contact (%s) is not working!   _WorkingProtocols=%s' % (first, str(_WorkingProtocols)))
        return False
    #if tcp contact is on first place and it is working - we are VERY HAPPY! - no need to change anything - return False
    if first == 'tcp' and 'tcp' in _WorkingProtocols:
        return True
    #but if tcp method is not the first and it works - we want to TURN IT ON! - return True
    if first != 'tcp' and 'tcp' in _WorkingProtocols:
        dhnio.Dprint(2, 'p2p_connector.DoWeUseTheBestProto tcp is not first but it works _WorkingProtocols=%s' % str(_WorkingProtocols))
        return False
    #if we are using cspace and it is working - this is fantastic!
    if transport_control._TransportCSpaceEnable:
        if first == 'cspace' and 'cspace' in _WorkingProtocols:
            return True
    #if we are using udp and it is working - not so bad
    if transport_control._TransportUDPEnable:
        if first == 'udp' and 'udp' in _WorkingProtocols:
            return True
    #cspace seems to be working and first contact is not working - so switch to cspace
    if transport_control._TransportCSpaceEnable:
        if first != 'cspace' and 'cspace' in _WorkingProtocols:
            dhnio.Dprint(2, 'p2p_connector.DoWeUseTheBestProto cspace is not first but it works _WorkingProtocols=%s' % str(_WorkingProtocols))
            return False
    #udp is working - we ca use it if all others is failed
    if transport_control._TransportUDPEnable:
        if first != 'udp' and 'udp' in _WorkingProtocols:
            dhnio.Dprint(2, 'p2p_connector.DoWeUseTheBestProto udp is not first but it works _WorkingProtocols=%s' % str(_WorkingProtocols))
            return False
    #in other cases - do nothing
    return True
示例#9
0
def SendToID(idurl, AckHandler=None, Payload=None, NeedAck=False, wide=False):
    dhnio.Dprint(8, "identitypropagate.SendToID [%s] NeedAck=%s" % (nameurl.GetName(idurl), str(NeedAck)))
    thePayload = Payload
    if thePayload is None:
        thePayload = misc.getLocalIdentity().serialize()
    packet = dhnpacket.dhnpacket(
        commands.Identity(),
        misc.getLocalID(), #MyID,
        misc.getLocalID(), #MyID,
        misc.getLocalID(), #PacketID,
        thePayload,
        idurl)
    if AckHandler is not None:
        transport_control.RegisterInterest(AckHandler, packet.RemoteID, packet.PacketID)
    transport_control.outbox(packet, NeedAck, wide)
    if wide:
        # this is a ping packet - need to clear old info
        transport_control.ErasePeerProtosStates(idurl)
        transport_control.EraseMyProtosStates(idurl)
示例#10
0
def SlowSendCustomers(delay=1):
    global _SlowSendIsWorking
    if _SlowSendIsWorking:
        dhnio.Dprint(8, "identitypropagate.SlowSendCustomers  slow send is working at the moment. skip.")
        return
    dhnio.Dprint(8, "identitypropagate.SlowSendCustomers delay=%s" % str(delay))

    def _send(index, payload, delay):
        global _SlowSendIsWorking
        idurl = contacts.getCustomerID(index)
        if not idurl:
            _SlowSendIsWorking = False
            return
        transport_control.ClearAliveTime(idurl)
        SendToID(idurl, Payload=payload, wide=True)
        reactor.callLater(delay, _send, index+1, payload, delay)

    _SlowSendIsWorking = True
    payload = misc.getLocalIdentity().serialize()
    _send(0, payload, delay)
示例#11
0
def SendToIDs(idlist, AckHandler=None, wide=False):
    dhnio.Dprint(8, "identitypropagate.SendToIDs to %d users" % len(idlist))
    MyID = misc.getLocalID()
    PacketID = MyID
    LocalIdentity = misc.getLocalIdentity()
    Payload = LocalIdentity.serialize()
    Hash = dhncrypto.Hash(Payload)
    alreadysent = set()
    for contact in idlist:
        if not contact:
            continue
        if contact in alreadysent:
            # just want to send once even if both customer and supplier
            continue
        found_previous_packets = 0
        for transfer_id in transport_control.transfers_by_idurl(contact):
            ti = transport_control.transfer_by_id(transfer_id)
            if ti and ti.description.count('Identity'):
                found_previous_packets += 1
                break
        if found_previous_packets >= 3:
            dhnio.Dprint(8, '        skip sending to %s' % contact)
            continue            
        packet = dhnpacket.dhnpacket(
            commands.Identity(),
            misc.getLocalID(), #MyID,
            misc.getLocalID(), #MyID,
            misc.getLocalID(), #PacketID,
            Payload,
            contact)
        dhnio.Dprint(8, "        sending [Identity] to %s" % nameurl.GetName(contact))
        if AckHandler is not None:
            transport_control.RegisterInterest(AckHandler, packet.RemoteID, packet.PacketID)
        transport_control.outboxNoAck(packet, wide)
        if wide:
            # this is a ping packet - need to clear old info
            transport_control.ErasePeerProtosStates(contact)
            transport_control.EraseMyProtosStates(contact)
        alreadysent.add(contact)
    del alreadysent
示例#12
0
def PopWorkingProto():
    global _WorkingProtocols
    if len(_WorkingProtocols) == 0:
        return
    lid = misc.getLocalIdentity()
    order = lid.getProtoOrder()
    first = order[0]
    wantedproto = ''
    #if first contact in local identity is not working yet
    #but there is another working methods - switch first method
    if first not in _WorkingProtocols:
        #take (but not remove) any item from the set
        wantedproto = _WorkingProtocols.pop()
        _WorkingProtocols.add(wantedproto)
    # if q2q method is not the first but it works - switch to q2q
    # disabled because we do not use q2q now
    # if first != 'q2q' and 'q2q' in _WorkingProtocols:
    #     wantedproto = 'q2q'
    #if udp method is not the first but it works - switch to udp
    if transport_control._TransportUDPEnable:
        if first != 'udp' and 'udp' in _WorkingProtocols:
            wantedproto = 'udp'
    #if cspace method is not the first but it works - switch to cspace
    if transport_control._TransportCSpaceEnable:
        if first != 'cspace' and 'cspace' in _WorkingProtocols:
            wantedproto = 'cspace'
    #if tcp method is not the first but it works - switch to tcp
    if first != 'tcp' and 'tcp' in _WorkingProtocols:
        wantedproto = 'tcp'
    dhnio.Dprint(4, 'p2p_connector.PopWorkingProto will pop %s contact   order=%s _WorkingProtocols=%s' % (wantedproto, str(order), str(_WorkingProtocols)))
    # now move best proto on the top
    # other users will use this method to send to us
    lid.popProtoContact(wantedproto)
    # save local id
    # also need to propagate our identity
    # other users must know our new contacts
    misc.setLocalIdentity(lid)
    misc.saveLocalIdentity() 
示例#13
0
 def _start_transports():
     startlist = []
     for contact in misc.getLocalIdentity().getContacts():
         proto, host, port, filename = nameurl.UrlParse(contact)
         opts = transport_control.ProtocolOptions(proto)
         if not transport_control.ProtocolIsSupported(proto):
             if settings.transportIsEnabled(proto) and settings.transportIsInstalled(proto) and settings.transportReceivingIsEnabled(proto):
                 #---tcp---
                 if proto == 'tcp':
                     def _tcp_started(l, opts):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._tcp_started')
                         if l is not None:
                             transport_control.StartProtocol('tcp', l, opts[0], opts[1], opts[2])
                         return l
                     def _tcp_failed(x):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._tcp_failed WARNING: '+str(x))
                         return x
                     def _start_tcp(options):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._start_tcp on port %d' % int(options[1]))
                         d = transport_tcp.receive(int(options[1]))
                         d.addCallback(_tcp_started, options)
                         d.addErrback(_tcp_failed)
                         startlist.append(d)
                     def _upnp_result(result, options):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._upnp_result %s' % str(result))
                         if result is not None:
                             options[1] = str(result[1])
                         _start_tcp(options)
                     def _run_upnpc(port):
                         shutdowner.A('block')
                         run_upnpc.update(port)
                         shutdowner.A('unblock')
                     externalIP = misc.readExternalIP() 
                     if opts is None:
                         opts = (externalIP, '', '')
                     opts = list(opts)
                     opts[0] = externalIP
                     opts[1] = settings.getTCPPort()
                     if settings.enableUPNP():
                         d = maybeDeferred(_run_upnpc, int(opts[1]))
                         d.addCallback(_upnp_result, opts)
                     else:
                         _start_tcp(opts)
                 #---cspace---
                 elif proto == 'cspace' and transport_control._TransportCSpaceEnable:
                     def _cspace_started(x, opts):
                         if not transport_cspace.registered():
                             dhnio.Dprint(4, 'p2p_connector.UpdateTransports._cspace_started WARNING not registered: ' + str(x))
                             return x
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._cspace_started')
                         keyID = transport_cspace.keyID()
                         settings.setCSpaceKeyID(keyID)
                         opts[0] = keyID
                         l = transport_cspace.getListener()
                         transport_control.StartProtocol('cspace', l, opts[0], opts[1], opts[2])
                         return x
                     if opts is None:
                         opts = (settings.getCSpaceKeyID(), '', '')
                     opts = list(opts)
                     d = transport_cspace.init().addBoth(_cspace_started, opts)
                     startlist.append(d)
                 #---udp---
                 elif proto == 'udp' and transport_control._TransportUDPEnable:
                     def _udp_start(x, opts):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._udp_start')
                         if opts is None:
                             opts = (stun.getUDPClient().externalAddress[0], str(stun.getUDPClient().externalAddress[1]), '')
                         opts = list(opts)
                         opts[0] = stun.getUDPClient().externalAddress[0]
                         opts[1] = str(stun.getUDPClient().externalAddress[1])
                         transport_udp.init(stun.getUDPClient())
                         l = transport_udp.getListener()
                         if l is not None:
                             transport_control.StartProtocol('udp', l, opts[0], opts[1], opts[2])
                         return x
                     def _udp_failed(x):
                         dhnio.Dprint(4, 'p2p_connector.UpdateTransports._udp_failed')
                         return x
                     if stun.getUDPClient() is None or stun.getUDPClient().externalAddress is None:
                         d = stun.stunExternalIP(
                             close_listener=False, 
                             internal_port=settings.getUDPPort(), 
                             block_marker=shutdowner.A)
                     else:
                         d = succeed('')
                     d.addCallback(_udp_start, opts)
                     d.addErrback(_udp_failed)
                     startlist.append(d)
                     
     #need to wait before all listeners will be started
     return DeferredList(startlist)
示例#14
0
def UpdateIdentity():
    global _RevisionNumber
    global _WorkingProtocols

    #getting local identity
    lid = misc.getLocalIdentity()
    nowip = misc.readExternalIP()
    order = lid.getProtoOrder()
    lid.clearContacts()

    #prepare contacts data
    cdict = {}
    cdict['tcp'] = 'tcp://'+nowip+':'+settings.getTCPPort()
    if transport_control._TransportSSHEnable:
        cdict['ssh'] = 'ssh://'+nowip+':'+settings.getSSHPort()
    if transport_control._TransportHTTPEnable:
        cdict['http'] = 'http://'+nowip+':'+settings.getHTTPPort()
    if transport_control._TransportQ2QEnable:
        cdict['q2q'] = 'q2q://'+settings.getQ2Quserathost()
    if transport_control._TransportEmailEnable:
        cdict['email'] = 'email://'+settings.getEmailAddress()
    if transport_control._TransportCSpaceEnable:
        cdict['cspace'] = 'cspace://'+settings.getCSpaceKeyID()
    if transport_control._TransportUDPEnable:
        if stun.getUDPClient() is None or stun.getUDPClient().externalAddress is None:
            cdict['udp'] = 'udp://'+nowip+':'+settings.getUDPPort()
        else:
            cdict['udp'] = 'udp://'+stun.getUDPClient().externalAddress[0]+':'+str(stun.getUDPClient().externalAddress[1])

    #making full order list
    for proto in cdict.keys():
        if proto not in order:
            order.append(proto)

    #add contacts data to the local identity
    #check if some transport is not installed
    for proto in order:
        if settings.transportIsEnabled(proto) and settings.transportReceivingIsEnabled(proto):
            contact = cdict.get(proto, None)
            if contact is not None:
                lid.setProtoContact(proto, contact)
        else:
            # if protocol is disabled - mark this
            # because we may want to turn it on in the future
            _WorkingProtocols.discard(proto)
            
    #misc.setLocalIdentity(lid)

    del order

#    #if IP is not external and upnp configuration was failed for some reasons
#    #we want to use another contact methods, NOT tcp or ssh
#    if IPisLocal() and run_upnpc.last_result('tcp') != 'upnp-done':
#        dhnio.Dprint(4, 'p2p_connector.update_identity want to push tcp contact: local IP, no upnp ...')
#        lid.pushProtoContact('tcp')
#        misc.setLocalIdentity(lid)

    #update software version number
    revnum = _RevisionNumber.strip()
    repo, location = misc.ReadRepoLocation()
    lid.version = (revnum.strip() + ' ' + repo.strip() + ' ' + dhnio.osinfo().strip()).strip()
    
    #generate signature with changed content
    lid.sign()
    
    #remember the identity
    misc.setLocalIdentity(lid)

    #finally saving local identity
    misc.saveLocalIdentity()
    dhnio.Dprint(4, 'p2p_connector.UpdateIdentity')
    dhnio.Dprint(4, '    version: %s' % str(lid.version))
    dhnio.Dprint(4, '    contacts: %s' % str(lid.contacts))