Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.1.5 · 2009-02-04

irc.cpp

314 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"678map<vector<unsigned char>, CAddress> mapIRCAddresses;9CCriticalSection cs_mapIRCAddresses;1011121314#pragma pack(push, 1)15struct ircaddr16{17    int ip;18    short port;19};20#pragma pack(pop)2122string EncodeAddress(const CAddress& addr)23{24    struct ircaddr tmp;25    tmp.ip    = addr.ip;26    tmp.port  = addr.port;2728    vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp));29    return string("u") + EncodeBase58Check(vch);30}3132bool DecodeAddress(string str, CAddress& addr)33{34    vector<unsigned char> vch;35    if (!DecodeBase58Check(str.substr(1), vch))36        return false;3738    struct ircaddr tmp;39    if (vch.size() != sizeof(tmp))40        return false;41    memcpy(&tmp, &vch[0], sizeof(tmp));4243    addr  = CAddress(tmp.ip, tmp.port);44    return true;45}46474849505152static bool Send(SOCKET hSocket, const char* pszSend)53{54    if (strstr(pszSend, "PONG") != pszSend)55        printf("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, 0);61        if (ret < 0)62            return false;63        psz += ret;64    }65    return true;66}6768bool RecvLine(SOCKET hSocket, string& strLine)69{70    strLine = "";71    loop72    {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        }83        else if (nBytes <= 0)84        {85            if (!strLine.empty())86                return true;87            // socket closed88            printf("IRC socket closed\n");89            return false;90        }91        else92        {93            // socket error94            int nErr = WSAGetLastError();95            if (nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)96            {97                printf("IRC recv failed: %d\n", nErr);98                return false;99            }100        }101    }102}103104bool RecvLineIRC(SOCKET hSocket, string& strLine)105{106    loop107    {108        bool fRet = RecvLine(hSocket, strLine);109        if (fRet)110        {111            if (fShutdown)112                return false;113            vector<string> vWords;114            ParseString(strLine, ' ', vWords);115            if (vWords[0] == "PING")116            {117                strLine[1] = 'O';118                strLine += '\r';119                Send(hSocket, strLine.c_str());120                continue;121            }122        }123        return fRet;124    }125}126127bool RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL)128{129    loop130    {131        string strLine;132        if (!RecvLineIRC(hSocket, strLine))133            return false;134        printf("IRC %s\n", strLine.c_str());135        if (psz1 && strLine.find(psz1) != -1)136            return true;137        if (psz2 && strLine.find(psz2) != -1)138            return true;139        if (psz3 && strLine.find(psz3) != -1)140            return true;141    }142}143144bool Wait(int nSeconds)145{146    if (fShutdown)147        return false;148    printf("Waiting %d seconds to reconnect to IRC\n", nSeconds);149    for (int i = 0; i < nSeconds; i++)150    {151        if (fShutdown)152            return false;153        Sleep(1000);154    }155    return true;156}157158159160void ThreadIRCSeed(void* parg)161{162    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL);163    int nErrorWait = 10;164    int nRetryWait = 10;165166    while (!fShutdown)167    {168        CAddress addrConnect("216.155.130.130:6667");169        struct hostent* phostent = gethostbyname("chat.freenode.net");170        if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])171            addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(6667));172173        SOCKET hSocket;174        if (!ConnectSocket(addrConnect, hSocket))175        {176            printf("IRC connect failed\n");177            nErrorWait = nErrorWait * 11 / 10;178            if (Wait(nErrorWait += 60))179                continue;180            else181                return;182        }183184        if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname"))185        {186            closesocket(hSocket);187            nErrorWait = nErrorWait * 11 / 10;188            if (Wait(nErrorWait += 60))189                continue;190            else191                return;192        }193194        string strMyName = EncodeAddress(addrLocalHost);195196        if (!addrLocalHost.IsRoutable())197            strMyName = strprintf("x%u", GetRand(1000000000));198199200        Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str());201        Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str());202203        if (!RecvUntil(hSocket, " 004 "))204        {205            closesocket(hSocket);206            nErrorWait = nErrorWait * 11 / 10;207            if (Wait(nErrorWait += 60))208                continue;209            else210                return;211        }212        Sleep(500);213214        Send(hSocket, "JOIN #bitcoin\r");215        Send(hSocket, "WHO #bitcoin\r");216217        int64 nStart = GetTime();218        string strLine;219        while (!fShutdown && RecvLineIRC(hSocket, strLine))220        {221            if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':')222                continue;223            printf("IRC %s\n", strLine.c_str());224225            vector<string> vWords;226            ParseString(strLine, ' ', vWords);227            if (vWords.size() < 2)228                continue;229230            char pszName[10000];231            pszName[0] = '\0';232233            if (vWords[1] == "352" && vWords.size() >= 8)234            {235                // index 7 is limited to 16 characters236                // could get full length name at index 10, but would be different from join messages237                strcpy(pszName, vWords[7].c_str());238                printf("GOT WHO: [%s]  ", pszName);239            }240241            if (vWords[1] == "JOIN" && vWords[0].size() > 1)242            {243                // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname244                strcpy(pszName, vWords[0].c_str() + 1);245                if (strchr(pszName, '!'))246                    *strchr(pszName, '!') = '\0';247                printf("GOT JOIN: [%s]  ", pszName);248            }249250            if (pszName[0] == 'u')251            {252                CAddress addr;253                if (DecodeAddress(pszName, addr))254                {255                    CAddrDB addrdb;256                    if (AddAddress(addrdb, addr))257                        printf("new  ");258                    else259                    {260                        // make it try connecting again261                        CRITICAL_BLOCK(cs_mapAddresses)262                            if (mapAddresses.count(addr.GetKey()))263                                mapAddresses[addr.GetKey()].nLastFailed = 0;264                    }265                    addr.print();266267                    CRITICAL_BLOCK(cs_mapIRCAddresses)268                        mapIRCAddresses.insert(make_pair(addr.GetKey(), addr));269                }270                else271                {272                    printf("decode failed\n");273                }274            }275        }276        closesocket(hSocket);277278        if (GetTime() - nStart > 20 * 60)279        {280            nErrorWait /= 3;281            nRetryWait /= 3;282        }283284        nRetryWait = nRetryWait * 11 / 10;285        if (!Wait(nRetryWait += 60))286            return;287    }288}289290291292293294295296297298299#ifdef TEST300int main(int argc, char *argv[])301{302    WSADATA wsadata;303    if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR)304    {305        printf("Error at WSAStartup()\n");306        return false;307    }308309    ThreadIRCSeed(NULL);310311    WSACleanup();312    return 0;313}314#endif

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00