You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

557 lines
16 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include <winsock2.h>
  2. #include <iostream>
  3. #include <string>
  4. #include "upnpnat.h"
  5. #include "xmlParser.h"
  6. #define LOG( X ) m_pLog->Log( "UPNPNAT", this, X )
  7. #define LOG_ERROR( X ) m_pLog->Log( "UPNPNAT", this, _LOG_ERROR, X )
  8. #define MAX_BUFF_SIZE 102400
  9. static bool parseUrl(const char* url,std::string& host,unsigned short* port,std::string& path)
  10. {
  11. std::string str_url=url;
  12. std::string::size_type pos1,pos2,pos3;
  13. pos1=str_url.find("://");
  14. if(pos1==std::string::npos)
  15. {
  16. return false;
  17. }
  18. pos1=pos1+3;
  19. pos2=str_url.find(":",pos1);
  20. if(pos2==std::string::npos)
  21. {
  22. *port=80;
  23. pos3=str_url.find("/",pos1);
  24. if(pos3==std::string::npos)
  25. {
  26. return false;
  27. }
  28. host=str_url.substr(pos1,pos3-pos1);
  29. }
  30. else
  31. {
  32. host=str_url.substr(pos1,pos2-pos1);
  33. pos3=str_url.find("/",pos1);
  34. if(pos3==std::string::npos)
  35. {
  36. return false;
  37. }
  38. std::string str_port=str_url.substr(pos2+1,pos3-pos2-1);
  39. *port=(unsigned short)atoi(str_port.c_str());
  40. }
  41. if(pos3+1>=str_url.size())
  42. {
  43. path="/";
  44. }
  45. else
  46. {
  47. path=str_url.substr(pos3,str_url.size());
  48. }
  49. return true;
  50. }
  51. /******************************************************************
  52. ** Discovery Defines *
  53. *******************************************************************/
  54. #define HTTPMU_HOST_ADDRESS "192.168.0.255" //"239.255.255.250"
  55. #define HTTPMU_HOST_PORT 3702
  56. /*
  57. #define SEARCH_REQUEST_STRING "M-SEARCH * HTTP/1.1\r\nST:ssdp:all\r\nMX: 3\r\nMAN:\"ssdp:discover\"\r\nHOST: 239.255.255.250:1900\r\n\r\n"
  58. //*/
  59. /*
  60. #define SEARCH_REQUEST_STRING "M-SEARCH * HTTP/1.1\r\n" \
  61. "ST:ssdp:all\r\n" \
  62. "MX: 3\r\n" \
  63. "MAN:\"ssdp:discover\"\r\n" \
  64. "HOST: 239.255.255.250:3702\r\n" \
  65. "\r\n"
  66. //*/
  67. #define SEARCH_REQUEST_STRING "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" \
  68. "<SOAP:Envelope xmlns:SOAP=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\" xmlns:DISCOVERY=\"http://schemas.xmlsoap.org/ws/2005/04/discovery\" xmlns:ssdp=\"http://example.com/wsdp/sample/print\">\n" \
  69. "<SOAP:Header>\n" \
  70. "<wsa:MessageID>urn:uuid:ac9823ee-6813-498c-8c1b-6272a22353f7</wsa:MessageID>\n" \
  71. "<wsa:Action>\n" \
  72. "http ://schemas.xmlsoap.org/ws/2005/04/discovery/Probe\n" \
  73. "</wsa:Action>\n" \
  74. "<wsa:To>urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To>\n" \
  75. "</SOAP:Header>\n" \
  76. "<SOAP:Body>\n" \
  77. "<DISCOVERY:Probe>\n" \
  78. "<DISCOVERY:Types>ssdp:any</DISCOVERY:Types>\n" \
  79. "</DISCOVERY:Probe>\n" \
  80. "</SOAP:Body>\n" \
  81. "</SOAP:Envelope>\r\n\r\n"
  82. #define HTTP_OK "200 OK"
  83. #define DEFAULT_HTTP_PORT 80
  84. /******************************************************************
  85. ** Device and Service Defines *
  86. *******************************************************************/
  87. #define DEVICE_TYPE_1 "urn:schemas-upnp-org:device:InternetGatewayDevice:1"
  88. #define DEVICE_TYPE_2 "urn:schemas-upnp-org:device:WANDevice:1"
  89. #define DEVICE_TYPE_3 "urn:schemas-upnp-org:device:WANConnectionDevice:1"
  90. #define SERVICE_WANIP "urn:schemas-upnp-org:service:WANIPConnection:1"
  91. #define SERVICE_WANPPP "urn:schemas-upnp-org:service:WANPPPConnection:1"
  92. /******************************************************************
  93. ** Action Defines *
  94. *******************************************************************/
  95. #define HTTP_HEADER_ACTION "POST %s HTTP/1.1\r\n" \
  96. "HOST: %s:%u\r\n" \
  97. "SOAPACTION:\"%s#%s\"\r\n" \
  98. "CONTENT-TYPE: text/xml ; charset=\"utf-8\"\r\n"\
  99. "Content-Length: %d \r\n\r\n"
  100. #define SOAP_ACTION "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" \
  101. "<s:Envelope xmlns:s=" \
  102. "\"http://schemas.xmlsoap.org/soap/envelope/\" " \
  103. "s:encodingStyle=" \
  104. "\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n" \
  105. "<s:Body>\r\n" \
  106. "<u:%s xmlns:u=\"%s\">\r\n%s" \
  107. "</u:%s>\r\n" \
  108. "</s:Body>\r\n" \
  109. "</s:Envelope>\r\n"
  110. #define PORT_MAPPING_LEASE_TIME "63072000" //two year
  111. #define ADD_PORT_MAPPING_PARAMS "<NewRemoteHost></NewRemoteHost>\r\n" \
  112. "<NewExternalPort>%u</NewExternalPort>\r\n"\
  113. "<NewProtocol>%s</NewProtocol>\r\n" \
  114. "<NewInternalPort>%u</NewInternalPort>\r\n"\
  115. "<NewInternalClient>%s</NewInternalClient>\r\n" \
  116. "<NewEnabled>1</NewEnabled>\r\n" \
  117. "<NewPortMappingDescription>%s</NewPortMappingDescription>\r\n" \
  118. "<NewLeaseDuration>" \
  119. PORT_MAPPING_LEASE_TIME \
  120. "</NewLeaseDuration>\r\n"
  121. #define ACTION_ADD "AddPortMapping"
  122. //*********************************************************************************
  123. UPNPNAT::UPNPNAT(){
  124. m_pLog = basicLogCollection::getInstance();
  125. };
  126. UPNPNAT::~UPNPNAT(){
  127. };
  128. bool UPNPNAT::init(int time,int inter){
  129. time_out=time;
  130. interval=inter;
  131. status=NAT_INIT;
  132. WORD wVersionRequested;
  133. WSADATA wsaData;
  134. int err;
  135. wVersionRequested = MAKEWORD (2, 2);
  136. err = WSAStartup (wVersionRequested, &wsaData);
  137. if (err != 0){
  138. LOG_ERROR("WSAStartup failed with error");
  139. return false;
  140. };
  141. return true;
  142. }
  143. bool UPNPNAT::tcp_connect(const char * _host,unsigned short int _port){
  144. int ret,i;
  145. tcp_socket_fd=socket(AF_INET,SOCK_STREAM,0);
  146. struct sockaddr_in r_address;
  147. r_address.sin_family = AF_INET;
  148. r_address.sin_port=htons(_port);
  149. r_address.sin_addr.s_addr=inet_addr(_host);
  150. for(i=1;i<=time_out;i++)
  151. {
  152. if(i>1)
  153. _sleep(1000);
  154. ret=connect(tcp_socket_fd,(const struct sockaddr *)&r_address,sizeof(struct sockaddr_in) );
  155. if(ret==0)
  156. {
  157. status = NAT_TCP_CONNECTED;
  158. LOG("NAT TCP Connected");
  159. return true;
  160. }
  161. }
  162. status=NAT_ERROR;
  163. char temp[100];
  164. sprintf(temp,"Fail to connect to %s:%i (using TCP)",_host,_port);
  165. LOG_ERROR(temp);
  166. last_error=temp;
  167. return false;
  168. }
  169. bool UPNPNAT::discovery(){
  170. udp_socket_fd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  171. int i,ret;
  172. std::string send_buff=SEARCH_REQUEST_STRING;
  173. std::string recv_buff;
  174. char buff[MAX_BUFF_SIZE+1]; //buff should be enough big
  175. struct sockaddr_in r_address;
  176. r_address.sin_family=AF_INET;
  177. r_address.sin_port=htons(HTTPMU_HOST_PORT);
  178. r_address.sin_addr.s_addr=inet_addr(HTTPMU_HOST_ADDRESS);
  179. bool bOptVal = true;
  180. int bOptLen = sizeof(bool);
  181. int iOptLen = sizeof(int);
  182. ret=setsockopt(udp_socket_fd, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen);
  183. LOG(send_buff.c_str());
  184. ret=sendto(udp_socket_fd,send_buff.c_str(),send_buff.size(),0,(struct sockaddr*)&r_address,sizeof(struct sockaddr_in));
  185. sprintf(buff, "Sent %d Bytes", ret);
  186. LOG(buff);
  187. for(i=1;i<=time_out;i++)
  188. {
  189. u_long val = 1;
  190. ioctlsocket (udp_socket_fd,FIONBIO,&val);//none block
  191. memset(buff, 0, sizeof(buff));
  192. ret=recvfrom(udp_socket_fd,buff,MAX_BUFF_SIZE,0,NULL,NULL);
  193. if(ret==SOCKET_ERROR){
  194. Sleep(1000);
  195. continue;
  196. }
  197. LOG("RESP:");
  198. //LOG(buff);
  199. recv_buff = buff;
  200. XMLNode node = XMLNode::parseString(buff, "root");
  201. if (node.isEmpty()){
  202. status = NAT_ERROR;
  203. LOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element.");
  204. continue;
  205. };
  206. XMLNode baseURL_node = node.getChildNode("Body", 0);
  207. std::string base_url;
  208. if (!baseURL_node.getText()){
  209. std::string::size_type index = recv_buff.find("/", 7);
  210. if (index == std::string::npos){
  211. status = NAT_ERROR;
  212. LOG_ERROR("Fail to get base_URL from XMLNode \"URLBase\" or describe_url.");
  213. continue;
  214. };
  215. base_url = base_url.assign(buff, 0, index);
  216. } else base_url = baseURL_node.getText();
  217. ret=recv_buff.find(HTTP_OK);
  218. if(ret==std::string::npos)
  219. continue; //invalid response
  220. std::string::size_type begin=recv_buff.find("http://");
  221. if(begin==std::string::npos)
  222. continue; //invalid response
  223. std::string::size_type end=recv_buff.find("\r",begin);
  224. if(end==std::string::npos)
  225. continue; //invalid response
  226. describe_url=describe_url.assign(recv_buff,begin,end-begin);
  227. if(!get_description()){
  228. Sleep(1000);
  229. continue;
  230. }
  231. if(!parser_description()){
  232. Sleep(1000);
  233. continue;
  234. }
  235. closesocket(udp_socket_fd);
  236. status=NAT_FOUND; //find a router
  237. return true ;
  238. }
  239. status=NAT_ERROR;
  240. last_error="Fail to find an UPNP NAT.\n";
  241. LOG_ERROR("Fail to find an UPNP NAT.");
  242. return false; //no router finded
  243. }
  244. bool UPNPNAT::get_description()
  245. {
  246. std::string host,path;
  247. unsigned short int port;
  248. int ret=parseUrl(describe_url.c_str(),host,&port,path);
  249. if(!ret)
  250. {
  251. status=NAT_ERROR;
  252. last_error="Failed to parseURl: "+describe_url+"\n";
  253. LOG_ERROR(last_error.c_str());
  254. return false;
  255. }
  256. //connect
  257. ret=tcp_connect(host.c_str(),port);
  258. if(!ret){
  259. return false;
  260. }
  261. char request[200];
  262. sprintf (request,"GET %s HTTP/1.1\r\nHost: %s:%d\r\n\r\n",path.c_str(),host.c_str(),port);
  263. std::string http_request=request;
  264. //send request
  265. ret=send(tcp_socket_fd,http_request.c_str(),http_request.size(),0);
  266. //get description xml file
  267. char buff[MAX_BUFF_SIZE+1];
  268. memset(buff, 0, sizeof(buff));
  269. std::string response;
  270. while ( ret=recv(tcp_socket_fd,buff,MAX_BUFF_SIZE,0) >0)
  271. {
  272. LOG(buff);
  273. response+=buff;
  274. memset(buff, 0, sizeof(buff));
  275. }
  276. description_info=response;
  277. return true;
  278. }
  279. bool UPNPNAT::parser_description()
  280. {
  281. XMLNode node=XMLNode::parseString(description_info.c_str(),"root");
  282. if(node.isEmpty())
  283. {
  284. status=NAT_ERROR;
  285. last_error="The device descripe XML file is not a valid XML file. Cann't find root element.\n";
  286. LOG_ERROR("The device descripe XML file is not a valid XML file. Cann't find root element.");
  287. return false;
  288. }
  289. XMLNode baseURL_node=node.getChildNode("URLBase",0);
  290. if(!baseURL_node.getText())
  291. {
  292. std::string::size_type index=describe_url.find("/",7);
  293. if(index==std::string::npos )
  294. {
  295. status=NAT_ERROR;
  296. last_error="Fail to get base_URL from XMLNode \"URLBase\" or describe_url.\n";
  297. LOG_ERROR("Fail to get base_URL from XMLNode \"URLBase\" or describe_url.");
  298. return false;
  299. }
  300. base_url=base_url.assign(describe_url,0,index);
  301. }
  302. else
  303. base_url=baseURL_node.getText();
  304. int num,i;
  305. XMLNode device_node,deviceList_node,deviceType_node;
  306. num=node.nChildNode("device");
  307. for(i=0;i<num;i++)
  308. {
  309. device_node=node.getChildNode("device",i);
  310. if(device_node.isEmpty())
  311. break;
  312. deviceType_node=device_node.getChildNode("deviceType",0);
  313. if(strcmp(deviceType_node.getText(),DEVICE_TYPE_1)==0)
  314. break;
  315. }
  316. if(device_node.isEmpty())
  317. {
  318. status=NAT_ERROR;
  319. last_error="Fail to find device \"urn:schemas-upnp-org:device:InternetGatewayDevice:1\"\n";
  320. LOG_ERROR("Fail to find device \"urn:schemas-upnp-org:device:InternetGatewayDevice:1\"");
  321. return false;
  322. }
  323. deviceList_node=device_node.getChildNode("deviceList",0);
  324. if(deviceList_node.isEmpty())
  325. {
  326. status=NAT_ERROR;
  327. last_error="Fail to find deviceList of device \"urn:schemas-upnp-org:device:InternetGatewayDevice:1\"\n";
  328. LOG_ERROR("Fail to find deviceList of device \"urn:schemas-upnp-org:device:InternetGatewayDevice:1\"");
  329. return false;
  330. }
  331. // get urn:schemas-upnp-org:device:WANDevice:1 and it's devicelist
  332. num=deviceList_node.nChildNode("device");
  333. for(i=0;i<num;i++)
  334. {
  335. device_node=deviceList_node.getChildNode("device",i);
  336. if(device_node.isEmpty())
  337. break;
  338. deviceType_node=device_node.getChildNode("deviceType",0);
  339. if(strcmp(deviceType_node.getText(),DEVICE_TYPE_2)==0)
  340. break;
  341. }
  342. if(device_node.isEmpty())
  343. {
  344. status=NAT_ERROR;
  345. last_error="Fail to find device \"urn:schemas-upnp-org:device:WANDevice:1\"\n";
  346. LOG_ERROR("Fail to find device \"urn:schemas-upnp-org:device:WANDevice:1\"");
  347. return false;
  348. }
  349. deviceList_node=device_node.getChildNode("deviceList",0);
  350. if(deviceList_node.isEmpty())
  351. {
  352. status=NAT_ERROR;
  353. last_error="Fail to find deviceList of device \"urn:schemas-upnp-org:device:WANDevice:1\"\n";
  354. LOG_ERROR("Fail to find deviceList of device \"urn:schemas-upnp-org:device:WANDevice:1\"");
  355. return false;
  356. }
  357. // get urn:schemas-upnp-org:device:WANConnectionDevice:1 and it's servicelist
  358. num=deviceList_node.nChildNode("device");
  359. for(i=0;i<num;i++)
  360. {
  361. device_node=deviceList_node.getChildNode("device",i);
  362. if(device_node.isEmpty())
  363. break;
  364. deviceType_node=device_node.getChildNode("deviceType",0);
  365. if(strcmp(deviceType_node.getText(),DEVICE_TYPE_3)==0)
  366. break;
  367. }
  368. if(device_node.isEmpty())
  369. {
  370. status=NAT_ERROR;
  371. last_error="Fail to find device \"urn:schemas-upnp-org:device:WANConnectionDevice:1\"\n";
  372. LOG_ERROR("Fail to find device \"urn:schemas-upnp-org:device:WANConnectionDevice:1\"");
  373. return false;
  374. }
  375. XMLNode serviceList_node,service_node,serviceType_node;
  376. serviceList_node=device_node.getChildNode("serviceList",0);
  377. if(serviceList_node.isEmpty())
  378. {
  379. status=NAT_ERROR;
  380. last_error="Fail to find serviceList of device \"urn:schemas-upnp-org:device:WANDevice:1\"\n";
  381. LOG_ERROR("Fail to find serviceList of device \"urn:schemas-upnp-org:device:WANDevice:1\"");
  382. return false;
  383. }
  384. num=serviceList_node.nChildNode("service");
  385. const char * serviceType;
  386. bool is_found=false;
  387. for(i=0;i<num;i++)
  388. {
  389. service_node=serviceList_node.getChildNode("service",i);
  390. if(service_node.isEmpty())
  391. break;
  392. serviceType_node=service_node.getChildNode("serviceType");
  393. if(serviceType_node.isEmpty())
  394. continue;
  395. serviceType=serviceType_node.getText();
  396. if(strcmp(serviceType,SERVICE_WANIP)==0||strcmp(serviceType,SERVICE_WANPPP)==0)
  397. {
  398. is_found=true;
  399. break;
  400. }
  401. }
  402. if(!is_found)
  403. {
  404. status=NAT_ERROR;
  405. last_error="can't find \" SERVICE_WANIP \" or \" SERVICE_WANPPP \" service.\n";
  406. LOG_ERROR("can't find \" SERVICE_WANIP \" or \" SERVICE_WANPPP \" service.");
  407. return false;
  408. }
  409. this->service_type=serviceType;
  410. XMLNode controlURL_node=service_node.getChildNode("controlURL");
  411. control_url=controlURL_node.getText();
  412. //make the complete control_url;
  413. if(control_url.find("http://")==std::string::npos&&control_url.find("HTTP://")==std::string::npos)
  414. control_url=base_url+control_url;
  415. if(service_describe_url.find("http://")==std::string::npos&&service_describe_url.find("HTTP://")==std::string::npos)
  416. service_describe_url=base_url+service_describe_url;
  417. closesocket(tcp_socket_fd);
  418. status=NAT_GETCONTROL;
  419. return true;
  420. }
  421. bool UPNPNAT::add_port_mapping(char * _description, char * _destination_ip, unsigned short int _port_ex, unsigned short int _port_in, char * _protocal)
  422. {
  423. int ret;
  424. std::string host,path;
  425. unsigned short int port;
  426. ret=parseUrl(control_url.c_str(),host,&port,path);
  427. if(!ret)
  428. {
  429. status=NAT_ERROR;
  430. last_error="Fail to parseURl: "+describe_url;
  431. LOG_ERROR(last_error.c_str());
  432. return false;
  433. }
  434. //connect
  435. ret=tcp_connect(host.c_str(),port);
  436. if(!ret)
  437. return false;
  438. char buff[MAX_BUFF_SIZE+1];
  439. sprintf(buff,ADD_PORT_MAPPING_PARAMS,_port_ex,_protocal,_port_in,_destination_ip,_description);
  440. std::string action_params=buff;
  441. sprintf(buff,SOAP_ACTION,ACTION_ADD,service_type.c_str(),action_params.c_str(),ACTION_ADD);
  442. std::string soap_message=buff;
  443. sprintf(buff,HTTP_HEADER_ACTION,path.c_str(),host.c_str(),port,service_type.c_str(),ACTION_ADD,soap_message.size());
  444. std::string action_message=buff;
  445. std::string http_request=action_message+soap_message;
  446. //send request
  447. ret=send(tcp_socket_fd,http_request.c_str(),http_request.size(),0);
  448. //wait for response
  449. std::string response;
  450. memset(buff, 0, sizeof(buff));
  451. while (ret=recv(tcp_socket_fd,buff,MAX_BUFF_SIZE,0) >0)
  452. {
  453. response+=buff;
  454. memset(buff, 0, sizeof(buff));
  455. }
  456. if(response.find(HTTP_OK)==std::string::npos)
  457. {
  458. status=NAT_ERROR;
  459. char temp[100];
  460. sprintf(temp,"Fail to add port mapping (%s/%s)",_description,_protocal);
  461. LOG_ERROR(temp);
  462. last_error=temp;
  463. return false;
  464. }
  465. closesocket(tcp_socket_fd);
  466. status=NAT_ADD;
  467. return true;
  468. }
  469. #undef LOG
  470. #undef LOG_ERROR