Update License in File Headers
[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 COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "irc.h"
7 #include "net.h"
8 #include "strlcpy.h"
9 #include "base58.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 RecvLineIRC(SOCKET hSocket, string& strLine)
80 {
81     loop
82     {
83         bool fRet = RecvLine(hSocket, strLine);
84         if (fRet)
85         {
86             if (fShutdown)
87                 return false;
88             vector<string> vWords;
89             ParseString(strLine, ' ', vWords);
90             if (vWords.size() >= 1 && vWords[0] == "PING")
91             {
92                 strLine[1] = 'O';
93                 strLine += '\r';
94                 Send(hSocket, strLine.c_str());
95                 continue;
96             }
97         }
98         return fRet;
99     }
100 }
101
102 int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
103 {
104     loop
105     {
106         string strLine;
107         strLine.reserve(10000);
108         if (!RecvLineIRC(hSocket, strLine))
109             return 0;
110         printf("IRC %s\n", strLine.c_str());
111         if (psz1 && strLine.find(psz1) != string::npos)
112             return 1;
113         if (psz2 && strLine.find(psz2) != string::npos)
114             return 2;
115         if (psz3 && strLine.find(psz3) != string::npos)
116             return 3;
117         if (psz4 && strLine.find(psz4) != string::npos)
118             return 4;
119     }
120 }
121
122 bool Wait(int nSeconds)
123 {
124     if (fShutdown)
125         return false;
126     printf("IRC waiting %d seconds to reconnect\n", nSeconds);
127     for (int i = 0; i < nSeconds; i++)
128     {
129         if (fShutdown)
130             return false;
131         Sleep(1000);
132     }
133     return true;
134 }
135
136 bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet)
137 {
138     strRet.clear();
139     loop
140     {
141         string strLine;
142         if (!RecvLineIRC(hSocket, strLine))
143             return false;
144
145         vector<string> vWords;
146         ParseString(strLine, ' ', vWords);
147         if (vWords.size() < 2)
148             continue;
149
150         if (vWords[1] == psz1)
151         {
152             printf("IRC %s\n", strLine.c_str());
153             strRet = strLine;
154             return true;
155         }
156     }
157 }
158
159 bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet)
160 {
161     Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str());
162
163     string strLine;
164     if (!RecvCodeLine(hSocket, "302", strLine))
165         return false;
166
167     vector<string> vWords;
168     ParseString(strLine, ' ', vWords);
169     if (vWords.size() < 4)
170         return false;
171
172     string str = vWords[3];
173     if (str.rfind("@") == string::npos)
174         return false;
175     string strHost = str.substr(str.rfind("@")+1);
176
177     // Hybrid IRC used by lfnet always returns IP when you userhost yourself,
178     // but in case another IRC is ever used this should work.
179     printf("GetIPFromIRC() got userhost %s\n", strHost.c_str());
180     if (fUseProxy)
181         return false;
182     CNetAddr addr(strHost, true);
183     if (!addr.IsValid())
184         return false;
185     ipRet = addr;
186
187     return true;
188 }
189
190
191
192 void ThreadIRCSeed(void* parg)
193 {
194     IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
195     try
196     {
197         ThreadIRCSeed2(parg);
198     }
199     catch (std::exception& e) {
200         PrintExceptionContinue(&e, "ThreadIRCSeed()");
201     } catch (...) {
202         PrintExceptionContinue(NULL, "ThreadIRCSeed()");
203     }
204     printf("ThreadIRCSeed exiting\n");
205 }
206
207 void ThreadIRCSeed2(void* parg)
208 {
209     /* Dont advertise on IRC if we don't allow incoming connections */
210     if (mapArgs.count("-connect") || fNoListen)
211         return;
212
213     if (!GetBoolArg("-irc", false))
214         return;
215
216     printf("ThreadIRCSeed started\n");
217     int nErrorWait = 10;
218     int nRetryWait = 10;
219     bool fNameInUse = false;
220
221     while (!fShutdown)
222     {
223         CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org
224
225         CService addrIRC("irc.lfnet.org", 6667, true);
226         if (addrIRC.IsValid())
227             addrConnect = addrIRC;
228
229         SOCKET hSocket;
230         if (!ConnectSocket(addrConnect, hSocket))
231         {
232             printf("IRC connect failed\n");
233             nErrorWait = nErrorWait * 11 / 10;
234             if (Wait(nErrorWait += 60))
235                 continue;
236             else
237                 return;
238         }
239
240         if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
241         {
242             closesocket(hSocket);
243             hSocket = INVALID_SOCKET;
244             nErrorWait = nErrorWait * 11 / 10;
245             if (Wait(nErrorWait += 60))
246                 continue;
247             else
248                 return;
249         }
250
251         string strMyName;
252         if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse)
253             strMyName = EncodeAddress(addrLocalHost);
254         else
255             strMyName = strprintf("x%u", GetRand(1000000000));
256
257         Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
258         Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
259
260         int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
261         if (nRet != 1)
262         {
263             closesocket(hSocket);
264             hSocket = INVALID_SOCKET;
265             if (nRet == 2)
266             {
267                 printf("IRC name already in use\n");
268                 fNameInUse = true;
269                 Wait(10);
270                 continue;
271             }
272             nErrorWait = nErrorWait * 11 / 10;
273             if (Wait(nErrorWait += 60))
274                 continue;
275             else
276                 return;
277         }
278         Sleep(500);
279
280         // Get our external IP from the IRC server and re-nick before joining the channel
281         CNetAddr addrFromIRC;
282         if (GetIPFromIRC(hSocket, strMyName, addrFromIRC))
283         {
284             printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str());
285             if (!fUseProxy && addrFromIRC.IsRoutable())
286             {
287                 // IRC lets you to re-nick
288                 fGotExternalIP = true;
289                 addrLocalHost.SetIP(addrFromIRC);
290                 strMyName = EncodeAddress(addrLocalHost);
291                 Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
292             }
293         }
294         
295         if (fTestNet) {
296             Send(hSocket, "JOIN #bitcoinTEST\r");
297             Send(hSocket, "WHO #bitcoinTEST\r");
298         } else {
299             // randomly join #bitcoin00-#bitcoin99
300             int channel_number = GetRandInt(100);
301             Send(hSocket, strprintf("JOIN #bitcoin%02d\r", channel_number).c_str());
302             Send(hSocket, strprintf("WHO #bitcoin%02d\r", channel_number).c_str());
303         }
304
305         int64 nStart = GetTime();
306         string strLine;
307         strLine.reserve(10000);
308         while (!fShutdown && RecvLineIRC(hSocket, strLine))
309         {
310             if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
311                 continue;
312
313             vector<string> vWords;
314             ParseString(strLine, ' ', vWords);
315             if (vWords.size() < 2)
316                 continue;
317
318             char pszName[10000];
319             pszName[0] = '\0';
320
321             if (vWords[1] == "352" && vWords.size() >= 8)
322             {
323                 // index 7 is limited to 16 characters
324                 // could get full length name at index 10, but would be different from join messages
325                 strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
326                 printf("IRC got who\n");
327             }
328
329             if (vWords[1] == "JOIN" && vWords[0].size() > 1)
330             {
331                 // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
332                 strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
333                 if (strchr(pszName, '!'))
334                     *strchr(pszName, '!') = '\0';
335                 printf("IRC got join\n");
336             }
337
338             if (pszName[0] == 'u')
339             {
340                 CAddress addr;
341                 if (DecodeAddress(pszName, addr))
342                 {
343                     addr.nTime = GetAdjustedTime();
344                     if (addrman.Add(addr, addrConnect, 51 * 60))
345                         printf("IRC got new address: %s\n", addr.ToString().c_str());
346                     nGotIRCAddresses++;
347                 }
348                 else
349                 {
350                     printf("IRC decode failed\n");
351                 }
352             }
353         }
354         closesocket(hSocket);
355         hSocket = INVALID_SOCKET;
356
357         if (GetTime() - nStart > 20 * 60)
358         {
359             nErrorWait /= 3;
360             nRetryWait /= 3;
361         }
362
363         nRetryWait = nRetryWait * 11 / 10;
364         if (!Wait(nRetryWait += 60))
365             return;
366     }
367 }
368
369
370
371
372
373
374
375
376
377
378 #ifdef TEST
379 int main(int argc, char *argv[])
380 {
381     WSADATA wsadata;
382     if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
383     {
384         printf("Error at WSAStartup()\n");
385         return false;
386     }
387
388     ThreadIRCSeed(NULL);
389
390     WSACleanup();
391     return 0;
392 }
393 #endif