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