⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vpnconfig.cpp

📁 VPN拨号程序源码(from sourceforge.net)
💻 CPP
📖 第 1 页 / 共 3 页
字号:
			AfxMessageBox(tmp3,MB_OK|MB_ICONERROR);
			return -1;
		}
	}

	/*
	 * Activate the policy
	 */
	log+="Activating policy...\r\n";
#ifdef _DEBUG
	AfxMessageBox("\tActivating policy...\n");
#endif
	tmp.Format("%s -w REG -p %s -x",ipsectool,"VPNDialer");

#ifdef _DEBUG
	tmp2.Format("Command 3: %s\r\n",tmp);
	log+=tmp2;
	AfxMessageBox(tmp2);
#endif

	res=CVPNConfig::ExecuteCmd(tmp,tmp2);
	if (res!=0)
	{
		tmp2.Format("Fehler bei Command: %s\r\n",tmp);
		log+=tmp2;
		AfxMessageBox(tmp2,MB_OK|MB_ICONERROR);
		return -1;
	}

	log+="IPSec active\r\n";
#ifdef _DEBUG
	AfxMessageBox("IPSec active");
#endif
	

	return(0);
}

int CVPNConfig::RemoveIPSec()
{
	CString ipsectool=GetIPSecTool();
	CString tmp,tmp1;

#ifdef _DEBUG
	AfxMessageBox("\tDeactivating old policy...\n");
#endif
	tmp.Format("%s -w REG -p %s -y",ipsectool,"VPNDialer");
	CVPNConfig::ExecuteCmd(tmp,tmp1);

#ifdef _DEBUG
	AfxMessageBox("\tRemoving old policy...\n");
#endif
	tmp.Format("%s -w REG -p %s -o",ipsectool,"VPNDialer");
	CVPNConfig::ExecuteCmd(tmp,tmp1);

	return 0;
}

int CVPNConfig::GetLanIPs(CArray<CString,CString>& IPs, CArray<CString,CString>& netmasks)
{
	CString tmp;

	IPs.RemoveAll();
	netmasks.RemoveAll();

	SOCKET sd = WSASocket(AF_INET, SOCK_DGRAM, 0, 0, 0, 0);
    if (sd == SOCKET_ERROR)
	{
        tmp.Format("Failed to get a socket. Error %i",WSAGetLastError());
		AfxMessageBox(tmp,MB_OK|MB_ICONERROR);
		return -1;
    }
    
	INTERFACE_INFO InterfaceList[20];
    unsigned long nBytesReturned;
    if (WSAIoctl(sd, SIO_GET_INTERFACE_LIST, 0, 0, &InterfaceList, sizeof(InterfaceList), &nBytesReturned, 0, 0) == SOCKET_ERROR)
	{
        tmp.Format("Failed calling WSAIoctl: error %i", WSAGetLastError());
		AfxMessageBox(tmp,MB_OK|MB_ICONERROR);
		return -1;
	}
	
	int nNumInterfaces = nBytesReturned / sizeof(INTERFACE_INFO);
#ifdef _DEBUG
	tmp.Format("There are %i interfaces.",nNumInterfaces);
	AfxMessageBox(tmp);
#endif
	
	for (int i = 0; i < nNumInterfaces; ++i)
	{
        u_long nFlags = InterfaceList[i].iiFlags;
        if (nFlags & IFF_UP)
		{
			// not point-to-point or loopback
			if(!((nFlags & IFF_POINTTOPOINT)||(nFlags & IFF_LOOPBACK)))
			{
				sockaddr_in *pAddress;
				pAddress = (sockaddr_in *) & (InterfaceList[i].iiAddress);
				tmp=inet_ntoa(pAddress->sin_addr);
				IPs.Add(tmp);
				
				pAddress = (sockaddr_in *) & (InterfaceList[i].iiNetmask);
				tmp=inet_ntoa(pAddress->sin_addr);
				netmasks.Add(tmp);
			}
		}
    }

	return 0;
}

int CVPNConfig::ExecuteCmd(const CString &cmd, CString& output, BOOL wait)
{
	char *szCmd;
	CString temp;
	STARTUPINFO si;
	SECURITY_ATTRIBUTES sa;
	SECURITY_DESCRIPTOR sd;		//security information for pipes
    PROCESS_INFORMATION pi;
	DWORD exitCode;
	HANDLE newstdin,newstdout,read_stdout,write_stdin;  //pipe handles
	char buf[1024];             //i/o buffer

	// Clear Ouptut
	output="";

	// Initialize Security for pipes
	InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
    SetSecurityDescriptorDacl(&sd, true, NULL, false);
    sa.lpSecurityDescriptor = &sd;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = true;         //allow inheritable handles

	// Create Pipes
	if (!CreatePipe(&newstdin,&write_stdin,&sa,0))   //create stdin pipe
	{
		AfxMessageBox("Error on CreatePipe stdin",MB_OK|MB_ICONERROR);
		getch();
		return -1;
	}
	
	if (!CreatePipe(&read_stdout,&newstdout,&sa,0))  //create stdout pipe
	{
		AfxMessageBox("Error on CreatePipe stdout",MB_OK|MB_ICONERROR);
		getch();
		CloseHandle(newstdin);
		CloseHandle(write_stdin);
		return -1;
	}
	
	//set startupinfo for the spawned process
	GetStartupInfo(&si);
	ZeroMemory( &pi, sizeof(pi) );

	/*
	The dwFlags member tells CreateProcess how to make the process.
	STARTF_USESTDHANDLES validates the hStd* members. STARTF_USESHOWWINDOW
	validates the wShowWindow member.
	*/
	si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_HIDE;
	si.hStdOutput = newstdout;
	si.hStdError = newstdout;     //set the new handles for the child process
	si.hStdInput = newstdin;

	// Copy CString to char*
	szCmd=new char[cmd.GetLength()+1];
	strcpy(szCmd,(LPCSTR)cmd);

	// Start the child process. 
	if( !CreateProcess( NULL,    // No module name (use command line). 
                        szCmd,   // Command line. 
                        NULL,    // Process handle not inheritable. 
                        NULL,    // Thread handle not inheritable. 
                        TRUE,    // Set handle inheritance to TRUE. //FALSE before
                        CREATE_NEW_CONSOLE, //CREATE_NO_WINDOW, // No Window for DOS-Commands. 
                        NULL,    // Use parent's environment block. 
                        NULL,    // Use parent's starting directory. 
                        &si,     // Pointer to STARTUPINFO structure.
                        &pi )    // Pointer to PROCESS_INFORMATION structure.
	  ) 
	{
		temp.Format(IDS_ERROREXECUTE,cmd);
		AfxMessageBox(temp,MB_OK|MB_ICONERROR);
	    getch();
		CloseHandle(newstdin);
		CloseHandle(newstdout);
		CloseHandle(read_stdout);
		CloseHandle(write_stdin);
		delete [] szCmd;
		return -1;
	}

	if(wait)
	{
		// Wait for process to terminate
		bzero(buf);
		do
		{
			DWORD bread,avail;

			if(!GetExitCodeProcess(pi.hProcess, &exitCode))
			{
				AfxMessageBox("Unexpected error on GetExitCodeProcess, contact Vendor.");
				// Close process and thread handles. 
				CloseHandle( pi.hProcess );
				CloseHandle( pi.hThread );
				CloseHandle(newstdin);            //clean stuff up
				CloseHandle(newstdout);
				CloseHandle(read_stdout);
				CloseHandle(write_stdin);
				delete [] szCmd;
				return -1;
			}
			if(exitCode==STILL_ACTIVE)
			{
				PeekNamedPipe(read_stdout,buf,1023,&bread,&avail,NULL);
				//check to see if there is any data to read from stdout
				if(bread != 0)
				{
					bzero(buf);
					if (avail > 1023)
					{
						while (bread >= 1023)
						{
							ReadFile(read_stdout,buf,1023,&bread,NULL);  //read the stdout pipe
							output+=buf;
							bzero(buf);
						}
					}
					else
					{
						ReadFile(read_stdout,buf,1023,&bread,NULL);
						output+=buf;
					}
				}
			}
		} while(exitCode==STILL_ACTIVE);
	}

	// Close process and thread handles. 
	CloseHandle( pi.hProcess );
	CloseHandle( pi.hThread );
	CloseHandle(newstdin);            //clean stuff up
	CloseHandle(newstdout);
	CloseHandle(read_stdout);
	CloseHandle(write_stdin);

	delete [] szCmd;

	return exitCode;
}

int CVPNConfig::GetIPSecStatus(CString &log)
{
	CString tmp;

	switch(GetOSVersion())
	{
	case OS_WIN2K:
		return CVPNConfig::ExecuteCmd("ipsecmon",log,FALSE);
		break;
	case OS_WINXP:
		tmp=GetIPSecTool();
		tmp+=" show all";
		return CVPNConfig::ExecuteCmd(tmp,log);
		break;
	}
	return -1;
}

int CVPNConfig::SendUDPEcho(const CString &destIp)
{
	// Here is a structure contains the port we'll use,
	// the protocol type and the IP address we'll communicate with.
	SOCKADDR_IN sockaddr;
	
	// This is our socket, it is the handle to the IO address to read/write packets
	SOCKET sock;
	
	// Here we create our socket, which will be a UDP socket (SOCK_DGRAM).
	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (!sock)
	{
		return -1;
	}
	
	//Now we'll set the sockaddr variables:
	sockaddr.sin_family = AF_INET; // Must be AF_INET
	// If this is the Server:
	sockaddr.sin_addr.s_addr = INADDR_ANY; // Means we will "answer" to all addresses.
	// IP of the client:
	sockaddr.sin_addr.s_addr = inet_addr(destIp); // IP to communicate with.
	
	// The following sets our communication port.
	// 'htons()' reverses the bytes (0x1020 would become 0x2010).
	// This metod is called Big Endian and it was first used on Unix systems, you
	// have to call it because all systems work that way
	sockaddr.sin_port = htons(7); // UDP echo
	
	// A server need to bind the socket to itself in order to receive all the packets
	// it gets from a port
	int ret = bind(sock, (SOCKADDR *)&sockaddr, sizeof(SOCKADDR));
	
	if (ret)
	{
		return -1;
	}
	
	// That's it, now let's send a message...
	char buffer[256];
	strcpy(buffer, "HELLO!!!");
	int len = sizeof(SOCKADDR);
	sendto(sock, buffer, strlen(buffer), 0, (SOCKADDR *)&sockaddr, sizeof(SOCKADDR));
	// Notice we use sendto() and NOT send(), because we use UDP!
	// Easy huh?? Let's receive a packet..
	
	closesocket(sock);

	return 0;
}

int CVPNConfig::GetOSVersion()
{
	OSVERSIONINFOEX osinfo;
	int retvalue;

	ZeroMemory(&osinfo, sizeof(OSVERSIONINFOEX));
	osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	retvalue = GetVersionEx((OSVERSIONINFO *) &osinfo);
	
	switch(osinfo.dwPlatformId)
	{
	case 1:
		switch(osinfo.dwMinorVersion)
		{
		case 0:
			//getVersion = "Windows 95"
			return OS_WIN95;
			break;
		case 10:
			//getVersion = "Windows 98"
			return OS_WIN98;
			break;
		case 90:
			//getVersion = "Windows Mellinnium"
			return OS_WINME;
			break;
		}
		break;
	case 2:
		switch(osinfo.dwMajorVersion)
		{
		case 3:
			//getVersion = "Windows NT 3.51"
			return OS_WINNT351;
			break;
		case 4:
			//getVersion = "Windows NT 4.0"
			return OS_WINNT40;
			break;
		case 5:
			if(osinfo.dwMinorVersion == 0)
				//getVersion = "Windows 2000"
				return OS_WIN2K;
			else
				//getVersion = "Windows XP"
				return OS_WINXP;
			break;
		}
	default:
		//getVersion = "Failed"
		return OS_UNKNOWN;
	} 
	return OS_UNKNOWN;

}

CString CVPNConfig::GetNetwork(const CString &ip, const CString &netmask)
{
	CString retVal;
	BYTE network1,network2,network3,network4;
	BYTE netmask1,netmask2,netmask3,netmask4;

	splitIp(ip,network1,network2,network3,network4);
	splitIp(netmask,netmask1,netmask2,netmask3,netmask4);

	network1&=netmask1;
	network2&=netmask2;
	network3&=netmask3;
	network4&=netmask4;

	joinIp(network1,network2,network3,network4,retVal);

	return retVal;
}

void CVPNConfig::splitIp(const CString &ip, BYTE &ip1, BYTE &ip2, BYTE &ip3, BYTE &ip4)
{
	CString temp;
	int pos1=0;
	int pos2=0;

	pos1=ip.Find(".",0);
	temp=ip.Left(pos1);
	ip1=atoi(temp);

	pos1++;
	pos2=ip.Find(".",pos1);
	temp=ip.Mid(pos1,pos2-pos1);
	ip2=atoi(temp);
	pos1=pos2+1;

	pos2=ip.Find(".",pos1);
	temp=ip.Mid(pos1,pos2-pos1);
	ip3=atoi(temp);
	pos1=pos2+1;

	temp=ip.Right(ip.GetLength()-pos1);
	ip4=atoi(temp);
}

void CVPNConfig::joinIp(BYTE ip1, BYTE ip2, BYTE ip3, BYTE ip4, CString& ip)
{
	ip.Format("%i.%i.%i.%i",ip1,ip2,ip3,ip4);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -