How to use foolscap - 10 common examples

To help you get started, we’ve selected a few foolscap examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github warner / foolscap / foolscap / negotiate.py View on Github external
def handlePLAINTEXTServer(self, header):
        # the client sends us a GET message
        lines = header.split("\r\n")
        if not lines[0].startswith("GET "):
            raise BananaError("not right")
        command, url, version = lines[0].split()
        if not url.startswith("/id/"):
            # probably a web browser
            raise BananaError("not right")
        targetTubID = url[4:]
        self.log("handlePLAINTEXTServer: targetTubID='%s'" % targetTubID,
                 level=NOISY)
        if targetTubID == "":
            targetTubID = None
        if isSubstring("Upgrade: TLS/1.0\r\n", header):
            wantEncrypted = True
        else:
            wantEncrypted = False
        self.log("handlePLAINTEXTServer: wantEncrypted=%s" % wantEncrypted,
                 level=NOISY)
        # we ignore the rest of the lines

        if wantEncrypted and not crypto_available:
            # this is a confused client, or a bad URL: if we don't have
            # crypto, we couldn't have created a pb:// URL.
github warner / foolscap / foolscap / negotiate.py View on Github external
# parse the decision here, create the connection parameters dict
        ver = int(decision['banana-decision-version'])
        vocab_index_string = decision.get('initial-vocab-table-index')
        if vocab_index_string:
            vocab_index, vocab_hash = vocab_index_string.split()
            vocab_index = int(vocab_index)
        else:
            vocab_index = 0
        check_inrange(self.initialVocabTableRange[0],
                      self.initialVocabTableRange[1],
                      vocab_index, "initial vocab table index")
        our_hash = vocab.hashVocabTable(vocab_index)
        if vocab_index > 0 and our_hash != vocab_hash:
            msg = ("Our hash for vocab-table-index %d (%s) does not match "
                   "your hash (%s)" % (vocab_index, our_hash, vocab_hash))
            raise NegotiationError(msg)

        if self.theirTubRef in self.tub.brokers:
            # we're the slave, so we need to drop our existing connection and
            # use the one picked by the master
            self.log("master told us to use a new connection, "
                     "so we must drop the existing one", level=UNUSUAL)
            err = DeadReferenceError("replaced by a new connection")
            why = Failure(err)
            self.tub.brokers[self.theirTubRef].shutdown(why)

        current_connection = decision.get('current-connection')
        if current_connection:
            tubID = self.theirTubRef.getTubID()
            if tubID != "":
                self.tub.slave_table[tubID] = tuple(current_connection.split())
        else:
github warner / foolscap / foolscap / negotiate.py View on Github external
the connection parameters we will use ourselves.

            - We are the master, we can't accomodate their request: raise
            NegotiationError

            - We are not the master: DECISION is None
        """

        self.log("evaluateHello(isClient=%s): offer=%s" %
                 (self.isClient, offer))
        if not offer.has_key('banana-negotiation-range'):
            if offer.has_key('banana-negotiation-version'):
                msg = ("Peer is speaking foolscap-0.0.5 or earlier, "
                       "which is not compatible with this version. "
                       "Please upgrade the peer.")
                raise NegotiationError(msg)
            raise NegotiationError("No valid banana-negotiation sequence seen")
        min_s, max_s = offer['banana-negotiation-range'].split()
        theirMinVer = int(min_s)
        theirMaxVer = int(max_s)
        # best_overlap() might raise a NegotiationError
        best = best_overlap(self.minVersion, self.maxVersion,
                            theirMinVer, theirMaxVer,
                            "banana version")

        negfunc = getattr(self, "evaluateNegotiationVersion%d" % best)
        self.decision_version = best
        return negfunc(offer)
github warner / foolscap / foolscap / negotiate.py View on Github external
- We are the master, we can't accomodate their request: raise
            NegotiationError

            - We are not the master: DECISION is None
        """

        self.log("evaluateHello(isClient=%s): offer=%s" %
                 (self.isClient, offer))
        if not offer.has_key('banana-negotiation-range'):
            if offer.has_key('banana-negotiation-version'):
                msg = ("Peer is speaking foolscap-0.0.5 or earlier, "
                       "which is not compatible with this version. "
                       "Please upgrade the peer.")
                raise NegotiationError(msg)
            raise NegotiationError("No valid banana-negotiation sequence seen")
        min_s, max_s = offer['banana-negotiation-range'].split()
        theirMinVer = int(min_s)
        theirMaxVer = int(max_s)
        # best_overlap() might raise a NegotiationError
        best = best_overlap(self.minVersion, self.maxVersion,
                            theirMinVer, theirMaxVer,
                            "banana version")

        negfunc = getattr(self, "evaluateNegotiationVersion%d" % best)
        self.decision_version = best
        return negfunc(offer)
github LeastAuthority / leastauthority.com / src / grid_router / _router.py View on Github external
"""
        # the client sends us a GET message
        lines = header.split("\r\n")
        if not lines[0].startswith("GET "):
            raise BananaError("not right")
        command, url, version = lines[0].split()
        if not url.startswith("/id/"):
            # probably a web browser
            raise BananaError("not right")
        targetTubID = url[4:]

        Message.log(event_type=u"handlePLAINTEXTServer", tub_id=targetTubID)

        if targetTubID == "":
            # they're asking for an old UnauthenticatedTub. Refuse.
            raise NegotiationError("secure Tubs require encryption")
        if isSubstring("Upgrade: TLS/1.0\r\n", header):
            wantEncrypted = True
        else:
            wantEncrypted = False

        Message.log(event_type=u"handlePLAINTEXTServer", want_encrypted=wantEncrypted)

        self._handleTubRequest(header, targetTubID)
github warner / foolscap / foolscap / appserver / cli.py View on Github external
pieces = port.split(":")
        if "0" in pieces:
            # If the --port argument didn't tightly specify the port to use,
            # write down the one we actually got, so we'll keep using the
            # same one later
            pieces[pieces.index("0")] = str(l0.getPortnum())
            if pieces[0] != "tcp":
                pieces = ["tcp"] + pieces
            got_port = ":".join(pieces)
            f = open(os.path.join(basedir, "port"), "w")
            f.write(got_port + "\n")
            f.close()

        tubid = tub.getTubID()

        sample_furl = tub.registerReference(Referenceable())
        furl_prefix = sample_furl[:sample_furl.rfind("/")+1]
        f = open(os.path.join(basedir, "furl_prefix"), "w")
        f.write(furl_prefix + "\n")
        f.close()

        f = open(os.path.join(basedir, "flappserver.tac"), "w")
        stashed_path = ""
        for p in sys.path:
            stashed_path += "  %r,\n" % p
        f.write(FLAPPSERVER_TACFILE % { 'path': stashed_path })
        f.close()

        if not quiet:
            print >>stdout, "Foolscap Application Server created in %s" % basedir
            print >>stdout, "TubID %s, listening on port %s" % (tubid, got_port)
            print >>stdout, "Now launch the daemon with 'flappserver start %s'" % basedir
github selfsk / nodeset.core / src / nodeset / core / dispatcher.py View on Github external
import logging
import simplejson

from nodeset.core import routing, config, message
from nodeset.common import log

class DispatcherStats(object):
    
    def __init__(self):
        self.pubs = 0
        self.subs = 0

    def toJSON(self):
        return simplejson.dumps({"subs": self.subs, "pubs": self.pubs})
    
class EventDispatcher(Referenceable, service.Service):
    """ 
    EventDispatcher instance is running on each host as separate process. Remote Nodes can subscribe for events
    on this dispatcher, too. Nodes are exchanging events through dispatcher.
    """
    def __init__(self, listen='pbu://localhost:5333/dispatcher'):
        self.routing = routing.RoutingTable() 
        self.tub = UnauthenticatedTub()
        
        host, port, refname = self._split(listen)
        
        self.listen_url = listen
        self.host = host
        self.port = port
        self.stats = DispatcherStats()
        
        self.tub.listenOn('tcp:%d' % port)
github selfsk / nodeset.core / src / nodeset / core / node.py View on Github external
def startService(self):
        # if we're not started yet
        if not self.cold_start:
            self.start()

        if not self.dispatcher_url:
            self.dispatcher_url = self.config['dispatcher-url']
        if self.config.has_key('listen') and not self.port:
            self.host, self.port = self.config['listen'].split(':')
        
        self.tub = Tub()
        self.tub.listenOn('tcp:%d' % int(self.port))
        self.tub.setLocation('%s:%d' % (self.host, int(self.port)))
        self.tub.registerReference(self, self.name)
        
        self.tub.startService()
        
        self._createConnector()
github warner / foolscap / doc / listings / pb2client.py View on Github external
def gotReference(remote):
    print "got a RemoteReference"
    print "asking it to add 1+2"
    d = remote.callRemote("add", a=1, b=2)
    d.addCallbacks(gotAnswer, gotError2)

def gotAnswer(answer):
    print "the answer is", answer
    reactor.stop()

if len(sys.argv) < 2:
    print "Usage: pb2client.py URL"
    sys.exit(1)
url = sys.argv[1]
tub = Tub()
tub.startService()
d = tub.getReference(url)
d.addCallbacks(gotReference, gotError1)

reactor.run()
github warner / foolscap / src / foolscap / logging / tail.py View on Github external
def formatted_print(self, d):
        time_s = format_time(d['time'], self.options["timestamps"])

        msg = log.format_message(d)
        level = d.get('level', log.OPERATIONAL)

        tubid = "" # TODO
        print("%s L%d [%s]#%d %s" % (time_s, level, tubid,
                                     d["num"], msg), file=self.output)
        if 'failure' in d:
            print(" FAILURE:", file=self.output)
            lines = str(d['failure']).split("\n")
            for line in lines:
                print(" %s" % (line,), file=self.output)