Exemplo n.º 1
0
        /// <summary>
        /// Do the work of expressInterest to make an Interest based on name and
        /// interestTemplate.
        /// </summary>
        ///
        /// <param name="name">A Name for the interest.  This copies the Name.</param>
        /// <param name="interestTemplate"></param>
        /// <returns>The Interest, suitable for Node.expressInterest.</returns>
        protected internal static Interest getInterestCopy(Name name,
				Interest interestTemplate)
        {
            if (interestTemplate != null) {
                // Copy the interestTemplate.
                Interest interestCopy = new Interest(interestTemplate);
                interestCopy.setName(name);
                return interestCopy;
            } else {
                Interest interestCopy_0 = new Interest(name);
                interestCopy_0.setInterestLifetimeMilliseconds(4000.0d);
                return interestCopy_0;
            }
        }
        static void Main(string[] args)
        {
            var interest = new Interest();
              interest.wireDecode(new Blob(TlvInterest));
              Console.Out.WriteLine("Interest:");
              dumpInterest(interest);

              // Set the name again to clear the cached encoding so we encode again.
              interest.setName(interest.getName());
              var encoding = interest.wireEncode();
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-encoded interest " + encoding.toHex());

              var reDecodedInterest = new Interest();
              reDecodedInterest.wireDecode(encoding);
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-decoded Interest:");
              dumpInterest(reDecodedInterest);

              var freshInterest = new Interest(new Name("/ndn/abc"));
              freshInterest.setMinSuffixComponents(4);
              freshInterest.setMaxSuffixComponents(6);
              freshInterest.setInterestLifetimeMilliseconds(30000);
              freshInterest.setChildSelector(1);
              freshInterest.setMustBeFresh(true);
              freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST);
              freshInterest.getKeyLocator().setKeyData
            (new Blob(new byte[] {
              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(new Name("abc").get(0)).appendAny();

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

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

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

              Interest reDecodedFreshInterest = new Interest();
              reDecodedFreshInterest.wireDecode(freshInterest.wireEncode());
              Console.Out.WriteLine("");
              Console.Out.WriteLine("Re-decoded fresh Interest:");
              dumpInterest(reDecodedFreshInterest);

              VerifyCallbacks callbacks = new VerifyCallbacks("Freshly-signed Interest");
              keyChain.verifyInterest(reDecodedFreshInterest, callbacks, callbacks);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Do the work of registerPrefix to register with NFD.
        /// </summary>
        ///
        /// <param name="registeredPrefixId">registeredPrefixTable_ (assuming it has already been done).</param>
        /// <param name="prefix"></param>
        /// <param name="onInterest"></param>
        /// <param name="onRegisterFailed"></param>
        /// <param name="onRegisterSuccess"></param>
        /// <param name="flags"></param>
        /// <param name="commandKeyChain"></param>
        /// <param name="commandCertificateName"></param>
        /// <param name="wireFormat_0"></param>
        /// <param name="face_1"></param>
        /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception>
        private void nfdRegisterPrefix(long registeredPrefixId, Name prefix,
                                       OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed,
                                       OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags,
                                       KeyChain commandKeyChain, Name commandCertificateName,
                                       WireFormat wireFormat_0, Face face_1)
        {
            if (commandKeyChain == null)
            {
                throw new Exception(
                          "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.");
            }
            if (commandCertificateName.size() == 0)
            {
                throw new Exception(
                          "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.");
            }

            ControlParameters controlParameters = new ControlParameters();

            controlParameters.setName(prefix);
            controlParameters.setForwardingFlags(flags);

            Interest commandInterest = new Interest();

            // Determine whether to use remote prefix registration.
            bool faceIsLocal;

            try {
                faceIsLocal = isLocal();
            } catch (IOException ex) {
                logger_.log(
                    ILOG.J2CsMapping.Util.Logging.Level.INFO,
                    "Register prefix failed: Error attempting to determine if the face is local: {0}",
                    ex);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                                exception);
                }
                return;
            }

            if (faceIsLocal)
            {
                commandInterest.setName(new Name("/localhost/nfd/rib/register"));
                // The interest is answered by the local host, so set a short timeout.
                commandInterest.setInterestLifetimeMilliseconds(2000.0d);
            }
            else
            {
                commandInterest.setName(new Name("/localhop/nfd/rib/register"));
                // The host is remote, so set a longer timeout.
                commandInterest.setInterestLifetimeMilliseconds(4000.0d);
            }

            // NFD only accepts TlvWireFormat packets.
            commandInterest.getName().append(
                controlParameters.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()));
            makeCommandInterest(commandInterest, commandKeyChain,
                                commandCertificateName, net.named_data.jndn.encoding.TlvWireFormat.get());

            // Send the registration interest.
            Node.RegisterResponse response = new Node.RegisterResponse(
                new RegisterResponse.Info(prefix, onRegisterFailed,
                                          onRegisterSuccess, registeredPrefixId, onInterest, face_1),
                this);
            try {
                expressInterest(getNextEntryId(), commandInterest, response,
                                response, null, wireFormat_0, face_1);
            } catch (IOException ex_2) {
                // Can't send the interest. Call onRegisterFailed.
                logger_.log(
                    ILOG.J2CsMapping.Util.Logging.Level.INFO,
                    "Register prefix failed: Error sending the register prefix interest to the forwarder: {0}",
                    ex_2);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                                exception_3);
                }
            }
        }
        /// <summary>
        /// Append a timestamp component and a random value component to interest's
        /// name. This ensures that the timestamp is greater than the timestamp used in
        /// the previous call. Then use keyChain to sign the interest which appends a
        /// SignatureInfo component and a component with the signature bits. If the
        /// interest lifetime is not set, this sets it.
        /// </summary>
        ///
        /// <param name="interest">The interest whose name is append with components.</param>
        /// <param name="keyChain">The KeyChain for calling sign.</param>
        /// <param name="certificateName">The certificate name of the key to use for signing.</param>
        /// <param name="wireFormat"></param>
        public void generate(Interest interest, KeyChain keyChain,
				Name certificateName, WireFormat wireFormat)
        {
            double timestamp;
             lock (lastTimestampLock_) {
                        timestamp = Math.Round(net.named_data.jndn.util.Common.getNowMilliseconds(),MidpointRounding.AwayFromZero);
                        while (timestamp <= lastTimestamp_)
                            timestamp += 1.0d;
                        // Update the timestamp now while it is locked. In the small chance that
                        //   signing fails, it just means that we have bumped the timestamp.
                        lastTimestamp_ = timestamp;
                    }

            // The timestamp is encoded as a TLV nonNegativeInteger.
            TlvEncoder encoder = new TlvEncoder(8);
            encoder.writeNonNegativeInteger((long) timestamp);
            interest.getName().append(new Blob(encoder.getOutput(), false));

            // The random value is a TLV nonNegativeInteger too, but we know it is 8 bytes,
            //   so we don't need to call the nonNegativeInteger encoder.
            ByteBuffer randomBuffer = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(8);
            // Note: SecureRandom is thread safe.
            net.named_data.jndn.util.Common.getRandom().nextBytes(randomBuffer.array());
            interest.getName().append(new Blob(randomBuffer, false));

            keyChain.sign(interest, certificateName, wireFormat);

            if (interest.getInterestLifetimeMilliseconds() < 0)
                // The caller has not set the interest lifetime, so set it here.
                interest.setInterestLifetimeMilliseconds(1000.0d);
        }
Exemplo n.º 5
0
        public void testEncodeDecodeInterestWithLink()
        {
            Link link1 = new Link();
            link1.setName(new Name("test"));
            link1.addDelegation(10, new Name("/test1"));
            link1.addDelegation(20, new Name("/test2"));
            link1.addDelegation(100, new Name("/test3"));

            try {
                keyChain.sign(link1, certificateName);
            } catch (SecurityException ex) {
                Assert.Fail(ex.Message);
            }

            Interest interestA = new Interest();
            interestA.setName(new Name("/Test/Encode/Decode/With/Link"));
            interestA.setChildSelector(1);
            interestA.setInterestLifetimeMilliseconds(10000);
            interestA.setLinkWireEncoding(link1.wireEncode());

            Blob interestEncoding = interestA.wireEncode();
            Interest interestB = new Interest();
            try {
                interestB.wireDecode(interestEncoding);
            } catch (EncodingException ex_0) {
                Assert.Fail(ex_0.Message);
            }

            Assert.AssertEquals(interestA.getName(), interestB.getName());

            Link link2 = null;
            try {
                link2 = interestB.getLink();
            } catch (Exception ex_1) {
                Assert.Fail("interestB.getLink(): " + ex_1.Message);
            }

            Assert.AssertTrue("Interest link object not specified", link2 != null);
            DelegationSet delegations = link2.getDelegations();
            for (int i = 0; i < delegations.size(); ++i) {
                if (i == 0) {
                    Assert.AssertEquals(10, delegations.get(i).getPreference());
                    Assert.AssertEquals(new Name("/test1"), delegations.get(i).getName());
                }
                if (i == 1) {
                    Assert.AssertEquals(20, delegations.get(i).getPreference());
                    Assert.AssertEquals(new Name("/test2"), delegations.get(i).getName());
                }
                if (i == 2) {
                    Assert.AssertEquals(100, delegations.get(i).getPreference());
                    Assert.AssertEquals(new Name("/test3"), delegations.get(i).getName());
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Decode input as an interest in  NDN-TLV and set the fields of the interest
        /// object.
        /// </summary>
        ///
        /// <param name="interest">The Interest object whose fields are updated.</param>
        /// <param name="input"></param>
        /// <param name="signedPortionBeginOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param>
        /// <param name="signedPortionEndOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param>
        /// <param name="copy">unchanged while the Blob values are used.</param>
        /// <exception cref="EncodingException">For invalid encoding.</exception>
        public override void decodeInterest(Interest interest, ByteBuffer input,
				int[] signedPortionBeginOffset, int[] signedPortionEndOffset,
				bool copy)
        {
            TlvDecoder decoder = new TlvDecoder(input);

            int endOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Interest);
            decodeName(interest.getName(), signedPortionBeginOffset,
                    signedPortionEndOffset, decoder, copy);
            if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Selectors, endOffset))
                decodeSelectors(interest, decoder, copy);
            // Require a Nonce, but don't force it to be 4 bytes.
            ByteBuffer nonce = decoder.readBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Nonce);
            interest.setInterestLifetimeMilliseconds(decoder
                    .readOptionalNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.InterestLifetime,
                            endOffset));

            if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Data, endOffset)) {
                // Get the bytes of the Link TLV.
                int linkBeginOffset = decoder.getOffset();
                int linkEndOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Data);
                decoder.seek(linkEndOffset);

                interest.setLinkWireEncoding(
                        new Blob(decoder.getSlice(linkBeginOffset, linkEndOffset),
                                copy), this);
            } else
                interest.unsetLink();
            interest.setSelectedDelegationIndex((int) decoder
                    .readOptionalNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.SelectedDelegation,
                            endOffset));
            if (interest.getSelectedDelegationIndex() >= 0 && !interest.hasLink())
                throw new EncodingException(
                        "Interest has a selected delegation, but no link object");

            // Set the nonce last because setting other interest fields clears it.
            interest.setNonce(new Blob(nonce, copy));

            decoder.finishNestedTlvs(endOffset);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Do the work of registerPrefix to register with NFD.
        /// </summary>
        ///
        /// <param name="registeredPrefixId">registeredPrefixTable_ (assuming it has already been done).</param>
        /// <param name="prefix"></param>
        /// <param name="onInterest"></param>
        /// <param name="onRegisterFailed"></param>
        /// <param name="onRegisterSuccess"></param>
        /// <param name="flags"></param>
        /// <param name="commandKeyChain"></param>
        /// <param name="commandCertificateName"></param>
        /// <param name="wireFormat_0"></param>
        /// <param name="face_1"></param>
        /// <exception cref="System.Security.SecurityException">If cannot find the private key for thecertificateName.</exception>
        private void nfdRegisterPrefix(long registeredPrefixId, Name prefix,
				OnInterestCallback onInterest, OnRegisterFailed onRegisterFailed,
				OnRegisterSuccess onRegisterSuccess, ForwardingFlags flags,
				KeyChain commandKeyChain, Name commandCertificateName,
				WireFormat wireFormat_0, Face face_1)
        {
            if (commandKeyChain == null)
                throw new Exception(
                        "registerPrefix: The command KeyChain has not been set. You must call setCommandSigningInfo.");
            if (commandCertificateName.size() == 0)
                throw new Exception(
                        "registerPrefix: The command certificate name has not been set. You must call setCommandSigningInfo.");

            ControlParameters controlParameters = new ControlParameters();
            controlParameters.setName(prefix);
            controlParameters.setForwardingFlags(flags);

            Interest commandInterest = new Interest();

            // Determine whether to use remote prefix registration.
            bool faceIsLocal;
            try {
                faceIsLocal = isLocal();
            } catch (IOException ex) {
                logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Error attempting to determine if the face is local: {0}",
                        ex);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                            exception);
                }
                return;
            }

            if (faceIsLocal) {
                commandInterest.setName(new Name("/localhost/nfd/rib/register"));
                // The interest is answered by the local host, so set a short timeout.
                commandInterest.setInterestLifetimeMilliseconds(2000.0d);
            } else {
                commandInterest.setName(new Name("/localhop/nfd/rib/register"));
                // The host is remote, so set a longer timeout.
                commandInterest.setInterestLifetimeMilliseconds(4000.0d);
            }

            // NFD only accepts TlvWireFormat packets.
            commandInterest.getName().append(
                    controlParameters.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get()));
            makeCommandInterest(commandInterest, commandKeyChain,
                    commandCertificateName, net.named_data.jndn.encoding.TlvWireFormat.get());

            // Send the registration interest.
            Node.RegisterResponse  response = new Node.RegisterResponse (
                    new RegisterResponse.Info(prefix, onRegisterFailed,
                            onRegisterSuccess, registeredPrefixId, onInterest, face_1),
                    this);
            try {
                expressInterest(getNextEntryId(), commandInterest, response,
                        response, null, wireFormat_0, face_1);
            } catch (IOException ex_2) {
                // Can't send the interest. Call onRegisterFailed.
                logger_.log(
                        ILOG.J2CsMapping.Util.Logging.Level.INFO,
                        "Register prefix failed: Error sending the register prefix interest to the forwarder: {0}",
                        ex_2);
                try {
                    onRegisterFailed.onRegisterFailed(prefix);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onRegisterFailed",
                            exception_3);
                }
            }
        }