using System;
using bareFTP.Preferences;

namespace bareFTP.Protocol.Sftp
{

/* C#-ified for bareFTP by Christian Eide
 * Original Copyright follows:
 */
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright 
     notice, this list of conditions and the following disclaimer in 
     the documentation and/or other materials provided with the distribution.

  3. The names of the authors may not be used to endorse or promote products
     derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

	public class HostKey
	{
		
		private static byte[] sshdss = System.Text.Encoding.Default.GetBytes("ssh-dss");
		private static byte[] sshrsa = System.Text.Encoding.Default.GetBytes("ssh-rsa");
		
		private const string HASH_MAGIC="|1|";
	    private const string HASH_DELIM="|";
		
		private bool hashed=false;
		private MAC hmacsha1=null;
		private byte[] salt=null;
	    private byte[] _hash=null;
		
		public const int GUESS = 0;
		public const int SSHDSS = 1;
		public const int SSHRSA = 2;
		public const int UNKNOWN = 3;

		private string _host;
		private int _type;
		private byte[] _key;
		
		public HostKey(Config conf, string host, int type, byte[] key)
		{
			_host = host;
			
			// Guess the type
			if(type == GUESS)
			{
				if(key[8]=='d') { _type=SSHDSS; }
				else if(key[8]=='r'){ _type=SSHRSA; }
				else { throw new System.Exception("invalid key type"); }
			}
			else
			{
				_type = type;
			}
			 
			_key=key;
						
			if(_host.StartsWith(HASH_MAGIC) &&
			   _host.Substring(HASH_MAGIC.Length).IndexOf(HASH_DELIM)>0)
			{
				string data = _host.Substring(HASH_MAGIC.Length);
				string _salt = data.Substring(0, data.IndexOf(HASH_DELIM));
				string __hash = data.Substring(data.IndexOf(HASH_DELIM)+1);
				salt= Util.fromBase64(System.Text.Encoding.Default.GetBytes(_salt), 0, _salt.Length);
				_hash = Util.fromBase64(System.Text.Encoding.Default.GetBytes(__hash), 0, __hash.Length);
				if(salt.Length != 20 ||  // block size of hmac-sha1
				   _hash.Length!=20){
					salt=null;
					_hash=null;
					return;
				}
				
				hashed=true;
			}
		}
		
		public string Host
		{ 
			get { return _host; } 
			set { _host = value; }
		}
		
		public string KeyType
		{
			get
			{
				if(_type == SSHDSS)
					return System.Text.Encoding.Default.GetString(sshdss);
				if(_type == SSHRSA)
					return System.Text.Encoding.Default.GetString(sshrsa);
				return "UNKNOWN";
			}
		}
		
		public int _Type
		{
			get { return _type; }
		}
		
		public string Key
		{
			get { return Convert.ToBase64String(_key, 0, _key.Length) ; }
		}
		
		public byte[] _Key
		{
			get { return _key; }
		}
		
		public string getFingerPrint(Config conf)
		{
			HASH hash = null;
			try
			{
				hash = new bareFTP.Protocol.Sftp.jce.MD5() as HASH;
			}
			catch(Exception e)
			{ 
				Console.Error.WriteLine("getFingerPrint: " + e.ToString()); 
			}
			return Util.getFingerPrint(hash, _key);
		}
		
		public bool isMatched(string host)
		{
			if(!hashed)
				return isIncluded(host);
			else
			{
				MAC macsha1= getHMACSHA1();
				try
				{
					lock(macsha1)
					{
						macsha1.init(salt);
						byte[] foo = System.Text.Encoding.Default.GetBytes(host);
						macsha1.update(foo, 0, foo.Length);
						byte[] bar = macsha1.doFinal();
						return Util.array_equals(_hash, bar);
					}
				}
				catch(Exception e){
					Console.WriteLine(e.ToString());
				}
				return false;
			}
		}
		
		public bool Hashed {
	      get { return hashed; }
	    }
		
		private bool isIncluded(string host)
		{
			
			int i = 0;
			string hosts = _host;
			int hostslen = hosts.Length;
			int hostlen = host.Length;
			int j;
			while(i<hostslen)
			{
				j = hosts.IndexOf(',', i);
				if( j == -1)
				{
					if(hostlen != hostslen - i)
						return false;
					//return
					
					return hosts.ToUpper().Substring(i, hostlen).CompareTo(host.ToUpper().Substring(0, hostlen)) == 0 ? true : false;
				}
				if(hostlen == (j-i))
				{
					if(hosts.ToUpper().Substring(i, hostlen).CompareTo(host.ToUpper().Substring(0, hostlen)) == 0)
						return true;
				}
				i = j + 1;
			}
			return false;
		}
		
		public void hash() 
		{
		 
	      if(hashed)
	        return;
	      
			MAC macsha1=getHMACSHA1();
			if(salt==null)
			{
				bareFTP.Protocol.Sftp.jce.Random random=Session.random;
				lock(random)
				{
					salt=new byte[macsha1.BlockSize];
					random.fill(salt, 0, salt.Length);
				}
			}
			try
			{
		        lock(macsha1)
				{
		          macsha1.init(salt);
		          byte[] foo= System.Text.Encoding.Default.GetBytes(_host);
		          macsha1.update(foo, 0, foo.Length);
		          _hash = macsha1.doFinal();
		          
		        }
	      }
	      catch(Exception ex)
		  {
				Console.WriteLine("Ooops: " + ex.ToString());
	      }
			
	      _host = HASH_MAGIC + Convert.ToBase64String(salt, 0, salt.Length) + HASH_DELIM + Convert.ToBase64String(_hash, 0, _hash.Length);
	      hashed=true;
	    }
		
		private MAC getHMACSHA1()
		{
			if(hmacsha1==null)
			{
				try
				{
					hmacsha1 = (MAC) new bareFTP.Protocol.Sftp.jce.HMACSHA1();
//					hmacsha1=(MAC)Activator.CreateInstance(Type.GetType("bareFTP.Protocol.Sftp.jce.HMACSHA1"));
				}
				catch(Exception e){ 
					Console.WriteLine("hmacsha1: "+e); 
				}
			}
			return hmacsha1;
		}
	}
}
