Exemplo n.º 1
0
address* Relocation::pd_address_in_code() {
  // Relocations in Shark are just stored directly
  return (address *) addr();
}
Exemplo n.º 2
0
void C2SHandler::onDisconnected()
{
    LOG(info) << "c2s handler disconnected: " << addr() << ENDL;
}
Exemplo n.º 3
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x55;
        pchMessageStart[1] = 0x42;
        pchMessageStart[2] = 0x4B;
        pchMessageStart[3] = 0x45;
        nDefaultPort = 11066;
        nRPCPort = 11067;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 100000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Viking Era";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 0.001 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1400630400; //nTime
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 2016973;
        
        hashGenesisBlock = genesis.GetHash();
        // while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
        //     if (++genesis.nNonce==0) break;
        //     hashGenesisBlock = genesis.GetHash();
        //}


        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000c07c30a4f74683e64ed156668e3f8d2e71bb4efcdcc44c248708d1cabf2"));
        assert(genesis.hashMerkleRoot == uint256("0xb8b26c88ea01ea6cbbd9fd39158f1e6cae130cc2cd5950b78727d83aa71c056d"));

        vSeeds.push_back(CDNSSeedData("198.46.134.15", "192.3.10.93"));
		vSeeds.push_back(CDNSSeedData("95.85.46.218", "81.11.246.44"));
        vSeeds.push_back(CDNSSeedData("108.61.10.90", "192.241.199.243"));
   

        base58Prefixes[PUBKEY_ADDRESS] = 70;
        base58Prefixes[SCRIPT_ADDRESS] = 132;
        base58Prefixes[SECRET_KEY] = 86;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Exemplo n.º 4
0
void CameraDialog::setnet()
{
    QString addr(ui->lineEdit_ip->text());
    ip.setAddress(addr);
    port = ui->lineEdit_port->text().toUInt();
}
Exemplo n.º 5
0
int main(int argc, char *argv[]) {

  /* Set up command line arguments */
  try {

    TCLAP::CmdLine cmd("Socket demo", ' ', "0.1");
    TCLAP::ValueArg<unsigned int> port("", "port", "Local Port (default: 1976)", false, 1976, "unsigned int", cmd);
    TCLAP::ValueArg<unsigned int> rport("", "rport", "Remote Port (default: 1976)", false, 1977, "unsigned int", cmd);

    TCLAP::UnlabeledValueArg<std::string> destIp("destIp", "Destination IP address", false, "", "std::string", cmd);
    TCLAP::SwitchArg receive("r", "receive", "Act as receiver.", cmd);

    cmd.parse(argc, argv);

    if (!receive.getValue()) {
      if (destIp.getValue() == "") {
        TCLAP::StdOutput().usage(cmd);
        exit(-1);
      }

      voip_toolbox::Ipv4SocketAddress addr("", port.getValue());
      voip_toolbox::Ipv4SocketAddress raddr(destIp.getValue(), rport.getValue());

      voip_toolbox::UdpSocket s;
      s.open();

      if (s.isOpen()) {
        std::cerr << "Socket is open. Sending 'hello' to " << raddr.toString(true) << std::endl;
      }

      if (!s.bind(addr)) {
        std::cerr << "Error binding socket!" << std::endl;
        s.close();
        exit(-1);
      }

      const char* hellostr = "hello";
      std::vector<uint8_t> data(hellostr, hellostr + strlen(hellostr));
      uint32_t send_cnt = 0, i = 0;

      while (true) {
        send_cnt = s.sendto(raddr, data);
        std::cerr << "Sent " << send_cnt << " bytes." << std::endl;
      }
      s.close();

    } else {
      voip_toolbox::Ipv4SocketAddress addr("", port.getValue());
      voip_toolbox::UdpSocket s;
      s.open();

      if (s.isOpen()) {
        std::cerr << "Socket is open. Listening... " << std::endl;
      }

      if (!s.bind(addr)) {
        std::cerr << "Error binding socket!" << std::endl;
        s.close();
        exit(-1);
      }

      while (true) {
        std::vector<uint8_t> data(128, 0);
        voip_toolbox::Ipv4SocketAddress from;
        s.recvfrom(from, data, 128);

        std::cerr << "Received " << data.size() << " bytes from " << from.toString(true) << std::endl;
        std::string msg(reinterpret_cast<const char*>(&data[0]), data.size());
        std::cerr << "Message: " << msg << std::endl;
      }
      s.close();

    }
  } catch (TCLAP::ArgException& argEx) {
    std::cerr << "Error parsing command line arguments: " << argEx.error() << " for argument " << argEx.argId() << std::endl;
  }

  return 0;
}
Exemplo n.º 6
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x09;
        pchMessageStart[1] = 0x04;
        pchMessageStart[2] = 0x04;
        pchMessageStart[3] = 0x05;
        nDefaultPort = 7777;
        nRPCPort = 7070;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 250000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.

        const char* pszTimestamp = "Pump dump sell buy hold but when you hear the thunder be ready bc it will be showtimeee";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1387754247;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 416023;

        //// debug print
        hashGenesisBlock = genesis.GetHash();
        while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
            if (++genesis.nNonce==0) break;
            hashGenesisBlock = genesis.GetHash();
        }

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();


        assert(hashGenesisBlock == uint256("0x00000a26ae3a3e42c19266cdcb6c1705c644f6e12eff14ed69384ae9415f555d"));
        assert(genesis.hashMerkleRoot == uint256("0xcbe518469ca4a98504a704913d2e3b4c0a131c8734a21aa8e56f879071e5c3fc"));

        vSeeds.push_back(CDNSSeedData("70.193.4.56", "70.193.4.56"));


        base58Prefixes[PUBKEY_ADDRESS] = 127;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time'
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Exemplo n.º 7
0
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP:
            settings.setValue("fUseUPnP", value.toBool());
            MapPort(value.toBool());
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;
        case ProxyUse:
            settings.setValue("fUseProxy", value.toBool());
            ApplyProxySettings();
            break;
        case ProxyIP: {
            proxyType proxy;
            proxy = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            CNetAddr addr(value.toString().toStdString());
            proxy.SetIP(addr);
            settings.setValue("addrProxy", proxy.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxyPort: {
            proxyType proxy;
            proxy = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            proxy.SetPort(value.toInt());
            settings.setValue("addrProxy", proxy.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case Fee:
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", (qint64) nTransactionFee);
            emit transactionFeeChanged(nTransactionFee);
            break;
        case ReserveBalance:
            nReserveBalance = value.toLongLong();
            settings.setValue("nReserveBalance", (qint64) nReserveBalance);
            emit reserveBalanceChanged(nReserveBalance);
            break;
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case Language:
            settings.setValue("language", value);
            break;
        case CoinControlFeatures: {
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            }
            break;
        case UseBlackTheme:
            fUseBlackTheme = value.toBool();
            settings.setValue("fUseBlackTheme", fUseBlackTheme);
            break;
        case DarksendRounds:
            nDarksendRounds = value.toInt();
            settings.setValue("nDarksendRounds", nDarksendRounds);
            emit darksendRoundsChanged(nDarksendRounds);
            break;
        case AnonymizeTaoAmount:
            nAnonymizeTaoAmount = value.toInt();
            settings.setValue("nAnonymizeTaoAmount", nAnonymizeTaoAmount);
            emit AnonymizeTaoAmountChanged(nAnonymizeTaoAmount);
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}
bool MediaStream::start(QHostAddress ip, int port, int localPort, int codecPayload )
{
    if ( isRunning() )
        stop();

    printf("%s %d | %d | %d\n",ip.toString().toAscii().data(), port, localPort, codecPayload);

    if(d->processThread == NULL)
	d->processThread = new MediaThread(this);
    d->outBufferPos = 0;
    d->outBufferTime = 0;

//    int localPort = 3000;
printf("getFactory(%d)\n", codecPayload);
    VoiceCodecFactory *factory = CodecsManager::instance()->codecFactory(codecPayload);
    if ( !factory ) {
        printf("VoiceCodecFactory not found!\n");
        return true;
    }

    d->codecPayload = codecPayload;
    d->decoder =  factory->decoder();
    d->encoder =  factory->encoder();

printf("transparams\n");
    // Now, we'll create a RTP session and set the destination
//     d->transparams.mediaChannel = mediaChannel;
//     d->transparams.incomingPackets = incomingPackets;
    d->transparams.SetPortbase(localPort);
	
    RTPSessionParams sessparams;
    sessparams.SetReceiveMode(RTPTransmitter::AcceptAll);

    sessparams.SetOwnTimestampUnit(1.0/8000.0); // 8KHz
	sessparams.SetAcceptOwnPackets(true);

printf("session.Create()\n");
    int status = d->session.Create( sessparams, &d->transparams, RTPTransmitter::SynapseProto );

    if ( status<0 ) {
        qDebug("can't create RTP session, %s", RTPGetErrorString(status).c_str() );
        d->session.Destroy(); 
        return false;
    }

printf("session.AddDestination()\n");
    RTPIPv4Address addr(ip.toIPv4Address(),port);
	status = d->session.AddDestination(addr);

    if ( status<0 ) {
         qDebug("can't add rtp destination, %s", RTPGetErrorString(status).c_str() );
        d->session.Destroy(); 
        return false;
    }

    d->session.SetDefaultPayloadType(codecPayload);
    d->session.SetDefaultMark(false);
    d->session.SetDefaultTimestampIncrement(160);

    //initialise audio

    status = Pa_Initialize();
//////////////////// FOR TESTING
    if( status != paNoError ) {
        qDebug( "PortAudio error: %s", Pa_GetErrorText(status) );
//        stop();
 //       return true;
    }

if(status == paNoError) {

    status = Pa_OpenDefaultStream(
        &d->audioStream,/* passes back stream pointer */
        1,              /* 1 input channel */
        1,              /* mono output */
        paInt16,        /* 16 bit fixed point output */
        8000,           /* sample rate */
        240,            /* frames per buffer */
        16,             /* number of buffers, if zero then use default minimum */
        audioCallback,  /* specify our custom callback */
        d );            /* pass our data through to callback */

    status = Pa_StartStream( d->audioStream );
    if( status != paNoError ) {
         qDebug( "PortAudio error: %s", Pa_GetErrorText(status) );
//        stop();
//        return true;
    }
}
    

    // put something to dsp buffer
    /*
    char emptyData[160*8];
    memset(  emptyData, 1, sizeof(emptyData) );
    d->dspBuffer->lock();
    d->dspBuffer->put( emptyData, sizeof(emptyData) );
    d->dspBuffer->unlock();
    */



    //d->timer.start(1,false);
    d->isRunning = true;
    d->processThread->start();
    
//    qDebug("mediastream started");
    printf("mediastream started\n");
    return true;
} // }}}
Exemplo n.º 9
0
		void TCPConnection::connect()
		{
			// do not connect to other hosts if we are in server
			if (_socket != NULL) return;

			// do not connect to anyone if we are already connected
			if (_socket_stream != NULL) return;

			// variables for address and port
			std::string address = "0.0.0.0";
			unsigned int port = 0;

			// try to connect to the other side
			try {
				const std::list<dtn::core::Node::URI> uri_list = _node.get(dtn::core::Node::CONN_TCPIP);

				for (std::list<dtn::core::Node::URI>::const_iterator iter = uri_list.begin(); iter != uri_list.end(); ++iter)
				{
					// break-out if the connection has been aborted
					if (_aborted) throw ibrcommon::socket_exception("connection has been aborted");

					try {
						// decode address and port
						const dtn::core::Node::URI &uri = (*iter);
						uri.decode(address, port);

						// create a virtual address to connect to
						ibrcommon::vaddress addr(address, port);

						IBRCOMMON_LOGGER_DEBUG_TAG(TCPConnection::TAG, 15) << "Initiate TCP connection to " << address << ":" << port << IBRCOMMON_LOGGER_ENDL;

						// create a new tcpsocket
						timeval tv;
						timerclear(&tv);
						tv.tv_sec = _timeout;

						// create a new tcp connection via the tcpsocket object
						ibrcommon::tcpsocket *client = new ibrcommon::tcpsocket(addr, &tv);

						try {
							// connect to the node
							client->up();

							// setup a new tcp connection
							__setup_socket(client, false);

							// add TCP connection descriptor to the node object
							_node.clear();
							_node.add( dtn::core::Node::URI(Node::NODE_CONNECTED, Node::CONN_TCPIP, uri.value, 0, 30) );

							// connection successful
							return;
						} catch (const ibrcommon::socket_exception&) {
							delete client;
						}
					} catch (const ibrcommon::socket_exception&) { };
				}

				// no connection has been established
				throw ibrcommon::socket_exception("no address available to connect");

			} catch (const ibrcommon::socket_exception&) {
				// error on open, requeue all bundles in the queue
				IBRCOMMON_LOGGER_TAG(TCPConnection::TAG, warning) << "connection to " << _node.toString() << " failed" << IBRCOMMON_LOGGER_ENDL;
				try {
					(*getProtocolStream()).shutdown(dtn::streams::StreamConnection::CONNECTION_SHUTDOWN_ERROR);
				} catch (const ibrcommon::Exception&) {};
				throw;
			} catch (const bad_cast&) { };
		}
Exemplo n.º 10
0
void ClientSktTcp::asynConn()
{
    show(QString("TCP connection to %1:%2 opened!")
        .arg(addr().toString()).arg(port()));
}
Exemplo n.º 11
0
void ClientSktUdp::asynConn()
{
    show(QString("UDP channel to %1:%2 opened!")
        .arg(addr().toString()).arg(port()));
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
    // individual tx do not affect any representation
    static const bool fMultiSig = true;

    QString strHTML;

    LOCK2(cs_main, wallet->cs_wallet);
    strHTML.reserve(4000);
    strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";

    int64_t nTime = wtx.GetTxTime();

    std::map<int, int64_t> mapDebit, mapCredit, mapChange, mapNet;
    // debits
    wallet->FillDebits(wtx, mapDebit, fMultiSig);
    // credits (mature)
    wallet->FillMatures(wtx, mapCredit, fMultiSig);

    // nets (mature - debits)
    FillNets(mapDebit, mapCredit, mapNet);

    strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
    int nRequests = wtx.GetRequestCount();
    if (nRequests != -1)
    {
        if (nRequests == 0)
            strHTML += tr(", has not been successfully broadcast yet");
        else if (nRequests > 0)
            strHTML += tr(", broadcast through %n node(s)", "", nRequests);
    }
    strHTML += "<br>";

    strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";

    //
    // From
    //
    if (wtx.IsCoinBase() || wtx.IsCoinStake())
    {
        strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
    }
    else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
    {
        // Online transaction
        strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
    }
    else
    {

        // Offline transaction
        if (ValueMapAllPositive(mapNet))
        {
            // Credit
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            {
                if (wallet->IsMine(txout, fMultiSig) & ISMINE_ALL)
                {
                    CTxDestination address;
                    if (ExtractDestination(txout.scriptPubKey, address) &&
                        (IsMine(*wallet, address, fMultiSig) & ISMINE_ALL))
                    {
                        if (wallet->mapAddressBook.count(address))
                        {
                            strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
                            strHTML += "<b>" + tr("To") + ":</b> ";
                            CBitcoinAddress addr(address, txout.nColor);
                            strHTML += GUIUtil::HtmlEscape(addr.ToString());
                            // indicate distinction between own address and watch address
                            if (IsMine(*wallet, address, fMultiSig) & ISMINE_SPENDABLE)
                            {
                                if (!wallet->mapAddressBook[address].empty())
                                {
                                    strHTML += " (" + tr("own address") + ", " + tr("label") + ": " +
                                                   GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                                }
                                else
                                {
                                    strHTML += " (" + tr("own address") + ")";
                                }
                            }
                            else
                            {
                                if (!wallet->mapAddressBook[address].empty())
                                {
                                    strHTML += " (" + tr("watch address") + ", " + tr("label") + ": " +
                                                   GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                                }
                                else
                                {
                                    strHTML += " (" + tr("watch address") + ")";
                                }
                            }
                            strHTML += "<br>";
                        }
                    }
                    break;
                }
            }
        }
    }

    //
    // To
    //
    if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
    {
        // Online transaction
        std::string strAddress = wtx.mapValue["to"];
        strHTML += "<b>" + tr("To") + ":</b> ";
        CTxDestination dest = CBitcoinAddress(strAddress).Get();
        if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
        strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
    }

    //
    // Amount
    //
    // Coinbase was not mature
    if (wtx.IsCoinBase() && ValueMapAllZero(mapCredit))
    {
        //
        // Coinbase
        //
        strHTML += "<b>" + tr("Credit") + ":</b> ";
        if (wtx.IsInMainChain())
        {
            std::map<int, int64_t> mapUnmatured;
            wallet->FillCredits(wtx, mapUnmatured, fMultiSig);
            strHTML += ValueMapToHTML(mapUnmatured);
            strHTML += " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
        }
        else
        {
            strHTML += "(" + tr("not accepted") + ")";
        }
        strHTML += "<br>";
    }
    else if (ValueMapAllPositive(mapNet))
    {
        //
        // Credit
        //
        strHTML += "<b>" + tr("Credit") + ":</b> " + ValueMapToHTML(mapNet) + "<br>";
    }
    else
    {
        bool fAllFromMe = true;
        BOOST_FOREACH(const CTxIn& txin, wtx.vin)
        {
            fAllFromMe = fAllFromMe && (wallet->IsMine(txin, fMultiSig) & ISMINE_SPENDABLE);
            if (!fAllFromMe)
            {
                break;
            }
        }

        bool fAllToMe = true;
        BOOST_FOREACH(const CTxOut& txout, wtx.vout)
        {
            fAllToMe = fAllToMe && (wallet->IsMine(txout, fMultiSig) & ISMINE_SPENDABLE);
            if (!fAllToMe)
            {
                break;
            }
        }

        if (fAllFromMe)
        {
            //
            // Debit
            //
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            {
                if (wallet->IsMine(txout, fMultiSig) & ISMINE_SPENDABLE)
                {
                    continue;
                }

                if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
                {
                    // Offline transaction
                    CTxDestination address;
                    if (ExtractDestination(txout.scriptPubKey, address))
                    {
                        strHTML += "<b>" + tr("To") + ":</b> ";
                        if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
                            strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
                        strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address, txout.nColor).ToString());
                        strHTML += "<br>";
                    }
                }

                strHTML += "<b>" + tr("Debit") + ":</b> " +
                           BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -txout.nValue, txout.nColor) + "<br>";
            }

             std::map<int, int64_t> mapFee, mapDebit, mapValuesOut;

            if (fAllToMe)
            {
                // Payment to self
                std::map<int, int64_t> mapChange, mapValue;
                wallet->FillChange(wtx, mapChange);
                FillNets(mapChange, mapCredit, mapValue);
                FillNets(mapCredit, mapChange, mapDebit);
                strHTML += "<b>" + tr("Debit") + ":</b> " + ValueMapToHTML(mapDebit) + "<br>";
                strHTML += "<b>" + tr("Credit") + ":</b> " + ValueMapToHTML(mapValue) + "<br>";
            }

            wtx.FillValuesOut(mapValuesOut);
            wallet->FillDebits(wtx, mapDebit, fMultiSig);
            FillNets(mapValuesOut, mapDebit, mapFee);
            if (ValueMapAllPositive(mapFee))
            {
                strHTML += "<b>" + tr("Transaction fee") + ":</b> " + ValueMapToHTML(mapFee) + "<br>";
            }
        }
        else
        {
            //
            // Mixed debit transaction
            //
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
            {
                strHTML += TxInToHTML(txin, wallet);
            }
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
            {
                strHTML += TxOutToHTML(txout, wallet);
            }
        }
    }
Exemplo n.º 13
0
bool TcpServer::initLocalProxy(QString & thisHost,qint16 & thisPort,LocalSocket * sock)
{
    QByteArray generalError;
    generalError.append((char)0x05); // SOCKS5
    generalError.append((char)0x01); // general error

    sock->waitForReadyRead();
    QByteArray ba = sock->read(2);
    // 1st byte - SOCKS version
    // 2nd byte - Auth method count

    int authCnt = (int)ba.at(1);

    // we only serve SOCKS5
    if(ba.at(0)!=5) {
        sock->close();
        sock->deleteLater();
        return false;
    }
    while(sock->bytesAvailable() < authCnt)
        sock->waitForReadyRead();
    // ignore auth
    sock->read(authCnt);
    QByteArray response;
    response.append((char)0x05); // SOCKS version
    response.append((char)0x00); // requested auth method (0x00 means no auth)
    sock->write(response);
    sock->waitForBytesWritten();
    while(sock->bytesAvailable() < 4)
        sock->waitForReadyRead();
    ba = sock->read(4);
    // 1st byte - SOCKS version
    // 2nd byte - command (1 = open TCP stream)
    // 3rd byte - 0x00
    // 4th byte - address type (1 = IPv4, 3 = QDN, 4 = IPv6)
    if(ba.at(0)!=5) {
        sock->write(generalError);
        sock->waitForBytesWritten();
        sock->close();
        sock->deleteLater();
        return false;
    } else if(ba.at(1)!=1) {
        // only handle "open stream" requests
        sock->write(generalError);
        sock->waitForBytesWritten();
        sock->close();
        sock->deleteLater();
        return false;
    } else if(ba.at(2)!=0) {
        sock->write(generalError);
        sock->waitForBytesWritten();
        sock->close();
        sock->deleteLater();
        return false;
    }
    // reuse old response object containing 0x05, 0x00
    // 1st byte = SOCKS version
    // 2nd byte = status (0x00 = success)
    // 3rd byte = 0x00
    // 4th and following bytes - repeat what the client sent, not sure that's correct,
    //                                                        it should contain the outgoing host:port pair
    response.append((char)0x00);
    response.append(ba.at(3));
    switch(ba.at(3)) {
    // IPv4
    case 1: {
        while(sock->bytesAvailable() < 4)
            sock->waitForReadyRead();
        ba = sock->read(4);
        QHostAddress addr(qFromBigEndian<quint32>((uchar*)ba.constData()));
        thisHost = addr.toString();
        response.append(ba);
        }
        break;
        // domain name
    case 3: {
        while(sock->bytesAvailable() < 1)
            sock->waitForReadyRead();
        ba = sock->read(1);
        int len = ba.at(0);
        response.append(ba);
        while(sock->bytesAvailable() < len)
            sock->waitForReadyRead();
        ba = sock->read(len);
        thisHost = ba;
        response.append(ba);
        }
        break;
    case 4:{
        while(sock->bytesAvailable() < 16)
            sock->waitForReadyRead();
        ba = sock->read(16);
        QHostAddress addr(ba.constData());
        thisHost = addr.toString();
        response.append(ba);
        }
        break;
    default: {
        // deny IPv6 (yes, I'm lazy, it's just a few lines of code) and incorrect values
        sock->write(generalError);
        sock->waitForBytesWritten();
        sock->close();
        sock->deleteLater();
        return false;
        }
    }
    while(sock->bytesAvailable() < 2)
        sock->waitForReadyRead();
    ba = sock->read(2);
    // port in network order
    thisPort = qFromBigEndian<qint16>((uchar*)ba.constData());
    response.append(ba);
    sock->write(response); // notify success and proceed with remote connection
    return true;
}
Exemplo n.º 14
0
QString EvaUser::currentLoginIP( )
{
	QHostAddress addr(getLoginWanIp());
	return addr.toString();
}
Exemplo n.º 15
0
DSN_API dsn_address_t dsn_group_next(dsn_group_t g, dsn_address_t ep)
{
    auto grp = (::dsn::rpc_group_address*)(g);
    ::dsn::rpc_address addr(ep);
    return grp->next(addr).c_addr();
}
Exemplo n.º 16
0
bool
CreateGameTransactions (const CCoinsView& view, unsigned nHeight,
                        const StepResult& stepResult,
                        std::vector<CTransaction>& vGameTx)
{
  vGameTx.clear ();

  /* Destroy name-coins of killed players.  */

  bool haveTxKills = false;
  CMutableTransaction txKills;
  txKills.SetGameTx ();

  const PlayerSet& killedPlayers = stepResult.GetKilledPlayers ();
  const KilledByMap& killedBy = stepResult.GetKilledBy ();
  txKills.vin.reserve (killedPlayers.size ());
  BOOST_FOREACH(const PlayerID &victim, killedPlayers)
    {
      const valtype vchName = ValtypeFromString (victim);
      CNameData data;
      if (!view.GetName (vchName, data))
        return error ("Game engine killed a non-existing player %s",
                      victim.c_str ());

      CTxIn txin(data.getUpdateOutpoint ());

      /* List all killers, if player was simultaneously killed by several
         other players.  If the reason was not KILLED_DESTRUCT, handle
         it also.  If multiple reasons apply, the game tx is constructed
         for the first reason according to the ordering inside of KilledByMap.
         (Which in turn is determined by the enum values for KILLED_*.)  */

      typedef KilledByMap::const_iterator Iter;
      const std::pair<Iter, Iter> iters = killedBy.equal_range (victim);
      if (iters.first == iters.second)
        return error ("No reason for killed player %s", victim.c_str ());
      const KilledByInfo::Reason reason = iters.first->second.reason;

      /* Unless we have destruct, there should be exactly one entry with
         the "first" reason.  There may be multiple entries for different
         reasons, for instance, killed by poison and staying in spawn
         area at the same time.  */
      {
        Iter it = iters.first;
        ++it;
        if (reason != KilledByInfo::KILLED_DESTRUCT && it != iters.second
            && reason == it->second.reason)
          return error ("Multiple same-reason, non-destruct killed-by"
                        " entries for %s", victim.c_str ());
      }

      switch (reason)
        {
        case KilledByInfo::KILLED_DESTRUCT:
          txin.scriptSig << vchName << GAMEOP_KILLED_BY;
          for (Iter it = iters.first; it != iters.second; ++it)
            {
              if (it->second.reason != KilledByInfo::KILLED_DESTRUCT)
                {
                  assert (it != iters.first);
                  break;
                }
              txin.scriptSig
                << ValtypeFromString (it->second.killer.ToString ());
            }
          break;

        case KilledByInfo::KILLED_SPAWN:
          txin.scriptSig << vchName << GAMEOP_KILLED_BY;
          break;

        case KilledByInfo::KILLED_POISON:
          txin.scriptSig << vchName << GAMEOP_KILLED_POISON;
          break;

        default:
          assert (false);
        }

      txKills.vin.push_back (txin);
      haveTxKills = true;
    }
  if (haveTxKills)
    {
      const CTransaction tx(txKills);
      assert (tx.IsGameTx () && !tx.IsBountyTx ());
      vGameTx.push_back (tx);
    }

  /* Pay bounties to the players who collected them.  The transaction
     inputs are just "dummy" containing informational messages.  */

  bool haveTxBounties = false;
  CMutableTransaction txBounties;
  txBounties.SetGameTx ();

  txBounties.vin.reserve (stepResult.bounties.size ());
  txBounties.vout.reserve (stepResult.bounties.size ());

  BOOST_FOREACH(const CollectedBounty& bounty, stepResult.bounties)
    {
      const valtype vchName = ValtypeFromString (bounty.character.player);
      CNameData data;
      if (!view.GetName (vchName, data))
        return error ("Game engine created bounty for non-existing player");

      CTxOut txout;
      txout.nValue = bounty.loot.nAmount;

      if (!bounty.address.empty ())
        {
          /* Player-provided addresses are validated before accepting them,
             so failing here is ok.  */
          CBitcoinAddress addr(bounty.address);
          if (!addr.IsValid ())
            return error ("Failed to set player-provided address for bounty");
          txout.scriptPubKey = GetScriptForDestination (addr.Get ());
        }
      else
        txout.scriptPubKey = data.getAddress ();

      txBounties.vout.push_back (txout);

      CTxIn txin;
      if (bounty.loot.IsRefund ())
        txin.scriptSig
          << vchName << GAMEOP_REFUND
          << bounty.character.index << bounty.loot.GetRefundHeight ();
      else
        txin.scriptSig
          << vchName << GAMEOP_COLLECTED_BOUNTY
          << bounty.character.index
          << bounty.loot.firstBlock
          << bounty.loot.lastBlock
          << bounty.loot.collectedFirstBlock
          << bounty.loot.collectedLastBlock;
      txBounties.vin.push_back (txin);

      haveTxBounties = true;
    }
  if (haveTxBounties)
    {
      const CTransaction tx(txBounties);
      assert (tx.IsGameTx () && tx.IsBountyTx ());
      vGameTx.push_back (tx);
    }

  /* Print log chatter.  */
  if (haveTxKills || haveTxBounties)
    {
      LogPrint ("game", "Game transactions @%d:\n", nHeight);
      if (haveTxKills)
        LogPrint ("game", "  kills:    %s\n", txKills.GetHash ().ToString ());
      if (haveTxBounties)
        LogPrint ("game", "  bounties: %s\n",
                  txBounties.GetHash ().ToString ());
    }

  return true;
}
Exemplo n.º 17
0
DSN_API bool dsn_group_remove(dsn_group_t g, dsn_address_t ep)
{
    auto grp = (::dsn::rpc_group_address*)(g);
    ::dsn::rpc_address addr(ep);
    return grp->remove(addr);
}
Exemplo n.º 18
0
    CMainParams() {
        // The message start string is designed to be unlikely to occur in normal data.
        pchMessageStart[0] = 0x66;
        pchMessageStart[1] = 0x66;
        pchMessageStart[2] = 0x66;
        pchMessageStart[3] = 0x66;
        nDefaultPort = 24242;
        nRPCPort = 24243;
        bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
        nSubsidyHalvingInterval = 35040000;

        // Build the genesis block. Note that the output of the genesis coinbase cannot
        // be spent as it did not originally exist in the database.
  
        const char* pszTimestamp = "Release the Kraken - www.krakencoin.com";
        CTransaction txNew;
        txNew.vin.resize(1);
        txNew.vout.resize(1);
        txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
        txNew.vout[0].nValue = 1 * COIN;
        txNewvout1nValue = 5;
        txNewvout2nValue = 450000 * COIN;
        txNew.vout[0].scriptPubKey = CScript() << ParseHex("") << OP_CHECKSIG;
        genesis.vtx.push_back(txNew);
        genesis.hashPrevBlock = 0;
        genesis.hashMerkleRoot = genesis.BuildMerkleTree();
        genesis.nVersion = 1;
        genesis.nTime    = 1394270601;
        genesis.nBits    = 0x1e0fffff;
        genesis.nNonce   = 943874;
        
        //// debug print
        hashGenesisBlock = genesis.GetHash();
        //while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
          //  if (++genesis.nNonce==0) break;
            //hashGenesisBlock = genesis.GetHash();
        //}

        printf("%s\n", hashGenesisBlock.ToString().c_str());
        printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
        printf("%x\n", bnProofOfWorkLimit.GetCompact());
        genesis.print();
        
        
        assert(hashGenesisBlock == uint256("0x00000e9d058285796d9d49c3110a98c9367d25b7ab82cab06088f29ff4160b2a"));
        assert(genesis.hashMerkleRoot == uint256("0x67cf79c130dc3b7f3a164ffde6d4ff3b30fb3847e649e5ab8c889cbcba8db40d"));

        vSeeds.push_back(CDNSSeedData("162.243.90.199", "162.243.90.199"));


        base58Prefixes[PUBKEY_ADDRESS] = 45;
        base58Prefixes[SCRIPT_ADDRESS] = 30;
        base58Prefixes[SECRET_KEY] = 224;

        // Convert the pnSeeds array into usable address objects.
        for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
        {
            // It'll only connect to one or two seed nodes because once it connects,
            // it'll get a pile of addresses with newer timestamps.
            // Seed nodes are given a random 'last seen time' 
            const int64 nTwoDays = 2 * 24 * 60 * 60;
            struct in_addr ip;
            memcpy(&ip, &pnSeed[i], sizeof(ip));
            CAddress addr(CService(ip, GetDefaultPort()));
            addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
            vFixedSeeds.push_back(addr);
        }
    }
Exemplo n.º 19
0
Arquivo: main.cpp Projeto: DavadDi/acl
int main(int argc, char* argv[])
{
    int  ch, max = 10;
    acl::string addr("127.0.0.1:8194");

    while ((ch = getopt(argc, argv, "hs:n:")) > 0)
    {
        switch (ch)
        {
        case 'h':
            usage(argv[0]);
            return 0;
        case 's':
            addr = optarg;
            break;
        case 'n':
            max = atoi(optarg);
            break;
        default:
            break;
        }
    }

    acl::string buf(1024);
    for (size_t i = 0; i < 1024; i++)
        buf << 'X';

    acl::http_request req(addr, 10, 10);
    acl::string tmp(1024);

    for (int i = 0; i < max; i++)
    {
        acl::http_header& header = req.request_header();
        header.set_url("/");
        header.set_keep_alive(true);
        header.set_content_length(buf.length());

        if (req.request(buf.c_str(), buf.length()) == false)
        {
            printf("send request error\n");
            break;
        }

        if (i < 10)
            printf("send request ok\r\n");

        tmp.clear();

        int  size = 0;
        while (true)
        {
            int ret = req.read_body(tmp, false);
            if (ret < 0) {
                printf("read_body error\n");
                return 1;
            }
            else if (ret == 0)
                break;
            size += ret;
        }
        if (i < 10)
            printf(">>size: %d\n", size);
    }

    return 0;
}
Exemplo n.º 20
0
int zmq::socket_base_t::connect (const char *addr_)
{
    if (unlikely (app_thread->is_terminated ())) {
        errno = ETERM;
        return -1;
    }

    //  Parse addr_ string.
    std::string addr_type;
    std::string addr_args;

    std::string addr (addr_);
    std::string::size_type pos = addr.find ("://");

    if (pos == std::string::npos) {
        errno = EINVAL;
        return -1;
    }

    addr_type = addr.substr (0, pos);
    addr_args = addr.substr (pos + 3);

    if (addr_type == "inproc") {

        //  TODO: inproc connect is specific with respect to creating pipes
        //  as there's no 'reconnect' functionality implemented. Once that
        //  is in place we should follow generic pipe creation algorithm.

        //  Find the peer socket.
        socket_base_t *peer = find_endpoint (addr_args.c_str ());
        if (!peer)
            return -1;

        pipe_t *in_pipe = NULL;
        pipe_t *out_pipe = NULL;

        //  Create inbound pipe, if required.
        if (options.requires_in) {
            in_pipe = new (std::nothrow) pipe_t (this, peer, options.hwm);
            zmq_assert (in_pipe);
        }

        //  Create outbound pipe, if required.
        if (options.requires_out) {
            out_pipe = new (std::nothrow) pipe_t (peer, this, options.hwm);
            zmq_assert (out_pipe);
        }

        //  Attach the pipes to this socket object.
        attach_pipes (in_pipe ? &in_pipe->reader : NULL,
            out_pipe ? &out_pipe->writer : NULL, blob_t ());

        //  Attach the pipes to the peer socket. Note that peer's seqnum
        //  was incremented in find_endpoint function. The callee is notified
        //  about the fact via the last parameter.
        send_bind (peer, out_pipe ? &out_pipe->reader : NULL,
            in_pipe ? &in_pipe->writer : NULL, options.identity, false);

        return 0;
    }

    //  Create unnamed session.
    io_thread_t *io_thread = choose_io_thread (options.affinity);
    session_t *session = new (std::nothrow) session_t (io_thread,
        this, options);
    zmq_assert (session);

    //  If 'immediate connect' feature is required, we'll created the pipes
    //  to the session straight away. Otherwise, they'll be created by the
    //  session once the connection is established.
    if (options.immediate_connect) {

        pipe_t *in_pipe = NULL;
        pipe_t *out_pipe = NULL;

        //  Create inbound pipe, if required.
        if (options.requires_in) {
            in_pipe = new (std::nothrow) pipe_t (this, session, options.hwm);
            zmq_assert (in_pipe);

        }

        //  Create outbound pipe, if required.
        if (options.requires_out) {
            out_pipe = new (std::nothrow) pipe_t (session, this, options.hwm);
            zmq_assert (out_pipe);
        }

        //  Attach the pipes to the socket object.
        attach_pipes (in_pipe ? &in_pipe->reader : NULL,
            out_pipe ? &out_pipe->writer : NULL, blob_t ());

        //  Attach the pipes to the session object.
        session->attach_pipes (out_pipe ? &out_pipe->reader : NULL,
            in_pipe ? &in_pipe->writer : NULL, blob_t ());
    }

    //  Activate the session.
    send_plug (session);
    send_own (this, session);

    if (addr_type == "tcp" || addr_type == "ipc") {

#if defined ZMQ_HAVE_WINDOWS || defined ZMQ_HAVE_OPENVMS
        //  Windows named pipes are not compatible with Winsock API.
        //  There's no UNIX domain socket implementation on OpenVMS.
        if (addr_type == "ipc") {
            errno = EPROTONOSUPPORT;
            return -1;
        }
#endif

        //  Create the connecter object. Supply it with the session name
        //  so that it can bind the new connection to the session once
        //  it is established.
        zmq_connecter_t *connecter = new (std::nothrow) zmq_connecter_t (
            choose_io_thread (options.affinity), this, options,
            session->get_ordinal (), false);
        zmq_assert (connecter);
        int rc = connecter->set_address (addr_type.c_str(), addr_args.c_str ());
        if (rc != 0) {
            delete connecter;
            return -1;
        }
        send_plug (connecter);
        send_own (this, connecter);

        return 0;
    }

#if defined ZMQ_HAVE_OPENPGM
    if (addr_type == "pgm" || addr_type == "epgm") {

        //  If the socket type requires bi-directional communication
        //  multicast is not an option (it is uni-directional).
        if (options.requires_in && options.requires_out) {
            errno = ENOCOMPATPROTO;
            return -1;
        }

        //  For epgm, pgm transport with UDP encapsulation is used.
        bool udp_encapsulation = (addr_type == "epgm");

        //  At this point we'll create message pipes to the session straight
        //  away. There's no point in delaying it as no concept of 'connect'
        //  exists with PGM anyway.
        if (options.requires_out) {

            //  PGM sender.
            pgm_sender_t *pgm_sender =  new (std::nothrow) pgm_sender_t (
                choose_io_thread (options.affinity), options);
            zmq_assert (pgm_sender);

            int rc = pgm_sender->init (udp_encapsulation, addr_args.c_str ());
            if (rc != 0) {
                delete pgm_sender;
                return -1;
            }

            send_attach (session, pgm_sender, blob_t ());
        }
        else if (options.requires_in) {

            //  PGM receiver.
            pgm_receiver_t *pgm_receiver =  new (std::nothrow) pgm_receiver_t (
                choose_io_thread (options.affinity), options);
            zmq_assert (pgm_receiver);

            int rc = pgm_receiver->init (udp_encapsulation, addr_args.c_str ());
            if (rc != 0) {
                delete pgm_receiver;
                return -1;
            }

            send_attach (session, pgm_receiver, blob_t ());
        }
        else
            zmq_assert (false);

        return 0;
    }
#endif

    //  Unknown protoco.
    errno = EPROTONOSUPPORT;
    return -1;
}
Exemplo n.º 21
0
void CUDP_RTSPClient::handleRecvVideoDataThread()
{
	bool bAudio = false;

	jrtplib::RTPSession sess;
	uint16_t portbase,destport;
	uint32_t destip;
	std::string ipstr;
	int status;

	// First, we'll ask for the necessary information
	portbase = m_clinet_video_rtpport;

	if( strlen( m_SrvAddressStr ) > 0 )
		destip = inet_addr( m_SrvAddressStr );
	else
		destip = inet_addr( m_realConnectIP );

	if ( destip == INADDR_NONE ){
		std::cerr << "Bad IP address specified" << std::endl;
		return;
	}

	// The inet_addr function returns a value in network byte order, but
	// we need the IP address in host byte order, so we use a call to
	// ntohl
	destip = ntohl(destip);

	if( !m_bVideoThreadRun )
	{
		destport = m_SrvVideoUDPPort;
		m_bVideoThreadRun = true;
		if( ( !m_recvAudioThread_.joinable() ) && m_SrvAudioUDPPort != 0 ) 
			m_recvAudioThread_ = boost::thread( &CRTSPClient::handleRecvVideoDataThread, this );
	}
	else
	{
		destport = m_SrvAudioUDPPort;
		portbase = m_clinet_audio_rtpport;

		bAudio = true;
	}

	// Now, we'll create a RTP session, set the destination, send some
	// packets and poll for incoming data.
	jrtplib::RTPUDPv4TransmissionParams transparams;
	jrtplib::RTPSessionParams sessparams;

	// IMPORTANT: The local timestamp unit MUST be set, otherwise
	//            RTCP Sender Report info will be calculated wrong
	// In this case, we'll be sending 10 samples each second, so we'll
	// put the timestamp unit to (1.0/10.0)
	sessparams.SetOwnTimestampUnit(1.0/90000.0);		

	//transparams.SetRTPSendBuffer(65536);
	transparams.SetRTPReceiveBuffer(65536*128);

	transparams.SetPortbase(portbase);
	status = sess.Create(sessparams,&transparams);	
	if(status < 0)return;

	jrtplib::RTPIPv4Address addr(destip,destport);
	status = sess.AddDestination(addr);
	if(status < 0)return;

	HRESULT hr;
	CH264_RTP_UNPACK m_h264_rtp_unpack(hr);
	bool bFrist = true;

	boost::shared_ptr<char> databuf = boost::shared_ptr<char>(new char[RAWDATALEN]);
	unsigned char* pdata = (unsigned char *)databuf.get();

	int icur = 0;
	unsigned long dwDataType = 0;
	while(m_brun){

		sess.BeginDataAccess();
		// check incoming packets
		if (sess.GotoFirstSourceWithData())
		{
			do
			{
				jrtplib::RTPPacket *pack;
				while ((pack = sess.GetNextPacket()) != NULL)
				{
					// You can examine the data here
					int timestamp = pack->GetTimestamp();

					RTPExtensionData t_RTPExtensionData;
					if(pack->GetExtensionLength() == sizeof(int))
						memcpy(&dwDataType, pack->GetExtensionData(), sizeof(int));
					if(pack->GetExtensionLength() >= sizeof(int)*2){
						memcpy(&t_RTPExtensionData, pack->GetExtensionData(), sizeof(int)*2);
						timestamp = t_RTPExtensionData.dwtimeTamp;
						dwDataType = t_RTPExtensionData.dwDataType;
					}

					if( pack->GetExtensionLength() > 0 )
					{
						//dwDataType = 2819;//mpeg4使用
						//if( bFrist ){
						//	unsigned char head[40];memset(head, 0, 40);
						//	if( !bAudio ) m_popen_camera->RecvData(0, 65536 + dwDataType, head, 40);
						//	bFrist = false;
						//}

						int i = sizeof(RTPExtensionData);
						if(icur + pack->GetPayloadLength() >= RAWDATALEN){
							if( !bAudio ) m_popen_camera->RecvData(timestamp, dwDataType, pdata, icur);
							icur = 0;
						}

						memcpy(pdata + icur, pack->GetPayloadData(), pack->GetPayloadLength());
						icur += pack->GetPayloadLength();

						if (pack->HasMarker()){
							if( !bAudio ) m_popen_camera->RecvData(timestamp, dwDataType, pdata, icur);
							icur = 0;
						}
					}
					else
					{
						//const int H264Type = 2819; //0x0B03
						const int H264Type = 20483;  //0x5003

						if( bFrist ){
							unsigned char head[40];memset(head, 0, 40);
							if( !bAudio ) m_popen_camera->RecvData(0, 65536 + H264Type, head, 40);
							bFrist = false;
						}

						// You can examine the data here
						int timestamp = pack->GetTimestamp();
						memcpy(pdata, pack->GetPacketData(), pack->GetPacketLength());

						int outsize = 0;
						BYTE* pbuf = m_h264_rtp_unpack.Parse_RTP_Packet(pdata,  pack->GetPacketLength(), &outsize);
						//m_log.Add("Parse_RTP_Packet pbuf = %d outsize=%d\n",pbuf, outsize);
						if( pbuf != NULL && outsize > 0 )
							if( !bAudio ) m_popen_camera->RecvData(0, H264Type, pbuf, outsize);
					}

					// we don't longer need the packet, so
					// we'll delete it
					sess.DeletePacket(pack);
				}
			} while (sess.GotoNextSourceWithData());
		}
		sess.EndDataAccess();

		status = sess.Poll();
		if(status < 0 || !m_brun)break;

		boost::this_thread::sleep(boost::posix_time::milliseconds(10));
	}
	//没有send BYE 对方UDP端口很难快速退出
	sess.BYEDestroy(jrtplib::RTPTime(3,0),0,0);
}
Exemplo n.º 22
0
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
    /* Clear old signature to ensure users don't get confused on error with an old signature displayed */
    ui->signatureOut_SM->clear();

    CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if (!ctx.isValid())
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
        return;
    }

    CKey key;
    CKey tkey;
    bool fwalletFound=false;
    BOOST_FOREACH(const wallet_map::value_type& item, pWalletManager->GetWalletMap())
    {

      pwalletMain = pWalletManager->GetWallet(item.first.c_str()).get();

      if (!pwalletMain->GetKey(keyID, tkey))
          qDebug() << "Address Not Found For " + QString(pwalletMain->strWalletFile.c_str());
      else
      {
          if (!pwalletMain->GetKey(keyID, key))
          {
              ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
              ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
              return;
          }
          fwalletFound=true;
      }
    }
    if (!fwalletFound)
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_SM->document()->toPlainText().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));

    ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
Exemplo n.º 23
0
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
    bool successful = true; /* set to false on parse error */
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
            break;
        case MinimizeToTray:
            fMinimizeToTray = value.toBool();
            settings.setValue("fMinimizeToTray", fMinimizeToTray);
            break;
        case MapPortUPnP:
            fUseUPnP = value.toBool();
            settings.setValue("fUseUPnP", fUseUPnP);
            MapPort();
            break;
        case MinimizeOnClose:
            fMinimizeOnClose = value.toBool();
            settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
            break;
        case ProxyUse:
            settings.setValue("fUseProxy", value.toBool());
            ApplyProxySettings();
            break;
        case ProxyIP: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            CNetAddr addr(value.toString().toStdString());
            proxy.first.SetIP(addr);
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxyPort: {
            proxyType proxy;
            proxy.first = CService("127.0.0.1", 9050);
            GetProxy(NET_IPV4, proxy);

            proxy.first.SetPort(value.toInt());
            settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
            successful = ApplyProxySettings();
        }
        break;
        case ProxySocksVersion: {
            proxyType proxy;
            proxy.second = 5;
            GetProxy(NET_IPV4, proxy);

            proxy.second = value.toInt();
            settings.setValue("nSocksVersion", proxy.second);
            successful = ApplyProxySettings();
        }
        break;
        case Fee:
            nTransactionFee = value.toLongLong();
            settings.setValue("nTransactionFee", nTransactionFee);
            emit transactionFeeChanged(nTransactionFee);
            break;
        case DisplayUnit:
            nDisplayUnit = value.toInt();
            settings.setValue("nDisplayUnit", nDisplayUnit);
            emit displayUnitChanged(nDisplayUnit);
            break;
        case DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            break;
        case DetachDatabases: {
            bool fDetachDB = value.toBool();
            bitdb.SetDetach(fDetachDB);
            settings.setValue("detachDB", fDetachDB);
            }
            break;
        case Language:
            settings.setValue("language", value);
            break;
        case CoinControlFeatures: {
            fCoinControlFeatures = value.toBool();
            settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
            emit coinControlFeaturesChanged(fCoinControlFeatures);
            }
            break;
        case CheckOnlineUpdate:
            fCheckOnlineUpdate = value.toBool();
            settings.setValue("fCheckOnlineUpdate", fCheckOnlineUpdate);
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}
Exemplo n.º 24
0
SaErrorT
cIpmi::IfGetPowerState( cIpmiEntity *ent, SaHpiHsPowerStateT &state )
{
  cIpmiAddr addr( eIpmiAddrTypeIpmb, ent->Channel(), 
                  0, ent->AccessAddress() );

  // get power level
  cIpmiMsg msg( eIpmiNetfnPicmg, eIpmiCmdGetPowerLevel );
  cIpmiMsg rsp;

  msg.m_data[0] = dIpmiPigMgId;
  msg.m_data[1] = ent->FruId();
  msg.m_data[2] = 0x01; // desired steady power
  msg.m_data_len = 3;

  int rv = SendCommand( addr, msg, rsp );

  if ( rv )
     {
       IpmiLog( "cannot send get power level: %d\n", rv );
       return SA_ERR_HPI_INVALID_CMD;
     }

  if (    rsp.m_data_len < 3
       || rsp.m_data[0] != eIpmiCcOk 
       || rsp.m_data[0] != dIpmiPigMgId )
     {
       IpmiLog( "cannot get power level: 0x%02x !\n", rsp.m_data[0] );
       return SA_ERR_HPI_INVALID_CMD;
     }

  unsigned char power_level = rsp.m_data[2] & 0x1f;

  // get current power level
  msg.m_data[2]  = 0; // steady state power

  rv = SendCommand( addr, msg, rsp );

  if ( rv )
     {
       IpmiLog( "SetHotSwapState: could not send get power level: 0x%02x !\n", rv );
       return SA_ERR_HPI_INVALID_CMD;
     }

  if (    rsp.m_data_len < 6
       || rsp.m_data[0] != eIpmiCcOk
       || rsp.m_data[1] != dIpmiPigMgId )
     {
       IpmiLog( "SetHotSwapState: IPMI error get power level: 0x%02x !\n",
                rsp.m_data[0]);

       return SA_ERR_HPI_INVALID_CMD;
     }

  unsigned char current_power_level = rsp.m_data[2] & 0x1f;
  
  if ( current_power_level >= power_level )
       state = SAHPI_HS_POWER_ON;
  else
       state = SAHPI_HS_POWER_OFF;

  return SA_OK;
}
Exemplo n.º 25
0
void C2SHandler::onOpen()
{
    LOG(info) << "c2s handler open: " << addr() << ENDL;

}
Exemplo n.º 26
0
SaErrorT
cIpmi::IfSetPowerState( cIpmiEntity *ent, SaHpiHsPowerStateT state )
{
  int rv;
  unsigned int power_level = 0;

  cIpmiAddr addr( eIpmiAddrTypeIpmb, ent->Channel(), 
                  0, ent->AccessAddress() );
  cIpmiMsg msg( eIpmiNetfnPicmg, eIpmiCmdGetPowerLevel );
  msg.m_data[0] = dIpmiPigMgId;
  msg.m_data[1] = ent->FruId();
  cIpmiMsg rsp;

  if ( state == SAHPI_HS_POWER_CYCLE )
     {
       // power off
       msg.m_cmd = eIpmiCmdSetPowerLevel;

       msg.m_data[2] = power_level;
       msg.m_data[3] = 0x01; // copy desierd level to present level
       msg.m_data_len = 4;

       rv = SendCommand( addr, msg, rsp );

       if ( rv )
          {
            IpmiLog( "cannot send set power level: %d\n", rv );
            return SA_ERR_HPI_INVALID_CMD;
          }

       if (    rsp.m_data_len < 2
               || rsp.m_data[0] != eIpmiCcOk 
               || rsp.m_data[1] != dIpmiPigMgId )
          {
            IpmiLog( "cannot set power level: 0x%02x !\n", rsp.m_data[0] );
            return SA_ERR_HPI_INVALID_CMD;
          }

       // power on
       state = SAHPI_HS_POWER_ON;
     }

  if ( state == SAHPI_HS_POWER_ON )
     {
       // get power level
       msg.m_cmd = eIpmiCmdGetPowerLevel;

       msg.m_data[2] = 0x01; // desired steady power
       msg.m_data_len = 3;

       rv = SendCommand( addr, msg, rsp );

       if ( rv )
          {
            IpmiLog( "cannot send get power level: %d\n", rv );
            return SA_ERR_HPI_INVALID_CMD;
          }

       if (    rsp.m_data_len < 3
            || rsp.m_data[0] != eIpmiCcOk 
            || rsp.m_data[1] != dIpmiPigMgId )
          {
            IpmiLog( "cannot get power level: 0x%02x !\n", rsp.m_data[0] );
            return SA_ERR_HPI_INVALID_CMD;
          }

       power_level = rsp.m_data[2] & 0x1f;
     }
  else
       assert( state == SAHPI_HS_POWER_OFF );

  // set power level
  msg.m_cmd = eIpmiCmdSetPowerLevel;

  msg.m_data[2] = power_level;
  msg.m_data[3] = 0x01; // copy desierd level to present level
  msg.m_data_len = 4;

  rv = SendCommand( addr, msg, rsp );

  if ( rv )
     {
       IpmiLog( "cannot send set power level: %d\n", rv );
       return SA_ERR_HPI_INVALID_CMD;
     }

  if (    rsp.m_data_len < 2
       || rsp.m_data[0] != eIpmiCcOk 
       || rsp.m_data[1] != dIpmiPigMgId )
     {
       IpmiLog( "cannot set power level: 0x%02x !\n", rsp.m_data[0] );
       return SA_ERR_HPI_INVALID_CMD;
     }

  return SA_OK;
}
Exemplo n.º 27
0
void CDatagrams::onReceiveGND()
{
	GND_HEADER* pHeader = (GND_HEADER*)m_pRecvBuffer->data();
	QHostAddress nIp = *m_pHostAddress;
	quint32 nSeq = ((pHeader->nSequence << 16) & 0xFFFF0000) + (m_nPort & 0x0000FFFF);

#ifdef DEBUG_UDP
	systemLog.postLog(LogSeverity::Debug, "Received GND from %s:%u nSequence = %u nPart = %u nCount = %u", m_pHostAddress->toString().toLocal8Bit().constData(), m_nPort, pHeader->nSequence, pHeader->nPart, pHeader->nCount);
#endif

	DatagramIn* pDatagramIn = 0;

	if(m_RecvCache.contains(nIp) && m_RecvCache[nIp].contains(nSeq))
	{
		pDatagramIn = m_RecvCache[nIp][nSeq];

		// To give a chance for bigger packages ;)
		if(pDatagramIn->m_nLeft)
		{
			pDatagramIn->m_tStarted = time(0);
		}
	}
	else
	{
		QMutexLocker l(&m_pSection);

		if(!m_FreeDatagramIn.isEmpty())
		{
			pDatagramIn = m_FreeDatagramIn.takeFirst();
		}
		else
		{
			if(m_FreeDatagramIn.isEmpty())
			{
				removeOldIn(true);
				if(m_FreeDatagramIn.isEmpty())
				{
#ifdef DEBUG_UDP
					systemLog.postLog(LogSeverity::Debug, QString("UDP in frames exhausted"));
#endif
					m_nDiscarded++;
					return;
				}
			}

			pDatagramIn = m_FreeDatagramIn.takeFirst();
		}

		if(m_FreeBuffer.size() < pHeader->nCount)
		{
			m_nDiscarded++;
			m_FreeDatagramIn.append(pDatagramIn);
			removeOldIn(false);
			return;
		}

		pDatagramIn->create(CEndPoint(*m_pHostAddress, m_nPort), pHeader->nFlags, pHeader->nSequence, pHeader->nCount);

		for(int i = 0; i < pHeader->nCount; i++)
		{
			Q_ASSERT(pDatagramIn->m_pBuffer[i] == 0);
			pDatagramIn->m_pBuffer[i] = m_FreeBuffer.takeFirst();
		}

		m_RecvCache[nIp][nSeq] = pDatagramIn;
		m_RecvCacheTime.prepend(pDatagramIn);
	}

	// It is here, in case if we did not have free datagrams
	// ACK = I've received a datagram, and if you have received and rejected it, do not send ACK-a
	if(pHeader->nFlags & 0x02)
	{
		GND_HEADER* pAck = new GND_HEADER;

		memcpy(pAck, pHeader, sizeof(GND_HEADER));
		pAck->nCount = 0;
		pAck->nFlags = 0;

#ifdef DEBUG_UDP
		systemLog.postLog(LogSeverity::Debug, "Sending UDP ACK to %s:%u", m_pHostAddress->toString().toLocal8Bit().constData(), m_nPort);
#endif

		//m_pSocket->writeDatagram((char*)&oAck, sizeof(GND_HEADER), *m_pHostAddress, m_nPort);
		//m_mOutput.Add(sizeof(GND_HEADER));
		m_AckCache.append(qMakePair(CEndPoint(*m_pHostAddress, m_nPort), reinterpret_cast<char*>(pAck)));
		if( m_AckCache.count() == 1 )
			QMetaObject::invokeMethod(this, "flushSendCache", Qt::QueuedConnection);
	}

	if(pDatagramIn->add(pHeader->nPart, m_pRecvBuffer->data() + sizeof(GND_HEADER), m_pRecvBuffer->size() - sizeof(GND_HEADER)))
	{

		G2Packet* pPacket = 0;
		try
		{
			CEndPoint addr(*m_pHostAddress, m_nPort);
			pPacket = pDatagramIn->toG2Packet();
			if(pPacket)
			{
				onPacket(addr, pPacket);
			}
		}
		catch(...)
		{

		}
		if(pPacket)
		{
			pPacket->release();
		}

		m_pSection.lock();
		remove(pDatagramIn, true);
		m_pSection.unlock();
	}
}
Exemplo n.º 28
0
DSN_API void dsn_group_set_leader(dsn_group_t g, dsn_address_t ep)
{
    auto grp = (::dsn::rpc_group_address*)(g);
    ::dsn::rpc_address addr(ep);
    grp->set_leader(addr);
}
static __u8 ich2rom_read8(struct map_info *map, unsigned long ofs)
{
	return __raw_readb(addr(map, ofs));
}
Exemplo n.º 30
0
int main(int argc, char* argv[])
{
	int  ch, n = 1, conn_timeout = 10, rw_timeout = 10;
	acl::string addr("127.0.0.1:6379"), cmd;
	bool slice_req = false;

	while ((ch = getopt(argc, argv, "hs:n:C:I:a:S")) > 0)
	{
		switch (ch)
		{
		case 'h':
			usage(argv[0]);
			return 0;
		case 's':
			addr = optarg;
			break;
		case 'n':
			n = atoi(optarg);
			break;
		case 'C':
			conn_timeout = atoi(optarg);
			break;
		case 'I':
			rw_timeout = atoi(optarg);
			break;
		case 'a':
			cmd = optarg;
			break;
		case 'S':
			slice_req = true;
			break;
		default:
			break;
		}
	}

	acl::acl_cpp_init();
	acl::redis_client client(addr.c_str(), conn_timeout, rw_timeout);
	client.set_slice_request(slice_req);
	acl::redis_connection redis(&client);

	bool ret;

	if (cmd == "auth")
		ret = test_auth(redis);
	else if (cmd == "echo")
		ret = test_echo(redis, n);
	else if (cmd == "ping")
		ret = test_ping(redis, n);
	else if (cmd == "quit")
		ret = test_quit(redis);
	else if (cmd == "select")
		ret = test_select(redis, n);
	else if (cmd == "all")
	{
		ret = test_auth(redis)
			&& test_echo(redis, n)
			&& test_ping(redis, n)
			&& test_select(redis, n)
			&& test_quit(redis);
	}
	else
	{
		printf("unknown cmd: %s\r\n", cmd.c_str());
		ret = false;
	}

	printf("cmd: %s %s\r\n", cmd.c_str(), ret ? "ok" : "failed");

#ifdef WIN32
	printf("enter any key to exit\r\n");
	getchar();
#endif
	return 0;
}