Пример #1
0
def parse_address(local_address, str):
    check.check_is_af_inet_address(local_address)  #=@R19
    
    try:
        match = re.match(r"\s*(.+)\s*:\s*([0-9]+)\s*$", str)
        if match:
            ret = (socket.gethostbyname(match.group(1)),
                   string.atoi(match.group(2)))
        else:
            match = re.match(r"\s*([0-9]+)\s*$", str)
            if match:
                ret = (local_address[0],
                       string.atoi(match.group(1)))
            else:
                ret = (socket.gethostbyname(string.strip(str)),
                       settings.default_ports[0])
        
        check.check_is_af_inet_address(ret)  #=@E9
        # Proof: socket.gethostbyname returns a string, atoi returns an int,
        # settings.default_ports is a non-empty list of integers.
        # local_address is itself an af_inet_address (@R19), so its first
        # element is a string suitable for an af_inet_address.  local_address
        # is deeply immutable from @E11.
        return ret

    except:
        raise error.Error(_("Could not find peer.\n"+\
                            "Please give a valid IP address or machine name,\n"+\
                            "optionally followed by a colon and a port number"))
Пример #2
0
                def acq_change_thread(ns, acq, address, call_id, node):
                    check.check_is_af_inet_address(address)  #=@R29
                    
                    try:
                        result, subthread = try_address(acq,address,node)
                        yield 'wait',subthread
                        if not result[0]:
                            return
                    except error.Error:
                        return

                    #acq.lock.acquire()
                    #acq.status = status
                    #acq.lock.release()
                    ns.acquaintance_status_changed(acq, 'connect')
Пример #3
0
def identity_test_thread(address, key, the_node, id_test_result):
    #from node import Node
    # Test identity
    check.check_is_af_inet_address(address)
    #check.check_isinstance(the_node, Node)

    tester = utility.random_bytes(settings.name_bytes)

    ticket, template, wait = the_node.call(address, ('identity test',tester))
    if wait: yield 'call',(the_node,ticket)
    try:
        result = the_node.get_reply(ticket, template)
    except error.Error,err:
        print "error",err
        id_test_result.append(0)
        return 
Пример #4
0
    def handle(self, request, address,call_id):
        check.check_matches(request, (types.StringType,))  #=@R34
        check.check_is_af_inet_address(address)  #=@R31
        
        self.lock.acquire()
        try:
            if request[0] == 'chat look':
                return (not self.quiet, self.activity)
            if request[0] in ['chat message 2']:
                unpacked = safe_pickle.loads(request[1])
                # TODO check unpacked against template
                # TODO don't unpack twice (here and in receive task)
                sender = unpacked['from']
                recipients = unpacked['to']
                    
                for recipient in recipients:
                    if recipient[0] == self.app.name_server.public_key_name:
                        break
                    if recipient[2][:1] == '#' and \
                         self.channels.is_listening_to(recipient[2]) and \
                         sender[0] != self.app.name_server.public_key_name:
                        break
                else:
                    return None
            
                if not self.repeated(address,call_id):
                    if self.quiet:
                        new_item = (request, address, time.time())
                        check.check_matches(new_item,
                                            unread_message_list_item_tmpl)
                        # Proof: @R34,@R31, and not having modified request or
                        # address, and the relevant types being immutable
                        # (partly by @E11).  time.time() returns float.
                        # Relevance: @R.I15.
                        self.unread_message_list.append(new_item)
                        self.set_prompt()
                        del new_item
                    else:
                        self.receive(request,address,self.quiet,time.time())
                        # Proof of @R33: @R31; deep immutability by @E11.
                        # Proof of @R35: time.time() returns float.

                return (not self.quiet, self.activity)

        finally:
            self.lock.release()
Пример #5
0
    def handle(self, request,address,call_id):
        check.check_matches(request, (types.StringType,))
        check.check_is_af_inet_address(address)
        
        # Idempotence is a bugger

        if request[0] == 'data cache store' or \
             request[0] == 'data cache store multi':
            self.lock.acquire()
            try:
                if self.cached_items.has_key(request[1]):
                    if self.cached_items[request[1]].call == (address,call_id):
                        return None
                    return Error('already storing')

                if request[0] == 'data cache store':
                    names = [ request[2] ]
                else:
                    names = request[2]

                if len(names) > settings.max_cache_names:
                    return Error('too many names')
                
                item = Cache_item(names,request[3],request[4],(address,call_id))
 
                self.cached_items[request[1]] = item

                # here is the actual publish: redundancy is settings.cache_redundancy
                for name in names:
                    self.node.publish(name, request[3], settings.cache_redundancy)
            finally:
                self.lock.release()
            return None

        if request[0] == 'data cache remove':
            self.lock.acquire()
            try:
                lock = hash.hash_of(request[1])
                if self.cached_items.has_key(lock):
                    self.node.unpublish(self.cached_items[lock].data)
                    del self.cached_items[lock]
            finally:
                self.lock.release()

            return None
Пример #6
0
    def handle(self, request, ignored__address, call_id):
        check.check_matches(request, (types.StringType,))
        check.check_is_af_inet_address(ignored__address)
        
        if request[0] == 'gossip list':
            #TODO: Type checking, locking, oh, and this is really inefficient
            self.any_gossip_gets = 1

            list = [ ]
            for item in self.gossip[:]:
                list.append((to_fixed(item.distance(self.app.name_server)),
                             item.unit_decay_time,
                             item.signature))
            list.sort()
            return list[request[1]:request[2]]
        elif request[0] == 'gossip get':
            for item in self.gossip:
                if item.signature == request[1]:
                    return item.string
            return error.Error(_("No such wodge."))
Пример #7
0
    def handle(self, request, address, call_id):
        check.check_matches(request, (types.StringType,))
        check.check_is_af_inet_address(address)

        if request[0] == 'auction bid':
            name = request[1]
            bid = request[2]
            if self.auctions.has_key(name):
                print "auction found"
                if self.auctions_prices[name] < bid:
                    self.auctions_prices[name] = bid
                    return 'ok'
                else:
                    print "bid too low"
                    return 'bid too low'
            else:
                return 'error: no such auction'
            
            
        elif request[0] == 'auction list':

            list = self.auctions
            return list
Пример #8
0
    def __init__(self, host,password=None, transient_for=None):
        utility.Synchronous.__init__(self)

        if sys.platform == 'win32':
            self.read_stdout, self.write_stdin = _make_connection_win32(host,password)
        else:
            self.read_stdout, self.write_stdin = _make_connection_daemon(host,password)
        
        #On win32 newline is \n\r, confusion ensues
        #line = self.read_stdout.readline()
        line = ''
        while 1:
            char = self.read_stdout.read(1)
            if char == '\n' or not char:
                break
            line = line + char
    
        if line[:5] != 'PORT ':
            self.write_stdin.close()
            self.read_stdout.close()

            if sys.platform == 'win32':
                message = 'Attempt to start the proxy failed.\n\n' + \
                                    'Check the username, server name and password.\n\n' + \
                                    '(see "Help" for more information)'
            else:
                message = 'Attempt to start the proxy failed.\n\n'+\
                                    'Check your username, server name and password.'
            raise Error(message)

        self.address = ('127.0.0.1', string.atoi(line[5:]))

        self.broken = 0
        self.running = 1
        
        check.check_is_af_inet_address(self.address)  #=@E3
Пример #9
0
    def handle(self, request, address, call_id):
        check.check_matches(request, (types.StringType,))
        check.check_is_af_inet_address(address)

        if request[0] == 'download chunk':
            path, mtime = self.paths.get(request[1],(None,None))
            if not path:
                path, mtime = self.private_paths.get(request[1],(None,None))
                
            try:
                if not path or \
                     os.path.getmtime(path) != mtime:
                    return Error("no such file")
                file = open(path,'rb') 
            except IOError:
                return Error("no such file")

            if address[0] !='127.0.0.1'\
                   and address not in self.node.trusted_addresses \
                   and self.private_directory != ''\
                   and utility.is_subdir(path,self.private_directory):
                return Error("access denied")

            try:
                file.seek(request[2])
                return file.read(request[3])
            finally:
                file.close()

        elif request[0] == 'files available':

            if len(request) == 3:
                # this returns the keys of
                # all published files from all directories
                # regardless of the directory structure
                list = self.paths.keys()
            else:
                list = [ ]
                access_denied = 0
                directory_found = 0

                string_request = []
                for str in request[3]:
                    string_request.append(utility.force_string(str))

                if not self.roots:
                    return Error('No public directory')
                request_dir = apply(
                    os.path.join,
                    [os.path.abspath(self.roots[0][0])] + string_request)

                if address[0]=='127.0.0.1':
                    flags = flags_local
                else:
                    flags = flags_fast            
                    
                if os.path.exists(request_dir):
                    directory_found = 1

                if address[0]!='127.0.0.1' \
                       and address not in self.node.trusted_addresses\
                       and self.private_directory != ''\
                       and utility.is_subdir(request_dir,self.private_directory):
                    access_denied = 1
                    
                if not directory_found:
                    return Error("no such directory: %s"%request_dir)
                elif access_denied:
                    return Error("access denied")
                
                entry = build_entry(request_dir,None,flags,self)
                
                if entry:
                    if not entry.is_dir:
                        return Error("not a directory: "+request_dir)
                    for file in entry.files:
                        entry_2 = build_entry(file,None,flags,self)
                        if entry_2:
                            info = entry_2.info.copy()
                            info['path'] = request[3] + [ info['filename'] ]
                            list.append(info)

            return list[request[1]:request[2]]
Пример #10
0
    def handle(self, request, address,call_id):
        check.check_matches(request, (types.StringType,))
        check.check_is_af_inet_address(address)  #=@R30
        
        if request[0] == 'identity test':
            check.check_matches(request[1:], ('name',))
            
            return self.sign('identity test ' + request[1])
        
        elif request[0] == 'identity query':
            return self.get_info()
        elif request[0] == 'identity watch':
            self.lock.acquire()
            try:
                if address not in self.watchers:
                    self.watchers.append(address)
                status = self.status
            finally:
                self.lock.release()
            return status
        elif request[0] == 'identity abort':
            def abort_thread(self, address=address):
                id_test_result = []
                yield 'wait', identity_test_thread(address,self.public_key,self.node,id_test_result)
                if not id_test_result[0]:
                    print "error testing identity"
                    return
                self.aborted = 1
                self.app.shutdown(_('Reconnecting from different machine'))
            utility.start_thread(abort_thread(self))
            return None
        elif request[0] == 'identity connecting':
            if not (len(request) >= 2):
                return error.Error('Name_server.handle: identity connecting: expecting tuple of at least 2.')
            self.acquire_lock('get acq')
            try:
                acq = self.acquaintances.get(request[1])
            finally:
                self.release_lock('get acq')
            if acq is None:
                return error.Error(_("I don't know you."))
            else:
                #if len(request) > 2:
                #  status = request[2]
                #else:
                #  status = { }

                def acq_change_thread(ns, acq, address, call_id, node):
                    check.check_is_af_inet_address(address)  #=@R29
                    
                    try:
                        result, subthread = try_address(acq,address,node)
                        yield 'wait',subthread
                        if not result[0]:
                            return
                    except error.Error:
                        return

                    #acq.lock.acquire()
                    #acq.status = status
                    #acq.lock.release()
                    ns.acquaintance_status_changed(acq, 'connect')
                utility.start_thread(acq_change_thread(self, acq, address, call_id, self.node))
                # Proof of @R29: @R30; deeply immutable by @E11.

                return None

        elif request[0] == 'identity status changed':
            if not (len(request) >= 3):
                return error.Error('Name_server.handle: identity status changed: expecting tuple of at least 3.')
            self.lock.acquire()
            try:
                acq = self.acquaintances.get(request[1],None)
                if acq:
                    acq.lock.acquire()
                    try:
                        acq.status = request[2]
                    finally:
                        acq.lock.release()
                    self.acquaintance_status_changed(acq, 'status changed')
            finally:
                self.lock.release()
        elif request[0] == 'identity disconnecting':
            if not (len(request) >= 2):
                return error.Error('Name_server.handle: identity disconnecting: expecting tuple of at least 2.')
            self.lock.acquire()
            if address in self.watchers:
                self.watchers.remove(address)
            
            if self.acquaintances.has_key(request[1]):
                acq = self.acquaintances[request[1]]
                self.lock.release()
                if acq.disconnection(address):
                    self.acquaintance_status_changed(acq, 'disconnect', message=request[2])
                return None
            else:
                self.lock.release()
                return error.Error(_("I don't know you."))
Пример #11
0
def random_af_inet_address():
    ret = (random_nullless_string(), random_int())

    check.check_is_af_inet_address(ret)
    return ret