Update README now that main svn has -testnet built in
[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 (!strLine.empty())
88                 return true;
89             // socket closed
90             printf("IRC socket closed\n");
91             return false;
92         }
93         else
94         {
95             // socket error
96             int nErr = WSAGetLastError();
97             if (nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
98             {
99                 printf("IRC recv failed: %d\n", nErr);
100                 return false;
101             }
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
129 int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL)
130 {
131     loop
132     {
133         string strLine;
134         strLine.reserve(10000);
135         if (!RecvLineIRC(hSocket, strLine))
136             return 0;
137         printf("IRC %s\n", strLine.c_str());
138         if (psz1 && strLine.find(psz1) != -1)
139             return 1;
140         if (psz2 && strLine.find(psz2) != -1)
141             return 2;
142         if (psz3 && strLine.find(psz3) != -1)
143             return 3;
144         if (psz4 && strLine.find(psz4) != -1)
145             return 4;
146     }
147 }
148
149 bool Wait(int nSeconds)
150 {
151     if (fShutdown)
152         return false;
153     printf("IRC waiting %d seconds to reconnect\n", nSeconds);
154     for (int i = 0; i < nSeconds; i++)
155     {
156         if (fShutdown)
157             return false;
158         Sleep(1000);
159     }
160     return true;
161 }
162
163
164
165 void ThreadIRCSeed(void* parg)
166 {
167     IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg));
168     try
169     {
170         ThreadIRCSeed2(parg);
171     }
172     catch (std::exception& e) {
173         PrintExceptionContinue(&e, "ThreadIRCSeed()");
174     } catch (...) {
175         PrintExceptionContinue(NULL, "ThreadIRCSeed()");
176     }
177     printf("ThreadIRCSeed exiting\n");
178 }
179
180 void ThreadIRCSeed2(void* parg)
181 {
182     if (mapArgs.count("-connect"))
183         return;
184     if (mapArgs.count("-noirc"))
185         return;
186     printf("ThreadIRCSeed started\n");
187     int nErrorWait = 10;
188     int nRetryWait = 10;
189     bool fNameInUse = false;
190     bool fTOR = (fUseProxy && addrProxy.port == htons(9050));
191
192     while (!fShutdown)
193     {
194         //CAddress addrConnect("216.155.130.130:6667"); // chat.freenode.net
195         CAddress addrConnect("92.243.23.21:6667"); // irc.lfnet.org
196         if (!fTOR)
197         {
198             //struct hostent* phostent = gethostbyname("chat.freenode.net");
199             struct hostent* phostent = gethostbyname("irc.lfnet.org");
200             if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])
201                 addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(6667));
202         }
203
204         SOCKET hSocket;
205         if (!ConnectSocket(addrConnect, hSocket))
206         {
207             printf("IRC connect failed\n");
208             nErrorWait = nErrorWait * 11 / 10;
209             if (Wait(nErrorWait += 60))
210                 continue;
211             else
212                 return;
213         }
214
215         if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname"))
216         {
217             closesocket(hSocket);
218             hSocket = INVALID_SOCKET;
219             nErrorWait = nErrorWait * 11 / 10;
220             if (Wait(nErrorWait += 60))
221                 continue;
222             else
223                 return;
224         }
225
226         string strMyName;
227         if (addrLocalHost.IsRoutable() && !fUseProxy && !fNameInUse)
228             strMyName = EncodeAddress(addrLocalHost);
229         else
230             strMyName = strprintf("x%u", GetRand(1000000000));
231
232         Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());
233         Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());
234
235         int nRet = RecvUntil(hSocket, " 004 ", " 433 ");
236         if (nRet != 1)
237         {
238             closesocket(hSocket);
239             hSocket = INVALID_SOCKET;
240             if (nRet == 2)
241             {
242                 printf("IRC name already in use\n");
243                 fNameInUse = true;
244                 Wait(10);
245                 continue;
246             }
247             nErrorWait = nErrorWait * 11 / 10;
248             if (Wait(nErrorWait += 60))
249                 continue;
250             else
251                 return;
252         }
253         Sleep(500);
254
255         Send(hSocket, fTestNet ? "JOIN #bitcoinTEST\r" : "JOIN #bitcoin\r");
256         Send(hSocket, fTestNet ? "WHO #bitcoinTEST\r"  : "WHO #bitcoin\r");
257
258         int64 nStart = GetTime();
259         string strLine;
260         strLine.reserve(10000);
261         while (!fShutdown && RecvLineIRC(hSocket, strLine))
262         {
263             if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')
264                 continue;
265
266             vector<string> vWords;
267             ParseString(strLine, ' ', vWords);
268             if (vWords.size() < 2)
269                 continue;
270
271             char pszName[10000];
272             pszName[0] = '\0';
273
274             if (vWords[1] == "352" && vWords.size() >= 8)
275             {
276                 // index 7 is limited to 16 characters
277                 // could get full length name at index 10, but would be different from join messages
278                 strlcpy(pszName, vWords[7].c_str(), sizeof(pszName));
279                 printf("IRC got who\n");
280             }
281
282             if (vWords[1] == "JOIN" && vWords[0].size() > 1)
283             {
284                 // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname
285                 strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName));
286                 if (strchr(pszName, '!'))
287                     *strchr(pszName, '!') = '\0';
288                 printf("IRC got join\n");
289             }
290
291             if (pszName[0] == 'u')
292             {
293                 CAddress addr;
294                 if (DecodeAddress(pszName, addr))
295                 {
296                     addr.nTime = GetAdjustedTime() - 51 * 60;
297                     if (AddAddress(addr))
298                         printf("IRC got new address\n");
299                     nGotIRCAddresses++;
300                 }
301                 else
302                 {
303                     printf("IRC decode failed\n");
304                 }
305             }
306         }
307         closesocket(hSocket);
308         hSocket = INVALID_SOCKET;
309
310         // IRC usually blocks TOR, so only try once
311         if (fTOR)
312             return;
313
314         if (GetTime() - nStart > 20 * 60)
315         {
316             nErrorWait /= 3;
317             nRetryWait /= 3;
318         }
319
320         nRetryWait = nRetryWait * 11 / 10;
321         if (!Wait(nRetryWait += 60))
322             return;
323     }
324 }
325
326
327
328
329
330
331
332
333
334
335 #ifdef TEST
336 int main(int argc, char *argv[])
337 {
338     WSADATA wsadata;
339     if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)
340     {
341         printf("Error at WSAStartup()\n");
342         return false;
343     }
344
345     ThreadIRCSeed(NULL);
346
347     WSACleanup();
348     return 0;
349 }
350 #endif