Example #1
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    #print("key1")
    #keyChain = KeyChain()
    #print("key2")
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    identityName = Name("TestProducer")
    certificateName = keyChain.createIdentityAndCertificate(identityName)
    keyChain.getIdentityManager().setDefaultIdentity(identityName)

    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    ubicdn = UbiCDN(keyChain, certificateName)
    prefix = Name("/ubicdn/video")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed)

    while 1:
        #while ubicdn._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #2
0
def main():
    async def face_loop():
        nonlocal face, repo
        while repo.running:
            face.processEvents()
            await asyncio.sleep(0.001)

    config = get_yaml()
    logging.info(config)

    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    # storage = LevelDBStorage(config['db_config']['leveldb']['dir'])
    storage = MongoDBStorage(config['db_config']['mongodb']['db'],
                             config['db_config']['mongodb']['collection'])
    read_handle = ReadHandle(face, keychain, storage)
    write_handle = WriteCommandHandle(face, keychain, storage, read_handle)
    delete_handle = DeleteCommandHandle(face, keychain, storage)
    tcp_bulk_insert_handle = TcpBulkInsertHandle(
        storage, read_handle, config['tcp_bulk_insert']['addr'],
        config['tcp_bulk_insert']['port'])

    repo = Repo(Name(config['repo_config']['repo_name']), face, storage,
                read_handle, write_handle, delete_handle,
                tcp_bulk_insert_handle)

    repo.listen()  # my nfd is broken...

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    objectPrefix = Namespace("/ndn/eb/run/28/description", keyChain)

    dump("Register prefix", objectPrefix.name)
    # Set the face and register to receive Interests.
    objectPrefix.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    dump("Preparing data for", objectPrefix.name)
    GeneralizedObjectHandler().setObject(objectPrefix,
                                         Blob("EB run #28. Ham and oats"),
                                         "text/html")

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #4
0
class TestRegistrationCallbacks(ut.TestCase):
    def setUp(self):
        self.face = Face()
        keyChain = KeyChain()
        self.face.setCommandSigningInfo(
          keyChain, keyChain.getDefaultCertificateName())

    def tearDown(self):
        self.face.shutdown()

    def test_registration_callbacks(self):
        onRegisterFailed = Mock()
        onRegisterSuccess = Mock()

        self.face.registerPrefix(
          Name("/test/register/callbacks"), None, onRegisterFailed,
          onRegisterSuccess)

        while True:
            self.face.processEvents()
            time.sleep(0.01)
            if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0):
                break

        self.assertEqual(
          onRegisterSuccess.call_count, 1,
          "Expected 1 onRegisterSuccess callback, got " +
            str(onRegisterSuccess.call_count))
Example #5
0
def main():
    if len(sys.argv) < 2:
        print("Usage:", sys.argv[0], "command-prefix", file=sys.stderr)
        return -1
    else:
        command_prefix = sys.argv[1]

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    event_loop = asyncio.get_event_loop()
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    server = Server(face, command_prefix)

    async def face_loop():
        nonlocal face, server
        while server.running:
            face.processEvents()
            await asyncio.sleep(0.01)

    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
Example #6
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())

    async def face_loop():
        nonlocal face
        while True:
            face.processEvents()
            await asyncio.sleep(0.001)

    parser = argparse.ArgumentParser(description='segmented insert client')
    parser.add_argument('-r', '--repo_name',
                        required=True, help='Name of repo')
    parser.add_argument('-p', '--process_id',
                        required=True, help="Process ID")
    args = parser.parse_args()

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    client = CommandChecker(face, keychain)
    event_loop = asyncio.get_event_loop()
    event_loop.create_task(face_loop())
    event_loop.run_until_complete(client.check_delete(args.repo_name, int(args.process_id)))
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ")
    else:
        userPrefixUri = input("Enter your user prefix (e.g. /a): ")
    if userPrefixUri == "":
        dump("You must enter a user prefix")
        return

    syncPrefixUri = "/sync"
    nUserPrefixes = 2
    maxPublishedSequenceNo = 3

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri,
                        nUserPrefixes, maxPublishedSequenceNo)

    # The main event loop.
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #8
0
class TestRegistrationCallbacks(ut.TestCase):
    def setUp(self):
        self.face = Face()
        keyChain = KeyChain()
        self.face.setCommandSigningInfo(
          keyChain, keyChain.getDefaultCertificateName())

    def tearDown(self):
        self.face.shutdown()

    def test_registration_callbacks(self):
        onRegisterFailed = Mock()
        onRegisterSuccess = Mock()

        self.face.registerPrefix(
          Name("/test/register/callbacks"), None, onRegisterFailed,
          onRegisterSuccess)

        while True:
            self.face.processEvents()
            time.sleep(0.01)
            if (onRegisterSuccess.call_count > 0 or onRegisterFailed.call_count > 0):
                break

        self.assertEqual(
          onRegisterSuccess.call_count, 1,
          "Expected 1 onRegisterSuccess callback, got " +
            str(onRegisterSuccess.call_count))
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    dataPrefix = "/home/test1/data"
    repoDataPrefix = "/home/test1/data"
    # Set up repo-ng, register prefix for repo-ng's fetch prefix
    # Per configuration file in /usr/local/etc/ndn/repo-ng.conf
    # memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd
    #memCache = MemoryContentCache(face, 100000)
    #memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound)

    counter = Counter(face, repoDataPrefix)

    interest = Interest(Name(dataPrefix))
    interest.setChildSelector(1)
    interest.setInterestLifetimeMilliseconds(defaultInterestLifetime)
    face.expressInterest(interest, counter.onData, counter.onTimeout)
    
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(1)
    face.shutdown()
Example #10
0
async def main():

    # Set up face
    async def face_loop():
        nonlocal face, running
        while running:
            face.processEvents()
            await asyncio.sleep(0.001)

    face = Face()
    running = True
    face_event = event_loop.create_task(face_loop())

    # register prefix in local NFD with it own name: /local_manager/building_1/camera_1
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    prefix_id = face.registerPrefix(Name(VIDEO_STREAM_NAME), None, on_register_failed)
    filter_id = face.setInterestFilter(Name(VIDEO_STREAM_NAME), on_interest)
    print('Registered prefix ID {}'.format(prefix_id))
    print('Registered filter ID {}'.format(filter_id))

    cap = cv2.VideoCapture(0)

    # Capture a video every second
    while True:
        cur_time = await capture_video_chunk(duration=1, cap=cap)
        prepare_packets(cur_time=cur_time, keychain=keychain)
        remove_outdated_data(cur_time)

    cap.release()
    cv2.destroyAllWindows()

    running = False
    await face_event
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    publishIntervalMs = 1000.0
    stream = Namespace("/ndn/eb/stream/run/28/annotations", keyChain)
    handler = GeneralizedObjectStreamHandler(stream)

    dump("Register prefix", stream.name)
    # Set the face and register to receive Interests.
    stream.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    # Loop, producing a new object every publishIntervalMs milliseconds (and
    # also calling processEvents()).
    previousPublishMs = 0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            dump("Preparing data for sequence",
              handler.getProducedSequenceNumber() + 1)
            handler.addObject(
              Blob("Payload " + str(handler.getProducedSequenceNumber() + 1)),
              "application/json")

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #12
0
    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager, newInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
          "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
          "Verification success called {} times instead of 1".format(
            vr.successCount))

        vr  = doVerify(self.policyManager, oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
          "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
          "Failure callback called {} times instead of 1".format(
            vr.failureCount))
Example #13
0
def main():
    if len(argv) < 3:
        dump("Usage:", argv[0], "<repo-command-prefix> <fetch-prefix>")
        return

    repoCommandPrefix = Name(argv[1])
    repoDataPrefix = Name(argv[2])

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    enabled = [True]

    def onInsertStarted():
        # nonlocal enabled
        dump("Insert started for", repoDataPrefix.toUri())
        enabled[0] = False

    def onFailed():
        # nonlocal enabled
        enabled[0] = False

    requestInsert(face, repoCommandPrefix, repoDataPrefix, onInsertStarted,
                  onFailed)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #14
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    running = True
    img = None

    interest = Interest(Name("/icear-server/result/example-data/2/deeplab"))
    interest.mustBeFresh = True

    def on_data(_, data):
        # type: (Interest, Data) -> None
        nonlocal running, img
        print(data.name.toUri())
        print(data.content.toBytes())
        running = False
        if data.metaInfo.type == ContentType.NACK:
            print("NACK")
        else:
            img = data.content.toBytes()

    face.expressInterest(interest, on_data)

    while running:
        face.processEvents()
        time.sleep(0.01)

    face.shutdown()

    if img:
        image = Image.open(io.BytesIO(img))
        image.show()
def main():
    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    dump(freshInterest.toUri())
    freshInterest.setMinSuffixComponents(4)
    freshInterest.setMaxSuffixComponents(6)
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(bytearray(
      [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
       0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.setInterestLifetimeMilliseconds(30000)
    freshInterest.setChildSelector(1)
    freshInterest.setMustBeFresh(True);
    freshInterest.setScope(2)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, certificateName)
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    keyChain.verifyInterest(
      reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"),
      makeOnVerifyFailed("Freshly-signed Interest"))
Example #16
0
def main():
    """
    Call requestInsert and register a prefix so that ProduceSegments will answer
    interests from the repo to send the data packets. This assumes that repo-ng
    is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/localhost/repo1")
    repoDataPrefix = Name("/NIST/library/mainroom/ESP32ID001")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append(
        Name.Component.fromNumber(nowMilliseconds))

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and send the repo insert command at the same time.
    startBlockId = 0
    endBlockId = 1
    enabled = [True]

    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False

    produceSegments = ProduceSegments(keyChain,
                                      keyChain.getDefaultCertificateName(),
                                      startBlockId, endBlockId, onFinished)
    dump("Register prefix", fetchPrefix.toUri())

    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False

    face.registerPrefix(fetchPrefix, produceSegments.onInterest,
                        onRegisterFailed)

    time.sleep(0.2)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())

    def onFailed():
        enabled[0] = False

    requestInsert(face, repoCommandPrefix, fetchPrefix, onInsertStarted,
                  onFailed)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(Name("/ndn/abc"))
      .setMustBeFresh(False)
      .setMinSuffixComponents(4)
      .setMaxSuffixComponents(6)
      .setInterestLifetimeMilliseconds(30000)
      .setChildSelector(1)
      .setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(bytearray(
      [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
       0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    validator.validate(
      reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"),
      makeFailureCallback("Freshly-signed Interest"))
Example #18
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(
        Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents(
            4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds(
                30000).setChildSelector(1).setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(
        bytearray([
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
            0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
            0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
        ]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    validator.validate(reDecodedFreshInterest,
                       makeSuccessCallback("Freshly-signed Interest"),
                       makeFailureCallback("Freshly-signed Interest"))
Example #19
0
class Consumer(object):
    def __init__(self):

        Prefix1 = '/umobile/notification/push'
        self.configPrefix = Name(Prefix1)
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()

        self.face = Face("127.0.0.1")

    def run(self):
        try:

            self.face.setCommandSigningInfo(self.keyChain, \
                                            self.keyChain.getDefaultCertificateName())
            self.face.registerPrefix(self.configPrefix, self.onInterest, self.onRegisterFailed)
            print "Registering listening prefix : " + self.configPrefix.toUri()

            while not self.isDone:
                self.face.processEvents()
                time.sleep(0.01)

        except RuntimeError as e:
            print "ERROR: %s" % e

    def onInterest(self, prefix, interest, face, interestFilterId, filter):

        interestName = interest.getName()
        ### Extract Data content from Interest name
        interest_name_components = interestName.toUri().split("/")
        Data_content = interest_name_components[interest_name_components.index("push") + 1]
        print 'Received Data: %s' %Data_content
        data = Data(interestName)
        data.setContent("ACK")
        hourMilliseconds = 600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        face.send(data.wireEncode().toBuffer())
        print "Sending ACK"


    def _onTimeout(self, interest):
        name = interest.getName()
        uri = name.toUri()

        print "TIMEOUT #%d: %s" % (self.outstanding[uri], uri)
        self.outstanding[uri] += 1

        if self.outstanding[uri] <= 3:
            self._sendNextInterest(name)
        else:
            self.isDone = True

    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
        self.isDone = True
def main():
    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(
        Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents(
            4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds(
                30000).setChildSelector(1).setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(
        bytearray([
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
            0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
            0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
        ]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    keyChain.verifyInterest(reDecodedFreshInterest,
                            makeOnVerified("Freshly-signed Interest"),
                            makeOnValidationFailed("Freshly-signed Interest"))
Example #21
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. This assumes that
    repo-ng is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
        nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and start the repo watch at the same time.
    enabled = [True]

    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)

    sendSegments = SendSegments(keyChain, keyChain.getDefaultCertificateName(),
                                onFinishedSending)

    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False

    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())

    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)

    startRepoWatch(face, repoCommandPrefix, watchPrefix, onRepoWatchStarted,
                   onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #22
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    running = True

    # The following line doesn't work sometimes
    # interest = Interest("/icear-server/calc")
    interest = Interest(Name("/icear-server/calc"))
    param_msg = SegmentParameterMessage()
    param_msg.segment_parameter.name.component.append(
        bytes("example-data", "utf-8"))
    param_msg.segment_parameter.start_frame = 2
    param_msg.segment_parameter.end_frame = 3
    op = param_msg.segment_parameter.operations.components.add()
    op.model = bytes("deeplab", "utf-8")
    op.flags = 0
    op = param_msg.segment_parameter.operations.components.add()
    op.model = bytes("la_muse", "utf-8")
    op.flags = 0
    interest.name.append(ProtobufTlv.encode(param_msg))

    interest.mustBeFresh = True
    interest.interestLifetimeMilliseconds = 4000.0
    interest.setCanBePrefix(True)

    def on_data(_, data):
        # type: (Interest, Data) -> None
        nonlocal running
        print(data.name.toUri())
        print(data.content.toBytes())
        running = False

    def on_timeout(_):
        nonlocal running
        print("Timeout")
        running = False

    def on_nack(_, nack):
        # type: (Interest, NetworkNack) -> None
        nonlocal running
        print("NACK")
        print(nack.getReason())
        running = False

    face.expressInterest(interest, on_data, on_timeout, on_nack)

    while running:
        face.processEvents()
        time.sleep(0.01)

    face.shutdown()
Example #23
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userName = raw_input("Enter your user name (e.g. \"a\" or \"b\"): ")
    else:
        userName = input("Enter your user name (e.g. \"a\" or \"b\"): ")
    if userName == "":
        dump("You must enter a user name")
        return

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    applicationPrefix = Namespace(Name("/test/app"), keyChain)
    applicationPrefix.setFace(face,
      lambda prefix: dump("Register failed for prefix", prefix))
    applicationPrefix.enableSync()

    userPrefix = applicationPrefix[Name.Component(userName)]

    def onStateChanged(nameSpace, changedNamespace, state, callbackId):
        if (state == NamespaceState.NAME_EXISTS and
             not userPrefix.name.isPrefixOf(changedNamespace.name)):
            dump("Received", changedNamespace.name.toUri())

    applicationPrefix.addOnStateChanged(onStateChanged)

    publishIntervalMs = 1000.0
    component = Name("/%00").get(0)

    # Loop, producing a new name every publishIntervalMs milliseconds (and also
    # calling processEvents()).
    previousPublishMs = 0.0
    while True:
        now = Common.getNowMilliseconds()
        if now >= previousPublishMs + publishIntervalMs:
            # If userName is "a", this makes /test/app/a/%00, /test/app/a/%01, etc.
            newNamespace = userPrefix[component]
            dump("Publish", newNamespace.name.toUri())
            component = component.getSuccessor()

            previousPublishMs = now

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #24
0
def main():
    """
    Call requestInsert and register a prefix so that ProduceSegments will answer
    interests from the repo to send the data packets. This assumes that repo-ng
    is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and send the repo insert command at the same time.
    startBlockId = 0
    endBlockId = 1
    enabled = [True]
    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False
    produceSegments = ProduceSegments(
      keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId,
      onFinished)
    dump("Register prefix", fetchPrefix.toUri())
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    face.registerPrefix(
      fetchPrefix, produceSegments.onInterest, onRegisterFailed)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())
    def onFailed():
        enabled[0] = False
    requestInsert(
      face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed,
      startBlockId, endBlockId)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
    def run(self):
        face = Face()

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign data packets.
        face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix %s" % self.prefix.toUri()

        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)
Example #26
0
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. This assumes that
    repo-ng is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
      nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and start the repo watch at the same time.
    enabled = [True]
    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    sendSegments = SendSegments(
      keyChain, keyChain.getDefaultCertificateName(), onFinishedSending)
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())
    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    startRepoWatch(
      face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #27
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Create an in-memory key chain with default keys.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    streamNamespace = Namespace(Name("/example-data"), keyChain)

    dump("Register prefix", streamNamespace.name)
    # Set the face and register to receive Interests.
    streamNamespace.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    # /example-data/2~3
    for sequenceNumber in range(2, 4):
        sequenceNamespace = streamNamespace[str(sequenceNumber)]
        dump("Preparing data for", sequenceNamespace.name)

        # Prepare the _meta packet.
        contentMetaInfo = ContentMetaInfo()
        contentMetaInfo.setContentType("jpeg")
        contentMetaInfo.setTimestamp(Common.getNowMilliseconds())
        contentMetaInfo.setHasSegments(True)
        sequenceNamespace["_meta"].serializeObject(contentMetaInfo.wireEncode())

        # Read jpeg file
        img_path = os.path.join(root_path, "sample420x236.jpg")
        with open(img_path, "rb") as f:
            data = f.read()
        segment_size = face.getMaxNdnPacketSize() // 2
        segment_cnt = (len(data) + segment_size - 1) // segment_size

        # We know the content has two segments.
        metaInfo = MetaInfo()
        metaInfo.setFinalBlockId(Name().appendSegment(segment_cnt - 1)[0])
        sequenceNamespace.setNewDataMetaInfo(metaInfo)
        for i in range(segment_cnt):
            start_offset = i * segment_size
            end_offset = start_offset + segment_size
            sequenceNamespace[Name.Component.fromSegment(i)].serializeObject(
                Blob(bytearray(data[start_offset:end_offset])))

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #28
0
def getKey():
    face = Face("129.241.208.115", 6363)

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    # util.dump(keyChain.getDefaultCertificateName())
    # Also use the default certificate name to sign data packets.
    face.expressInterest("/ndn/no/ntnu/KEY", onData, onTimeout)

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #29
0
    def run(self, namespace):
        face = Face()

        prefix = Name(namespace)

        face.setCommandSigningInfo(self.keyChain, \
                                self.keyChain.getDefaultCertificateName())

        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print("Registering prefix", prefix.toUri())

        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)
        pass
Example #30
0
def main():

    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    prefix = Name("/test")

    counter = Counter(keyChain, keyChain.getDefaultCertificateName())
    face.registerPrefix(prefix, counter.onInterest, counter.onRegisterFailed)

    while counter.rec == 1:
        face.processEvents()
        time.sleep(0.5)

    face.shutdown()
Example #31
0
def main():
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    certificateName = keyChain.getDefaultCertificateName()
    face.setCommandSigningInfo(keyChain, certificateName)
    test = DiscoveryTest(face, keyChain, certificateName)
    test.start()

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
def main():

    backboneFace = Face()

    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    backboneFace.setCommandSigningInfo(keyChain,
                                       keyChain.getDefaultCertificateName())

    prefix = Name("/farm1")
    backboneFace.registerPrefix(prefix, onInterest, onRegisterFailed)
    print("Ready to go...")

    while 1:
        try:
            backboneFace.processEvents()

            e.acquire()
            frame = ieee.wait_read_frame(0.01)
            e.release()

            if frame is not None:
                if frame['rf_data'][0] == b'\x06' or frame['rf_data'][
                        0] == b'\x05':  #if Data or Interest
                    buffData[0] = frame['rf_data'][0]
                    buffData[1] = ord(frame['rf_data'][1]) + lCP
                    buffData[2] = frame['rf_data'][2]
                    buffData[3] = ord(frame['rf_data'][3]) + lCP
                    buffData[4:lCP + 4] = eCP
                    buffData[lCP + 4:] = frame['rf_data'][4:]
                    print(str(datetime.now().strftime('%X.%f')))
                    backboneFace.send(buffData)
                else:
                    print(frame['rf_data'][:])
            #time.sleep(0.1)
            gc.collect()
        except KeyboardInterrupt:
            backboneFace.shutdown()
            ser.close()
            break
Example #33
0
    def run(self, namespace):

        # The default Face will connect using a Unix socket
        face = Face()
        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        while True:
            face.processEvents()
            time.sleep(0.01)
class Controller_Listener_CtrlInfo(object):
    def __init__(self):
        self.keyChain = KeyChain()
        self.isDone = False
        self.ofmsg = OFMSG()
        self.nodeid = OSCommand.getnodeid()
        self.face = Face()
        self.featurereq = FeatureReq()
        self.helloreq_name_list = []
        self.new_CtrlInfo_data = "---Initial CtrlInfo data---"  # used to get new ctrlinfo data and send to nodes.
        self.CtrlInfo_data = ""  # used to record used ctrlinfo data

    def ctrl_info_run(self):

        ControllerPrefixString = '/ndn/ie/tcd/controller01/ofndn/--/n1.0/36/0/0/'
        ControllerPrefix = Name(ControllerPrefixString)
        self.face.setCommandSigningInfo(self.keyChain, \
                                        self.keyChain.getDefaultCertificateName())

        self.face.registerPrefix(ControllerPrefix, self.onInterest_CtrlInfo, self.onRegisterFailed)  # run prefix
        #
        # # filters:
        # CtrlInfo_msg_prefix = Name('/ndn/ie/tcd/controller01/ofndn/--/n1.0/36/0/0/')
        # self.face.setInterestFilter(CtrlInfo_msg_prefix, self.onInterest_CtrlInfo)  # for CtrlInfo msg

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:  # listen hello cannot stop
            self.face.processEvents()
            time.sleep(0.01)

    def onInterest_CtrlInfo(self, mainPrefix, interest, transport, registeredPrefixId):
        print("******** Received <<<CtrlInfoReq>>> Interest ******** \n {0} \n".format(interest.getName().toUri()))
        while (self.new_CtrlInfo_data == self.CtrlInfo_data):  # wait for new data.
            time.sleep(15)
        self.CtrlInfo_data = self.new_CtrlInfo_data
        data = self.ofmsg.create_ctrlinfo_res_data(interest, self.CtrlInfo_data)
        transport.send(data.wireEncode().toBuffer())
        print("******** Sent <<<New CtrlInfo Res>>> Data ******** \n")

    def onInterest_Mian(self, mainPrefix, interest, transport, registeredPrefixId):
        pass

    def onRegisterFailed(self, ControllerPrefix):
        print("Register failed for prefix", ControllerPrefix.toUri())
        self.isDone = True
Example #35
0
    def run(self):
        # Create a connection to the local forwarder.
        face = Face()

        prefix = Name(namesp)
        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())
        # Also use the default certificate name to sign Data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print("Registering prefix: %s" % prefix.toUri())

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)
Example #36
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    prefix = Namespace("/ndn/test/status", keyChain)

    dump("Register prefix", prefix.name)
    # Set the face and register to receive Interests.
    prefix.setFace(face,
      lambda prefixName: dump("Register failed for prefix", prefixName))

    handler = GeneralizedObjectHandler()
    # Each generalized object will have a 1000 millisecond freshness period.
    metaInfo = MetaInfo()
    metaInfo.setFreshnessPeriod(1000.0)

    # This is called when the library receives an Interest which is not
    # satisfied by Data already in the Namespace tree.
    def onObjectNeeded(namespace, neededNamespace, callbackId):
        if not (neededNamespace is prefix):
            # This is not the expected Namespace.
            return False

        # Make a version from the current time.
        versionNamespace = prefix[
          Name.Component.fromVersion(Common.getNowMilliseconds())]
        # The metaInfo has the freshness period.
        versionNamespace.setNewDataMetaInfo(metaInfo)
        dump("Producing the generalized object for", versionNamespace.name)
        handler.setObject(
          versionNamespace, Blob("Status as of " + str(datetime.datetime.now())),
          "text/html")
        return True

    prefix.addOnObjectNeeded(onObjectNeeded)

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #37
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    prefix = Name("/nfd/edu/ucla/remap/test")
    # Route to aleph.ndn.ucla.edu.  Have to use the canonical name with an IP
    # address and port.
    uri = "udp4://128.97.98.7:6363"

    # The default Face connects to the local NFD.
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Create the /localhost/nfd/faces/query command interest, including the
    # FaceQueryFilter. Construct the FaceQueryFilter using the structure in
    # face_query_filter_pb2 which was produced by protoc.
    message = face_query_filter_pb2.FaceQueryFilterMessage()
    filter = message.face_query_filter.add()
    filter.uri = uri
    encodedFilter = ProtobufTlv.encode(message)

    interest = Interest(Name("/localhost/nfd/faces/query"))
    interest.getName().append(encodedFilter)

    enabled = [True]

    def onComplete(content):
        processFaceStatus(content, prefix, uri, face, enabled)

    def onError(errorCode, message):
        enabled[0] = False
        dump(message)

    SegmentFetcher.fetch(face, interest, None, onComplete, onError)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()

        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #38
0
def main():
    prefix = Name("/nfd/edu/ucla/remap/test")
    # Route to aleph.ndn.ucla.edu.  Have to use the canonical name with an IP
    # address and port.
    uri = "udp4://128.97.98.7:6363"

    # The default Face connects to the local NFD.
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Create the /localhost/nfd/faces/query command interest, including the
    # FaceQueryFilter. Construct the FaceQueryFilter using the structure in
    # face_query_filter_pb2 which was produced by protoc.
    message = face_query_filter_pb2.FaceQueryFilterMessage()
    filter = message.face_query_filter.add()
    filter.uri = uri
    encodedFilter = ProtobufTlv.encode(message)

    interest = Interest(Name("/localhost/nfd/faces/query"))
    interest.getName().append(encodedFilter)

    enabled = [True]

    def onComplete(content):
        processFaceStatus(content, prefix, uri, face, enabled)

    def onError(errorCode, message):
        enabled[0] = False
        dump(message)

    SegmentFetcher.fetch(
        face, interest, SegmentFetcher.DontVerifySegment, onComplete, onError)

    # Loop calling processEvents until a callback sets enabled[0] = False.
    while enabled[0]:
        face.processEvents()

        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
    def run(self, namespace):
        # Create a connection to the local forwarder over a Unix socket
        face = Face()

        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, \
                                   self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign Data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    echo = Echo(keyChain, keyChain.getDefaultCertificateName())
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Example #41
0
    def run(self, prefix):
        self.keyChain = KeyChain()

        self.consoleThread = ConsoleThread()
        self.consoleThread.start()

        # The default Face will connect using a Unix socket
        face = Face()
        prefix = Name(prefix)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)
Example #42
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    (keyChain, certificateName) = createKeyChain()
    face.setCommandSigningInfo(keyChain, certificateName)

    userKeyName = Name("/U/Key")
    contentPrefix = Name("/Prefix/SAMPLE")

    testProducer = TestProducer(
      contentPrefix, userKeyName, keyChain, certificateName)

    prefix = Name("/Prefix")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(
      prefix, testProducer.onInterest, testProducer.onRegisterFailed)

    while testProducer._enabled:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ")
    else:
        userPrefixUri = input("Enter your user prefix (e.g. /a): ")
    if userPrefixUri == "":
        dump("You must enter a user prefix")
        return

    syncPrefixUri = "/sync"
    nUserPrefixes = 2
    maxPublishedSequenceNo = 3

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    producer = Producer(
      face, keyChain, Name(syncPrefixUri), userPrefixUri, nUserPrefixes,
      maxPublishedSequenceNo)

    # The main event loop.
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Example #44
0
class LightController():
    shouldSign = False
    COLORS_PER_LIGHT = 3
    STRAND_SIZE = 50
    def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"):
        self.log = logging.getLogger("LightController")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.WARNING)
        self.log.addHandler(sh)
        fh = logging.FileHandler("LightController.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)

        self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)]

        self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT)
        self.registerFailed = False
        self.done = False
        self.prefix = Name(prefix)
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

    # XXX: we should get a thread for this or something!
    def start(self):
        self.face = Face()
        self.face.setCommandSigningInfo(self.keychain, self.certificateName)
        self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed)
        while self.face is not None:
            self.face.processEvents()
            if self.registerFailed:
                self.stop()
                break
            #time.sleep(0.001)


    def stop(self):
        self.kinetsender.stop = True
        self.kinetsender.complete.wait()         
        self.face.shutdown()
        self.face = None

    def signData(self, data):
        if LightController.shouldSign:
            self.keychain.sign(data, self.certificateName)
        else:
            data.setSignature(Sha256WithRsaSignature())

    def setPayloadColor(self, strand, color):
        # will expand this to allow the repeats, etc
        self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.STRAND_SIZE

    def onLightingCommand(self, prefix, interest, transport, prefixId):
        interestName = Name(interest.getName())
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        d = Data(interest.getName())
        # get the command parameters from the name
        try:
            commandComponent = interest.getName().get(prefix.size())
            commandParams = interest.getName().get(prefix.size()+1)

            lightingCommand = LightCommandMessage()
            ProtobufTlv.decode(lightingCommand, commandParams.getValue())
            self.log.info("Command: " + commandComponent.toEscapedString())
            requestedColor = lightingCommand.command.pattern.colors[0] 
            colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
            self.log.info("Requested color: " + colorStr)
            self.setPayloadColor(0, requestedColor)
            self.sendLightPayload(1)
            d.setContent("Gotcha: " + colorStr+ "\n")
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            d.getMetaInfo().setFinalBlockID(0)
            self.signData(d)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())

    def onRegisterFailed(self, prefix):
        self.log.error("Could not register " + prefix.toUri())
        print "Register failed!"
        self.registerFailed = True

    def sendLightPayload(self, port):
        self.kinetsender.setPayload(port, self.payloadBuffer[port-1])
Example #45
0
class TestFaceRegisterMethods(ut.TestCase):
    def setUp(self):
        self.face_in = Face()
        self.face_out = Face()
        self.keyChain = KeyChain()

    def tearDown(self):
        self.face_in.shutdown()
        self.face_out.shutdown()

    def test_register_prefix_response(self):
        prefixName = Name("/test")
        self.face_in.setCommandSigningInfo(self.keyChain,
                self.keyChain.getDefaultCertificateName())

        interestCallbackCount = [0]
        def onInterest(prefix, interest, transport, prefixID):
            interestCallbackCount[0] += 1
            data = Data(interest.getName())
            data.setContent("SUCCESS")
            self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
            encodedData = data.wireEncode()
            transport.send(encodedData.toBuffer())

        failedCallback = Mock()

        self.face_in.registerPrefix(prefixName, onInterest, failedCallback)
        # Give the 'server' time to register the interest.
        time.sleep(1)

        # express an interest on another face
        dataCallback = Mock()
        timeoutCallback = Mock()

        # now express an interest on this new face, and see if onInterest is called
        # Add the timestamp so it is unique and we don't get a cached response.
        interestName = prefixName.append("hello" + repr(time.time()))
        self.face_out.expressInterest(interestName, dataCallback, timeoutCallback)

        # Process events for the in and out faces.
        timeout = 10000
        startTime = getNowMilliseconds()
        while True:
            if getNowMilliseconds() - startTime >= timeout:
                break

            self.face_in.processEvents()
            self.face_out.processEvents()

            done = True
            if interestCallbackCount[0] == 0 and failedCallback.call_count == 0:
                # Still processing face_in.
                done = False
            if dataCallback.call_count == 0 and timeoutCallback.call_count == 0:
                # Still processing face_out.
                done = False

            if done:
                break
            time.sleep(0.01)


        self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all')

        self.assertEqual(interestCallbackCount[0], 1, 'Expected 1 onInterest callback, got '+str(interestCallbackCount[0]))

        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0]
        # check the message content
        data = onDataArgs[1]
        expectedBlob = Blob("SUCCESS")
        self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')
Example #46
0
        #time.sleep(0.001)
        if timeout is not None and time.time() >= start+timeout:
            break

    done = time.time()
    
    if onTimeout.call_count > 0:
        timeouts +=1
    else:
        timing.append(done-start)


if __name__ == '__main__':
    face = Face()
    if shouldSign:
        face.setCommandSigningInfo(keychain, certName)
    input = None
    N = 0
    try:
        while True:
            byteVal = (N)&0xff
            color = (0,0,0)
            selector = (N/256)%0x3
            if selector == 1:
                color = (byteVal, 0, 0)
            elif selector == 2:
                color = (0, byteVal, 0)
            elif selector == 0:
                color = (0, 0, byteVal)

            interest = createCommandInterest(color=color)
Example #47
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
    face.setCommandSigningInfo(keyChain, certificateName)

    chat = Chat(
      screenName, chatRoom, Name(hubPrefix), face, keyChain, certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
Example #48
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"")

    face = Face(host)

    # Set up the key chain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    chat = Chat(
      screenName, chatRoom, Name(hubPrefix), face, keyChain,
      keyChain.getDefaultCertificateName())

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
Example #49
0
    registerFail = Mock()
    def publisher_loop(face):
       global done
       try:
           while not done:   
               face.processEvents()
               if registerFail.call_count > 0:
                   logger.error("Registration failed!")
                   done = True
               time.sleep(0.01)
       except:
           face.shutdown()
           return 0

    publisher_face = Face("localhost")
    publisher_face.setCommandSigningInfo(keychain, certName)

    dataCache = MemoryContentCache(publisher_face, 1)
    dataCache.registerPrefix(data_prefix,  registerFail, onDataMissing)

    publisher = Thread(target=publisher_loop, name="Data publisher", args=(publisher_face,))    
    publisher.start()

    try:
        # sleep a second, like the repo-ng test
        time.sleep(1)
        while not done:
            #pick a random data name
            data_part = suffix# str(randint(0,N))

            fullName = Name(data_prefix).append(Name(data_part))
Example #50
0
class TestFaceRegisterMethods(ut.TestCase):
    def setUp(self):
        self.face_in = Face()
        self.face_out = Face()
        self.keyChain = KeyChain()

    def tearDown(self):
        self.face_in.shutdown()
        self.face_out.shutdown()

    def onInterestEffect(self, prefix, interest, transport, prefixID):
        data = Data(interest.getName())
        data.setContent("SUCCESS")
        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
        encodedData = data.wireEncode()
        transport.send(encodedData.toBuffer())

    def test_register_prefix_response(self):
        # gotta sign it (WAT)
        prefixName = Name("/test")
        self.face_in.setCommandSigningInfo(self.keyChain,
                self.keyChain.getDefaultCertificateName())

        failedCallback = Mock()
        interestCallback = Mock(side_effect=self.onInterestEffect)

        self.face_in.registerPrefix(prefixName, interestCallback, failedCallback)
        server = gevent.spawn(self.face_process_events, self.face_in, [interestCallback, failedCallback], 'h')

        time.sleep(1) # give the 'server' time to register the interest

        # express an interest on another face
        dataCallback = Mock()
        timeoutCallback = Mock()

        # now express an interest on this new face, and see if onInterest is called
        interestName = prefixName.append("hello")
        self.face_out.expressInterest(interestName, dataCallback, timeoutCallback)

        client = gevent.spawn(self.face_process_events, self.face_out, [dataCallback, timeoutCallback], 'c')

        gevent.joinall([server, client], timeout=10)

        self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all')

        self.assertEqual(interestCallback.call_count, 1, 'Expected 1 onInterest callback, got '+str(interestCallback.call_count))

        self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))

        onDataArgs = dataCallback.call_args[0]
        # check the message content
        data = onDataArgs[1]
        expectedBlob = Blob(bytearray("SUCCESS"))
        self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')

    def face_process_events(self, face, callbacks, name=None):
        # implemented as a 'greenlet': something like a thread, but semi-synchronous
        # callbacks should be a list
        done = False
        while not done:
            face.processEvents()
            gevent.sleep()
            for c in callbacks:

                if (c.call_count > 0):
                    done = True
import time

from pyndn import Face, Name, Data, KeyLocator, Interest
from pyndn.security import KeyChain
#from pyndn.node import Node

def onRegisterSuccess(prefix, registeredPrefixId):
    print "Registered: " + prefix.toUri()

def onRegisterFailed(prefix):
    print "Prefix registration failed: " + prefix.toUri()

def onInterest(prefix, interest, face, interestFilterId, filter):
    print "Got interest " + interest.getName().toUri()

face = Face("128.97.98.7", 6363)
print "Local face is: " + str(face.isLocal())

keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain._identityManager.getDefaultCertificateNameForIdentity(Name("/ndn/edu/ucla/remap/%40GUEST/wangzhehao410305%40gmail.com")))
face.registerPrefix("/ndn/edu/ucla/remap/zhehao", onInterest, onRegisterFailed, onRegisterSuccess)

while True:
    face.processEvents()
    # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
    time.sleep(0.01)
Example #52
0
class StatusServer(object):
    def __init__(self):
        self._face = Face()
        self._keyChain = KeyChain()
        #print(dir(self._keyChain))
        self._certificateName = self._keyChain.getDefaultCertificateName()
        self.registerWithNfd()
        #self.nfdCheck()

    def registerWithNfd(self):
        #self._face = Face()
        # Use the system default key chain and certificate name to sign commands.
        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)

        logging.debug('Register prefix ' + LINK_STATUS_NAME.toUri())
        self._face.registerPrefix(LINK_STATUS_NAME, self.onLinkInterest, self.onRegisterFailed)

        logging.debug('Register prefix ' + METADATA_STATUS_NAME.toUri())
        self._face.registerPrefix(METADATA_STATUS_NAME, self.onMetaDataInterest, self.onRegisterFailed)

        logging.debug('Register prefix ' + PREFIX_STATUS_NAME.toUri())
        self._face.registerPrefix(PREFIX_STATUS_NAME, self.onPrefixInterest, self.onRegisterFailed)

    def onLinkInterest(self, prefix, interest, face, registeredPrefixId, filter):
        self._linkData = getLinkData()
        logging.debug('Received interest for Link')
        self.sendData(prefix, interest, face, registeredPrefixId, self._linkData)

    def onMetaDataInterest(self, prefix, interest, face, registeredPrefixId, filter):
        print("on meta interest")
        print("interest rcvd for: ", interest.getName().toUri())
        print("interest must be fresh value: ", interest.getMustBeFresh())
        processFiles()
        self._metaData = processAndGetMetaData()
        logging.debug('Received interest for Metadata')
        self.sendData(prefix, interest, face, registeredPrefixId, self._metaData)
        print("Data send")

    def onPrefixInterest(self, prefix, interest, transport, registeredPrefixId, filter):

        self._prefixData = getPrefixData()
        logging.debug('Received interest for Prefix')
        self.sendData(prefix, interest, transport, registeredPrefixId, self._prefixData)

    def sendData(self, prefix, interest, face, registeredPrefixId, content):      #onInterest

        #transport.send(encodedData.toBuffer())
	#print(prefix)
        # Publish segments
        dataSize = len(content)
        print("Dat size: ",dataSize)
        segmentBegin = 0
        segmentNo = 0
        print "Start"
        while segmentBegin < dataSize: 
            segmentEnd = segmentBegin + 2000 #Common.MAX_NDN_PACKET_SIZE

            if segmentEnd > dataSize:
                segmentEnd = dataSize

            # Make and sign a Data packet.
	    print("Prefix: ")
	    print(prefix)
            if not "%" in str(prefix)[-7:]:
                segmentName = prefix
		#print("NO % in name: ", segmentName)
                segmentName.appendSegment(segmentNo)
            else:
                segmentName = str(prefix)[:-1]
                #print("% in name: ",segmentName)
		segmentName += str(segmentNo)
		segmentName = Name(segmentName)
            print("Segment Name: ")
	    print(segmentName)

            print("Segment Name appended: ", segmentName)

            print "Segmenting data from %d to %d" % (segmentBegin, segmentEnd)
            print("COntent: ")
            print(content[segmentBegin:segmentEnd])

            data = Data(segmentName)
            data.setContent(content[segmentBegin:segmentEnd])
            data.getMetaInfo().setFreshnessPeriod(2000)
            self._keyChain.sign(data, self._certificateName)

            if segmentEnd >= dataSize:
              print("yes")
              data.getMetaInfo().setFinalBlockId(segmentName[-1])

            #encodedData = data.wireEncode()

            segmentBegin = segmentEnd

            print "Sending data " + segmentName.toUri()
            #transport.send(encodedData.toBuffer())
            face.putData(data)

            segmentNo += 1
            time.sleep(0.5)
        print "Finish"

    def onRegisterFailed(self, prefix):
        dump("Register failed for prefix", prefix.toUri())

    def nfdCheck(self):
	try:
            try:
                output=subprocess.check_output('nfd-status | grep memphis.edu/internal', shell=True)
            except subprocess.CalledProcessError,e:
                output=e.output
            print("output", output)	
	    if "memphis.edu/internal" not in output:
	        try:
                    self.registerWithNfd()
		    threading.Timer(1, self.nfdCheck).start()
		    self.run()
                except:
	            pass
            else:
	         pass
        except:
    rp.setStartBlockId(0)
    
    interest = Interest(Name("/example/repo/1").append("insert").append(rp.wireEncode()))
    
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, certificateName)
    face.makeCommandInterest(interest)
    
    callbacks = Callbacks()
    print interest.getName().toUri()
    face.expressInterest(interest, callbacks.onData, callbacks.onTimeout)
    
    face.registerPrefix(dataPrefix, callbacks.onInterest, callbacks.onRegisterFailed)

    while True:
        face.processEvents()
        time.sleep(0.1)
Example #54
0
class TestConfigPolicyManager(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        # Reuse the policy_config subdirectory for the temporary SQLite file.
        self.databaseFilePath = "policy_config/test-public-info.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.identityStorage = BasicIdentityStorage(self.databaseFilePath)
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()

    def tearDown(self):
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            pass
        self.privateKeyStorage.deleteKeyPair(self.keyName)
        self.face.shutdown()
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_no_verify(self):
        policyManager = NoVerifyPolicyManager()
        identityName = Name('TestValidator/Null').appendVersion(int(time.time()))

        keyChain = KeyChain(self.identityManager, policyManager)
        keyChain.createIdentityAndCertificate(identityName)
        data = Data(Name(identityName).append('data'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "NoVerifyPolicyManager returned a ValidationRequest")

        self.assertEqual(vr.failureCount, 0,
            "Verification failed with NoVerifyPolicyManager")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

    def test_self_verification(self):
        policyManager = SelfVerifyPolicyManager(self.identityStorage)
        keyChain = KeyChain(self.identityManager, policyManager)

        identityName  = Name('TestValidator/RsaSignatureVerification')
        keyChain.createIdentityAndCertificate(identityName)

        data = Data(Name('/TestData/1'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
            "Verification of identity-signed data failed")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

        data2 = Data(Name('/TestData/2'))

        vr = doVerify(policyManager,
                data2)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.successCount, 0,
            "Verification of unsigned data succeeded")
        self.assertEqual(vr.failureCount, 1,
            "Verification failure callback called {} times instead of 1".format(
            vr.failureCount))

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.identityManager.getDefaultCertificateNameForIdentity(
                self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        self.face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        self.face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager,
                newInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
                "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                      vr.successCount))

        vr  = doVerify(self.policyManager,
                oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
                "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
                "Failure callback called {} times instead of 1".format(
                      vr.failureCount))

    def _removeFile(self, filename):
        try:
            os.remove(filename)
        except OSError:
            # no such file
            pass

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # needed, since the KeyChain will express interests in unknown
        # certificates
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # now save the cert data to our anchor directory, and wait
        # we have to sign it with the current identity or the
        # policy manager will create an interest for the signing certificate

        with open(self.testCertFile, 'w') as certFile:
            cert = IdentityCertificate()
            certData = b64decode(CERT_DUMP)
            cert.wireDecode(Blob(certData, False))
            self.keyChain.signByIdentity(cert, self.identityName)
            encodedCert = b64encode(cert.wireEncode().toBuffer())
            certFile.write(Blob(encodedCert, False).toRawStr())

        # still too early for refresh to pick it up
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")
        time.sleep(6)

        # now we should find it
        vr  = doVerify(self.policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                    vr.successCount))
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager did not verify valid signed data")