Exemple #1
0
 /// <summary>
 /// Write the value to result, escaping characters according to the NDN URI
 /// Scheme.
 /// This also adds "..." to a value with zero or more ".".
 /// This does not add a type code prefix such as "sha256digest=".
 /// </summary>
 ///
 /// <param name="value"></param>
 /// <param name="result">The StringBuffer to write to.</param>
 public static void toEscapedString(ByteBuffer value_ren, StringBuilder result)
 {
     bool gotNonDot = false;
     for (int i = value_ren.position(); i < value_ren.limit(); ++i) {
         if (value_ren.get(i) != 0x2e) {
             gotNonDot = true;
             break;
         }
     }
     if (!gotNonDot) {
         // Special case for component of zero or more periods.  Add 3 periods.
         result.append("...");
         for (int i_0 = value_ren.position(); i_0 < value_ren.limit(); ++i_0)
             result.append('.');
     } else {
         for (int i_1 = value_ren.position(); i_1 < value_ren.limit(); ++i_1) {
             int x = ((int) value_ren.get(i_1) & 0xff);
             // Check for 0-9, A-Z, a-z, (+), (-), (.), (_)
             if (x >= 0x30 && x <= 0x39 || x >= 0x41 && x <= 0x5a
                     || x >= 0x61 && x <= 0x7a || x == 0x2b || x == 0x2d
                     || x == 0x2e || x == 0x5f)
                 result.append((char) x);
             else {
                 result.append('%');
                 if (x < 16)
                     result.append('0');
                 result.append(ILOG.J2CsMapping.Util.IlNumber.ToString(x,16).ToUpper());
             }
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Parse the data from the input buffer recursively and return the root as an
        /// object of a subclass of DerNode.
        /// </summary>
        ///
        /// <param name="inputBuf">position.</param>
        /// <param name="startIdx">The offset into the buffer.</param>
        /// <returns>An object of a subclass of DerNode.</returns>
        public static DerNode parse(ByteBuffer inputBuf, int startIdx)
        {
            int nodeType = ((int) inputBuf.get(startIdx)) & 0xff;
            // Don't increment idx. We're just peeking.

            DerNode newNode;
            if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.Boolean)
                newNode = new DerNode.DerBoolean ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.Integer)
                newNode = new DerNode.DerInteger ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.BitString)
                newNode = new DerNode.DerBitString ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.OctetString)
                newNode = new DerNode.DerOctetString ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.Null)
                newNode = new DerNode.DerNull ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.ObjectIdentifier)
                newNode = new DerNode.DerOid ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.Sequence)
                newNode = new DerNode.DerSequence ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.PrintableString)
                newNode = new DerNode.DerPrintableString ();
            else if (nodeType == net.named_data.jndn.encoding.der.DerNodeType.GeneralizedTime)
                newNode = new DerNode.DerGeneralizedTime ();
            else
                throw new DerDecodingException("Unimplemented DER type " + nodeType);

            newNode.decode(inputBuf, startIdx);
            return newNode;
        }
Exemple #3
0
            /// <summary>
            /// Reverse the bytes in buffer starting at position, up to but not including
            /// limit.
            /// </summary>
            ///
            /// <param name="buffer"></param>
            /// <param name="position"></param>
            /// <param name="limit"></param>
            public static void reverse(ByteBuffer buffer, int position, int limit)
            {
                int from = position;
                int to = limit - 1;
                while (from < to) {
                    // swap
                    byte temp = buffer.get(from);
                    buffer.put(from, buffer.get(to));
                    buffer.put(to, temp);

                    --to;
                    ++from;
                }
            }
Exemple #4
0
        /// <summary>
        /// Extract the header from an input buffer and return the size.
        /// </summary>
        ///
        /// <param name="inputBuf">position.</param>
        /// <param name="startIdx">The offset into the buffer.</param>
        /// <returns>The parsed size in the header.</returns>
        protected internal int decodeHeader(ByteBuffer inputBuf, int startIdx)
        {
            int idx = startIdx;

            int nodeType = ((int) inputBuf.get(idx)) & 0xff;
            idx += 1;

            nodeType_ = nodeType;

            int sizeLen = ((int) inputBuf.get(idx)) & 0xff;
            idx += 1;

            DynamicByteBuffer header = new DynamicByteBuffer(10);
            header.ensuredPut((byte) nodeType);
            header.ensuredPut((byte) sizeLen);

            int size = sizeLen;
            bool isLongFormat = (sizeLen & (1 << 7)) != 0;
            if (isLongFormat) {
                int lenCount = sizeLen & ((1 << 7) - 1);
                size = 0;
                while (lenCount > 0) {
                    byte b = inputBuf.get(idx);
                    idx += 1;
                    header.ensuredPut(b);
                    size = 256 * size + (((int) b) & 0xff);
                    lenCount -= 1;
                }
            }

            header_ = header.flippedBuffer();
            return size;
        }
Exemple #5
0
            /// <summary>
            /// Create a new DerInteger from the bytes in the buffer. If bytes represent
            /// a positive integer, you must ensure that the first byte is less than 0x80.
            /// </summary>
            ///
            /// <param name="buffer"></param>
            /// <exception cref="DerEncodingException">if the first byte is not less than 0x80.</exception>
            public DerInteger(ByteBuffer buffer)
                : base(net.named_data.jndn.encoding.der.DerNodeType.Integer)
            {
                if (buffer.remaining() > 0
                        && (((int) buffer.get(buffer.position())) & 0xff) >= 0x80)
                    throw new DerEncodingException(
                            "DerInteger: Negative integers are not currently supported");

                if (buffer.remaining() == 0)
                    payload_.ensuredPut((byte) 0);
                else
                    payload_.ensuredPut(buffer);

                encodeHeader(payload_.position());
            }
        /// <summary>
        /// Continue scanning input starting from offset_ to find the element end.
        /// If the end of the element which started at offset 0 is found, this returns
        /// true and getOffset() is the length of the element.  Otherwise, this returns
        /// false which means you should read more into input and call again.
        /// </summary>
        ///
        /// <param name="input">You have to pass in input each time because the buffer could be reallocated.</param>
        /// <returns>true if found the element end, false if not.</returns>
        public bool findElementEnd(ByteBuffer input)
        {
            if (gotElementEnd_)
                // Someone is calling when we already got the end.
                return true;

            TlvDecoder decoder = new TlvDecoder(input);

            while (true) {
                if (offset_ >= input.limit())
                    // All the cases assume we have some input. Return and wait for more.
                    return false;

                if (state_ == TlvStructureDecoder.READ_TYPE) {
                    int firstOctet = (int) input.get(offset_) & 0xff;
                    offset_ += 1;
                    if (firstOctet < 253)
                        // The value is simple, so we can skip straight to reading the length.
                        state_ = TlvStructureDecoder.READ_LENGTH;
                    else {
                        // Set up to skip the type bytes.
                        if (firstOctet == 253)
                            nBytesToRead_ = 2;
                        else if (firstOctet == 254)
                            nBytesToRead_ = 4;
                        else
                            // value == 255.
                            nBytesToRead_ = 8;

                        state_ = TlvStructureDecoder.READ_TYPE_BYTES;
                    }
                } else if (state_ == TlvStructureDecoder.READ_TYPE_BYTES) {
                    int nRemainingBytes = input.limit() - offset_;
                    if (nRemainingBytes < nBytesToRead_) {
                        // Need more.
                        offset_ += nRemainingBytes;
                        nBytesToRead_ -= nRemainingBytes;
                        return false;
                    }

                    // Got the type bytes. Move on to read the length.
                    offset_ += nBytesToRead_;
                    state_ = TlvStructureDecoder.READ_LENGTH;
                } else if (state_ == TlvStructureDecoder.READ_LENGTH) {
                    int firstOctet_0 = (int) input.get(offset_) & 0xff;
                    offset_ += 1;
                    if (firstOctet_0 < 253) {
                        // The value is simple, so we can skip straight to reading
                        //  the value bytes.
                        nBytesToRead_ = firstOctet_0;
                        if (nBytesToRead_ == 0) {
                            // No value bytes to read. We're finished.
                            gotElementEnd_ = true;
                            return true;
                        }

                        state_ = TlvStructureDecoder.READ_VALUE_BYTES;
                    } else {
                        // We need to read the bytes in the extended encoding of
                        //  the length.
                        if (firstOctet_0 == 253)
                            nBytesToRead_ = 2;
                        else if (firstOctet_0 == 254)
                            nBytesToRead_ = 4;
                        else
                            // value == 255.
                            nBytesToRead_ = 8;

                        // We need to use firstOctet in the next state.
                        firstOctet_ = firstOctet_0;
                        state_ = TlvStructureDecoder.READ_LENGTH_BYTES;
                    }
                } else if (state_ == TlvStructureDecoder.READ_LENGTH_BYTES) {
                    int nRemainingBytes_1 = input.limit() - offset_;
                    if (!useHeaderBuffer_ && nRemainingBytes_1 >= nBytesToRead_) {
                        // We don't have to use the headerBuffer. Set nBytesToRead.
                        decoder.seek(offset_);

                        nBytesToRead_ = decoder.readExtendedVarNumber(firstOctet_);
                        // Update offset_ to the decoder's offset after reading.
                        offset_ = decoder.getOffset();
                    } else {
                        useHeaderBuffer_ = true;

                        int nNeededBytes = nBytesToRead_ - headerBuffer_.position();
                        if (nNeededBytes > nRemainingBytes_1) {
                            // We can't get all of the header bytes from this input.
                            // Save in headerBuffer.
                            if (headerBuffer_.position() + nRemainingBytes_1 > headerBuffer_
                                    .limit())
                                // We don't expect this to happen.
                                throw new Exception(
                                        "Cannot store more header bytes than the size of headerBuffer");
                            ByteBuffer remainingInput = input.duplicate();
                            remainingInput.position(offset_);
                            headerBuffer_.put(remainingInput);
                            offset_ += nRemainingBytes_1;

                            return false;
                        }

                        // Copy the remaining bytes into headerBuffer, read the
                        //   length and set nBytesToRead.
                        if (headerBuffer_.position() + nNeededBytes > headerBuffer_
                                .limit())
                            // We don't expect this to happen.
                            throw new Exception(
                                    "Cannot store more header bytes than the size of headerBuffer");
                        ByteBuffer remainingLengthBytes = input.duplicate();
                        remainingLengthBytes.position(offset_);
                        remainingLengthBytes.limit(offset_ + nNeededBytes);
                        headerBuffer_.put(remainingLengthBytes);
                        offset_ += nNeededBytes;

                        // Use a local decoder just for the headerBuffer.
                        headerBuffer_.flip();
                        TlvDecoder bufferDecoder = new TlvDecoder(headerBuffer_);
                        // Replace nBytesToRead with the length of the value.
                        nBytesToRead_ = bufferDecoder
                                .readExtendedVarNumber(firstOctet_);
                    }

                    if (nBytesToRead_ == 0) {
                        // No value bytes to read. We're finished.
                        gotElementEnd_ = true;
                        return true;
                    }

                    // Get ready to read the value bytes.
                    state_ = TlvStructureDecoder.READ_VALUE_BYTES;
                } else if (state_ == TlvStructureDecoder.READ_VALUE_BYTES) {
                    int nRemainingBytes_2 = input.limit() - offset_;
                    if (nRemainingBytes_2 < nBytesToRead_) {
                        // Need more.
                        offset_ += nRemainingBytes_2;
                        nBytesToRead_ -= nRemainingBytes_2;
                        return false;
                    }

                    // Got the bytes. We're finished.
                    offset_ += nBytesToRead_;
                    gotElementEnd_ = true;
                    return true;
                } else
                    // We don't expect this to happen.
                    throw new Exception("findElementEnd: unrecognized state");
            }
        }
        /// <summary>
        /// Set data to the host.
        /// </summary>
        /// <param name="data">The buffer of data to send.  This reads from position() to 
        /// limit(), but does not change the position.</param>
        public override void send(ByteBuffer data)
        {
            if (socket_ == null)
            throw new System.IO.IOException
              ("Cannot send because the socket is not open.  Use connect.");

              // ByteBuffer is readonly so we can't call array(), and we can't do a low-level
              //   operation on the array, so we have to copy.
              var buffer = new byte[data.remaining()];
              int savePosition = data.position();
              data.get(buffer);
              data.position(savePosition);

              socket_.Send(buffer);
        }
		private Bitmap decodeToBitmap(ByteBuffer jpegData, int sampleSize)
		{
			sbyte[] jpegDataArray = new sbyte[jpegData.remaining()];
			jpegData.get(jpegDataArray);
			jpegData.rewind();

			BitmapFactory.Options option = new BitmapFactory.Options();
			option.inSampleSize = sampleSize;

			return BitmapFactory.decodeByteArray(jpegDataArray, 0, jpegDataArray.Length, option);
		}
Exemple #9
0
 /// <summary>
 /// Write a hex string of the contents of buffer from position to limit to the
 /// output.
 /// </summary>
 ///
 /// <param name="buffer">The buffer.</param>
 /// <returns>A string of hex bytes.</returns>
 /// <param name="output">The StringBuffer to write to.</param>
 public static void toHex(ByteBuffer buffer, StringBuilder output)
 {
     for (int i = buffer.position(); i < buffer.limit(); ++i) {
         String hex = ILOG.J2CsMapping.Util.IlNumber.ToString((int) buffer.get(i) & 0xff,16);
         if (hex.Length <= 1)
             // Append the leading zero.
             output.append("0");
         output.append(hex);
     }
 }
Exemple #10
0
        public void onReceivedElement(ByteBuffer element)
        {
            LpPacket lpPacket = null;
            if (element.get(0) == net.named_data.jndn.encoding.tlv.Tlv.LpPacket_LpPacket) {
                // Decode the LpPacket and replace element with the fragment.
                lpPacket = new LpPacket();
                // Set copy false so that the fragment is a slice which will be copied below.
                // The header fields are all integers and don't need to be copied.
                net.named_data.jndn.encoding.TlvWireFormat.get().decodeLpPacket(lpPacket, element, false);
                element = lpPacket.getFragmentWireEncoding().buf();
            }

            // First, decode as Interest or Data.
            Interest interest = null;
            Data data = null;
            if (element.get(0) == net.named_data.jndn.encoding.tlv.Tlv.Interest || element.get(0) == net.named_data.jndn.encoding.tlv.Tlv.Data) {
                TlvDecoder decoder = new TlvDecoder(element);
                if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Interest, element.remaining())) {
                    interest = new Interest();
                    interest.wireDecode(element, net.named_data.jndn.encoding.TlvWireFormat.get());

                    if (lpPacket != null)
                        interest.setLpPacket(lpPacket);
                } else if (decoder.peekType(net.named_data.jndn.encoding.tlv.Tlv.Data, element.remaining())) {
                    data = new Data();
                    data.wireDecode(element, net.named_data.jndn.encoding.TlvWireFormat.get());

                    if (lpPacket != null)
                        data.setLpPacket(lpPacket);
                }
            }

            if (lpPacket != null) {
                // We have decoded the fragment, so remove the wire encoding to save memory.
                lpPacket.setFragmentWireEncoding(new Blob());

                NetworkNack networkNack = net.named_data.jndn.NetworkNack.getFirstHeader(lpPacket);
                if (networkNack != null) {
                    if (interest == null)
                        // We got a Nack but not for an Interest, so drop the packet.
                        return;

                    ArrayList<PendingInterestTable.Entry> pitEntries = new ArrayList<PendingInterestTable.Entry>();
                    pendingInterestTable_.extractEntriesForNackInterest(interest,
                            pitEntries);
                    for (int i = 0; i < pitEntries.Count; ++i) {
                        PendingInterestTable.Entry pendingInterest = pitEntries[i];
                        try {
                            pendingInterest.getOnNetworkNack().onNetworkNack(
                                    pendingInterest.getInterest(), networkNack);
                        } catch (Exception ex) {
                            logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onNack", ex);
                        }
                    }

                    // We have processed the network Nack packet.
                    return;
                }
            }

            // Now process as Interest or Data.
            if (interest != null) {
                // Quickly lock and get all interest filter callbacks which match.
                ArrayList matchedFilters = new ArrayList();
                interestFilterTable_.getMatchedFilters(interest, matchedFilters);

                // The lock on interestFilterTable_ is released, so call the callbacks.
                for (int i_0 = 0; i_0 < matchedFilters.Count; ++i_0) {
                    InterestFilterTable.Entry entry = (InterestFilterTable.Entry) matchedFilters[i_0];
                    try {
                        entry.getOnInterest().onInterest(
                                entry.getFilter().getPrefix(), interest,
                                entry.getFace(), entry.getInterestFilterId(),
                                entry.getFilter());
                    } catch (Exception ex_1) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onInterest", ex_1);
                    }
                }
            } else if (data != null) {
                ArrayList<PendingInterestTable.Entry> pitEntries_2 = new ArrayList<PendingInterestTable.Entry>();
                pendingInterestTable_.extractEntriesForExpressedInterest(data,
                        pitEntries_2);
                for (int i_3 = 0; i_3 < pitEntries_2.Count; ++i_3) {
                    PendingInterestTable.Entry pendingInterest_4 = pitEntries_2[i_3];
                    try {
                        pendingInterest_4.getOnData().onData(
                                pendingInterest_4.getInterest(), data);
                    } catch (Exception ex_5) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onData", ex_5);
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Compute the HMAC with SHA-256 of data, as defined in
        /// http://tools.ietf.org/html/rfc2104#section-2 .
        /// </summary>
        ///
        /// <param name="key">The key byte array.</param>
        /// <param name="data">The input byte buffer. This does not change the position.</param>
        /// <returns>The HMAC result.</returns>
        public static byte[] computeHmacWithSha256(byte[] key, ByteBuffer data)
        {
            using (var hmac = new HMACSHA256(key)) {
            // Copy the buffer to an array.
            var array = new byte[data.remaining()];
            int savePosition = data.position();
            data.get(array);
            data.position(savePosition);

            return hmac.ComputeHash(array);
              }
        }
Exemple #12
0
        /// <summary>
        /// Compute the sha-256 digest of data.
        /// </summary>
        ///
        /// <param name="data">The input byte buffer. This does not change the position.</param>
        /// <returns>The digest.</returns>
        public static byte[] digestSha256(ByteBuffer data)
        {
            // Copy the buffer to an array.
              var array = new byte[data.remaining()];
              int savePosition = data.position();
              data.get(array);
              data.position(savePosition);

              return sha256_.ComputeHash(array);
        }
        /**
	     * Send an object through the telemetry link.
	     * @throws IOException
	     * @param[in] obj Object handle to send
	     * @param[in] type Transaction type \return Success (true), Failure (false)
	     */
        private bool transmitSingleObject(UAVObject obj, int type, bool allInstances)
        {
            int length;
            int allInstId = uavConsts.ALL_INSTANCES;

            ByteBuffer bbuf = new ByteBuffer(uavConsts.MAX_PACKET_LENGTH);
            
            // Determine data length
            if (type == uavConsts.TYPE_OBJ_REQ || type == uavConsts.TYPE_ACK)
            {
                length = 0;
            }
            else
            {
                length = obj.getNumBytes();
            }

            // Setup type and object id fields
            bbuf.put((byte)(uavConsts.SYNC_VAL & 0xff));
            bbuf.put((byte)(type & 0xff));
            bbuf.putShort((UInt16)(length + 2 /* SYNC, Type */+ 2 /* Size */+ 4 /* ObjID */+ (obj
                            .isSingleInstance() ? 0 : 2)));
            bbuf.putUint32((UInt32)obj.getObjID());

            // Setup instance ID if one is required
            if (!obj.isSingleInstance())
            {
                // Check if all instances are requested
                if (allInstances)
                    bbuf.putShort((UInt16)(allInstId & 0xffff));
                else
                    bbuf.putShort((UInt16)(obj.getInstID() & 0xffff));
            }

            // Check length
            if (length >= uavConsts.MAX_PAYLOAD_LENGTH)
                return false;

            // Copy data (if any)
            if (length > 0)
                try
                {
                    if (obj.pack(bbuf) == 0)
                        return false;
                }
                catch (Exception e)
                {
                    // TODO Auto-generated catch block
                    Debug.Write(e.Message);
                    return false;
                }

            // Calculate checksum
            bbuf.put((byte)(CRC.updateCRC(0, bbuf.array(), bbuf.position()) & 0xff));

            int packlen = bbuf.position();
            bbuf.position(0);
            byte[] dst = new byte[packlen];
            bbuf.get(dst, 0, packlen);

            if (type == uavConsts.TYPE_OBJ_ACK || type == uavConsts.TYPE_OBJ_REQ)
            {
                // Once we send a UAVTalk packet that requires an ack or object let's set up
                // the transaction here
                setupTransaction(obj, allInstances, type);
            }

            ch.write(dst);


            // Update stats
            ++txStats.Objects;
            txStats.Bytes += bbuf.position();
            txStats.ObjectBytes += length;

            // Done
            return true;
        }
		private Bitmap decodeToBitmap(ByteBuffer jpegData, int sampleSize, int cropWidth)
		{
			sbyte[] jpegDataArray = new sbyte[jpegData.remaining()];
			jpegData.get(jpegDataArray);
			jpegData.rewind();

			BitmapFactory.Options option = new BitmapFactory.Options();
			option.inSampleSize = sampleSize;

			if (cropWidth == 0)
			{
				return BitmapFactory.decodeByteArray(jpegDataArray, 0, jpegDataArray.Length, option);
			}

			Bitmap bitmap = null;
			try
			{
				BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(jpegDataArray, 0, jpegDataArray.Length, true);

				int cropHeight = cropWidth * decoder.Height / decoder.Width;
				Rect cropRect = new Rect(decoder.Width / 2 - cropWidth, decoder.Height / 2 - cropHeight, decoder.Width / 2 + cropWidth, decoder.Height / 2 + cropHeight);

				bitmap = decoder.decodeRegion(cropRect, option);
			}
			catch (IOException e)
			{
				Console.WriteLine(e.ToString());
				Console.Write(e.StackTrace);
			}

			return bitmap;
		}