Exemplo n.º 1
0
 public static sbyte[] ReadBytes([NotNull] FilePath file)
 {
     int length = (int)file.Length();
     // should only be zero if loading from a network or similar
     System.Diagnostics.Debug.Assert((length != 0));
     sbyte[] bytes = new sbyte[length];
     int totalBytesRead = 0;
     FileInputStream inputStream = null;
     try
     {
         inputStream = new FileInputStream(file);
         while (totalBytesRead != length)
         {
             int bytesRead = inputStream.Read(bytes, totalBytesRead, length - totalBytesRead);
             if (bytesRead == -1)
             {
                 break;
             }
             totalBytesRead += bytesRead;
         }
     }
     finally
     {
         if (inputStream != null)
         {
             inputStream.Close();
         }
     }
     return bytes;
 }
Exemplo n.º 2
0
		/// <exception cref="System.IO.IOException"></exception>
		protected internal static void CopyFile(FilePath src, FilePath dst)
		{
			FileInputStream fis = new FileInputStream(src);
			try
			{
				FileOutputStream fos = new FileOutputStream(dst);
				try
				{
					byte[] buf = new byte[4096];
					int r;
					while ((r = fis.Read(buf)) > 0)
					{
						fos.Write(buf, 0, r);
					}
				}
				finally
				{
					fos.Close();
				}
			}
			finally
			{
				fis.Close();
			}
		}
Exemplo n.º 3
0
 /// <summary>Copy the current file content into the temporary file.</summary>
 /// <remarks>
 /// Copy the current file content into the temporary file.
 /// <p>
 /// This method saves the current file content by inserting it into the
 /// temporary file, so that the caller can safely append rather than replace
 /// the primary file.
 /// <p>
 /// This method does nothing if the current file does not exist, or exists
 /// but is empty.
 /// </remarks>
 /// <exception cref="System.IO.IOException">
 /// the temporary file could not be written, or a read error
 /// occurred while reading from the current file. The lock is
 /// released before throwing the underlying IO exception to the
 /// caller.
 /// </exception>
 /// <exception cref="Sharpen.RuntimeException">
 /// the temporary file could not be written. The lock is released
 /// before throwing the underlying exception to the caller.
 /// </exception>
 public virtual void CopyCurrentContent()
 {
     RequireLock();
     try
     {
         FileInputStream fis = new FileInputStream(@ref);
         try
         {
             if (fsync)
             {
                 FileChannel @in = fis.GetChannel();
                 long pos = 0;
                 long cnt = @in.Size();
                 while (0 < cnt)
                 {
                     long r = os.GetChannel().TransferFrom(@in, pos, cnt);
                     pos += r;
                     cnt -= r;
                 }
             }
             else
             {
                 byte[] buf = new byte[2048];
                 int r;
                 while ((r = fis.Read(buf)) >= 0)
                 {
                     os.Write(buf, 0, r);
                 }
             }
         }
         finally
         {
             fis.Close();
         }
     }
     catch (FileNotFoundException)
     {
     }
     catch (IOException ioe)
     {
         // Don't worry about a file that doesn't exist yet, it
         // conceptually has no current content to copy.
         //
         Unlock();
         throw;
     }
     catch (RuntimeException ioe)
     {
         Unlock();
         throw;
     }
     catch (Error ioe)
     {
         Unlock();
         throw;
     }
 }
Exemplo n.º 4
0
        /// <exception cref="NGit.Errors.CorruptObjectException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void AssertWorkDir(Dictionary<string, string> i)
        {
            TreeWalk walk = new TreeWalk(db);
            walk.Recursive = true;
            walk.AddTree(new FileTreeIterator(db));
            string expectedValue;
            string path;
            int nrFiles = 0;
            FileTreeIterator ft;
            while (walk.Next())
            {
                ft = walk.GetTree<FileTreeIterator>(0);
                path = ft.EntryPathString;
                expectedValue = i.Get(path);
                NUnit.Framework.Assert.IsNotNull(expectedValue, "found unexpected file for path "
                     + path + " in workdir");
                FilePath file = new FilePath(db.WorkTree, path);
                NUnit.Framework.Assert.IsTrue(file.Exists());
                if (file.IsFile())
                {
                    FileInputStream @is = new FileInputStream(file);
                    byte[] buffer = new byte[(int)file.Length()];
                    int offset = 0;
                    int numRead = 0;
                    while (offset < buffer.Length && (numRead = @is.Read(buffer, offset, buffer.Length
                         - offset)) >= 0)
                    {
                        offset += numRead;
                    }
                    @is.Close();

                    CollectionAssert.AreEqual (buffer, Sharpen.Runtime.GetBytesForString(i.Get(path)),
                        "unexpected content for path " + path + " in workDir. ");
                    nrFiles++;
                }
            }
            NUnit.Framework.Assert.AreEqual(i.Count, nrFiles, "WorkDir has not the right size."
                );
        }
 /// <exception cref="System.IO.IOException"></exception>
 public override void WriteTo(OutputStream @out)
 {
     if (@out == null)
     {
         throw new ArgumentException("Output stream may not be null");
     }
     InputStream @in = new FileInputStream(this.file);
     try
     {
         byte[] tmp = new byte[4096];
         int l;
         while ((l = @in.Read(tmp)) != -1)
         {
             @out.Write(tmp, 0, l);
         }
         @out.Flush();
     }
     finally
     {
         @in.Close();
     }
 }
Exemplo n.º 6
0
			/// <exception cref="System.IO.IOException"></exception>
			public override void WriteTo(OutputStream os, ProgressMonitor pm)
			{
				if (onDiskFile == null)
				{
					base.WriteTo(os, pm);
					return;
				}
				if (pm == null)
				{
					pm = NullProgressMonitor.INSTANCE;
				}
				FileInputStream @in = new FileInputStream(onDiskFile);
				try
				{
					int cnt;
					byte[] buf = new byte[TemporaryBuffer.Block.SZ];
					while ((cnt = @in.Read(buf)) >= 0)
					{
						os.Write(buf, 0, cnt);
						pm.Update(cnt / 1024);
					}
				}
				finally
				{
					@in.Close();
				}
			}
Exemplo n.º 7
0
 public static BlobKey KeyForBlobFromFile(FileInfo file)
 {
     MessageDigest md;
     try
     {
         md = MessageDigest.GetInstance("SHA-1");
     }
     catch (NoSuchAlgorithmException)
     {
         Log.E(Database.Tag, "Error, SHA-1 digest is unavailable.");
         return null;
     }
     byte[] sha1hash = new byte[40];
     try
     {
         var fis = new FileInputStream(file);
         byte[] buffer = new byte[65536];
         int lenRead = fis.Read(buffer);
         while (lenRead > 0)
         {
             md.Update(buffer, 0, lenRead);
             lenRead = fis.Read(buffer);
         }
         fis.Close();
     }
     catch (IOException)
     {
         Log.E(Database.Tag, "Error readin tmp file to compute key");
     }
     sha1hash = md.Digest();
     BlobKey result = new BlobKey(sha1hash);
     return result;
 }
Exemplo n.º 8
0
 /// <exception cref="System.IO.IOException"></exception>
 private static byte[] GetBytesFromFile(FilePath file)
 {
     InputStream @is = new FileInputStream(file);
     // Get the size of the file
     long length = file.Length();
     // Create the byte array to hold the data
     byte[] bytes = new byte[(int)length];
     // Read in the bytes
     int offset = 0;
     int numRead = 0;
     while (offset < bytes.Length && (numRead = @is.Read(bytes, offset, bytes.Length -
          offset)) >= 0)
     {
         offset += numRead;
     }
     // Ensure all the bytes have been read in
     if (offset < bytes.Length)
     {
         throw new IOException("Could not completely read file " + file.GetName());
     }
     // Close the input stream and return bytes
     @is.Close();
     return bytes;
 }
Exemplo n.º 9
0
 /// <exception cref="System.IO.IOException"></exception>
 private void AssertFileContentsEqual(FilePath actFile, string @string)
 {
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     FileInputStream fis = null;
     byte[] buffer = new byte[100];
     try
     {
         fis = new FileInputStream(actFile);
         int read = fis.Read(buffer);
         while (read > 0)
         {
             bos.Write(buffer, 0, read);
             read = fis.Read(buffer);
         }
         string content = Sharpen.Runtime.GetStringForBytes(bos.ToByteArray(), "UTF-8");
         NUnit.Framework.Assert.AreEqual(@string, content);
     }
     finally
     {
         if (fis != null)
         {
             fis.Close();
         }
     }
 }
Exemplo n.º 10
0
		/// <exception cref="NSch.JSchException"></exception>
		public static NSch.KeyPair Load(JSch jsch, string prvkey, string pubkey)
		{
			byte[] iv = new byte[8];
			// 8
			bool encrypted = true;
			byte[] data = null;
			byte[] publickeyblob = null;
			int type = ERROR;
			int vendor = VENDOR_OPENSSH;
			try
			{
				FilePath file = new FilePath(prvkey);
				FileInputStream fis = new FileInputStream(prvkey);
				byte[] buf = new byte[(int)(file.Length())];
				int len = 0;
				while (true)
				{
					int i = fis.Read(buf, len, buf.Length - len);
					if (i <= 0)
					{
						break;
					}
					len += i;
				}
				fis.Close();
				int i_1 = 0;
				while (i_1 < len)
				{
					if (buf[i_1] == 'B' && buf[i_1 + 1] == 'E' && buf[i_1 + 2] == 'G' && buf[i_1 + 3]
						 == 'I')
					{
						i_1 += 6;
						if (buf[i_1] == 'D' && buf[i_1 + 1] == 'S' && buf[i_1 + 2] == 'A')
						{
							type = DSA;
						}
						else
						{
							if (buf[i_1] == 'R' && buf[i_1 + 1] == 'S' && buf[i_1 + 2] == 'A')
							{
								type = RSA;
							}
							else
							{
								if (buf[i_1] == 'S' && buf[i_1 + 1] == 'S' && buf[i_1 + 2] == 'H')
								{
									// FSecure
									type = UNKNOWN;
									vendor = VENDOR_FSECURE;
								}
								else
								{
									//System.err.println("invalid format: "+identity);
									throw new JSchException("invalid privatekey: " + prvkey);
								}
							}
						}
						i_1 += 3;
						continue;
					}
					if (buf[i_1] == 'C' && buf[i_1 + 1] == 'B' && buf[i_1 + 2] == 'C' && buf[i_1 + 3]
						 == ',')
					{
						i_1 += 4;
						for (int ii = 0; ii < iv.Length; ii++)
						{
							iv[ii] = unchecked((byte)(((A2b(buf[i_1++]) << 4) & unchecked((int)(0xf0))) + (A2b
								(buf[i_1++]) & unchecked((int)(0xf)))));
						}
						continue;
					}
					if (buf[i_1] == unchecked((int)(0x0d)) && i_1 + 1 < buf.Length && buf[i_1 + 1] ==
						 unchecked((int)(0x0a)))
					{
						i_1++;
						continue;
					}
					if (buf[i_1] == unchecked((int)(0x0a)) && i_1 + 1 < buf.Length)
					{
						if (buf[i_1 + 1] == unchecked((int)(0x0a)))
						{
							i_1 += 2;
							break;
						}
						if (buf[i_1 + 1] == unchecked((int)(0x0d)) && i_1 + 2 < buf.Length && buf[i_1 + 2
							] == unchecked((int)(0x0a)))
						{
							i_1 += 3;
							break;
						}
						bool inheader = false;
						for (int j = i_1 + 1; j < buf.Length; j++)
						{
							if (buf[j] == unchecked((int)(0x0a)))
							{
								break;
							}
							//if(buf[j]==0x0d) break;
							if (buf[j] == ':')
							{
								inheader = true;
								break;
							}
						}
						if (!inheader)
						{
							i_1++;
							encrypted = false;
							// no passphrase
							break;
						}
					}
					i_1++;
				}
				if (type == ERROR)
				{
					throw new JSchException("invalid privatekey: " + prvkey);
				}
				int start = i_1;
				while (i_1 < len)
				{
					if (buf[i_1] == unchecked((int)(0x0a)))
					{
						bool xd = (buf[i_1 - 1] == unchecked((int)(0x0d)));
						System.Array.Copy(buf, i_1 + 1, buf, i_1 - (xd ? 1 : 0), len - i_1 - 1 - (xd ? 1 : 
							0));
						if (xd)
						{
							len--;
						}
						len--;
						continue;
					}
					if (buf[i_1] == '-')
					{
						break;
					}
					i_1++;
				}
				data = Util.FromBase64(buf, start, i_1 - start);
				if (data.Length > 4 && data[0] == unchecked((byte)unchecked((int)(0x3f))) && data
					[1] == unchecked((byte)unchecked((int)(0x6f))) && data[2] == unchecked((byte)unchecked(
					(int)(0xf9))) && data[3] == unchecked((byte)unchecked((int)(0xeb))))
				{
					// FSecure
					Buffer _buf = new Buffer(data);
					_buf.GetInt();
					// 0x3f6ff9be
					_buf.GetInt();
					byte[] _type = _buf.GetString();
					//System.err.println("type: "+new String(_type)); 
					byte[] _cipher = _buf.GetString();
					string cipher = Util.Byte2str(_cipher);
					//System.err.println("cipher: "+cipher); 
					if (cipher.Equals("3des-cbc"))
					{
						_buf.GetInt();
						byte[] foo = new byte[data.Length - _buf.GetOffSet()];
						_buf.GetByte(foo);
						data = foo;
						encrypted = true;
						throw new JSchException("unknown privatekey format: " + prvkey);
					}
					else
					{
						if (cipher.Equals("none"))
						{
							_buf.GetInt();
							_buf.GetInt();
							encrypted = false;
							byte[] foo = new byte[data.Length - _buf.GetOffSet()];
							_buf.GetByte(foo);
							data = foo;
						}
					}
				}
				if (pubkey != null)
				{
					try
					{
						file = new FilePath(pubkey);
						fis = new FileInputStream(pubkey);
						buf = new byte[(int)(file.Length())];
						len = 0;
						while (true)
						{
							i_1 = fis.Read(buf, len, buf.Length - len);
							if (i_1 <= 0)
							{
								break;
							}
							len += i_1;
						}
						fis.Close();
						if (buf.Length > 4 && buf[0] == '-' && buf[1] == '-' && buf[2] == '-' && buf[3] ==
							 '-')
						{
							// FSecure's public key
							bool valid = true;
							i_1 = 0;
							do
							{
								i_1++;
							}
							while (buf.Length > i_1 && buf[i_1] != unchecked((int)(0x0a)));
							if (buf.Length <= i_1)
							{
								valid = false;
							}
							while (valid)
							{
								if (buf[i_1] == unchecked((int)(0x0a)))
								{
									bool inheader = false;
									for (int j = i_1 + 1; j < buf.Length; j++)
									{
										if (buf[j] == unchecked((int)(0x0a)))
										{
											break;
										}
										if (buf[j] == ':')
										{
											inheader = true;
											break;
										}
									}
									if (!inheader)
									{
										i_1++;
										break;
									}
								}
								i_1++;
							}
							if (buf.Length <= i_1)
							{
								valid = false;
							}
							start = i_1;
							while (valid && i_1 < len)
							{
								if (buf[i_1] == unchecked((int)(0x0a)))
								{
									System.Array.Copy(buf, i_1 + 1, buf, i_1, len - i_1 - 1);
									len--;
									continue;
								}
								if (buf[i_1] == '-')
								{
									break;
								}
								i_1++;
							}
							if (valid)
							{
								publickeyblob = Util.FromBase64(buf, start, i_1 - start);
								if (type == UNKNOWN)
								{
									if (publickeyblob[8] == 'd')
									{
										type = DSA;
									}
									else
									{
										if (publickeyblob[8] == 'r')
										{
											type = RSA;
										}
									}
								}
							}
						}
						else
						{
							if (buf[0] == 's' && buf[1] == 's' && buf[2] == 'h' && buf[3] == '-')
							{
								i_1 = 0;
								while (i_1 < len)
								{
									if (buf[i_1] == ' ')
									{
										break;
									}
									i_1++;
								}
								i_1++;
								if (i_1 < len)
								{
									start = i_1;
									while (i_1 < len)
									{
										if (buf[i_1] == ' ')
										{
											break;
										}
										i_1++;
									}
									publickeyblob = Util.FromBase64(buf, start, i_1 - start);
								}
							}
						}
					}
					catch (Exception)
					{
					}
				}
			}
			catch (Exception e)
			{
				if (e is JSchException)
				{
					throw (JSchException)e;
				}
				if (e is Exception)
				{
					throw new JSchException(e.ToString(), (Exception)e);
				}
				throw new JSchException(e.ToString());
			}
			NSch.KeyPair kpair = null;
			if (type == DSA)
			{
				kpair = new KeyPairDSA(jsch);
			}
			else
			{
				if (type == RSA)
				{
					kpair = new KeyPairRSA(jsch);
				}
			}
			if (kpair != null)
			{
				kpair.encrypted = encrypted;
				kpair.publickeyblob = publickeyblob;
				kpair.vendor = vendor;
				if (encrypted)
				{
					kpair.iv = iv;
					kpair.data = data;
				}
				else
				{
					if (kpair.Parse(data))
					{
						return kpair;
					}
					else
					{
						throw new JSchException("invalid privatekey: " + prvkey);
					}
				}
			}
			return kpair;
		}
Exemplo n.º 11
0
 /// <summary>Read at most limit bytes from the local file into memory as a byte array.
 /// 	</summary>
 /// <remarks>Read at most limit bytes from the local file into memory as a byte array.
 /// 	</remarks>
 /// <param name="path">location of the file to read.</param>
 /// <param name="limit">
 /// maximum number of bytes to read, if the file is larger than
 /// only the first limit number of bytes are returned
 /// </param>
 /// <returns>
 /// complete contents of the requested local file. If the contents
 /// exceeds the limit, then only the limit is returned.
 /// </returns>
 /// <exception cref="System.IO.FileNotFoundException">the file does not exist.</exception>
 /// <exception cref="System.IO.IOException">the file exists, but its contents cannot be read.
 /// 	</exception>
 public static byte[] ReadSome(FilePath path, int limit)
 {
     FileInputStream @in = new FileInputStream(path);
     try
     {
         byte[] buf = new byte[limit];
         int cnt = 0;
         for (; ; )
         {
             int n = @in.Read(buf, cnt, buf.Length - cnt);
             if (n <= 0)
             {
                 break;
             }
             cnt += n;
         }
         if (cnt == buf.Length)
         {
             return buf;
         }
         byte[] res = new byte[cnt];
         System.Array.Copy(buf, 0, res, 0, cnt);
         return res;
     }
     finally
     {
         try
         {
             @in.Close();
         }
         catch (IOException)
         {
         }
     }
 }
Exemplo n.º 12
0
		// DSA
		// RSA
		// modulus
		// public exponent
		// private exponent
		//  private String algname="ssh-dss";
		/// <exception cref="NSch.JSchException"></exception>
		internal static NSch.IdentityFile NewInstance(string prvfile, string pubfile, JSch
			 jsch)
		{
			byte[] prvkey = null;
			byte[] pubkey = null;
			FilePath file = null;
			FileInputStream fis = null;
			try
			{
				file = new FilePath(prvfile);
				fis = new FileInputStream(prvfile);
				prvkey = new byte[(int)(file.Length())];
				int len = 0;
				while (true)
				{
					int i = fis.Read(prvkey, len, prvkey.Length - len);
					if (i <= 0)
					{
						break;
					}
					len += i;
				}
				fis.Close();
			}
			catch (Exception e)
			{
				try
				{
					if (fis != null)
					{
						fis.Close();
					}
				}
				catch (Exception)
				{
				}
				if (e is Exception)
				{
					throw new JSchException(e.ToString(), (Exception)e);
				}
				throw new JSchException(e.ToString());
			}
			string _pubfile = pubfile;
			if (pubfile == null)
			{
				_pubfile = prvfile + ".pub";
			}
			try
			{
				file = new FilePath(_pubfile);
				fis = new FileInputStream(_pubfile);
				pubkey = new byte[(int)(file.Length())];
				int len = 0;
				while (true)
				{
					int i = fis.Read(pubkey, len, pubkey.Length - len);
					if (i <= 0)
					{
						break;
					}
					len += i;
				}
				fis.Close();
			}
			catch (Exception e)
			{
				try
				{
					if (fis != null)
					{
						fis.Close();
					}
				}
				catch (Exception)
				{
				}
				if (pubfile != null)
				{
					// The pubfile is explicitry given, but not accessible.
					if (e is Exception)
					{
						throw new JSchException(e.ToString(), (Exception)e);
					}
					throw new JSchException(e.ToString());
				}
			}
			return NewInstance(prvfile, prvkey, pubkey, jsch);
		}
Exemplo n.º 13
0
 // do nothing
 /// <summary>Read an entire local file into memory as a byte array.</summary>
 /// <remarks>Read an entire local file into memory as a byte array.</remarks>
 /// <param name="path">location of the file to read.</param>
 /// <param name="max">
 /// maximum number of bytes to read, if the file is larger than
 /// this limit an IOException is thrown.
 /// </param>
 /// <returns>complete contents of the requested local file.</returns>
 /// <exception cref="System.IO.FileNotFoundException">the file does not exist.</exception>
 /// <exception cref="System.IO.IOException">the file exists, but its contents cannot be read.
 /// 	</exception>
 public static byte[] ReadFully(FilePath path, int max)
 {
     FileInputStream @in = new FileInputStream(path);
     try
     {
         long sz = Math.Max(path.Length(), 1);
         if (sz > max)
         {
             throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path));
         }
         byte[] buf = new byte[(int)sz];
         int valid = 0;
         for (; ; )
         {
             if (buf.Length == valid)
             {
                 if (buf.Length == max)
                 {
                     int next = @in.Read();
                     if (next < 0)
                     {
                         break;
                     }
                     throw new IOException(MessageFormat.Format(JGitText.Get().fileIsTooLarge, path));
                 }
                 byte[] nb = new byte[Math.Min(buf.Length * 2, max)];
                 System.Array.Copy(buf, 0, nb, 0, valid);
                 buf = nb;
             }
             int n = @in.Read(buf, valid, buf.Length - valid);
             if (n < 0)
             {
                 break;
             }
             valid += n;
         }
         if (valid < buf.Length)
         {
             byte[] nb = new byte[valid];
             System.Array.Copy(buf, 0, nb, 0, valid);
             buf = nb;
         }
         return buf;
     }
     finally
     {
         try
         {
             @in.Close();
         }
         catch (IOException)
         {
         }
     }
 }