Esempio n. 1
0
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout)
{
    proxyType proxy;

    // no proxy needed
    if (!GetProxy(addrDest.GetNetwork(), proxy))
        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:
        closesocket(hSocket);
        return false;
    }

    hSocketRet = hSocket;
    return true;
}
Esempio n. 2
0
bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
    // Directly query current base proxy, because
    // GUI settings can be overridden with -proxy.
    proxyType curProxy;
    if (GetProxy(NET_IPV4, curProxy)) {
        if (curProxy.second == 5) {
            proxy.setType(QNetworkProxy::Socks5Proxy);
            proxy.setHostName(QString::fromStdString(curProxy.first.ToStringIP()));
            proxy.setPort(curProxy.first.GetPort());

            return true;
        }
        else
            return false;
    }
    else
        proxy.setType(QNetworkProxy::NoProxy);






    return true;
}
Esempio n. 3
0
void Debugger::Interrupt(int type, const char *program,
                         InterruptSite *site /* = NULL */,
                         const char *error /* = NULL */) {
  ASSERT(RuntimeOption::EnableDebugger);

  RequestInjectionData &rjdata = ThreadInfo::s_threadInfo->m_reqInjectionData;
  if (rjdata.debuggerIdle > 0 && type == BreakPointReached) {
    --rjdata.debuggerIdle;
    return;
  }

  DebuggerProxyPtr proxy = GetProxy();
  if (proxy) {
    if (proxy->needInterrupt() || type != BreakPointReached) {
      // Interrupts may execute some PHP code, causing another interruption.
      std::stack<void *> &interrupts = rjdata.interrupts;

      CmdInterrupt cmd((InterruptType)type, program, site, error);
      interrupts.push(&cmd);
      proxy->interrupt(cmd);
      interrupts.pop();
    }
    rjdata.debuggerIdle = proxy->needInterrupt() ? 0 : 1000;
  } else {
    // debugger clients are disconnected abnormally
    if (type == SessionStarted || type == SessionEnded) {
      // for command line programs, we need this exception to exit from
      // the infinite execution loop
      throw DebuggerClientExitException();
    }
  }
}
Esempio n. 4
0
ECode Proxy::GetPreferredHttpHost(
    /* [in] */ IContext* context,
    /* [in] */ const String& url,
    /* [out] */ IHttpHost** httpHost)
{
    VALIDATE_NOT_NULL(httpHost);

    AutoPtr<Elastos::Net::IProxyHelper> helper;
    Elastos::Net::CProxyHelper::AcquireSingleton((Elastos::Net::IProxyHelper**)&helper);
    AutoPtr<Elastos::Net::IProxy> noproxy;
    helper->GetNO_PROXY((Elastos::Net::IProxy**)&noproxy);
    AutoPtr<Elastos::Net::IProxy> prefProxy;
    GetProxy(context, url, (Elastos::Net::IProxy**)&prefProxy);
    if (prefProxy == noproxy) {
        *httpHost = NULL;
        return NOERROR;
    } else {
        AutoPtr<ISocketAddress> socketaddress;
        prefProxy->GetAddress((ISocketAddress**)&socketaddress);
        AutoPtr<IInetSocketAddress> sa = IInetSocketAddress::Probe(socketaddress);
        String hostName;
        sa->GetHostName(&hostName);
        Int32 portNum;
        sa->GetPort(&portNum);
        return CHttpHost::New(hostName, portNum, String("http"), httpHost);
    }
    return NOERROR;
}
Esempio n. 5
0
void CIceClientBase::InitIce(void)
{
    string strBasePath = "";
    strBasePath = GetProcessPath();
    try
    {
        Ice::InitializationData initData;
        initData.properties = Ice::createProperties();

        //
        // Set a default value for "Hello.Proxy" so that the demo will
        // run without a configuration file.
        //
        //initData.properties->setProperty("SHMIAlarm.Proxy", "SHMIAlarm:tcp -p 11888");

        //
        // Now, load the configuration file if present. Under WinCE we
        // use "config.txt" since it can be edited with pocket word.
        //
        std::string strConfigfile = "";
        try
        {
            strConfigfile =strBasePath + "../config/";
            strConfigfile += m_strConfigFileName;
            initData.properties->load(strConfigfile);
        }
        catch(const Ice::FileException& ex)
        {
            std::cout<< ex.what() << endl;
            std::cout<< "Maybe cannot find the config file: " << strConfigfile << endl;
            Sleep(1000);
            return;
        }

        int argc = 0;
        m_communicator = Ice::initialize(argc, 0, initData);

        string strProxy = m_strProxy;
        strProxy += ".Proxy";
        m_objPrx = m_communicator->stringToProxy(initData.properties->getProperty(strProxy));

        //IceInternal::ProxyHandle<T>
        //AlarmViewer =
        //IceInternal::ProxyHandle::checkedCast(m_objPrx);

        GetProxy();
    }
    catch(const Ice::Exception& ex)
    {
        //MessageBox(NULL, CString(ex.ice_name().c_str()), L"Exception", MB_ICONEXCLAMATION | MB_OK);
        string strMsg;
        strMsg = ex.ice_name();
        //printf("%s \n", strMsg.c_str());
        LOG_ERROR("%s", strMsg.c_str());
        return;
    }
}
    int HttpConnectProxyHttpSocket::ConnectImpl(const char *address)
    {
        ProxyHttpSocket::ConnectImpl(GetProxy());
        Util::AddressParser parser(address);
        Util::AddressParser proxyParser(GetProxy());

        std::ostringstream request;
        request << "CONNECT " << parser.GetHost() << ":" << parser.GetPort() << " HTTP/1.0\r\n";
        request << "Host: " << proxyParser.GetHost() << ":" << proxyParser.GetPort() << "\r\n";
        request << "User-Agent: " << GetAgent() << "\r\n";

        const char *user = proxyParser.GetUser();
        const char *password = proxyParser.GetPassword();

        if (*user || *password) {
		    // Encode user:password
            std::string auth = user;
            auth += ':';
            auth += password;
            auth = Util::BinToBase64(auth.c_str(), auth.length());

            request << "Proxy-Authorization: Basic " << auth << "\r\n";
	    }
    	
        request << "\r\n";

        Send(request.str().c_str());

        std::string response = Receive();

	    if (response.length() < 12) 
            throw ProxyError("Invalid response");
        
        if (response[9] != '2' || response[10] != '0' || response[11] != '0') {
		    // Proxy responded with error
            std::ostringstream msg;
            int err = (response[9] - '0') * 100 + (response[10] - '0') * 10 + (response[11] - '0');
            msg << "Responded with error " << err;
		    throw ProxyError(msg.str().c_str());
	    }

        return 0;
    }
void OptionsDialog::updateDefaultProxyNets()
{
    proxyType proxy;
    std::string strProxy;
    QString strDefaultProxyGUI;

    GetProxy(NET_IPV4, proxy);
    strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
    strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
    (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv4->setChecked(true) : ui->proxyReachIPv4->setChecked(false);

    GetProxy(NET_IPV6, proxy);
    strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
    strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
    (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachIPv6->setChecked(true) : ui->proxyReachIPv6->setChecked(false);

    GetProxy(NET_TOR, proxy);
    strProxy = proxy.proxy.ToStringIP() + ":" + proxy.proxy.ToStringPort();
    strDefaultProxyGUI = ui->proxyIp->text() + ":" + ui->proxyPort->text();
    (strProxy == strDefaultProxyGUI.toStdString()) ? ui->proxyReachTor->setChecked(true) : ui->proxyReachTor->setChecked(false);
}
Esempio n. 8
0
void KX_PythonComponent::Update()
{
	if (!m_init) {
		Start();
		m_init = true;
	}

	PyObject *pycomp = GetProxy();
	if (!PyObject_CallMethod(pycomp, "update", "")) {
		PyErr_Print();
	}
}
Esempio n. 9
0
void KX_PythonComponent::Start()
{
	PyObject *arg_dict = (PyObject *)BKE_python_component_argument_dict_new(m_pc);

	PyObject *ret = PyObject_CallMethod(GetProxy(), "start", "O", arg_dict);

	if (PyErr_Occurred()) {
		PyErr_Print();
	}

	Py_XDECREF(arg_dict);
	Py_XDECREF(ret);
}
void KX_LibLoadStatus::RunFinishCallback()
{
#ifdef WITH_PYTHON
	if (m_finish_cb) {
		PyObject* args = Py_BuildValue("(O)", GetProxy());

		if (!PyObject_Call(m_finish_cb, args, NULL)) {
			PyErr_Print();
			PyErr_Clear();
		}

		Py_DECREF(args);
	}
#endif
}
Esempio n. 11
0
CValue *KX_PythonComponent::GetReplica()
{
	KX_PythonComponent *replica = new KX_PythonComponent(*this);
	replica->ProcessReplica();

	// Subclass the python component.
	PyTypeObject *type = Py_TYPE(GetProxy());
	if (!py_base_new(type, PyTuple_Pack(1, replica->GetProxy()), NULL)) {
		CM_Error("failed replicate component: \"" << m_name << "\"");
		delete replica;
		return NULL;
	}

	return replica;
}
Esempio n. 12
0
/**
* Return the proxy host set by the user.
* @param ctx A Context used to get the settings for the proxy host.
* @return String containing the host name. If the user did not set a host
*         name it returns the default host. A null value means that no
*         host is to be used.
* @deprecated Use standard java vm proxy values to find the host, port
*         and exclusion list.  This call ignores the exclusion list.
*/
ECode CProxy::GetHost(
    /* [in] */ IContext* ctx,
    /* [out] */ String* host)
{
    VALIDATE_NOT_NULL(host);
    AutoPtr<Elastos::Net::IProxy> proxy;
    AutoPtr<Elastos::Net::IProxy> noproxy;
    proxyhelper->GetNO_PROXY((Elastos::Net::IProxy**)&noproxy);
    String str;
    GetProxy(ctx, str, (Elastos::Net::IProxy**)&proxy);
    if (proxy == noproxy) {
        *host = NULL;
        return NOERROR;
    }
    AutoPtr<ISocketAddress> socketAddress;
    proxy->GetAddress((ISocketAddress**)&socketAddress);
    AutoPtr<IInetSocketAddress> address = IInetSocketAddress::Probe(socketAddress);
    return address->GetHostName(host);
}
Esempio n. 13
0
/**
* Return the proxy port set by the user.
* @param ctx A Context used to get the settings for the proxy port.
* @return The port number to use or -1 if no proxy is to be used.
* @deprecated Use standard java vm proxy values to find the host, port
*         and exclusion list.  This call ignores the exclusion list.
*/
ECode CProxy::GetPort(
    /* [in] */ IContext* ctx,
    /* [out] */ Int32* portNum)
{
    VALIDATE_NOT_NULL(portNum);
    AutoPtr<Elastos::Net::IProxy> proxy;
    AutoPtr<Elastos::Net::IProxy> noproxy;
    proxyhelper->GetNO_PROXY((Elastos::Net::IProxy**)&noproxy);
    String str;
    GetProxy(ctx, str, (Elastos::Net::IProxy**)&proxy);
    if (proxy == noproxy) {
         *portNum = -1;
         return NOERROR;
    }
    AutoPtr<ISocketAddress> socketAddress;
    proxy->GetAddress((ISocketAddress**)&socketAddress);
    AutoPtr<IInetSocketAddress> inetaddress;
    AutoPtr<IInetSocketAddress> address = IInetSocketAddress::Probe(socketAddress);
    return address->GetPort(portNum);
}
Esempio n. 14
0
static UniValue GetNetworksInfo()
{
    UniValue networks(UniValue::VARR);
    for(int n=0; n<NET_MAX; ++n)
    {
        enum Network network = static_cast<enum Network>(n);
        if(network == NET_UNROUTABLE || network == NET_INTERNAL)
            continue;
        proxyType proxy;
        UniValue obj(UniValue::VOBJ);
        GetProxy(network, proxy);
        obj.pushKV("name", GetNetworkName(network));
        obj.pushKV("limited", IsLimited(network));
        obj.pushKV("reachable", IsReachable(network));
        obj.pushKV("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string());
        obj.pushKV("proxy_randomize_credentials", proxy.randomize_credentials);
        networks.push_back(obj);
    }
    return networks;
}
void KX_LibLoadStatus::RunProgressCallback()
{
// Progess callbacks are causing threading problems with Python, so they're disabled for now
#if 0
#ifdef WITH_PYTHON
	if (m_progress_cb) {
		//PyGILState_STATE gstate = PyGILState_Ensure();
		PyObject* args = Py_BuildValue("(O)", GetProxy());

		if (!PyObject_Call(m_progress_cb, args, NULL)) {
			PyErr_Print();
			PyErr_Clear();
		}

		Py_DECREF(args);
		//PyGILState_Release(gstate);
	}
#endif
#endif
}
Esempio n. 16
0
HRESULT
AccessibleHandler::ResolveIA2()
{
  if (mIA2PassThru) {
    return S_OK;
  }

  RefPtr<IUnknown> proxy(GetProxy());
  if (!proxy) {
    return E_UNEXPECTED;
  }

  HRESULT hr = proxy->QueryInterface(NEWEST_IA2_IID,
                                     reinterpret_cast<void**>(&mIA2PassThru));
  if (SUCCEEDED(hr)) {
    // mIA2PassThru is a weak reference (see comments in AccesssibleHandler.h)
    mIA2PassThru->Release();
  }

  return hr;
}
Esempio n. 17
0
HRESULT
AccessibleHandler::QueryService(REFGUID aServiceId, REFIID aIid,
                                void** aOutInterface)
{
  static_assert(&NEWEST_IA2_IID == &IID_IAccessible2_3,
                "You have modified NEWEST_IA2_IID. This code needs updating.");
  /* We're taking advantage of the fact that we are implementing IA2 as part
     of our own object to implement this just like a QI. */
  if (aIid == IID_IAccessible2_3 || aIid == IID_IAccessible2_2 ||
      aIid == IID_IAccessible2) {
    RefPtr<NEWEST_IA2_INTERFACE> ia2(this);
    ia2.forget(aOutInterface);
    return S_OK;
  }

  for (uint32_t i = 0; i < ArrayLength(kUnsupportedServices); ++i) {
    if (aServiceId == kUnsupportedServices[i]) {
      return E_NOINTERFACE;
    }
  }

  if (!mServProvPassThru) {
    RefPtr<IUnknown> proxy(GetProxy());
    if (!proxy) {
      return E_UNEXPECTED;
    }

    HRESULT hr = proxy->QueryInterface(IID_IServiceProvider,
                                       reinterpret_cast<void**>(&mServProvPassThru));
    if (FAILED(hr)) {
      return hr;
    }

    // mServProvPassThru is a weak reference (see comments in
    // AccessibleHandler.h)
    mServProvPassThru->Release();
  }

  return mServProvPassThru->QueryService(aServiceId, aIid, aOutInterface);
}
Esempio n. 18
0
// Primary entrypoint for the debugger from the VM. Called in response to a host
// of VM events that the debugger is interested in. The debugger will execute
// any logic needed to handle the event, and will block below this to wait for
// and process more commands from the debugger client. This function will only
// return when the debugger is letting the thread continue execution, e.g., for
// flow control command like continue, next, etc.
void Debugger::Interrupt(int type, const char *program,
                         InterruptSite *site /* = NULL */,
                         const char *error /* = NULL */) {
  assert(RuntimeOption::EnableDebugger);
  TRACE_RB(2, "Debugger::Interrupt type %d\n", type);

  DebuggerProxyPtr proxy = GetProxy();
  if (proxy) {
    TRACE(3, "proxy != null\n");
    RequestInjectionData &rjdata = ThreadInfo::s_threadInfo->m_reqInjectionData;
    // The proxy will only service an interrupt if we've previously setup some
    // form of flow control command (steps, breakpoints, etc.) or if it's
    // an interrupt related to something like the session or request.
    if (proxy->needInterrupt() || type != BreakPointReached) {
      // Interrupts may execute some PHP code, causing another interruption.
      std::stack<void *> &interrupts = rjdata.interrupts;

      CmdInterrupt cmd((InterruptType)type, program, site, error);
      interrupts.push(&cmd);
      proxy->interrupt(cmd);
      interrupts.pop();
    }
    // Some cmds require us to interpret all instructions until the cmd
    // completes. Setting this will ensure we stay out of JIT code and in the
    // interpreter so phpDebuggerOpcodeHook has a chance to work.
    rjdata.setDebuggerIntr(proxy->needVMInterrupts());
  } else {
    TRACE(3, "proxy == null\n");
    // Debugger clients are disconnected abnormally, or this sandbox is not
    // being debugged.
    if (type == SessionStarted || type == SessionEnded) {
      // For command line programs, we need this exception to exit from
      // the infinite execution loop.
      throw DebuggerClientExitException();
    }
  }
}
Esempio n. 19
0
void Debugger::Interrupt(int type, const char *program,
                         InterruptSite *site /* = NULL */,
                         const char *error /* = NULL */) {
  ASSERT(RuntimeOption::EnableDebugger);

  DebuggerProxyPtr proxy = GetProxy();
  if (proxy) {
    // Interrupts may execute some PHP code, causing another interruption.
    void *&tint = ThreadInfo::s_threadInfo->m_reqInjectionData.interrupt;
    if (!tint) {
      CmdInterrupt cmd((InterruptType)type, program, site, error);
      tint = &cmd;
      proxy->interrupt(cmd);
      tint = NULL;
    }
  } else {
    // debugger clients are disconnected abnormally
    if (type == SessionStarted || type == SessionEnded) {
      // for command line programs, we need this exception to exit from
      // the infinite execution loop
      throw DebuggerClientExitException();
    }
  }
}
Esempio n. 20
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", 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 DisplayAddresses:
            bDisplayAddresses = value.toBool();
            settings.setValue("bDisplayAddresses", bDisplayAddresses);
            emit displayUnitChanged(settings.value("nDisplayUnit", BitcoinUnits::LEO).toInt());
            break;
        case DetachDatabases: {
            bool fDetachDB = value.toBool();
            bitdb.SetDetach(fDetachDB);
            settings.setValue("detachDB", fDetachDB);
            }
            break;
        case Language:
            settings.setValue("language", value);
            break;
        case RowsPerPage: {
            nRowsPerPage = value.toInt();
            settings.setValue("nRowsPerPage", nRowsPerPage);
            emit rowsPerPageChanged(nRowsPerPage);
            }
            break;
        case Notifications: {
            notifications = value.toStringList();
            settings.setValue("notifications", notifications);
            }
            break;
        case VisibleTransactions: {
            visibleTransactions = value.toStringList();
            settings.setValue("visibleTransactions", visibleTransactions);
            emit visibleTransactionsChanged(visibleTransactions);
            }
            break;
        case AutoRingSize: {
            fAutoRingSize = value.toBool();
            settings.setValue("fAutoRingSize", fAutoRingSize);
            }
            break;
        case AutoRedeemLEOcoin: {
            fAutoRedeemLEOcoin = value.toBool();
            settings.setValue("fAutoRedeemLEOcoin", fAutoRedeemLEOcoin);
            }
            break;
        case MinRingSize: {
            nMinRingSize = value.toInt();
            settings.setValue("nMinRingSize", nMinRingSize);
            }
            break;
        case MaxRingSize: {
            nMaxRingSize = value.toInt();
            settings.setValue("nMaxRingSize", nMaxRingSize);
            }
            break;
        case Staking:
            settings.setValue("fStaking", value.toBool());
            break;
        case MinStakeInterval:
            nMinStakeInterval = value.toInt();
            settings.setValue("nMinStakeInterval", nMinStakeInterval);
            break;
        case ThinMode:
            settings.setValue("fThinMode", value.toBool());
            break;
        case ThinFullIndex:
            settings.setValue("fThinFullIndex", value.toBool());
            break;
        case ThinIndexWindow:
            settings.setValue("fThinIndexWindow", value.toInt());
            break;
        case SecureMessaging: {
            if(value.toBool())
            {
                if(!fSecMsgEnabled)
                    SecureMsgEnable();
            }
            else
                SecureMsgDisable();

            settings.setValue("fSecMsgEnabled", fSecMsgEnabled);
            }
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}
Esempio n. 21
0
int main  (int argc, char *argv[])
{
    int arg;
    char *Parm = NULL;
    char *TempFileDir=NULL;
    int c;
    int InitFlag=0;
    int CmdlineFlag = 0; /** run from command line flag, 1 yes, 0 not */
    int user_pk;
    char *agent_desc = "Network downloader.  Uses wget(1).";

    memset(GlobalTempFile,'\0',MAXCMD);
    memset(GlobalURL,'\0',MAXCMD);
    memset(GlobalParam,'\0',MAXCMD);
    memset(GlobalType,'\0',MAXCMD);
    GlobalUploadKey = -1;
    int upload_pk = 0;           // the upload primary key
    //int Agent_pk;
    char *SVN_REV;
    char *VERSION;
    char agent_rev[MAXCMD];

    /* open the connection to the scheduler and configuration */
    fo_scheduler_connect(&argc, argv, &pgConn);

    /* Process command-line */
    while((c = getopt(argc,argv,"d:Gg:ik:A:R:l:Cc:Vvh")) != -1)
    {
        switch(c)
        {
        case 'd':
            TempFileDir = PathCheck(optarg);
            break;
        case 'g':
        {
            struct group *SG;
            SG = getgrnam(optarg);
            if (SG) ForceGroup = SG->gr_gid;
        }
        break;
        case 'G':
            GlobalImportGold=0;
            break;
        case 'i':
            InitFlag=1;
            break;
        case 'k':
            GlobalUploadKey = atol(optarg);
            if (!GlobalTempFile[0])
                strcpy(GlobalTempFile,"wget.default_download");
            break;
        case 'A':
            sprintf(GlobalParam, "%s -A %s ",GlobalParam, optarg);
            break;
        case 'R':
            sprintf(GlobalParam, "%s -R %s ",GlobalParam, optarg);
            break;
        case 'l':
            sprintf(GlobalParam, "%s -l %s ",GlobalParam, optarg);
            break;
        case 'c':
            break; /* handled by fo_scheduler_connect() */
        case 'C':
            CmdlineFlag = 1;
            break;
        case 'v':
            break;
        case 'V':
            printf("%s", BuildVersion);
            SafeExit(0);
        default:
            Usage(argv[0]);
            SafeExit(-1);
        }
    }
    if (argc - optind > 1)
    {
        Usage(argv[0]);
        SafeExit(-1);
    }

    /* When initializing the DB, don't do anything else */
    if (InitFlag)
    {
        if (pgConn) PQfinish(pgConn);
        SafeExit(0);
    }

    SVN_REV = fo_sysconfig("wget_agent", "SVN_REV");
    VERSION = fo_sysconfig("wget_agent", "VERSION");
    sprintf(agent_rev, "%s.%s", VERSION, SVN_REV);
    /* Get the Agent Key from the DB */
    fo_GetAgentKey(pgConn, basename(argv[0]), GlobalUploadKey, agent_rev, agent_desc);

    /** get proxy */
    GetProxy();

    /* Run from the command-line (for testing) */
    for(arg=optind; arg < argc; arg++)
    {
        memset(GlobalURL,'\0',sizeof(GlobalURL));
        strncpy(GlobalURL,argv[arg],sizeof(GlobalURL));
        /* If the file contains "://" then assume it is a URL.
           Else, assume it is a file. */
        LOG_VERBOSE0("Command-line: %s",GlobalURL);
        if (strstr(GlobalURL,"://"))
        {
            fo_scheduler_heart(1);
            LOG_VERBOSE0("It's a URL");
            if (GetURL(GlobalTempFile,GlobalURL,TempFileDir) != 0)
            {
                LOG_FATAL("Download of %s failed.",GlobalURL);
                SafeExit(21);
            }
            if (GlobalUploadKey != -1) {
                DBLoadGold();
            }
            unlink(GlobalTempFile);
        }
        else /* must be a file */
        {
            LOG_VERBOSE0("It's a file -- GlobalUploadKey = %ld",GlobalUploadKey);
            if (GlobalUploadKey != -1)
            {
                memcpy(GlobalTempFile,GlobalURL,MAXCMD);
                DBLoadGold();
            }
        }
    }

    /* Run from scheduler! */
    if (0 == CmdlineFlag)
    {
        user_pk = fo_scheduler_userID(); /* get user_pk for user who queued the agent */
        while(fo_scheduler_next())
        {
            Parm = fo_scheduler_current(); /* get piece of information, including upload_pk, downloadfile url, and parameters */
            if (Parm && Parm[0])
            {
                fo_scheduler_heart(1);
                /* set globals: uploadpk, downloadfile url, parameters */
                SetEnv(Parm,TempFileDir);
                upload_pk = GlobalUploadKey;

                /* Check Permissions */
                if (GetUploadPerm(pgConn, upload_pk, user_pk) < PERM_WRITE)
                {
                    LOG_ERROR("You have no update permissions on upload %d", upload_pk);
                    continue;
                }

                char TempDir[MAXCMD];
                memset(TempDir,'\0',MAXCMD);
                snprintf(TempDir, MAXCMD-1, "%s/wget", TempFileDir); // /var/local/lib/fossology/agents/wget
                struct stat Status;

                if (GlobalType[0])
                {
                    if (GetVersionControl() == 0)
                    {
                        DBLoadGold();
                        unlink(GlobalTempFile);
                    }
                    else
                    {
                        LOG_FATAL("upload %ld File retrieval failed: uploadpk=%ld tempfile=%s URL=%s Type=%s",
                                  GlobalUploadKey,GlobalUploadKey,GlobalTempFile,GlobalURL, GlobalType);
                        SafeExit(23);
                    }
                }
                else if (strstr(GlobalURL, "*") || stat(GlobalURL, &Status) == 0)
                {
                    if (!Archivefs(GlobalURL, GlobalTempFile, TempFileDir, Status))
                    {
                        LOG_FATAL("Failed to archieve. GlobalURL, GlobalTempFile, TempFileDir are: %s, %s, %s, "
                                  "Mode is: %lo (octal)\n", GlobalURL, GlobalTempFile, TempFileDir, (unsigned long) Status.st_mode);
                        SafeExit(50);
                    }
                    DBLoadGold();
                    unlink(GlobalTempFile);
                }
                else
                {
                    if (GetURL(GlobalTempFile,GlobalURL,TempDir) == 0)
                    {
                        DBLoadGold();
                        unlink(GlobalTempFile);
                    }
                    else
                    {
                        LOG_FATAL("upload %ld File retrieval failed: uploadpk=%ld tempfile=%s URL=%s",
                                  GlobalUploadKey,GlobalUploadKey,GlobalTempFile,GlobalURL);
                        SafeExit(22);
                    }
                }
            }
        }
    } /* if run from scheduler */

    SafeExit(0);
    exit(0);  /* to prevent compiler warning */
} /* main() */
Esempio n. 22
0
bool
CHttp::AllocHandles ( bool isbase64, int *status, bool checkauth)
{

	DWORD		flags	=	INTERNET_FLAG_RELOAD | 
							INTERNET_FLAG_NO_CACHE_WRITE | 
							INTERNET_FLAG_KEEP_CONNECTION;
    unsigned long errnum;
	DWORD rec_timeout = RECIEVE_TIMEOUT;					// override the 30 second timeout fixed in 12.11
	wyString contenttype,contenttypestr;
	//wyInt32     ret;
	
		

	/* 
		If a user has selected to use proxy server for Internet connection then we
		create a separate handle, send a dummy request and set the username, password 

		The real data connection and transfer is done in another handle */
	
	if (IsProxy () )
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_PROXY, GetProxy(), NULL, 0 );
	else
		m_InternetSession = InternetOpen (TEXT(USER_AGENT), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0 );
	
	if (!m_InternetSession )
		return false;
	InternetSetOption(m_InternetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &rec_timeout, sizeof(rec_timeout));
	m_InternetConnect = InternetConnect (m_InternetSession, m_HostName, m_Port, m_UserName, m_Password, INTERNET_SERVICE_HTTP, 0L, 0L );
	if (!m_InternetConnect )
		return false;

	/* set the flags for internet connection  and check if SSL required */
	if (wcsicmp (m_Protocol, L"https" ) == 0 )
		flags |= INTERNET_FLAG_SECURE;

	/* check for proxy or password protected authentication 
	checkauth flag tells whether its required to be authenticated 
	*/
	if (checkauth && !Authorize (&errnum) )
    {
        *status = errnum;
		return false;
    }

	m_HttpOpenRequest = HttpOpenRequest(m_InternetConnect, L"POST", m_FileName, NULL, NULL, NULL, flags, 0L );
	if (!m_HttpOpenRequest )
		return false;

	//Content-Type 
	contenttype.SetAs(m_contenttype);
	contenttypestr.Sprintf("Content-Type: %s\r\n", contenttype.GetString());
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, contenttypestr.GetAsWideChar () , (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;
				
	/*if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;*/
	//changing user string for avoid update your browser bug
	if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"HTTP_USER_AGENT: Mozilla/5.0 (Windows; U;Windows NT 6.3; en-US; rv:36.0) Gecko/20100101 Firefox/36.0\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) )
		return false;

	if (isbase64 ) {
		if (!HttpAddRequestHeaders(m_HttpOpenRequest, L"Base64: yes\r\n", (DWORD)-1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE ) ) {
			assert (0 );
			return false;
		}
	}

	return true;
}
Esempio n. 23
0
/**
 * @note Do not add or change anything in the information returned by this
 * method. `getinfo` exists for backwards-compatibility only. It combines
 * information from wildly different sources in the program, which is a mess,
 * and is thus planned to be deprecated eventually.
 *
 * Based on the source of the information, new information should be added to:
 * - `getblockchaininfo`,
 * - `getnetworkinfo` or
 * - `getwalletinfo`
 *
 * Or alternatively, create a specific query method for the information.
 **/
UniValue getinfo(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() != 0)
        throw std::runtime_error(
            "getinfo\n"
            "\nDEPRECATED. Returns an object containing various state info.\n"
            "\nResult:\n"
            "{\n"
            "  \"deprecation-warning\": \"...\" (string) warning that the getinfo command is deprecated and will be removed in 0.16\n"
            "  \"version\": xxxxx,           (numeric) the server version\n"
            "  \"protocolversion\": xxxxx,   (numeric) the protocol version\n"
            "  \"walletversion\": xxxxx,     (numeric) the wallet version\n"
            "  \"balance\": xxxxxxx,         (numeric) the total bitcoin balance of the wallet\n"
            "  \"blocks\": xxxxxx,           (numeric) the current number of blocks processed in the server\n"
            "  \"timeoffset\": xxxxx,        (numeric) the time offset\n"
            "  \"connections\": xxxxx,       (numeric) the number of connections\n"
            "  \"proxy\": \"host:port\",       (string, optional) the proxy used by the server\n"
            "  \"difficulty\": xxxxxx,       (numeric) the current difficulty\n"
            "  \"testnet\": true|false,      (boolean) if the server is using testnet or not\n"
            "  \"keypoololdest\": xxxxxx,    (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
            "  \"keypoolsize\": xxxx,        (numeric) how many new keys are pre-generated\n"
            "  \"unlocked_until\": ttt,      (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
            "  \"paytxfee\": x.xxxx,         (numeric) the transaction fee set in " + CURRENCY_UNIT + "/kB\n"
            "  \"relayfee\": x.xxxx,         (numeric) minimum relay fee for transactions in " + CURRENCY_UNIT + "/kB\n"
            "  \"errors\": \"...\"             (string) any error messages\n"
            "}\n"
            "\nExamples:\n"
            + HelpExampleCli("getinfo", "")
            + HelpExampleRpc("getinfo", "")
        );

#ifdef ENABLE_WALLET
    CWallet * const pwallet = GetWalletForJSONRPCRequest(request);

    LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : NULL);
#else
    LOCK(cs_main);
#endif

    proxyType proxy;
    GetProxy(NET_IPV4, proxy);

    UniValue obj(UniValue::VOBJ);
    obj.push_back(Pair("deprecation-warning", "WARNING: getinfo is deprecated and will be fully removed in 0.16."
        " Projects should transition to using getblockchaininfo, getnetworkinfo, and getwalletinfo before upgrading to 0.16"));
    obj.push_back(Pair("version", CLIENT_VERSION));
    obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
    if (pwallet) {
        obj.push_back(Pair("walletversion", pwallet->GetVersion()));
        obj.push_back(Pair("balance",       ValueFromAmount(pwallet->GetBalance())));
    }
#endif
    obj.push_back(Pair("blocks",        (int)chainActive.Height()));
    obj.push_back(Pair("timeoffset",    GetTimeOffset()));
    if(g_connman)
        obj.push_back(Pair("connections",   (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL)));
    obj.push_back(Pair("proxy",         (proxy.IsValid() ? proxy.proxy.ToStringIPPort() : std::string())));
    obj.push_back(Pair("difficulty",    (double)GetDifficulty()));
    obj.push_back(Pair("testnet",       Params().NetworkIDString() == CBaseChainParams::TESTNET));
#ifdef ENABLE_WALLET
    if (pwallet) {
        obj.push_back(Pair("keypoololdest", pwallet->GetOldestKeyPoolTime()));
        obj.push_back(Pair("keypoolsize",   (int)pwallet->GetKeyPoolSize()));
    }
    if (pwallet && pwallet->IsCrypted()) {
        obj.push_back(Pair("unlocked_until", pwallet->nRelockTime));
    }
    obj.push_back(Pair("paytxfee",      ValueFromAmount(payTxFee.GetFeePerK())));
#endif
    obj.push_back(Pair("relayfee",      ValueFromAmount(::minRelayTxFee.GetFeePerK())));
    obj.push_back(Pair("errors",        GetWarnings("statusbar")));
    return obj;
}
Esempio n. 24
0
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return GUIUtil::GetStartOnSystemStartup();
        case MinimizeToTray:
            return fMinimizeToTray;
        case MapPortUPnP:
            return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
        case MinimizeOnClose:
            return fMinimizeOnClose;
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QString::fromStdString(proxy.ToStringIP());
            else
                return "";
        }
        case ProxyPort: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(proxy.GetPort());
        }
            break;

        case ProxySocksVersion:
            return settings.value("nSocksVersion", 5);
        case Fee:
            return (qint64) nTransactionFee;
        case ReserveBalance:
            return (qint64) nReserveBalance;
        case DisplayUnit:
            return nDisplayUnit;
        case DisplayAddresses:
            return bDisplayAddresses;
        case DetachDatabases:
            return bitdb.GetDetach();
        case Language:
            return settings.value("language", "");
        case RowsPerPage:
            return nRowsPerPage;
        case AutoRingSize:
            return fAutoRingSize;
        case AutoRedeemLEOcoin:
            return fAutoRedeemLEOcoin;
        case MinRingSize:
            return nMinRingSize;
        case MaxRingSize:
            return nMaxRingSize;
        case Staking:
            return settings.value("fStaking", GetBoolArg("-staking", true)).toBool();
        case MinStakeInterval:
            return nMinStakeInterval;
        case SecureMessaging:
            return fSecMsgEnabled;
        case ThinMode:
            return settings.value("fThinMode",      GetBoolArg("-thinmode",      false)).toBool();
        case ThinFullIndex:
            return settings.value("fThinFullIndex", GetBoolArg("-thinfullindex", false)).toBool();
        case ThinIndexWindow:
            return settings.value("ThinIndexWindow", (qint64) GetArg("-thinindexwindow", 4096)).toInt();
        case Notifications:
            return notifications;
        case VisibleTransactions:
            return visibleTransactions;
        }
    }

    return QVariant();
}
Esempio n. 25
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 MinimizeCoinAge:
           fMinimizeCoinAge = value.toBool();
           settings.setValue("fMinimizeCoinAge", fMinimizeCoinAge);
           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 anonymizeGridmasterAmount:
            nAnonymizeGridmasterAmount = value.toInt();
            settings.setValue("nAnonymizeGridmasterAmount", nAnonymizeGridmasterAmount);
            emit anonymizeGridmasterAmountChanged(nAnonymizeGridmasterAmount);
            break;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}
Esempio n. 26
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 MinimizeCoinAge:
           fMinimizeCoinAge = value.toBool();
           settings.setValue("fMinimizeCoinAge", fMinimizeCoinAge);
           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 anonymizecovenAmount:
            nAnonymizecovenAmount = value.toInt();
            settings.setValue("nAnonymizecovenAmount", nAnonymizecovenAmount);
            emit anonymizecovenAmountChanged(nAnonymizecovenAmount);
            break;
#ifdef USE_NATIVE_I2P
        case I2PUseI2POnly:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            settings.setValue("useI2POnly", value.toBool());
            break;
        }
        case I2PSAMHost:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            settings.setValue("samhost", value.toString());
            break;
        }
        case I2PSAMPort:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            settings.setValue("samport", value.toString());
            break;
        }
        case I2PSessionName:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            settings.setValue("sessionName", value.toString());
            break;
        }
        case I2PInboundQuantity:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundQuantity = value.toInt();
            settings.setValue(SAM_NAME_INBOUND_QUANTITY, i2pInboundQuantity);
            break;
        }
        case I2PInboundLength:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundLength = value.toInt();
            settings.setValue(SAM_NAME_INBOUND_LENGTH, i2pInboundLength);
            break;
        }
        case I2PInboundLengthVariance:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundLengthVariance = value.toInt();
            settings.setValue(SAM_NAME_INBOUND_LENGTHVARIANCE, i2pInboundLengthVariance);
            break;
        }
        case I2PInboundBackupQuantity:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundBackupQuantity = value.toInt();
            settings.setValue(SAM_NAME_INBOUND_BACKUPQUANTITY, i2pInboundBackupQuantity);
            break;
        }
        case I2PInboundAllowZeroHop:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundAllowZeroHop = value.toBool();
            settings.setValue(SAM_NAME_INBOUND_ALLOWZEROHOP, i2pInboundAllowZeroHop);
            break;
        }
        case I2PInboundIPRestriction:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pInboundIPRestriction = value.toInt();
            settings.setValue(SAM_NAME_INBOUND_IPRESTRICTION, i2pInboundIPRestriction);
            break;
        }
        case I2POutboundQuantity:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundQuantity = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_QUANTITY, i2pOutboundQuantity);
            break;
        }
        case I2POutboundLength:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundLength = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_LENGTH, i2pOutboundLength);
            break;
        }
        case I2POutboundLengthVariance:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundLengthVariance = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_LENGTHVARIANCE, i2pOutboundLengthVariance);
            break;
        }
        case I2POutboundBackupQuantity:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundBackupQuantity = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_BACKUPQUANTITY, i2pOutboundBackupQuantity);
            break;
        }
        case I2POutboundAllowZeroHop:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundAllowZeroHop = value.toBool();
            settings.setValue(SAM_NAME_OUTBOUND_ALLOWZEROHOP, i2pOutboundAllowZeroHop);
            break;
        }
        case I2POutboundIPRestriction:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundIPRestriction = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_IPRESTRICTION, i2pOutboundIPRestriction);
            break;
        }
        case I2POutboundPriority:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            i2pOutboundPriority = value.toInt();
            settings.setValue(SAM_NAME_OUTBOUND_PRIORITY, i2pOutboundPriority);
            break;
        }

#endif
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}
Esempio n. 27
0
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
    if(role == Qt::EditRole)
    {
        QSettings settings;
        switch(index.row())
        {
        case StartAtStartup:
            return QVariant(GUIUtil::GetStartOnSystemStartup());
        case MinimizeToTray:
            return QVariant(fMinimizeToTray);
        case MapPortUPnP:
            return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
        case MinimizeOnClose:
            return QVariant(fMinimizeOnClose);
        case ProxyUse:
            return settings.value("fUseProxy", false);
        case ProxyIP: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(QString::fromStdString(proxy.ToStringIP()));
            else
                return QVariant(QString::fromStdString("127.0.0.1"));
        }
        case ProxyPort: {
            proxyType proxy;
            if (GetProxy(NET_IPV4, proxy))
                return QVariant(proxy.GetPort());
            else
                return QVariant(9050);
        }
        case Fee:
            return QVariant((qint64) nTransactionFee);
        case ReserveBalance:
            return QVariant((qint64) nReserveBalance);
        case DisplayUnit:
            return QVariant(nDisplayUnit);
        case Language:
            return settings.value("language", "");
        case CoinControlFeatures:
            return QVariant(fCoinControlFeatures);
        case MinimizeCoinAge:
            return settings.value("fMinimizeCoinAge", GetBoolArg("-minimizecoinage", false));
        case UseBlackTheme:
            return QVariant(fUseBlackTheme);
#ifdef USE_NATIVE_I2P
        case I2PUseI2POnly:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            bool useI2POnly = false;
            if (mapArgs.count("-onlynet"))
            {
                const std::vector<std::string>& onlyNets = mapMultiArgs["-onlynet"];
                if (std::find(onlyNets.begin(), onlyNets.end(), NATIVE_I2P_NET_STRING) != onlyNets.end())
                    useI2POnly = true;
            }
            return settings.value("useI2POnly", useI2POnly);
        }
        case I2PSAMHost:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            return settings.value("samhost", QString::fromStdString(GetArg(I2P_SAM_HOST_PARAM, I2P_SAM_HOST_DEFAULT)));
        }
        case I2PSAMPort:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            return settings.value("samport", QString::number((qint64)GetArg(I2P_SAM_PORT_PARAM, I2P_SAM_PORT_DEFAULT)));
        }
        case I2PSessionName:
        {
            ScopeGroupHelper s(settings, I2P_OPTIONS_SECTION_NAME);
            return settings.value("sessionName", QString::fromStdString(GetArg(I2P_SESSION_NAME_PARAM, I2P_SESSION_NAME_DEFAULT)));
        }
        case I2PInboundQuantity:
            return QVariant(i2pInboundQuantity);
        case I2PInboundLength:
            return QVariant(i2pInboundLength);
        case I2PInboundLengthVariance:
            return QVariant(i2pInboundLengthVariance);
        case I2PInboundBackupQuantity:
            return QVariant(i2pInboundBackupQuantity);
        case I2PInboundAllowZeroHop:
            return QVariant(i2pInboundAllowZeroHop);
        case I2PInboundIPRestriction:
            return QVariant(i2pInboundIPRestriction);
        case I2POutboundQuantity:
            return QVariant(i2pOutboundQuantity);
        case I2POutboundLength:
            return QVariant(i2pOutboundLength);
        case I2POutboundLengthVariance:
            return QVariant(i2pOutboundLengthVariance);
        case I2POutboundBackupQuantity:
            return QVariant(i2pOutboundBackupQuantity);
        case I2POutboundAllowZeroHop:
            return QVariant(i2pOutboundAllowZeroHop);
        case I2POutboundIPRestriction:
            return QVariant(i2pOutboundIPRestriction);
        case I2POutboundPriority:
            return QVariant(i2pOutboundPriority);
#endif
        default:
            return QVariant();
        }
    }
    return QVariant();
}
Esempio n. 28
0
void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
	m_sCurrentController = this;

	PyObject *excdict=		NULL;
	PyObject *resultobj=	NULL;
	
	switch (m_mode) {
		case SCA_PYEXEC_SCRIPT:
		{
			if (m_bModified)
				if (Compile()==false) // sets m_bModified to false
					return;
			if (!m_bytecode)
				return;

			/*
			 * This part here with excdict is a temporary patch
			 * to avoid python/gameengine crashes when python
			 * inadvertently holds references to game objects
			 * in global variables.
			 *
			 * The idea is always make a fresh dictionary, and
			 * destroy it right after it is used to make sure
			 * python won't hold any gameobject references.
			 *
			 * Note that the PyDict_Clear _is_ necessary before
			 * the Py_DECREF() because it is possible for the
			 * variables inside the dictionary to hold references
			 * to the dictionary (ie. generate a cycle), so we
			 * break it by hand, then DECREF (which in this case
			 * should always ensure excdict is cleared).
			 */

			excdict= PyDict_Copy(m_pythondictionary);

			resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);

			/* PyRun_SimpleString(m_scriptText.Ptr()); */
			break;
		}
		case SCA_PYEXEC_MODULE:
		{
			if (m_bModified || m_debug)
				if (Import()==false) // sets m_bModified to false
					return;
			if (!m_function)
				return;

			PyObject *args= NULL;

			if (m_function_argc==1) {
				args = PyTuple_New(1);
				PyTuple_SET_ITEM(args, 0, GetProxy());
			}

			resultobj = PyObject_CallObject(m_function, args);
			Py_XDECREF(args);
			break;
		}

	} /* end switch */


	/* Free the return value and print the error */
	if (resultobj)
		Py_DECREF(resultobj);
	else
		ErrorPrint("Python script error");
	
	if (excdict) /* Only for SCA_PYEXEC_SCRIPT types */
	{
		/* clear after PyErrPrint - seems it can be using
		 * something in this dictionary and crash? */
		// This doesn't appear to be needed anymore
		//PyDict_Clear(excdict);
		Py_DECREF(excdict);
	}
	
	m_triggeredSensors.clear();
	m_sCurrentController = NULL;
}
Esempio n. 29
0
void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
	m_sCurrentController = this;
	m_sCurrentLogicManager = logicmgr;
	
	PyObject *excdict=		NULL;
	PyObject* resultobj=	NULL;
	
	switch(m_mode) {
	case SCA_PYEXEC_SCRIPT:
	{
		if (m_bModified)
			if (Compile()==false) // sets m_bModified to false
				return;
		if (!m_bytecode)
			return;
		
		/*
		 * This part here with excdict is a temporary patch
		 * to avoid python/gameengine crashes when python
		 * inadvertently holds references to game objects
		 * in global variables.
		 * 
		 * The idea is always make a fresh dictionary, and
		 * destroy it right after it is used to make sure
		 * python won't hold any gameobject references.
		 * 
		 * Note that the PyDict_Clear _is_ necessary before
		 * the Py_DECREF() because it is possible for the
		 * variables inside the dictionary to hold references
		 * to the dictionary (ie. generate a cycle), so we
		 * break it by hand, then DECREF (which in this case
		 * should always ensure excdict is cleared).
		 */

		excdict= PyDict_Copy(m_pythondictionary);

#if PY_VERSION_HEX >=  0x03020000
		resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);
#else
		resultobj = PyEval_EvalCode((PyCodeObject *)m_bytecode, excdict, excdict);
#endif

		/* PyRun_SimpleString(m_scriptText.Ptr()); */
		break;
	}
	case SCA_PYEXEC_MODULE:
	{
		if (m_bModified || m_debug)
			if (Import()==false) // sets m_bModified to false
				return;
		if (!m_function)
			return;
		
		PyObject *args= NULL;
		
		if(m_function_argc==1) {
			args = PyTuple_New(1);
			PyTuple_SET_ITEM(args, 0, GetProxy());
		}
		
		resultobj = PyObject_CallObject(m_function, args);
		Py_XDECREF(args);
		break;
	}
	
	} /* end switch */
	
	
	
	/* Free the return value and print the error */
	if (resultobj)
	{
		Py_DECREF(resultobj);
	}
	else
	{
		// something is wrong, tell the user what went wrong
		printf("Python script error from controller \"%s\":\n", GetName().Ptr());
		PyErr_Print();
		
		/* Added in 2.48a, the last_traceback can reference Objects for example, increasing
		 * their user count. Not to mention holding references to wrapped data.
		 * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
		 * has already dealocated the pointer */
		PySys_SetObject( (char *)"last_traceback", NULL);
		PyErr_Clear(); /* just to be sure */
	}
	
	if(excdict) /* Only for SCA_PYEXEC_SCRIPT types */
	{
		/* clear after PyErrPrint - seems it can be using
		 * something in this dictionary and crash? */
		// This doesn't appear to be needed anymore
		//PyDict_Clear(excdict);
		Py_DECREF(excdict);
	}	
	
	m_triggeredSensors.clear();
	m_sCurrentController = NULL;
}
Esempio n. 30
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", (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 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;
        default:
            break;
        }
    }
    emit dataChanged(index, index);

    return successful;
}