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