bool CMasternodeBroadcast::Create(const std::string& strService, const std::string& strKeyMasternode, const std::string& strTxHash, const std::string& strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline)
{
    COutPoint outpoint;
    CPubKey pubKeyCollateralAddressNew;
    CKey keyCollateralAddressNew;
    CPubKey pubKeyMasternodeNew;
    CKey keyMasternodeNew;

    auto Log = [&strErrorRet](std::string sErr) -> bool {
        strErrorRet = sErr;
        return false;
    };

    // Wait for sync to finish because mnb simply won't be relayed otherwise
    if (!fOffline && !masternodeSync.IsSynced())
        return Log("Sync in progress. Must wait until sync is complete to start Masternode");

    if (!CMessageSigner::GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew))
        return Log(strprintf("Invalid masternode key %s", strKeyMasternode));

    const COutPoint outpt(uint256S(strTxHash), std::stoi(strOutputIndex));

    for (CWalletRef pwallet : vpwallets) {
        pwallet->UnlockCoin(outpt);
        if (pwallet->GetMasternodeOutpointAndKeys(outpoint, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) {
            pwallet->LockCoin(outpt);
        } else {
            return Log(strprintf("Could not allocate outpoint %s:%s for masternode %s", strTxHash, strOutputIndex, strService));
        }
    }

    CService service;
    if (!Lookup(strService.c_str(), service, 0, false))
        return Log(strprintf("Invalid address %s for masternode.", strService));
    int mainnetDefaultPort = CreateChainParams(CBaseChainParams::MAIN)->GetDefaultPort();
    if (Params().NetworkIDString() == CBaseChainParams::MAIN) {
        if (service.GetPort() != mainnetDefaultPort)
            return Log(strprintf("Invalid port %u for masternode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort));
    } else if (service.GetPort() == mainnetDefaultPort)
        return Log(strprintf("Invalid port %u for masternode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort));

    return Create(outpoint, service, keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet);
}
Ejemplo n.º 2
0
bool static Socks4(const CService &addrDest, SOCKET& hSocket)
{
    printf("SOCKS4 connecting %s\n", addrDest.ToString().c_str());
    if (!addrDest.IsIPv4())
    {
        closesocket(hSocket);
        return error("Proxy destination is not IPv4");
    }
    char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    if (!addrDest.GetSockAddr((struct sockaddr*)&addr, &len) || addr.sin_family != AF_INET)
    {
        closesocket(hSocket);
        return error("Cannot get proxy destination address");
    }
    memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
    memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
    char* pszSocks4 = pszSocks4IP;
    int nSize = sizeof(pszSocks4IP);

    int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
    if (ret != nSize)
    {
        closesocket(hSocket);
        return error("Error sending to proxy");
    }
    char pchRet[8];
    if (recv(hSocket, pchRet, 8, 0) != 8)
    {
        closesocket(hSocket);
        return error("Error reading proxy response");
    }
    if (pchRet[1] != 0x5a)
    {
        closesocket(hSocket);
        if (pchRet[1] != 0x5b)
            printf("ERROR: Proxy returned error %d\n", pchRet[1]);
        return false;
    }
    printf("SOCKS4 connected %s\n", addrDest.ToString().c_str());
    return true;
}
Ejemplo n.º 3
0
bool SetProxy(enum Network net, CService addrProxy, int nSocksVersion) {
    assert(net >= 0 && net < NET_MAX);
    if (nSocksVersion != 0 && nSocksVersion != 4 && nSocksVersion != 5)
        return false;
    if (nSocksVersion != 0 && !addrProxy.IsValid())
        return false;
    LOCK(cs_proxyInfos);
    proxyInfo[net] = std::make_pair(addrProxy, nSocksVersion);
    return true;
}
Ejemplo n.º 4
0
void CAddrMan::Good_(const CService &addr, int64_t nTime)
{
//    printf("Good: addr=%s\n", addr.ToString().c_str());

    int nId;
    CAddrInfo *pinfo = Find(addr, &nId);

    // if not found, bail out
    if (!pinfo)
        return;

    CAddrInfo &info = *pinfo;

    // check whether we are talking about the exact same CService (including same port)
    if (info != addr)
        return;

    // update info
    info.nLastSuccess = nTime;
    info.nLastTry = nTime;
    info.nTime = nTime;
    info.nAttempts = 0;

    // if it is already in the tried set, don't do anything else
    if (info.fInTried)
        return;

    // find a bucket it is in now
    int nRnd = GetRandInt(ADDRMAN_NEW_BUCKET_COUNT);
    int nUBucket = -1;
 /* for (unsigned int n = 0; n < vvNew.size(); n++)
    {
        int nB = (n+nRnd) % vvNew.size();
        std::set<int> &vNew = vvNew[nB];
        if (vNew.count(nId))
        {
 */
    for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
        int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
        int nBpos = info.GetBucketPosition(nKey, true, nB);
        if (vvNew[nB][nBpos] == nId) {
            nUBucket = nB;
            break;
        }
    }

    // if no bucket is found, something bad happened;
    // TODO: maybe re-add the node, but for now, just bail out
    if (nUBucket == -1) return;

    printf("Moving %s to tried\n", addr.ToString().c_str());

    // move nId to the tried tables
    MakeTried(info, nId);
}
Ejemplo n.º 5
0
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
    const proxyType &proxy = proxyInfo[addrDest.GetNetwork()];

#ifdef USE_NATIVE_I2P
    if (addrDest.IsNativeI2P()&&IsI2PEnabled()) {
        SOCKET streamSocket = I2PSession::Instance().connect(addrDest.GetI2PDestination(), false/*, streamSocket*/);
        if (SetSocketOptions(streamSocket)) {
            hSocketRet = streamSocket;
            return true;
        }
        return false;
    }
#endif

    // no proxy needed
    if (!proxy.second)
        return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);

    SOCKET hSocket = INVALID_SOCKET;

    // first connect to proxy server
    if (!ConnectSocketDirectly(proxy.first, hSocket, nTimeout))
        return false;
 
    // do socks negotiation
    switch (proxy.second) {
    case 4:
        if (!Socks4(addrDest, hSocket))
            return false;
        break;
    case 5:
        if (!Socks5(addrDest.ToStringIP(), addrDest.GetPort(), hSocket))
            return false;
        break;
    default:
        return false;
    }

    hSocketRet = hSocket;
    return true;
}
Ejemplo n.º 6
0
 bool CServiceManager::unload(const Service::Uid &service)
 {
    LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
    mActiveServicesMutex.lock();
    tServiceMap::iterator it = mActiveServices.find(service);
    if (mActiveServices.end() == it)
    {
       mActiveServicesMutex.unlock();
       return false;
    }
    CService * pService = it->second;
    pService->unload();
    if (!pService->hasUnloadWaits())
    {
       mActiveServices.erase(it);
       delete pService;
    }
    mActiveServicesMutex.unlock();
    return true;
 }
Ejemplo n.º 7
0
 Error CServiceManager::load(const Service::Uid & service)
 {
    LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
    mSystemServicesMutex.lock();
    tServiceSet::const_iterator it = mSystemServices.find(service);
    if (mSystemServices.end() == it)
    {
       mSystemServicesMutex.unlock();
       LOG4CPLUS_ERROR(msLogger, "hasn't found the requested service");
       return Error(SERVICE_NOT_FOUND, "The service requested: " + service.value() 
          + " was not found among system services, please check that it is present in " + mXmlPath, false);
    }
    mSystemServicesMutex.unlock();
    mActiveServicesMutex.lock();
    tServiceMap::const_iterator sit = mActiveServices.find(service);
    if (mActiveServices.end() != sit)
    {
       mActiveServicesMutex.unlock();
       LOG4CPLUS_ERROR(msLogger, "The requested service is among active!");
       return Error(SERVICE_ALREADY_LOADED, "The service requested: " + service.value() 
          + " is already loaded!", false);
    }
    mActiveServicesMutex.unlock();
    CService * pService = new CService(mXmlPath, mAppInfo, service);
    mCallbacksMutex.lock();
    Error cserviceError = pService->load(mCallbacks);
    if (!cserviceError.isNoError())
    {
       mCallbacksMutex.unlock();
       LOG4CPLUS_ERROR(msLogger, "CService couldn't load the service: " + cserviceError.toString());
       delete pService;
       return cserviceError;
    }
    mCallbacksMutex.unlock();
    mActiveServicesMutex.lock();
    mActiveServices[service] = pService;
    mActiveServicesMutex.unlock();
    LOG4CPLUS_TRACE(msLogger, "Loaded a service successfully");
    return Error::NoError();
 }
Ejemplo n.º 8
0
      void CServiceManager::releaseProfile(const Service::Uid &service, const Profile::ApiUid &profileApi)
      {
         LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__);
         mActiveServicesMutex.lock();
         tServiceMap::iterator it = mActiveServices.find(service);
         if (mActiveServices.end() != it)
         {
            it->second->releaseProfile(profileApi);
            if (it->second->allDied())
            {
               CService * pService = it->second;
               pService->unload();
               if (!pService->hasUnloadWaits())
               {
                  mActiveServices.erase(it);
                  delete pService;
               }

            }
         }
         mActiveServicesMutex.unlock();
      }
Ejemplo n.º 9
0
void CAddrMan::Good_(const CService& addr, int64_t nTime)
{
    int nId;

    nLastGood = nTime;

    CAddrInfo* pinfo = Find(addr, &nId);

    // if not found, bail out
    if (!pinfo)
        return;

    CAddrInfo& info = *pinfo;

    // check whether we are talking about the exact same CService (including same port)
    if (info != addr)
        return;

    // update info
    info.nLastSuccess = nTime;
    info.nLastTry = nTime;
    info.nAttempts = 0;
    // nTime is not updated here, to avoid leaking information about
    // currently-connected peers.

    // if it is already in the tried set, don't do anything else
    if (info.fInTried)
        return;

    // find a bucket it is in now
    int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT);
    int nUBucket = -1;
    for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
        int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
        int nBpos = info.GetBucketPosition(nKey, true, nB);
        if (vvNew[nB][nBpos] == nId) {
            nUBucket = nB;
            break;
        }
    }

    // if no bucket is found, something bad happened;
    // TODO: maybe re-add the node, but for now, just bail out
    if (nUBucket == -1)
        return;

    LogPrint("addrman", "Moving %s to tried\n", addr.ToString());

    // move nId to the tried tables
    MakeTried(info, nId);
}
Ejemplo n.º 10
0
void CAddrMan::Good_(const CService &addr, int64 nTime)
{
//    printf("Good: addr=%s\n", addr.ToString().c_str());

    int nId;
    CAddrInfo *pinfo = Find(addr, &nId);

    // if not found, bail out                                                       если не найдено, bail out(аварийное завершение)
    if (!pinfo)
        return;

    CAddrInfo &info = *pinfo;

    // check whether we are talking about the exact same CService (including same port)    убедитесь, что мы говорим о том же CService (в том числе тот же порт)
    if (info != addr)
        return;

    // update info                                                                  обновление информации
    info.nLastSuccess = nTime;
    info.nLastTry = nTime;
    info.nTime = nTime;
    info.nAttempts = 0;

    // if it is already in the tried set, don't do anything else                    исли это уже в пыталась установить, не делать что-либо еще
    if (info.fInTried)
        return;

    // find a bucket it is in now                                                   найдите бакет, в котором это находится теперь
    int nRnd = GetRandInt(vvNew.size());
    int nUBucket = -1;
    for (unsigned int n = 0; n < vvNew.size(); n++)
    {
        int nB = (n+nRnd) % vvNew.size();
        std::set<int> &vNew = vvNew[nB];
        if (vNew.count(nId))
        {
            nUBucket = nB;
            break;
        }
    }

    // if no bucket is found, something bad happened;                               если бакет не найден, что-то плохое случилось;
    // TODO: maybe re-add the node, but for now, just bail out                      может быть повторно добавить узел, но сейчас только bail out(аварийное завершение)
    if (nUBucket == -1) return;

    printf("Moving %s to tried\n", addr.ToString().c_str());

    // move nId to the tried tables
    MakeTried(info, nId, nUBucket);
}
Ejemplo n.º 11
0
void CSocketListener::StartServiceL()
	{
/*	HBufC* threadName = HBufC::NewLC(KMaxFileName);
	TPtr ptr = threadName->Des();
	GenerateUniqueName(ptr, this);
	RThread service;
	TRequestStatus status;
	User::LeaveIfError(service.Create(*threadName, CSocketListener::ThreadFunc,
			KStackSize, NULL, this));
	service.Resume();
	service.Close();
	CleanupStack::PopAndDestroy(threadName);
*/
/*	CService* service = CService::NewLC(iServerT);
	service->StartL(iSockClient);
	iSockClient = NULL;
*/
	for(TInt8 i=0; i< iServicePool.Count(); i++)
		{
		CService* service = iServicePool[i]; 
		if(service->IsIdle())
			{
			service->StartL(iSockClient);
			iSockClient = NULL;
			break;
			}
		}
	
	if(iSockClient!=NULL) // if the service pool is fulled, deny a service.
		{
		iSockClient->Close();
		delete iSockClient;
		iSockClient = NULL;
		}
	
	// SetActive();
	}
Ejemplo n.º 12
0
DWORD WINAPI CService::DeviceNotificationCallback(HCMNOTIFICATION Notify,
    PVOID Context, CM_NOTIFY_ACTION Action, PCM_NOTIFY_EVENT_DATA EventData,
    DWORD EventDataSize)
{
    CService *pThis = reinterpret_cast<CService *>(Context);
    DWORD event = 0;

    switch (Action)
    {
        case CM_NOTIFY_ACTION_DEVICEINTERFACEARRIVAL:
            event = DBT_DEVICEARRIVAL;
            break;

        case CM_NOTIFY_ACTION_DEVICEQUERYREMOVE:
            event = DBT_DEVICEQUERYREMOVE;
            break;

        case CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED:
            event = DBT_DEVICEQUERYREMOVEFAILED;
            break;

        case CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE:
            event = DBT_DEVICEREMOVECOMPLETE;
            break;

        default:
            break;
    }

    if (event > 0)
    {
        pThis->ServiceHandleDeviceChange(event);
    }

    return ERROR_SUCCESS;
}
Ejemplo n.º 13
0
void TorController::disconnected_cb(TorControlConnection& conn)
{
    // Stop advertising service when disconnected
    if (service.IsValid())
        RemoveLocal(service);
    service = CService();
    if (!reconnect)
        return;

    LogPrint("tor", "tor: Not connected to Tor control port %s, trying to reconnect\n", target);

    // Single-shot timer for reconnect. Use exponential backoff.
    struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
    if (reconnect_ev)
        event_add(reconnect_ev, &time);
    reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
}
Ejemplo n.º 14
0
bool CActiveMasternode::Dseep(CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage, bool stop) {
    std::string errorMessage;
    std::vector<unsigned char> vchMasterNodeSignature;
    std::string strMasterNodeSignMessage;
    int64_t masterNodeSignatureTime = GetAdjustedTime();

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(stop);

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyMasternode)) {
    	retErrorMessage = "sign message failed: " + errorMessage;
    	LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, errorMessage)) {
    	retErrorMessage = "Verify message failed: " + errorMessage;
    	LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    // Update Last Seen timestamp in masternode list
    bool found = false;
    BOOST_FOREACH(CMasterNode& mn, vecMasternodes) {
        //LogPrintf(" -- %s\n", mn.vin.ToString().c_str());
        if(mn.vin == vin) {
            found = true;
            mn.UpdateLastSeen();
        }
    }

    if(!found){
    	// Seems like we are trying to send a ping while the masternode is not registered in the network
    	retErrorMessage = "Darksend Masternode List doesn't include our masternode, Shutting down masternode pinging service! " + vin.ToString();
    	LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str());
        status = MASTERNODE_NOT_CAPABLE;
        notCapableReason = retErrorMessage;
        return false;
    }

    //send to all peers
    LogPrintf("CActiveMasternode::Dseep() - SendDarkSendElectionEntryPing vin = %s\n", vin.ToString().c_str());
    SendDarkSendElectionEntryPing(vin, vchMasterNodeSignature, masterNodeSignatureTime, stop);

    return true;
}
Ejemplo n.º 15
0
bool CActiveThrone::Dseep(CTxIn vin, CService service, CKey keyThrone, CPubKey pubKeyThrone, std::string &retErrorMessage, bool stop) {
    std::string errorMessage;
    std::vector<unsigned char> vchThroNeSignature;
    std::string strThroNeSignMessage;
    int64_t ThroneSignatureTime = GetAdjustedTime();

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(ThroneSignatureTime) + boost::lexical_cast<std::string>(stop);

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchThroNeSignature, keyThrone)) {
        retErrorMessage = "sign message failed: " + errorMessage;
        LogPrintf("CActiveThrone::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    if(!darkSendSigner.VerifyMessage(pubKeyThrone, vchThroNeSignature, strMessage, errorMessage)) {
        retErrorMessage = "Verify message failed: " + errorMessage;
        LogPrintf("CActiveThrone::Dseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    // Update Last Seen timestamp in Throne list
    CThrone* pmn = mnodeman.Find(vin);
    if(pmn != NULL)
    {
        if(stop)
            mnodeman.Remove(pmn->vin);
        else
            pmn->UpdateLastSeen();
    }
    else
    {
        // Seems like we are trying to send a ping while the Throne is not registered in the network
        retErrorMessage = "Darksend Throne List doesn't include our Throne, Shutting down Throne pinging service! " + vin.ToString();
        LogPrintf("CActiveThrone::Dseep() - Error: %s\n", retErrorMessage.c_str());
        status = THRONE_NOT_CAPABLE;
        notCapableReason = retErrorMessage;
        return false;
    }

    //send to all peers
    LogPrintf("CActiveThrone::Dseep() - RelayThroneEntryPing vin = %s\n", vin.ToString().c_str());
    mnodeman.RelayThroneEntryPing(vin, vchThroNeSignature, ThroneSignatureTime, stop);

    return true;
}
Ejemplo n.º 16
0
bool CActiveBlanknode::Sseep(CTxIn vin, CService service, CKey keyBlanknode, CPubKey pubKeyBlanknode, std::string &retErrorMessage, bool stop) {
    std::string errorMessage;
    std::vector<unsigned char> vchBlankNodeSignature;
    std::string strBlankNodeSignMessage;
    int64_t blankNodeSignatureTime = GetAdjustedTime();

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(blankNodeSignatureTime) + boost::lexical_cast<std::string>(stop);

    if(!zeroSendSigner.SignMessage(strMessage, errorMessage, vchBlankNodeSignature, keyBlanknode)) {
    	retErrorMessage = "sign message failed: " + errorMessage;
    	LogPrintf("CActiveBlanknode::Sseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    if(!zeroSendSigner.VerifyMessage(pubKeyBlanknode, vchBlankNodeSignature, strMessage, errorMessage)) {
    	retErrorMessage = "Verify message failed: " + errorMessage;
    	LogPrintf("CActiveBlanknode::Sseep() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    CBlanknode* psn = snodeman.Find(vin);
    if(psn != NULL)
    {
        if(stop)
            snodeman.Remove(psn->vin);
        else
            psn->UpdateLastSeen();
    } else {
    	// Seems like we are trying to send a ping while the blanknode is not registered in the network
    	retErrorMessage = "Zerosend Blanknode List doesn't include our blanknode, Shutting down blanknode pinging service! " + vin.ToString();
    	LogPrintf("CActiveBlanknode::Sseep() - Error: %s\n", retErrorMessage.c_str());
        status = BLANKNODE_NOT_CAPABLE;
        notCapableReason = retErrorMessage;
        return false;
    }

    //send to all peers
    LogPrintf("CActiveBlanknode::Sseep() - RelayBlanknodeEntryPing vin = %s\n", vin.ToString().c_str());
    snodeman.RelayBlanknodeEntryPing(vin, vchBlankNodeSignature, blankNodeSignatureTime, stop);

    return true;
}
Ejemplo n.º 17
0
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
  SOCKET hSocket;
  if(!ConnectSocket(addrConnect, hSocket))
    return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());

  send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);

  string strLine;
  while(RecvLine(hSocket, strLine))
  {
    if(strLine.empty()) // HTTP response is separated from headers by blank line
    {
      loop
      {
        if(!RecvLine(hSocket, strLine))
        {
          closesocket(hSocket);
          return false;
        }
        if(pszKeyword == NULL)
          break;
        if(strLine.find(pszKeyword) != string::npos)
        {
          strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
          break;
        }
      }
      closesocket(hSocket);
      if(strLine.find("<") != string::npos)
        strLine = strLine.substr(0, strLine.find("<"));
      strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
      while(strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
        strLine.resize(strLine.size()-1);
      CService addr(strLine,0,true);
      printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
      if(!addr.IsValid() || !addr.IsRoutable())
        return false;
      ipRet.SetIP(addr);
      return true;
    }
  }
Ejemplo n.º 18
0
bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage) {
    std::string errorMessage;
    std::vector<unsigned char> vchMasterNodeSignature;
    std::string strMasterNodeSignMessage;
    int64_t masterNodeSignatureTime = GetAdjustedTime();

    std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
    std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION);

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) {
		retErrorMessage = "sign message failed: " + errorMessage;
		LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
    }

    if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) {
		retErrorMessage = "Verify message failed: " + errorMessage;
		LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
	}

    bool found = false;
    LOCK(cs_masternodes);
    BOOST_FOREACH(CMasterNode& mn, vecMasternodes)
        if(mn.vin == vin)
            found = true;

    if(!found) {
        LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str());
        CMasterNode mn(service, vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION);
        mn.UpdateLastSeen(masterNodeSignatureTime);
        vecMasternodes.push_back(mn);
    }

    //send to all peers
    LogPrintf("CActiveMasternode::Register() - SendDarkSendElectionEntry vin = %s\n", vin.ToString().c_str());
    SendDarkSendElectionEntry(vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION);

    return true;
}
Ejemplo n.º 19
0
void CAddrMan::Good_(const CService& addr, int64_t nTime)
{
    int nId;

    nLastGood = nTime;

    CAddrInfo* pinfo = Find(addr, &nId);

    if (!pinfo)
        return;

    CAddrInfo& info = *pinfo;

    if (info != addr)
        return;

    info.nLastSuccess = nTime;
    info.nLastTry = nTime;
    info.nAttempts = 0;

    if (info.fInTried)
        return;

    int nRnd = RandomInt(ADDRMAN_NEW_BUCKET_COUNT);
    int nUBucket = -1;
    for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
        int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
        int nBpos = info.GetBucketPosition(nKey, true, nB);
        if (vvNew[nB][nBpos] == nId) {
            nUBucket = nB;
            break;
        }
    }

    if (nUBucket == -1)
        return;

    LogPrint("addrman", "Moving %s to tried\n", addr.ToString());

    MakeTried(info, nId);
}
Ejemplo n.º 20
0
BOOL ServiceControl(int ctrl)
{
    SC_HANDLE service;
    SC_HANDLE scm;
    BOOL res;
    SERVICE_STATUS status;

    scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (!scm) {
        ErrorHandler("OpenSCManager", GetLastError());
    }

    service = OpenService(scm, ServiceName, SERVICE_ALL_ACCESS);
    if (!service) {
        ErrorHandler("OpenService", GetLastError());
    }

    if (ctrl == SERVICE_CONTROL_STOP) {
        printf("Service is stopping...\n");
        res = ControlService(service, SERVICE_CONTROL_STOP, &status);
    } else if (ctrl == SERVICE_CONTROL_PAUSE) {
        printf("Service is pausing...\n");
        res = ControlService(service, SERVICE_CONTROL_PAUSE, &status);
    } else if (ctrl == SERVICE_CONTROL_CONTINUE) {
        printf("Service is resuming...\n");
        res = ControlService(service, SERVICE_CONTROL_CONTINUE, &status);
    }

    if (!res) {
        ErrorHandler("ControlService", GetLastError());
    } else {
        srvc.GetStatus(service);
    }

    CloseServiceHandle(service);
    CloseServiceHandle(scm);

    return TRUE;
}
Ejemplo n.º 21
0
void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
{
    if (reply.code == 250) {
        LogPrint("tor", "tor: ADD_ONION successful\n");
        BOOST_FOREACH(const std::string &s, reply.lines) {
            std::map<std::string,std::string> m = ParseTorReplyMapping(s);
            std::map<std::string,std::string>::iterator i;
            if ((i = m.find("ServiceID")) != m.end())
                service_id = i->second;
            if ((i = m.find("PrivateKey")) != m.end())
                private_key = i->second;
        }
        service = LookupNumeric(std::string(service_id+".onion").c_str(), GetListenPort());
        LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
        if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
            LogPrint("tor", "tor: Cached service private key to %s\n", GetPrivateKeyFile());
        } else {
            LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile());
        }
        AddLocal(service, LOCAL_MANUAL);
        // ... onion requested - keep connection open
    } else if (reply.code == 510) { // 510 Unrecognized command
Ejemplo n.º 22
0
bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, CScript rewardAddress, int rewardPercentage, std::string &retErrorMessage) {
    std::string errorMessage;
    std::vector<unsigned char> vchMasterNodeSignature;
    std::string strMasterNodeSignMessage;
    int64_t masterNodeSignatureTime = GetAdjustedTime();

    std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
    std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + rewardAddress.ToString() + boost::lexical_cast<std::string>(rewardPercentage);

    if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) {
		retErrorMessage = "sign message failed: " + errorMessage;
		LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
    }

    if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) {
		retErrorMessage = "Verify message failed: " + errorMessage;
		LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str());
		return false;
	}

    CMasternode* pmn = mnodeman.Find(vin);
    if(pmn == NULL)
    {
        LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str());
        CMasternode mn(service, vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION, rewardAddress, rewardPercentage); 
        mn.ChangeNodeStatus(false);
        mn.UpdateLastSeen(masterNodeSignatureTime);
        mnodeman.Add(mn);
    }

    //send to all peers
    LogPrintf("CActiveMasternode::Register() - RelayElectionEntry vin = %s\n", vin.ToString().c_str());
    mnodeman.RelayMasternodeEntry(vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, rewardAddress, rewardPercentage);

    return true;
}
Ejemplo n.º 23
0
bool CActiveBlanknode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyBlanknode, CPubKey pubKeyBlanknode, CScript donationAddress, int donationPercentage, std::string &retErrorMessage) {
    std::string errorMessage;
    std::vector<unsigned char> vchBlankNodeSignature;
    std::string strBlankNodeSignMessage;
    int64_t blankNodeSignatureTime = GetAdjustedTime();

    std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
    std::string vchPubKey2(pubKeyBlanknode.begin(), pubKeyBlanknode.end());

    std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(blankNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + donationAddress.ToString() + boost::lexical_cast<std::string>(donationPercentage);

    if(!zeroSendSigner.SignMessage(strMessage, errorMessage, vchBlankNodeSignature, keyCollateralAddress)) {
        retErrorMessage = "sign message failed: " + errorMessage;
        LogPrintf("CActiveBlanknode::Register() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    if(!zeroSendSigner.VerifyMessage(pubKeyCollateralAddress, vchBlankNodeSignature, strMessage, errorMessage)) {
        retErrorMessage = "Verify message failed: " + errorMessage;
        LogPrintf("CActiveBlanknode::Register() - Error: %s\n", retErrorMessage.c_str());
        return false;
    }

    CBlanknode* psn = snodeman.Find(vin);
    if(psn == NULL)
    {
        LogPrintf("CActiveBlanknode::Register() - Adding to Blanknode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str());
        CBlanknode sn(service, vin, pubKeyCollateralAddress, vchBlankNodeSignature, blankNodeSignatureTime, pubKeyBlanknode, PROTOCOL_VERSION, donationAddress, donationPercentage);
        sn.UpdateLastSeen(blankNodeSignatureTime);
        snodeman.Add(sn);
    }

    //send to all peers
    LogPrintf("CActiveBlanknode::Register() - RelayElectionEntry vin = %s\n", vin.ToString().c_str());
    snodeman.RelayBlanknodeEntry(vin, service, vchBlankNodeSignature, blankNodeSignatureTime, pubKeyCollateralAddress, pubKeyBlanknode, -1, -1, blankNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercentage);

    return true;
}
Ejemplo n.º 24
0
void CAddrMan::Good_(const CService& addr, bool test_before_evict, int64_t nTime)
{
    int nId;

    nLastGood = nTime;

    CAddrInfo* pinfo = Find(addr, &nId);

    // if not found, bail out
    if (!pinfo)
        return;

    CAddrInfo& info = *pinfo;

    // check whether we are talking about the exact same CService (including same port)
    if (info != addr)
        return;

    // update info
    info.nLastSuccess = nTime;
    info.nLastTry = nTime;
    info.nAttempts = 0;
    // nTime is not updated here, to avoid leaking information about
    // currently-connected peers.

    // if it is already in the tried set, don't do anything else
    if (info.fInTried)
        return;

    // find a bucket it is in now
    int nRnd = insecure_rand.randrange(ADDRMAN_NEW_BUCKET_COUNT);
    int nUBucket = -1;
    for (unsigned int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
        int nB = (n + nRnd) % ADDRMAN_NEW_BUCKET_COUNT;
        int nBpos = info.GetBucketPosition(nKey, true, nB);
        if (vvNew[nB][nBpos] == nId) {
            nUBucket = nB;
            break;
        }
    }

    // if no bucket is found, something bad happened;
    // TODO: maybe re-add the node, but for now, just bail out
    if (nUBucket == -1)
        return;

    // which tried bucket to move the entry to
    int tried_bucket = info.GetTriedBucket(nKey);
    int tried_bucket_pos = info.GetBucketPosition(nKey, false, tried_bucket);

    // Will moving this address into tried evict another entry?
    if (test_before_evict && (vvTried[tried_bucket][tried_bucket_pos] != -1)) {
        // Output the entry we'd be colliding with, for debugging purposes
        auto colliding_entry = mapInfo.find(vvTried[tried_bucket][tried_bucket_pos]);
        LogPrint(BCLog::ADDRMAN, "Collision inserting element into tried table (%s), moving %s to m_tried_collisions=%d\n", colliding_entry != mapInfo.end() ? colliding_entry->second.ToString() : "", addr.ToString(), m_tried_collisions.size());
        if (m_tried_collisions.size() < ADDRMAN_SET_TRIED_COLLISION_SIZE) {
            m_tried_collisions.insert(nId);
        }
    } else {
        LogPrint(BCLog::ADDRMAN, "Moving %s to tried\n", addr.ToString());

        // move nId to the tried tables
        MakeTried(info, nId);
    }
}
Ejemplo n.º 25
0
bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &errorMessage) {
    CMasternodeBroadcast mnb;
    CMasternodePing mnp(vin);
    if(!mnp.Sign(keyMasternode, pubKeyMasternode)){
        errorMessage = strprintf("Failed to sign ping, vin: %s", vin.ToString());
        LogPrintf("CActiveMasternode::Register() -  %s\n", errorMessage);
        return false;
    }
    mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));

    LogPrintf("CActiveMasternode::Register() - Adding to Masternode list\n    service: %s\n    vin: %s\n", service.ToString(), vin.ToString());
    mnb = CMasternodeBroadcast(service, vin, pubKeyCollateralAddress, pubKeyMasternode, PROTOCOL_VERSION);
    mnb.lastPing = mnp;
    if(!mnb.Sign(keyCollateralAddress)){
        errorMessage = strprintf("Failed to sign broadcast, vin: %s", vin.ToString());
        LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
        return false;
    }
    mnodeman.mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb));
    masternodeSync.AddedMasternodeList(mnb.GetHash());

    CMasternode* pmn = mnodeman.Find(vin);
    if(pmn == NULL)
    {
        CMasternode mn(mnb);
        mnodeman.Add(mn);
    } else {
        pmn->UpdateFromNewBroadcast(mnb);
    }

    //send to all peers
    LogPrintf("CActiveMasternode::Register() - RelayElectionEntry vin = %s\n", vin.ToString());
    mnb.Relay();

    return true;
}
Ejemplo n.º 26
0
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
    hSocketRet = INVALID_SOCKET;

#ifdef USE_IPV6
    struct sockaddr_storage sockaddr;
#else
    struct sockaddr sockaddr;
#endif
    socklen_t len = sizeof(sockaddr);
    if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
        printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
        return false;
    }

    SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (hSocket == INVALID_SOCKET)
        return false;
#ifdef SO_NOSIGPIPE
    int set = 1;
    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif

#ifdef WIN32
    u_long fNonblock = 1;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    int fFlags = fcntl(hSocket, F_GETFL, 0);
    if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
    {
        closesocket(hSocket);
        return false;
    }

    if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
    {
        // WSAEINVAL is here because some legacy version of winsock uses it
        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
        {
            struct timeval timeout;
            timeout.tv_sec  = nTimeout / 1000;
            timeout.tv_usec = (nTimeout % 1000) * 1000;

            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0)
            {
                printf("connection timeout\n");
                closesocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR)
            {
                printf("select() for connection failed: %i\n",WSAGetLastError());
                closesocket(hSocket);
                return false;
            }
            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
                printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
                closesocket(hSocket);
                return false;
            }
            if (nRet != 0)
            {
                printf("connect() failed after select(): %s\n",strerror(nRet));
                closesocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
            printf("connect() failed: %i\n",WSAGetLastError());
            closesocket(hSocket);
            return false;
        }
    }

    // this isn't even strictly necessary
    // CNode::ConnectNode immediately turns the socket back to non-blocking
    // but we'll turn it back to blocking just in case
#ifdef WIN32
    fNonblock = 0;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    fFlags = fcntl(hSocket, F_GETFL, 0);
    if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
#endif
    {
        closesocket(hSocket);
        return false;
    }

    hSocketRet = hSocket;
    return true;
}
Ejemplo n.º 27
0
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
    hSocketRet = INVALID_SOCKET;

    struct sockaddr_storage sockaddr;
    socklen_t len = sizeof(sockaddr);
    if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
        LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
        return false;
    }

    SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (hSocket == INVALID_SOCKET)
        return false;
#ifdef SO_NOSIGPIPE
    int set = 1;
    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif

#ifdef WIN32
    u_long fNonblock = 1;
    if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
#else
    int fFlags = fcntl(hSocket, F_GETFL, 0);
    if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
#endif
    {
        closesocket(hSocket);
        return false;
    }

    if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
    {
        int nErr = WSAGetLastError();
        // WSAEINVAL is here because some legacy version of winsock uses it
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL)
        {
            struct timeval timeout;
            timeout.tv_sec  = nTimeout / 1000;
            timeout.tv_usec = (nTimeout % 1000) * 1000;

            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0)
            {
                LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
                closesocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR)
            {
                LogPrintf("select() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
                closesocket(hSocket);
                return false;
            }
            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
                LogPrintf("getsockopt() for %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
                closesocket(hSocket);
                return false;
            }
            if (nRet != 0)
            {
                LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), strerror(nRet));
                closesocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
            LogPrintf("connect() to %s failed: %i\n", addrConnect.ToString(), WSAGetLastError());
            closesocket(hSocket);
            return false;
        }
    }
Ejemplo n.º 28
0
bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout)
{
    hSocketRet = INVALID_SOCKET;

    struct sockaddr_storage sockaddr;
    socklen_t len = sizeof(sockaddr);
    if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
        LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
        return false;
    }

    SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (hSocket == INVALID_SOCKET)
        return false;

#ifdef SO_NOSIGPIPE
    int set = 1;
    // Different way of disabling SIGPIPE on BSD
    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif

    // Set to non-blocking
    if (!SetSocketNonBlocking(hSocket, true))
        return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));

    if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
        int nErr = WSAGetLastError();
        // WSAEINVAL is here because some legacy version of winsock uses it
        if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
            struct timeval timeout = MillisToTimeval(nTimeout);
            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0) {
                LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
                CloseSocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR) {
                LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
                CloseSocket(hSocket);
                return false;
            }
            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
                LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
                CloseSocket(hSocket);
                return false;
            }
            if (nRet != 0) {
                LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
                CloseSocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
            LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
            CloseSocket(hSocket);
            return false;
        }
    }
Ejemplo n.º 29
0
	bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
	{
		hSocketRet = INVALID_SOCKET;

		SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (hSocket == INVALID_SOCKET)
			return false;
	#ifdef SO_NOSIGPIPE
		int set = 1;
		setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
	#endif

		bool fProxy = (fUseProxy && addrDest.IsRoutable());
		struct sockaddr_in sockaddr;
		if (fProxy)
			addrProxy.GetSockAddr(&sockaddr);
		else
			addrDest.GetSockAddr(&sockaddr);

	#ifdef WIN32
		u_long fNonblock = 1;
		if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
	#else
		int fFlags = fcntl(hSocket, F_GETFL, 0);
		if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == -1)
	#endif
		{
			closesocket(hSocket);
			return false;
		}


		if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)
		{
			// WSAEINVAL is here because some legacy version of winsock uses it
			if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
			{
				struct timeval timeout;
				timeout.tv_sec  = nTimeout / 1000;
				timeout.tv_usec = (nTimeout % 1000) * 1000;

				fd_set fdset;
				FD_ZERO(&fdset);
				FD_SET(hSocket, &fdset);
				int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
				if (nRet == 0)
				{
					printf("connection timeout\n");
					closesocket(hSocket);
					return false;
				}
				if (nRet == SOCKET_ERROR)
				{
					printf("select() for connection failed: %i\n",WSAGetLastError());
					closesocket(hSocket);
					return false;
				}
				socklen_t nRetSize = sizeof(nRet);
	#ifdef WIN32
				if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
	#else
				if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
	#endif
				{
					printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
					closesocket(hSocket);
					return false;
				}
				if (nRet != 0)
				{
					printf("connect() failed after select(): %s\n",strerror(nRet));
					closesocket(hSocket);
					return false;
				}
			}
	#ifdef WIN32
			else if (WSAGetLastError() != WSAEISCONN)
	#else
			else
	#endif
			{
				printf("connect() failed: %i\n",WSAGetLastError());
				closesocket(hSocket);
				return false;
			}
		}

		// this isn't even strictly necessary
		// CNode::ConnectNode immediately turns the socket back to non-blocking
		// but we'll turn it back to blocking just in case
	#ifdef WIN32
		fNonblock = 0;
		if (ioctlsocket(hSocket, FIONBIO, &fNonblock) == SOCKET_ERROR)
	#else
		fFlags = fcntl(hSocket, F_GETFL, 0);
		if (fcntl(hSocket, F_SETFL, fFlags & !O_NONBLOCK) == SOCKET_ERROR)
	#endif
		{
			closesocket(hSocket);
			return false;
		}

		if (fProxy)
		{
			printf("proxy connecting %s\n", addrDest.ToString().c_str());
			char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";
			struct sockaddr_in addr;
			addrDest.GetSockAddr(&addr);
			memcpy(pszSocks4IP + 2, &addr.sin_port, 2);
			memcpy(pszSocks4IP + 4, &addr.sin_addr, 4);
			char* pszSocks4 = pszSocks4IP;
			int nSize = sizeof(pszSocks4IP);

			int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);
			if (ret != nSize)
			{
				closesocket(hSocket);
				return error("Error sending to proxy");
			}
			char pchRet[8];
			if (recv(hSocket, pchRet, 8, 0) != 8)
			{
				closesocket(hSocket);
				return error("Error reading proxy response");
			}
			if (pchRet[1] != 0x5a)
			{
				closesocket(hSocket);
				if (pchRet[1] != 0x5b)
					printf("ERROR: Proxy returned error %d\n", pchRet[1]);
				return false;
			}
			printf("proxy connected %s\n", addrDest.ToString().c_str());
		}

		hSocketRet = hSocket;
		return true;
	}
Ejemplo n.º 30
0
bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout)
{
    hSocketRet = INVALID_SOCKET;

    struct sockaddr_storage sockaddr;
    socklen_t len = sizeof(sockaddr);
    if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
        printf("Cannot connect to %s: unsupported network\n", addrConnect.ToString().c_str());
        return false;
    }

    SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
    if (hSocket == INVALID_SOCKET)
        return false;
#ifdef SO_NOSIGPIPE
    int set = 1;
    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif

    if (!SetSocketNonBlocking(hSocket, true))
        return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %i\n", WSAGetLastError());

    if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
    {
        // WSAEINVAL is here because some legacy version of winsock uses it
        if (WSAGetLastError() == WSAEINPROGRESS || WSAGetLastError() == WSAEWOULDBLOCK || WSAGetLastError() == WSAEINVAL)
        {
            struct timeval timeout;
            timeout.tv_sec  = nTimeout / 1000;
            timeout.tv_usec = (nTimeout % 1000) * 1000;

            fd_set fdset;
            FD_ZERO(&fdset);
            FD_SET(hSocket, &fdset);
            int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
            if (nRet == 0)
            {
                printf("connection timeout\n");
                CloseSocket(hSocket);
                return false;
            }
            if (nRet == SOCKET_ERROR)
            {
                printf("select() for connection failed: %i\n",WSAGetLastError());
                CloseSocket(hSocket);
                return false;
            }
            socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
            if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
            {
                printf("getsockopt() for connection failed: %i\n",WSAGetLastError());
                CloseSocket(hSocket);
                return false;
            }
            if (nRet != 0)
            {
                printf("connect() failed after select(): %s\n",strerror(nRet));
                CloseSocket(hSocket);
                return false;
            }
        }
#ifdef WIN32
        else if (WSAGetLastError() != WSAEISCONN)
#else
        else
#endif
        {
            printf("connect() failed: %i\n",WSAGetLastError());
            CloseSocket(hSocket);
            return false;
        }
    }

    hSocketRet = hSocket;
    return true;
}