using System;
using System.Collections.Generic;
using System.IO;
using bareFTP.Preferences;

namespace bareFTP.Protocol.Sftp
{
	/* -*-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 KnownHosts : HostKeyRepository
	{
		//private const string _known_hosts ="~/.ssh/known_hosts";
		
		//private JSch jsch=null;
		private string known_hosts=null;
		private List<HostKey> pool = null;
		private Config conf;
		
		internal KnownHosts(Config conf) : base()
		{
			this.conf = conf;
			pool= new List<HostKey>();
			setKnownHosts(conf.SSHKnownHostsFile);
		}

		internal void setKnownHosts(string foo) 
		{
			try
			{
				known_hosts=foo;
				FileStream fis=File.OpenRead(foo);
				setKnownHosts( new StreamReader(fis) );
			}
			catch
			{
			} 
		}
		
		internal void setKnownHosts(StreamReader foo) 
		{
			pool.Clear();
			System.Text.StringBuilder sb=new System.Text.StringBuilder();
			byte i;
			int j;
			bool error=false;
			try
			{
				StreamReader fis=foo;
				String host;
				String key=null;
				int type;
				byte[] buf=new byte[1024];
				int bufl=0;
			loop:
				while(true)
				{
					bufl=0;
					while(true)
					{
						j=fis.Read();
						if(j==-1){ goto break_loop;}
						if(j==0x0d){ continue; }
						if(j==0x0a){ break; }
						buf[bufl++]=(byte)j;
					}

					j=0;
					while(j<bufl)
					{
						i=buf[j];
						if(i==' '||i=='\t'){ j++; continue; }
						if(i=='#')
						{
							addInvalidLine(System.Text.Encoding.Default.GetString(buf, 0, bufl));			
							goto loop;
						}
						break;
					}
					if(j>=bufl)
					{ 
						addInvalidLine(System.Text.Encoding.Default.GetString(buf, 0, bufl));
						goto loop;
					}

					sb.Length = 0;
					while(j<bufl)
					{
						i=buf[j++];
						if(i==0x20 || i=='\t'){ break; }
						sb.Append((char)i);
					}
					host=sb.ToString();
					if(j>=bufl || host.Length==0)
					{
						addInvalidLine(System.Text.Encoding.Default.GetString(buf, 0, bufl));
						goto loop; 
					}

					sb.Length=0;
					type=-1;
					while(j<bufl)
					{
						i=buf[j++];
						if(i==0x20 || i=='\t'){ break; }
						sb.Append((char)i);
					}
					if(sb.ToString().Equals("ssh-dss")){ type=HostKey.SSHDSS; }
					else if(sb.ToString().Equals("ssh-rsa")){ type=HostKey.SSHRSA; }
					else { j=bufl; }
					if(j>=bufl)
					{
						addInvalidLine(Util.getString(buf, 0, bufl));
						goto loop; 
					}

					sb.Length=0;
					while(j<bufl)
					{
						i=buf[j++];
						if(i==0x0d){ continue; }
						if(i==0x0a){ break; }
						sb.Append((char)i);
					}
					key=sb.ToString();
					if(key.Length==0)
					{
						addInvalidLine(Util.getString(buf, 0, bufl));
						goto loop; 
					}

					HostKey hk = null;
					hk = new HostKey(conf, host, type,
						Util.fromBase64(Util.getBytes(key), 0, 
						key.Length));
					pool.Add(hk);
				}

			break_loop:

				fis.Close();
				if(error)
				{
					throw new Exception("KnownHosts: invalid format");
				}
			}
			catch(Exception e)
			{
				if(e is Exception)
				{
					throw (Exception)e;         
				}
				throw new Exception(e.ToString());
			}
		}
		private void addInvalidLine(String line)
		{
			HostKey hk = new HostKey(conf, line, HostKey.UNKNOWN, null);
			pool.Add(hk);
		}
	
		//string getKnownHostsFile(){ return known_hosts; }
		
		public override string getKnownHostsRepositoryID(){ return known_hosts; }

		public override int check(string host, byte[] key)
		{
			int result=NOT_INCLUDED;
			if(string.IsNullOrEmpty(host))
				return result;
			
			int type=getType(key);
			
			lock(pool)
			{
				foreach(HostKey hk in pool)
				{
					
					if(hk.isMatched(host) && hk._Type == type)
					{
						if(Util.array_equals(hk._Key, key))
						{
							//System.out.println("find!!");
							return OK;
						}
						else
						{
							result=CHANGED;
						}
					}
				}
			}
			
			return result;
		}
		
		public override void add(HostKey hostkey, IDialogHost userinfo)
		{
			pool.Add(hostkey);

			string bar = getKnownHostsRepositoryID();
			if(!string.IsNullOrEmpty(bar))
			{
				bool foo=true;
				FileInfo goo=new FileInfo(bar);
				if(!goo.Exists)
				{
					foo=false;
					if(userinfo!=null)
					{
						foo=userinfo.DisplayDialogQuestion(
							bar+" does not exist.\n"+
							"Are you sure you want to create it?"
							);
						DirectoryInfo dir =goo.Directory;
						if(foo && dir!=null && !dir.Exists)
						{
							foo=userinfo.DisplayDialogQuestion(
								"The parent directory "+dir.Name+" does not exist.\n"+
								"Are you sure you want to create it?"
								);
							if(foo)
							{
								try{dir.Create(); userinfo.DisplayDialogInfo(dir.Name+" has been succesfully created.\nPlease check its access permission.");}
								catch
								{
									userinfo.DisplayDialogInfo(dir.Name+" has not been created.");
									foo=false;
								}
							}
						}
						if(goo==null)foo=false;
					}
				}
				if(foo)
				{
					try
					{ 
						sync(bar); 
					}
					catch(Exception e){ Console.WriteLine("sync known_hosts: "+e); }
				}
			}
		}

		public override HostKey[] getHostKey()
		{
			return getHostKey(null, null);
		}
		public override HostKey[] getHostKey(string host, string type)
		{
			lock(pool)
			{
				int count=0;
				for(int i=0; i<pool.Count; i++)
				{
					HostKey hk=(HostKey)pool[i];
					if(hk._Type==HostKey.UNKNOWN) continue;
					if(host==null || 
						(hk.isMatched(host) && 
						(type==null || hk.KeyType.Equals(type))))
					{
						count++;
					}
				}
				if(count==0)return null;
				HostKey[] foo=new HostKey[count];
				int j=0;
				for(int i=0; i<pool.Count; i++)
				{
					HostKey hk=(HostKey)pool[i];
					if(hk._Type==HostKey.UNKNOWN) continue;
					if(host==null || 
						(hk.isMatched(host) && 
						(type==null || hk.KeyType.Equals(type))))
					{
						foo[j++]=hk;
					}
				}
				return foo;
			}
		}
		public override void  remove(string host, string type)
		{
			remove(host, type, null);
		}
		public override void remove(string host, string type, byte[] key)
		{
			bool _sync=false;
			lock(pool)
			{
				foreach(HostKey hk in pool)
				{
					if(host==null ||
						(hk.isMatched(host) && 
						(type==null || (hk.KeyType.Equals(type) &&
						(key==null || Util.array_equals(key, hk._Key))))))
					{
						string hosts = hk.Host;
						if(hosts.Equals(host) || 
						   ((hk.Hashed)))
						{
							pool.Remove(hk);
						}
						else
						{
							//hk.host = hosts.Replace(host, string.Empty);
							hk.Host = deleteSubString(hosts, host);
						}
						_sync=true;
					}
				}
			}
			if(_sync)
			{
				try{sync();}
				catch{};
			}
		}

		private void sync() 
		{ 
			if(known_hosts!=null)
				sync(known_hosts); 
		}
		private void sync(String foo) 
		{
			if(foo==null) return;
			FileStream fos=File.OpenWrite(foo);
			dump(fos);
			fos.Close();
		}

		private static byte[] space= new byte[]{(byte)0x20};
		private static byte[] cr= System.Text.Encoding.Default.GetBytes("\n");
		
		void dump(FileStream outs) 
		{
			//StreamWriter outs = new StreamWriter(fs);
			try
			{
				foreach(HostKey hk in pool)
				{
					//hk.dump(out);
					string host=hk.Host;
					string type=hk.KeyType;
					if(type.Equals("UNKNOWN"))
					{
						Write(outs, Util.getBytes(host));
						Write(outs, cr);
						continue;
					}
					Write(outs, Util.getBytes(host));
					Write(outs, space);
					Write(outs, Util.getBytes(type));
					Write(outs, space);
					Write(outs, Util.getBytes(hk.Key));
					Write(outs, cr);
				}
				outs.Flush();
			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}

		private void Write(Stream s, byte[] buff)
		{
			s.Write(buff, 0, buff.Length);
		}
		private int getType(byte[] key)
		{
			if(key[8]=='d') return HostKey.SSHDSS;
			if(key[8]=='r') return HostKey.SSHRSA;
			return HostKey.UNKNOWN;
		}
		
		private String deleteSubString(String hosts, String host)
		{
			int i=0;
			int hostlen=host.Length;
			int hostslen=hosts.Length;
			int j;
			while(i<hostslen)
			{
				j=hosts.IndexOf(',', i);
				if(j==-1) break;
				if(!host.Equals(hosts.Substring(i, j)))
				{
					i=j+1;	  
					continue;
				}
				return hosts.Substring(0, i)+hosts.Substring(j+1);
			}
			if(hosts.EndsWith(host) && hostslen-i==hostlen)
			{
				return hosts.Substring(0, (hostlen==hostslen) ? 0 :hostslen-hostlen-1);
			}
			return hosts;
		}
		
	}
}
