PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/irc.cpp

https://github.com/bitchip/bitchip
C++ | 452 lines | 364 code | 66 blank | 22 comment | 107 complexity | ea80a37d0662799594ad67306a0c39b1 MD5 | raw file
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2011 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file license.txt or http://www.opensource.org/licenses/mit-license.php.
  5. #include "headers.h"
  6. #include "irc.h"
  7. #include "net.h"
  8. #include "strlcpy.h"
  9. using namespace std;
  10. using namespace boost;
  11. int nGotIRCAddresses = 0;
  12. bool fGotExternalIP = false;
  13. void ThreadIRCSeed2(void* parg);
  14. #pragma pack(push, 1)
  15. struct ircaddr
  16. {
  17. int ip;
  18. short port;
  19. };
  20. #pragma pack(pop)
  21. string EncodeAddress(const CAddress& addr)
  22. {
  23. struct ircaddr tmp;
  24. tmp.ip = addr.ip;
  25. tmp.port = addr.port;
  26. vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));
  27. return string("u") + EncodeBase58Check(vch);
  28. }
  29. bool DecodeAddress(string str, CAddress& addr)
  30. {
  31. vector<unsigned char> vch;
  32. if (!DecodeBase58Check(str.substr(1), vch))
  33. return false;
  34. struct ircaddr tmp;
  35. if (vch.size() != sizeof(tmp))
  36. return false;
  37. memcpy(&tmp, &vch[0], sizeof(tmp));
  38. addr = CAddress(tmp.ip, ntohs(tmp.port), NODE_NETWORK);
  39. return true;
  40. }
  41. static bool Send(SOCKET hSocket, const char* pszSend)
  42. {
  43. if (strstr(pszSend, "PONG") != pszSend)
  44. printf("IRC SENDING: %s\n", pszSend);
  45. const char* psz = pszSend;
  46. const char* pszEnd = psz + strlen(psz);
  47. while (psz < pszEnd)
  48. {
  49. int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL);
  50. if (ret < 0)
  51. return false;
  52. psz += ret;
  53. }
  54. return true;
  55. }
  56. bool RecvLine(SOCKET hSocket, string& strLine)
  57. {
  58. strLine = "";
  59. loop
  60. {
  61. char c;
  62. int nBytes = recv(hSocket, &c, 1, 0);
  63. if (nBytes > 0)
  64. {
  65. if (c == '\n')
  66. continue;
  67. if (c == '\r')
  68. return true;
  69. strLine += c;
  70. if (strLine.size() >= 9000)
  71. return true;
  72. }
  73. else if (nBytes <= 0)
  74. {
  75. if (fShutdown)
  76. return false;
  77. if (nBytes < 0)
  78. {
  79. int nErr = WSAGetLastError();
  80. if (nErr == WSAEMSGSIZE)
  81. continue;
  82. if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
  83. {
  84. Sleep(10);
  85. continue;
  86. }
  87. }
  88. if (!strLine.empty())
  89. return true;
  90. if (nBytes == 0)
  91. {
  92. // socket closed
  93. printf("IRC socket closed\n");
  94. return false;
  95. }
  96. else
  97. {
  98. // socket error
  99. int nErr = WSAGetLastError();
  100. printf("IRC recv failed: %d\n", nErr);
  101. return false;
  102. }
  103. }
  104. }
  105. }
  106. bool RecvLineIRC(SOCKET hSocket, string& strLine)
  107. {
  108. loop
  109. {
  110. bool fRet = RecvLine(hSocket, strLine);
  111. if (fRet)
  112. {
  113. if (fShutdown)
  114. return false;
  115. vector<string> vWords;
  116. ParseString(strLine, ' ', vWords);
  117. if (vWords.size() >= 1 && vWords[0] == "PING")
  118. {
  119. strLine[1] = 'O';
  120. strLine += '\r';
  121. Send(hSocket, strLine.c_str());
  122. continue;
  123. }
  124. }
  125. return fRet;
  126. }
  127. }
  128. int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
  129. {
  130. loop
  131. {
  132. string strLine;
  133. strLine.reserve(10000);
  134. if (!RecvLineIRC(hSocket, strLine))
  135. return 0;
  136. printf("IRC %s\n", strLine.c_str());
  137. if (psz1 && strLine.find(psz1) != -1)
  138. return 1;
  139. if (psz2 && strLine.find(psz2) != -1)
  140. return 2;
  141. if (psz3 && strLine.find(psz3) != -1)
  142. return 3;
  143. if (psz4 && strLine.find(psz4) != -1)
  144. return 4;
  145. }
  146. }
  147. bool Wait(int nSeconds)
  148. {
  149. if (fShutdown)
  150. return false;
  151. printf("IRC waiting %d seconds to reconnect\n", nSeconds);
  152. for (int i = 0; i < nSeconds; i++)
  153. {
  154. if (fShutdown)
  155. return false;
  156. Sleep(1000);
  157. }
  158. return true;
  159. }
  160. bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
  161. {
  162. strRet.clear();
  163. loop
  164. {
  165. string strLine;
  166. if (!RecvLineIRC(hSocket, strLine))
  167. return false;
  168. vector<string> vWords;
  169. ParseString(strLine, ' ', vWords);
  170. if (vWords.size() < 2)
  171. continue;
  172. if (vWords[1] == psz1)
  173. {
  174. printf("IRC %s\n", strLine.c_str());
  175. strRet = strLine;
  176. return true;
  177. }
  178. }
  179. }
  180. bool GetIPFromIRC(SOCKET hSocket, string strMyName, unsigned int& ipRet)
  181. {
  182. Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
  183. string strLine;
  184. if (!RecvCodeLine(hSocket, "302", strLine))
  185. return false;
  186. vector<string> vWords;
  187. ParseString(strLine, ' ', vWords);
  188. if (vWords.size() < 4)
  189. return false;
  190. string str = vWords[3];
  191. if (str.rfind("@") == string::npos)
  192. return false;
  193. string strHost = str.substr(str.rfind("@")+1);
  194. // Hybrid IRC used by lfnet always returns IP when you userhost yourself,
  195. // but in case another IRC is ever used this should work.
  196. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
  197. if (fUseProxy)
  198. return false;
  199. CAddress addr(strHost, 0, true);
  200. if (!addr.IsValid())
  201. return false;
  202. ipRet = addr.ip;
  203. return true;
  204. }
  205. void ThreadIRCSeed(void* parg)
  206. {
  207. IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
  208. try
  209. {
  210. ThreadIRCSeed2(parg);
  211. }
  212. catch (std::exception& e) {
  213. PrintExceptionContinue(&e, "ThreadIRCSeed()");
  214. } catch (...) {
  215. PrintExceptionContinue(NULL, "ThreadIRCSeed()");
  216. }
  217. printf("ThreadIRCSeed exiting\n");
  218. }
  219. void ThreadIRCSeed2(void* parg)
  220. {
  221. /* Dont advertise on IRC if we don't allow incoming connections */
  222. if (mapArgs.count("-connect") || fNoListen)
  223. return;
  224. if (GetBoolArg("-noirc"))
  225. return;
  226. printf("ThreadIRCSeed started\n");
  227. int nErrorWait = 10;
  228. int nRetryWait = 10;
  229. bool fNameInUse = false;
  230. bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
  231. while (!fShutdown)
  232. {
  233. CAddress addrConnect("216.155.130.130:6667"); // chat.freenode.net
  234. //CAddress addrConnect("92.243.23.21", 6667); // irc.lfnet.org
  235. if (!fTOR)
  236. {
  237. //struct hostent* phostent = gethostbyname("chat.freenode.net");
  238. //CAddress addrIRC("irc.lfnet.org", 6667, true);
  239. CAddress addrIRC("216.155.130.130", 6667, true);
  240. if (addrIRC.IsValid())
  241. addrConnect = addrIRC;
  242. }
  243. SOCKET hSocket;
  244. if (!ConnectSocket(addrConnect, hSocket))
  245. {
  246. printf("IRC connect failed\n");
  247. nErrorWait = nErrorWait * 11 / 10;
  248. if (Wait(nErrorWait += 60))
  249. continue;
  250. else
  251. return;
  252. }
  253. if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
  254. {
  255. closesocket(hSocket);
  256. hSocket = INVALID_SOCKET;
  257. nErrorWait = nErrorWait * 11 / 10;
  258. if (Wait(nErrorWait += 60))
  259. continue;
  260. else
  261. return;
  262. }
  263. string strMyName;
  264. if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse)
  265. strMyName = EncodeAddress(addrLocalHost);
  266. else
  267. strMyName = strprintf("x%u", GetRand(1000000000));
  268. Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
  269. Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
  270. int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
  271. if (nRet != 1)
  272. {
  273. closesocket(hSocket);
  274. hSocket = INVALID_SOCKET;
  275. if (nRet == 2)
  276. {
  277. printf("IRC name already in use\n");
  278. fNameInUse = true;
  279. Wait(10);
  280. continue;
  281. }
  282. nErrorWait = nErrorWait * 11 / 10;
  283. if (Wait(nErrorWait += 60))
  284. continue;
  285. else
  286. return;
  287. }
  288. Sleep(500);
  289. // Get our external IP from the IRC server and re-nick before joining the channel
  290. CAddress addrFromIRC;
  291. if (GetIPFromIRC(hSocket, strMyName, addrFromIRC.ip))
  292. {
  293. printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToStringIP().c_str());
  294. if (!fUseProxy && addrFromIRC.IsRoutable())
  295. {
  296. // IRC lets you to re-nick
  297. fGotExternalIP = true;
  298. addrLocalHost.ip = addrFromIRC.ip;
  299. strMyName = EncodeAddress(addrLocalHost);
  300. Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
  301. }
  302. }
  303. if (fTestNet) {
  304. Send(hSocket, "JOIN #bitchipTEST\r");
  305. Send(hSocket, "WHO #bitchipTEST\r");
  306. } else {
  307. // randomly join #bitchip00-#bitchip99
  308. //int channel_number = GetRandInt(100);
  309. //Send(hSocket, strprintf("JOIN #bitchip%02d\r", channel_number).c_str());
  310. //Send(hSocket, strprintf("WHO #bitchip%02d\r", channel_number).c_str());
  311. Send(hSocket, strprintf("JOIN #bitchip\r").c_str());
  312. Send(hSocket, strprintf("WHO #bitchip\r").c_str());
  313. }
  314. int64 nStart = GetTime();
  315. string strLine;
  316. strLine.reserve(10000);
  317. while (!fShutdown && RecvLineIRC(hSocket, strLine))
  318. {
  319. if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
  320. continue;
  321. vector<string> vWords;
  322. ParseString(strLine, ' ', vWords);
  323. if (vWords.size() < 2)
  324. continue;
  325. char pszName[10000];
  326. pszName[0] = '\0';
  327. if (vWords[1] == "352" && vWords.size() >= 8)
  328. {
  329. // index 7 is limited to 16 characters
  330. // could get full length name at index 10, but would be different from join messages
  331. strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
  332. printf("IRC got who\n");
  333. }
  334. if (vWords[1] == "JOIN" && vWords[0].size() > 1)
  335. {
  336. // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
  337. strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
  338. if (strchr(pszName, '!'))
  339. *strchr(pszName, '!') = '\0';
  340. printf("IRC got join\n");
  341. }
  342. if (pszName[0] == 'u')
  343. {
  344. CAddress addr;
  345. if (DecodeAddress(pszName, addr))
  346. {
  347. addr.nTime = GetAdjustedTime();
  348. if (AddAddress(addr, 51 * 60))
  349. printf("IRC got new address: %s\n", addr.ToString().c_str());
  350. nGotIRCAddresses++;
  351. }
  352. else
  353. {
  354. printf("IRC decode failed\n");
  355. }
  356. }
  357. }
  358. closesocket(hSocket);
  359. hSocket = INVALID_SOCKET;
  360. // IRC usually blocks TOR, so only try once
  361. if (fTOR)
  362. return;
  363. if (GetTime() - nStart > 20 * 60)
  364. {
  365. nErrorWait /= 3;
  366. nRetryWait /= 3;
  367. }
  368. nRetryWait = nRetryWait * 11 / 10;
  369. if (!Wait(nRetryWait += 60))
  370. return;
  371. }
  372. }
  373. #ifdef TEST
  374. int main(int argc, char *argv[])
  375. {
  376. WSADATA wsadata;
  377. if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
  378. {
  379. printf("Error at WSAStartup()\n");
  380. return false;
  381. }
  382. ThreadIRCSeed(NULL);
  383. WSACleanup();
  384. return 0;
  385. }
  386. #endif