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