ArmoredInputStream.cs 13.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
using System;
using System.Collections;
using System.IO;
using System.Text;

using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.IO;

namespace Org.BouncyCastle.Bcpg
{
    /**
    * reader for Base64 armored objects - read the headers and then start returning
    * bytes when the data is reached. An IOException is thrown if the CRC check
    * fails.
    */
    public class ArmoredInputStream
        : BaseInputStream
    {
        /*
        * set up the decoding table.
        */
        private readonly static byte[] decodingTable;
        static ArmoredInputStream()
        {
            decodingTable = new byte[128];
            for (int i = 'A'; i <= 'Z'; i++)
            {
                decodingTable[i] = (byte)(i - 'A');
            }
            for (int i = 'a'; i <= 'z'; i++)
            {
                decodingTable[i] = (byte)(i - 'a' + 26);
            }
            for (int i = '0'; i <= '9'; i++)
            {
                decodingTable[i] = (byte)(i - '0' + 52);
            }
            decodingTable['+'] = 62;
            decodingTable['/'] = 63;
        }

        /**
        * decode the base 64 encoded input data.
        *
        * @return the offset the data starts in out.
        */
        private int Decode(
            int      in0,
            int      in1,
            int      in2,
            int      in3,
            int[]    result)
        {
            if (in3 < 0)
            {
                throw new EndOfStreamException("unexpected end of file in armored stream.");
            }

            int    b1, b2, b3, b4;
            if (in2 == '=')
            {
                b1 = decodingTable[in0] &0xff;
                b2 = decodingTable[in1] & 0xff;
                result[2] = ((b1 << 2) | (b2 >> 4)) & 0xff;
                return 2;
            }
            else if (in3 == '=')
            {
                b1 = decodingTable[in0];
                b2 = decodingTable[in1];
                b3 = decodingTable[in2];
                result[1] = ((b1 << 2) | (b2 >> 4)) & 0xff;
                result[2] = ((b2 << 4) | (b3 >> 2)) & 0xff;
                return 1;
            }
            else
            {
                b1 = decodingTable[in0];
                b2 = decodingTable[in1];
                b3 = decodingTable[in2];
                b4 = decodingTable[in3];
                result[0] = ((b1 << 2) | (b2 >> 4)) & 0xff;
                result[1] = ((b2 << 4) | (b3 >> 2)) & 0xff;
                result[2] = ((b3 << 6) | b4) & 0xff;
                return 0;
            }
        }

        Stream      input;
        bool        start = true;
        int[]       outBuf = new int[3];
        int         bufPtr = 3;
        Crc24       crc = new Crc24();
        bool        crcFound = false;
        bool        hasHeaders = true;
        string      header = null;
        bool        newLineFound = false;
        bool        clearText = false;
        bool        restart = false;
        IList       headerList= Platform.CreateArrayList();
        int         lastC = 0;
		bool		isEndOfStream;

        /**
        * Create a stream for reading a PGP armoured message, parsing up to a header
        * and then reading the data that follows.
        *
        * @param input
        */
        public ArmoredInputStream(
            Stream input)
			: this(input, true)
        {
        }

		/**
        * Create an armoured input stream which will assume the data starts
        * straight away, or parse for headers first depending on the value of
        * hasHeaders.
        *
        * @param input
        * @param hasHeaders true if headers are to be looked for, false otherwise.
        */
        public ArmoredInputStream(
            Stream	input,
            bool	hasHeaders)
        {
            this.input = input;
            this.hasHeaders = hasHeaders;

			if (hasHeaders)
            {
                ParseHeaders();
            }

			start = false;
        }

		private bool ParseHeaders()
        {
            header = null;

			int		c;
            int		last = 0;
            bool	headerFound = false;

            headerList = Platform.CreateArrayList();

			//
            // if restart we already have a header
            //
            if (restart)
            {
                headerFound = true;
            }
            else
            {
                while ((c = input.ReadByte()) >= 0)
                {
                    if (c == '-' && (last == 0 || last == '\n' || last == '\r'))
                    {
                        headerFound = true;
                        break;
                    }

					last = c;
                }
            }

			if (headerFound)
            {
                StringBuilder    Buffer = new StringBuilder("-");
                bool             eolReached = false;
                bool             crLf = false;

				if (restart)    // we've had to look ahead two '-'
                {
                    Buffer.Append('-');
                }

				while ((c = input.ReadByte()) >= 0)
                {
                    if (last == '\r' && c == '\n')
                    {
                        crLf = true;
                    }
                    if (eolReached && (last != '\r' && c == '\n'))
                    {
                        break;
                    }
                    if (eolReached && c == '\r')
                    {
                        break;
                    }
                    if (c == '\r' || (last != '\r' && c == '\n'))
                    {
						string line = Buffer.ToString();
						if (line.Trim().Length < 1)
							break;
                        headerList.Add(line);
                        Buffer.Length = 0;
                    }

                    if (c != '\n' && c != '\r')
                    {
                        Buffer.Append((char)c);
                        eolReached = false;
                    }
                    else
                    {
                        if (c == '\r' || (last != '\r' && c == '\n'))
                        {
                            eolReached = true;
                        }
                    }

					last = c;
                }

				if (crLf)
                {
                    input.ReadByte(); // skip last \n
                }
            }

			if (headerList.Count > 0)
            {
                header = (string) headerList[0];
            }

			clearText = "-----BEGIN PGP SIGNED MESSAGE-----".Equals(header);
            newLineFound = true;

			return headerFound;
        }

		/**
        * @return true if we are inside the clear text section of a PGP
        * signed message.
        */
        public bool IsClearText()
        {
            return clearText;
        }

		/**
		 * @return true if the stream is actually at end of file.
		 */
		public bool IsEndOfStream()
		{
			return isEndOfStream;
		}

		/**
        * Return the armor header line (if there is one)
        * @return the armor header line, null if none present.
        */
        public string GetArmorHeaderLine()
        {
            return header;
        }

		/**
        * Return the armor headers (the lines after the armor header line),
        * @return an array of armor headers, null if there aren't any.
        */
        public string[] GetArmorHeaders()
        {
            if (headerList.Count <= 1)
            {
                return null;
            }

			string[] hdrs = new string[headerList.Count - 1];
            for (int i = 0; i != hdrs.Length; i++)
            {
                hdrs[i] = (string) headerList[i + 1];
            }

			return hdrs;
        }

		private int ReadIgnoreSpace()
        {
            int c;
            do
            {
                c = input.ReadByte();
            }
            while (c == ' ' || c == '\t');

			return c;
        }

		private int ReadIgnoreWhitespace()
        {
            int c;
            do
            {
                c = input.ReadByte();
            }
            while (c == ' ' || c == '\t' || c == '\r' || c == '\n');

            return c;
        }

		private int ReadByteClearText()
        {
            int c = input.ReadByte();

            if (c == '\r' || (c == '\n' && lastC != '\r'))
            {
                newLineFound = true;
            }
            else if (newLineFound && c == '-')
            {
                c = input.ReadByte();
                if (c == '-')            // a header, not dash escaped
                {
                    clearText = false;
                    start = true;
                    restart = true;
                }
                else                   // a space - must be a dash escape
                {
                    c = input.ReadByte();
                }
                newLineFound = false;
            }
            else
            {
                if (c != '\n' && lastC != '\r')
                {
                    newLineFound = false;
                }
            }

            lastC = c;

			if (c < 0)
			{
				isEndOfStream = true;
			}

			return c;
        }

        private int ReadClearText(byte[] buffer, int offset, int count)
        {
            int pos = offset;
            try
            {
                int end = offset + count;
                while (pos < end)
                {
                    int c = ReadByteClearText();
                    if (c == -1)
                    {
                        break;
                    }
                    buffer[pos++] = (byte) c;
                }
            }
            catch (IOException ioe)
            {
                if (pos == offset) throw ioe;
            }

			return pos - offset;
        }

        private int DoReadByte()
        {
            if (bufPtr > 2 || crcFound)
            {
                int c = ReadIgnoreSpace();
                if (c == '\n' || c == '\r')
                {
                    c = ReadIgnoreWhitespace();
                    if (c == '=')            // crc reached
                    {
                        bufPtr = Decode(ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), outBuf);

                        if (bufPtr != 0)
                        {
                            throw new IOException("no crc found in armored message.");
                        }

                        crcFound = true;

                        int i = ((outBuf[0] & 0xff) << 16)
                            | ((outBuf[1] & 0xff) << 8)
                            | (outBuf[2] & 0xff);

                        if (i != crc.Value)
                        {
                            throw new IOException("crc check failed in armored message.");
                        }

						return ReadByte();
                    }

                    if (c == '-')        // end of record reached
                    {
                        while ((c = input.ReadByte()) >= 0)
                        {
                            if (c == '\n' || c == '\r')
                            {
                                break;
                            }
                        }

                        if (!crcFound)
                        {
                            throw new IOException("crc check not found.");
                        }

                        crcFound = false;
                        start = true;
                        bufPtr = 3;

						if (c < 0)
						{
							isEndOfStream = true;
						}

						return -1;
                    }
                }

                if (c < 0)
                {
					isEndOfStream = true;
					return -1;
                }

                bufPtr = Decode(c, ReadIgnoreSpace(), ReadIgnoreSpace(), ReadIgnoreSpace(), outBuf);
            }

            return outBuf[bufPtr++];
        }

        public override int ReadByte()
        {
            if (start)
            {
                if (hasHeaders)
                {
                    ParseHeaders();
                }

				crc.Reset();
				start = false;
            }

			if (clearText)
            {
                return ReadByteClearText();
            }

            int c = DoReadByte();

            crc.Update(c);

            return c;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (start && count > 0)
            {
                if (hasHeaders)
                {
                    ParseHeaders();
                }
                start = false;
            }

            if (clearText)
            {
                return ReadClearText(buffer, offset, count);
            }

            int pos = offset;
            try
            {
                int end = offset + count;
                while (pos < end)
                {
                    int c = DoReadByte();
                    crc.Update(c);
                    if (c == -1)
                    {
                        break;
                    }
                    buffer[pos++] = (byte) c;
                }
            }
            catch (IOException ioe)
            {
                if (pos == offset) throw ioe;
            }

            return pos - offset;
        }

#if PORTABLE
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Platform.Dispose(input);
            }
            base.Dispose(disposing);
        }
#else
		public override void Close()
		{
            Platform.Dispose(input);
			base.Close();
		}
#endif
    }
}